import_ref.cpp 193 KB

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