import_ref.cpp 179 KB

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