import_ref.cpp 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070
  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/typed_insts.h"
  18. namespace Carbon::Check {
  19. // Adds the ImportIR, excluding the update to the check_ir_map.
  20. static auto InternalAddImportIR(Context& context, SemIR::ImportIR import_ir)
  21. -> SemIR::ImportIRId {
  22. context.import_ir_constant_values().push_back(
  23. SemIR::ConstantValueStore(SemIR::ConstantId::Invalid));
  24. return context.import_irs().Add(import_ir);
  25. }
  26. auto SetApiImportIR(Context& context, SemIR::ImportIR import_ir) -> void {
  27. auto ir_id = SemIR::ImportIRId::Invalid;
  28. if (import_ir.sem_ir != nullptr) {
  29. ir_id = AddImportIR(context, import_ir);
  30. } else {
  31. // We don't have a check_ir_id, so add without touching check_ir_map.
  32. ir_id = InternalAddImportIR(context, import_ir);
  33. }
  34. CARBON_CHECK(ir_id == SemIR::ImportIRId::ApiForImpl)
  35. << "ApiForImpl must be the first IR";
  36. }
  37. auto AddImportIR(Context& context, SemIR::ImportIR import_ir)
  38. -> SemIR::ImportIRId {
  39. auto& ir_id = context.GetImportIRId(*import_ir.sem_ir);
  40. if (!ir_id.is_valid()) {
  41. // Note this updates check_ir_map.
  42. ir_id = InternalAddImportIR(context, import_ir);
  43. } else if (import_ir.is_export) {
  44. // We're processing an `export import`. In case the IR was indirectly added
  45. // as a non-export, mark it as an export.
  46. context.import_irs().Get(ir_id).is_export = true;
  47. }
  48. return ir_id;
  49. }
  50. auto AddImportRef(Context& context, SemIR::ImportIRInst import_ir_inst,
  51. SemIR::EntityNameId entity_name_id) -> SemIR::InstId {
  52. auto import_ir_inst_id = context.import_ir_insts().Add(import_ir_inst);
  53. SemIR::ImportRefUnloaded inst = {.import_ir_inst_id = import_ir_inst_id,
  54. .entity_name_id = entity_name_id};
  55. auto import_ref_id = context.AddPlaceholderInstInNoBlock(
  56. SemIR::LocIdAndInst(import_ir_inst_id, inst));
  57. // ImportRefs have a dedicated block because this may be called during
  58. // processing where the instruction shouldn't be inserted in the current inst
  59. // block.
  60. context.import_ref_ids().push_back(import_ref_id);
  61. return import_ref_id;
  62. }
  63. auto GetCanonicalImportIRInst(Context& context, const SemIR::File* cursor_ir,
  64. SemIR::InstId cursor_inst_id)
  65. -> SemIR::ImportIRInst {
  66. while (true) {
  67. auto inst = cursor_ir->insts().Get(cursor_inst_id);
  68. CARBON_KIND_SWITCH(inst) {
  69. case CARBON_KIND(SemIR::ExportDecl bind_export): {
  70. cursor_inst_id = bind_export.value_id;
  71. continue;
  72. }
  73. case SemIR::ImportRefLoaded::Kind:
  74. case SemIR::ImportRefUnloaded::Kind: {
  75. auto import_ref = inst.As<SemIR::AnyImportRef>();
  76. auto import_ir_inst =
  77. cursor_ir->import_ir_insts().Get(import_ref.import_ir_inst_id);
  78. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  79. cursor_inst_id = import_ir_inst.inst_id;
  80. continue;
  81. }
  82. default: {
  83. auto ir_id = SemIR::ImportIRId::Invalid;
  84. if (cursor_ir != &context.sem_ir()) {
  85. // This uses AddImportIR in case it was indirectly found, which can
  86. // happen with two or more steps of exports.
  87. ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  88. .is_export = false,
  89. .sem_ir = cursor_ir});
  90. }
  91. return {.ir_id = ir_id, .inst_id = cursor_inst_id};
  92. }
  93. }
  94. }
  95. }
  96. auto VerifySameCanonicalImportIRInst(Context& context, SemIR::InstId prev_id,
  97. SemIR::ImportIRInst prev_import_ir_inst,
  98. SemIR::ImportIRId new_ir_id,
  99. const SemIR::File* new_import_ir,
  100. SemIR::InstId new_inst_id) -> void {
  101. auto new_import_ir_inst =
  102. GetCanonicalImportIRInst(context, new_import_ir, new_inst_id);
  103. if (new_import_ir_inst == prev_import_ir_inst) {
  104. return;
  105. }
  106. auto conflict_id =
  107. AddImportRef(context, {.ir_id = new_ir_id, .inst_id = new_inst_id},
  108. SemIR::EntityNameId::Invalid);
  109. context.DiagnoseDuplicateName(conflict_id, prev_id);
  110. }
  111. // Returns an instruction that has the specified constant value.
  112. static auto GetInstWithConstantValue(const SemIR::File& file,
  113. SemIR::ConstantId const_id)
  114. -> SemIR::InstId {
  115. if (!const_id.is_valid()) {
  116. return SemIR::InstId::Invalid;
  117. }
  118. // For template constants, the corresponding instruction has the desired
  119. // constant value.
  120. if (!const_id.is_symbolic()) {
  121. return file.constant_values().GetInstId(const_id);
  122. }
  123. // For abstract symbolic constants, the corresponding instruction has the
  124. // desired constant value.
  125. const auto& symbolic_const =
  126. file.constant_values().GetSymbolicConstant(const_id);
  127. if (!symbolic_const.generic_id.is_valid()) {
  128. return file.constant_values().GetInstId(const_id);
  129. }
  130. // For a symbolic constant in a generic, pick the corresponding instruction
  131. // out of the eval block for the generic.
  132. const auto& generic = file.generics().Get(symbolic_const.generic_id);
  133. auto block = generic.GetEvalBlock(symbolic_const.index.region());
  134. return file.inst_blocks().Get(block)[symbolic_const.index.index()];
  135. }
  136. // Resolves an instruction from an imported IR into a constant referring to the
  137. // current IR.
  138. //
  139. // Calling Resolve on an instruction operates in an iterative manner, tracking
  140. // Work items on work_stack_. At a high level, the loop is:
  141. //
  142. // 1. If a constant value is already known for the work item and was not set by
  143. // this work item, it's considered resolved.
  144. // - The constant check avoids performance costs of deduplication on add.
  145. // - If we've processed this work item before, then we now process it again.
  146. // It didn't complete last time, even though we have a constant value
  147. // already.
  148. //
  149. // 2. Resolve the instruction (TryResolveInst/TryResolveTypedInst). This is done
  150. // in three phases. The first and second phases can add work to the worklist
  151. // and end in a retry, in which case those phases will be rerun once the
  152. // added work is done. The rerun cannot also end in a retry, so this results
  153. // in at most three calls, but in practice one or two calls is almost always
  154. // sufficient. Due to the chance of a second or third call to TryResolveInst,
  155. // it's important to only perform expensive work once, even when the same
  156. // phase is rerun.
  157. //
  158. // - First phase:
  159. // - Gather all input constants necessary to form the constant value of the
  160. // instruction. Gathering constants directly adds unresolved values to
  161. // work_stack_.
  162. // - If HasNewWork() reports that any work was added, then return Retry():
  163. // this instruction needs another call to complete. Gather the
  164. // now-resolved constants and continue to the next step once the retry
  165. // happens.
  166. //
  167. // - Second phase:
  168. // - Build the constant value of the instruction.
  169. // - Gather all input constants necessary to finish importing the
  170. // instruction. This is only necessary for instructions like classes that
  171. // can be forward-declared. For these instructions, we first import the
  172. // constant value and then later import the rest of the declaration in
  173. // order to break cycles.
  174. // - If HasNewWork() reports that any work was added, then return
  175. // Retry(constant_value): this instruction needs another call to
  176. // complete. Gather the now-resolved constants and continue to the next
  177. // step once the retry happens.
  178. //
  179. // - Third phase:
  180. // - After the second phase, the constant value for the instruction is
  181. // already set, and will be passed back into TryResolve*Inst on retry. It
  182. // should not be created again.
  183. // - Fill in any remaining information to complete the import of the
  184. // instruction. For example, when importing a class declaration, build
  185. // the class scope and information about the definition.
  186. // - Return ResolveAs/ResolveAsConstant to finish the resolution process.
  187. // This will cause the Resolve loop to set a constant value if we didn't
  188. // retry at the end of the second phase.
  189. //
  190. // 3. If resolve didn't return Retry(), pop the work. Otherwise, it needs to
  191. // remain, and may no longer be at the top of the stack; update the state of
  192. // the work item to track what work still needs to be done.
  193. //
  194. // The same instruction can be enqueued for resolution multiple times. However,
  195. // we will only reach the second phase once: once a constant value is set, only
  196. // the resolution step that set it will retry.
  197. //
  198. // TODO: Fix class `extern` handling and merging, rewrite tests.
  199. // - check/testdata/class/cross_package_import.carbon
  200. // - check/testdata/class/extern.carbon
  201. // TODO: Fix function `extern` handling and merging, rewrite tests.
  202. // - check/testdata/function/declaration/import.carbon
  203. // - check/testdata/packages/cross_package_import.carbon
  204. class ImportRefResolver {
  205. public:
  206. explicit ImportRefResolver(Context& context, SemIR::ImportIRId import_ir_id)
  207. : context_(context),
  208. import_ir_id_(import_ir_id),
  209. import_ir_(*context_.import_irs().Get(import_ir_id).sem_ir) {}
  210. // Iteratively resolves an imported instruction's inner references until a
  211. // constant ID referencing the current IR is produced. See the class comment
  212. // for more details.
  213. auto ResolveOneInst(SemIR::InstId inst_id) -> SemIR::ConstantId {
  214. work_stack_.push_back({.inst_id = inst_id});
  215. while (!work_stack_.empty()) {
  216. auto work = work_stack_.back();
  217. CARBON_CHECK(work.inst_id.is_valid());
  218. // Step 1: check for a constant value.
  219. auto existing = FindResolvedConstId(work.inst_id);
  220. if (existing.const_id.is_valid() && !work.retry_with_constant_value) {
  221. work_stack_.pop_back();
  222. continue;
  223. }
  224. // Step 2: resolve the instruction.
  225. initial_work_ = work_stack_.size();
  226. auto [new_const_id, retry] =
  227. TryResolveInst(work.inst_id, existing.const_id);
  228. CARBON_CHECK(!existing.const_id.is_valid() ||
  229. existing.const_id == new_const_id)
  230. << "Constant value changed in third phase.";
  231. if (!existing.const_id.is_valid()) {
  232. SetResolvedConstId(work.inst_id, existing.indirect_insts, new_const_id);
  233. }
  234. // Step 3: pop or retry.
  235. if (retry) {
  236. work_stack_[initial_work_ - 1].retry_with_constant_value =
  237. new_const_id.is_valid();
  238. } else {
  239. work_stack_.pop_back();
  240. }
  241. }
  242. auto constant_id = import_ir_constant_values().Get(inst_id);
  243. CARBON_CHECK(constant_id.is_valid());
  244. return constant_id;
  245. }
  246. // Performs resolution for one instruction and then performs all work we
  247. // deferred.
  248. auto Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId {
  249. auto const_id = ResolveOneInst(inst_id);
  250. PerformPendingWork();
  251. return const_id;
  252. }
  253. // Wraps constant evaluation with logic to handle constants.
  254. auto ResolveConstant(SemIR::ConstantId import_const_id) -> SemIR::ConstantId {
  255. return Resolve(GetInstWithConstantValue(import_ir_, import_const_id));
  256. }
  257. // Wraps constant evaluation with logic to handle types.
  258. auto ResolveType(SemIR::TypeId import_type_id) -> SemIR::TypeId {
  259. if (!import_type_id.is_valid()) {
  260. return import_type_id;
  261. }
  262. auto import_type_const_id =
  263. import_ir_.types().GetConstantId(import_type_id);
  264. CARBON_CHECK(import_type_const_id.is_valid());
  265. if (auto import_type_inst_id =
  266. import_ir_.constant_values().GetInstId(import_type_const_id);
  267. import_type_inst_id.is_builtin()) {
  268. // Builtins don't require constant resolution; we can use them directly.
  269. return context_.GetBuiltinType(import_type_inst_id.builtin_inst_kind());
  270. } else {
  271. return context_.GetTypeIdForTypeConstant(
  272. ResolveConstant(import_type_id.AsConstantId()));
  273. }
  274. }
  275. private:
  276. // The result of attempting to resolve an imported instruction to a constant.
  277. struct ResolveResult {
  278. // The new constant value, if known.
  279. SemIR::ConstantId const_id;
  280. // Whether resolution has been attempted once and needs to be retried.
  281. bool retry = false;
  282. };
  283. // A step in work_stack_.
  284. struct Work {
  285. // The instruction to work on.
  286. SemIR::InstId inst_id;
  287. // Whether this work item set the constant value for the instruction and
  288. // requested a retry.
  289. bool retry_with_constant_value = false;
  290. };
  291. // The constant found by FindResolvedConstId.
  292. struct ResolvedConstId {
  293. // The constant for the instruction. Invalid if not yet resolved.
  294. SemIR::ConstantId const_id = SemIR::ConstantId::Invalid;
  295. // Instructions which are indirect but equivalent to the current instruction
  296. // being resolved, and should have their constant set to the same. Empty
  297. // when const_id is valid.
  298. llvm::SmallVector<SemIR::ImportIRInst> indirect_insts = {};
  299. };
  300. // Local information associated with an imported parameter.
  301. struct ParamData {
  302. SemIR::ConstantId type_const_id;
  303. SemIR::ConstantId bind_const_id;
  304. };
  305. // Local information associated with an imported generic.
  306. struct GenericData {
  307. llvm::SmallVector<SemIR::InstId> bindings;
  308. };
  309. // Local information associated with an imported specific.
  310. struct SpecificData {
  311. SemIR::ConstantId generic_const_id;
  312. llvm::SmallVector<SemIR::InstId> args;
  313. };
  314. // A generic that we have partially imported.
  315. struct PendingGeneric {
  316. SemIR::GenericId import_id;
  317. SemIR::GenericId local_id;
  318. };
  319. // A specific that we have partially imported.
  320. struct PendingSpecific {
  321. SemIR::SpecificId import_id;
  322. SemIR::SpecificId local_id;
  323. };
  324. // Looks to see if an instruction has been resolved. If a constant is only
  325. // found indirectly, sets the constant for any indirect steps that don't
  326. // already have the constant. If a constant isn't found, returns the indirect
  327. // instructions so that they can have the resolved constant assigned later.
  328. auto FindResolvedConstId(SemIR::InstId inst_id) -> ResolvedConstId {
  329. ResolvedConstId result;
  330. if (auto existing_const_id = import_ir_constant_values().Get(inst_id);
  331. existing_const_id.is_valid()) {
  332. result.const_id = existing_const_id;
  333. return result;
  334. }
  335. const auto* cursor_ir = &import_ir_;
  336. auto cursor_ir_id = SemIR::ImportIRId::Invalid;
  337. auto cursor_inst_id = inst_id;
  338. while (true) {
  339. auto loc_id = cursor_ir->insts().GetLocId(cursor_inst_id);
  340. if (!loc_id.is_import_ir_inst_id()) {
  341. return result;
  342. }
  343. auto ir_inst =
  344. cursor_ir->import_ir_insts().Get(loc_id.import_ir_inst_id());
  345. const auto* prev_ir = cursor_ir;
  346. auto prev_inst_id = cursor_inst_id;
  347. cursor_ir = cursor_ir->import_irs().Get(ir_inst.ir_id).sem_ir;
  348. cursor_ir_id = context_.GetImportIRId(*cursor_ir);
  349. if (!cursor_ir_id.is_valid()) {
  350. // TODO: Should we figure out a location to assign here?
  351. cursor_ir_id = AddImportIR(context_, {.decl_id = SemIR::InstId::Invalid,
  352. .is_export = false,
  353. .sem_ir = cursor_ir});
  354. }
  355. cursor_inst_id = ir_inst.inst_id;
  356. CARBON_CHECK(cursor_ir != prev_ir || cursor_inst_id != prev_inst_id)
  357. << cursor_ir->insts().Get(cursor_inst_id);
  358. if (auto const_id =
  359. context_.import_ir_constant_values()[cursor_ir_id.index].Get(
  360. cursor_inst_id);
  361. const_id.is_valid()) {
  362. SetResolvedConstId(inst_id, result.indirect_insts, const_id);
  363. result.const_id = const_id;
  364. result.indirect_insts.clear();
  365. return result;
  366. } else {
  367. result.indirect_insts.push_back(
  368. {.ir_id = cursor_ir_id, .inst_id = cursor_inst_id});
  369. }
  370. }
  371. }
  372. // Sets a resolved constant into the current and indirect instructions.
  373. auto SetResolvedConstId(SemIR::InstId inst_id,
  374. llvm::ArrayRef<SemIR::ImportIRInst> indirect_insts,
  375. SemIR::ConstantId const_id) -> void {
  376. import_ir_constant_values().Set(inst_id, const_id);
  377. for (auto indirect_inst : indirect_insts) {
  378. context_.import_ir_constant_values()[indirect_inst.ir_id.index].Set(
  379. indirect_inst.inst_id, const_id);
  380. }
  381. }
  382. // Returns true if new unresolved constants were found as part of this
  383. // `Resolve` step.
  384. auto HasNewWork() -> bool {
  385. CARBON_CHECK(initial_work_ <= work_stack_.size())
  386. << "Work shouldn't decrease";
  387. return initial_work_ < work_stack_.size();
  388. }
  389. auto AddImportIRInst(SemIR::InstId inst_id) -> SemIR::ImportIRInstId {
  390. return context_.import_ir_insts().Add(
  391. {.ir_id = import_ir_id_, .inst_id = inst_id});
  392. }
  393. // Returns the ConstantId for an InstId. Adds unresolved constants to
  394. // work_stack_.
  395. auto GetLocalConstantId(SemIR::InstId inst_id) -> SemIR::ConstantId {
  396. auto const_id = import_ir_constant_values().Get(inst_id);
  397. if (!const_id.is_valid()) {
  398. work_stack_.push_back({.inst_id = inst_id});
  399. }
  400. return const_id;
  401. }
  402. // Returns the ConstantId for an imported ConstantId. Adds unresolved
  403. // constants to work_stack_.
  404. auto GetLocalConstantId(SemIR::ConstantId const_id) -> SemIR::ConstantId {
  405. return GetLocalConstantId(GetInstWithConstantValue(import_ir_, const_id));
  406. }
  407. // Returns the local constant InstId for an imported InstId.
  408. auto GetLocalConstantInstId(SemIR::InstId inst_id) -> SemIR::InstId {
  409. auto const_id = import_ir_constant_values().Get(inst_id);
  410. if (!const_id.is_valid()) {
  411. work_stack_.push_back({.inst_id = inst_id});
  412. return SemIR::InstId::Invalid;
  413. }
  414. return context_.constant_values().GetInstId(const_id);
  415. }
  416. // Returns the ConstantId for a TypeId. Adds unresolved constants to
  417. // work_stack_.
  418. auto GetLocalConstantId(SemIR::TypeId type_id) -> SemIR::ConstantId {
  419. return GetLocalConstantId(import_ir_.types().GetConstantId(type_id));
  420. }
  421. // Gets the local constant values corresponding to an imported inst block.
  422. auto GetLocalInstBlockContents(SemIR::InstBlockId import_block_id)
  423. -> llvm::SmallVector<SemIR::InstId> {
  424. llvm::SmallVector<SemIR::InstId> inst_ids;
  425. if (!import_block_id.is_valid() ||
  426. import_block_id == SemIR::InstBlockId::Empty) {
  427. return inst_ids;
  428. }
  429. // Import all the values in the block.
  430. auto import_block = import_ir_.inst_blocks().Get(import_block_id);
  431. inst_ids.reserve(import_block.size());
  432. for (auto import_inst_id : import_block) {
  433. auto const_id = GetLocalConstantId(import_inst_id);
  434. inst_ids.push_back(context_.constant_values().GetInstIdIfValid(const_id));
  435. }
  436. return inst_ids;
  437. }
  438. // Gets a local instruction block ID corresponding to an imported inst block
  439. // whose contents were already imported, for example by
  440. // GetLocalInstBlockContents.
  441. auto GetLocalInstBlockId(SemIR::InstBlockId import_block_id,
  442. llvm::ArrayRef<SemIR::InstId> contents)
  443. -> SemIR::InstBlockId {
  444. if (!import_block_id.is_valid()) {
  445. return SemIR::InstBlockId::Invalid;
  446. }
  447. return context_.inst_blocks().Add(contents);
  448. }
  449. // Gets a local canonical instruction block ID corresponding to an imported
  450. // inst block whose contents were already imported, for example by
  451. // GetLocalInstBlockContents.
  452. auto GetLocalCanonicalInstBlockId(SemIR::InstBlockId import_block_id,
  453. llvm::ArrayRef<SemIR::InstId> contents)
  454. -> SemIR::InstBlockId {
  455. if (!import_block_id.is_valid()) {
  456. return SemIR::InstBlockId::Invalid;
  457. }
  458. return context_.inst_blocks().AddCanonical(contents);
  459. }
  460. // Gets an incomplete local version of an imported generic. Most fields are
  461. // set in the third phase.
  462. auto MakeIncompleteGeneric(SemIR::InstId decl_id, SemIR::GenericId generic_id)
  463. -> SemIR::GenericId {
  464. if (!generic_id.is_valid()) {
  465. return SemIR::GenericId::Invalid;
  466. }
  467. return context_.generics().Add(
  468. {.decl_id = decl_id,
  469. .bindings_id = SemIR::InstBlockId::Invalid,
  470. .self_specific_id = SemIR::SpecificId::Invalid});
  471. }
  472. // Gets a local version of the data associated with a generic.
  473. auto GetLocalGenericData(SemIR::GenericId generic_id) -> GenericData {
  474. if (!generic_id.is_valid()) {
  475. return GenericData();
  476. }
  477. const auto& generic = import_ir_.generics().Get(generic_id);
  478. return {.bindings = GetLocalInstBlockContents(generic.bindings_id)};
  479. }
  480. // Adds the given local generic data to the given generic.
  481. auto SetGenericData(SemIR::GenericId import_generic_id,
  482. SemIR::GenericId new_generic_id,
  483. const GenericData& generic_data) -> void {
  484. if (!import_generic_id.is_valid()) {
  485. return;
  486. }
  487. const auto& import_generic = import_ir_.generics().Get(import_generic_id);
  488. auto& new_generic = context_.generics().Get(new_generic_id);
  489. new_generic.bindings_id = GetLocalCanonicalInstBlockId(
  490. import_generic.bindings_id, generic_data.bindings);
  491. // Fill in the remaining information in FinishPendingGeneric.
  492. pending_generics_.push_back(
  493. {.import_id = import_generic_id, .local_id = new_generic_id});
  494. }
  495. // Gets a local constant value corresponding to an imported generic ID. May
  496. // add work to the work stack and return `Invalid`.
  497. auto GetLocalConstantId(SemIR::GenericId generic_id) -> SemIR::ConstantId {
  498. if (!generic_id.is_valid()) {
  499. return SemIR::ConstantId::Invalid;
  500. }
  501. return GetLocalConstantId(
  502. import_ir_.insts()
  503. .Get(import_ir_.generics().Get(generic_id).decl_id)
  504. .type_id());
  505. }
  506. // Gets a local generic ID given the corresponding local constant ID returned
  507. // by GetLocalConstantId for the imported generic. Does not add any new work.
  508. auto GetLocalGenericId(SemIR::ConstantId local_const_id) -> SemIR::GenericId {
  509. if (!local_const_id.is_valid()) {
  510. return SemIR::GenericId::Invalid;
  511. }
  512. auto type = context_.insts().Get(
  513. context_.constant_values().GetInstId(local_const_id));
  514. CARBON_KIND_SWITCH(type) {
  515. case CARBON_KIND(SemIR::FunctionType fn_type): {
  516. return context_.functions().Get(fn_type.function_id).generic_id;
  517. }
  518. case CARBON_KIND(SemIR::GenericClassType class_type): {
  519. return context_.classes().Get(class_type.class_id).generic_id;
  520. }
  521. case CARBON_KIND(SemIR::GenericInterfaceType interface_type): {
  522. return context_.interfaces()
  523. .Get(interface_type.interface_id)
  524. .generic_id;
  525. }
  526. default: {
  527. CARBON_FATAL() << "Unexpected type for generic declaration: " << type;
  528. }
  529. }
  530. }
  531. // Gets local information about an imported specific.
  532. auto GetLocalSpecificData(SemIR::SpecificId specific_id) -> SpecificData {
  533. if (!specific_id.is_valid()) {
  534. return {.generic_const_id = SemIR::ConstantId::Invalid, .args = {}};
  535. }
  536. const auto& specific = import_ir_.specifics().Get(specific_id);
  537. return {
  538. .generic_const_id = GetLocalConstantId(specific.generic_id),
  539. .args = GetLocalInstBlockContents(specific.args_id),
  540. };
  541. }
  542. // Gets a local specific whose data was already imported by
  543. // GetLocalSpecificData. Does not add any new work.
  544. auto GetOrAddLocalSpecific(SemIR::SpecificId import_specific_id,
  545. const SpecificData& data) -> SemIR::SpecificId {
  546. if (!import_specific_id.is_valid()) {
  547. return SemIR::SpecificId::Invalid;
  548. }
  549. // Form a corresponding local specific ID.
  550. const auto& import_specific =
  551. import_ir_.specifics().Get(import_specific_id);
  552. auto generic_id = GetLocalGenericId(data.generic_const_id);
  553. auto args_id =
  554. GetLocalCanonicalInstBlockId(import_specific.args_id, data.args);
  555. // Get the specific.
  556. auto specific_id = context_.specifics().GetOrAdd(generic_id, args_id);
  557. // Fill in the remaining information in FinishPendingSpecific, if necessary.
  558. auto& specific = context_.specifics().Get(specific_id);
  559. if (!specific.decl_block_id.is_valid() ||
  560. (import_specific.definition_block_id.is_valid() &&
  561. !specific.definition_block_id.is_valid())) {
  562. pending_specifics_.push_back(
  563. {.import_id = import_specific_id, .local_id = specific_id});
  564. }
  565. return specific_id;
  566. }
  567. // Returns the ConstantId for each parameter's type. Adds unresolved constants
  568. // to work_stack_.
  569. auto GetLocalParamConstantIds(SemIR::InstBlockId param_refs_id)
  570. -> llvm::SmallVector<ParamData> {
  571. llvm::SmallVector<ParamData> param_data;
  572. if (!param_refs_id.is_valid() ||
  573. param_refs_id == SemIR::InstBlockId::Empty) {
  574. return param_data;
  575. }
  576. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  577. param_data.reserve(param_refs.size());
  578. for (auto inst_id : param_refs) {
  579. auto type_const_id =
  580. GetLocalConstantId(import_ir_.insts().Get(inst_id).type_id());
  581. // If the parameter is a symbolic binding, build the BindSymbolicName
  582. // constant.
  583. auto bind_id = inst_id;
  584. auto bind_inst = import_ir_.insts().Get(bind_id);
  585. if (auto addr = bind_inst.TryAs<SemIR::AddrPattern>()) {
  586. bind_id = addr->inner_id;
  587. bind_inst = import_ir_.insts().Get(bind_id);
  588. }
  589. auto bind_const_id = bind_inst.Is<SemIR::BindSymbolicName>()
  590. ? GetLocalConstantId(bind_id)
  591. : SemIR::ConstantId::Invalid;
  592. param_data.push_back(
  593. {.type_const_id = type_const_id, .bind_const_id = bind_const_id});
  594. }
  595. return param_data;
  596. }
  597. // Given a param_refs_id and const_ids from GetLocalParamConstantIds, returns
  598. // a version of param_refs_id localized to the current IR.
  599. auto GetLocalParamRefsId(SemIR::InstBlockId param_refs_id,
  600. const llvm::SmallVector<ParamData>& params_data)
  601. -> SemIR::InstBlockId {
  602. if (!param_refs_id.is_valid() ||
  603. param_refs_id == SemIR::InstBlockId::Empty) {
  604. return param_refs_id;
  605. }
  606. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  607. llvm::SmallVector<SemIR::InstId> new_param_refs;
  608. for (auto [ref_id, param_data] : llvm::zip(param_refs, params_data)) {
  609. // Figure out the param structure. This echoes
  610. // Function::GetParamFromParamRefId.
  611. // TODO: Consider a different parameter handling to simplify import logic.
  612. auto inst = import_ir_.insts().Get(ref_id);
  613. auto addr_inst = inst.TryAs<SemIR::AddrPattern>();
  614. auto bind_id = ref_id;
  615. auto param_id = ref_id;
  616. if (addr_inst) {
  617. bind_id = addr_inst->inner_id;
  618. param_id = bind_id;
  619. inst = import_ir_.insts().Get(bind_id);
  620. }
  621. auto bind_inst = inst.TryAs<SemIR::AnyBindName>();
  622. if (bind_inst) {
  623. param_id = bind_inst->value_id;
  624. inst = import_ir_.insts().Get(param_id);
  625. }
  626. auto param_inst = inst.As<SemIR::Param>();
  627. // Rebuild the param instruction.
  628. auto name_id = GetLocalNameId(param_inst.name_id);
  629. auto type_id =
  630. context_.GetTypeIdForTypeConstant(param_data.type_const_id);
  631. auto new_param_id = context_.AddInstInNoBlock<SemIR::Param>(
  632. AddImportIRInst(param_id), {.type_id = type_id, .name_id = name_id});
  633. if (bind_inst) {
  634. switch (bind_inst->kind) {
  635. case SemIR::BindName::Kind: {
  636. auto entity_name_id = context_.entity_names().Add(
  637. {.name_id = name_id,
  638. .parent_scope_id = SemIR::NameScopeId::Invalid,
  639. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  640. new_param_id = context_.AddInstInNoBlock<SemIR::BindName>(
  641. AddImportIRInst(bind_id), {.type_id = type_id,
  642. .entity_name_id = entity_name_id,
  643. .value_id = new_param_id});
  644. break;
  645. }
  646. case SemIR::BindSymbolicName::Kind: {
  647. // We already imported a constant value for this symbolic binding.
  648. // We can reuse most of it, but update the value to point to our
  649. // specific parameter, and preserve the constant value.
  650. auto new_bind_inst =
  651. context_.insts().GetAs<SemIR::BindSymbolicName>(
  652. context_.constant_values().GetInstId(
  653. param_data.bind_const_id));
  654. new_bind_inst.value_id = new_param_id;
  655. new_param_id = context_.AddInstInNoBlock(AddImportIRInst(bind_id),
  656. new_bind_inst);
  657. context_.constant_values().Set(new_param_id,
  658. param_data.bind_const_id);
  659. break;
  660. }
  661. default: {
  662. CARBON_FATAL() << "Unexpected kind: " << bind_inst->kind;
  663. }
  664. }
  665. }
  666. if (addr_inst) {
  667. new_param_id = context_.AddInstInNoBlock<SemIR::AddrPattern>(
  668. AddImportIRInst(ref_id),
  669. {.type_id = type_id, .inner_id = new_param_id});
  670. }
  671. new_param_refs.push_back(new_param_id);
  672. }
  673. return context_.inst_blocks().Add(new_param_refs);
  674. }
  675. // Translates a NameId from the import IR to a local NameId.
  676. auto GetLocalNameId(SemIR::NameId import_name_id) -> SemIR::NameId {
  677. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.is_valid()) {
  678. return SemIR::NameId::ForIdentifier(
  679. context_.identifiers().Add(import_ir_.identifiers().Get(ident_id)));
  680. }
  681. return import_name_id;
  682. }
  683. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  684. // unresolved constants to the work stack.
  685. auto GetLocalNameScopeId(SemIR::NameScopeId name_scope_id)
  686. -> SemIR::NameScopeId {
  687. // Get the instruction that created the scope.
  688. auto [inst_id, inst] =
  689. import_ir_.name_scopes().GetInstIfValid(name_scope_id);
  690. if (!inst) {
  691. // Map scopes that aren't associated with an instruction to invalid
  692. // scopes. For now, such scopes aren't used, and we don't have a good way
  693. // to remap them.
  694. return SemIR::NameScopeId::Invalid;
  695. }
  696. // Get the constant value for the scope.
  697. auto const_id = SemIR::ConstantId::Invalid;
  698. CARBON_KIND_SWITCH(*inst) {
  699. case SemIR::ImplDecl::Kind:
  700. // TODO: Import the scope for an `impl` definition.
  701. return SemIR::NameScopeId::Invalid;
  702. case SemIR::Namespace::Kind:
  703. // If the namespace has already been imported, we can use its constant.
  704. // However, if it hasn't, we use Invalid instead of adding it to the
  705. // work stack. That's expected to be okay when resolving references.
  706. const_id = import_ir_constant_values().Get(inst_id);
  707. break;
  708. default:
  709. const_id = GetLocalConstantId(inst_id);
  710. }
  711. if (!const_id.is_valid()) {
  712. return SemIR::NameScopeId::Invalid;
  713. }
  714. auto const_inst_id = context_.constant_values().GetInstId(const_id);
  715. auto name_scope_inst = context_.insts().Get(const_inst_id);
  716. CARBON_KIND_SWITCH(name_scope_inst) {
  717. case CARBON_KIND(SemIR::Namespace inst): {
  718. return inst.name_scope_id;
  719. }
  720. case CARBON_KIND(SemIR::ClassType inst): {
  721. return context_.classes().Get(inst.class_id).scope_id;
  722. }
  723. case CARBON_KIND(SemIR::InterfaceType inst): {
  724. return context_.interfaces().Get(inst.interface_id).scope_id;
  725. }
  726. case SemIR::StructValue::Kind: {
  727. auto type_inst = context_.types().GetAsInst(name_scope_inst.type_id());
  728. CARBON_KIND_SWITCH(type_inst) {
  729. case CARBON_KIND(SemIR::GenericClassType inst): {
  730. return context_.classes().Get(inst.class_id).scope_id;
  731. }
  732. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  733. return context_.interfaces().Get(inst.interface_id).scope_id;
  734. }
  735. default: {
  736. break;
  737. }
  738. }
  739. break;
  740. }
  741. default: {
  742. if (const_inst_id == SemIR::InstId::BuiltinError) {
  743. return SemIR::NameScopeId::Invalid;
  744. }
  745. break;
  746. }
  747. }
  748. CARBON_FATAL() << "Unexpected instruction kind for name scope: "
  749. << name_scope_inst;
  750. }
  751. // Given an imported entity base, returns an incomplete, local version of it.
  752. //
  753. // Most fields are set in the third phase once they're imported. Import enough
  754. // of the parameter lists that we know whether this interface is a generic
  755. // interface and can build the right constant value for it.
  756. //
  757. // TODO: Support extern.
  758. // TODO: Add a better way to represent a generic prior to importing the
  759. // parameters.
  760. auto GetIncompleteLocalEntityBase(
  761. SemIR::InstId decl_id, const SemIR::EntityWithParamsBase& import_base)
  762. -> SemIR::EntityWithParamsBase {
  763. // Translate the extern_library_id if present.
  764. auto extern_library_id = SemIR::LibraryNameId::Invalid;
  765. if (import_base.extern_library_id.is_valid()) {
  766. if (import_base.extern_library_id.index >= 0) {
  767. auto val = import_ir_.string_literal_values().Get(
  768. import_base.extern_library_id.AsStringLiteralValueId());
  769. extern_library_id = SemIR::LibraryNameId::ForStringLiteralValueId(
  770. context_.string_literal_values().Add(val));
  771. } else {
  772. extern_library_id = import_base.extern_library_id;
  773. }
  774. }
  775. return {
  776. .name_id = GetLocalNameId(import_base.name_id),
  777. .parent_scope_id = SemIR::NameScopeId::Invalid,
  778. .generic_id = MakeIncompleteGeneric(decl_id, import_base.generic_id),
  779. .first_param_node_id = Parse::NodeId::Invalid,
  780. .last_param_node_id = Parse::NodeId::Invalid,
  781. .implicit_param_refs_id = import_base.implicit_param_refs_id.is_valid()
  782. ? SemIR::InstBlockId::Empty
  783. : SemIR::InstBlockId::Invalid,
  784. .param_refs_id = import_base.param_refs_id.is_valid()
  785. ? SemIR::InstBlockId::Empty
  786. : SemIR::InstBlockId::Invalid,
  787. .is_extern = import_base.is_extern,
  788. .extern_library_id = extern_library_id,
  789. .non_owning_decl_id = import_base.non_owning_decl_id.is_valid()
  790. ? decl_id
  791. : SemIR::InstId::Invalid,
  792. .first_owning_decl_id = import_base.first_owning_decl_id.is_valid()
  793. ? decl_id
  794. : SemIR::InstId::Invalid,
  795. };
  796. }
  797. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  798. // lookup.
  799. auto AddNameScopeImportRefs(const SemIR::NameScope& import_scope,
  800. SemIR::NameScope& new_scope) -> void {
  801. for (auto entry : import_scope.names) {
  802. auto ref_id = AddImportRef(
  803. context_, {.ir_id = import_ir_id_, .inst_id = entry.inst_id},
  804. SemIR::EntityNameId::Invalid);
  805. new_scope.AddRequired({.name_id = GetLocalNameId(entry.name_id),
  806. .inst_id = ref_id,
  807. .access_kind = entry.access_kind});
  808. }
  809. }
  810. // Given a block ID for a list of associated entities of a witness, returns a
  811. // version localized to the current IR.
  812. auto AddAssociatedEntities(SemIR::InstBlockId associated_entities_id)
  813. -> SemIR::InstBlockId {
  814. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  815. return SemIR::InstBlockId::Empty;
  816. }
  817. auto associated_entities =
  818. import_ir_.inst_blocks().Get(associated_entities_id);
  819. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  820. new_associated_entities.reserve(associated_entities.size());
  821. for (auto inst_id : associated_entities) {
  822. new_associated_entities.push_back(
  823. AddImportRef(context_, {.ir_id = import_ir_id_, .inst_id = inst_id},
  824. SemIR::EntityNameId::Invalid));
  825. }
  826. return context_.inst_blocks().Add(new_associated_entities);
  827. }
  828. // Tries to resolve the InstId, returning a constant when ready, or Invalid if
  829. // more has been added to the stack. A similar API is followed for all
  830. // following TryResolveTypedInst helper functions.
  831. //
  832. // `const_id` is Invalid unless we've tried to resolve this instruction
  833. // before, in which case it's the previous result.
  834. //
  835. // TODO: Error is returned when support is missing, but that should go away.
  836. auto TryResolveInst(SemIR::InstId inst_id, SemIR::ConstantId const_id)
  837. -> ResolveResult {
  838. auto inst_const_id = import_ir_.constant_values().Get(inst_id);
  839. if (!inst_const_id.is_valid() || !inst_const_id.is_symbolic()) {
  840. return TryResolveInstCanonical(inst_id, const_id);
  841. }
  842. // Try to import the generic. This might add new work.
  843. const auto& symbolic_const =
  844. import_ir_.constant_values().GetSymbolicConstant(inst_const_id);
  845. auto generic_const_id = GetLocalConstantId(symbolic_const.generic_id);
  846. auto inner_const_id = SemIR::ConstantId::Invalid;
  847. if (const_id.is_valid()) {
  848. // For the third phase, extract the constant value that
  849. // TryResolveInstCanonical produced previously.
  850. inner_const_id = context_.constant_values().Get(
  851. context_.constant_values().GetSymbolicConstant(const_id).inst_id);
  852. }
  853. // Import the constant and rebuild the symbolic constant data.
  854. auto result = TryResolveInstCanonical(inst_id, inner_const_id);
  855. if (!result.const_id.is_valid()) {
  856. // First phase: TryResolveInstCanoncial needs a retry.
  857. return result;
  858. }
  859. if (!const_id.is_valid()) {
  860. // Second phase: we have created an abstract constant. Create a
  861. // corresponding generic constant.
  862. if (symbolic_const.generic_id.is_valid()) {
  863. result.const_id = context_.constant_values().AddSymbolicConstant(
  864. {.inst_id = context_.constant_values().GetInstId(result.const_id),
  865. .generic_id = GetLocalGenericId(generic_const_id),
  866. .index = symbolic_const.index});
  867. }
  868. } else {
  869. // Third phase: perform a consistency check and produce the constant we
  870. // created in the second phase.
  871. CARBON_CHECK(result.const_id == inner_const_id)
  872. << "Constant value changed in third phase.";
  873. result.const_id = const_id;
  874. }
  875. return result;
  876. }
  877. // Tries to resolve the InstId, returning a canonical constant when ready, or
  878. // Invalid if more has been added to the stack. This is the same as
  879. // TryResolveInst, except that it may resolve symbolic constants as canonical
  880. // constants instead of as constants associated with a particular generic.
  881. auto TryResolveInstCanonical(SemIR::InstId inst_id,
  882. SemIR::ConstantId const_id) -> ResolveResult {
  883. if (inst_id.is_builtin()) {
  884. CARBON_CHECK(!const_id.is_valid());
  885. // Constants for builtins can be directly copied.
  886. return ResolveAsConstant(context_.constant_values().Get(inst_id));
  887. }
  888. auto untyped_inst = import_ir_.insts().Get(inst_id);
  889. CARBON_KIND_SWITCH(untyped_inst) {
  890. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  891. return TryResolveTypedInst(inst);
  892. }
  893. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  894. return TryResolveTypedInst(inst);
  895. }
  896. case CARBON_KIND(SemIR::BaseDecl inst): {
  897. return TryResolveTypedInst(inst, inst_id);
  898. }
  899. case CARBON_KIND(SemIR::BindAlias inst): {
  900. return TryResolveTypedInst(inst);
  901. }
  902. case SemIR::BindName::Kind: {
  903. // TODO: Should we be resolving BindNames at all?
  904. return ResolveAsConstant(SemIR::ConstantId::NotConstant);
  905. }
  906. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  907. return TryResolveTypedInst(inst);
  908. }
  909. case CARBON_KIND(SemIR::ClassDecl inst): {
  910. return TryResolveTypedInst(inst, const_id);
  911. }
  912. case CARBON_KIND(SemIR::ClassType inst): {
  913. return TryResolveTypedInst(inst);
  914. }
  915. case CARBON_KIND(SemIR::ConstType inst): {
  916. return TryResolveTypedInst(inst);
  917. }
  918. case CARBON_KIND(SemIR::ExportDecl inst): {
  919. return TryResolveTypedInst(inst);
  920. }
  921. case CARBON_KIND(SemIR::FieldDecl inst): {
  922. return TryResolveTypedInst(inst, inst_id);
  923. }
  924. case CARBON_KIND(SemIR::FunctionDecl inst): {
  925. return TryResolveTypedInst(inst, const_id);
  926. }
  927. case CARBON_KIND(SemIR::FunctionType inst): {
  928. return TryResolveTypedInst(inst);
  929. }
  930. case CARBON_KIND(SemIR::GenericClassType inst): {
  931. return TryResolveTypedInst(inst);
  932. }
  933. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  934. return TryResolveTypedInst(inst);
  935. }
  936. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  937. return TryResolveTypedInst(inst, inst_id);
  938. }
  939. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  940. return TryResolveTypedInst(inst, const_id);
  941. }
  942. case CARBON_KIND(SemIR::InterfaceWitness inst): {
  943. return TryResolveTypedInst(inst);
  944. }
  945. case CARBON_KIND(SemIR::InterfaceType inst): {
  946. return TryResolveTypedInst(inst);
  947. }
  948. case CARBON_KIND(SemIR::IntLiteral inst): {
  949. return TryResolveTypedInst(inst);
  950. }
  951. case CARBON_KIND(SemIR::PointerType inst): {
  952. return TryResolveTypedInst(inst);
  953. }
  954. case CARBON_KIND(SemIR::StructType inst): {
  955. return TryResolveTypedInst(inst, inst_id);
  956. }
  957. case CARBON_KIND(SemIR::StructValue inst): {
  958. return TryResolveTypedInst(inst);
  959. }
  960. case CARBON_KIND(SemIR::TupleType inst): {
  961. return TryResolveTypedInst(inst);
  962. }
  963. case CARBON_KIND(SemIR::TupleValue inst): {
  964. return TryResolveTypedInst(inst);
  965. }
  966. case CARBON_KIND(SemIR::UnboundElementType inst): {
  967. return TryResolveTypedInst(inst);
  968. }
  969. default:
  970. context_.TODO(
  971. SemIR::LocId(AddImportIRInst(inst_id)),
  972. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  973. return {.const_id = SemIR::ConstantId::Error};
  974. }
  975. }
  976. // Produces a resolve result that tries resolving this instruction again. If
  977. // `const_id` is specified, then this is the end of the second phase, and the
  978. // constant value will be passed to the next resolution attempt. Otherwise,
  979. // this is the end of the first phase.
  980. auto Retry(SemIR::ConstantId const_id = SemIR::ConstantId::Invalid)
  981. -> ResolveResult {
  982. CARBON_CHECK(HasNewWork());
  983. return {.const_id = const_id, .retry = true};
  984. }
  985. // Produces a resolve result that provides the given constant value. Requires
  986. // that there is no new work.
  987. auto ResolveAsConstant(SemIR::ConstantId const_id) -> ResolveResult {
  988. CARBON_CHECK(!HasNewWork());
  989. return {.const_id = const_id};
  990. }
  991. // Produces a resolve result that provides the given constant value. Retries
  992. // instead if work has been added.
  993. auto RetryOrResolveAsConstant(SemIR::ConstantId const_id) -> ResolveResult {
  994. if (HasNewWork()) {
  995. return Retry();
  996. }
  997. return ResolveAsConstant(const_id);
  998. }
  999. // Produces a resolve result for the given instruction that describes a
  1000. // constant value. This should only be used for instructions that describe
  1001. // constants, and not for instructions that represent declarations. For a
  1002. // declaration, we need an associated location, so AddInstInNoBlock should be
  1003. // used instead. Requires that there is no new work.
  1004. auto ResolveAsUntyped(SemIR::Inst inst) -> ResolveResult {
  1005. CARBON_CHECK(!HasNewWork());
  1006. auto result = TryEvalInst(context_, SemIR::InstId::Invalid, inst);
  1007. CARBON_CHECK(result.is_constant()) << inst << " is not constant";
  1008. return {.const_id = result};
  1009. }
  1010. // Same as ResolveAsUntyped, but with an explicit type for convenience.
  1011. template <typename InstT>
  1012. auto ResolveAs(InstT inst) -> ResolveResult {
  1013. return ResolveAsUntyped(inst);
  1014. }
  1015. auto TryResolveTypedInst(SemIR::AssociatedEntity inst) -> ResolveResult {
  1016. auto type_const_id = GetLocalConstantId(inst.type_id);
  1017. if (HasNewWork()) {
  1018. return Retry();
  1019. }
  1020. // Add a lazy reference to the target declaration.
  1021. auto decl_id = AddImportRef(
  1022. context_, {.ir_id = import_ir_id_, .inst_id = inst.decl_id},
  1023. SemIR::EntityNameId::Invalid);
  1024. return ResolveAs<SemIR::AssociatedEntity>(
  1025. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  1026. .index = inst.index,
  1027. .decl_id = decl_id});
  1028. }
  1029. auto TryResolveTypedInst(SemIR::AssociatedEntityType inst) -> ResolveResult {
  1030. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1031. auto entity_type_const_id = GetLocalConstantId(inst.entity_type_id);
  1032. auto interface_inst_id = GetLocalConstantId(inst.interface_type_id);
  1033. if (HasNewWork()) {
  1034. return Retry();
  1035. }
  1036. return ResolveAs<SemIR::AssociatedEntityType>(
  1037. {.type_id = SemIR::TypeId::TypeType,
  1038. .interface_type_id =
  1039. context_.GetTypeIdForTypeConstant(interface_inst_id),
  1040. .entity_type_id =
  1041. context_.GetTypeIdForTypeConstant(entity_type_const_id)});
  1042. }
  1043. auto TryResolveTypedInst(SemIR::BaseDecl inst, SemIR::InstId import_inst_id)
  1044. -> ResolveResult {
  1045. auto type_const_id = GetLocalConstantId(inst.type_id);
  1046. auto base_type_const_id = GetLocalConstantId(inst.base_type_id);
  1047. if (HasNewWork()) {
  1048. return Retry();
  1049. }
  1050. // Import the instruction in order to update contained base_type_id and
  1051. // track the import location.
  1052. auto inst_id = context_.AddInstInNoBlock<SemIR::BaseDecl>(
  1053. AddImportIRInst(import_inst_id),
  1054. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  1055. .base_type_id = context_.GetTypeIdForTypeConstant(base_type_const_id),
  1056. .index = inst.index});
  1057. return ResolveAsConstant(context_.constant_values().Get(inst_id));
  1058. }
  1059. auto TryResolveTypedInst(SemIR::BindAlias inst) -> ResolveResult {
  1060. auto value_id = GetLocalConstantId(inst.value_id);
  1061. return RetryOrResolveAsConstant(value_id);
  1062. }
  1063. auto TryResolveTypedInst(SemIR::BindSymbolicName inst) -> ResolveResult {
  1064. auto type_id = GetLocalConstantId(inst.type_id);
  1065. if (HasNewWork()) {
  1066. return Retry();
  1067. }
  1068. const auto& import_entity_name =
  1069. import_ir_.entity_names().Get(inst.entity_name_id);
  1070. auto name_id = GetLocalNameId(import_entity_name.name_id);
  1071. auto entity_name_id = context_.entity_names().Add(
  1072. {.name_id = name_id,
  1073. .parent_scope_id = SemIR::NameScopeId::Invalid,
  1074. .bind_index = import_entity_name.bind_index});
  1075. return ResolveAs<SemIR::BindSymbolicName>(
  1076. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1077. .entity_name_id = entity_name_id,
  1078. .value_id = SemIR::InstId::Invalid});
  1079. }
  1080. // Makes an incomplete class. This is necessary even with classes with a
  1081. // complete declaration, because things such as `Self` may refer back to the
  1082. // type.
  1083. auto MakeIncompleteClass(const SemIR::Class& import_class)
  1084. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  1085. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeId::TypeType,
  1086. .class_id = SemIR::ClassId::Invalid,
  1087. .decl_block_id = SemIR::InstBlockId::Empty};
  1088. auto class_decl_id =
  1089. context_.AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst(
  1090. AddImportIRInst(import_class.latest_decl_id()), class_decl));
  1091. // Regardless of whether ClassDecl is a complete type, we first need an
  1092. // incomplete type so that any references have something to point at.
  1093. class_decl.class_id = context_.classes().Add(
  1094. {GetIncompleteLocalEntityBase(class_decl_id, import_class),
  1095. {.self_type_id = SemIR::TypeId::Invalid,
  1096. .inheritance_kind = import_class.inheritance_kind}});
  1097. if (import_class.has_parameters()) {
  1098. class_decl.type_id = context_.GetGenericClassType(class_decl.class_id);
  1099. }
  1100. // Write the class ID into the ClassDecl.
  1101. context_.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  1102. auto self_const_id = context_.constant_values().Get(class_decl_id);
  1103. return {class_decl.class_id, self_const_id};
  1104. }
  1105. // Fills out the class definition for an incomplete class.
  1106. auto AddClassDefinition(const SemIR::Class& import_class,
  1107. SemIR::Class& new_class,
  1108. SemIR::ConstantId object_repr_const_id,
  1109. SemIR::InstId base_id) -> void {
  1110. new_class.definition_id = new_class.first_owning_decl_id;
  1111. new_class.object_repr_id =
  1112. context_.GetTypeIdForTypeConstant(object_repr_const_id);
  1113. new_class.scope_id = context_.name_scopes().Add(
  1114. new_class.first_owning_decl_id, SemIR::NameId::Invalid,
  1115. new_class.parent_scope_id);
  1116. auto& new_scope = context_.name_scopes().Get(new_class.scope_id);
  1117. const auto& import_scope =
  1118. import_ir_.name_scopes().Get(import_class.scope_id);
  1119. // Push a block so that we can add scoped instructions to it.
  1120. context_.inst_block_stack().Push();
  1121. AddNameScopeImportRefs(import_scope, new_scope);
  1122. new_class.body_block_id = context_.inst_block_stack().Pop();
  1123. if (import_class.base_id.is_valid()) {
  1124. new_class.base_id = base_id;
  1125. // Add the base scope to extended scopes.
  1126. auto base_inst_id = context_.types().GetInstId(
  1127. context_.insts()
  1128. .GetAs<SemIR::BaseDecl>(new_class.base_id)
  1129. .base_type_id);
  1130. const auto& base_class = context_.classes().Get(
  1131. context_.insts().GetAs<SemIR::ClassType>(base_inst_id).class_id);
  1132. new_scope.extended_scopes.push_back(base_class.scope_id);
  1133. }
  1134. CARBON_CHECK(new_scope.extended_scopes.size() ==
  1135. import_scope.extended_scopes.size());
  1136. }
  1137. auto TryResolveTypedInst(SemIR::ClassDecl inst,
  1138. SemIR::ConstantId class_const_id) -> ResolveResult {
  1139. // TODO: The handling of interfaces repeats a lot with the handling of
  1140. // classes, and will likely also be repeated for named constraints and
  1141. // choice types. Factor out some of this functionality.
  1142. const auto& import_class = import_ir_.classes().Get(inst.class_id);
  1143. SemIR::ClassId class_id = SemIR::ClassId::Invalid;
  1144. if (!class_const_id.is_valid()) {
  1145. if (HasNewWork()) {
  1146. // This is the end of the first phase. Don't make a new class yet if we
  1147. // already have new work.
  1148. return Retry();
  1149. }
  1150. // On the second phase, create a forward declaration of the class for any
  1151. // recursive references.
  1152. std::tie(class_id, class_const_id) = MakeIncompleteClass(import_class);
  1153. } else {
  1154. // On the third phase, compute the class ID from the constant
  1155. // value of the declaration.
  1156. auto class_const_inst = context_.insts().Get(
  1157. context_.constant_values().GetInstId(class_const_id));
  1158. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  1159. class_id = class_type->class_id;
  1160. } else {
  1161. auto generic_class_type =
  1162. context_.types().GetAs<SemIR::GenericClassType>(
  1163. class_const_inst.type_id());
  1164. class_id = generic_class_type.class_id;
  1165. }
  1166. }
  1167. // Load constants for the definition.
  1168. auto parent_scope_id = GetLocalNameScopeId(import_class.parent_scope_id);
  1169. auto implicit_param_const_ids =
  1170. GetLocalParamConstantIds(import_class.implicit_param_refs_id);
  1171. auto param_const_ids = GetLocalParamConstantIds(import_class.param_refs_id);
  1172. auto generic_data = GetLocalGenericData(import_class.generic_id);
  1173. auto self_const_id = GetLocalConstantId(import_class.self_type_id);
  1174. auto object_repr_const_id =
  1175. import_class.object_repr_id.is_valid()
  1176. ? GetLocalConstantId(import_class.object_repr_id)
  1177. : SemIR::ConstantId::Invalid;
  1178. auto base_id = import_class.base_id.is_valid()
  1179. ? GetLocalConstantInstId(import_class.base_id)
  1180. : SemIR::InstId::Invalid;
  1181. if (HasNewWork()) {
  1182. return Retry(class_const_id);
  1183. }
  1184. auto& new_class = context_.classes().Get(class_id);
  1185. new_class.parent_scope_id = parent_scope_id;
  1186. new_class.implicit_param_refs_id = GetLocalParamRefsId(
  1187. import_class.implicit_param_refs_id, implicit_param_const_ids);
  1188. new_class.param_refs_id =
  1189. GetLocalParamRefsId(import_class.param_refs_id, param_const_ids);
  1190. SetGenericData(import_class.generic_id, new_class.generic_id, generic_data);
  1191. new_class.self_type_id = context_.GetTypeIdForTypeConstant(self_const_id);
  1192. if (import_class.is_defined()) {
  1193. AddClassDefinition(import_class, new_class, object_repr_const_id,
  1194. base_id);
  1195. }
  1196. return ResolveAsConstant(class_const_id);
  1197. }
  1198. auto TryResolveTypedInst(SemIR::ClassType inst) -> ResolveResult {
  1199. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1200. auto class_const_id = GetLocalConstantId(
  1201. import_ir_.classes().Get(inst.class_id).first_owning_decl_id);
  1202. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1203. if (HasNewWork()) {
  1204. return Retry();
  1205. }
  1206. // Find the corresponding class type. For a non-generic class, this is the
  1207. // type of the class declaration. For a generic class, build a class type
  1208. // referencing this specialization of the generic class.
  1209. auto class_const_inst = context_.insts().Get(
  1210. context_.constant_values().GetInstId(class_const_id));
  1211. if (class_const_inst.Is<SemIR::ClassType>()) {
  1212. return ResolveAsConstant(class_const_id);
  1213. } else {
  1214. auto generic_class_type = context_.types().GetAs<SemIR::GenericClassType>(
  1215. class_const_inst.type_id());
  1216. auto specific_id = GetOrAddLocalSpecific(inst.specific_id, specific_data);
  1217. return ResolveAs<SemIR::ClassType>(
  1218. {.type_id = SemIR::TypeId::TypeType,
  1219. .class_id = generic_class_type.class_id,
  1220. .specific_id = specific_id});
  1221. }
  1222. }
  1223. auto TryResolveTypedInst(SemIR::ConstType inst) -> ResolveResult {
  1224. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1225. auto inner_const_id = GetLocalConstantId(inst.inner_id);
  1226. if (HasNewWork()) {
  1227. return Retry();
  1228. }
  1229. auto inner_type_id = context_.GetTypeIdForTypeConstant(inner_const_id);
  1230. return ResolveAs<SemIR::ConstType>(
  1231. {.type_id = SemIR::TypeId::TypeType, .inner_id = inner_type_id});
  1232. }
  1233. auto TryResolveTypedInst(SemIR::ExportDecl inst) -> ResolveResult {
  1234. auto value_id = GetLocalConstantId(inst.value_id);
  1235. return RetryOrResolveAsConstant(value_id);
  1236. }
  1237. auto TryResolveTypedInst(SemIR::FieldDecl inst, SemIR::InstId import_inst_id)
  1238. -> ResolveResult {
  1239. auto const_id = GetLocalConstantId(inst.type_id);
  1240. if (HasNewWork()) {
  1241. return Retry();
  1242. }
  1243. auto inst_id = context_.AddInstInNoBlock<SemIR::FieldDecl>(
  1244. AddImportIRInst(import_inst_id),
  1245. {.type_id = context_.GetTypeIdForTypeConstant(const_id),
  1246. .name_id = GetLocalNameId(inst.name_id),
  1247. .index = inst.index});
  1248. return {.const_id = context_.constant_values().Get(inst_id)};
  1249. }
  1250. // Make a declaration of a function. This is done as a separate step from
  1251. // importing the function declaration in order to resolve cycles.
  1252. auto MakeFunctionDecl(const SemIR::Function& import_function,
  1253. SemIR::SpecificId specific_id)
  1254. -> std::pair<SemIR::FunctionId, SemIR::ConstantId> {
  1255. SemIR::FunctionDecl function_decl = {
  1256. .type_id = SemIR::TypeId::Invalid,
  1257. .function_id = SemIR::FunctionId::Invalid,
  1258. .decl_block_id = SemIR::InstBlockId::Empty};
  1259. auto function_decl_id =
  1260. context_.AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst(
  1261. AddImportIRInst(import_function.first_decl_id()), function_decl));
  1262. // Start with an incomplete function.
  1263. function_decl.function_id = context_.functions().Add(
  1264. {GetIncompleteLocalEntityBase(function_decl_id, import_function),
  1265. {.return_storage_id = SemIR::InstId::Invalid,
  1266. .builtin_function_kind = import_function.builtin_function_kind}});
  1267. function_decl.type_id =
  1268. context_.GetFunctionType(function_decl.function_id, specific_id);
  1269. // Write the function ID and type into the FunctionDecl.
  1270. context_.ReplaceInstBeforeConstantUse(function_decl_id, function_decl);
  1271. return {function_decl.function_id,
  1272. context_.constant_values().Get(function_decl_id)};
  1273. }
  1274. auto TryResolveTypedInst(SemIR::FunctionDecl inst,
  1275. SemIR::ConstantId function_const_id)
  1276. -> ResolveResult {
  1277. const auto& import_function = import_ir_.functions().Get(inst.function_id);
  1278. SemIR::FunctionId function_id = SemIR::FunctionId::Invalid;
  1279. if (!function_const_id.is_valid()) {
  1280. auto import_specific_id = import_ir_.types()
  1281. .GetAs<SemIR::FunctionType>(inst.type_id)
  1282. .specific_id;
  1283. auto specific_data = GetLocalSpecificData(import_specific_id);
  1284. if (HasNewWork()) {
  1285. // This is the end of the first phase. Don't make a new function yet if
  1286. // we already have new work.
  1287. return Retry();
  1288. }
  1289. auto specific_id =
  1290. GetOrAddLocalSpecific(import_specific_id, specific_data);
  1291. // On the second phase, create a forward declaration of the interface.
  1292. std::tie(function_id, function_const_id) =
  1293. MakeFunctionDecl(import_function, specific_id);
  1294. } else {
  1295. // On the third phase, compute the function ID from the constant value of
  1296. // the declaration.
  1297. auto function_const_inst = context_.insts().Get(
  1298. context_.constant_values().GetInstId(function_const_id));
  1299. auto function_type = context_.types().GetAs<SemIR::FunctionType>(
  1300. function_const_inst.type_id());
  1301. function_id = function_type.function_id;
  1302. }
  1303. auto return_type_const_id = SemIR::ConstantId::Invalid;
  1304. if (import_function.return_storage_id.is_valid()) {
  1305. return_type_const_id = GetLocalConstantId(
  1306. import_ir_.insts().Get(import_function.return_storage_id).type_id());
  1307. }
  1308. auto parent_scope_id = GetLocalNameScopeId(import_function.parent_scope_id);
  1309. auto implicit_param_const_ids =
  1310. GetLocalParamConstantIds(import_function.implicit_param_refs_id);
  1311. auto param_const_ids =
  1312. GetLocalParamConstantIds(import_function.param_refs_id);
  1313. auto generic_data = GetLocalGenericData(import_function.generic_id);
  1314. if (HasNewWork()) {
  1315. return Retry(function_const_id);
  1316. }
  1317. // Add the function declaration.
  1318. auto& new_function = context_.functions().Get(function_id);
  1319. new_function.parent_scope_id = parent_scope_id;
  1320. new_function.implicit_param_refs_id = GetLocalParamRefsId(
  1321. import_function.implicit_param_refs_id, implicit_param_const_ids);
  1322. new_function.param_refs_id =
  1323. GetLocalParamRefsId(import_function.param_refs_id, param_const_ids);
  1324. SetGenericData(import_function.generic_id, new_function.generic_id,
  1325. generic_data);
  1326. if (import_function.return_storage_id.is_valid()) {
  1327. // Recreate the return slot from scratch.
  1328. // TODO: Once we import function definitions, we'll need to make sure we
  1329. // use the same return storage variable in the declaration and definition.
  1330. new_function.return_storage_id =
  1331. context_.AddInstInNoBlock<SemIR::VarStorage>(
  1332. AddImportIRInst(import_function.return_storage_id),
  1333. {.type_id =
  1334. context_.GetTypeIdForTypeConstant(return_type_const_id),
  1335. .name_id = SemIR::NameId::ReturnSlot});
  1336. }
  1337. if (import_function.definition_id.is_valid()) {
  1338. new_function.definition_id = new_function.first_owning_decl_id;
  1339. }
  1340. return ResolveAsConstant(function_const_id);
  1341. }
  1342. auto TryResolveTypedInst(SemIR::FunctionType inst) -> ResolveResult {
  1343. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1344. auto fn_val_id = GetLocalConstantInstId(
  1345. import_ir_.functions().Get(inst.function_id).first_decl_id());
  1346. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1347. if (HasNewWork()) {
  1348. return Retry();
  1349. }
  1350. auto fn_type_id = context_.insts().Get(fn_val_id).type_id();
  1351. return ResolveAs<SemIR::FunctionType>(
  1352. {.type_id = SemIR::TypeId::TypeType,
  1353. .function_id = context_.types()
  1354. .GetAs<SemIR::FunctionType>(fn_type_id)
  1355. .function_id,
  1356. .specific_id =
  1357. GetOrAddLocalSpecific(inst.specific_id, specific_data)});
  1358. }
  1359. auto TryResolveTypedInst(SemIR::GenericClassType inst) -> ResolveResult {
  1360. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1361. auto class_val_id = GetLocalConstantInstId(
  1362. import_ir_.classes().Get(inst.class_id).first_owning_decl_id);
  1363. if (HasNewWork()) {
  1364. return Retry();
  1365. }
  1366. auto class_val = context_.insts().Get(class_val_id);
  1367. CARBON_CHECK(
  1368. context_.types().Is<SemIR::GenericClassType>(class_val.type_id()));
  1369. return ResolveAsConstant(
  1370. context_.types().GetConstantId(class_val.type_id()));
  1371. }
  1372. auto TryResolveTypedInst(SemIR::GenericInterfaceType inst) -> ResolveResult {
  1373. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1374. auto interface_val_id = GetLocalConstantInstId(
  1375. import_ir_.interfaces().Get(inst.interface_id).first_owning_decl_id);
  1376. if (HasNewWork()) {
  1377. return Retry();
  1378. }
  1379. auto interface_val = context_.insts().Get(interface_val_id);
  1380. CARBON_CHECK(context_.types().Is<SemIR::GenericInterfaceType>(
  1381. interface_val.type_id()));
  1382. return ResolveAsConstant(
  1383. context_.types().GetConstantId(interface_val.type_id()));
  1384. }
  1385. auto TryResolveTypedInst(SemIR::ImportRefLoaded /*inst*/,
  1386. SemIR::InstId inst_id) -> ResolveResult {
  1387. // Return the constant for the instruction of the imported constant.
  1388. auto constant_id = import_ir_.constant_values().Get(inst_id);
  1389. if (!constant_id.is_valid()) {
  1390. return ResolveAsConstant(SemIR::ConstantId::Error);
  1391. }
  1392. if (!constant_id.is_constant()) {
  1393. context_.TODO(inst_id,
  1394. "Non-constant ImportRefLoaded (comes up with var)");
  1395. return ResolveAsConstant(SemIR::ConstantId::Error);
  1396. }
  1397. auto new_constant_id =
  1398. GetLocalConstantId(import_ir_.constant_values().GetInstId(constant_id));
  1399. return RetryOrResolveAsConstant(new_constant_id);
  1400. }
  1401. // Make a declaration of an interface. This is done as a separate step from
  1402. // importing the interface definition in order to resolve cycles.
  1403. auto MakeInterfaceDecl(const SemIR::Interface& import_interface)
  1404. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  1405. SemIR::InterfaceDecl interface_decl = {
  1406. .type_id = SemIR::TypeId::TypeType,
  1407. .interface_id = SemIR::InterfaceId::Invalid,
  1408. .decl_block_id = SemIR::InstBlockId::Empty};
  1409. auto interface_decl_id =
  1410. context_.AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst(
  1411. AddImportIRInst(import_interface.first_owning_decl_id),
  1412. interface_decl));
  1413. // Start with an incomplete interface.
  1414. interface_decl.interface_id = context_.interfaces().Add(
  1415. {GetIncompleteLocalEntityBase(interface_decl_id, import_interface),
  1416. {}});
  1417. if (import_interface.has_parameters()) {
  1418. interface_decl.type_id =
  1419. context_.GetGenericInterfaceType(interface_decl.interface_id);
  1420. }
  1421. // Write the interface ID into the InterfaceDecl.
  1422. context_.ReplaceInstBeforeConstantUse(interface_decl_id, interface_decl);
  1423. return {interface_decl.interface_id,
  1424. context_.constant_values().Get(interface_decl_id)};
  1425. }
  1426. // Imports the definition for an interface that has been imported as a forward
  1427. // declaration.
  1428. auto AddInterfaceDefinition(const SemIR::Interface& import_interface,
  1429. SemIR::Interface& new_interface,
  1430. SemIR::InstId self_param_id) -> void {
  1431. new_interface.scope_id = context_.name_scopes().Add(
  1432. new_interface.first_owning_decl_id, SemIR::NameId::Invalid,
  1433. new_interface.parent_scope_id);
  1434. auto& new_scope = context_.name_scopes().Get(new_interface.scope_id);
  1435. const auto& import_scope =
  1436. import_ir_.name_scopes().Get(import_interface.scope_id);
  1437. // Push a block so that we can add scoped instructions to it.
  1438. context_.inst_block_stack().Push();
  1439. AddNameScopeImportRefs(import_scope, new_scope);
  1440. new_interface.associated_entities_id =
  1441. AddAssociatedEntities(import_interface.associated_entities_id);
  1442. new_interface.body_block_id = context_.inst_block_stack().Pop();
  1443. new_interface.self_param_id = self_param_id;
  1444. CARBON_CHECK(import_scope.extended_scopes.empty())
  1445. << "Interfaces don't currently have extended scopes to support.";
  1446. }
  1447. auto TryResolveTypedInst(SemIR::InterfaceDecl inst,
  1448. SemIR::ConstantId interface_const_id)
  1449. -> ResolveResult {
  1450. const auto& import_interface =
  1451. import_ir_.interfaces().Get(inst.interface_id);
  1452. SemIR::InterfaceId interface_id = SemIR::InterfaceId::Invalid;
  1453. if (!interface_const_id.is_valid()) {
  1454. if (HasNewWork()) {
  1455. // This is the end of the first phase. Don't make a new interface yet if
  1456. // we already have new work.
  1457. return Retry();
  1458. }
  1459. // On the second phase, create a forward declaration of the interface.
  1460. std::tie(interface_id, interface_const_id) =
  1461. MakeInterfaceDecl(import_interface);
  1462. } else {
  1463. // On the third phase, compute the interface ID from the constant value of
  1464. // the declaration.
  1465. auto interface_const_inst = context_.insts().Get(
  1466. context_.constant_values().GetInstId(interface_const_id));
  1467. if (auto interface_type =
  1468. interface_const_inst.TryAs<SemIR::InterfaceType>()) {
  1469. interface_id = interface_type->interface_id;
  1470. } else {
  1471. auto generic_interface_type =
  1472. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1473. interface_const_inst.type_id());
  1474. interface_id = generic_interface_type.interface_id;
  1475. }
  1476. }
  1477. auto parent_scope_id =
  1478. GetLocalNameScopeId(import_interface.parent_scope_id);
  1479. auto implicit_param_const_ids =
  1480. GetLocalParamConstantIds(import_interface.implicit_param_refs_id);
  1481. auto param_const_ids =
  1482. GetLocalParamConstantIds(import_interface.param_refs_id);
  1483. auto generic_data = GetLocalGenericData(import_interface.generic_id);
  1484. std::optional<SemIR::InstId> self_param_id;
  1485. if (import_interface.is_defined()) {
  1486. self_param_id = GetLocalConstantInstId(import_interface.self_param_id);
  1487. }
  1488. if (HasNewWork()) {
  1489. return Retry(interface_const_id);
  1490. }
  1491. auto& new_interface = context_.interfaces().Get(interface_id);
  1492. new_interface.parent_scope_id = parent_scope_id;
  1493. new_interface.implicit_param_refs_id = GetLocalParamRefsId(
  1494. import_interface.implicit_param_refs_id, implicit_param_const_ids);
  1495. new_interface.param_refs_id =
  1496. GetLocalParamRefsId(import_interface.param_refs_id, param_const_ids);
  1497. SetGenericData(import_interface.generic_id, new_interface.generic_id,
  1498. generic_data);
  1499. if (import_interface.is_defined()) {
  1500. CARBON_CHECK(self_param_id);
  1501. AddInterfaceDefinition(import_interface, new_interface, *self_param_id);
  1502. }
  1503. return ResolveAsConstant(interface_const_id);
  1504. }
  1505. auto TryResolveTypedInst(SemIR::InterfaceType inst) -> ResolveResult {
  1506. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1507. auto interface_const_id = GetLocalConstantId(
  1508. import_ir_.interfaces().Get(inst.interface_id).first_owning_decl_id);
  1509. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1510. if (HasNewWork()) {
  1511. return Retry();
  1512. }
  1513. // Find the corresponding interface type. For a non-generic interface, this
  1514. // is the type of the interface declaration. For a generic interface, build
  1515. // a interface type referencing this specialization of the generic
  1516. // interface.
  1517. auto interface_const_inst = context_.insts().Get(
  1518. context_.constant_values().GetInstId(interface_const_id));
  1519. if (interface_const_inst.Is<SemIR::InterfaceType>()) {
  1520. return ResolveAsConstant(interface_const_id);
  1521. } else {
  1522. auto generic_interface_type =
  1523. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1524. interface_const_inst.type_id());
  1525. auto specific_id = GetOrAddLocalSpecific(inst.specific_id, specific_data);
  1526. return ResolveAs<SemIR::InterfaceType>(
  1527. {.type_id = SemIR::TypeId::TypeType,
  1528. .interface_id = generic_interface_type.interface_id,
  1529. .specific_id = specific_id});
  1530. }
  1531. }
  1532. auto TryResolveTypedInst(SemIR::InterfaceWitness inst) -> ResolveResult {
  1533. auto elements = GetLocalInstBlockContents(inst.elements_id);
  1534. if (HasNewWork()) {
  1535. return Retry();
  1536. }
  1537. auto elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elements);
  1538. return ResolveAs<SemIR::InterfaceWitness>(
  1539. {.type_id =
  1540. context_.GetBuiltinType(SemIR::BuiltinInstKind::WitnessType),
  1541. .elements_id = elements_id});
  1542. }
  1543. auto TryResolveTypedInst(SemIR::IntLiteral inst) -> ResolveResult {
  1544. auto type_id = GetLocalConstantId(inst.type_id);
  1545. if (HasNewWork()) {
  1546. return Retry();
  1547. }
  1548. return ResolveAs<SemIR::IntLiteral>(
  1549. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1550. .int_id = context_.ints().Add(import_ir_.ints().Get(inst.int_id))});
  1551. }
  1552. auto TryResolveTypedInst(SemIR::PointerType inst) -> ResolveResult {
  1553. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1554. auto pointee_const_id = GetLocalConstantId(inst.pointee_id);
  1555. if (HasNewWork()) {
  1556. return Retry();
  1557. }
  1558. auto pointee_type_id = context_.GetTypeIdForTypeConstant(pointee_const_id);
  1559. return ResolveAs<SemIR::PointerType>(
  1560. {.type_id = SemIR::TypeId::TypeType, .pointee_id = pointee_type_id});
  1561. }
  1562. auto TryResolveTypedInst(SemIR::StructType inst, SemIR::InstId import_inst_id)
  1563. -> ResolveResult {
  1564. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1565. auto orig_fields = import_ir_.inst_blocks().Get(inst.fields_id);
  1566. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  1567. field_const_ids.reserve(orig_fields.size());
  1568. for (auto field_id : orig_fields) {
  1569. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1570. field_const_ids.push_back(GetLocalConstantId(field.field_type_id));
  1571. }
  1572. if (HasNewWork()) {
  1573. return Retry();
  1574. }
  1575. // Prepare a vector of fields for GetStructType.
  1576. // TODO: Should we have field constants so that we can deduplicate fields
  1577. // without creating instructions here?
  1578. llvm::SmallVector<SemIR::InstId> fields;
  1579. fields.reserve(orig_fields.size());
  1580. for (auto [field_id, field_const_id] :
  1581. llvm::zip(orig_fields, field_const_ids)) {
  1582. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1583. auto name_id = GetLocalNameId(field.name_id);
  1584. auto field_type_id = context_.GetTypeIdForTypeConstant(field_const_id);
  1585. fields.push_back(context_.AddInstInNoBlock<SemIR::StructTypeField>(
  1586. AddImportIRInst(import_inst_id),
  1587. {.name_id = name_id, .field_type_id = field_type_id}));
  1588. }
  1589. return ResolveAs<SemIR::StructType>(
  1590. {.type_id = SemIR::TypeId::TypeType,
  1591. .fields_id = context_.inst_blocks().AddCanonical(fields)});
  1592. }
  1593. auto TryResolveTypedInst(SemIR::StructValue inst) -> ResolveResult {
  1594. auto type_id = GetLocalConstantId(inst.type_id);
  1595. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1596. if (HasNewWork()) {
  1597. return Retry();
  1598. }
  1599. return ResolveAs<SemIR::StructValue>(
  1600. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1601. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1602. }
  1603. auto TryResolveTypedInst(SemIR::TupleType inst) -> ResolveResult {
  1604. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1605. auto orig_elem_type_ids = import_ir_.type_blocks().Get(inst.elements_id);
  1606. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  1607. elem_const_ids.reserve(orig_elem_type_ids.size());
  1608. for (auto elem_type_id : orig_elem_type_ids) {
  1609. elem_const_ids.push_back(GetLocalConstantId(elem_type_id));
  1610. }
  1611. if (HasNewWork()) {
  1612. return Retry();
  1613. }
  1614. // Prepare a vector of the tuple types for GetTupleType.
  1615. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  1616. elem_type_ids.reserve(orig_elem_type_ids.size());
  1617. for (auto elem_const_id : elem_const_ids) {
  1618. elem_type_ids.push_back(context_.GetTypeIdForTypeConstant(elem_const_id));
  1619. }
  1620. return ResolveAsConstant(
  1621. context_.types().GetConstantId(context_.GetTupleType(elem_type_ids)));
  1622. }
  1623. auto TryResolveTypedInst(SemIR::TupleValue inst) -> ResolveResult {
  1624. auto type_id = GetLocalConstantId(inst.type_id);
  1625. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1626. if (HasNewWork()) {
  1627. return Retry();
  1628. }
  1629. return ResolveAs<SemIR::TupleValue>(
  1630. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1631. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1632. }
  1633. auto TryResolveTypedInst(SemIR::UnboundElementType inst) -> ResolveResult {
  1634. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1635. auto class_const_id = GetLocalConstantId(inst.class_type_id);
  1636. auto elem_const_id = GetLocalConstantId(inst.element_type_id);
  1637. if (HasNewWork()) {
  1638. return Retry();
  1639. }
  1640. return ResolveAs<SemIR::UnboundElementType>(
  1641. {.type_id = SemIR::TypeId::TypeType,
  1642. .class_type_id = context_.GetTypeIdForTypeConstant(class_const_id),
  1643. .element_type_id = context_.GetTypeIdForTypeConstant(elem_const_id)});
  1644. }
  1645. // Perform any work that we deferred until the end of the main Resolve loop.
  1646. auto PerformPendingWork() -> void {
  1647. // Note that the individual Finish steps can add new pending work, so keep
  1648. // going until we have no more work to do.
  1649. while (!pending_generics_.empty() || !pending_specifics_.empty()) {
  1650. while (!pending_generics_.empty()) {
  1651. FinishPendingGeneric(pending_generics_.pop_back_val());
  1652. }
  1653. while (!pending_specifics_.empty()) {
  1654. FinishPendingSpecific(pending_specifics_.pop_back_val());
  1655. }
  1656. }
  1657. }
  1658. // Resolves and returns the local contents for an imported instruction block
  1659. // of constant instructions.
  1660. auto ResolveLocalInstBlockContents(SemIR::InstBlockId import_block_id)
  1661. -> llvm::SmallVector<SemIR::InstId> {
  1662. auto import_block = import_ir_.inst_blocks().Get(import_block_id);
  1663. llvm::SmallVector<SemIR::InstId> inst_ids;
  1664. inst_ids.reserve(import_block.size());
  1665. for (auto import_inst_id : import_block) {
  1666. inst_ids.push_back(
  1667. context_.constant_values().GetInstId(ResolveOneInst(import_inst_id)));
  1668. }
  1669. return inst_ids;
  1670. }
  1671. // Resolves and returns a local eval block for a region of an imported
  1672. // generic.
  1673. auto ResolveLocalEvalBlock(const SemIR::Generic& import_generic,
  1674. SemIR::GenericId generic_id,
  1675. SemIR::GenericInstIndex::Region region)
  1676. -> SemIR::InstBlockId {
  1677. auto import_block_id = import_generic.GetEvalBlock(region);
  1678. if (!import_block_id.is_valid()) {
  1679. return SemIR::InstBlockId::Invalid;
  1680. }
  1681. auto inst_ids = ResolveLocalInstBlockContents(import_block_id);
  1682. return RebuildGenericEvalBlock(context_, generic_id, region, inst_ids);
  1683. }
  1684. // Fills in the remaining information in a partially-imported generic.
  1685. auto FinishPendingGeneric(PendingGeneric pending) -> void {
  1686. const auto& import_generic = import_ir_.generics().Get(pending.import_id);
  1687. // Don't store the local generic between calls: the generics list can be
  1688. // reallocated by ResolveLocalEvalBlock importing more specifics.
  1689. auto decl_block_id =
  1690. ResolveLocalEvalBlock(import_generic, pending.local_id,
  1691. SemIR::GenericInstIndex::Region::Declaration);
  1692. context_.generics().Get(pending.local_id).decl_block_id = decl_block_id;
  1693. auto self_specific_id = MakeSelfSpecific(context_, pending.local_id);
  1694. context_.generics().Get(pending.local_id).self_specific_id =
  1695. self_specific_id;
  1696. pending_specifics_.push_back({.import_id = import_generic.self_specific_id,
  1697. .local_id = self_specific_id});
  1698. auto definition_block_id =
  1699. ResolveLocalEvalBlock(import_generic, pending.local_id,
  1700. SemIR::GenericInstIndex::Region::Definition);
  1701. context_.generics().Get(pending.local_id).definition_block_id =
  1702. definition_block_id;
  1703. }
  1704. // Resolves and returns a local inst block of constant instructions
  1705. // corresponding to an imported inst block.
  1706. auto ResolveLocalInstBlock(SemIR::InstBlockId import_block_id)
  1707. -> SemIR::InstBlockId {
  1708. if (!import_block_id.is_valid()) {
  1709. return SemIR::InstBlockId::Invalid;
  1710. }
  1711. auto inst_ids = ResolveLocalInstBlockContents(import_block_id);
  1712. return context_.inst_blocks().Add(inst_ids);
  1713. }
  1714. // Fills in the remaining information in a partially-imported specific.
  1715. auto FinishPendingSpecific(PendingSpecific pending) -> void {
  1716. const auto& import_specific = import_ir_.specifics().Get(pending.import_id);
  1717. // Don't store the local specific between calls: the specifics list can be
  1718. // reallocated by ResolveLocalInstBlock importing more specifics.
  1719. if (!context_.specifics().Get(pending.local_id).decl_block_id.is_valid()) {
  1720. auto decl_block_id = ResolveLocalInstBlock(import_specific.decl_block_id);
  1721. context_.specifics().Get(pending.local_id).decl_block_id = decl_block_id;
  1722. }
  1723. if (!context_.specifics()
  1724. .Get(pending.local_id)
  1725. .definition_block_id.is_valid() &&
  1726. import_specific.definition_block_id.is_valid()) {
  1727. auto definition_block_id =
  1728. ResolveLocalInstBlock(import_specific.definition_block_id);
  1729. context_.specifics().Get(pending.local_id).definition_block_id =
  1730. definition_block_id;
  1731. }
  1732. }
  1733. auto import_ir_constant_values() -> SemIR::ConstantValueStore& {
  1734. return context_.import_ir_constant_values()[import_ir_id_.index];
  1735. }
  1736. Context& context_;
  1737. SemIR::ImportIRId import_ir_id_;
  1738. const SemIR::File& import_ir_;
  1739. llvm::SmallVector<Work> work_stack_;
  1740. // The size of work_stack_ at the start of resolving the current instruction.
  1741. size_t initial_work_ = 0;
  1742. // Generics that we have partially imported but not yet finished importing.
  1743. llvm::SmallVector<PendingGeneric> pending_generics_;
  1744. // Specifics that we have partially imported but not yet finished importing.
  1745. llvm::SmallVector<PendingSpecific> pending_specifics_;
  1746. };
  1747. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  1748. // loaded (including the one pointed at directly by the ImportRef), and the
  1749. // final instruction's type ID.
  1750. //
  1751. // This addresses cases where an ImportRefUnloaded may point at another
  1752. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  1753. // constant-evaluated version of the instruction to work with.
  1754. static auto GetInstForLoad(Context& context,
  1755. SemIR::ImportIRInstId import_ir_inst_id)
  1756. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  1757. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  1758. {}, SemIR::TypeId::Invalid};
  1759. auto& [import_ir_insts, type_id] = result;
  1760. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  1761. // The first ImportIRInst is added directly because the IR doesn't need to be
  1762. // localized.
  1763. import_ir_insts.push_back(import_ir_inst);
  1764. const auto* cursor_ir = context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1765. while (true) {
  1766. auto cursor_inst = cursor_ir->insts().Get(import_ir_inst.inst_id);
  1767. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  1768. if (!import_ref) {
  1769. type_id = cursor_inst.type_id();
  1770. return result;
  1771. }
  1772. import_ir_inst =
  1773. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  1774. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1775. import_ir_insts.push_back(
  1776. {.ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  1777. .is_export = false,
  1778. .sem_ir = cursor_ir}),
  1779. .inst_id = import_ir_inst.inst_id});
  1780. }
  1781. }
  1782. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  1783. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  1784. if (!inst) {
  1785. return;
  1786. }
  1787. auto [indirect_insts, load_type_id] =
  1788. GetInstForLoad(context, inst->import_ir_inst_id);
  1789. // The last indirect instruction is the one to resolve. Pop it here because
  1790. // Resolve will assign the constant.
  1791. auto load_ir_inst = indirect_insts.pop_back_val();
  1792. ImportRefResolver resolver(context, load_ir_inst.ir_id);
  1793. // The resolver calls into Context to create instructions. Don't register
  1794. // those instructions as part of the enclosing generic scope if they're
  1795. // dependent on a generic parameter.
  1796. context.generic_region_stack().Push();
  1797. auto type_id = resolver.ResolveType(load_type_id);
  1798. auto constant_id = resolver.Resolve(load_ir_inst.inst_id);
  1799. context.generic_region_stack().Pop();
  1800. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  1801. // doesn't use ReplaceInstBeforeConstantUse because it would trigger
  1802. // TryEvalInst, which we want to avoid with ImportRefs.
  1803. context.sem_ir().insts().Set(
  1804. inst_id,
  1805. SemIR::ImportRefLoaded{.type_id = type_id,
  1806. .import_ir_inst_id = inst->import_ir_inst_id,
  1807. .entity_name_id = inst->entity_name_id});
  1808. // Store the constant for both the ImportRefLoaded and indirect instructions.
  1809. context.constant_values().Set(inst_id, constant_id);
  1810. for (const auto& import_ir_inst : indirect_insts) {
  1811. context.import_ir_constant_values()[import_ir_inst.ir_id.index].Set(
  1812. import_ir_inst.inst_id, constant_id);
  1813. }
  1814. }
  1815. // Imports the impl `import_impl_id` from the imported IR `import_ir`.
  1816. static auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  1817. const SemIR::File& import_ir,
  1818. SemIR::ImplId import_impl_id) -> void {
  1819. // Resolve the imported impl to a local impl ID.
  1820. ImportRefResolver resolver(context, import_ir_id);
  1821. const auto& import_impl = import_ir.impls().Get(import_impl_id);
  1822. auto self_id = resolver.ResolveType(import_impl.self_id);
  1823. auto constraint_id = resolver.ResolveType(import_impl.constraint_id);
  1824. // Import the definition if the impl is defined.
  1825. // TODO: Do we need to check for multiple definitions?
  1826. auto impl_id = context.impls().LookupOrAdd(self_id, constraint_id);
  1827. if (import_impl.is_defined()) {
  1828. // TODO: Create a scope for the `impl` if necessary.
  1829. // TODO: Consider importing the definition_id.
  1830. auto& impl = context.impls().Get(impl_id);
  1831. impl.witness_id = AddImportRef(
  1832. context, {.ir_id = import_ir_id, .inst_id = import_impl.witness_id},
  1833. SemIR::EntityNameId::Invalid);
  1834. }
  1835. }
  1836. // TODO: This doesn't belong in this file. Consider moving the import resolver
  1837. // and this file elsewhere.
  1838. auto ImportImpls(Context& context) -> void {
  1839. for (auto [import_index, import_ir] :
  1840. llvm::enumerate(context.import_irs().array_ref())) {
  1841. if (!import_ir.sem_ir) {
  1842. continue;
  1843. }
  1844. SemIR::ImportIRId import_ir_id(import_index);
  1845. for (auto impl_index : llvm::seq(import_ir.sem_ir->impls().size())) {
  1846. SemIR::ImplId impl_id(impl_index);
  1847. ImportImpl(context, import_ir_id, *import_ir.sem_ir, impl_id);
  1848. }
  1849. }
  1850. }
  1851. } // namespace Carbon::Check