import_ref.cpp 174 KB

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