import_ref.cpp 161 KB

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