import_ref.cpp 119 KB

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