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