import_ref.cpp 126 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/check/import_ref.h"
  5. #include "common/check.h"
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/context.h"
  8. #include "toolchain/check/eval.h"
  9. #include "toolchain/check/generic.h"
  10. #include "toolchain/parse/node_ids.h"
  11. #include "toolchain/sem_ir/constant.h"
  12. #include "toolchain/sem_ir/file.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. #include "toolchain/sem_ir/import_ir.h"
  15. #include "toolchain/sem_ir/inst.h"
  16. #include "toolchain/sem_ir/inst_kind.h"
  17. #include "toolchain/sem_ir/type_info.h"
  18. #include "toolchain/sem_ir/typed_insts.h"
  19. namespace Carbon::Check {
  20. // Adds the ImportIR, excluding the update to the check_ir_map.
  21. static auto InternalAddImportIR(Context& context, SemIR::ImportIR import_ir)
  22. -> SemIR::ImportIRId {
  23. context.import_ir_constant_values().push_back(
  24. SemIR::ConstantValueStore(SemIR::ConstantId::Invalid));
  25. return context.import_irs().Add(import_ir);
  26. }
  27. auto SetApiImportIR(Context& context, SemIR::ImportIR import_ir) -> void {
  28. auto ir_id = SemIR::ImportIRId::Invalid;
  29. if (import_ir.sem_ir != nullptr) {
  30. ir_id = AddImportIR(context, import_ir);
  31. } else {
  32. // We don't have a check_ir_id, so add without touching check_ir_map.
  33. ir_id = InternalAddImportIR(context, import_ir);
  34. }
  35. CARBON_CHECK(ir_id == SemIR::ImportIRId::ApiForImpl,
  36. "ApiForImpl must be the first IR");
  37. }
  38. auto AddImportIR(Context& context, SemIR::ImportIR import_ir)
  39. -> SemIR::ImportIRId {
  40. auto& ir_id = context.GetImportIRId(*import_ir.sem_ir);
  41. if (!ir_id.is_valid()) {
  42. // Note this updates check_ir_map.
  43. ir_id = InternalAddImportIR(context, import_ir);
  44. } else if (import_ir.is_export) {
  45. // We're processing an `export import`. In case the IR was indirectly added
  46. // as a non-export, mark it as an export.
  47. context.import_irs().Get(ir_id).is_export = true;
  48. }
  49. return ir_id;
  50. }
  51. auto AddImportRef(Context& context, SemIR::ImportIRInst import_ir_inst,
  52. SemIR::EntityNameId entity_name_id =
  53. SemIR::EntityNameId::Invalid) -> SemIR::InstId {
  54. auto import_ir_inst_id = context.import_ir_insts().Add(import_ir_inst);
  55. SemIR::ImportRefUnloaded inst = {.import_ir_inst_id = import_ir_inst_id,
  56. .entity_name_id = entity_name_id};
  57. auto import_ref_id = context.AddPlaceholderInstInNoBlock(
  58. context.MakeImportedLocAndInst(import_ir_inst_id, inst));
  59. // ImportRefs have a dedicated block because this may be called during
  60. // processing where the instruction shouldn't be inserted in the current inst
  61. // block.
  62. context.import_ref_ids().push_back(import_ref_id);
  63. return import_ref_id;
  64. }
  65. // Adds an import_ref instruction for an instruction that we have already loaded
  66. // from an imported IR, with a known constant value. This is useful when the
  67. // instruction has a symbolic constant value, in order to produce an instruction
  68. // that hold that symbolic constant.
  69. static auto AddLoadedImportRef(Context& context, SemIR::TypeId type_id,
  70. SemIR::ImportIRInst import_ir_inst,
  71. SemIR::ConstantId const_id) -> SemIR::InstId {
  72. auto import_ir_inst_id = context.import_ir_insts().Add(import_ir_inst);
  73. SemIR::ImportRefLoaded inst = {
  74. .type_id = type_id,
  75. .import_ir_inst_id = import_ir_inst_id,
  76. .entity_name_id = SemIR::EntityNameId::Invalid};
  77. auto inst_id = context.AddPlaceholderInstInNoBlock(
  78. context.MakeImportedLocAndInst(import_ir_inst_id, inst));
  79. context.import_ref_ids().push_back(inst_id);
  80. context.constant_values().Set(inst_id, const_id);
  81. context.import_ir_constant_values()[import_ir_inst.ir_id.index].Set(
  82. import_ir_inst.inst_id, const_id);
  83. return inst_id;
  84. }
  85. static auto GetCanonicalImportIRInst(Context& context,
  86. const SemIR::File* cursor_ir,
  87. SemIR::InstId cursor_inst_id)
  88. -> SemIR::ImportIRInst {
  89. while (true) {
  90. // Step through an instruction with an imported location to the imported
  91. // instruction.
  92. auto loc_id = cursor_ir->insts().GetLocId(cursor_inst_id);
  93. if (loc_id.is_import_ir_inst_id()) {
  94. auto import_ir_inst =
  95. cursor_ir->import_ir_insts().Get(loc_id.import_ir_inst_id());
  96. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  97. cursor_inst_id = import_ir_inst.inst_id;
  98. continue;
  99. }
  100. // Step through export declarations to their exported value.
  101. if (auto export_decl =
  102. cursor_ir->insts().TryGetAs<SemIR::ExportDecl>(cursor_inst_id)) {
  103. cursor_inst_id = export_decl->value_id;
  104. continue;
  105. }
  106. // Reached a non-imported entity.
  107. break;
  108. }
  109. auto ir_id = SemIR::ImportIRId::Invalid;
  110. if (cursor_ir != &context.sem_ir()) {
  111. // This uses AddImportIR in case it was indirectly found, which can
  112. // happen with two or more steps of exports.
  113. ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  114. .is_export = false,
  115. .sem_ir = cursor_ir});
  116. }
  117. return {.ir_id = ir_id, .inst_id = cursor_inst_id};
  118. }
  119. auto GetCanonicalImportIRInst(Context& context, SemIR::InstId inst_id)
  120. -> SemIR::ImportIRInst {
  121. return GetCanonicalImportIRInst(context, &context.sem_ir(), inst_id);
  122. }
  123. auto VerifySameCanonicalImportIRInst(Context& context, SemIR::InstId prev_id,
  124. SemIR::ImportIRInst prev_import_ir_inst,
  125. SemIR::ImportIRId new_ir_id,
  126. const SemIR::File* new_import_ir,
  127. SemIR::InstId new_inst_id) -> void {
  128. auto new_import_ir_inst =
  129. GetCanonicalImportIRInst(context, new_import_ir, new_inst_id);
  130. if (new_import_ir_inst == prev_import_ir_inst) {
  131. return;
  132. }
  133. auto conflict_id =
  134. AddImportRef(context, {.ir_id = new_ir_id, .inst_id = new_inst_id});
  135. context.DiagnoseDuplicateName(conflict_id, prev_id);
  136. }
  137. // Returns an instruction that has the specified constant value.
  138. static auto GetInstWithConstantValue(const SemIR::File& file,
  139. SemIR::ConstantId const_id)
  140. -> SemIR::InstId {
  141. if (!const_id.is_valid()) {
  142. return SemIR::InstId::Invalid;
  143. }
  144. // For template constants, the corresponding instruction has the desired
  145. // constant value.
  146. if (!const_id.is_symbolic()) {
  147. return file.constant_values().GetInstId(const_id);
  148. }
  149. // For abstract symbolic constants, the corresponding instruction has the
  150. // desired constant value.
  151. const auto& symbolic_const =
  152. file.constant_values().GetSymbolicConstant(const_id);
  153. if (!symbolic_const.generic_id.is_valid()) {
  154. return file.constant_values().GetInstId(const_id);
  155. }
  156. // For a symbolic constant in a generic, pick the corresponding instruction
  157. // out of the eval block for the generic.
  158. const auto& generic = file.generics().Get(symbolic_const.generic_id);
  159. auto block = generic.GetEvalBlock(symbolic_const.index.region());
  160. return file.inst_blocks().Get(block)[symbolic_const.index.index()];
  161. }
  162. namespace {
  163. class ImportRefResolver;
  164. // The result of attempting to resolve an imported instruction to a constant.
  165. struct ResolveResult {
  166. // The new constant value, if known.
  167. SemIR::ConstantId const_id;
  168. // Newly created declaration whose value is being resolved, if any.
  169. SemIR::InstId decl_id = SemIR::InstId::Invalid;
  170. // Whether resolution has been attempted once and needs to be retried.
  171. bool retry = false;
  172. // Produces a resolve result that tries resolving this instruction again. If
  173. // `const_id` is specified, then this is the end of the second phase, and the
  174. // constant value will be passed to the next resolution attempt. Otherwise,
  175. // this is the end of the first phase.
  176. static auto Retry(SemIR::ConstantId const_id = SemIR::ConstantId::Invalid,
  177. SemIR::InstId decl_id = SemIR::InstId::Invalid)
  178. -> ResolveResult {
  179. return {.const_id = const_id, .decl_id = decl_id, .retry = true};
  180. }
  181. // Produces a resolve result that provides the given constant value. Requires
  182. // that there is no new work.
  183. static auto Done(SemIR::ConstantId const_id,
  184. SemIR::InstId decl_id = SemIR::InstId::Invalid)
  185. -> ResolveResult {
  186. return {.const_id = const_id, .decl_id = decl_id};
  187. }
  188. };
  189. } // namespace
  190. static auto TryResolveInst(ImportRefResolver& resolver, SemIR::InstId inst_id,
  191. SemIR::ConstantId const_id) -> ResolveResult;
  192. namespace {
  193. // A context within which we are performing an import. Tracks information about
  194. // the source and destination. This provides a restricted interface compared to
  195. // ImportResolver: in particular, it does not have access to a work list.
  196. // Therefore code that accepts an ImportContext is unable to enqueue new work.
  197. class ImportContext {
  198. public:
  199. // A generic that we have partially imported.
  200. struct PendingGeneric {
  201. SemIR::GenericId import_id;
  202. SemIR::GenericId local_id;
  203. };
  204. // A specific that we have partially imported.
  205. struct PendingSpecific {
  206. SemIR::SpecificId import_id;
  207. SemIR::SpecificId local_id;
  208. };
  209. explicit ImportContext(Context& context, SemIR::ImportIRId import_ir_id)
  210. : context_(context),
  211. import_ir_id_(import_ir_id),
  212. import_ir_(*context_.import_irs().Get(import_ir_id).sem_ir) {}
  213. // Returns the file we are importing from.
  214. auto import_ir() -> const SemIR::File& { return import_ir_; }
  215. // Accessors into value stores of the file we are importing from.
  216. auto import_classes() -> decltype(auto) { return import_ir().classes(); }
  217. auto import_constant_values() -> decltype(auto) {
  218. return import_ir().constant_values();
  219. }
  220. auto import_entity_names() -> decltype(auto) {
  221. return import_ir().entity_names();
  222. }
  223. auto import_facet_types() -> decltype(auto) {
  224. return import_ir().facet_types();
  225. }
  226. auto import_functions() -> decltype(auto) { return import_ir().functions(); }
  227. auto import_generics() -> decltype(auto) { return import_ir().generics(); }
  228. auto import_identifiers() -> decltype(auto) {
  229. return import_ir().identifiers();
  230. }
  231. auto import_impls() -> decltype(auto) { return import_ir().impls(); }
  232. auto import_inst_blocks() -> decltype(auto) {
  233. return import_ir().inst_blocks();
  234. }
  235. auto import_insts() -> decltype(auto) { return import_ir().insts(); }
  236. auto import_interfaces() -> decltype(auto) {
  237. return import_ir().interfaces();
  238. }
  239. auto import_ints() -> decltype(auto) { return import_ir().ints(); }
  240. auto import_name_scopes() -> decltype(auto) {
  241. return import_ir().name_scopes();
  242. }
  243. auto import_specifics() -> decltype(auto) { return import_ir().specifics(); }
  244. auto import_string_literal_values() -> decltype(auto) {
  245. return import_ir().string_literal_values();
  246. }
  247. auto import_struct_type_fields() -> decltype(auto) {
  248. return import_ir().struct_type_fields();
  249. }
  250. auto import_type_blocks() -> decltype(auto) {
  251. return import_ir().type_blocks();
  252. }
  253. auto import_types() -> decltype(auto) { return import_ir().types(); }
  254. // Returns the local file's import ID for the IR we are importing from.
  255. auto import_ir_id() -> SemIR::ImportIRId { return import_ir_id_; }
  256. // A value store for local constant values of imported instructions. This maps
  257. // from `InstId`s in the import IR to corresponding `ConstantId`s in the local
  258. // IR.
  259. auto local_constant_values_for_import_insts() -> decltype(auto) {
  260. return local_context().import_ir_constant_values()[import_ir_id_.index];
  261. }
  262. // Returns the file we are importing into.
  263. auto local_ir() -> SemIR::File& { return context_.sem_ir(); }
  264. // Returns the type-checking context we are importing into.
  265. auto local_context() -> Context& { return context_; }
  266. // Accessors into value stores of the file we are importing into.
  267. auto local_classes() -> decltype(auto) { return local_ir().classes(); }
  268. auto local_constant_values() -> decltype(auto) {
  269. return local_ir().constant_values();
  270. }
  271. auto local_entity_names() -> decltype(auto) {
  272. return local_ir().entity_names();
  273. }
  274. auto local_facet_types() -> decltype(auto) {
  275. return local_ir().facet_types();
  276. }
  277. auto local_functions() -> decltype(auto) { return local_ir().functions(); }
  278. auto local_generics() -> decltype(auto) { return local_ir().generics(); }
  279. auto local_identifiers() -> decltype(auto) {
  280. return local_ir().identifiers();
  281. }
  282. auto local_impls() -> decltype(auto) { return local_ir().impls(); }
  283. auto local_import_ir_insts() -> decltype(auto) {
  284. return local_ir().import_ir_insts();
  285. }
  286. auto local_inst_blocks() -> decltype(auto) {
  287. return local_ir().inst_blocks();
  288. }
  289. auto local_insts() -> decltype(auto) { return local_ir().insts(); }
  290. auto local_interfaces() -> decltype(auto) { return local_ir().interfaces(); }
  291. auto local_ints() -> decltype(auto) { return local_ir().ints(); }
  292. auto local_name_scopes() -> decltype(auto) {
  293. return local_ir().name_scopes();
  294. }
  295. auto local_specifics() -> decltype(auto) { return local_ir().specifics(); }
  296. auto local_string_literal_values() -> decltype(auto) {
  297. return local_ir().string_literal_values();
  298. }
  299. auto local_struct_type_fields() -> decltype(auto) {
  300. return local_ir().struct_type_fields();
  301. }
  302. auto local_types() -> decltype(auto) { return local_ir().types(); }
  303. // Add a generic that has been partially imported but needs to be finished.
  304. auto AddPendingGeneric(PendingGeneric pending) -> void {
  305. pending_generics_.push_back(pending);
  306. }
  307. // Add a specific that has been partially imported but needs to be finished.
  308. auto AddPendingSpecific(PendingSpecific pending) -> void {
  309. pending_specifics_.push_back(pending);
  310. }
  311. protected:
  312. auto pending_generics() -> llvm::SmallVector<PendingGeneric>& {
  313. return pending_generics_;
  314. }
  315. auto pending_specifics() -> llvm::SmallVector<PendingSpecific>& {
  316. return pending_specifics_;
  317. }
  318. private:
  319. Context& context_;
  320. SemIR::ImportIRId import_ir_id_;
  321. const SemIR::File& import_ir_;
  322. // TODO: The following members don't belong here. This pending work mechanism
  323. // can probably be removed entirely if we stop importing generic eval blocks
  324. // and instead evaluate them directly in the imported IR.
  325. // Generics that we have partially imported but not yet finished importing.
  326. llvm::SmallVector<PendingGeneric> pending_generics_;
  327. // Specifics that we have partially imported but not yet finished importing.
  328. llvm::SmallVector<PendingSpecific> pending_specifics_;
  329. };
  330. // Resolves an instruction from an imported IR into a constant referring to the
  331. // current IR.
  332. //
  333. // Calling Resolve on an instruction operates in an iterative manner, tracking
  334. // Work items on work_stack_. At a high level, the loop is:
  335. //
  336. // 1. If a constant value is already known for the work item and was not set by
  337. // this work item, it's considered resolved.
  338. // - The constant check avoids performance costs of deduplication on add.
  339. // - If we've processed this work item before, then we now process it again.
  340. // It didn't complete last time, even though we have a constant value
  341. // already.
  342. //
  343. // 2. Resolve the instruction (TryResolveInst/TryResolveTypedInst). This is done
  344. // in three phases. The first and second phases can add work to the worklist
  345. // and end in a retry, in which case those phases will be rerun once the
  346. // added work is done. The rerun cannot also end in a retry, so this results
  347. // in at most three calls, but in practice one or two calls is almost always
  348. // sufficient. Due to the chance of a second or third call to TryResolveInst,
  349. // it's important to only perform expensive work once, even when the same
  350. // phase is rerun.
  351. //
  352. // - First phase:
  353. // - Gather all input constants necessary to form the constant value of the
  354. // instruction. Gathering constants directly adds unresolved values to
  355. // work_stack_.
  356. // - If HasNewWork() reports that any work was added, then return Retry():
  357. // this instruction needs another call to complete. Gather the
  358. // now-resolved constants and continue to the next step once the retry
  359. // happens.
  360. //
  361. // - Second phase:
  362. // - Build the constant value of the instruction.
  363. // - Gather all input constants necessary to finish importing the
  364. // instruction. This is only necessary for instructions like classes that
  365. // can be forward-declared. For these instructions, we first import the
  366. // constant value and then later import the rest of the declaration in
  367. // order to break cycles.
  368. // - If HasNewWork() reports that any work was added, then return
  369. // Retry(constant_value): this instruction needs another call to
  370. // complete. Gather the now-resolved constants and continue to the next
  371. // step once the retry happens.
  372. //
  373. // - Third phase:
  374. // - After the second phase, the constant value for the instruction is
  375. // already set, and will be passed back into TryResolve*Inst on retry. It
  376. // should not be created again.
  377. // - Fill in any remaining information to complete the import of the
  378. // instruction. For example, when importing a class declaration, build
  379. // the class scope and information about the definition.
  380. // - Return ResolveAs/ResolveAsConstant to finish the resolution process.
  381. // This will cause the Resolve loop to set a constant value if we didn't
  382. // retry at the end of the second phase.
  383. //
  384. // 3. If resolve didn't return Retry(), pop the work. Otherwise, it needs to
  385. // remain, and may no longer be at the top of the stack; update the state of
  386. // the work item to track what work still needs to be done.
  387. //
  388. // The same instruction can be enqueued for resolution multiple times. However,
  389. // we will only reach the second phase once: once a constant value is set, only
  390. // the resolution step that set it will retry.
  391. //
  392. // TODO: Fix class `extern` handling and merging, rewrite tests.
  393. // - check/testdata/class/cross_package_import.carbon
  394. // - check/testdata/class/extern.carbon
  395. // TODO: Fix function `extern` handling and merging, rewrite tests.
  396. // - check/testdata/function/declaration/import.carbon
  397. // - check/testdata/packages/cross_package_import.carbon
  398. class ImportRefResolver : public ImportContext {
  399. public:
  400. explicit ImportRefResolver(Context& context, SemIR::ImportIRId import_ir_id)
  401. : ImportContext(context, import_ir_id) {}
  402. // Iteratively resolves an imported instruction's inner references until a
  403. // constant ID referencing the current IR is produced. See the class comment
  404. // for more details.
  405. auto ResolveOneInst(SemIR::InstId inst_id) -> SemIR::ConstantId {
  406. work_stack_.push_back({.inst_id = inst_id});
  407. while (!work_stack_.empty()) {
  408. auto work = work_stack_.back();
  409. CARBON_CHECK(work.inst_id.is_valid());
  410. // Step 1: check for a constant value.
  411. auto existing = FindResolvedConstId(work.inst_id);
  412. if (existing.const_id.is_valid() && !work.retry_with_constant_value) {
  413. work_stack_.pop_back();
  414. continue;
  415. }
  416. // Step 2: resolve the instruction.
  417. initial_work_ = work_stack_.size();
  418. auto [new_const_id, _, retry] =
  419. TryResolveInst(*this, work.inst_id, existing.const_id);
  420. CARBON_CHECK(!HasNewWork() || retry);
  421. CARBON_CHECK(
  422. !existing.const_id.is_valid() || existing.const_id == new_const_id,
  423. "Constant value changed in third phase.");
  424. if (!existing.const_id.is_valid()) {
  425. SetResolvedConstId(work.inst_id, existing.indirect_insts, new_const_id);
  426. }
  427. // Step 3: pop or retry.
  428. if (retry) {
  429. work_stack_[initial_work_ - 1].retry_with_constant_value =
  430. new_const_id.is_valid();
  431. } else {
  432. work_stack_.pop_back();
  433. }
  434. }
  435. auto constant_id = local_constant_values_for_import_insts().Get(inst_id);
  436. CARBON_CHECK(constant_id.is_valid());
  437. return constant_id;
  438. }
  439. // Performs resolution for one instruction and then performs all work we
  440. // deferred.
  441. auto Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId {
  442. auto const_id = ResolveOneInst(inst_id);
  443. PerformPendingWork();
  444. return const_id;
  445. }
  446. // Wraps constant evaluation with logic to handle constants.
  447. auto ResolveConstant(SemIR::ConstantId import_const_id) -> SemIR::ConstantId {
  448. return Resolve(GetInstWithConstantValue(import_ir(), import_const_id));
  449. }
  450. // Wraps constant evaluation with logic to handle types.
  451. auto ResolveType(SemIR::TypeId import_type_id) -> SemIR::TypeId {
  452. if (!import_type_id.is_valid()) {
  453. return import_type_id;
  454. }
  455. auto import_type_const_id =
  456. import_ir().types().GetConstantId(import_type_id);
  457. CARBON_CHECK(import_type_const_id.is_valid());
  458. if (auto import_type_inst_id =
  459. import_ir().constant_values().GetInstId(import_type_const_id);
  460. SemIR::IsSingletonInstId(import_type_inst_id)) {
  461. // Builtins don't require constant resolution; we can use them directly.
  462. return local_context().GetSingletonType(import_type_inst_id);
  463. } else {
  464. return local_context().GetTypeIdForTypeConstant(
  465. ResolveConstant(import_type_id.AsConstantId()));
  466. }
  467. }
  468. // Returns true if new unresolved constants were found as part of this
  469. // `Resolve` step.
  470. auto HasNewWork() -> bool {
  471. CARBON_CHECK(initial_work_ <= work_stack_.size(),
  472. "Work shouldn't decrease");
  473. return initial_work_ < work_stack_.size();
  474. }
  475. // Returns the ConstantId for an InstId. Adds unresolved constants to
  476. // work_stack_.
  477. auto GetLocalConstantValueOrPush(SemIR::InstId inst_id) -> SemIR::ConstantId {
  478. auto const_id = local_constant_values_for_import_insts().Get(inst_id);
  479. if (!const_id.is_valid()) {
  480. work_stack_.push_back({.inst_id = inst_id});
  481. }
  482. return const_id;
  483. }
  484. private:
  485. // A step in work_stack_.
  486. struct Work {
  487. // The instruction to work on.
  488. SemIR::InstId inst_id;
  489. // Whether this work item set the constant value for the instruction and
  490. // requested a retry.
  491. bool retry_with_constant_value = false;
  492. };
  493. // The constant found by FindResolvedConstId.
  494. struct ResolvedConstId {
  495. // The constant for the instruction. Invalid if not yet resolved.
  496. SemIR::ConstantId const_id = SemIR::ConstantId::Invalid;
  497. // Instructions which are indirect but equivalent to the current instruction
  498. // being resolved, and should have their constant set to the same. Empty
  499. // when const_id is valid.
  500. llvm::SmallVector<SemIR::ImportIRInst> indirect_insts = {};
  501. };
  502. // Looks to see if an instruction has been resolved. If a constant is only
  503. // found indirectly, sets the constant for any indirect steps that don't
  504. // already have the constant. If a constant isn't found, returns the indirect
  505. // instructions so that they can have the resolved constant assigned later.
  506. auto FindResolvedConstId(SemIR::InstId inst_id) -> ResolvedConstId {
  507. ResolvedConstId result;
  508. if (auto existing_const_id =
  509. local_constant_values_for_import_insts().Get(inst_id);
  510. existing_const_id.is_valid()) {
  511. result.const_id = existing_const_id;
  512. return result;
  513. }
  514. const auto* cursor_ir = &import_ir();
  515. auto cursor_ir_id = SemIR::ImportIRId::Invalid;
  516. auto cursor_inst_id = inst_id;
  517. while (true) {
  518. auto loc_id = cursor_ir->insts().GetLocId(cursor_inst_id);
  519. if (!loc_id.is_import_ir_inst_id()) {
  520. return result;
  521. }
  522. auto ir_inst =
  523. cursor_ir->import_ir_insts().Get(loc_id.import_ir_inst_id());
  524. const auto* prev_ir = cursor_ir;
  525. auto prev_inst_id = cursor_inst_id;
  526. cursor_ir = cursor_ir->import_irs().Get(ir_inst.ir_id).sem_ir;
  527. cursor_ir_id = local_context().GetImportIRId(*cursor_ir);
  528. if (!cursor_ir_id.is_valid()) {
  529. // TODO: Should we figure out a location to assign here?
  530. cursor_ir_id =
  531. AddImportIR(local_context(), {.decl_id = SemIR::InstId::Invalid,
  532. .is_export = false,
  533. .sem_ir = cursor_ir});
  534. }
  535. cursor_inst_id = ir_inst.inst_id;
  536. CARBON_CHECK(cursor_ir != prev_ir || cursor_inst_id != prev_inst_id,
  537. "{0}", cursor_ir->insts().Get(cursor_inst_id));
  538. if (auto const_id = local_context()
  539. .import_ir_constant_values()[cursor_ir_id.index]
  540. .Get(cursor_inst_id);
  541. const_id.is_valid()) {
  542. SetResolvedConstId(inst_id, result.indirect_insts, const_id);
  543. result.const_id = const_id;
  544. result.indirect_insts.clear();
  545. return result;
  546. } else {
  547. result.indirect_insts.push_back(
  548. {.ir_id = cursor_ir_id, .inst_id = cursor_inst_id});
  549. }
  550. }
  551. }
  552. // Sets a resolved constant into the current and indirect instructions.
  553. auto SetResolvedConstId(SemIR::InstId inst_id,
  554. llvm::ArrayRef<SemIR::ImportIRInst> indirect_insts,
  555. SemIR::ConstantId const_id) -> void {
  556. local_constant_values_for_import_insts().Set(inst_id, const_id);
  557. for (auto indirect_inst : indirect_insts) {
  558. local_context()
  559. .import_ir_constant_values()[indirect_inst.ir_id.index]
  560. .Set(indirect_inst.inst_id, const_id);
  561. }
  562. }
  563. auto PerformPendingWork() -> void;
  564. llvm::SmallVector<Work> work_stack_;
  565. // The size of work_stack_ at the start of resolving the current instruction.
  566. size_t initial_work_ = 0;
  567. };
  568. } // namespace
  569. static auto AddImportRef(ImportContext& context, SemIR::InstId inst_id,
  570. SemIR::EntityNameId entity_name_id =
  571. SemIR::EntityNameId::Invalid) -> SemIR::InstId {
  572. return AddImportRef(context.local_context(),
  573. {.ir_id = context.import_ir_id(), .inst_id = inst_id},
  574. entity_name_id);
  575. }
  576. static auto AddLoadedImportRef(ImportContext& context, SemIR::TypeId type_id,
  577. SemIR::InstId inst_id,
  578. SemIR::ConstantId const_id) -> SemIR::InstId {
  579. return AddLoadedImportRef(
  580. context.local_context(), type_id,
  581. {.ir_id = context.import_ir_id(), .inst_id = inst_id}, const_id);
  582. }
  583. static auto AddImportIRInst(ImportContext& context, SemIR::InstId inst_id)
  584. -> SemIR::ImportIRInstId {
  585. return context.local_import_ir_insts().Add(
  586. {.ir_id = context.import_ir_id(), .inst_id = inst_id});
  587. }
  588. // Returns the ConstantId for an InstId. Adds unresolved constants to
  589. // the resolver's work stack.
  590. static auto GetLocalConstantId(ImportRefResolver& resolver,
  591. SemIR::InstId inst_id) -> SemIR::ConstantId {
  592. return resolver.GetLocalConstantValueOrPush(inst_id);
  593. }
  594. // Returns the ConstantId for an imported ConstantId. Adds unresolved
  595. // constants to the resolver's work stack.
  596. static auto GetLocalConstantId(ImportRefResolver& resolver,
  597. SemIR::ConstantId const_id)
  598. -> SemIR::ConstantId {
  599. return GetLocalConstantId(
  600. resolver, GetInstWithConstantValue(resolver.import_ir(), const_id));
  601. }
  602. // Returns the local constant InstId for an imported InstId.
  603. static auto GetLocalConstantInstId(ImportRefResolver& resolver,
  604. SemIR::InstId inst_id) -> SemIR::InstId {
  605. auto const_id = GetLocalConstantId(resolver, inst_id);
  606. return resolver.local_constant_values().GetInstIdIfValid(const_id);
  607. }
  608. // Returns the ConstantId for a TypeId. Adds unresolved constants to
  609. // work_stack_.
  610. static auto GetLocalConstantId(ImportRefResolver& resolver,
  611. SemIR::TypeId type_id) -> SemIR::ConstantId {
  612. return GetLocalConstantId(resolver,
  613. resolver.import_types().GetConstantId(type_id));
  614. }
  615. // Returns the ConstantId for an InstId that is required to have already been
  616. // imported.
  617. static auto GetLocalConstantIdChecked(ImportContext& context,
  618. SemIR::InstId inst_id)
  619. -> SemIR::ConstantId {
  620. auto result_id =
  621. context.local_constant_values_for_import_insts().Get(inst_id);
  622. CARBON_CHECK(result_id.is_valid());
  623. return result_id;
  624. }
  625. // Returns the ConstantId for a ConstantId that is required to have already been
  626. // imported.
  627. static auto GetLocalConstantIdChecked(ImportContext& context,
  628. SemIR::ConstantId const_id)
  629. -> SemIR::ConstantId {
  630. return GetLocalConstantIdChecked(
  631. context, GetInstWithConstantValue(context.import_ir(), const_id));
  632. }
  633. // Returns the ConstantId for a TypeId that is required to have already been
  634. // imported.
  635. static auto GetLocalConstantIdChecked(ImportContext& context,
  636. SemIR::TypeId type_id)
  637. -> SemIR::ConstantId {
  638. return GetLocalConstantIdChecked(
  639. context, context.import_types().GetConstantId(type_id));
  640. }
  641. // Translates a NameId from the import IR to a local NameId.
  642. static auto GetLocalNameId(ImportContext& context, SemIR::NameId import_name_id)
  643. -> SemIR::NameId {
  644. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.is_valid()) {
  645. return SemIR::NameId::ForIdentifier(context.local_identifiers().Add(
  646. context.import_identifiers().Get(ident_id)));
  647. }
  648. return import_name_id;
  649. }
  650. // Gets the local constant values corresponding to an imported inst block.
  651. static auto GetLocalInstBlockContents(ImportRefResolver& resolver,
  652. SemIR::InstBlockId import_block_id)
  653. -> llvm::SmallVector<SemIR::InstId> {
  654. llvm::SmallVector<SemIR::InstId> inst_ids;
  655. if (!import_block_id.is_valid() ||
  656. import_block_id == SemIR::InstBlockId::Empty) {
  657. return inst_ids;
  658. }
  659. // Import all the values in the block.
  660. auto import_block = resolver.import_inst_blocks().Get(import_block_id);
  661. inst_ids.reserve(import_block.size());
  662. for (auto import_inst_id : import_block) {
  663. auto const_id = GetLocalConstantId(resolver, import_inst_id);
  664. inst_ids.push_back(
  665. resolver.local_constant_values().GetInstIdIfValid(const_id));
  666. }
  667. return inst_ids;
  668. }
  669. // Gets a local canonical instruction block ID corresponding to an imported inst
  670. // block whose contents were already imported, for example by
  671. // GetLocalInstBlockContents.
  672. static auto GetLocalCanonicalInstBlockId(ImportContext& context,
  673. SemIR::InstBlockId import_block_id,
  674. llvm::ArrayRef<SemIR::InstId> contents)
  675. -> SemIR::InstBlockId {
  676. if (!import_block_id.is_valid()) {
  677. return SemIR::InstBlockId::Invalid;
  678. }
  679. return context.local_inst_blocks().AddCanonical(contents);
  680. }
  681. // Gets an incomplete local version of an imported generic. Most fields are
  682. // set in the third phase.
  683. static auto MakeIncompleteGeneric(ImportContext& context, SemIR::InstId decl_id,
  684. SemIR::GenericId generic_id)
  685. -> SemIR::GenericId {
  686. if (!generic_id.is_valid()) {
  687. return SemIR::GenericId::Invalid;
  688. }
  689. return context.local_generics().Add(
  690. {.decl_id = decl_id,
  691. .bindings_id = SemIR::InstBlockId::Invalid,
  692. .self_specific_id = SemIR::SpecificId::Invalid});
  693. }
  694. namespace {
  695. // Local information associated with an imported generic.
  696. struct GenericData {
  697. llvm::SmallVector<SemIR::InstId> bindings;
  698. };
  699. } // namespace
  700. // Gets a local version of the data associated with a generic.
  701. static auto GetLocalGenericData(ImportRefResolver& resolver,
  702. SemIR::GenericId generic_id) -> GenericData {
  703. if (!generic_id.is_valid()) {
  704. return GenericData();
  705. }
  706. const auto& generic = resolver.import_generics().Get(generic_id);
  707. return {.bindings = GetLocalInstBlockContents(resolver, generic.bindings_id)};
  708. }
  709. // Adds the given local generic data to the given generic.
  710. static auto SetGenericData(ImportContext& context,
  711. SemIR::GenericId import_generic_id,
  712. SemIR::GenericId new_generic_id,
  713. const GenericData& generic_data) -> void {
  714. if (!import_generic_id.is_valid()) {
  715. return;
  716. }
  717. const auto& import_generic = context.import_generics().Get(import_generic_id);
  718. auto& new_generic = context.local_generics().Get(new_generic_id);
  719. new_generic.bindings_id = GetLocalCanonicalInstBlockId(
  720. context, import_generic.bindings_id, generic_data.bindings);
  721. // Track that we need to fill in the remaining information in
  722. // FinishPendingGeneric.
  723. context.AddPendingGeneric(
  724. {.import_id = import_generic_id, .local_id = new_generic_id});
  725. }
  726. // Gets a local constant value corresponding to an imported generic ID. May
  727. // add work to the work stack and return `Invalid`.
  728. static auto GetLocalConstantId(ImportRefResolver& resolver,
  729. SemIR::GenericId generic_id)
  730. -> SemIR::ConstantId {
  731. if (!generic_id.is_valid()) {
  732. return SemIR::ConstantId::Invalid;
  733. }
  734. auto import_decl_inst_id = resolver.import_generics().Get(generic_id).decl_id;
  735. auto import_decl_inst = resolver.import_insts().Get(import_decl_inst_id);
  736. if (import_decl_inst.Is<SemIR::ImplDecl>()) {
  737. // For an impl declaration, the imported entity can be found via the
  738. // declaration.
  739. return GetLocalConstantId(resolver, import_decl_inst_id);
  740. }
  741. // For all other kinds of declaration, the imported entity can be found via
  742. // the type of the declaration.
  743. return GetLocalConstantId(resolver, import_decl_inst.type_id());
  744. }
  745. // Gets a local generic ID given the corresponding local constant ID returned
  746. // by GetLocalConstantId for the imported generic. Does not add any new work.
  747. static auto GetLocalGenericId(ImportContext& context,
  748. SemIR::ConstantId local_const_id)
  749. -> SemIR::GenericId {
  750. if (!local_const_id.is_valid()) {
  751. return SemIR::GenericId::Invalid;
  752. }
  753. auto inst = context.local_insts().Get(
  754. context.local_constant_values().GetInstId(local_const_id));
  755. CARBON_KIND_SWITCH(inst) {
  756. case CARBON_KIND(SemIR::FunctionType fn_type): {
  757. return context.local_functions().Get(fn_type.function_id).generic_id;
  758. }
  759. case CARBON_KIND(SemIR::GenericClassType class_type): {
  760. return context.local_classes().Get(class_type.class_id).generic_id;
  761. }
  762. case CARBON_KIND(SemIR::GenericInterfaceType interface_type): {
  763. return context.local_interfaces()
  764. .Get(interface_type.interface_id)
  765. .generic_id;
  766. }
  767. case CARBON_KIND(SemIR::ImplDecl impl_decl): {
  768. return context.local_impls().Get(impl_decl.impl_id).generic_id;
  769. }
  770. default: {
  771. CARBON_FATAL("Unexpected inst for generic declaration: {0}", inst);
  772. }
  773. }
  774. }
  775. namespace {
  776. // Local information associated with an imported specific.
  777. struct SpecificData {
  778. SemIR::ConstantId generic_const_id;
  779. llvm::SmallVector<SemIR::InstId> args;
  780. };
  781. } // namespace
  782. // Gets local information about an imported specific.
  783. static auto GetLocalSpecificData(ImportRefResolver& resolver,
  784. SemIR::SpecificId specific_id)
  785. -> SpecificData {
  786. if (!specific_id.is_valid()) {
  787. return {.generic_const_id = SemIR::ConstantId::Invalid, .args = {}};
  788. }
  789. const auto& specific = resolver.import_specifics().Get(specific_id);
  790. return {
  791. .generic_const_id = GetLocalConstantId(resolver, specific.generic_id),
  792. .args = GetLocalInstBlockContents(resolver, specific.args_id),
  793. };
  794. }
  795. // Gets a local specific whose data was already imported by
  796. // GetLocalSpecificData. Does not add any new work.
  797. static auto GetOrAddLocalSpecific(ImportContext& context,
  798. SemIR::SpecificId import_specific_id,
  799. const SpecificData& data)
  800. -> SemIR::SpecificId {
  801. if (!import_specific_id.is_valid()) {
  802. return SemIR::SpecificId::Invalid;
  803. }
  804. // Form a corresponding local specific ID.
  805. const auto& import_specific =
  806. context.import_specifics().Get(import_specific_id);
  807. auto generic_id = GetLocalGenericId(context, data.generic_const_id);
  808. auto args_id =
  809. GetLocalCanonicalInstBlockId(context, import_specific.args_id, data.args);
  810. // Get the specific.
  811. auto specific_id = context.local_specifics().GetOrAdd(generic_id, args_id);
  812. // Fill in the remaining information in FinishPendingSpecific, if necessary.
  813. auto& specific = context.local_specifics().Get(specific_id);
  814. if (!specific.decl_block_id.is_valid() ||
  815. (import_specific.definition_block_id.is_valid() &&
  816. !specific.definition_block_id.is_valid())) {
  817. context.AddPendingSpecific(
  818. {.import_id = import_specific_id, .local_id = specific_id});
  819. }
  820. return specific_id;
  821. }
  822. // Adds unresolved constants for each parameter's type to the resolver's work
  823. // stack.
  824. static auto LoadLocalPatternConstantIds(ImportRefResolver& resolver,
  825. SemIR::InstBlockId param_patterns_id)
  826. -> void {
  827. if (!param_patterns_id.is_valid() ||
  828. param_patterns_id == SemIR::InstBlockId::Empty) {
  829. return;
  830. }
  831. const auto& param_patterns =
  832. resolver.import_inst_blocks().Get(param_patterns_id);
  833. for (auto pattern_id : param_patterns) {
  834. auto pattern_inst = resolver.import_insts().Get(pattern_id);
  835. GetLocalConstantId(resolver, pattern_inst.type_id());
  836. if (auto addr = pattern_inst.TryAs<SemIR::AddrPattern>()) {
  837. pattern_id = addr->inner_id;
  838. pattern_inst = resolver.import_insts().Get(pattern_id);
  839. GetLocalConstantId(resolver, pattern_inst.type_id());
  840. }
  841. pattern_id = resolver.import_insts()
  842. .GetAs<SemIR::ValueParamPattern>(pattern_id)
  843. .subpattern_id;
  844. pattern_inst = resolver.import_insts().Get(pattern_id);
  845. // If the parameter is a symbolic binding, build the
  846. // SymbolicBindingPattern constant.
  847. if (pattern_inst.Is<SemIR::SymbolicBindingPattern>()) {
  848. GetLocalConstantId(resolver, pattern_id);
  849. }
  850. }
  851. }
  852. // Returns a version of param_patterns_id localized to the current IR.
  853. //
  854. // Must only be called after a call to
  855. // LoadLocalPatternConstantIds(param_patterns_id) has completed without adding
  856. // any new work to work_stack_.
  857. //
  858. // TODO: This is inconsistent with the rest of this class, which expects
  859. // the relevant constants to be explicitly passed in. That makes it
  860. // easier to statically detect when an input isn't loaded, but makes it
  861. // harder to support importing more complex inst structures. We should
  862. // take a holistic look at how to balance those concerns. For example,
  863. // could the same function be used to load the constants and use them, with
  864. // a parameter to select between the two?
  865. static auto GetLocalParamPatternsId(ImportContext& context,
  866. SemIR::InstBlockId param_patterns_id)
  867. -> SemIR::InstBlockId {
  868. if (!param_patterns_id.is_valid() ||
  869. param_patterns_id == SemIR::InstBlockId::Empty) {
  870. return param_patterns_id;
  871. }
  872. const auto& param_patterns =
  873. context.import_inst_blocks().Get(param_patterns_id);
  874. llvm::SmallVector<SemIR::InstId> new_patterns;
  875. for (auto param_id : param_patterns) {
  876. // Figure out the pattern structure. This echoes
  877. // Function::GetParamPatternInfoFromPatternId.
  878. auto addr_pattern_id = param_id;
  879. auto addr_inst =
  880. context.import_insts().TryGetAs<SemIR::AddrPattern>(addr_pattern_id);
  881. auto param_pattern_id = addr_pattern_id;
  882. if (addr_inst) {
  883. param_pattern_id = addr_inst->inner_id;
  884. }
  885. auto param_pattern = context.import_insts().GetAs<SemIR::ValueParamPattern>(
  886. param_pattern_id);
  887. auto binding_id = param_pattern.subpattern_id;
  888. auto binding =
  889. context.import_insts().GetAs<SemIR::AnyBindingPattern>(binding_id);
  890. // Rebuild the pattern.
  891. auto entity_name =
  892. context.import_entity_names().Get(binding.entity_name_id);
  893. auto name_id = GetLocalNameId(context, entity_name.name_id);
  894. auto type_id = context.local_context().GetTypeIdForTypeConstant(
  895. GetLocalConstantIdChecked(context, binding.type_id));
  896. auto new_param_id = SemIR::InstId::Invalid;
  897. switch (binding.kind) {
  898. case SemIR::BindingPattern::Kind: {
  899. auto entity_name_id = context.local_entity_names().Add(
  900. {.name_id = name_id,
  901. .parent_scope_id = SemIR::NameScopeId::Invalid,
  902. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  903. new_param_id =
  904. context.local_context().AddInstInNoBlock<SemIR::BindingPattern>(
  905. AddImportIRInst(context, binding_id),
  906. {.type_id = type_id, .entity_name_id = entity_name_id});
  907. break;
  908. }
  909. case SemIR::SymbolicBindingPattern::Kind: {
  910. // We already imported a constant value for this symbolic binding.
  911. // We can reuse most of it, but update the value to point to our
  912. // specific parameter, and preserve the constant value.
  913. auto bind_const_id = GetLocalConstantIdChecked(context, binding_id);
  914. auto new_binding_inst =
  915. context.local_insts().GetAs<SemIR::SymbolicBindingPattern>(
  916. context.local_constant_values().GetInstId(bind_const_id));
  917. new_param_id = context.local_context().AddInstInNoBlock(
  918. AddImportIRInst(context, binding_id), new_binding_inst);
  919. context.local_constant_values().Set(new_param_id, bind_const_id);
  920. break;
  921. }
  922. default: {
  923. CARBON_FATAL("Unexpected kind: ", binding.kind);
  924. }
  925. }
  926. new_param_id = context.local_context().AddInstInNoBlock(
  927. context.local_context()
  928. .MakeImportedLocAndInst<SemIR::ValueParamPattern>(
  929. AddImportIRInst(context, param_pattern_id),
  930. {.type_id = type_id,
  931. .subpattern_id = new_param_id,
  932. .runtime_index = param_pattern.runtime_index}));
  933. if (addr_inst) {
  934. type_id = context.local_context().GetTypeIdForTypeConstant(
  935. GetLocalConstantIdChecked(context, addr_inst->type_id));
  936. new_param_id = context.local_context().AddInstInNoBlock(
  937. context.local_context().MakeImportedLocAndInst<SemIR::AddrPattern>(
  938. AddImportIRInst(context, addr_pattern_id),
  939. {.type_id = type_id, .inner_id = new_param_id}));
  940. }
  941. new_patterns.push_back(new_param_id);
  942. }
  943. return context.local_inst_blocks().Add(new_patterns);
  944. }
  945. // Returns a version of import_return_slot_pattern_id localized to the current
  946. // IR.
  947. static auto GetLocalReturnSlotPatternId(
  948. ImportContext& context, SemIR::InstId import_return_slot_pattern_id)
  949. -> SemIR::InstId {
  950. if (!import_return_slot_pattern_id.is_valid()) {
  951. return SemIR::InstId::Invalid;
  952. }
  953. auto param_pattern = context.import_insts().GetAs<SemIR::OutParamPattern>(
  954. import_return_slot_pattern_id);
  955. auto return_slot_pattern =
  956. context.import_insts().GetAs<SemIR::ReturnSlotPattern>(
  957. param_pattern.subpattern_id);
  958. auto type_id = context.local_context().GetTypeIdForTypeConstant(
  959. GetLocalConstantIdChecked(context, return_slot_pattern.type_id));
  960. auto new_return_slot_pattern_id = context.local_context().AddInstInNoBlock(
  961. context.local_context().MakeImportedLocAndInst<SemIR::ReturnSlotPattern>(
  962. AddImportIRInst(context, param_pattern.subpattern_id),
  963. {.type_id = type_id, .type_inst_id = SemIR::InstId::Invalid}));
  964. return context.local_context().AddInstInNoBlock(
  965. context.local_context().MakeImportedLocAndInst<SemIR::OutParamPattern>(
  966. AddImportIRInst(context, import_return_slot_pattern_id),
  967. {.type_id = type_id,
  968. .subpattern_id = new_return_slot_pattern_id,
  969. .runtime_index = param_pattern.runtime_index}));
  970. }
  971. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  972. // unresolved constants to the resolver's work stack.
  973. static auto GetLocalNameScopeId(ImportRefResolver& resolver,
  974. SemIR::NameScopeId name_scope_id)
  975. -> SemIR::NameScopeId {
  976. // Get the instruction that created the scope.
  977. auto [inst_id, inst] =
  978. resolver.import_name_scopes().GetInstIfValid(name_scope_id);
  979. if (!inst) {
  980. // Map scopes that aren't associated with an instruction to invalid
  981. // scopes. For now, such scopes aren't used, and we don't have a good way
  982. // to remap them.
  983. return SemIR::NameScopeId::Invalid;
  984. }
  985. // Get the constant value for the scope.
  986. auto const_id = GetLocalConstantId(resolver, inst_id);
  987. if (!const_id.is_valid()) {
  988. return SemIR::NameScopeId::Invalid;
  989. }
  990. auto const_inst_id = resolver.local_constant_values().GetInstId(const_id);
  991. auto name_scope_inst = resolver.local_insts().Get(const_inst_id);
  992. CARBON_KIND_SWITCH(name_scope_inst) {
  993. case CARBON_KIND(SemIR::Namespace inst): {
  994. return inst.name_scope_id;
  995. }
  996. case CARBON_KIND(SemIR::ClassType inst): {
  997. return resolver.local_classes().Get(inst.class_id).scope_id;
  998. }
  999. case CARBON_KIND(SemIR::FacetType inst): {
  1000. const SemIR::FacetTypeInfo& facet_type_info =
  1001. resolver.local_facet_types().Get(inst.facet_type_id);
  1002. // This is specifically the facet type produced by an interface
  1003. // declaration, and so should consist of a single interface.
  1004. // TODO: Will also have to handle named constraints here, once those are
  1005. // implemented.
  1006. auto interface = facet_type_info.TryAsSingleInterface();
  1007. CARBON_CHECK(interface);
  1008. return resolver.local_interfaces().Get(interface->interface_id).scope_id;
  1009. }
  1010. case CARBON_KIND(SemIR::ImplDecl inst): {
  1011. return resolver.local_impls().Get(inst.impl_id).scope_id;
  1012. }
  1013. case SemIR::StructValue::Kind: {
  1014. auto type_inst =
  1015. resolver.local_types().GetAsInst(name_scope_inst.type_id());
  1016. CARBON_KIND_SWITCH(type_inst) {
  1017. case CARBON_KIND(SemIR::GenericClassType inst): {
  1018. return resolver.local_classes().Get(inst.class_id).scope_id;
  1019. }
  1020. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  1021. return resolver.local_interfaces().Get(inst.interface_id).scope_id;
  1022. }
  1023. default: {
  1024. break;
  1025. }
  1026. }
  1027. break;
  1028. }
  1029. default: {
  1030. if (const_inst_id == SemIR::ErrorInst::SingletonInstId) {
  1031. return SemIR::NameScopeId::Invalid;
  1032. }
  1033. break;
  1034. }
  1035. }
  1036. CARBON_FATAL("Unexpected instruction kind for name scope: {0}",
  1037. name_scope_inst);
  1038. }
  1039. // Given an imported entity base, returns an incomplete, local version of it.
  1040. //
  1041. // Most fields are set in the third phase once they're imported. Import enough
  1042. // of the parameter lists that we know whether this interface is a generic
  1043. // interface and can build the right constant value for it.
  1044. //
  1045. // TODO: Support extern.
  1046. static auto GetIncompleteLocalEntityBase(
  1047. ImportContext& context, SemIR::InstId decl_id,
  1048. const SemIR::EntityWithParamsBase& import_base)
  1049. -> SemIR::EntityWithParamsBase {
  1050. // Translate the extern_library_id if present.
  1051. auto extern_library_id = SemIR::LibraryNameId::Invalid;
  1052. if (import_base.extern_library_id.is_valid()) {
  1053. if (import_base.extern_library_id.index >= 0) {
  1054. auto val = context.import_string_literal_values().Get(
  1055. import_base.extern_library_id.AsStringLiteralValueId());
  1056. extern_library_id = SemIR::LibraryNameId::ForStringLiteralValueId(
  1057. context.local_string_literal_values().Add(val));
  1058. } else {
  1059. extern_library_id = import_base.extern_library_id;
  1060. }
  1061. }
  1062. return {
  1063. .name_id = GetLocalNameId(context, import_base.name_id),
  1064. .parent_scope_id = SemIR::NameScopeId::Invalid,
  1065. .generic_id =
  1066. MakeIncompleteGeneric(context, decl_id, import_base.generic_id),
  1067. .first_param_node_id = Parse::NodeId::Invalid,
  1068. .last_param_node_id = Parse::NodeId::Invalid,
  1069. .pattern_block_id = SemIR::InstBlockId::Invalid,
  1070. .implicit_param_patterns_id =
  1071. import_base.implicit_param_patterns_id.is_valid()
  1072. ? SemIR::InstBlockId::Empty
  1073. : SemIR::InstBlockId::Invalid,
  1074. .param_patterns_id = import_base.param_patterns_id.is_valid()
  1075. ? SemIR::InstBlockId::Empty
  1076. : SemIR::InstBlockId::Invalid,
  1077. .call_params_id = SemIR::InstBlockId::Invalid,
  1078. .is_extern = import_base.is_extern,
  1079. .extern_library_id = extern_library_id,
  1080. .non_owning_decl_id = import_base.non_owning_decl_id.is_valid()
  1081. ? decl_id
  1082. : SemIR::InstId::Invalid,
  1083. .first_owning_decl_id = import_base.first_owning_decl_id.is_valid()
  1084. ? decl_id
  1085. : SemIR::InstId::Invalid,
  1086. };
  1087. }
  1088. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  1089. // lookup.
  1090. static auto AddNameScopeImportRefs(ImportContext& context,
  1091. const SemIR::NameScope& import_scope,
  1092. SemIR::NameScope& new_scope) -> void {
  1093. for (auto entry : import_scope.entries()) {
  1094. if (entry.is_poisoned) {
  1095. continue;
  1096. }
  1097. auto ref_id = AddImportRef(context, entry.inst_id);
  1098. new_scope.AddRequired({.name_id = GetLocalNameId(context, entry.name_id),
  1099. .inst_id = ref_id,
  1100. .access_kind = entry.access_kind});
  1101. }
  1102. for (auto scope_inst_id : import_scope.extended_scopes()) {
  1103. new_scope.AddExtendedScope(AddImportRef(context, scope_inst_id));
  1104. }
  1105. }
  1106. // Given a block ID for a list of associated entities of a witness, returns a
  1107. // version localized to the current IR.
  1108. static auto AddAssociatedEntities(ImportContext& context,
  1109. SemIR::NameScopeId local_name_scope_id,
  1110. SemIR::InstBlockId associated_entities_id)
  1111. -> SemIR::InstBlockId {
  1112. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  1113. return SemIR::InstBlockId::Empty;
  1114. }
  1115. auto associated_entities =
  1116. context.import_inst_blocks().Get(associated_entities_id);
  1117. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  1118. new_associated_entities.reserve(associated_entities.size());
  1119. for (auto inst_id : associated_entities) {
  1120. // Determine the name of the associated entity, by switching on its kind.
  1121. SemIR::NameId import_name_id = SemIR::NameId::Invalid;
  1122. if (auto associated_const =
  1123. context.import_insts().TryGetAs<SemIR::AssociatedConstantDecl>(
  1124. inst_id)) {
  1125. import_name_id = associated_const->name_id;
  1126. } else if (auto function_decl =
  1127. context.import_insts().TryGetAs<SemIR::FunctionDecl>(
  1128. inst_id)) {
  1129. auto function =
  1130. context.import_functions().Get(function_decl->function_id);
  1131. import_name_id = function.name_id;
  1132. } else if (auto import_ref =
  1133. context.import_insts().TryGetAs<SemIR::AnyImportRef>(
  1134. inst_id)) {
  1135. import_name_id =
  1136. context.import_entity_names().Get(import_ref->entity_name_id).name_id;
  1137. } else {
  1138. CARBON_FATAL("Unhandled associated entity kind: {0}",
  1139. context.import_insts().Get(inst_id).kind());
  1140. }
  1141. auto name_id = GetLocalNameId(context, import_name_id);
  1142. auto entity_name_id = context.local_entity_names().Add(
  1143. {.name_id = name_id,
  1144. .parent_scope_id = local_name_scope_id,
  1145. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  1146. new_associated_entities.push_back(
  1147. AddImportRef(context, inst_id, entity_name_id));
  1148. }
  1149. return context.local_inst_blocks().Add(new_associated_entities);
  1150. }
  1151. // Produces a resolve result that provides the given constant value. Retries
  1152. // instead if work has been added.
  1153. static auto RetryOrDone(ImportRefResolver& resolver, SemIR::ConstantId const_id)
  1154. -> ResolveResult {
  1155. if (resolver.HasNewWork()) {
  1156. return ResolveResult::Retry();
  1157. }
  1158. return ResolveResult::Done(const_id);
  1159. }
  1160. // Produces a resolve result for the given instruction that describes a constant
  1161. // value. This should only be used for instructions that describe constants, and
  1162. // not for instructions that represent declarations. For a declaration, we need
  1163. // an associated location, so AddInstInNoBlock should be used instead. Requires
  1164. // that there is no new work.
  1165. static auto ResolveAsUntyped(ImportContext& context, SemIR::Inst inst)
  1166. -> ResolveResult {
  1167. auto result =
  1168. TryEvalInst(context.local_context(), SemIR::InstId::Invalid, inst);
  1169. CARBON_CHECK(result.is_constant(), "{0} is not constant", inst);
  1170. return ResolveResult::Done(result);
  1171. }
  1172. // Same as ResolveAsUntyped, but with an explicit type for convenience.
  1173. template <typename InstT>
  1174. static auto ResolveAs(ImportContext& context, InstT inst) -> ResolveResult {
  1175. return ResolveAsUntyped(context, inst);
  1176. }
  1177. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1178. SemIR::AdaptDecl inst,
  1179. SemIR::InstId import_inst_id) -> ResolveResult {
  1180. auto adapted_type_const_id = GetLocalConstantId(
  1181. resolver,
  1182. resolver.import_constant_values().Get(inst.adapted_type_inst_id));
  1183. if (resolver.HasNewWork()) {
  1184. return ResolveResult::Retry();
  1185. }
  1186. auto adapted_type_inst_id =
  1187. AddLoadedImportRef(resolver, SemIR::TypeType::SingletonTypeId,
  1188. inst.adapted_type_inst_id, adapted_type_const_id);
  1189. // Create a corresponding instruction to represent the declaration.
  1190. auto inst_id = resolver.local_context().AddInstInNoBlock(
  1191. resolver.local_context().MakeImportedLocAndInst<SemIR::AdaptDecl>(
  1192. AddImportIRInst(resolver, import_inst_id),
  1193. {.adapted_type_inst_id = adapted_type_inst_id}));
  1194. return ResolveResult::Done(resolver.local_constant_values().Get(inst_id),
  1195. inst_id);
  1196. }
  1197. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1198. SemIR::ArrayType inst) -> ResolveResult {
  1199. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1200. auto element_type_const_id =
  1201. GetLocalConstantId(resolver, inst.element_type_id);
  1202. auto bound_id = GetLocalConstantInstId(resolver, inst.bound_id);
  1203. if (resolver.HasNewWork()) {
  1204. return ResolveResult::Retry();
  1205. }
  1206. auto element_type_id =
  1207. resolver.local_context().GetTypeIdForTypeConstant(element_type_const_id);
  1208. return ResolveAs<SemIR::ArrayType>(
  1209. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  1210. .bound_id = bound_id,
  1211. .element_type_id = element_type_id});
  1212. }
  1213. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1214. SemIR::AssociatedConstantDecl inst,
  1215. SemIR::InstId import_inst_id) -> ResolveResult {
  1216. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1217. if (resolver.HasNewWork()) {
  1218. return ResolveResult::Retry();
  1219. }
  1220. auto type_id =
  1221. resolver.local_context().GetTypeIdForTypeConstant(type_const_id);
  1222. // Create a corresponding instruction to represent the declaration.
  1223. auto inst_id = resolver.local_context().AddInstInNoBlock(
  1224. resolver.local_context()
  1225. .MakeImportedLocAndInst<SemIR::AssociatedConstantDecl>(
  1226. AddImportIRInst(resolver, import_inst_id),
  1227. {.type_id = type_id,
  1228. .name_id = GetLocalNameId(resolver, inst.name_id)}));
  1229. return ResolveResult::Done(resolver.local_constant_values().Get(inst_id),
  1230. inst_id);
  1231. }
  1232. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1233. SemIR::AssociatedEntity inst) -> ResolveResult {
  1234. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1235. if (resolver.HasNewWork()) {
  1236. return ResolveResult::Retry();
  1237. }
  1238. // Add a lazy reference to the target declaration.
  1239. auto decl_id = AddImportRef(resolver, inst.decl_id);
  1240. return ResolveAs<SemIR::AssociatedEntity>(
  1241. resolver, {.type_id = resolver.local_context().GetTypeIdForTypeConstant(
  1242. type_const_id),
  1243. .index = inst.index,
  1244. .decl_id = decl_id});
  1245. }
  1246. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1247. SemIR::AssociatedEntityType inst)
  1248. -> ResolveResult {
  1249. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1250. auto entity_type_const_id = GetLocalConstantId(resolver, inst.entity_type_id);
  1251. auto interface_inst_id = GetLocalConstantId(resolver, inst.interface_type_id);
  1252. if (resolver.HasNewWork()) {
  1253. return ResolveResult::Retry();
  1254. }
  1255. return ResolveAs<SemIR::AssociatedEntityType>(
  1256. resolver,
  1257. {.type_id = SemIR::TypeType::SingletonTypeId,
  1258. .interface_type_id =
  1259. resolver.local_context().GetTypeIdForTypeConstant(interface_inst_id),
  1260. .entity_type_id = resolver.local_context().GetTypeIdForTypeConstant(
  1261. entity_type_const_id)});
  1262. }
  1263. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1264. SemIR::BaseDecl inst,
  1265. SemIR::InstId import_inst_id) -> ResolveResult {
  1266. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1267. auto base_type_const_id = GetLocalConstantId(
  1268. resolver, resolver.import_constant_values().Get(inst.base_type_inst_id));
  1269. if (resolver.HasNewWork()) {
  1270. return ResolveResult::Retry();
  1271. }
  1272. auto base_type_inst_id =
  1273. AddLoadedImportRef(resolver, SemIR::TypeType::SingletonTypeId,
  1274. inst.base_type_inst_id, base_type_const_id);
  1275. // Create a corresponding instruction to represent the declaration.
  1276. auto inst_id = resolver.local_context().AddInstInNoBlock(
  1277. resolver.local_context().MakeImportedLocAndInst<SemIR::BaseDecl>(
  1278. AddImportIRInst(resolver, import_inst_id),
  1279. {.type_id =
  1280. resolver.local_context().GetTypeIdForTypeConstant(type_const_id),
  1281. .base_type_inst_id = base_type_inst_id,
  1282. .index = inst.index}));
  1283. return ResolveResult::Done(resolver.local_constant_values().Get(inst_id),
  1284. inst_id);
  1285. }
  1286. static auto TryResolveTypedInst(ImportRefResolver& resolver, SemIR::Vtable inst,
  1287. SemIR::InstId /*import_inst_id*/)
  1288. -> ResolveResult {
  1289. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1290. auto virtual_functions =
  1291. GetLocalInstBlockContents(resolver, inst.virtual_functions_id);
  1292. if (resolver.HasNewWork()) {
  1293. return ResolveResult::Retry();
  1294. }
  1295. auto virtual_functions_id = GetLocalCanonicalInstBlockId(
  1296. resolver, inst.virtual_functions_id, virtual_functions);
  1297. return ResolveAs<SemIR::Vtable>(
  1298. resolver, {.type_id = resolver.local_context().GetTypeIdForTypeConstant(
  1299. type_const_id),
  1300. .virtual_functions_id = virtual_functions_id});
  1301. }
  1302. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1303. SemIR::BindAlias inst) -> ResolveResult {
  1304. auto value_id = GetLocalConstantId(resolver, inst.value_id);
  1305. return RetryOrDone(resolver, value_id);
  1306. }
  1307. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1308. SemIR::BindSymbolicName inst) -> ResolveResult {
  1309. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1310. if (resolver.HasNewWork()) {
  1311. return ResolveResult::Retry();
  1312. }
  1313. const auto& import_entity_name =
  1314. resolver.import_entity_names().Get(inst.entity_name_id);
  1315. auto name_id = GetLocalNameId(resolver, import_entity_name.name_id);
  1316. auto entity_name_id = resolver.local_entity_names().Add(
  1317. {.name_id = name_id,
  1318. .parent_scope_id = SemIR::NameScopeId::Invalid,
  1319. .bind_index = import_entity_name.bind_index});
  1320. return ResolveAs<SemIR::BindSymbolicName>(
  1321. resolver,
  1322. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  1323. .entity_name_id = entity_name_id,
  1324. .value_id = SemIR::InstId::Invalid});
  1325. }
  1326. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1327. SemIR::SymbolicBindingPattern inst)
  1328. -> ResolveResult {
  1329. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1330. if (resolver.HasNewWork()) {
  1331. return ResolveResult::Retry();
  1332. }
  1333. const auto& import_entity_name =
  1334. resolver.import_entity_names().Get(inst.entity_name_id);
  1335. auto name_id = GetLocalNameId(resolver, import_entity_name.name_id);
  1336. auto entity_name_id = resolver.local_entity_names().Add(
  1337. {.name_id = name_id,
  1338. .parent_scope_id = SemIR::NameScopeId::Invalid,
  1339. .bind_index = import_entity_name.bind_index});
  1340. return ResolveAs<SemIR::SymbolicBindingPattern>(
  1341. resolver,
  1342. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  1343. .entity_name_id = entity_name_id});
  1344. }
  1345. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1346. SemIR::BoundMethod inst) -> ResolveResult {
  1347. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  1348. SemIR::BoundMethodType::SingletonInstId);
  1349. auto object_id = GetLocalConstantInstId(resolver, inst.object_id);
  1350. auto function_decl_id =
  1351. GetLocalConstantInstId(resolver, inst.function_decl_id);
  1352. if (resolver.HasNewWork()) {
  1353. return ResolveResult::Retry();
  1354. }
  1355. return ResolveAs<SemIR::BoundMethod>(
  1356. resolver, {.type_id = resolver.local_context().GetSingletonType(
  1357. SemIR::BoundMethodType::SingletonInstId),
  1358. .object_id = object_id,
  1359. .function_decl_id = function_decl_id});
  1360. }
  1361. static auto TryResolveTypedInst(ImportRefResolver& resolver, SemIR::Call inst)
  1362. -> ResolveResult {
  1363. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1364. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  1365. auto args = GetLocalInstBlockContents(resolver, inst.args_id);
  1366. if (resolver.HasNewWork()) {
  1367. return ResolveResult::Retry();
  1368. }
  1369. return ResolveAs<SemIR::Call>(
  1370. resolver,
  1371. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  1372. .callee_id = callee_id,
  1373. .args_id = GetLocalCanonicalInstBlockId(resolver, inst.args_id, args)});
  1374. }
  1375. // Makes an incomplete class. This is necessary even with classes with a
  1376. // complete declaration, because things such as `Self` may refer back to the
  1377. // type.
  1378. static auto MakeIncompleteClass(ImportContext& context,
  1379. const SemIR::Class& import_class,
  1380. SemIR::SpecificId enclosing_specific_id)
  1381. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  1382. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeType::SingletonTypeId,
  1383. .class_id = SemIR::ClassId::Invalid,
  1384. .decl_block_id = SemIR::InstBlockId::Empty};
  1385. auto class_decl_id = context.local_context().AddPlaceholderInstInNoBlock(
  1386. context.local_context().MakeImportedLocAndInst(
  1387. AddImportIRInst(context, import_class.latest_decl_id()), class_decl));
  1388. // Regardless of whether ClassDecl is a complete type, we first need an
  1389. // incomplete type so that any references have something to point at.
  1390. class_decl.class_id = context.local_classes().Add(
  1391. {GetIncompleteLocalEntityBase(context, class_decl_id, import_class),
  1392. {.self_type_id = SemIR::TypeId::Invalid,
  1393. .inheritance_kind = import_class.inheritance_kind,
  1394. .is_dynamic = import_class.is_dynamic}});
  1395. if (import_class.has_parameters()) {
  1396. class_decl.type_id = context.local_context().GetGenericClassType(
  1397. class_decl.class_id, enclosing_specific_id);
  1398. }
  1399. // Write the class ID into the ClassDecl.
  1400. context.local_context().ReplaceInstBeforeConstantUse(class_decl_id,
  1401. class_decl);
  1402. auto self_const_id = context.local_constant_values().Get(class_decl_id);
  1403. return {class_decl.class_id, self_const_id};
  1404. }
  1405. // Fills out the class definition for an incomplete class.
  1406. static auto AddClassDefinition(ImportContext& context,
  1407. const SemIR::Class& import_class,
  1408. SemIR::Class& new_class,
  1409. SemIR::InstId complete_type_witness_id,
  1410. SemIR::InstId base_id, SemIR::InstId adapt_id,
  1411. SemIR::InstId vtable_id) -> void {
  1412. new_class.definition_id = new_class.first_owning_decl_id;
  1413. new_class.complete_type_witness_id = complete_type_witness_id;
  1414. new_class.scope_id = context.local_name_scopes().Add(
  1415. new_class.first_owning_decl_id, SemIR::NameId::Invalid,
  1416. new_class.parent_scope_id);
  1417. auto& new_scope = context.local_name_scopes().Get(new_class.scope_id);
  1418. const auto& import_scope =
  1419. context.import_name_scopes().Get(import_class.scope_id);
  1420. // Push a block so that we can add scoped instructions to it.
  1421. context.local_context().inst_block_stack().Push();
  1422. AddNameScopeImportRefs(context, import_scope, new_scope);
  1423. new_class.body_block_id = context.local_context().inst_block_stack().Pop();
  1424. if (import_class.base_id.is_valid()) {
  1425. new_class.base_id = base_id;
  1426. }
  1427. if (import_class.adapt_id.is_valid()) {
  1428. new_class.adapt_id = adapt_id;
  1429. }
  1430. if (import_class.vtable_id.is_valid()) {
  1431. new_class.vtable_id = vtable_id;
  1432. }
  1433. }
  1434. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1435. SemIR::ClassDecl inst,
  1436. SemIR::ConstantId class_const_id)
  1437. -> ResolveResult {
  1438. // TODO: The handling of interfaces repeats a lot with the handling of
  1439. // classes, and will likely also be repeated for named constraints and
  1440. // choice types. Factor out some of this functionality.
  1441. const auto& import_class = resolver.import_classes().Get(inst.class_id);
  1442. SemIR::ClassId class_id = SemIR::ClassId::Invalid;
  1443. if (!class_const_id.is_valid()) {
  1444. auto import_specific_id = SemIR::SpecificId::Invalid;
  1445. if (auto import_generic_class_type =
  1446. resolver.import_types().TryGetAs<SemIR::GenericClassType>(
  1447. inst.type_id)) {
  1448. import_specific_id = import_generic_class_type->enclosing_specific_id;
  1449. }
  1450. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1451. if (resolver.HasNewWork()) {
  1452. // This is the end of the first phase. Don't make a new class yet if
  1453. // we already have new work.
  1454. return ResolveResult::Retry();
  1455. }
  1456. // On the second phase, create a forward declaration of the class for any
  1457. // recursive references.
  1458. auto enclosing_specific_id =
  1459. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1460. std::tie(class_id, class_const_id) =
  1461. MakeIncompleteClass(resolver, import_class, enclosing_specific_id);
  1462. } else {
  1463. // On the third phase, compute the class ID from the constant
  1464. // value of the declaration.
  1465. auto class_const_inst = resolver.local_insts().Get(
  1466. resolver.local_constant_values().GetInstId(class_const_id));
  1467. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  1468. class_id = class_type->class_id;
  1469. } else {
  1470. auto generic_class_type =
  1471. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1472. class_const_inst.type_id());
  1473. class_id = generic_class_type.class_id;
  1474. }
  1475. }
  1476. // Load constants for the definition.
  1477. auto parent_scope_id =
  1478. GetLocalNameScopeId(resolver, import_class.parent_scope_id);
  1479. LoadLocalPatternConstantIds(resolver,
  1480. import_class.implicit_param_patterns_id);
  1481. LoadLocalPatternConstantIds(resolver, import_class.param_patterns_id);
  1482. auto generic_data = GetLocalGenericData(resolver, import_class.generic_id);
  1483. auto self_const_id = GetLocalConstantId(resolver, import_class.self_type_id);
  1484. auto complete_type_witness_const_id =
  1485. import_class.complete_type_witness_id.is_valid()
  1486. ? GetLocalConstantId(resolver, import_class.complete_type_witness_id)
  1487. : SemIR::ConstantId::Invalid;
  1488. auto base_id = import_class.base_id.is_valid()
  1489. ? GetLocalConstantInstId(resolver, import_class.base_id)
  1490. : SemIR::InstId::Invalid;
  1491. auto adapt_id = import_class.adapt_id.is_valid()
  1492. ? GetLocalConstantInstId(resolver, import_class.adapt_id)
  1493. : SemIR::InstId::Invalid;
  1494. auto& new_class = resolver.local_classes().Get(class_id);
  1495. if (resolver.HasNewWork()) {
  1496. return ResolveResult::Retry(class_const_id, new_class.first_decl_id());
  1497. }
  1498. auto vtable_id = import_class.vtable_id.is_valid()
  1499. ? AddImportRef(resolver, import_class.vtable_id)
  1500. : SemIR::InstId::Invalid;
  1501. new_class.parent_scope_id = parent_scope_id;
  1502. new_class.implicit_param_patterns_id = GetLocalParamPatternsId(
  1503. resolver, import_class.implicit_param_patterns_id);
  1504. new_class.param_patterns_id =
  1505. GetLocalParamPatternsId(resolver, import_class.param_patterns_id);
  1506. SetGenericData(resolver, import_class.generic_id, new_class.generic_id,
  1507. generic_data);
  1508. new_class.self_type_id =
  1509. resolver.local_context().GetTypeIdForTypeConstant(self_const_id);
  1510. if (import_class.is_defined()) {
  1511. auto complete_type_witness_id = AddLoadedImportRef(
  1512. resolver,
  1513. resolver.local_context().GetSingletonType(
  1514. SemIR::WitnessType::SingletonInstId),
  1515. import_class.complete_type_witness_id, complete_type_witness_const_id);
  1516. AddClassDefinition(resolver, import_class, new_class,
  1517. complete_type_witness_id, base_id, adapt_id, vtable_id);
  1518. }
  1519. return ResolveResult::Done(class_const_id, new_class.first_decl_id());
  1520. }
  1521. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1522. SemIR::ClassType inst) -> ResolveResult {
  1523. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1524. auto class_const_id = GetLocalConstantId(
  1525. resolver,
  1526. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  1527. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  1528. if (resolver.HasNewWork()) {
  1529. return ResolveResult::Retry();
  1530. }
  1531. // Find the corresponding class type. For a non-generic class, this is the
  1532. // type of the class declaration. For a generic class, build a class type
  1533. // referencing this specialization of the generic class.
  1534. auto class_const_inst = resolver.local_insts().Get(
  1535. resolver.local_constant_values().GetInstId(class_const_id));
  1536. if (class_const_inst.Is<SemIR::ClassType>()) {
  1537. return ResolveResult::Done(class_const_id);
  1538. } else {
  1539. auto generic_class_type =
  1540. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1541. class_const_inst.type_id());
  1542. auto specific_id =
  1543. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  1544. return ResolveAs<SemIR::ClassType>(
  1545. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  1546. .class_id = generic_class_type.class_id,
  1547. .specific_id = specific_id});
  1548. }
  1549. }
  1550. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1551. SemIR::CompleteTypeWitness inst)
  1552. -> ResolveResult {
  1553. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  1554. SemIR::WitnessType::SingletonInstId);
  1555. auto object_repr_const_id = GetLocalConstantId(resolver, inst.object_repr_id);
  1556. if (resolver.HasNewWork()) {
  1557. return ResolveResult::Retry();
  1558. }
  1559. auto object_repr_id =
  1560. resolver.local_context().GetTypeIdForTypeConstant(object_repr_const_id);
  1561. return ResolveAs<SemIR::CompleteTypeWitness>(
  1562. resolver, {.type_id = resolver.local_context().GetSingletonType(
  1563. SemIR::WitnessType::SingletonInstId),
  1564. .object_repr_id = object_repr_id});
  1565. }
  1566. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1567. SemIR::ConstType inst) -> ResolveResult {
  1568. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1569. auto inner_const_id = GetLocalConstantId(resolver, inst.inner_id);
  1570. if (resolver.HasNewWork()) {
  1571. return ResolveResult::Retry();
  1572. }
  1573. auto inner_type_id =
  1574. resolver.local_context().GetTypeIdForTypeConstant(inner_const_id);
  1575. return ResolveAs<SemIR::ConstType>(
  1576. resolver,
  1577. {.type_id = SemIR::TypeType::SingletonTypeId, .inner_id = inner_type_id});
  1578. }
  1579. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1580. SemIR::ExportDecl inst) -> ResolveResult {
  1581. auto value_id = GetLocalConstantId(resolver, inst.value_id);
  1582. return RetryOrDone(resolver, value_id);
  1583. }
  1584. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1585. SemIR::FieldDecl inst,
  1586. SemIR::InstId import_inst_id) -> ResolveResult {
  1587. auto const_id = GetLocalConstantId(resolver, inst.type_id);
  1588. if (resolver.HasNewWork()) {
  1589. return ResolveResult::Retry();
  1590. }
  1591. auto inst_id = resolver.local_context().AddInstInNoBlock(
  1592. resolver.local_context().MakeImportedLocAndInst<SemIR::FieldDecl>(
  1593. AddImportIRInst(resolver, import_inst_id),
  1594. {.type_id =
  1595. resolver.local_context().GetTypeIdForTypeConstant(const_id),
  1596. .name_id = GetLocalNameId(resolver, inst.name_id),
  1597. .index = inst.index}));
  1598. return ResolveResult::Done(resolver.local_constant_values().Get(inst_id),
  1599. inst_id);
  1600. }
  1601. // Make a declaration of a function. This is done as a separate step from
  1602. // importing the function declaration in order to resolve cycles.
  1603. static auto MakeFunctionDecl(ImportContext& context,
  1604. const SemIR::Function& import_function,
  1605. SemIR::SpecificId specific_id)
  1606. -> std::pair<SemIR::FunctionId, SemIR::ConstantId> {
  1607. SemIR::FunctionDecl function_decl = {
  1608. .type_id = SemIR::TypeId::Invalid,
  1609. .function_id = SemIR::FunctionId::Invalid,
  1610. .decl_block_id = SemIR::InstBlockId::Empty};
  1611. auto function_decl_id = context.local_context().AddPlaceholderInstInNoBlock(
  1612. context.local_context().MakeImportedLocAndInst(
  1613. AddImportIRInst(context, import_function.first_decl_id()),
  1614. function_decl));
  1615. // Start with an incomplete function.
  1616. function_decl.function_id = context.local_functions().Add(
  1617. {GetIncompleteLocalEntityBase(context, function_decl_id, import_function),
  1618. {.return_slot_pattern_id = SemIR::InstId::Invalid,
  1619. .builtin_function_kind = import_function.builtin_function_kind}});
  1620. function_decl.type_id = context.local_context().GetFunctionType(
  1621. function_decl.function_id, specific_id);
  1622. // Write the function ID and type into the FunctionDecl.
  1623. context.local_context().ReplaceInstBeforeConstantUse(function_decl_id,
  1624. function_decl);
  1625. return {function_decl.function_id,
  1626. context.local_constant_values().Get(function_decl_id)};
  1627. }
  1628. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1629. SemIR::FunctionDecl inst,
  1630. SemIR::ConstantId function_const_id)
  1631. -> ResolveResult {
  1632. const auto& import_function =
  1633. resolver.import_functions().Get(inst.function_id);
  1634. SemIR::FunctionId function_id = SemIR::FunctionId::Invalid;
  1635. if (!function_const_id.is_valid()) {
  1636. auto import_specific_id = resolver.import_types()
  1637. .GetAs<SemIR::FunctionType>(inst.type_id)
  1638. .specific_id;
  1639. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1640. if (resolver.HasNewWork()) {
  1641. // This is the end of the first phase. Don't make a new function yet if
  1642. // we already have new work.
  1643. return ResolveResult::Retry();
  1644. }
  1645. // On the second phase, create a forward declaration of the interface.
  1646. auto specific_id =
  1647. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1648. std::tie(function_id, function_const_id) =
  1649. MakeFunctionDecl(resolver, import_function, specific_id);
  1650. } else {
  1651. // On the third phase, compute the function ID from the constant value of
  1652. // the declaration.
  1653. auto function_const_inst = resolver.local_insts().Get(
  1654. resolver.local_constant_values().GetInstId(function_const_id));
  1655. auto function_type = resolver.local_types().GetAs<SemIR::FunctionType>(
  1656. function_const_inst.type_id());
  1657. function_id = function_type.function_id;
  1658. }
  1659. auto return_type_const_id = SemIR::ConstantId::Invalid;
  1660. if (import_function.return_slot_pattern_id.is_valid()) {
  1661. return_type_const_id = GetLocalConstantId(
  1662. resolver, resolver.import_insts()
  1663. .Get(import_function.return_slot_pattern_id)
  1664. .type_id());
  1665. }
  1666. auto parent_scope_id =
  1667. GetLocalNameScopeId(resolver, import_function.parent_scope_id);
  1668. LoadLocalPatternConstantIds(resolver,
  1669. import_function.implicit_param_patterns_id);
  1670. LoadLocalPatternConstantIds(resolver, import_function.param_patterns_id);
  1671. auto generic_data = GetLocalGenericData(resolver, import_function.generic_id);
  1672. auto& new_function = resolver.local_functions().Get(function_id);
  1673. if (resolver.HasNewWork()) {
  1674. return ResolveResult::Retry(function_const_id,
  1675. new_function.first_decl_id());
  1676. }
  1677. // Add the function declaration.
  1678. new_function.parent_scope_id = parent_scope_id;
  1679. new_function.implicit_param_patterns_id = GetLocalParamPatternsId(
  1680. resolver, import_function.implicit_param_patterns_id);
  1681. new_function.param_patterns_id =
  1682. GetLocalParamPatternsId(resolver, import_function.param_patterns_id);
  1683. new_function.return_slot_pattern_id = GetLocalReturnSlotPatternId(
  1684. resolver, import_function.return_slot_pattern_id);
  1685. SetGenericData(resolver, import_function.generic_id, new_function.generic_id,
  1686. generic_data);
  1687. if (import_function.definition_id.is_valid()) {
  1688. new_function.definition_id = new_function.first_owning_decl_id;
  1689. }
  1690. return ResolveResult::Done(function_const_id, new_function.first_decl_id());
  1691. }
  1692. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1693. SemIR::FunctionType inst) -> ResolveResult {
  1694. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1695. auto fn_val_id = GetLocalConstantInstId(
  1696. resolver,
  1697. resolver.import_functions().Get(inst.function_id).first_decl_id());
  1698. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  1699. if (resolver.HasNewWork()) {
  1700. return ResolveResult::Retry();
  1701. }
  1702. auto fn_type_id = resolver.local_insts().Get(fn_val_id).type_id();
  1703. return ResolveAs<SemIR::FunctionType>(
  1704. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  1705. .function_id = resolver.local_types()
  1706. .GetAs<SemIR::FunctionType>(fn_type_id)
  1707. .function_id,
  1708. .specific_id = GetOrAddLocalSpecific(
  1709. resolver, inst.specific_id, specific_data)});
  1710. }
  1711. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1712. SemIR::GenericClassType inst) -> ResolveResult {
  1713. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1714. auto class_val_id = GetLocalConstantInstId(
  1715. resolver,
  1716. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  1717. if (resolver.HasNewWork()) {
  1718. return ResolveResult::Retry();
  1719. }
  1720. auto class_val = resolver.local_insts().Get(class_val_id);
  1721. CARBON_CHECK(
  1722. resolver.local_types().Is<SemIR::GenericClassType>(class_val.type_id()));
  1723. return ResolveResult::Done(
  1724. resolver.local_types().GetConstantId(class_val.type_id()));
  1725. }
  1726. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1727. SemIR::GenericInterfaceType inst)
  1728. -> ResolveResult {
  1729. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1730. auto interface_val_id = GetLocalConstantInstId(
  1731. resolver,
  1732. resolver.import_interfaces().Get(inst.interface_id).first_owning_decl_id);
  1733. if (resolver.HasNewWork()) {
  1734. return ResolveResult::Retry();
  1735. }
  1736. auto interface_val = resolver.local_insts().Get(interface_val_id);
  1737. CARBON_CHECK(resolver.local_types().Is<SemIR::GenericInterfaceType>(
  1738. interface_val.type_id()));
  1739. return ResolveResult::Done(
  1740. resolver.local_types().GetConstantId(interface_val.type_id()));
  1741. }
  1742. // Make a declaration of an impl. This is done as a separate step from
  1743. // importing the impl definition in order to resolve cycles.
  1744. static auto MakeImplDeclaration(ImportContext& context,
  1745. const SemIR::Impl& import_impl,
  1746. SemIR::InstId witness_id)
  1747. -> std::pair<SemIR::ImplId, SemIR::ConstantId> {
  1748. SemIR::ImplDecl impl_decl = {.impl_id = SemIR::ImplId::Invalid,
  1749. .decl_block_id = SemIR::InstBlockId::Empty};
  1750. auto impl_decl_id = context.local_context().AddPlaceholderInstInNoBlock(
  1751. context.local_context().MakeImportedLocAndInst(
  1752. AddImportIRInst(context, import_impl.latest_decl_id()), impl_decl));
  1753. impl_decl.impl_id = context.local_impls().Add(
  1754. {GetIncompleteLocalEntityBase(context, impl_decl_id, import_impl),
  1755. {.self_id = SemIR::InstId::Invalid,
  1756. .constraint_id = SemIR::InstId::Invalid,
  1757. .witness_id = witness_id}});
  1758. // Write the impl ID into the ImplDecl.
  1759. context.local_context().ReplaceInstBeforeConstantUse(impl_decl_id, impl_decl);
  1760. return {impl_decl.impl_id, context.local_constant_values().Get(impl_decl_id)};
  1761. }
  1762. // Imports the definition of an impl.
  1763. static auto AddImplDefinition(ImportContext& context,
  1764. const SemIR::Impl& import_impl,
  1765. SemIR::Impl& new_impl) -> void {
  1766. new_impl.definition_id = new_impl.first_owning_decl_id;
  1767. new_impl.defined = true;
  1768. if (import_impl.scope_id.is_valid()) {
  1769. new_impl.scope_id = context.local_name_scopes().Add(
  1770. new_impl.first_owning_decl_id, SemIR::NameId::Invalid,
  1771. new_impl.parent_scope_id);
  1772. // Import the contents of the definition scope, if we might need it. Name
  1773. // lookup is never performed into this scope by a user of the impl, so
  1774. // this is only necessary in the same library that defined the impl, in
  1775. // order to support defining members of the impl out of line in the impl
  1776. // file when the impl is defined in the API file.
  1777. // TODO: Check to see if this impl is owned by the API file, rather than
  1778. // merely being imported into it.
  1779. if (context.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  1780. auto& new_scope = context.local_name_scopes().Get(new_impl.scope_id);
  1781. const auto& import_scope =
  1782. context.import_name_scopes().Get(import_impl.scope_id);
  1783. // Push a block so that we can add scoped instructions to it.
  1784. context.local_context().inst_block_stack().Push();
  1785. AddNameScopeImportRefs(context, import_scope, new_scope);
  1786. new_impl.body_block_id = context.local_context().inst_block_stack().Pop();
  1787. }
  1788. }
  1789. }
  1790. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1791. SemIR::ImplDecl inst,
  1792. SemIR::ConstantId impl_const_id)
  1793. -> ResolveResult {
  1794. // TODO: This duplicates a lot of the handling of interfaces, classes, and
  1795. // functions. Factor out the commonality.
  1796. const auto& import_impl = resolver.import_impls().Get(inst.impl_id);
  1797. SemIR::ImplId impl_id = SemIR::ImplId::Invalid;
  1798. if (!impl_const_id.is_valid()) {
  1799. if (resolver.HasNewWork()) {
  1800. // This is the end of the first phase. Don't make a new impl yet if we
  1801. // already have new work.
  1802. return ResolveResult::Retry();
  1803. }
  1804. // On the second phase, create a forward declaration of the impl for any
  1805. // recursive references.
  1806. auto witness_id = AddImportRef(resolver, import_impl.witness_id);
  1807. std::tie(impl_id, impl_const_id) =
  1808. MakeImplDeclaration(resolver, import_impl, witness_id);
  1809. } else {
  1810. // On the third phase, compute the impl ID from the "constant value" of
  1811. // the declaration, which is a reference to the created ImplDecl.
  1812. auto impl_const_inst = resolver.local_insts().GetAs<SemIR::ImplDecl>(
  1813. resolver.local_constant_values().GetInstId(impl_const_id));
  1814. impl_id = impl_const_inst.impl_id;
  1815. }
  1816. // Load constants for the definition.
  1817. auto parent_scope_id =
  1818. GetLocalNameScopeId(resolver, import_impl.parent_scope_id);
  1819. LoadLocalPatternConstantIds(resolver, import_impl.implicit_param_patterns_id);
  1820. auto generic_data = GetLocalGenericData(resolver, import_impl.generic_id);
  1821. auto self_const_id = GetLocalConstantId(
  1822. resolver, resolver.import_constant_values().Get(import_impl.self_id));
  1823. auto constraint_const_id = GetLocalConstantId(
  1824. resolver,
  1825. resolver.import_constant_values().Get(import_impl.constraint_id));
  1826. auto& new_impl = resolver.local_impls().Get(impl_id);
  1827. if (resolver.HasNewWork()) {
  1828. return ResolveResult::Retry(impl_const_id, new_impl.first_decl_id());
  1829. }
  1830. new_impl.parent_scope_id = parent_scope_id;
  1831. new_impl.implicit_param_patterns_id =
  1832. GetLocalParamPatternsId(resolver, import_impl.implicit_param_patterns_id);
  1833. SetGenericData(resolver, import_impl.generic_id, new_impl.generic_id,
  1834. generic_data);
  1835. // Create instructions for self and constraint to hold the symbolic constant
  1836. // value for a generic impl.
  1837. new_impl.self_id =
  1838. AddLoadedImportRef(resolver, SemIR::TypeType::SingletonTypeId,
  1839. import_impl.self_id, self_const_id);
  1840. new_impl.constraint_id =
  1841. AddLoadedImportRef(resolver, SemIR::TypeType::SingletonTypeId,
  1842. import_impl.constraint_id, constraint_const_id);
  1843. if (import_impl.is_defined()) {
  1844. AddImplDefinition(resolver, import_impl, new_impl);
  1845. }
  1846. // If the `impl` is declared in the API file corresponding to the current
  1847. // file, add this to impl lookup so that it can be found by redeclarations
  1848. // in the current file.
  1849. if (resolver.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  1850. resolver.local_impls().GetOrAddLookupBucket(new_impl).push_back(impl_id);
  1851. }
  1852. return ResolveResult::Done(impl_const_id, new_impl.first_decl_id());
  1853. }
  1854. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1855. SemIR::ImportRefLoaded /*inst*/,
  1856. SemIR::InstId inst_id) -> ResolveResult {
  1857. // Return the constant for the instruction of the imported constant.
  1858. auto constant_id = resolver.import_constant_values().Get(inst_id);
  1859. if (!constant_id.is_valid()) {
  1860. return ResolveResult::Done(SemIR::ErrorInst::SingletonConstantId);
  1861. }
  1862. if (!constant_id.is_constant()) {
  1863. resolver.local_context().TODO(
  1864. inst_id, "Non-constant ImportRefLoaded (comes up with var)");
  1865. return ResolveResult::Done(SemIR::ErrorInst::SingletonConstantId);
  1866. }
  1867. auto new_constant_id = GetLocalConstantId(
  1868. resolver, resolver.import_constant_values().GetInstId(constant_id));
  1869. return RetryOrDone(resolver, new_constant_id);
  1870. }
  1871. // Make a declaration of an interface. This is done as a separate step from
  1872. // importing the interface definition in order to resolve cycles.
  1873. static auto MakeInterfaceDecl(ImportContext& context,
  1874. const SemIR::Interface& import_interface,
  1875. SemIR::SpecificId enclosing_specific_id)
  1876. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  1877. SemIR::InterfaceDecl interface_decl = {
  1878. .type_id = SemIR::TypeType::SingletonTypeId,
  1879. .interface_id = SemIR::InterfaceId::Invalid,
  1880. .decl_block_id = SemIR::InstBlockId::Empty};
  1881. auto interface_decl_id = context.local_context().AddPlaceholderInstInNoBlock(
  1882. context.local_context().MakeImportedLocAndInst(
  1883. AddImportIRInst(context, import_interface.first_owning_decl_id),
  1884. interface_decl));
  1885. // Start with an incomplete interface.
  1886. interface_decl.interface_id = context.local_interfaces().Add(
  1887. {GetIncompleteLocalEntityBase(context, interface_decl_id,
  1888. import_interface),
  1889. {}});
  1890. if (import_interface.has_parameters()) {
  1891. interface_decl.type_id = context.local_context().GetGenericInterfaceType(
  1892. interface_decl.interface_id, enclosing_specific_id);
  1893. }
  1894. // Write the interface ID into the InterfaceDecl.
  1895. context.local_context().ReplaceInstBeforeConstantUse(interface_decl_id,
  1896. interface_decl);
  1897. return {interface_decl.interface_id,
  1898. context.local_constant_values().Get(interface_decl_id)};
  1899. }
  1900. // Imports the definition for an interface that has been imported as a forward
  1901. // declaration.
  1902. static auto AddInterfaceDefinition(ImportContext& context,
  1903. const SemIR::Interface& import_interface,
  1904. SemIR::Interface& new_interface,
  1905. SemIR::InstId self_param_id) -> void {
  1906. new_interface.scope_id = context.local_name_scopes().Add(
  1907. new_interface.first_owning_decl_id, SemIR::NameId::Invalid,
  1908. new_interface.parent_scope_id);
  1909. auto& new_scope = context.local_name_scopes().Get(new_interface.scope_id);
  1910. const auto& import_scope =
  1911. context.import_name_scopes().Get(import_interface.scope_id);
  1912. // Push a block so that we can add scoped instructions to it.
  1913. context.local_context().inst_block_stack().Push();
  1914. AddNameScopeImportRefs(context, import_scope, new_scope);
  1915. new_interface.associated_entities_id = AddAssociatedEntities(
  1916. context, new_interface.scope_id, import_interface.associated_entities_id);
  1917. new_interface.body_block_id =
  1918. context.local_context().inst_block_stack().Pop();
  1919. new_interface.self_param_id = self_param_id;
  1920. CARBON_CHECK(import_scope.extended_scopes().empty(),
  1921. "Interfaces don't currently have extended scopes to support.");
  1922. }
  1923. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1924. SemIR::InterfaceDecl inst,
  1925. SemIR::ConstantId interface_const_id)
  1926. -> ResolveResult {
  1927. const auto& import_interface =
  1928. resolver.import_interfaces().Get(inst.interface_id);
  1929. SemIR::InterfaceId interface_id = SemIR::InterfaceId::Invalid;
  1930. if (!interface_const_id.is_valid()) {
  1931. auto import_specific_id = SemIR::SpecificId::Invalid;
  1932. if (auto import_generic_interface_type =
  1933. resolver.import_types().TryGetAs<SemIR::GenericInterfaceType>(
  1934. inst.type_id)) {
  1935. import_specific_id = import_generic_interface_type->enclosing_specific_id;
  1936. }
  1937. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1938. if (resolver.HasNewWork()) {
  1939. // This is the end of the first phase. Don't make a new interface yet if
  1940. // we already have new work.
  1941. return ResolveResult::Retry();
  1942. }
  1943. // On the second phase, create a forward declaration of the interface.
  1944. auto enclosing_specific_id =
  1945. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1946. std::tie(interface_id, interface_const_id) =
  1947. MakeInterfaceDecl(resolver, import_interface, enclosing_specific_id);
  1948. } else {
  1949. // On the third phase, compute the interface ID from the constant value of
  1950. // the declaration.
  1951. auto interface_const_inst = resolver.local_insts().Get(
  1952. resolver.local_constant_values().GetInstId(interface_const_id));
  1953. if (auto facet_type = interface_const_inst.TryAs<SemIR::FacetType>()) {
  1954. const SemIR::FacetTypeInfo& facet_type_info =
  1955. resolver.local_facet_types().Get(facet_type->facet_type_id);
  1956. auto interface_type = facet_type_info.TryAsSingleInterface();
  1957. CARBON_CHECK(interface_type);
  1958. interface_id = interface_type->interface_id;
  1959. } else {
  1960. auto generic_interface_type =
  1961. resolver.local_types().GetAs<SemIR::GenericInterfaceType>(
  1962. interface_const_inst.type_id());
  1963. interface_id = generic_interface_type.interface_id;
  1964. }
  1965. }
  1966. auto parent_scope_id =
  1967. GetLocalNameScopeId(resolver, import_interface.parent_scope_id);
  1968. LoadLocalPatternConstantIds(resolver,
  1969. import_interface.implicit_param_patterns_id);
  1970. LoadLocalPatternConstantIds(resolver, import_interface.param_patterns_id);
  1971. auto generic_data =
  1972. GetLocalGenericData(resolver, import_interface.generic_id);
  1973. std::optional<SemIR::InstId> self_param_id;
  1974. if (import_interface.is_defined()) {
  1975. self_param_id =
  1976. GetLocalConstantInstId(resolver, import_interface.self_param_id);
  1977. }
  1978. auto& new_interface = resolver.local_interfaces().Get(interface_id);
  1979. if (resolver.HasNewWork()) {
  1980. return ResolveResult::Retry(interface_const_id,
  1981. new_interface.first_decl_id());
  1982. }
  1983. new_interface.parent_scope_id = parent_scope_id;
  1984. new_interface.implicit_param_patterns_id = GetLocalParamPatternsId(
  1985. resolver, import_interface.implicit_param_patterns_id);
  1986. new_interface.param_patterns_id =
  1987. GetLocalParamPatternsId(resolver, import_interface.param_patterns_id);
  1988. SetGenericData(resolver, import_interface.generic_id,
  1989. new_interface.generic_id, generic_data);
  1990. if (import_interface.is_defined()) {
  1991. CARBON_CHECK(self_param_id);
  1992. AddInterfaceDefinition(resolver, import_interface, new_interface,
  1993. *self_param_id);
  1994. }
  1995. return ResolveResult::Done(interface_const_id, new_interface.first_decl_id());
  1996. }
  1997. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1998. SemIR::FacetAccessType inst) -> ResolveResult {
  1999. auto facet_value_inst_id =
  2000. GetLocalConstantInstId(resolver, inst.facet_value_inst_id);
  2001. if (resolver.HasNewWork()) {
  2002. return ResolveResult::Retry();
  2003. }
  2004. return ResolveAs<SemIR::FacetAccessType>(
  2005. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  2006. .facet_value_inst_id = facet_value_inst_id});
  2007. }
  2008. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2009. SemIR::FacetAccessWitness inst)
  2010. -> ResolveResult {
  2011. auto facet_value_inst_id =
  2012. GetLocalConstantInstId(resolver, inst.facet_value_inst_id);
  2013. if (resolver.HasNewWork()) {
  2014. return ResolveResult::Retry();
  2015. }
  2016. return ResolveAs<SemIR::FacetAccessWitness>(
  2017. resolver, {.type_id = resolver.local_context().GetSingletonType(
  2018. SemIR::WitnessType::SingletonInstId),
  2019. .facet_value_inst_id = facet_value_inst_id});
  2020. }
  2021. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2022. SemIR::FacetType inst) -> ResolveResult {
  2023. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2024. const SemIR::FacetTypeInfo& facet_type_info =
  2025. resolver.import_facet_types().Get(inst.facet_type_id);
  2026. for (auto interface : facet_type_info.impls_constraints) {
  2027. GetLocalConstantId(resolver, resolver.import_interfaces()
  2028. .Get(interface.interface_id)
  2029. .first_owning_decl_id);
  2030. GetLocalSpecificData(resolver, interface.specific_id);
  2031. }
  2032. for (auto rewrite : facet_type_info.rewrite_constraints) {
  2033. GetLocalConstantId(resolver, rewrite.lhs_const_id);
  2034. GetLocalConstantId(resolver, rewrite.rhs_const_id);
  2035. }
  2036. if (resolver.HasNewWork()) {
  2037. return ResolveResult::Retry();
  2038. }
  2039. llvm::SmallVector<SemIR::FacetTypeInfo::ImplsConstraint> impls_constraints;
  2040. for (auto interface : facet_type_info.impls_constraints) {
  2041. auto interface_const_id =
  2042. GetLocalConstantId(resolver, resolver.import_interfaces()
  2043. .Get(interface.interface_id)
  2044. .first_owning_decl_id);
  2045. auto specific_data = GetLocalSpecificData(resolver, interface.specific_id);
  2046. // Find the corresponding interface type. For a non-generic interface,
  2047. // this is the type of the interface declaration. For a generic interface,
  2048. // build a interface type referencing this specialization of the generic
  2049. // interface.
  2050. auto interface_const_inst = resolver.local_insts().Get(
  2051. resolver.local_constant_values().GetInstId(interface_const_id));
  2052. if (auto facet_type = interface_const_inst.TryAs<SemIR::FacetType>()) {
  2053. const SemIR::FacetTypeInfo& new_facet_type_info =
  2054. resolver.local_facet_types().Get(facet_type->facet_type_id);
  2055. impls_constraints.append(new_facet_type_info.impls_constraints);
  2056. } else {
  2057. auto generic_interface_type =
  2058. resolver.local_types().GetAs<SemIR::GenericInterfaceType>(
  2059. interface_const_inst.type_id());
  2060. auto specific_id =
  2061. GetOrAddLocalSpecific(resolver, interface.specific_id, specific_data);
  2062. impls_constraints.push_back(
  2063. {generic_interface_type.interface_id, specific_id});
  2064. }
  2065. }
  2066. llvm::SmallVector<SemIR::FacetTypeInfo::RewriteConstraint>
  2067. rewrite_constraints;
  2068. for (auto rewrite : facet_type_info.rewrite_constraints) {
  2069. rewrite_constraints.push_back(
  2070. {.lhs_const_id = GetLocalConstantId(resolver, rewrite.lhs_const_id),
  2071. .rhs_const_id = GetLocalConstantId(resolver, rewrite.rhs_const_id)});
  2072. }
  2073. // TODO: Also process the other requirements.
  2074. SemIR::FacetTypeId facet_type_id =
  2075. resolver.local_facet_types().Add(SemIR::FacetTypeInfo{
  2076. .impls_constraints = impls_constraints,
  2077. .rewrite_constraints = rewrite_constraints,
  2078. .other_requirements = facet_type_info.other_requirements});
  2079. return ResolveAs<SemIR::FacetType>(
  2080. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  2081. .facet_type_id = facet_type_id});
  2082. }
  2083. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2084. SemIR::FacetValue inst) -> ResolveResult {
  2085. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2086. auto type_inst_id = GetLocalConstantInstId(resolver, inst.type_inst_id);
  2087. auto witness_inst_id = GetLocalConstantInstId(resolver, inst.witness_inst_id);
  2088. if (resolver.HasNewWork()) {
  2089. return ResolveResult::Retry();
  2090. }
  2091. return ResolveAs<SemIR::FacetValue>(
  2092. resolver,
  2093. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  2094. .type_inst_id = type_inst_id,
  2095. .witness_inst_id = witness_inst_id});
  2096. }
  2097. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2098. SemIR::ImplWitness inst) -> ResolveResult {
  2099. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2100. if (resolver.HasNewWork()) {
  2101. return ResolveResult::Retry();
  2102. }
  2103. llvm::SmallVector<SemIR::InstId> elements;
  2104. auto import_elements = resolver.import_inst_blocks().Get(inst.elements_id);
  2105. elements.reserve(import_elements.size());
  2106. for (auto element : import_elements) {
  2107. elements.push_back(AddImportRef(resolver, element));
  2108. }
  2109. auto elements_id = resolver.local_inst_blocks().Add(elements);
  2110. auto specific_id =
  2111. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  2112. return ResolveAs<SemIR::ImplWitness>(
  2113. resolver, {.type_id = resolver.local_context().GetSingletonType(
  2114. SemIR::WitnessType::SingletonInstId),
  2115. .elements_id = elements_id,
  2116. .specific_id = specific_id});
  2117. }
  2118. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2119. SemIR::ImplWitnessAccess inst)
  2120. -> ResolveResult {
  2121. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2122. auto witness_id = GetLocalConstantInstId(resolver, inst.witness_id);
  2123. if (resolver.HasNewWork()) {
  2124. return ResolveResult::Retry();
  2125. }
  2126. return ResolveAs<SemIR::ImplWitnessAccess>(
  2127. resolver,
  2128. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  2129. .witness_id = witness_id,
  2130. .index = inst.index});
  2131. }
  2132. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2133. SemIR::IntValue inst) -> ResolveResult {
  2134. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2135. if (resolver.HasNewWork()) {
  2136. return ResolveResult::Retry();
  2137. }
  2138. // We can directly reuse the value IDs across file IRs. Otherwise, we need
  2139. // to add a new canonical int in this IR.
  2140. auto int_id = inst.int_id.is_value()
  2141. ? inst.int_id
  2142. : resolver.local_ints().AddSigned(
  2143. resolver.import_ints().Get(inst.int_id));
  2144. return ResolveAs<SemIR::IntValue>(
  2145. resolver,
  2146. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  2147. .int_id = int_id});
  2148. }
  2149. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2150. SemIR::IntType inst) -> ResolveResult {
  2151. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2152. auto bit_width_id = GetLocalConstantInstId(resolver, inst.bit_width_id);
  2153. if (resolver.HasNewWork()) {
  2154. return ResolveResult::Retry();
  2155. }
  2156. return ResolveAs<SemIR::IntType>(resolver,
  2157. {.type_id = SemIR::TypeType::SingletonTypeId,
  2158. .int_kind = inst.int_kind,
  2159. .bit_width_id = bit_width_id});
  2160. }
  2161. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2162. SemIR::Namespace inst,
  2163. SemIR::InstId import_inst_id) -> ResolveResult {
  2164. const auto& name_scope =
  2165. resolver.import_name_scopes().Get(inst.name_scope_id);
  2166. // A package from a different file becomes a child of the package here, as it
  2167. // would be if it were imported.
  2168. auto parent_scope_id =
  2169. inst.name_scope_id == SemIR::NameScopeId::Package
  2170. ? SemIR::NameScopeId::Package
  2171. : GetLocalNameScopeId(resolver, name_scope.parent_scope_id());
  2172. if (resolver.HasNewWork()) {
  2173. return ResolveResult::Retry();
  2174. }
  2175. auto namespace_type_id = resolver.local_context().GetSingletonType(
  2176. SemIR::NamespaceType::SingletonInstId);
  2177. auto namespace_decl =
  2178. SemIR::Namespace{.type_id = namespace_type_id,
  2179. .name_scope_id = SemIR::NameScopeId::Invalid,
  2180. .import_id = SemIR::AbsoluteInstId::Invalid};
  2181. auto inst_id = resolver.local_context().AddPlaceholderInstInNoBlock(
  2182. resolver.local_context().MakeImportedLocAndInst(
  2183. AddImportIRInst(resolver, import_inst_id), namespace_decl));
  2184. auto name_id = GetLocalNameId(resolver, name_scope.name_id());
  2185. namespace_decl.name_scope_id =
  2186. resolver.local_name_scopes().Add(inst_id, name_id, parent_scope_id);
  2187. // Namespaces from this package are eagerly imported, so anything we load here
  2188. // must be a closed import.
  2189. resolver.local_name_scopes()
  2190. .Get(namespace_decl.name_scope_id)
  2191. .set_is_closed_import(true);
  2192. resolver.local_context().ReplaceInstBeforeConstantUse(inst_id,
  2193. namespace_decl);
  2194. return {.const_id = resolver.local_constant_values().Get(inst_id)};
  2195. }
  2196. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2197. SemIR::PointerType inst) -> ResolveResult {
  2198. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2199. auto pointee_const_id = GetLocalConstantId(resolver, inst.pointee_id);
  2200. if (resolver.HasNewWork()) {
  2201. return ResolveResult::Retry();
  2202. }
  2203. auto pointee_type_id =
  2204. resolver.local_context().GetTypeIdForTypeConstant(pointee_const_id);
  2205. return ResolveAs<SemIR::PointerType>(
  2206. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  2207. .pointee_id = pointee_type_id});
  2208. }
  2209. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2210. SemIR::RequireCompleteType inst)
  2211. -> ResolveResult {
  2212. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  2213. SemIR::WitnessType::SingletonInstId);
  2214. auto complete_type_const_id =
  2215. GetLocalConstantId(resolver, inst.complete_type_id);
  2216. if (resolver.HasNewWork()) {
  2217. return ResolveResult::Retry();
  2218. }
  2219. auto complete_type_id =
  2220. resolver.local_context().GetTypeIdForTypeConstant(complete_type_const_id);
  2221. return ResolveAs<SemIR::RequireCompleteType>(
  2222. resolver, {.type_id = resolver.local_context().GetSingletonType(
  2223. SemIR::WitnessType::SingletonInstId),
  2224. .complete_type_id = complete_type_id});
  2225. }
  2226. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2227. SemIR::SpecificFunction inst) -> ResolveResult {
  2228. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  2229. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  2230. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2231. if (resolver.HasNewWork()) {
  2232. return ResolveResult::Retry();
  2233. }
  2234. auto type_id =
  2235. resolver.local_context().GetTypeIdForTypeConstant(type_const_id);
  2236. auto specific_id =
  2237. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  2238. return ResolveAs<SemIR::SpecificFunction>(
  2239. resolver,
  2240. {.type_id = type_id, .callee_id = callee_id, .specific_id = specific_id});
  2241. }
  2242. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2243. SemIR::StructType inst) -> ResolveResult {
  2244. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2245. auto orig_fields = resolver.import_struct_type_fields().Get(inst.fields_id);
  2246. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  2247. field_const_ids.reserve(orig_fields.size());
  2248. for (auto field : orig_fields) {
  2249. field_const_ids.push_back(GetLocalConstantId(resolver, field.type_id));
  2250. }
  2251. if (resolver.HasNewWork()) {
  2252. return ResolveResult::Retry();
  2253. }
  2254. // Prepare a vector of fields for GetStructType.
  2255. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  2256. new_fields.reserve(orig_fields.size());
  2257. for (auto [orig_field, field_const_id] :
  2258. llvm::zip(orig_fields, field_const_ids)) {
  2259. auto name_id = GetLocalNameId(resolver, orig_field.name_id);
  2260. auto field_type_id =
  2261. resolver.local_context().GetTypeIdForTypeConstant(field_const_id);
  2262. new_fields.push_back({.name_id = name_id, .type_id = field_type_id});
  2263. }
  2264. return ResolveAs<SemIR::StructType>(
  2265. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  2266. .fields_id = resolver.local_struct_type_fields().AddCanonical(
  2267. new_fields)});
  2268. }
  2269. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2270. SemIR::StructValue inst) -> ResolveResult {
  2271. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2272. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  2273. if (resolver.HasNewWork()) {
  2274. return ResolveResult::Retry();
  2275. }
  2276. return ResolveAs<SemIR::StructValue>(
  2277. resolver,
  2278. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  2279. .elements_id =
  2280. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  2281. }
  2282. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2283. SemIR::TupleType inst) -> ResolveResult {
  2284. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2285. auto orig_elem_type_ids = resolver.import_type_blocks().Get(inst.elements_id);
  2286. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  2287. elem_const_ids.reserve(orig_elem_type_ids.size());
  2288. for (auto elem_type_id : orig_elem_type_ids) {
  2289. elem_const_ids.push_back(GetLocalConstantId(resolver, elem_type_id));
  2290. }
  2291. if (resolver.HasNewWork()) {
  2292. return ResolveResult::Retry();
  2293. }
  2294. // Prepare a vector of the tuple types for GetTupleType.
  2295. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  2296. elem_type_ids.reserve(orig_elem_type_ids.size());
  2297. for (auto elem_const_id : elem_const_ids) {
  2298. elem_type_ids.push_back(
  2299. resolver.local_context().GetTypeIdForTypeConstant(elem_const_id));
  2300. }
  2301. return ResolveResult::Done(resolver.local_types().GetConstantId(
  2302. resolver.local_context().GetTupleType(elem_type_ids)));
  2303. }
  2304. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2305. SemIR::TupleValue inst) -> ResolveResult {
  2306. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2307. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  2308. if (resolver.HasNewWork()) {
  2309. return ResolveResult::Retry();
  2310. }
  2311. return ResolveAs<SemIR::TupleValue>(
  2312. resolver,
  2313. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  2314. .elements_id =
  2315. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  2316. }
  2317. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2318. SemIR::UnboundElementType inst)
  2319. -> ResolveResult {
  2320. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2321. auto class_const_id = GetLocalConstantId(resolver, inst.class_type_id);
  2322. auto elem_const_id = GetLocalConstantId(resolver, inst.element_type_id);
  2323. if (resolver.HasNewWork()) {
  2324. return ResolveResult::Retry();
  2325. }
  2326. return ResolveAs<SemIR::UnboundElementType>(
  2327. resolver,
  2328. {.type_id = SemIR::TypeType::SingletonTypeId,
  2329. .class_type_id =
  2330. resolver.local_context().GetTypeIdForTypeConstant(class_const_id),
  2331. .element_type_id =
  2332. resolver.local_context().GetTypeIdForTypeConstant(elem_const_id)});
  2333. }
  2334. // Tries to resolve the InstId, returning a canonical constant when ready, or
  2335. // Invalid if more has been added to the stack. This is the same as
  2336. // TryResolveInst, except that it may resolve symbolic constants as canonical
  2337. // constants instead of as constants associated with a particular generic.
  2338. //
  2339. // TODO: Consider refactoring the body to a helper in order to eliminate
  2340. // recursion.
  2341. // NOLINTNEXTLINE(misc-no-recursion)
  2342. static auto TryResolveInstCanonical(ImportRefResolver& resolver,
  2343. SemIR::InstId inst_id,
  2344. SemIR::ConstantId const_id)
  2345. -> ResolveResult {
  2346. if (SemIR::IsSingletonInstId(inst_id)) {
  2347. CARBON_CHECK(!const_id.is_valid());
  2348. // Constants for builtins can be directly copied.
  2349. return ResolveResult::Done(resolver.local_constant_values().Get(inst_id));
  2350. }
  2351. auto untyped_inst = resolver.import_insts().Get(inst_id);
  2352. CARBON_KIND_SWITCH(untyped_inst) {
  2353. case CARBON_KIND(SemIR::AdaptDecl inst): {
  2354. return TryResolveTypedInst(resolver, inst, inst_id);
  2355. }
  2356. case CARBON_KIND(SemIR::ArrayType inst): {
  2357. return TryResolveTypedInst(resolver, inst);
  2358. }
  2359. case CARBON_KIND(SemIR::AssociatedConstantDecl inst): {
  2360. return TryResolveTypedInst(resolver, inst, inst_id);
  2361. }
  2362. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  2363. return TryResolveTypedInst(resolver, inst);
  2364. }
  2365. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  2366. return TryResolveTypedInst(resolver, inst);
  2367. }
  2368. case CARBON_KIND(SemIR::BaseDecl inst): {
  2369. return TryResolveTypedInst(resolver, inst, inst_id);
  2370. }
  2371. case CARBON_KIND(SemIR::BindAlias inst): {
  2372. return TryResolveTypedInst(resolver, inst);
  2373. }
  2374. case SemIR::BindName::Kind: {
  2375. // TODO: Should we be resolving BindNames at all?
  2376. return ResolveResult::Done(SemIR::ConstantId::NotConstant);
  2377. }
  2378. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  2379. return TryResolveTypedInst(resolver, inst);
  2380. }
  2381. case CARBON_KIND(SemIR::BoundMethod inst): {
  2382. return TryResolveTypedInst(resolver, inst);
  2383. }
  2384. case CARBON_KIND(SemIR::Call inst): {
  2385. return TryResolveTypedInst(resolver, inst);
  2386. }
  2387. case CARBON_KIND(SemIR::ClassDecl inst): {
  2388. return TryResolveTypedInst(resolver, inst, const_id);
  2389. }
  2390. case CARBON_KIND(SemIR::ClassType inst): {
  2391. return TryResolveTypedInst(resolver, inst);
  2392. }
  2393. case CARBON_KIND(SemIR::CompleteTypeWitness inst): {
  2394. return TryResolveTypedInst(resolver, inst);
  2395. }
  2396. case CARBON_KIND(SemIR::ConstType inst): {
  2397. return TryResolveTypedInst(resolver, inst);
  2398. }
  2399. case CARBON_KIND(SemIR::ExportDecl inst): {
  2400. return TryResolveTypedInst(resolver, inst);
  2401. }
  2402. case CARBON_KIND(SemIR::FacetAccessType inst): {
  2403. return TryResolveTypedInst(resolver, inst);
  2404. }
  2405. case CARBON_KIND(SemIR::FacetAccessWitness inst): {
  2406. return TryResolveTypedInst(resolver, inst);
  2407. }
  2408. case CARBON_KIND(SemIR::FacetType inst): {
  2409. return TryResolveTypedInst(resolver, inst);
  2410. }
  2411. case CARBON_KIND(SemIR::FacetValue inst): {
  2412. return TryResolveTypedInst(resolver, inst);
  2413. }
  2414. case CARBON_KIND(SemIR::FieldDecl inst): {
  2415. return TryResolveTypedInst(resolver, inst, inst_id);
  2416. }
  2417. case CARBON_KIND(SemIR::FunctionDecl inst): {
  2418. return TryResolveTypedInst(resolver, inst, const_id);
  2419. }
  2420. case CARBON_KIND(SemIR::FunctionType inst): {
  2421. return TryResolveTypedInst(resolver, inst);
  2422. }
  2423. case CARBON_KIND(SemIR::GenericClassType inst): {
  2424. return TryResolveTypedInst(resolver, inst);
  2425. }
  2426. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  2427. return TryResolveTypedInst(resolver, inst);
  2428. }
  2429. case CARBON_KIND(SemIR::ImplDecl inst): {
  2430. return TryResolveTypedInst(resolver, inst, const_id);
  2431. }
  2432. case CARBON_KIND(SemIR::ImplWitness inst): {
  2433. return TryResolveTypedInst(resolver, inst);
  2434. }
  2435. case CARBON_KIND(SemIR::ImplWitnessAccess inst): {
  2436. return TryResolveTypedInst(resolver, inst);
  2437. }
  2438. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  2439. return TryResolveTypedInst(resolver, inst, inst_id);
  2440. }
  2441. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  2442. return TryResolveTypedInst(resolver, inst, const_id);
  2443. }
  2444. case CARBON_KIND(SemIR::IntValue inst): {
  2445. return TryResolveTypedInst(resolver, inst);
  2446. }
  2447. case CARBON_KIND(SemIR::IntType inst): {
  2448. return TryResolveTypedInst(resolver, inst);
  2449. }
  2450. case CARBON_KIND(SemIR::Namespace inst): {
  2451. return TryResolveTypedInst(resolver, inst, inst_id);
  2452. }
  2453. case CARBON_KIND(SemIR::PointerType inst): {
  2454. return TryResolveTypedInst(resolver, inst);
  2455. }
  2456. case CARBON_KIND(SemIR::RequireCompleteType inst): {
  2457. return TryResolveTypedInst(resolver, inst);
  2458. }
  2459. case CARBON_KIND(SemIR::SpecificFunction inst): {
  2460. return TryResolveTypedInst(resolver, inst);
  2461. }
  2462. case CARBON_KIND(SemIR::SymbolicBindingPattern inst): {
  2463. return TryResolveTypedInst(resolver, inst);
  2464. }
  2465. case CARBON_KIND(SemIR::StructType inst): {
  2466. return TryResolveTypedInst(resolver, inst);
  2467. }
  2468. case CARBON_KIND(SemIR::StructValue inst): {
  2469. return TryResolveTypedInst(resolver, inst);
  2470. }
  2471. case CARBON_KIND(SemIR::TupleType inst): {
  2472. return TryResolveTypedInst(resolver, inst);
  2473. }
  2474. case CARBON_KIND(SemIR::TupleValue inst): {
  2475. return TryResolveTypedInst(resolver, inst);
  2476. }
  2477. case CARBON_KIND(SemIR::UnboundElementType inst): {
  2478. return TryResolveTypedInst(resolver, inst);
  2479. }
  2480. case CARBON_KIND(SemIR::Vtable inst): {
  2481. return TryResolveTypedInst(resolver, inst, inst_id);
  2482. }
  2483. default: {
  2484. // This instruction might have a constant value of a different kind.
  2485. auto constant_inst_id =
  2486. resolver.import_constant_values().GetConstantInstId(inst_id);
  2487. if (constant_inst_id == inst_id) {
  2488. resolver.local_context().TODO(
  2489. SemIR::LocId(AddImportIRInst(resolver, inst_id)),
  2490. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  2491. return {.const_id = SemIR::ErrorInst::SingletonConstantId};
  2492. }
  2493. // Try to resolve the constant value instead. Note that this can only
  2494. // retry once.
  2495. CARBON_DCHECK(resolver.import_constant_values().GetConstantInstId(
  2496. constant_inst_id) == constant_inst_id,
  2497. "Constant value of constant instruction should refer to "
  2498. "the same instruction");
  2499. return TryResolveInstCanonical(resolver, constant_inst_id, const_id);
  2500. }
  2501. }
  2502. }
  2503. // Tries to resolve the InstId, returning a constant when ready, or Invalid if
  2504. // more has been added to the stack. A similar API is followed for all
  2505. // following TryResolveTypedInst helper functions.
  2506. //
  2507. // `const_id` is Invalid unless we've tried to resolve this instruction
  2508. // before, in which case it's the previous result.
  2509. //
  2510. // TODO: Error is returned when support is missing, but that should go away.
  2511. static auto TryResolveInst(ImportRefResolver& resolver, SemIR::InstId inst_id,
  2512. SemIR::ConstantId const_id) -> ResolveResult {
  2513. auto inst_const_id = resolver.import_constant_values().Get(inst_id);
  2514. if (!inst_const_id.is_valid() || !inst_const_id.is_symbolic()) {
  2515. return TryResolveInstCanonical(resolver, inst_id, const_id);
  2516. }
  2517. // Try to import the generic. This might add new work.
  2518. const auto& symbolic_const =
  2519. resolver.import_constant_values().GetSymbolicConstant(inst_const_id);
  2520. auto generic_const_id =
  2521. GetLocalConstantId(resolver, symbolic_const.generic_id);
  2522. auto inner_const_id = SemIR::ConstantId::Invalid;
  2523. if (const_id.is_valid()) {
  2524. // For the third phase, extract the constant value that
  2525. // TryResolveInstCanonical produced previously.
  2526. inner_const_id = resolver.local_constant_values().Get(
  2527. resolver.local_constant_values().GetSymbolicConstant(const_id).inst_id);
  2528. }
  2529. // Import the constant and rebuild the symbolic constant data.
  2530. auto result = TryResolveInstCanonical(resolver, inst_id, inner_const_id);
  2531. if (!result.const_id.is_valid()) {
  2532. // First phase: TryResolveInstCanoncial needs a retry.
  2533. return result;
  2534. }
  2535. if (!const_id.is_valid()) {
  2536. // Second phase: we have created an abstract constant. Create a
  2537. // corresponding generic constant.
  2538. if (symbolic_const.generic_id.is_valid()) {
  2539. result.const_id = resolver.local_constant_values().AddSymbolicConstant(
  2540. {.inst_id =
  2541. resolver.local_constant_values().GetInstId(result.const_id),
  2542. .generic_id = GetLocalGenericId(resolver, generic_const_id),
  2543. .index = symbolic_const.index});
  2544. if (result.decl_id.is_valid()) {
  2545. // Overwrite the abstract symbolic constant given initially to the
  2546. // declaration with its final concrete symbolic value.
  2547. resolver.local_constant_values().Set(result.decl_id, result.const_id);
  2548. }
  2549. }
  2550. } else {
  2551. // Third phase: perform a consistency check and produce the constant we
  2552. // created in the second phase.
  2553. CARBON_CHECK(result.const_id == inner_const_id,
  2554. "Constant value changed in third phase.");
  2555. result.const_id = const_id;
  2556. }
  2557. return result;
  2558. }
  2559. // Resolves and returns the local contents for an imported instruction block
  2560. // of constant instructions.
  2561. static auto ResolveLocalInstBlockContents(ImportRefResolver& resolver,
  2562. SemIR::InstBlockId import_block_id)
  2563. -> llvm::SmallVector<SemIR::InstId> {
  2564. auto import_block = resolver.import_inst_blocks().Get(import_block_id);
  2565. llvm::SmallVector<SemIR::InstId> inst_ids;
  2566. inst_ids.reserve(import_block.size());
  2567. for (auto import_inst_id : import_block) {
  2568. inst_ids.push_back(resolver.local_constant_values().GetInstId(
  2569. resolver.ResolveOneInst(import_inst_id)));
  2570. }
  2571. return inst_ids;
  2572. }
  2573. // Resolves and returns a local eval block for a region of an imported
  2574. // generic.
  2575. static auto ResolveLocalEvalBlock(ImportRefResolver& resolver,
  2576. const SemIR::Generic& import_generic,
  2577. SemIR::GenericId generic_id,
  2578. SemIR::GenericInstIndex::Region region)
  2579. -> SemIR::InstBlockId {
  2580. auto import_block_id = import_generic.GetEvalBlock(region);
  2581. if (!import_block_id.is_valid()) {
  2582. return SemIR::InstBlockId::Invalid;
  2583. }
  2584. auto inst_ids = ResolveLocalInstBlockContents(resolver, import_block_id);
  2585. return RebuildGenericEvalBlock(resolver.local_context(), generic_id, region,
  2586. inst_ids);
  2587. }
  2588. // Fills in the remaining information in a partially-imported generic.
  2589. static auto FinishPendingGeneric(ImportRefResolver& resolver,
  2590. ImportContext::PendingGeneric pending)
  2591. -> void {
  2592. const auto& import_generic =
  2593. resolver.import_generics().Get(pending.import_id);
  2594. // Don't store the local generic between calls: the generics list can be
  2595. // reallocated by ResolveLocalEvalBlock importing more specifics.
  2596. auto decl_block_id =
  2597. ResolveLocalEvalBlock(resolver, import_generic, pending.local_id,
  2598. SemIR::GenericInstIndex::Region::Declaration);
  2599. resolver.local_generics().Get(pending.local_id).decl_block_id = decl_block_id;
  2600. auto local_decl_id = resolver.local_generics().Get(pending.local_id).decl_id;
  2601. auto self_specific_id = MakeSelfSpecific(resolver.local_context(),
  2602. local_decl_id, pending.local_id);
  2603. resolver.local_generics().Get(pending.local_id).self_specific_id =
  2604. self_specific_id;
  2605. resolver.AddPendingSpecific({.import_id = import_generic.self_specific_id,
  2606. .local_id = self_specific_id});
  2607. auto definition_block_id =
  2608. ResolveLocalEvalBlock(resolver, import_generic, pending.local_id,
  2609. SemIR::GenericInstIndex::Region::Definition);
  2610. resolver.local_generics().Get(pending.local_id).definition_block_id =
  2611. definition_block_id;
  2612. }
  2613. // Resolves and returns a local inst block of constant instructions
  2614. // corresponding to an imported inst block.
  2615. static auto ResolveLocalInstBlock(ImportRefResolver& resolver,
  2616. SemIR::InstBlockId import_block_id)
  2617. -> SemIR::InstBlockId {
  2618. if (!import_block_id.is_valid()) {
  2619. return SemIR::InstBlockId::Invalid;
  2620. }
  2621. auto inst_ids = ResolveLocalInstBlockContents(resolver, import_block_id);
  2622. return resolver.local_inst_blocks().Add(inst_ids);
  2623. }
  2624. // Fills in the remaining information in a partially-imported specific.
  2625. static auto FinishPendingSpecific(ImportRefResolver& resolver,
  2626. ImportContext::PendingSpecific pending)
  2627. -> void {
  2628. const auto& import_specific =
  2629. resolver.import_specifics().Get(pending.import_id);
  2630. // Don't store the local specific between calls: the specifics list can be
  2631. // reallocated by ResolveLocalInstBlock importing more specifics.
  2632. if (!resolver.local_specifics()
  2633. .Get(pending.local_id)
  2634. .decl_block_id.is_valid()) {
  2635. auto decl_block_id =
  2636. ResolveLocalInstBlock(resolver, import_specific.decl_block_id);
  2637. resolver.local_specifics().Get(pending.local_id).decl_block_id =
  2638. decl_block_id;
  2639. }
  2640. if (!resolver.local_specifics()
  2641. .Get(pending.local_id)
  2642. .definition_block_id.is_valid() &&
  2643. import_specific.definition_block_id.is_valid()) {
  2644. auto definition_block_id =
  2645. ResolveLocalInstBlock(resolver, import_specific.definition_block_id);
  2646. resolver.local_specifics().Get(pending.local_id).definition_block_id =
  2647. definition_block_id;
  2648. }
  2649. }
  2650. // Perform any work that we deferred until the end of the main Resolve loop.
  2651. auto ImportRefResolver::PerformPendingWork() -> void {
  2652. // Note that the individual Finish steps can add new pending work, so keep
  2653. // going until we have no more work to do.
  2654. while (!pending_generics().empty() || !pending_specifics().empty()) {
  2655. // Process generics in the order that we added them because a later
  2656. // generic might refer to an earlier one, and the calls to
  2657. // RebuildGenericEvalBlock assume that the reachable SemIR is in a valid
  2658. // state.
  2659. // TODO: Import the generic eval block rather than calling
  2660. // RebuildGenericEvalBlock to rebuild it so that order doesn't matter.
  2661. // NOLINTNEXTLINE(modernize-loop-convert)
  2662. for (size_t i = 0; i != pending_generics().size(); ++i) {
  2663. FinishPendingGeneric(*this, pending_generics()[i]);
  2664. }
  2665. pending_generics().clear();
  2666. while (!pending_specifics().empty()) {
  2667. FinishPendingSpecific(*this, pending_specifics().pop_back_val());
  2668. }
  2669. }
  2670. }
  2671. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  2672. // loaded (including the one pointed at directly by the ImportRef), and the
  2673. // final instruction's type ID.
  2674. //
  2675. // This addresses cases where an ImportRefUnloaded may point at another
  2676. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  2677. // constant-evaluated version of the instruction to work with.
  2678. static auto GetInstForLoad(Context& context,
  2679. SemIR::ImportIRInstId import_ir_inst_id)
  2680. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  2681. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  2682. {}, SemIR::TypeId::Invalid};
  2683. auto& [import_ir_insts, type_id] = result;
  2684. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  2685. // The first ImportIRInst is added directly because the IR doesn't need to be
  2686. // localized.
  2687. import_ir_insts.push_back(import_ir_inst);
  2688. const auto* cursor_ir = context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  2689. while (true) {
  2690. auto cursor_inst = cursor_ir->insts().Get(import_ir_inst.inst_id);
  2691. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  2692. if (!import_ref) {
  2693. type_id = cursor_inst.type_id();
  2694. return result;
  2695. }
  2696. import_ir_inst =
  2697. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  2698. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  2699. import_ir_insts.push_back(
  2700. {.ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  2701. .is_export = false,
  2702. .sem_ir = cursor_ir}),
  2703. .inst_id = import_ir_inst.inst_id});
  2704. }
  2705. }
  2706. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  2707. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  2708. if (!inst) {
  2709. return;
  2710. }
  2711. auto [indirect_insts, load_type_id] =
  2712. GetInstForLoad(context, inst->import_ir_inst_id);
  2713. // The last indirect instruction is the one to resolve. Pop it here because
  2714. // Resolve will assign the constant.
  2715. auto load_ir_inst = indirect_insts.pop_back_val();
  2716. ImportRefResolver resolver(context, load_ir_inst.ir_id);
  2717. // The resolver calls into Context to create instructions. Don't register
  2718. // those instructions as part of the enclosing generic scope if they're
  2719. // dependent on a generic parameter.
  2720. context.generic_region_stack().Push();
  2721. auto type_id = resolver.ResolveType(load_type_id);
  2722. auto constant_id = resolver.Resolve(load_ir_inst.inst_id);
  2723. context.generic_region_stack().Pop();
  2724. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  2725. // doesn't use ReplaceInstBeforeConstantUse because it would trigger
  2726. // TryEvalInst, which we want to avoid with ImportRefs.
  2727. context.sem_ir().insts().Set(
  2728. inst_id,
  2729. SemIR::ImportRefLoaded{.type_id = type_id,
  2730. .import_ir_inst_id = inst->import_ir_inst_id,
  2731. .entity_name_id = inst->entity_name_id});
  2732. // Store the constant for both the ImportRefLoaded and indirect instructions.
  2733. context.constant_values().Set(inst_id, constant_id);
  2734. for (const auto& import_ir_inst : indirect_insts) {
  2735. context.import_ir_constant_values()[import_ir_inst.ir_id.index].Set(
  2736. import_ir_inst.inst_id, constant_id);
  2737. }
  2738. }
  2739. auto ImportImplsFromApiFile(Context& context) -> void {
  2740. SemIR::ImportIRId import_ir_id = SemIR::ImportIRId::ApiForImpl;
  2741. auto& import_ir = context.import_irs().Get(import_ir_id);
  2742. if (!import_ir.sem_ir) {
  2743. return;
  2744. }
  2745. for (auto impl_index : llvm::seq(import_ir.sem_ir->impls().size())) {
  2746. SemIR::ImplId impl_id(impl_index);
  2747. // Resolve the imported impl to a local impl ID.
  2748. ImportImpl(context, import_ir_id, impl_id);
  2749. }
  2750. }
  2751. auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  2752. SemIR::ImplId impl_id) -> void {
  2753. ImportRefResolver resolver(context, import_ir_id);
  2754. context.generic_region_stack().Push();
  2755. resolver.Resolve(context.import_irs()
  2756. .Get(import_ir_id)
  2757. .sem_ir->impls()
  2758. .Get(impl_id)
  2759. .first_decl_id());
  2760. context.generic_region_stack().Pop();
  2761. }
  2762. } // namespace Carbon::Check