import_ref.cpp 139 KB

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