import_ref.cpp 143 KB

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