import_ref.cpp 140 KB

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