import_ref.cpp 138 KB

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