import_ref.cpp 154 KB

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