import_ref.cpp 142 KB

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