import_ref.cpp 141 KB

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