import_ref.cpp 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066
  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. -> ResolveResult {
  1288. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  1289. auto virtual_functions =
  1290. GetLocalInstBlockContents(resolver, inst.virtual_functions_id);
  1291. if (resolver.HasNewWork()) {
  1292. return ResolveResult::Retry();
  1293. }
  1294. auto virtual_functions_id = GetLocalCanonicalInstBlockId(
  1295. resolver, inst.virtual_functions_id, virtual_functions);
  1296. return ResolveAs<SemIR::Vtable>(
  1297. resolver, {.type_id = resolver.local_context().GetTypeIdForTypeConstant(
  1298. type_const_id),
  1299. .virtual_functions_id = virtual_functions_id});
  1300. }
  1301. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1302. SemIR::BindAlias inst) -> ResolveResult {
  1303. auto value_id = GetLocalConstantId(resolver, inst.value_id);
  1304. return RetryOrDone(resolver, value_id);
  1305. }
  1306. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1307. SemIR::BindSymbolicName inst) -> ResolveResult {
  1308. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1309. if (resolver.HasNewWork()) {
  1310. return ResolveResult::Retry();
  1311. }
  1312. const auto& import_entity_name =
  1313. resolver.import_entity_names().Get(inst.entity_name_id);
  1314. auto name_id = GetLocalNameId(resolver, import_entity_name.name_id);
  1315. auto entity_name_id = resolver.local_entity_names().Add(
  1316. {.name_id = name_id,
  1317. .parent_scope_id = SemIR::NameScopeId::Invalid,
  1318. .bind_index = import_entity_name.bind_index});
  1319. return ResolveAs<SemIR::BindSymbolicName>(
  1320. resolver,
  1321. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  1322. .entity_name_id = entity_name_id,
  1323. .value_id = SemIR::InstId::Invalid});
  1324. }
  1325. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1326. SemIR::SymbolicBindingPattern inst)
  1327. -> ResolveResult {
  1328. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1329. if (resolver.HasNewWork()) {
  1330. return ResolveResult::Retry();
  1331. }
  1332. const auto& import_entity_name =
  1333. resolver.import_entity_names().Get(inst.entity_name_id);
  1334. auto name_id = GetLocalNameId(resolver, import_entity_name.name_id);
  1335. auto entity_name_id = resolver.local_entity_names().Add(
  1336. {.name_id = name_id,
  1337. .parent_scope_id = SemIR::NameScopeId::Invalid,
  1338. .bind_index = import_entity_name.bind_index});
  1339. return ResolveAs<SemIR::SymbolicBindingPattern>(
  1340. resolver,
  1341. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  1342. .entity_name_id = entity_name_id});
  1343. }
  1344. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1345. SemIR::BoundMethod inst) -> ResolveResult {
  1346. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  1347. SemIR::BoundMethodType::SingletonInstId);
  1348. auto object_id = GetLocalConstantInstId(resolver, inst.object_id);
  1349. auto function_decl_id =
  1350. GetLocalConstantInstId(resolver, inst.function_decl_id);
  1351. if (resolver.HasNewWork()) {
  1352. return ResolveResult::Retry();
  1353. }
  1354. return ResolveAs<SemIR::BoundMethod>(
  1355. resolver, {.type_id = resolver.local_context().GetSingletonType(
  1356. SemIR::BoundMethodType::SingletonInstId),
  1357. .object_id = object_id,
  1358. .function_decl_id = function_decl_id});
  1359. }
  1360. static auto TryResolveTypedInst(ImportRefResolver& resolver, SemIR::Call inst)
  1361. -> ResolveResult {
  1362. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  1363. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  1364. auto args = GetLocalInstBlockContents(resolver, inst.args_id);
  1365. if (resolver.HasNewWork()) {
  1366. return ResolveResult::Retry();
  1367. }
  1368. return ResolveAs<SemIR::Call>(
  1369. resolver,
  1370. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  1371. .callee_id = callee_id,
  1372. .args_id = GetLocalCanonicalInstBlockId(resolver, inst.args_id, args)});
  1373. }
  1374. // Makes an incomplete class. This is necessary even with classes with a
  1375. // complete declaration, because things such as `Self` may refer back to the
  1376. // type.
  1377. static auto MakeIncompleteClass(ImportContext& context,
  1378. const SemIR::Class& import_class,
  1379. SemIR::SpecificId enclosing_specific_id)
  1380. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  1381. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeType::SingletonTypeId,
  1382. .class_id = SemIR::ClassId::Invalid,
  1383. .decl_block_id = SemIR::InstBlockId::Empty};
  1384. auto class_decl_id = context.local_context().AddPlaceholderInstInNoBlock(
  1385. context.local_context().MakeImportedLocAndInst(
  1386. AddImportIRInst(context, import_class.latest_decl_id()), class_decl));
  1387. // Regardless of whether ClassDecl is a complete type, we first need an
  1388. // incomplete type so that any references have something to point at.
  1389. class_decl.class_id = context.local_classes().Add(
  1390. {GetIncompleteLocalEntityBase(context, class_decl_id, import_class),
  1391. {.self_type_id = SemIR::TypeId::Invalid,
  1392. .inheritance_kind = import_class.inheritance_kind,
  1393. .is_dynamic = import_class.is_dynamic}});
  1394. if (import_class.has_parameters()) {
  1395. class_decl.type_id = context.local_context().GetGenericClassType(
  1396. class_decl.class_id, enclosing_specific_id);
  1397. }
  1398. // Write the class ID into the ClassDecl.
  1399. context.local_context().ReplaceInstBeforeConstantUse(class_decl_id,
  1400. class_decl);
  1401. auto self_const_id = context.local_constant_values().Get(class_decl_id);
  1402. return {class_decl.class_id, self_const_id};
  1403. }
  1404. // Fills out the class definition for an incomplete class.
  1405. static auto AddClassDefinition(ImportContext& context,
  1406. const SemIR::Class& import_class,
  1407. SemIR::Class& new_class,
  1408. SemIR::InstId complete_type_witness_id,
  1409. SemIR::InstId base_id, SemIR::InstId adapt_id,
  1410. SemIR::InstId vtable_id) -> void {
  1411. new_class.definition_id = new_class.first_owning_decl_id;
  1412. new_class.complete_type_witness_id = complete_type_witness_id;
  1413. new_class.scope_id = context.local_name_scopes().Add(
  1414. new_class.first_owning_decl_id, SemIR::NameId::Invalid,
  1415. new_class.parent_scope_id);
  1416. auto& new_scope = context.local_name_scopes().Get(new_class.scope_id);
  1417. const auto& import_scope =
  1418. context.import_name_scopes().Get(import_class.scope_id);
  1419. // Push a block so that we can add scoped instructions to it.
  1420. context.local_context().inst_block_stack().Push();
  1421. AddNameScopeImportRefs(context, import_scope, new_scope);
  1422. new_class.body_block_id = context.local_context().inst_block_stack().Pop();
  1423. if (import_class.base_id.is_valid()) {
  1424. new_class.base_id = base_id;
  1425. }
  1426. if (import_class.adapt_id.is_valid()) {
  1427. new_class.adapt_id = adapt_id;
  1428. }
  1429. if (import_class.vtable_id.is_valid()) {
  1430. new_class.vtable_id = vtable_id;
  1431. }
  1432. }
  1433. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1434. SemIR::ClassDecl inst,
  1435. SemIR::ConstantId class_const_id)
  1436. -> ResolveResult {
  1437. // TODO: The handling of interfaces repeats a lot with the handling of
  1438. // classes, and will likely also be repeated for named constraints and
  1439. // choice types. Factor out some of this functionality.
  1440. const auto& import_class = resolver.import_classes().Get(inst.class_id);
  1441. SemIR::ClassId class_id = SemIR::ClassId::Invalid;
  1442. if (!class_const_id.is_valid()) {
  1443. auto import_specific_id = SemIR::SpecificId::Invalid;
  1444. if (auto import_generic_class_type =
  1445. resolver.import_types().TryGetAs<SemIR::GenericClassType>(
  1446. inst.type_id)) {
  1447. import_specific_id = import_generic_class_type->enclosing_specific_id;
  1448. }
  1449. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1450. if (resolver.HasNewWork()) {
  1451. // This is the end of the first phase. Don't make a new class yet if
  1452. // we already have new work.
  1453. return ResolveResult::Retry();
  1454. }
  1455. // On the second phase, create a forward declaration of the class for any
  1456. // recursive references.
  1457. auto enclosing_specific_id =
  1458. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1459. std::tie(class_id, class_const_id) =
  1460. MakeIncompleteClass(resolver, import_class, enclosing_specific_id);
  1461. } else {
  1462. // On the third phase, compute the class ID from the constant
  1463. // value of the declaration.
  1464. auto class_const_inst = resolver.local_insts().Get(
  1465. resolver.local_constant_values().GetInstId(class_const_id));
  1466. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  1467. class_id = class_type->class_id;
  1468. } else {
  1469. auto generic_class_type =
  1470. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1471. class_const_inst.type_id());
  1472. class_id = generic_class_type.class_id;
  1473. }
  1474. }
  1475. // Load constants for the definition.
  1476. auto parent_scope_id =
  1477. GetLocalNameScopeId(resolver, import_class.parent_scope_id);
  1478. LoadLocalPatternConstantIds(resolver,
  1479. import_class.implicit_param_patterns_id);
  1480. LoadLocalPatternConstantIds(resolver, import_class.param_patterns_id);
  1481. auto generic_data = GetLocalGenericData(resolver, import_class.generic_id);
  1482. auto self_const_id = GetLocalConstantId(resolver, import_class.self_type_id);
  1483. auto complete_type_witness_const_id =
  1484. import_class.complete_type_witness_id.is_valid()
  1485. ? GetLocalConstantId(resolver, import_class.complete_type_witness_id)
  1486. : SemIR::ConstantId::Invalid;
  1487. auto base_id = import_class.base_id.is_valid()
  1488. ? GetLocalConstantInstId(resolver, import_class.base_id)
  1489. : SemIR::InstId::Invalid;
  1490. auto adapt_id = import_class.adapt_id.is_valid()
  1491. ? GetLocalConstantInstId(resolver, import_class.adapt_id)
  1492. : SemIR::InstId::Invalid;
  1493. auto& new_class = resolver.local_classes().Get(class_id);
  1494. if (resolver.HasNewWork()) {
  1495. return ResolveResult::Retry(class_const_id, new_class.first_decl_id());
  1496. }
  1497. auto vtable_id = import_class.vtable_id.is_valid()
  1498. ? AddImportRef(resolver, import_class.vtable_id)
  1499. : SemIR::InstId::Invalid;
  1500. new_class.parent_scope_id = parent_scope_id;
  1501. new_class.implicit_param_patterns_id = GetLocalParamPatternsId(
  1502. resolver, import_class.implicit_param_patterns_id);
  1503. new_class.param_patterns_id =
  1504. GetLocalParamPatternsId(resolver, import_class.param_patterns_id);
  1505. SetGenericData(resolver, import_class.generic_id, new_class.generic_id,
  1506. generic_data);
  1507. new_class.self_type_id =
  1508. resolver.local_context().GetTypeIdForTypeConstant(self_const_id);
  1509. if (import_class.is_defined()) {
  1510. auto complete_type_witness_id = AddLoadedImportRef(
  1511. resolver,
  1512. resolver.local_context().GetSingletonType(
  1513. SemIR::WitnessType::SingletonInstId),
  1514. import_class.complete_type_witness_id, complete_type_witness_const_id);
  1515. AddClassDefinition(resolver, import_class, new_class,
  1516. complete_type_witness_id, base_id, adapt_id, vtable_id);
  1517. }
  1518. return ResolveResult::Done(class_const_id, new_class.first_decl_id());
  1519. }
  1520. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1521. SemIR::ClassType inst) -> ResolveResult {
  1522. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1523. auto class_const_id = GetLocalConstantId(
  1524. resolver,
  1525. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  1526. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  1527. if (resolver.HasNewWork()) {
  1528. return ResolveResult::Retry();
  1529. }
  1530. // Find the corresponding class type. For a non-generic class, this is the
  1531. // type of the class declaration. For a generic class, build a class type
  1532. // referencing this specialization of the generic class.
  1533. auto class_const_inst = resolver.local_insts().Get(
  1534. resolver.local_constant_values().GetInstId(class_const_id));
  1535. if (class_const_inst.Is<SemIR::ClassType>()) {
  1536. return ResolveResult::Done(class_const_id);
  1537. } else {
  1538. auto generic_class_type =
  1539. resolver.local_types().GetAs<SemIR::GenericClassType>(
  1540. class_const_inst.type_id());
  1541. auto specific_id =
  1542. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  1543. return ResolveAs<SemIR::ClassType>(
  1544. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  1545. .class_id = generic_class_type.class_id,
  1546. .specific_id = specific_id});
  1547. }
  1548. }
  1549. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1550. SemIR::CompleteTypeWitness inst)
  1551. -> ResolveResult {
  1552. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  1553. SemIR::WitnessType::SingletonInstId);
  1554. auto object_repr_const_id = GetLocalConstantId(resolver, inst.object_repr_id);
  1555. if (resolver.HasNewWork()) {
  1556. return ResolveResult::Retry();
  1557. }
  1558. auto object_repr_id =
  1559. resolver.local_context().GetTypeIdForTypeConstant(object_repr_const_id);
  1560. return ResolveAs<SemIR::CompleteTypeWitness>(
  1561. resolver, {.type_id = resolver.local_context().GetSingletonType(
  1562. SemIR::WitnessType::SingletonInstId),
  1563. .object_repr_id = object_repr_id});
  1564. }
  1565. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1566. SemIR::ConstType inst) -> ResolveResult {
  1567. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1568. auto inner_const_id = GetLocalConstantId(resolver, inst.inner_id);
  1569. if (resolver.HasNewWork()) {
  1570. return ResolveResult::Retry();
  1571. }
  1572. auto inner_type_id =
  1573. resolver.local_context().GetTypeIdForTypeConstant(inner_const_id);
  1574. return ResolveAs<SemIR::ConstType>(
  1575. resolver,
  1576. {.type_id = SemIR::TypeType::SingletonTypeId, .inner_id = inner_type_id});
  1577. }
  1578. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1579. SemIR::ExportDecl inst) -> ResolveResult {
  1580. auto value_id = GetLocalConstantId(resolver, inst.value_id);
  1581. return RetryOrDone(resolver, value_id);
  1582. }
  1583. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1584. SemIR::FieldDecl inst,
  1585. SemIR::InstId import_inst_id) -> ResolveResult {
  1586. auto const_id = GetLocalConstantId(resolver, inst.type_id);
  1587. if (resolver.HasNewWork()) {
  1588. return ResolveResult::Retry();
  1589. }
  1590. auto inst_id = resolver.local_context().AddInstInNoBlock(
  1591. resolver.local_context().MakeImportedLocAndInst<SemIR::FieldDecl>(
  1592. AddImportIRInst(resolver, import_inst_id),
  1593. {.type_id =
  1594. resolver.local_context().GetTypeIdForTypeConstant(const_id),
  1595. .name_id = GetLocalNameId(resolver, inst.name_id),
  1596. .index = inst.index}));
  1597. return ResolveResult::Done(resolver.local_constant_values().Get(inst_id),
  1598. inst_id);
  1599. }
  1600. // Make a declaration of a function. This is done as a separate step from
  1601. // importing the function declaration in order to resolve cycles.
  1602. static auto MakeFunctionDecl(ImportContext& context,
  1603. const SemIR::Function& import_function,
  1604. SemIR::SpecificId specific_id)
  1605. -> std::pair<SemIR::FunctionId, SemIR::ConstantId> {
  1606. SemIR::FunctionDecl function_decl = {
  1607. .type_id = SemIR::TypeId::Invalid,
  1608. .function_id = SemIR::FunctionId::Invalid,
  1609. .decl_block_id = SemIR::InstBlockId::Empty};
  1610. auto function_decl_id = context.local_context().AddPlaceholderInstInNoBlock(
  1611. context.local_context().MakeImportedLocAndInst(
  1612. AddImportIRInst(context, import_function.first_decl_id()),
  1613. function_decl));
  1614. // Start with an incomplete function.
  1615. function_decl.function_id = context.local_functions().Add(
  1616. {GetIncompleteLocalEntityBase(context, function_decl_id, import_function),
  1617. {.return_slot_pattern_id = SemIR::InstId::Invalid,
  1618. .builtin_function_kind = import_function.builtin_function_kind}});
  1619. function_decl.type_id = context.local_context().GetFunctionType(
  1620. function_decl.function_id, specific_id);
  1621. // Write the function ID and type into the FunctionDecl.
  1622. context.local_context().ReplaceInstBeforeConstantUse(function_decl_id,
  1623. function_decl);
  1624. return {function_decl.function_id,
  1625. context.local_constant_values().Get(function_decl_id)};
  1626. }
  1627. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1628. SemIR::FunctionDecl inst,
  1629. SemIR::ConstantId function_const_id)
  1630. -> ResolveResult {
  1631. const auto& import_function =
  1632. resolver.import_functions().Get(inst.function_id);
  1633. SemIR::FunctionId function_id = SemIR::FunctionId::Invalid;
  1634. if (!function_const_id.is_valid()) {
  1635. auto import_specific_id = resolver.import_types()
  1636. .GetAs<SemIR::FunctionType>(inst.type_id)
  1637. .specific_id;
  1638. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1639. if (resolver.HasNewWork()) {
  1640. // This is the end of the first phase. Don't make a new function yet if
  1641. // we already have new work.
  1642. return ResolveResult::Retry();
  1643. }
  1644. // On the second phase, create a forward declaration of the interface.
  1645. auto specific_id =
  1646. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1647. std::tie(function_id, function_const_id) =
  1648. MakeFunctionDecl(resolver, import_function, specific_id);
  1649. } else {
  1650. // On the third phase, compute the function ID from the constant value of
  1651. // the declaration.
  1652. auto function_const_inst = resolver.local_insts().Get(
  1653. resolver.local_constant_values().GetInstId(function_const_id));
  1654. auto function_type = resolver.local_types().GetAs<SemIR::FunctionType>(
  1655. function_const_inst.type_id());
  1656. function_id = function_type.function_id;
  1657. }
  1658. auto return_type_const_id = SemIR::ConstantId::Invalid;
  1659. if (import_function.return_slot_pattern_id.is_valid()) {
  1660. return_type_const_id = GetLocalConstantId(
  1661. resolver, resolver.import_insts()
  1662. .Get(import_function.return_slot_pattern_id)
  1663. .type_id());
  1664. }
  1665. auto parent_scope_id =
  1666. GetLocalNameScopeId(resolver, import_function.parent_scope_id);
  1667. LoadLocalPatternConstantIds(resolver,
  1668. import_function.implicit_param_patterns_id);
  1669. LoadLocalPatternConstantIds(resolver, import_function.param_patterns_id);
  1670. auto generic_data = GetLocalGenericData(resolver, import_function.generic_id);
  1671. auto& new_function = resolver.local_functions().Get(function_id);
  1672. if (resolver.HasNewWork()) {
  1673. return ResolveResult::Retry(function_const_id,
  1674. new_function.first_decl_id());
  1675. }
  1676. // Add the function declaration.
  1677. new_function.parent_scope_id = parent_scope_id;
  1678. new_function.implicit_param_patterns_id = GetLocalParamPatternsId(
  1679. resolver, import_function.implicit_param_patterns_id);
  1680. new_function.param_patterns_id =
  1681. GetLocalParamPatternsId(resolver, import_function.param_patterns_id);
  1682. new_function.return_slot_pattern_id = GetLocalReturnSlotPatternId(
  1683. resolver, import_function.return_slot_pattern_id);
  1684. SetGenericData(resolver, import_function.generic_id, new_function.generic_id,
  1685. generic_data);
  1686. if (import_function.definition_id.is_valid()) {
  1687. new_function.definition_id = new_function.first_owning_decl_id;
  1688. }
  1689. return ResolveResult::Done(function_const_id, new_function.first_decl_id());
  1690. }
  1691. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1692. SemIR::FunctionType inst) -> ResolveResult {
  1693. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1694. auto fn_val_id = GetLocalConstantInstId(
  1695. resolver,
  1696. resolver.import_functions().Get(inst.function_id).first_decl_id());
  1697. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  1698. if (resolver.HasNewWork()) {
  1699. return ResolveResult::Retry();
  1700. }
  1701. auto fn_type_id = resolver.local_insts().Get(fn_val_id).type_id();
  1702. return ResolveAs<SemIR::FunctionType>(
  1703. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  1704. .function_id = resolver.local_types()
  1705. .GetAs<SemIR::FunctionType>(fn_type_id)
  1706. .function_id,
  1707. .specific_id = GetOrAddLocalSpecific(
  1708. resolver, inst.specific_id, specific_data)});
  1709. }
  1710. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1711. SemIR::GenericClassType inst) -> ResolveResult {
  1712. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1713. auto class_val_id = GetLocalConstantInstId(
  1714. resolver,
  1715. resolver.import_classes().Get(inst.class_id).first_owning_decl_id);
  1716. if (resolver.HasNewWork()) {
  1717. return ResolveResult::Retry();
  1718. }
  1719. auto class_val = resolver.local_insts().Get(class_val_id);
  1720. CARBON_CHECK(
  1721. resolver.local_types().Is<SemIR::GenericClassType>(class_val.type_id()));
  1722. return ResolveResult::Done(
  1723. resolver.local_types().GetConstantId(class_val.type_id()));
  1724. }
  1725. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1726. SemIR::GenericInterfaceType inst)
  1727. -> ResolveResult {
  1728. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  1729. auto interface_val_id = GetLocalConstantInstId(
  1730. resolver,
  1731. resolver.import_interfaces().Get(inst.interface_id).first_owning_decl_id);
  1732. if (resolver.HasNewWork()) {
  1733. return ResolveResult::Retry();
  1734. }
  1735. auto interface_val = resolver.local_insts().Get(interface_val_id);
  1736. CARBON_CHECK(resolver.local_types().Is<SemIR::GenericInterfaceType>(
  1737. interface_val.type_id()));
  1738. return ResolveResult::Done(
  1739. resolver.local_types().GetConstantId(interface_val.type_id()));
  1740. }
  1741. // Make a declaration of an impl. This is done as a separate step from
  1742. // importing the impl definition in order to resolve cycles.
  1743. static auto MakeImplDeclaration(ImportContext& context,
  1744. const SemIR::Impl& import_impl,
  1745. SemIR::InstId witness_id)
  1746. -> std::pair<SemIR::ImplId, SemIR::ConstantId> {
  1747. SemIR::ImplDecl impl_decl = {.impl_id = SemIR::ImplId::Invalid,
  1748. .decl_block_id = SemIR::InstBlockId::Empty};
  1749. auto impl_decl_id = context.local_context().AddPlaceholderInstInNoBlock(
  1750. context.local_context().MakeImportedLocAndInst(
  1751. AddImportIRInst(context, import_impl.latest_decl_id()), impl_decl));
  1752. impl_decl.impl_id = context.local_impls().Add(
  1753. {GetIncompleteLocalEntityBase(context, impl_decl_id, import_impl),
  1754. {.self_id = SemIR::InstId::Invalid,
  1755. .constraint_id = SemIR::InstId::Invalid,
  1756. .witness_id = witness_id}});
  1757. // Write the impl ID into the ImplDecl.
  1758. context.local_context().ReplaceInstBeforeConstantUse(impl_decl_id, impl_decl);
  1759. return {impl_decl.impl_id, context.local_constant_values().Get(impl_decl_id)};
  1760. }
  1761. // Imports the definition of an impl.
  1762. static auto AddImplDefinition(ImportContext& context,
  1763. const SemIR::Impl& import_impl,
  1764. SemIR::Impl& new_impl) -> void {
  1765. new_impl.definition_id = new_impl.first_owning_decl_id;
  1766. new_impl.defined = true;
  1767. if (import_impl.scope_id.is_valid()) {
  1768. new_impl.scope_id = context.local_name_scopes().Add(
  1769. new_impl.first_owning_decl_id, SemIR::NameId::Invalid,
  1770. new_impl.parent_scope_id);
  1771. // Import the contents of the definition scope, if we might need it. Name
  1772. // lookup is never performed into this scope by a user of the impl, so
  1773. // this is only necessary in the same library that defined the impl, in
  1774. // order to support defining members of the impl out of line in the impl
  1775. // file when the impl is defined in the API file.
  1776. // TODO: Check to see if this impl is owned by the API file, rather than
  1777. // merely being imported into it.
  1778. if (context.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  1779. auto& new_scope = context.local_name_scopes().Get(new_impl.scope_id);
  1780. const auto& import_scope =
  1781. context.import_name_scopes().Get(import_impl.scope_id);
  1782. // Push a block so that we can add scoped instructions to it.
  1783. context.local_context().inst_block_stack().Push();
  1784. AddNameScopeImportRefs(context, import_scope, new_scope);
  1785. new_impl.body_block_id = context.local_context().inst_block_stack().Pop();
  1786. }
  1787. }
  1788. }
  1789. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1790. SemIR::ImplDecl inst,
  1791. SemIR::ConstantId impl_const_id)
  1792. -> ResolveResult {
  1793. // TODO: This duplicates a lot of the handling of interfaces, classes, and
  1794. // functions. Factor out the commonality.
  1795. const auto& import_impl = resolver.import_impls().Get(inst.impl_id);
  1796. SemIR::ImplId impl_id = SemIR::ImplId::Invalid;
  1797. if (!impl_const_id.is_valid()) {
  1798. if (resolver.HasNewWork()) {
  1799. // This is the end of the first phase. Don't make a new impl yet if we
  1800. // already have new work.
  1801. return ResolveResult::Retry();
  1802. }
  1803. // On the second phase, create a forward declaration of the impl for any
  1804. // recursive references.
  1805. auto witness_id = AddImportRef(resolver, import_impl.witness_id);
  1806. std::tie(impl_id, impl_const_id) =
  1807. MakeImplDeclaration(resolver, import_impl, witness_id);
  1808. } else {
  1809. // On the third phase, compute the impl ID from the "constant value" of
  1810. // the declaration, which is a reference to the created ImplDecl.
  1811. auto impl_const_inst = resolver.local_insts().GetAs<SemIR::ImplDecl>(
  1812. resolver.local_constant_values().GetInstId(impl_const_id));
  1813. impl_id = impl_const_inst.impl_id;
  1814. }
  1815. // Load constants for the definition.
  1816. auto parent_scope_id =
  1817. GetLocalNameScopeId(resolver, import_impl.parent_scope_id);
  1818. LoadLocalPatternConstantIds(resolver, import_impl.implicit_param_patterns_id);
  1819. auto generic_data = GetLocalGenericData(resolver, import_impl.generic_id);
  1820. auto self_const_id = GetLocalConstantId(
  1821. resolver, resolver.import_constant_values().Get(import_impl.self_id));
  1822. auto constraint_const_id = GetLocalConstantId(
  1823. resolver,
  1824. resolver.import_constant_values().Get(import_impl.constraint_id));
  1825. auto& new_impl = resolver.local_impls().Get(impl_id);
  1826. if (resolver.HasNewWork()) {
  1827. return ResolveResult::Retry(impl_const_id, new_impl.first_decl_id());
  1828. }
  1829. new_impl.parent_scope_id = parent_scope_id;
  1830. new_impl.implicit_param_patterns_id =
  1831. GetLocalParamPatternsId(resolver, import_impl.implicit_param_patterns_id);
  1832. SetGenericData(resolver, import_impl.generic_id, new_impl.generic_id,
  1833. generic_data);
  1834. // Create instructions for self and constraint to hold the symbolic constant
  1835. // value for a generic impl.
  1836. new_impl.self_id =
  1837. AddLoadedImportRef(resolver, SemIR::TypeType::SingletonTypeId,
  1838. import_impl.self_id, self_const_id);
  1839. new_impl.constraint_id =
  1840. AddLoadedImportRef(resolver, SemIR::TypeType::SingletonTypeId,
  1841. import_impl.constraint_id, constraint_const_id);
  1842. if (import_impl.is_defined()) {
  1843. AddImplDefinition(resolver, import_impl, new_impl);
  1844. }
  1845. // If the `impl` is declared in the API file corresponding to the current
  1846. // file, add this to impl lookup so that it can be found by redeclarations
  1847. // in the current file.
  1848. if (resolver.import_ir_id() == SemIR::ImportIRId::ApiForImpl) {
  1849. resolver.local_impls().GetOrAddLookupBucket(new_impl).push_back(impl_id);
  1850. }
  1851. return ResolveResult::Done(impl_const_id, new_impl.first_decl_id());
  1852. }
  1853. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1854. SemIR::ImportRefLoaded /*inst*/,
  1855. SemIR::InstId inst_id) -> ResolveResult {
  1856. // Return the constant for the instruction of the imported constant.
  1857. auto constant_id = resolver.import_constant_values().Get(inst_id);
  1858. if (!constant_id.is_valid()) {
  1859. return ResolveResult::Done(SemIR::ErrorInst::SingletonConstantId);
  1860. }
  1861. if (!constant_id.is_constant()) {
  1862. resolver.local_context().TODO(
  1863. inst_id, "Non-constant ImportRefLoaded (comes up with var)");
  1864. return ResolveResult::Done(SemIR::ErrorInst::SingletonConstantId);
  1865. }
  1866. auto new_constant_id = GetLocalConstantId(
  1867. resolver, resolver.import_constant_values().GetInstId(constant_id));
  1868. return RetryOrDone(resolver, new_constant_id);
  1869. }
  1870. // Make a declaration of an interface. This is done as a separate step from
  1871. // importing the interface definition in order to resolve cycles.
  1872. static auto MakeInterfaceDecl(ImportContext& context,
  1873. const SemIR::Interface& import_interface,
  1874. SemIR::SpecificId enclosing_specific_id)
  1875. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  1876. SemIR::InterfaceDecl interface_decl = {
  1877. .type_id = SemIR::TypeType::SingletonTypeId,
  1878. .interface_id = SemIR::InterfaceId::Invalid,
  1879. .decl_block_id = SemIR::InstBlockId::Empty};
  1880. auto interface_decl_id = context.local_context().AddPlaceholderInstInNoBlock(
  1881. context.local_context().MakeImportedLocAndInst(
  1882. AddImportIRInst(context, import_interface.first_owning_decl_id),
  1883. interface_decl));
  1884. // Start with an incomplete interface.
  1885. interface_decl.interface_id = context.local_interfaces().Add(
  1886. {GetIncompleteLocalEntityBase(context, interface_decl_id,
  1887. import_interface),
  1888. {}});
  1889. if (import_interface.has_parameters()) {
  1890. interface_decl.type_id = context.local_context().GetGenericInterfaceType(
  1891. interface_decl.interface_id, enclosing_specific_id);
  1892. }
  1893. // Write the interface ID into the InterfaceDecl.
  1894. context.local_context().ReplaceInstBeforeConstantUse(interface_decl_id,
  1895. interface_decl);
  1896. return {interface_decl.interface_id,
  1897. context.local_constant_values().Get(interface_decl_id)};
  1898. }
  1899. // Imports the definition for an interface that has been imported as a forward
  1900. // declaration.
  1901. static auto AddInterfaceDefinition(ImportContext& context,
  1902. const SemIR::Interface& import_interface,
  1903. SemIR::Interface& new_interface,
  1904. SemIR::InstId self_param_id) -> void {
  1905. new_interface.scope_id = context.local_name_scopes().Add(
  1906. new_interface.first_owning_decl_id, SemIR::NameId::Invalid,
  1907. new_interface.parent_scope_id);
  1908. auto& new_scope = context.local_name_scopes().Get(new_interface.scope_id);
  1909. const auto& import_scope =
  1910. context.import_name_scopes().Get(import_interface.scope_id);
  1911. // Push a block so that we can add scoped instructions to it.
  1912. context.local_context().inst_block_stack().Push();
  1913. AddNameScopeImportRefs(context, import_scope, new_scope);
  1914. new_interface.associated_entities_id = AddAssociatedEntities(
  1915. context, new_interface.scope_id, import_interface.associated_entities_id);
  1916. new_interface.body_block_id =
  1917. context.local_context().inst_block_stack().Pop();
  1918. new_interface.self_param_id = self_param_id;
  1919. CARBON_CHECK(import_scope.extended_scopes().empty(),
  1920. "Interfaces don't currently have extended scopes to support.");
  1921. }
  1922. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1923. SemIR::InterfaceDecl inst,
  1924. SemIR::ConstantId interface_const_id)
  1925. -> ResolveResult {
  1926. const auto& import_interface =
  1927. resolver.import_interfaces().Get(inst.interface_id);
  1928. SemIR::InterfaceId interface_id = SemIR::InterfaceId::Invalid;
  1929. if (!interface_const_id.is_valid()) {
  1930. auto import_specific_id = SemIR::SpecificId::Invalid;
  1931. if (auto import_generic_interface_type =
  1932. resolver.import_types().TryGetAs<SemIR::GenericInterfaceType>(
  1933. inst.type_id)) {
  1934. import_specific_id = import_generic_interface_type->enclosing_specific_id;
  1935. }
  1936. auto specific_data = GetLocalSpecificData(resolver, import_specific_id);
  1937. if (resolver.HasNewWork()) {
  1938. // This is the end of the first phase. Don't make a new interface yet if
  1939. // we already have new work.
  1940. return ResolveResult::Retry();
  1941. }
  1942. // On the second phase, create a forward declaration of the interface.
  1943. auto enclosing_specific_id =
  1944. GetOrAddLocalSpecific(resolver, import_specific_id, specific_data);
  1945. std::tie(interface_id, interface_const_id) =
  1946. MakeInterfaceDecl(resolver, import_interface, enclosing_specific_id);
  1947. } else {
  1948. // On the third phase, compute the interface ID from the constant value of
  1949. // the declaration.
  1950. auto interface_const_inst = resolver.local_insts().Get(
  1951. resolver.local_constant_values().GetInstId(interface_const_id));
  1952. if (auto facet_type = interface_const_inst.TryAs<SemIR::FacetType>()) {
  1953. const SemIR::FacetTypeInfo& facet_type_info =
  1954. resolver.local_facet_types().Get(facet_type->facet_type_id);
  1955. auto interface_type = facet_type_info.TryAsSingleInterface();
  1956. CARBON_CHECK(interface_type);
  1957. interface_id = interface_type->interface_id;
  1958. } else {
  1959. auto generic_interface_type =
  1960. resolver.local_types().GetAs<SemIR::GenericInterfaceType>(
  1961. interface_const_inst.type_id());
  1962. interface_id = generic_interface_type.interface_id;
  1963. }
  1964. }
  1965. auto parent_scope_id =
  1966. GetLocalNameScopeId(resolver, import_interface.parent_scope_id);
  1967. LoadLocalPatternConstantIds(resolver,
  1968. import_interface.implicit_param_patterns_id);
  1969. LoadLocalPatternConstantIds(resolver, import_interface.param_patterns_id);
  1970. auto generic_data =
  1971. GetLocalGenericData(resolver, import_interface.generic_id);
  1972. std::optional<SemIR::InstId> self_param_id;
  1973. if (import_interface.is_defined()) {
  1974. self_param_id =
  1975. GetLocalConstantInstId(resolver, import_interface.self_param_id);
  1976. }
  1977. auto& new_interface = resolver.local_interfaces().Get(interface_id);
  1978. if (resolver.HasNewWork()) {
  1979. return ResolveResult::Retry(interface_const_id,
  1980. new_interface.first_decl_id());
  1981. }
  1982. new_interface.parent_scope_id = parent_scope_id;
  1983. new_interface.implicit_param_patterns_id = GetLocalParamPatternsId(
  1984. resolver, import_interface.implicit_param_patterns_id);
  1985. new_interface.param_patterns_id =
  1986. GetLocalParamPatternsId(resolver, import_interface.param_patterns_id);
  1987. SetGenericData(resolver, import_interface.generic_id,
  1988. new_interface.generic_id, generic_data);
  1989. if (import_interface.is_defined()) {
  1990. CARBON_CHECK(self_param_id);
  1991. AddInterfaceDefinition(resolver, import_interface, new_interface,
  1992. *self_param_id);
  1993. }
  1994. return ResolveResult::Done(interface_const_id, new_interface.first_decl_id());
  1995. }
  1996. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  1997. SemIR::FacetAccessType inst) -> ResolveResult {
  1998. auto facet_value_inst_id =
  1999. GetLocalConstantInstId(resolver, inst.facet_value_inst_id);
  2000. if (resolver.HasNewWork()) {
  2001. return ResolveResult::Retry();
  2002. }
  2003. return ResolveAs<SemIR::FacetAccessType>(
  2004. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  2005. .facet_value_inst_id = facet_value_inst_id});
  2006. }
  2007. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2008. SemIR::FacetAccessWitness inst)
  2009. -> ResolveResult {
  2010. auto facet_value_inst_id =
  2011. GetLocalConstantInstId(resolver, inst.facet_value_inst_id);
  2012. if (resolver.HasNewWork()) {
  2013. return ResolveResult::Retry();
  2014. }
  2015. return ResolveAs<SemIR::FacetAccessWitness>(
  2016. resolver, {.type_id = resolver.local_context().GetSingletonType(
  2017. SemIR::WitnessType::SingletonInstId),
  2018. .facet_value_inst_id = facet_value_inst_id});
  2019. }
  2020. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2021. SemIR::FacetType inst) -> ResolveResult {
  2022. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2023. const SemIR::FacetTypeInfo& facet_type_info =
  2024. resolver.import_facet_types().Get(inst.facet_type_id);
  2025. for (auto interface : facet_type_info.impls_constraints) {
  2026. GetLocalConstantId(resolver, resolver.import_interfaces()
  2027. .Get(interface.interface_id)
  2028. .first_owning_decl_id);
  2029. GetLocalSpecificData(resolver, interface.specific_id);
  2030. }
  2031. for (auto rewrite : facet_type_info.rewrite_constraints) {
  2032. GetLocalConstantId(resolver, rewrite.lhs_const_id);
  2033. GetLocalConstantId(resolver, rewrite.rhs_const_id);
  2034. }
  2035. if (resolver.HasNewWork()) {
  2036. return ResolveResult::Retry();
  2037. }
  2038. llvm::SmallVector<SemIR::FacetTypeInfo::ImplsConstraint> impls_constraints;
  2039. for (auto interface : facet_type_info.impls_constraints) {
  2040. auto interface_const_id =
  2041. GetLocalConstantId(resolver, resolver.import_interfaces()
  2042. .Get(interface.interface_id)
  2043. .first_owning_decl_id);
  2044. auto specific_data = GetLocalSpecificData(resolver, interface.specific_id);
  2045. // Find the corresponding interface type. For a non-generic interface,
  2046. // this is the type of the interface declaration. For a generic interface,
  2047. // build a interface type referencing this specialization of the generic
  2048. // interface.
  2049. auto interface_const_inst = resolver.local_insts().Get(
  2050. resolver.local_constant_values().GetInstId(interface_const_id));
  2051. if (auto facet_type = interface_const_inst.TryAs<SemIR::FacetType>()) {
  2052. const SemIR::FacetTypeInfo& new_facet_type_info =
  2053. resolver.local_facet_types().Get(facet_type->facet_type_id);
  2054. impls_constraints.append(new_facet_type_info.impls_constraints);
  2055. } else {
  2056. auto generic_interface_type =
  2057. resolver.local_types().GetAs<SemIR::GenericInterfaceType>(
  2058. interface_const_inst.type_id());
  2059. auto specific_id =
  2060. GetOrAddLocalSpecific(resolver, interface.specific_id, specific_data);
  2061. impls_constraints.push_back(
  2062. {generic_interface_type.interface_id, specific_id});
  2063. }
  2064. }
  2065. llvm::SmallVector<SemIR::FacetTypeInfo::RewriteConstraint>
  2066. rewrite_constraints;
  2067. for (auto rewrite : facet_type_info.rewrite_constraints) {
  2068. rewrite_constraints.push_back(
  2069. {.lhs_const_id = GetLocalConstantId(resolver, rewrite.lhs_const_id),
  2070. .rhs_const_id = GetLocalConstantId(resolver, rewrite.rhs_const_id)});
  2071. }
  2072. // TODO: Also process the other requirements.
  2073. SemIR::FacetTypeId facet_type_id =
  2074. resolver.local_facet_types().Add(SemIR::FacetTypeInfo{
  2075. .impls_constraints = impls_constraints,
  2076. .rewrite_constraints = rewrite_constraints,
  2077. .other_requirements = facet_type_info.other_requirements});
  2078. return ResolveAs<SemIR::FacetType>(
  2079. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  2080. .facet_type_id = facet_type_id});
  2081. }
  2082. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2083. SemIR::FacetValue inst) -> ResolveResult {
  2084. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2085. auto type_inst_id = GetLocalConstantInstId(resolver, inst.type_inst_id);
  2086. auto witness_inst_id = GetLocalConstantInstId(resolver, inst.witness_inst_id);
  2087. if (resolver.HasNewWork()) {
  2088. return ResolveResult::Retry();
  2089. }
  2090. return ResolveAs<SemIR::FacetValue>(
  2091. resolver,
  2092. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  2093. .type_inst_id = type_inst_id,
  2094. .witness_inst_id = witness_inst_id});
  2095. }
  2096. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2097. SemIR::ImplWitness inst) -> ResolveResult {
  2098. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2099. if (resolver.HasNewWork()) {
  2100. return ResolveResult::Retry();
  2101. }
  2102. llvm::SmallVector<SemIR::InstId> elements;
  2103. auto import_elements = resolver.import_inst_blocks().Get(inst.elements_id);
  2104. elements.reserve(import_elements.size());
  2105. for (auto element : import_elements) {
  2106. elements.push_back(AddImportRef(resolver, element));
  2107. }
  2108. auto elements_id = resolver.local_inst_blocks().Add(elements);
  2109. auto specific_id =
  2110. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  2111. return ResolveAs<SemIR::ImplWitness>(
  2112. resolver, {.type_id = resolver.local_context().GetSingletonType(
  2113. SemIR::WitnessType::SingletonInstId),
  2114. .elements_id = elements_id,
  2115. .specific_id = specific_id});
  2116. }
  2117. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2118. SemIR::ImplWitnessAccess inst)
  2119. -> ResolveResult {
  2120. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2121. auto witness_id = GetLocalConstantInstId(resolver, inst.witness_id);
  2122. if (resolver.HasNewWork()) {
  2123. return ResolveResult::Retry();
  2124. }
  2125. return ResolveAs<SemIR::ImplWitnessAccess>(
  2126. resolver,
  2127. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  2128. .witness_id = witness_id,
  2129. .index = inst.index});
  2130. }
  2131. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2132. SemIR::IntValue inst) -> ResolveResult {
  2133. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2134. if (resolver.HasNewWork()) {
  2135. return ResolveResult::Retry();
  2136. }
  2137. // We can directly reuse the value IDs across file IRs. Otherwise, we need
  2138. // to add a new canonical int in this IR.
  2139. auto int_id = inst.int_id.is_value()
  2140. ? inst.int_id
  2141. : resolver.local_ints().AddSigned(
  2142. resolver.import_ints().Get(inst.int_id));
  2143. return ResolveAs<SemIR::IntValue>(
  2144. resolver,
  2145. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  2146. .int_id = int_id});
  2147. }
  2148. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2149. SemIR::IntType inst) -> ResolveResult {
  2150. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2151. auto bit_width_id = GetLocalConstantInstId(resolver, inst.bit_width_id);
  2152. if (resolver.HasNewWork()) {
  2153. return ResolveResult::Retry();
  2154. }
  2155. return ResolveAs<SemIR::IntType>(resolver,
  2156. {.type_id = SemIR::TypeType::SingletonTypeId,
  2157. .int_kind = inst.int_kind,
  2158. .bit_width_id = bit_width_id});
  2159. }
  2160. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2161. SemIR::Namespace inst,
  2162. SemIR::InstId import_inst_id) -> ResolveResult {
  2163. const auto& name_scope =
  2164. resolver.import_name_scopes().Get(inst.name_scope_id);
  2165. // A package from a different file becomes a child of the package here, as it
  2166. // would be if it were imported.
  2167. auto parent_scope_id =
  2168. inst.name_scope_id == SemIR::NameScopeId::Package
  2169. ? SemIR::NameScopeId::Package
  2170. : GetLocalNameScopeId(resolver, name_scope.parent_scope_id());
  2171. if (resolver.HasNewWork()) {
  2172. return ResolveResult::Retry();
  2173. }
  2174. auto namespace_type_id = resolver.local_context().GetSingletonType(
  2175. SemIR::NamespaceType::SingletonInstId);
  2176. auto namespace_decl =
  2177. SemIR::Namespace{.type_id = namespace_type_id,
  2178. .name_scope_id = SemIR::NameScopeId::Invalid,
  2179. .import_id = SemIR::AbsoluteInstId::Invalid};
  2180. auto inst_id = resolver.local_context().AddPlaceholderInstInNoBlock(
  2181. resolver.local_context().MakeImportedLocAndInst(
  2182. AddImportIRInst(resolver, import_inst_id), namespace_decl));
  2183. auto name_id = GetLocalNameId(resolver, name_scope.name_id());
  2184. namespace_decl.name_scope_id =
  2185. resolver.local_name_scopes().Add(inst_id, name_id, parent_scope_id);
  2186. // Namespaces from this package are eagerly imported, so anything we load here
  2187. // must be a closed import.
  2188. resolver.local_name_scopes()
  2189. .Get(namespace_decl.name_scope_id)
  2190. .set_is_closed_import(true);
  2191. resolver.local_context().ReplaceInstBeforeConstantUse(inst_id,
  2192. namespace_decl);
  2193. return {.const_id = resolver.local_constant_values().Get(inst_id)};
  2194. }
  2195. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2196. SemIR::PointerType inst) -> ResolveResult {
  2197. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2198. auto pointee_const_id = GetLocalConstantId(resolver, inst.pointee_id);
  2199. if (resolver.HasNewWork()) {
  2200. return ResolveResult::Retry();
  2201. }
  2202. auto pointee_type_id =
  2203. resolver.local_context().GetTypeIdForTypeConstant(pointee_const_id);
  2204. return ResolveAs<SemIR::PointerType>(
  2205. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  2206. .pointee_id = pointee_type_id});
  2207. }
  2208. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2209. SemIR::RequireCompleteType inst)
  2210. -> ResolveResult {
  2211. CARBON_CHECK(resolver.import_types().GetInstId(inst.type_id) ==
  2212. SemIR::WitnessType::SingletonInstId);
  2213. auto complete_type_const_id =
  2214. GetLocalConstantId(resolver, inst.complete_type_id);
  2215. if (resolver.HasNewWork()) {
  2216. return ResolveResult::Retry();
  2217. }
  2218. auto complete_type_id =
  2219. resolver.local_context().GetTypeIdForTypeConstant(complete_type_const_id);
  2220. return ResolveAs<SemIR::RequireCompleteType>(
  2221. resolver, {.type_id = resolver.local_context().GetSingletonType(
  2222. SemIR::WitnessType::SingletonInstId),
  2223. .complete_type_id = complete_type_id});
  2224. }
  2225. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2226. SemIR::SpecificFunction inst) -> ResolveResult {
  2227. auto type_const_id = GetLocalConstantId(resolver, inst.type_id);
  2228. auto callee_id = GetLocalConstantInstId(resolver, inst.callee_id);
  2229. auto specific_data = GetLocalSpecificData(resolver, inst.specific_id);
  2230. if (resolver.HasNewWork()) {
  2231. return ResolveResult::Retry();
  2232. }
  2233. auto type_id =
  2234. resolver.local_context().GetTypeIdForTypeConstant(type_const_id);
  2235. auto specific_id =
  2236. GetOrAddLocalSpecific(resolver, inst.specific_id, specific_data);
  2237. return ResolveAs<SemIR::SpecificFunction>(
  2238. resolver,
  2239. {.type_id = type_id, .callee_id = callee_id, .specific_id = specific_id});
  2240. }
  2241. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2242. SemIR::StructType inst) -> ResolveResult {
  2243. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2244. auto orig_fields = resolver.import_struct_type_fields().Get(inst.fields_id);
  2245. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  2246. field_const_ids.reserve(orig_fields.size());
  2247. for (auto field : orig_fields) {
  2248. field_const_ids.push_back(GetLocalConstantId(resolver, field.type_id));
  2249. }
  2250. if (resolver.HasNewWork()) {
  2251. return ResolveResult::Retry();
  2252. }
  2253. // Prepare a vector of fields for GetStructType.
  2254. llvm::SmallVector<SemIR::StructTypeField> new_fields;
  2255. new_fields.reserve(orig_fields.size());
  2256. for (auto [orig_field, field_const_id] :
  2257. llvm::zip(orig_fields, field_const_ids)) {
  2258. auto name_id = GetLocalNameId(resolver, orig_field.name_id);
  2259. auto field_type_id =
  2260. resolver.local_context().GetTypeIdForTypeConstant(field_const_id);
  2261. new_fields.push_back({.name_id = name_id, .type_id = field_type_id});
  2262. }
  2263. return ResolveAs<SemIR::StructType>(
  2264. resolver, {.type_id = SemIR::TypeType::SingletonTypeId,
  2265. .fields_id = resolver.local_struct_type_fields().AddCanonical(
  2266. new_fields)});
  2267. }
  2268. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2269. SemIR::StructValue inst) -> ResolveResult {
  2270. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2271. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  2272. if (resolver.HasNewWork()) {
  2273. return ResolveResult::Retry();
  2274. }
  2275. return ResolveAs<SemIR::StructValue>(
  2276. resolver,
  2277. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  2278. .elements_id =
  2279. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  2280. }
  2281. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2282. SemIR::TupleType inst) -> ResolveResult {
  2283. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2284. auto orig_elem_type_ids = resolver.import_type_blocks().Get(inst.elements_id);
  2285. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  2286. elem_const_ids.reserve(orig_elem_type_ids.size());
  2287. for (auto elem_type_id : orig_elem_type_ids) {
  2288. elem_const_ids.push_back(GetLocalConstantId(resolver, elem_type_id));
  2289. }
  2290. if (resolver.HasNewWork()) {
  2291. return ResolveResult::Retry();
  2292. }
  2293. // Prepare a vector of the tuple types for GetTupleType.
  2294. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  2295. elem_type_ids.reserve(orig_elem_type_ids.size());
  2296. for (auto elem_const_id : elem_const_ids) {
  2297. elem_type_ids.push_back(
  2298. resolver.local_context().GetTypeIdForTypeConstant(elem_const_id));
  2299. }
  2300. return ResolveResult::Done(resolver.local_types().GetConstantId(
  2301. resolver.local_context().GetTupleType(elem_type_ids)));
  2302. }
  2303. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2304. SemIR::TupleValue inst) -> ResolveResult {
  2305. auto type_id = GetLocalConstantId(resolver, inst.type_id);
  2306. auto elems = GetLocalInstBlockContents(resolver, inst.elements_id);
  2307. if (resolver.HasNewWork()) {
  2308. return ResolveResult::Retry();
  2309. }
  2310. return ResolveAs<SemIR::TupleValue>(
  2311. resolver,
  2312. {.type_id = resolver.local_context().GetTypeIdForTypeConstant(type_id),
  2313. .elements_id =
  2314. GetLocalCanonicalInstBlockId(resolver, inst.elements_id, elems)});
  2315. }
  2316. static auto TryResolveTypedInst(ImportRefResolver& resolver,
  2317. SemIR::UnboundElementType inst)
  2318. -> ResolveResult {
  2319. CARBON_CHECK(inst.type_id == SemIR::TypeType::SingletonTypeId);
  2320. auto class_const_id = GetLocalConstantId(resolver, inst.class_type_id);
  2321. auto elem_const_id = GetLocalConstantId(resolver, inst.element_type_id);
  2322. if (resolver.HasNewWork()) {
  2323. return ResolveResult::Retry();
  2324. }
  2325. return ResolveAs<SemIR::UnboundElementType>(
  2326. resolver,
  2327. {.type_id = SemIR::TypeType::SingletonTypeId,
  2328. .class_type_id =
  2329. resolver.local_context().GetTypeIdForTypeConstant(class_const_id),
  2330. .element_type_id =
  2331. resolver.local_context().GetTypeIdForTypeConstant(elem_const_id)});
  2332. }
  2333. // Tries to resolve the InstId, returning a canonical constant when ready, or
  2334. // Invalid if more has been added to the stack. This is the same as
  2335. // TryResolveInst, except that it may resolve symbolic constants as canonical
  2336. // constants instead of as constants associated with a particular generic.
  2337. //
  2338. // TODO: Consider refactoring the body to a helper in order to eliminate
  2339. // recursion.
  2340. // NOLINTNEXTLINE(misc-no-recursion)
  2341. static auto TryResolveInstCanonical(ImportRefResolver& resolver,
  2342. SemIR::InstId inst_id,
  2343. SemIR::ConstantId const_id)
  2344. -> ResolveResult {
  2345. if (SemIR::IsSingletonInstId(inst_id)) {
  2346. CARBON_CHECK(!const_id.is_valid());
  2347. // Constants for builtins can be directly copied.
  2348. return ResolveResult::Done(resolver.local_constant_values().Get(inst_id));
  2349. }
  2350. auto untyped_inst = resolver.import_insts().Get(inst_id);
  2351. CARBON_KIND_SWITCH(untyped_inst) {
  2352. case CARBON_KIND(SemIR::AdaptDecl inst): {
  2353. return TryResolveTypedInst(resolver, inst, inst_id);
  2354. }
  2355. case CARBON_KIND(SemIR::ArrayType inst): {
  2356. return TryResolveTypedInst(resolver, inst);
  2357. }
  2358. case CARBON_KIND(SemIR::AssociatedConstantDecl inst): {
  2359. return TryResolveTypedInst(resolver, inst, inst_id);
  2360. }
  2361. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  2362. return TryResolveTypedInst(resolver, inst);
  2363. }
  2364. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  2365. return TryResolveTypedInst(resolver, inst);
  2366. }
  2367. case CARBON_KIND(SemIR::BaseDecl inst): {
  2368. return TryResolveTypedInst(resolver, inst, inst_id);
  2369. }
  2370. case CARBON_KIND(SemIR::BindAlias inst): {
  2371. return TryResolveTypedInst(resolver, inst);
  2372. }
  2373. case SemIR::BindName::Kind: {
  2374. // TODO: Should we be resolving BindNames at all?
  2375. return ResolveResult::Done(SemIR::ConstantId::NotConstant);
  2376. }
  2377. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  2378. return TryResolveTypedInst(resolver, inst);
  2379. }
  2380. case CARBON_KIND(SemIR::BoundMethod inst): {
  2381. return TryResolveTypedInst(resolver, inst);
  2382. }
  2383. case CARBON_KIND(SemIR::Call inst): {
  2384. return TryResolveTypedInst(resolver, inst);
  2385. }
  2386. case CARBON_KIND(SemIR::ClassDecl inst): {
  2387. return TryResolveTypedInst(resolver, inst, const_id);
  2388. }
  2389. case CARBON_KIND(SemIR::ClassType inst): {
  2390. return TryResolveTypedInst(resolver, inst);
  2391. }
  2392. case CARBON_KIND(SemIR::CompleteTypeWitness inst): {
  2393. return TryResolveTypedInst(resolver, inst);
  2394. }
  2395. case CARBON_KIND(SemIR::ConstType inst): {
  2396. return TryResolveTypedInst(resolver, inst);
  2397. }
  2398. case CARBON_KIND(SemIR::ExportDecl inst): {
  2399. return TryResolveTypedInst(resolver, inst);
  2400. }
  2401. case CARBON_KIND(SemIR::FacetAccessType inst): {
  2402. return TryResolveTypedInst(resolver, inst);
  2403. }
  2404. case CARBON_KIND(SemIR::FacetAccessWitness inst): {
  2405. return TryResolveTypedInst(resolver, inst);
  2406. }
  2407. case CARBON_KIND(SemIR::FacetType inst): {
  2408. return TryResolveTypedInst(resolver, inst);
  2409. }
  2410. case CARBON_KIND(SemIR::FacetValue inst): {
  2411. return TryResolveTypedInst(resolver, inst);
  2412. }
  2413. case CARBON_KIND(SemIR::FieldDecl inst): {
  2414. return TryResolveTypedInst(resolver, inst, inst_id);
  2415. }
  2416. case CARBON_KIND(SemIR::FunctionDecl inst): {
  2417. return TryResolveTypedInst(resolver, inst, const_id);
  2418. }
  2419. case CARBON_KIND(SemIR::FunctionType inst): {
  2420. return TryResolveTypedInst(resolver, inst);
  2421. }
  2422. case CARBON_KIND(SemIR::GenericClassType inst): {
  2423. return TryResolveTypedInst(resolver, inst);
  2424. }
  2425. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  2426. return TryResolveTypedInst(resolver, inst);
  2427. }
  2428. case CARBON_KIND(SemIR::ImplDecl inst): {
  2429. return TryResolveTypedInst(resolver, inst, const_id);
  2430. }
  2431. case CARBON_KIND(SemIR::ImplWitness inst): {
  2432. return TryResolveTypedInst(resolver, inst);
  2433. }
  2434. case CARBON_KIND(SemIR::ImplWitnessAccess inst): {
  2435. return TryResolveTypedInst(resolver, inst);
  2436. }
  2437. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  2438. return TryResolveTypedInst(resolver, inst, inst_id);
  2439. }
  2440. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  2441. return TryResolveTypedInst(resolver, inst, const_id);
  2442. }
  2443. case CARBON_KIND(SemIR::IntValue inst): {
  2444. return TryResolveTypedInst(resolver, inst);
  2445. }
  2446. case CARBON_KIND(SemIR::IntType inst): {
  2447. return TryResolveTypedInst(resolver, inst);
  2448. }
  2449. case CARBON_KIND(SemIR::Namespace inst): {
  2450. return TryResolveTypedInst(resolver, inst, inst_id);
  2451. }
  2452. case CARBON_KIND(SemIR::PointerType inst): {
  2453. return TryResolveTypedInst(resolver, inst);
  2454. }
  2455. case CARBON_KIND(SemIR::RequireCompleteType inst): {
  2456. return TryResolveTypedInst(resolver, inst);
  2457. }
  2458. case CARBON_KIND(SemIR::SpecificFunction inst): {
  2459. return TryResolveTypedInst(resolver, inst);
  2460. }
  2461. case CARBON_KIND(SemIR::SymbolicBindingPattern inst): {
  2462. return TryResolveTypedInst(resolver, inst);
  2463. }
  2464. case CARBON_KIND(SemIR::StructType inst): {
  2465. return TryResolveTypedInst(resolver, inst);
  2466. }
  2467. case CARBON_KIND(SemIR::StructValue inst): {
  2468. return TryResolveTypedInst(resolver, inst);
  2469. }
  2470. case CARBON_KIND(SemIR::TupleType inst): {
  2471. return TryResolveTypedInst(resolver, inst);
  2472. }
  2473. case CARBON_KIND(SemIR::TupleValue inst): {
  2474. return TryResolveTypedInst(resolver, inst);
  2475. }
  2476. case CARBON_KIND(SemIR::UnboundElementType inst): {
  2477. return TryResolveTypedInst(resolver, inst);
  2478. }
  2479. case CARBON_KIND(SemIR::Vtable inst): {
  2480. return TryResolveTypedInst(resolver, inst);
  2481. }
  2482. default: {
  2483. // This instruction might have a constant value of a different kind.
  2484. auto constant_inst_id =
  2485. resolver.import_constant_values().GetConstantInstId(inst_id);
  2486. if (constant_inst_id == inst_id) {
  2487. resolver.local_context().TODO(
  2488. SemIR::LocId(AddImportIRInst(resolver, inst_id)),
  2489. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  2490. return {.const_id = SemIR::ErrorInst::SingletonConstantId};
  2491. }
  2492. // Try to resolve the constant value instead. Note that this can only
  2493. // retry once.
  2494. CARBON_DCHECK(resolver.import_constant_values().GetConstantInstId(
  2495. constant_inst_id) == constant_inst_id,
  2496. "Constant value of constant instruction should refer to "
  2497. "the same instruction");
  2498. return TryResolveInstCanonical(resolver, constant_inst_id, const_id);
  2499. }
  2500. }
  2501. }
  2502. // Tries to resolve the InstId, returning a constant when ready, or Invalid if
  2503. // more has been added to the stack. A similar API is followed for all
  2504. // following TryResolveTypedInst helper functions.
  2505. //
  2506. // `const_id` is Invalid unless we've tried to resolve this instruction
  2507. // before, in which case it's the previous result.
  2508. //
  2509. // TODO: Error is returned when support is missing, but that should go away.
  2510. static auto TryResolveInst(ImportRefResolver& resolver, SemIR::InstId inst_id,
  2511. SemIR::ConstantId const_id) -> ResolveResult {
  2512. auto inst_const_id = resolver.import_constant_values().Get(inst_id);
  2513. if (!inst_const_id.is_valid() || !inst_const_id.is_symbolic()) {
  2514. return TryResolveInstCanonical(resolver, inst_id, const_id);
  2515. }
  2516. // Try to import the generic. This might add new work.
  2517. const auto& symbolic_const =
  2518. resolver.import_constant_values().GetSymbolicConstant(inst_const_id);
  2519. auto generic_const_id =
  2520. GetLocalConstantId(resolver, symbolic_const.generic_id);
  2521. auto inner_const_id = SemIR::ConstantId::Invalid;
  2522. if (const_id.is_valid()) {
  2523. // For the third phase, extract the constant value that
  2524. // TryResolveInstCanonical produced previously.
  2525. inner_const_id = resolver.local_constant_values().Get(
  2526. resolver.local_constant_values().GetSymbolicConstant(const_id).inst_id);
  2527. }
  2528. // Import the constant and rebuild the symbolic constant data.
  2529. auto result = TryResolveInstCanonical(resolver, inst_id, inner_const_id);
  2530. if (!result.const_id.is_valid()) {
  2531. // First phase: TryResolveInstCanoncial needs a retry.
  2532. return result;
  2533. }
  2534. if (!const_id.is_valid()) {
  2535. // Second phase: we have created an abstract constant. Create a
  2536. // corresponding generic constant.
  2537. if (symbolic_const.generic_id.is_valid()) {
  2538. result.const_id = resolver.local_constant_values().AddSymbolicConstant(
  2539. {.inst_id =
  2540. resolver.local_constant_values().GetInstId(result.const_id),
  2541. .generic_id = GetLocalGenericId(resolver, generic_const_id),
  2542. .index = symbolic_const.index});
  2543. if (result.decl_id.is_valid()) {
  2544. // Overwrite the abstract symbolic constant given initially to the
  2545. // declaration with its final concrete symbolic value.
  2546. resolver.local_constant_values().Set(result.decl_id, result.const_id);
  2547. }
  2548. }
  2549. } else {
  2550. // Third phase: perform a consistency check and produce the constant we
  2551. // created in the second phase.
  2552. CARBON_CHECK(result.const_id == inner_const_id,
  2553. "Constant value changed in third phase.");
  2554. result.const_id = const_id;
  2555. }
  2556. return result;
  2557. }
  2558. // Resolves and returns the local contents for an imported instruction block
  2559. // of constant instructions.
  2560. static auto ResolveLocalInstBlockContents(ImportRefResolver& resolver,
  2561. SemIR::InstBlockId import_block_id)
  2562. -> llvm::SmallVector<SemIR::InstId> {
  2563. auto import_block = resolver.import_inst_blocks().Get(import_block_id);
  2564. llvm::SmallVector<SemIR::InstId> inst_ids;
  2565. inst_ids.reserve(import_block.size());
  2566. for (auto import_inst_id : import_block) {
  2567. inst_ids.push_back(resolver.local_constant_values().GetInstId(
  2568. resolver.ResolveOneInst(import_inst_id)));
  2569. }
  2570. return inst_ids;
  2571. }
  2572. // Resolves and returns a local eval block for a region of an imported
  2573. // generic.
  2574. static auto ResolveLocalEvalBlock(ImportRefResolver& resolver,
  2575. const SemIR::Generic& import_generic,
  2576. SemIR::GenericId generic_id,
  2577. SemIR::GenericInstIndex::Region region)
  2578. -> SemIR::InstBlockId {
  2579. auto import_block_id = import_generic.GetEvalBlock(region);
  2580. if (!import_block_id.is_valid()) {
  2581. return SemIR::InstBlockId::Invalid;
  2582. }
  2583. auto inst_ids = ResolveLocalInstBlockContents(resolver, import_block_id);
  2584. return RebuildGenericEvalBlock(resolver.local_context(), generic_id, region,
  2585. inst_ids);
  2586. }
  2587. // Fills in the remaining information in a partially-imported generic.
  2588. static auto FinishPendingGeneric(ImportRefResolver& resolver,
  2589. ImportContext::PendingGeneric pending)
  2590. -> void {
  2591. const auto& import_generic =
  2592. resolver.import_generics().Get(pending.import_id);
  2593. // Don't store the local generic between calls: the generics list can be
  2594. // reallocated by ResolveLocalEvalBlock importing more specifics.
  2595. auto decl_block_id =
  2596. ResolveLocalEvalBlock(resolver, import_generic, pending.local_id,
  2597. SemIR::GenericInstIndex::Region::Declaration);
  2598. resolver.local_generics().Get(pending.local_id).decl_block_id = decl_block_id;
  2599. auto local_decl_id = resolver.local_generics().Get(pending.local_id).decl_id;
  2600. auto self_specific_id = MakeSelfSpecific(resolver.local_context(),
  2601. local_decl_id, pending.local_id);
  2602. resolver.local_generics().Get(pending.local_id).self_specific_id =
  2603. self_specific_id;
  2604. resolver.AddPendingSpecific({.import_id = import_generic.self_specific_id,
  2605. .local_id = self_specific_id});
  2606. auto definition_block_id =
  2607. ResolveLocalEvalBlock(resolver, import_generic, pending.local_id,
  2608. SemIR::GenericInstIndex::Region::Definition);
  2609. resolver.local_generics().Get(pending.local_id).definition_block_id =
  2610. definition_block_id;
  2611. }
  2612. // Resolves and returns a local inst block of constant instructions
  2613. // corresponding to an imported inst block.
  2614. static auto ResolveLocalInstBlock(ImportRefResolver& resolver,
  2615. SemIR::InstBlockId import_block_id)
  2616. -> SemIR::InstBlockId {
  2617. if (!import_block_id.is_valid()) {
  2618. return SemIR::InstBlockId::Invalid;
  2619. }
  2620. auto inst_ids = ResolveLocalInstBlockContents(resolver, import_block_id);
  2621. return resolver.local_inst_blocks().Add(inst_ids);
  2622. }
  2623. // Fills in the remaining information in a partially-imported specific.
  2624. static auto FinishPendingSpecific(ImportRefResolver& resolver,
  2625. ImportContext::PendingSpecific pending)
  2626. -> void {
  2627. const auto& import_specific =
  2628. resolver.import_specifics().Get(pending.import_id);
  2629. // Don't store the local specific between calls: the specifics list can be
  2630. // reallocated by ResolveLocalInstBlock importing more specifics.
  2631. if (!resolver.local_specifics()
  2632. .Get(pending.local_id)
  2633. .decl_block_id.is_valid()) {
  2634. auto decl_block_id =
  2635. ResolveLocalInstBlock(resolver, import_specific.decl_block_id);
  2636. resolver.local_specifics().Get(pending.local_id).decl_block_id =
  2637. decl_block_id;
  2638. }
  2639. if (!resolver.local_specifics()
  2640. .Get(pending.local_id)
  2641. .definition_block_id.is_valid() &&
  2642. import_specific.definition_block_id.is_valid()) {
  2643. auto definition_block_id =
  2644. ResolveLocalInstBlock(resolver, import_specific.definition_block_id);
  2645. resolver.local_specifics().Get(pending.local_id).definition_block_id =
  2646. definition_block_id;
  2647. }
  2648. }
  2649. // Perform any work that we deferred until the end of the main Resolve loop.
  2650. auto ImportRefResolver::PerformPendingWork() -> void {
  2651. // Note that the individual Finish steps can add new pending work, so keep
  2652. // going until we have no more work to do.
  2653. while (!pending_generics().empty() || !pending_specifics().empty()) {
  2654. // Process generics in the order that we added them because a later
  2655. // generic might refer to an earlier one, and the calls to
  2656. // RebuildGenericEvalBlock assume that the reachable SemIR is in a valid
  2657. // state.
  2658. // TODO: Import the generic eval block rather than calling
  2659. // RebuildGenericEvalBlock to rebuild it so that order doesn't matter.
  2660. // NOLINTNEXTLINE(modernize-loop-convert)
  2661. for (size_t i = 0; i != pending_generics().size(); ++i) {
  2662. FinishPendingGeneric(*this, pending_generics()[i]);
  2663. }
  2664. pending_generics().clear();
  2665. while (!pending_specifics().empty()) {
  2666. FinishPendingSpecific(*this, pending_specifics().pop_back_val());
  2667. }
  2668. }
  2669. }
  2670. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  2671. // loaded (including the one pointed at directly by the ImportRef), and the
  2672. // final instruction's type ID.
  2673. //
  2674. // This addresses cases where an ImportRefUnloaded may point at another
  2675. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  2676. // constant-evaluated version of the instruction to work with.
  2677. static auto GetInstForLoad(Context& context,
  2678. SemIR::ImportIRInstId import_ir_inst_id)
  2679. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  2680. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  2681. {}, SemIR::TypeId::Invalid};
  2682. auto& [import_ir_insts, type_id] = result;
  2683. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  2684. // The first ImportIRInst is added directly because the IR doesn't need to be
  2685. // localized.
  2686. import_ir_insts.push_back(import_ir_inst);
  2687. const auto* cursor_ir = context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  2688. while (true) {
  2689. auto cursor_inst = cursor_ir->insts().Get(import_ir_inst.inst_id);
  2690. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  2691. if (!import_ref) {
  2692. type_id = cursor_inst.type_id();
  2693. return result;
  2694. }
  2695. import_ir_inst =
  2696. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  2697. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  2698. import_ir_insts.push_back(
  2699. {.ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  2700. .is_export = false,
  2701. .sem_ir = cursor_ir}),
  2702. .inst_id = import_ir_inst.inst_id});
  2703. }
  2704. }
  2705. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  2706. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  2707. if (!inst) {
  2708. return;
  2709. }
  2710. auto [indirect_insts, load_type_id] =
  2711. GetInstForLoad(context, inst->import_ir_inst_id);
  2712. // The last indirect instruction is the one to resolve. Pop it here because
  2713. // Resolve will assign the constant.
  2714. auto load_ir_inst = indirect_insts.pop_back_val();
  2715. ImportRefResolver resolver(context, load_ir_inst.ir_id);
  2716. // The resolver calls into Context to create instructions. Don't register
  2717. // those instructions as part of the enclosing generic scope if they're
  2718. // dependent on a generic parameter.
  2719. context.generic_region_stack().Push();
  2720. auto type_id = resolver.ResolveType(load_type_id);
  2721. auto constant_id = resolver.Resolve(load_ir_inst.inst_id);
  2722. context.generic_region_stack().Pop();
  2723. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  2724. // doesn't use ReplaceInstBeforeConstantUse because it would trigger
  2725. // TryEvalInst, which we want to avoid with ImportRefs.
  2726. context.sem_ir().insts().Set(
  2727. inst_id,
  2728. SemIR::ImportRefLoaded{.type_id = type_id,
  2729. .import_ir_inst_id = inst->import_ir_inst_id,
  2730. .entity_name_id = inst->entity_name_id});
  2731. // Store the constant for both the ImportRefLoaded and indirect instructions.
  2732. context.constant_values().Set(inst_id, constant_id);
  2733. for (const auto& import_ir_inst : indirect_insts) {
  2734. context.import_ir_constant_values()[import_ir_inst.ir_id.index].Set(
  2735. import_ir_inst.inst_id, constant_id);
  2736. }
  2737. }
  2738. auto ImportImplsFromApiFile(Context& context) -> void {
  2739. SemIR::ImportIRId import_ir_id = SemIR::ImportIRId::ApiForImpl;
  2740. auto& import_ir = context.import_irs().Get(import_ir_id);
  2741. if (!import_ir.sem_ir) {
  2742. return;
  2743. }
  2744. for (auto impl_index : llvm::seq(import_ir.sem_ir->impls().size())) {
  2745. SemIR::ImplId impl_id(impl_index);
  2746. // Resolve the imported impl to a local impl ID.
  2747. ImportImpl(context, import_ir_id, impl_id);
  2748. }
  2749. }
  2750. auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  2751. SemIR::ImplId impl_id) -> void {
  2752. ImportRefResolver resolver(context, import_ir_id);
  2753. context.generic_region_stack().Push();
  2754. resolver.Resolve(context.import_irs()
  2755. .Get(import_ir_id)
  2756. .sem_ir->impls()
  2757. .Get(impl_id)
  2758. .first_decl_id());
  2759. context.generic_region_stack().Pop();
  2760. }
  2761. } // namespace Carbon::Check