import_ref.cpp 177 KB

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