import_ref.cpp 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651
  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/parse/node_ids.h"
  10. #include "toolchain/sem_ir/constant.h"
  11. #include "toolchain/sem_ir/file.h"
  12. #include "toolchain/sem_ir/ids.h"
  13. #include "toolchain/sem_ir/import_ir.h"
  14. #include "toolchain/sem_ir/inst.h"
  15. #include "toolchain/sem_ir/inst_kind.h"
  16. #include "toolchain/sem_ir/typed_insts.h"
  17. namespace Carbon::Check {
  18. // Adds the ImportIR, excluding the update to the check_ir_map.
  19. static auto InternalAddImportIR(Context& context, SemIR::ImportIR import_ir)
  20. -> SemIR::ImportIRId {
  21. context.import_ir_constant_values().push_back(
  22. SemIR::ConstantValueStore(SemIR::ConstantId::Invalid));
  23. return context.import_irs().Add(import_ir);
  24. }
  25. auto SetApiImportIR(Context& context, SemIR::ImportIR import_ir) -> void {
  26. auto ir_id = SemIR::ImportIRId::Invalid;
  27. if (import_ir.sem_ir != nullptr) {
  28. ir_id = AddImportIR(context, import_ir);
  29. } else {
  30. // We don't have a check_ir_id, so add without touching check_ir_map.
  31. ir_id = InternalAddImportIR(context, import_ir);
  32. }
  33. CARBON_CHECK(ir_id == SemIR::ImportIRId::ApiForImpl)
  34. << "ApiForImpl must be the first IR";
  35. }
  36. auto AddImportIR(Context& context, SemIR::ImportIR import_ir)
  37. -> SemIR::ImportIRId {
  38. auto& ir_id = context.GetImportIRId(*import_ir.sem_ir);
  39. if (!ir_id.is_valid()) {
  40. // Note this updates check_ir_map.
  41. ir_id = InternalAddImportIR(context, import_ir);
  42. } else if (import_ir.is_export) {
  43. // We're processing an `export import`. In case the IR was indirectly added
  44. // as a non-export, mark it as an export.
  45. context.import_irs().Get(ir_id).is_export = true;
  46. }
  47. return ir_id;
  48. }
  49. auto AddImportRef(Context& context, SemIR::ImportIRInst import_ir_inst,
  50. SemIR::BindNameId bind_name_id) -> SemIR::InstId {
  51. auto import_ir_inst_id = context.import_ir_insts().Add(import_ir_inst);
  52. SemIR::ImportRefUnloaded inst = {.import_ir_inst_id = import_ir_inst_id,
  53. .bind_name_id = bind_name_id};
  54. auto import_ref_id = context.AddPlaceholderInstInNoBlock(
  55. SemIR::LocIdAndInst(import_ir_inst_id, inst));
  56. // ImportRefs have a dedicated block because this may be called during
  57. // processing where the instruction shouldn't be inserted in the current inst
  58. // block.
  59. context.import_ref_ids().push_back(import_ref_id);
  60. return import_ref_id;
  61. }
  62. auto GetCanonicalImportIRInst(Context& context, const SemIR::File* cursor_ir,
  63. SemIR::InstId cursor_inst_id)
  64. -> SemIR::ImportIRInst {
  65. while (true) {
  66. auto inst = cursor_ir->insts().Get(cursor_inst_id);
  67. CARBON_KIND_SWITCH(inst) {
  68. case CARBON_KIND(SemIR::ExportDecl bind_export): {
  69. cursor_inst_id = bind_export.value_id;
  70. continue;
  71. }
  72. case SemIR::ImportRefLoaded::Kind:
  73. case SemIR::ImportRefUnloaded::Kind: {
  74. auto import_ref = inst.As<SemIR::AnyImportRef>();
  75. auto import_ir_inst =
  76. cursor_ir->import_ir_insts().Get(import_ref.import_ir_inst_id);
  77. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  78. cursor_inst_id = import_ir_inst.inst_id;
  79. continue;
  80. }
  81. default: {
  82. auto ir_id = SemIR::ImportIRId::Invalid;
  83. if (cursor_ir != &context.sem_ir()) {
  84. // This uses AddImportIR in case it was indirectly found, which can
  85. // happen with two or more steps of exports.
  86. ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  87. .is_export = false,
  88. .sem_ir = cursor_ir});
  89. }
  90. return {.ir_id = ir_id, .inst_id = cursor_inst_id};
  91. }
  92. }
  93. }
  94. }
  95. auto VerifySameCanonicalImportIRInst(Context& context, SemIR::InstId prev_id,
  96. SemIR::ImportIRInst prev_import_ir_inst,
  97. SemIR::ImportIRId new_ir_id,
  98. const SemIR::File* new_import_ir,
  99. SemIR::InstId new_inst_id) -> void {
  100. auto new_import_ir_inst =
  101. GetCanonicalImportIRInst(context, new_import_ir, new_inst_id);
  102. if (new_import_ir_inst == prev_import_ir_inst) {
  103. return;
  104. }
  105. auto conflict_id =
  106. AddImportRef(context, {.ir_id = new_ir_id, .inst_id = new_inst_id},
  107. SemIR::BindNameId::Invalid);
  108. context.DiagnoseDuplicateName(conflict_id, prev_id);
  109. }
  110. // Resolves an instruction from an imported IR into a constant referring to the
  111. // current IR.
  112. //
  113. // Calling Resolve on an instruction operates in an iterative manner, tracking
  114. // Work items on work_stack_. At a high level, the loop is:
  115. //
  116. // 1. If a constant value is already known for the work item, and we're
  117. // processing it for the first time, it's considered resolved.
  118. // - The constant check avoids performance costs of deduplication on add.
  119. // - If `retry` is set, we process it again, because it didn't complete last
  120. // time, even though we have a constant value already.
  121. // 2. Resolve the instruction: (TryResolveInst/TryResolveTypedInst)
  122. // - For instructions that can be forward declared, if we don't already have
  123. // a constant value from a previous attempt at resolution, start by making
  124. // a forward declared constant value to address circular references.
  125. // - Gather all input constants.
  126. // - Gathering constants directly adds unresolved values to work_stack_.
  127. // - If any need to be resolved (HasNewWork), return Retry(): this
  128. // instruction needs two calls to complete.
  129. // - If the constant value is already known because we have made a forward
  130. // declaration, pass it to Retry(). It will be passed to future attempts
  131. // to resolve this instruction so the earlier work can be found, and will
  132. // be made available for other instructions to use.
  133. // - The second attempt to resolve this instruction must produce the same
  134. // constant, because the value may have already been used by resolved
  135. // instructions.
  136. // - Build any necessary IR structures, and return the output constant.
  137. // 3. If resolve didn't return Retry(), pop the work. Otherwise, it needs to
  138. // remain, and may no longer be at the top of the stack; set `retry` on it so
  139. // we'll make sure to run it again later.
  140. //
  141. // TryResolveInst/TryResolveTypedInst can complete in one call for a given
  142. // instruction, but should always complete within two calls. However, due to the
  143. // chance of a second call, it's important to reserve all expensive logic until
  144. // it's been established that input constants are available; this in particular
  145. // includes GetTypeIdForTypeConstant calls which do a hash table lookup.
  146. //
  147. // TODO: Fix class `extern` handling and merging, rewrite tests.
  148. // - check/testdata/class/cross_package_import.carbon
  149. // - check/testdata/class/extern.carbon
  150. // TODO: Fix function `extern` handling and merging, rewrite tests.
  151. // - check/testdata/function/declaration/import.carbon
  152. // - check/testdata/packages/cross_package_import.carbon
  153. class ImportRefResolver {
  154. public:
  155. explicit ImportRefResolver(Context& context, SemIR::ImportIRId import_ir_id)
  156. : context_(context),
  157. import_ir_id_(import_ir_id),
  158. import_ir_(*context_.import_irs().Get(import_ir_id).sem_ir) {}
  159. // Iteratively resolves an imported instruction's inner references until a
  160. // constant ID referencing the current IR is produced. See the class comment
  161. // for more details.
  162. auto Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId {
  163. work_stack_.push_back({.inst_id = inst_id});
  164. while (!work_stack_.empty()) {
  165. auto work = work_stack_.back();
  166. CARBON_CHECK(work.inst_id.is_valid());
  167. // Step 1: check for a constant value.
  168. auto existing = FindResolvedConstId(work.inst_id);
  169. if (existing.const_id.is_valid() && !work.retry) {
  170. work_stack_.pop_back();
  171. continue;
  172. }
  173. // Step 2: resolve the instruction.
  174. auto initial_work = work_stack_.size();
  175. auto [new_const_id, finished] =
  176. TryResolveInst(work.inst_id, existing.const_id);
  177. CARBON_CHECK(finished == !HasNewWork(initial_work));
  178. CARBON_CHECK(!existing.const_id.is_valid() ||
  179. existing.const_id == new_const_id)
  180. << "Constant value changed in second pass.";
  181. if (!existing.const_id.is_valid()) {
  182. SetResolvedConstId(work.inst_id, existing.indirect_insts, new_const_id);
  183. }
  184. // Step 3: pop or retry.
  185. if (finished) {
  186. work_stack_.pop_back();
  187. } else {
  188. work_stack_[initial_work - 1].retry = true;
  189. }
  190. }
  191. auto constant_id = import_ir_constant_values().Get(inst_id);
  192. CARBON_CHECK(constant_id.is_valid());
  193. return constant_id;
  194. }
  195. // Wraps constant evaluation with logic to handle types.
  196. auto ResolveType(SemIR::TypeId import_type_id) -> SemIR::TypeId {
  197. if (!import_type_id.is_valid()) {
  198. return import_type_id;
  199. }
  200. auto import_type_inst_id = import_ir_.types().GetInstId(import_type_id);
  201. CARBON_CHECK(import_type_inst_id.is_valid());
  202. if (import_type_inst_id.is_builtin()) {
  203. // Builtins don't require constant resolution; we can use them directly.
  204. return context_.GetBuiltinType(import_type_inst_id.builtin_kind());
  205. } else {
  206. return context_.GetTypeIdForTypeConstant(Resolve(import_type_inst_id));
  207. }
  208. }
  209. private:
  210. // A step in work_stack_.
  211. struct Work {
  212. // The instruction to work on.
  213. SemIR::InstId inst_id;
  214. // True if another pass was requested last time this was run.
  215. bool retry = false;
  216. };
  217. // The result of attempting to resolve an imported instruction to a constant.
  218. struct ResolveResult {
  219. // Try resolving this function again. If `const_id` is specified, it will be
  220. // passed to the next resolution attempt.
  221. static auto Retry(SemIR::ConstantId const_id = SemIR::ConstantId::Invalid)
  222. -> ResolveResult {
  223. return {.const_id = const_id, .finished = false};
  224. }
  225. // The new constant value, if known.
  226. SemIR::ConstantId const_id;
  227. // Whether resolution has finished. If false, `TryResolveInst` will be
  228. // called again. Note that this is not strictly necessary, and we can get
  229. // the same information by checking whether new work was added to the stack.
  230. // However, we use this for consistency checks between resolve actions and
  231. // the work stack.
  232. bool finished = true;
  233. };
  234. // The constant found by FindResolvedConstId.
  235. struct ResolvedConstId {
  236. // The constant for the instruction. Invalid if not yet resolved.
  237. SemIR::ConstantId const_id = SemIR::ConstantId::Invalid;
  238. // Instructions which are indirect but equivalent to the current instruction
  239. // being resolved, and should have their constant set to the same. Empty
  240. // when const_id is valid.
  241. llvm::SmallVector<SemIR::ImportIRInst> indirect_insts = {};
  242. };
  243. // Looks to see if an instruction has been resolved. If a constant is only
  244. // found indirectly, sets the constant for any indirect steps that don't
  245. // already have the constant. If a constant isn't found, returns the indirect
  246. // instructions so that they can have the resolved constant assigned later.
  247. auto FindResolvedConstId(SemIR::InstId inst_id) -> ResolvedConstId {
  248. ResolvedConstId result;
  249. if (auto existing_const_id = import_ir_constant_values().Get(inst_id);
  250. existing_const_id.is_valid()) {
  251. result.const_id = existing_const_id;
  252. return result;
  253. }
  254. const auto* cursor_ir = &import_ir_;
  255. auto cursor_ir_id = SemIR::ImportIRId::Invalid;
  256. auto cursor_inst_id = inst_id;
  257. while (true) {
  258. auto loc_id = cursor_ir->insts().GetLocId(cursor_inst_id);
  259. if (!loc_id.is_import_ir_inst_id()) {
  260. return result;
  261. }
  262. auto ir_inst =
  263. cursor_ir->import_ir_insts().Get(loc_id.import_ir_inst_id());
  264. const auto* prev_ir = cursor_ir;
  265. auto prev_inst_id = cursor_inst_id;
  266. cursor_ir = cursor_ir->import_irs().Get(ir_inst.ir_id).sem_ir;
  267. cursor_ir_id = context_.GetImportIRId(*cursor_ir);
  268. if (!cursor_ir_id.is_valid()) {
  269. // TODO: Should we figure out a location to assign here?
  270. cursor_ir_id = AddImportIR(context_, {.decl_id = SemIR::InstId::Invalid,
  271. .is_export = false,
  272. .sem_ir = cursor_ir});
  273. }
  274. cursor_inst_id = ir_inst.inst_id;
  275. CARBON_CHECK(cursor_ir != prev_ir || cursor_inst_id != prev_inst_id)
  276. << cursor_ir->insts().Get(cursor_inst_id);
  277. if (auto const_id =
  278. context_.import_ir_constant_values()[cursor_ir_id.index].Get(
  279. cursor_inst_id);
  280. const_id.is_valid()) {
  281. SetResolvedConstId(inst_id, result.indirect_insts, const_id);
  282. result.const_id = const_id;
  283. result.indirect_insts.clear();
  284. return result;
  285. } else {
  286. result.indirect_insts.push_back(
  287. {.ir_id = cursor_ir_id, .inst_id = cursor_inst_id});
  288. }
  289. }
  290. }
  291. // Sets a resolved constant into the current and indirect instructions.
  292. auto SetResolvedConstId(SemIR::InstId inst_id,
  293. llvm::ArrayRef<SemIR::ImportIRInst> indirect_insts,
  294. SemIR::ConstantId const_id) -> void {
  295. import_ir_constant_values().Set(inst_id, const_id);
  296. for (auto indirect_inst : indirect_insts) {
  297. context_.import_ir_constant_values()[indirect_inst.ir_id.index].Set(
  298. indirect_inst.inst_id, const_id);
  299. }
  300. }
  301. // Returns true if new unresolved constants were found.
  302. //
  303. // At the start of a function, do:
  304. // auto initial_work = work_stack_.size();
  305. // Then when determining:
  306. // if (HasNewWork(initial_work)) { ... }
  307. auto HasNewWork(size_t initial_work) -> bool {
  308. CARBON_CHECK(initial_work <= work_stack_.size())
  309. << "Work shouldn't decrease";
  310. return initial_work < work_stack_.size();
  311. }
  312. auto AddImportIRInst(SemIR::InstId inst_id) -> SemIR::ImportIRInstId {
  313. return context_.import_ir_insts().Add(
  314. {.ir_id = import_ir_id_, .inst_id = inst_id});
  315. }
  316. // Returns the ConstantId for an InstId. Adds unresolved constants to
  317. // work_stack_.
  318. auto GetLocalConstantId(SemIR::InstId inst_id) -> SemIR::ConstantId {
  319. auto const_id = import_ir_constant_values().Get(inst_id);
  320. if (!const_id.is_valid()) {
  321. work_stack_.push_back({.inst_id = inst_id});
  322. }
  323. return const_id;
  324. }
  325. // Returns the local constant InstId for an imported InstId.
  326. auto GetLocalConstantInstId(SemIR::InstId inst_id) -> SemIR::InstId {
  327. auto const_id = import_ir_constant_values().Get(inst_id);
  328. if (!const_id.is_valid()) {
  329. work_stack_.push_back({.inst_id = inst_id});
  330. return SemIR::InstId::Invalid;
  331. }
  332. return context_.constant_values().GetInstId(const_id);
  333. }
  334. // Returns the ConstantId for a TypeId. Adds unresolved constants to
  335. // work_stack_.
  336. auto GetLocalConstantId(SemIR::TypeId type_id) -> SemIR::ConstantId {
  337. return GetLocalConstantId(import_ir_.types().GetInstId(type_id));
  338. }
  339. // Gets the local constant values corresponding to an imported inst block.
  340. auto GetLocalInstBlockContents(SemIR::InstBlockId import_block_id)
  341. -> llvm::SmallVector<SemIR::InstId> {
  342. llvm::SmallVector<SemIR::InstId> inst_ids;
  343. if (!import_block_id.is_valid() ||
  344. import_block_id == SemIR::InstBlockId::Empty) {
  345. return inst_ids;
  346. }
  347. // Import all the values in the block.
  348. auto import_block = import_ir_.inst_blocks().Get(import_block_id);
  349. inst_ids.reserve(import_block.size());
  350. for (auto import_inst_id : import_block) {
  351. auto const_id = GetLocalConstantId(import_inst_id);
  352. inst_ids.push_back(context_.constant_values().GetInstIdIfValid(const_id));
  353. }
  354. return inst_ids;
  355. }
  356. // Gets a local canonical instruction block ID corresponding to an imported
  357. // inst block whose contents were already imported, for example by
  358. // GetLocalInstBlockContents.
  359. auto GetLocalCanonicalInstBlockId(SemIR::InstBlockId import_block_id,
  360. llvm::ArrayRef<SemIR::InstId> contents)
  361. -> SemIR::InstBlockId {
  362. if (!import_block_id.is_valid()) {
  363. return SemIR::InstBlockId::Invalid;
  364. }
  365. return context_.inst_blocks().AddCanonical(contents);
  366. }
  367. // Gets a local version of an imported generic.
  368. auto GetLocalGeneric(SemIR::GenericId generic_id) -> SemIR::GenericId {
  369. if (!generic_id.is_valid()) {
  370. return SemIR::GenericId::Invalid;
  371. }
  372. // TODO: Support importing generics. Note that this comes up in the prelude,
  373. // so for now we fall back to producing `Invalid` and treating imported
  374. // generics as non-generic.
  375. return SemIR::GenericId::Invalid;
  376. }
  377. // Gets a local argument list corresponding to the arguments of an imported
  378. // generic instance.
  379. auto GetLocalGenericInstanceArgs(SemIR::GenericInstanceId instance_id)
  380. -> llvm::SmallVector<SemIR::InstId> {
  381. if (!instance_id.is_valid()) {
  382. return {};
  383. }
  384. return GetLocalInstBlockContents(
  385. import_ir_.generic_instances().Get(instance_id).args_id);
  386. }
  387. // Gets a local generic instance whose arguments were already imported by
  388. // GetLocalGenericInstanceArgs. Does not add any new work.
  389. auto GetLocalGenericInstance(SemIR::GenericInstanceId instance_id,
  390. llvm::ArrayRef<SemIR::InstId> args)
  391. -> SemIR::GenericInstanceId {
  392. if (!instance_id.is_valid()) {
  393. return SemIR::GenericInstanceId::Invalid;
  394. }
  395. const auto& instance = import_ir_.generic_instances().Get(instance_id);
  396. // TODO: Import the generic.
  397. auto generic_id = SemIR::GenericId::Invalid;
  398. auto args_id = GetLocalCanonicalInstBlockId(instance.args_id, args);
  399. // TODO: Also import the generic instance.
  400. return context_.generic_instances().GetOrAdd(generic_id, args_id);
  401. }
  402. // Returns the ConstantId for each parameter's type. Adds unresolved constants
  403. // to work_stack_.
  404. auto GetLocalParamConstantIds(SemIR::InstBlockId param_refs_id)
  405. -> llvm::SmallVector<SemIR::ConstantId> {
  406. llvm::SmallVector<SemIR::ConstantId> const_ids;
  407. if (!param_refs_id.is_valid() ||
  408. param_refs_id == SemIR::InstBlockId::Empty) {
  409. return const_ids;
  410. }
  411. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  412. const_ids.reserve(param_refs.size());
  413. for (auto inst_id : param_refs) {
  414. const_ids.push_back(
  415. GetLocalConstantId(import_ir_.insts().Get(inst_id).type_id()));
  416. // If the parameter is a symbolic binding, build the BindSymbolicName
  417. // constant.
  418. auto bind_id = inst_id;
  419. if (auto addr =
  420. import_ir_.insts().TryGetAs<SemIR::AddrPattern>(bind_id)) {
  421. bind_id = addr->inner_id;
  422. }
  423. GetLocalConstantId(bind_id);
  424. }
  425. return const_ids;
  426. }
  427. // Given a param_refs_id and const_ids from GetLocalParamConstantIds, returns
  428. // a version of param_refs_id localized to the current IR.
  429. auto GetLocalParamRefsId(
  430. SemIR::InstBlockId param_refs_id,
  431. const llvm::SmallVector<SemIR::ConstantId>& const_ids)
  432. -> SemIR::InstBlockId {
  433. if (!param_refs_id.is_valid() ||
  434. param_refs_id == SemIR::InstBlockId::Empty) {
  435. return param_refs_id;
  436. }
  437. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  438. llvm::SmallVector<SemIR::InstId> new_param_refs;
  439. for (auto [ref_id, const_id] : llvm::zip(param_refs, const_ids)) {
  440. // Figure out the param structure. This echoes
  441. // Function::GetParamFromParamRefId.
  442. // TODO: Consider a different parameter handling to simplify import logic.
  443. auto inst = import_ir_.insts().Get(ref_id);
  444. auto addr_inst = inst.TryAs<SemIR::AddrPattern>();
  445. auto bind_id = ref_id;
  446. auto param_id = ref_id;
  447. if (addr_inst) {
  448. bind_id = addr_inst->inner_id;
  449. param_id = bind_id;
  450. inst = import_ir_.insts().Get(bind_id);
  451. }
  452. auto bind_inst = inst.TryAs<SemIR::AnyBindName>();
  453. if (bind_inst) {
  454. param_id = bind_inst->value_id;
  455. inst = import_ir_.insts().Get(param_id);
  456. }
  457. auto param_inst = inst.As<SemIR::Param>();
  458. // Rebuild the param instruction.
  459. auto name_id = GetLocalNameId(param_inst.name_id);
  460. auto type_id = context_.GetTypeIdForTypeConstant(const_id);
  461. auto new_param_id = context_.AddInstInNoBlock<SemIR::Param>(
  462. AddImportIRInst(param_id), {.type_id = type_id, .name_id = name_id});
  463. if (bind_inst) {
  464. switch (bind_inst->kind) {
  465. case SemIR::BindName::Kind: {
  466. auto bind_name_id = context_.bind_names().Add(
  467. {.name_id = name_id,
  468. .parent_scope_id = SemIR::NameScopeId::Invalid,
  469. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  470. new_param_id = context_.AddInstInNoBlock<SemIR::BindName>(
  471. AddImportIRInst(bind_id), {.type_id = type_id,
  472. .bind_name_id = bind_name_id,
  473. .value_id = new_param_id});
  474. break;
  475. }
  476. case SemIR::BindSymbolicName::Kind: {
  477. // The symbolic name will be created on first reference, so might
  478. // already exist. Update the value in it to refer to the parameter.
  479. auto new_bind_inst_id = GetLocalConstantInstId(bind_id);
  480. auto new_bind_inst =
  481. context_.insts().GetAs<SemIR::BindSymbolicName>(
  482. new_bind_inst_id);
  483. new_bind_inst.value_id = new_param_id;
  484. // This is not before constant use, but doesn't change the
  485. // constant value of the instruction.
  486. context_.ReplaceInstBeforeConstantUse(new_bind_inst_id,
  487. new_bind_inst);
  488. new_param_id = new_bind_inst_id;
  489. break;
  490. }
  491. default: {
  492. CARBON_FATAL() << "Unexpected kind: " << bind_inst->kind;
  493. }
  494. }
  495. }
  496. if (addr_inst) {
  497. new_param_id = context_.AddInstInNoBlock<SemIR::AddrPattern>(
  498. AddImportIRInst(ref_id),
  499. {.type_id = type_id, .inner_id = new_param_id});
  500. }
  501. new_param_refs.push_back(new_param_id);
  502. }
  503. return context_.inst_blocks().Add(new_param_refs);
  504. }
  505. // Translates a NameId from the import IR to a local NameId.
  506. auto GetLocalNameId(SemIR::NameId import_name_id) -> SemIR::NameId {
  507. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.is_valid()) {
  508. return SemIR::NameId::ForIdentifier(
  509. context_.identifiers().Add(import_ir_.identifiers().Get(ident_id)));
  510. }
  511. return import_name_id;
  512. }
  513. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  514. // unresolved constants to the work stack.
  515. auto GetLocalNameScopeId(SemIR::NameScopeId name_scope_id)
  516. -> SemIR::NameScopeId {
  517. // Get the instruction that created the scope.
  518. auto [inst_id, inst] =
  519. import_ir_.name_scopes().GetInstIfValid(name_scope_id);
  520. if (!inst) {
  521. // Map scopes that aren't associated with an instruction to invalid
  522. // scopes. For now, such scopes aren't used, and we don't have a good way
  523. // to remap them.
  524. return SemIR::NameScopeId::Invalid;
  525. }
  526. // Get the constant value for the scope.
  527. auto const_id = SemIR::ConstantId::Invalid;
  528. CARBON_KIND_SWITCH(*inst) {
  529. case SemIR::ImplDecl::Kind:
  530. // TODO: Import the scope for an `impl` definition.
  531. return SemIR::NameScopeId::Invalid;
  532. case SemIR::Namespace::Kind:
  533. // If the namespace has already been imported, we can use its constant.
  534. // However, if it hasn't, we use Invalid instead of adding it to the
  535. // work stack. That's expected to be okay when resolving references.
  536. const_id = import_ir_constant_values().Get(inst_id);
  537. break;
  538. default:
  539. const_id = GetLocalConstantId(inst_id);
  540. }
  541. if (!const_id.is_valid()) {
  542. return SemIR::NameScopeId::Invalid;
  543. }
  544. auto const_inst_id = context_.constant_values().GetInstId(const_id);
  545. auto name_scope_inst = context_.insts().Get(const_inst_id);
  546. CARBON_KIND_SWITCH(name_scope_inst) {
  547. case CARBON_KIND(SemIR::Namespace inst): {
  548. return inst.name_scope_id;
  549. }
  550. case CARBON_KIND(SemIR::ClassType inst): {
  551. return context_.classes().Get(inst.class_id).scope_id;
  552. }
  553. case CARBON_KIND(SemIR::InterfaceType inst): {
  554. return context_.interfaces().Get(inst.interface_id).scope_id;
  555. }
  556. case SemIR::StructValue::Kind: {
  557. auto type_inst = context_.types().GetAsInst(name_scope_inst.type_id());
  558. CARBON_KIND_SWITCH(type_inst) {
  559. case CARBON_KIND(SemIR::GenericClassType inst): {
  560. return context_.classes().Get(inst.class_id).scope_id;
  561. }
  562. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  563. return context_.interfaces().Get(inst.interface_id).scope_id;
  564. }
  565. default: {
  566. break;
  567. }
  568. }
  569. break;
  570. }
  571. default: {
  572. if (const_inst_id == SemIR::InstId::BuiltinError) {
  573. return SemIR::NameScopeId::Invalid;
  574. }
  575. break;
  576. }
  577. }
  578. CARBON_FATAL() << "Unexpected instruction kind for name scope: "
  579. << name_scope_inst;
  580. }
  581. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  582. // lookup.
  583. auto AddNameScopeImportRefs(const SemIR::NameScope& import_scope,
  584. SemIR::NameScope& new_scope) -> void {
  585. for (auto entry : import_scope.names) {
  586. auto ref_id = AddImportRef(
  587. context_, {.ir_id = import_ir_id_, .inst_id = entry.inst_id},
  588. SemIR::BindNameId::Invalid);
  589. new_scope.AddRequired({.name_id = GetLocalNameId(entry.name_id),
  590. .inst_id = ref_id,
  591. .access_kind = entry.access_kind});
  592. }
  593. }
  594. // Given a block ID for a list of associated entities of a witness, returns a
  595. // version localized to the current IR.
  596. auto AddAssociatedEntities(SemIR::InstBlockId associated_entities_id)
  597. -> SemIR::InstBlockId {
  598. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  599. return SemIR::InstBlockId::Empty;
  600. }
  601. auto associated_entities =
  602. import_ir_.inst_blocks().Get(associated_entities_id);
  603. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  604. new_associated_entities.reserve(associated_entities.size());
  605. for (auto inst_id : associated_entities) {
  606. new_associated_entities.push_back(
  607. AddImportRef(context_, {.ir_id = import_ir_id_, .inst_id = inst_id},
  608. SemIR::BindNameId::Invalid));
  609. }
  610. return context_.inst_blocks().Add(new_associated_entities);
  611. }
  612. // Tries to resolve the InstId, returning a constant when ready, or Invalid if
  613. // more has been added to the stack. A similar API is followed for all
  614. // following TryResolveTypedInst helper functions.
  615. //
  616. // `const_id` is Invalid unless we've tried to resolve this instruction
  617. // before, in which case it's the previous result.
  618. //
  619. // TODO: Error is returned when support is missing, but that should go away.
  620. auto TryResolveInst(SemIR::InstId inst_id, SemIR::ConstantId const_id)
  621. -> ResolveResult {
  622. if (inst_id.is_builtin()) {
  623. CARBON_CHECK(!const_id.is_valid());
  624. // Constants for builtins can be directly copied.
  625. return {.const_id = context_.constant_values().Get(inst_id)};
  626. }
  627. auto untyped_inst = import_ir_.insts().Get(inst_id);
  628. CARBON_KIND_SWITCH(untyped_inst) {
  629. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  630. return TryResolveTypedInst(inst);
  631. }
  632. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  633. return TryResolveTypedInst(inst);
  634. }
  635. case CARBON_KIND(SemIR::BaseDecl inst): {
  636. return TryResolveTypedInst(inst, inst_id);
  637. }
  638. case CARBON_KIND(SemIR::BindAlias inst): {
  639. return TryResolveTypedInst(inst);
  640. }
  641. case CARBON_KIND(SemIR::BindName inst): {
  642. // TODO: This always returns `ConstantId::NotConstant`.
  643. return {.const_id = TryEvalInst(context_, inst_id, inst)};
  644. }
  645. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  646. return TryResolveTypedInst(inst);
  647. }
  648. case CARBON_KIND(SemIR::ClassDecl inst): {
  649. return TryResolveTypedInst(inst, const_id);
  650. }
  651. case CARBON_KIND(SemIR::ClassType inst): {
  652. return TryResolveTypedInst(inst);
  653. }
  654. case CARBON_KIND(SemIR::ConstType inst): {
  655. return TryResolveTypedInst(inst);
  656. }
  657. case CARBON_KIND(SemIR::ExportDecl inst): {
  658. return TryResolveTypedInst(inst);
  659. }
  660. case CARBON_KIND(SemIR::FieldDecl inst): {
  661. return TryResolveTypedInst(inst, inst_id);
  662. }
  663. case CARBON_KIND(SemIR::FunctionDecl inst): {
  664. return TryResolveTypedInst(inst);
  665. }
  666. case CARBON_KIND(SemIR::FunctionType inst): {
  667. return TryResolveTypedInst(inst);
  668. }
  669. case CARBON_KIND(SemIR::GenericClassType inst): {
  670. return TryResolveTypedInst(inst);
  671. }
  672. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  673. return TryResolveTypedInst(inst);
  674. }
  675. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  676. return TryResolveTypedInst(inst, inst_id);
  677. }
  678. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  679. return TryResolveTypedInst(inst, const_id);
  680. }
  681. case CARBON_KIND(SemIR::InterfaceWitness inst): {
  682. return TryResolveTypedInst(inst);
  683. }
  684. case CARBON_KIND(SemIR::InterfaceType inst): {
  685. return TryResolveTypedInst(inst);
  686. }
  687. case CARBON_KIND(SemIR::IntLiteral inst): {
  688. return TryResolveTypedInst(inst);
  689. }
  690. case CARBON_KIND(SemIR::Namespace inst): {
  691. CARBON_FATAL() << "Namespaces shouldn't need resolution this way: "
  692. << inst;
  693. }
  694. case CARBON_KIND(SemIR::PointerType inst): {
  695. return TryResolveTypedInst(inst);
  696. }
  697. case CARBON_KIND(SemIR::StructType inst): {
  698. return TryResolveTypedInst(inst, inst_id);
  699. }
  700. case CARBON_KIND(SemIR::StructValue inst): {
  701. return TryResolveTypedInst(inst);
  702. }
  703. case CARBON_KIND(SemIR::TupleType inst): {
  704. return TryResolveTypedInst(inst);
  705. }
  706. case CARBON_KIND(SemIR::TupleValue inst): {
  707. return TryResolveTypedInst(inst);
  708. }
  709. case CARBON_KIND(SemIR::UnboundElementType inst): {
  710. return TryResolveTypedInst(inst);
  711. }
  712. default:
  713. context_.TODO(
  714. SemIR::LocId(AddImportIRInst(inst_id)),
  715. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  716. return {.const_id = SemIR::ConstantId::Error};
  717. }
  718. }
  719. // Produce a resolve result for the given instruction that describes a
  720. // constant value. This should only be used for instructions that describe
  721. // constants, and not for instructions that represent declarations. For a
  722. // declaration, we need an associated location, so AddInstInNoBlock should be
  723. // used instead.
  724. auto ResolveAsUntyped(SemIR::Inst inst) -> ResolveResult {
  725. auto result = TryEvalInst(context_, SemIR::InstId::Invalid, inst);
  726. CARBON_CHECK(result.is_constant()) << inst << " is not constant";
  727. return {.const_id = result};
  728. }
  729. // Same as ResolveAsUntyped, but with an explicit type for convenience.
  730. template <typename InstT>
  731. auto ResolveAs(InstT inst) -> ResolveResult {
  732. return ResolveAsUntyped(inst);
  733. }
  734. auto TryResolveTypedInst(SemIR::AssociatedEntity inst) -> ResolveResult {
  735. auto initial_work = work_stack_.size();
  736. auto type_const_id = GetLocalConstantId(inst.type_id);
  737. if (HasNewWork(initial_work)) {
  738. return ResolveResult::Retry();
  739. }
  740. // Add a lazy reference to the target declaration.
  741. auto decl_id = AddImportRef(
  742. context_, {.ir_id = import_ir_id_, .inst_id = inst.decl_id},
  743. SemIR::BindNameId::Invalid);
  744. return ResolveAs<SemIR::AssociatedEntity>(
  745. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  746. .index = inst.index,
  747. .decl_id = decl_id});
  748. }
  749. auto TryResolveTypedInst(SemIR::AssociatedEntityType inst) -> ResolveResult {
  750. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  751. auto initial_work = work_stack_.size();
  752. auto entity_type_const_id = GetLocalConstantId(inst.entity_type_id);
  753. auto interface_inst_id = GetLocalConstantInstId(
  754. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  755. if (HasNewWork(initial_work)) {
  756. return ResolveResult::Retry();
  757. }
  758. return ResolveAs<SemIR::AssociatedEntityType>(
  759. {.type_id = SemIR::TypeId::TypeType,
  760. .interface_id = context_.insts()
  761. .GetAs<SemIR::InterfaceType>(interface_inst_id)
  762. .interface_id,
  763. .entity_type_id =
  764. context_.GetTypeIdForTypeConstant(entity_type_const_id)});
  765. }
  766. auto TryResolveTypedInst(SemIR::BaseDecl inst, SemIR::InstId import_inst_id)
  767. -> ResolveResult {
  768. auto initial_work = work_stack_.size();
  769. auto type_const_id = GetLocalConstantId(inst.type_id);
  770. auto base_type_const_id = GetLocalConstantId(inst.base_type_id);
  771. if (HasNewWork(initial_work)) {
  772. return ResolveResult::Retry();
  773. }
  774. // Import the instruction in order to update contained base_type_id and
  775. // track the import location.
  776. auto inst_id = context_.AddInstInNoBlock<SemIR::BaseDecl>(
  777. AddImportIRInst(import_inst_id),
  778. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  779. .base_type_id = context_.GetTypeIdForTypeConstant(base_type_const_id),
  780. .index = inst.index});
  781. return {.const_id = context_.constant_values().Get(inst_id)};
  782. }
  783. auto TryResolveTypedInst(SemIR::BindAlias inst) -> ResolveResult {
  784. auto initial_work = work_stack_.size();
  785. auto value_id = GetLocalConstantId(inst.value_id);
  786. if (HasNewWork(initial_work)) {
  787. return ResolveResult::Retry();
  788. }
  789. return {.const_id = value_id};
  790. }
  791. auto TryResolveTypedInst(SemIR::BindSymbolicName inst) -> ResolveResult {
  792. auto initial_work = work_stack_.size();
  793. auto type_id = GetLocalConstantId(inst.type_id);
  794. if (HasNewWork(initial_work)) {
  795. return ResolveResult::Retry();
  796. }
  797. const auto& import_bind_info =
  798. import_ir_.bind_names().Get(inst.bind_name_id);
  799. auto name_id = GetLocalNameId(import_bind_info.name_id);
  800. auto bind_name_id = context_.bind_names().Add(
  801. {.name_id = name_id,
  802. .parent_scope_id = SemIR::NameScopeId::Invalid,
  803. .bind_index = import_bind_info.bind_index});
  804. return ResolveAs<SemIR::BindSymbolicName>(
  805. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  806. .bind_name_id = bind_name_id,
  807. .value_id = SemIR::InstId::Invalid});
  808. }
  809. // Makes an incomplete class. This is necessary even with classes with a
  810. // complete declaration, because things such as `Self` may refer back to the
  811. // type.
  812. auto MakeIncompleteClass(const SemIR::Class& import_class)
  813. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  814. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeId::TypeType,
  815. .class_id = SemIR::ClassId::Invalid,
  816. .decl_block_id = SemIR::InstBlockId::Empty};
  817. auto class_decl_id = context_.AddPlaceholderInstInNoBlock(
  818. SemIR::LocIdAndInst(AddImportIRInst(import_class.decl_id), class_decl));
  819. // TODO: Support for importing generics.
  820. auto generic_id = GetLocalGeneric(import_class.generic_id);
  821. // Regardless of whether ClassDecl is a complete type, we first need an
  822. // incomplete type so that any references have something to point at.
  823. class_decl.class_id = context_.classes().Add({
  824. .name_id = GetLocalNameId(import_class.name_id),
  825. // These are set in the second pass once we've imported them. Import
  826. // enough of the parameter lists that we know whether this class is a
  827. // generic class and can build the right constant value for it.
  828. // TODO: Add a better way to represent a generic `Class` prior to
  829. // importing the parameters.
  830. .parent_scope_id = SemIR::NameScopeId::Invalid,
  831. .generic_id = generic_id,
  832. .implicit_param_refs_id = import_class.implicit_param_refs_id.is_valid()
  833. ? SemIR::InstBlockId::Empty
  834. : SemIR::InstBlockId::Invalid,
  835. .param_refs_id = import_class.param_refs_id.is_valid()
  836. ? SemIR::InstBlockId::Empty
  837. : SemIR::InstBlockId::Invalid,
  838. .self_type_id = SemIR::TypeId::Invalid,
  839. // These fields can be set immediately.
  840. .decl_id = class_decl_id,
  841. .inheritance_kind = import_class.inheritance_kind,
  842. });
  843. if (import_class.is_generic()) {
  844. class_decl.type_id = context_.GetGenericClassType(class_decl.class_id);
  845. }
  846. // Write the class ID into the ClassDecl.
  847. context_.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  848. auto self_const_id = context_.constant_values().Get(class_decl_id);
  849. return {class_decl.class_id, self_const_id};
  850. }
  851. // Fills out the class definition for an incomplete class.
  852. auto AddClassDefinition(const SemIR::Class& import_class,
  853. SemIR::Class& new_class,
  854. SemIR::ConstantId object_repr_const_id,
  855. SemIR::InstId base_id) -> void {
  856. new_class.definition_id = new_class.decl_id;
  857. new_class.object_repr_id =
  858. context_.GetTypeIdForTypeConstant(object_repr_const_id);
  859. new_class.scope_id = context_.name_scopes().Add(
  860. new_class.decl_id, SemIR::NameId::Invalid, new_class.parent_scope_id);
  861. auto& new_scope = context_.name_scopes().Get(new_class.scope_id);
  862. const auto& import_scope =
  863. import_ir_.name_scopes().Get(import_class.scope_id);
  864. // Push a block so that we can add scoped instructions to it.
  865. context_.inst_block_stack().Push();
  866. AddNameScopeImportRefs(import_scope, new_scope);
  867. new_class.body_block_id = context_.inst_block_stack().Pop();
  868. if (import_class.base_id.is_valid()) {
  869. new_class.base_id = base_id;
  870. // Add the base scope to extended scopes.
  871. auto base_inst_id = context_.types().GetInstId(
  872. context_.insts()
  873. .GetAs<SemIR::BaseDecl>(new_class.base_id)
  874. .base_type_id);
  875. const auto& base_class = context_.classes().Get(
  876. context_.insts().GetAs<SemIR::ClassType>(base_inst_id).class_id);
  877. new_scope.extended_scopes.push_back(base_class.scope_id);
  878. }
  879. CARBON_CHECK(new_scope.extended_scopes.size() ==
  880. import_scope.extended_scopes.size());
  881. }
  882. auto TryResolveTypedInst(SemIR::ClassDecl inst,
  883. SemIR::ConstantId class_const_id) -> ResolveResult {
  884. // TODO: The handling of interfaces repeats a lot with the handling of
  885. // classes, and will likely also be repeated for named constraints and
  886. // choice types. Factor out some of this functionality.
  887. const auto& import_class = import_ir_.classes().Get(inst.class_id);
  888. SemIR::ClassId class_id = SemIR::ClassId::Invalid;
  889. if (!class_const_id.is_valid()) {
  890. // On the first pass, create a forward declaration of the class for any
  891. // recursive references.
  892. std::tie(class_id, class_const_id) = MakeIncompleteClass(import_class);
  893. } else {
  894. // On the second pass, compute the class ID from the constant value of the
  895. // declaration.
  896. auto class_const_inst = context_.insts().Get(
  897. context_.constant_values().GetInstId(class_const_id));
  898. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  899. class_id = class_type->class_id;
  900. } else {
  901. auto generic_class_type =
  902. context_.types().GetAs<SemIR::GenericClassType>(
  903. class_const_inst.type_id());
  904. class_id = generic_class_type.class_id;
  905. }
  906. }
  907. // Load constants for the definition.
  908. auto initial_work = work_stack_.size();
  909. auto parent_scope_id = GetLocalNameScopeId(import_class.parent_scope_id);
  910. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  911. GetLocalParamConstantIds(import_class.implicit_param_refs_id);
  912. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  913. GetLocalParamConstantIds(import_class.param_refs_id);
  914. auto self_const_id = GetLocalConstantId(import_class.self_type_id);
  915. auto object_repr_const_id =
  916. import_class.object_repr_id.is_valid()
  917. ? GetLocalConstantId(import_class.object_repr_id)
  918. : SemIR::ConstantId::Invalid;
  919. auto base_id = import_class.base_id.is_valid()
  920. ? GetLocalConstantInstId(import_class.base_id)
  921. : SemIR::InstId::Invalid;
  922. if (HasNewWork(initial_work)) {
  923. return ResolveResult::Retry(class_const_id);
  924. }
  925. auto& new_class = context_.classes().Get(class_id);
  926. new_class.parent_scope_id = parent_scope_id;
  927. new_class.implicit_param_refs_id = GetLocalParamRefsId(
  928. import_class.implicit_param_refs_id, implicit_param_const_ids);
  929. new_class.param_refs_id =
  930. GetLocalParamRefsId(import_class.param_refs_id, param_const_ids);
  931. new_class.self_type_id = context_.GetTypeIdForTypeConstant(self_const_id);
  932. if (import_class.is_defined()) {
  933. AddClassDefinition(import_class, new_class, object_repr_const_id,
  934. base_id);
  935. }
  936. return {.const_id = class_const_id};
  937. }
  938. auto TryResolveTypedInst(SemIR::ClassType inst) -> ResolveResult {
  939. auto initial_work = work_stack_.size();
  940. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  941. auto class_const_id =
  942. GetLocalConstantId(import_ir_.classes().Get(inst.class_id).decl_id);
  943. auto args = GetLocalGenericInstanceArgs(inst.instance_id);
  944. if (HasNewWork(initial_work)) {
  945. return ResolveResult::Retry();
  946. }
  947. // Find the corresponding class type. For a non-generic class, this is the
  948. // type of the class declaration. For a generic class, build a class type
  949. // referencing this specialization of the generic class.
  950. auto class_const_inst = context_.insts().Get(
  951. context_.constant_values().GetInstId(class_const_id));
  952. if (class_const_inst.Is<SemIR::ClassType>()) {
  953. return {.const_id = class_const_id};
  954. } else {
  955. auto generic_class_type = context_.types().GetAs<SemIR::GenericClassType>(
  956. class_const_inst.type_id());
  957. auto instance_id = GetLocalGenericInstance(inst.instance_id, args);
  958. return ResolveAs<SemIR::ClassType>(
  959. {.type_id = SemIR::TypeId::TypeType,
  960. .class_id = generic_class_type.class_id,
  961. .instance_id = instance_id});
  962. }
  963. }
  964. auto TryResolveTypedInst(SemIR::ConstType inst) -> ResolveResult {
  965. auto initial_work = work_stack_.size();
  966. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  967. auto inner_const_id = GetLocalConstantId(inst.inner_id);
  968. if (HasNewWork(initial_work)) {
  969. return ResolveResult::Retry();
  970. }
  971. auto inner_type_id = context_.GetTypeIdForTypeConstant(inner_const_id);
  972. return ResolveAs<SemIR::ConstType>(
  973. {.type_id = SemIR::TypeId::TypeType, .inner_id = inner_type_id});
  974. }
  975. auto TryResolveTypedInst(SemIR::ExportDecl inst) -> ResolveResult {
  976. auto initial_work = work_stack_.size();
  977. auto value_id = GetLocalConstantId(inst.value_id);
  978. if (HasNewWork(initial_work)) {
  979. return ResolveResult::Retry();
  980. }
  981. return {.const_id = value_id};
  982. }
  983. auto TryResolveTypedInst(SemIR::FieldDecl inst, SemIR::InstId import_inst_id)
  984. -> ResolveResult {
  985. auto initial_work = work_stack_.size();
  986. auto const_id = GetLocalConstantId(inst.type_id);
  987. if (HasNewWork(initial_work)) {
  988. return ResolveResult::Retry();
  989. }
  990. auto inst_id = context_.AddInstInNoBlock<SemIR::FieldDecl>(
  991. AddImportIRInst(import_inst_id),
  992. {.type_id = context_.GetTypeIdForTypeConstant(const_id),
  993. .name_id = GetLocalNameId(inst.name_id),
  994. .index = inst.index});
  995. return {.const_id = context_.constant_values().Get(inst_id)};
  996. }
  997. auto TryResolveTypedInst(SemIR::FunctionDecl inst) -> ResolveResult {
  998. auto initial_work = work_stack_.size();
  999. const auto& function = import_ir_.functions().Get(inst.function_id);
  1000. auto return_type_const_id = SemIR::ConstantId::Invalid;
  1001. if (function.return_storage_id.is_valid()) {
  1002. return_type_const_id =
  1003. GetLocalConstantId(function.declared_return_type(import_ir_));
  1004. }
  1005. auto parent_scope_id = GetLocalNameScopeId(function.parent_scope_id);
  1006. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  1007. GetLocalParamConstantIds(function.implicit_param_refs_id);
  1008. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  1009. GetLocalParamConstantIds(function.param_refs_id);
  1010. if (HasNewWork(initial_work)) {
  1011. return ResolveResult::Retry();
  1012. }
  1013. // Add the function declaration.
  1014. SemIR::FunctionDecl function_decl = {
  1015. .type_id = SemIR::TypeId::Invalid,
  1016. .function_id = SemIR::FunctionId::Invalid,
  1017. .decl_block_id = SemIR::InstBlockId::Empty};
  1018. // Prefer pointing diagnostics towards a definition.
  1019. auto import_ir_inst_id = AddImportIRInst(function.definition_id.is_valid()
  1020. ? function.definition_id
  1021. : function.decl_id);
  1022. auto function_decl_id = context_.AddPlaceholderInstInNoBlock(
  1023. SemIR::LocIdAndInst(import_ir_inst_id, function_decl));
  1024. // TODO: Implement import for generics.
  1025. auto generic_id = GetLocalGeneric(function.generic_id);
  1026. auto new_return_storage = SemIR::InstId::Invalid;
  1027. if (function.return_storage_id.is_valid()) {
  1028. // Recreate the return slot from scratch.
  1029. // TODO: Once we import function definitions, we'll need to make sure we
  1030. // use the same return storage variable in the declaration and definition.
  1031. new_return_storage = context_.AddInstInNoBlock<SemIR::VarStorage>(
  1032. AddImportIRInst(function.return_storage_id),
  1033. {.type_id = context_.GetTypeIdForTypeConstant(return_type_const_id),
  1034. .name_id = SemIR::NameId::ReturnSlot});
  1035. }
  1036. function_decl.function_id = context_.functions().Add(
  1037. {.name_id = GetLocalNameId(function.name_id),
  1038. .parent_scope_id = parent_scope_id,
  1039. .decl_id = function_decl_id,
  1040. .generic_id = generic_id,
  1041. .implicit_param_refs_id = GetLocalParamRefsId(
  1042. function.implicit_param_refs_id, implicit_param_const_ids),
  1043. .param_refs_id =
  1044. GetLocalParamRefsId(function.param_refs_id, param_const_ids),
  1045. .return_storage_id = new_return_storage,
  1046. .is_extern = function.is_extern,
  1047. .return_slot = function.return_slot,
  1048. .builtin_kind = function.builtin_kind,
  1049. .definition_id = function.definition_id.is_valid()
  1050. ? function_decl_id
  1051. : SemIR::InstId::Invalid});
  1052. function_decl.type_id = context_.GetFunctionType(function_decl.function_id);
  1053. // Write the function ID into the FunctionDecl.
  1054. context_.ReplaceInstBeforeConstantUse(function_decl_id, function_decl);
  1055. return {.const_id = context_.constant_values().Get(function_decl_id)};
  1056. }
  1057. auto TryResolveTypedInst(SemIR::FunctionType inst) -> ResolveResult {
  1058. auto initial_work = work_stack_.size();
  1059. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1060. auto fn_val_id = GetLocalConstantInstId(
  1061. import_ir_.functions().Get(inst.function_id).decl_id);
  1062. if (HasNewWork(initial_work)) {
  1063. return ResolveResult::Retry();
  1064. }
  1065. auto fn_val = context_.insts().Get(fn_val_id);
  1066. CARBON_CHECK(context_.types().Is<SemIR::FunctionType>(fn_val.type_id()));
  1067. return {.const_id = context_.types().GetConstantId(fn_val.type_id())};
  1068. }
  1069. auto TryResolveTypedInst(SemIR::GenericClassType inst) -> ResolveResult {
  1070. auto initial_work = work_stack_.size();
  1071. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1072. auto class_val_id =
  1073. GetLocalConstantInstId(import_ir_.classes().Get(inst.class_id).decl_id);
  1074. if (HasNewWork(initial_work)) {
  1075. return ResolveResult::Retry();
  1076. }
  1077. auto class_val = context_.insts().Get(class_val_id);
  1078. CARBON_CHECK(
  1079. context_.types().Is<SemIR::GenericClassType>(class_val.type_id()));
  1080. return {.const_id = context_.types().GetConstantId(class_val.type_id())};
  1081. }
  1082. auto TryResolveTypedInst(SemIR::GenericInterfaceType inst) -> ResolveResult {
  1083. auto initial_work = work_stack_.size();
  1084. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1085. auto interface_val_id = GetLocalConstantInstId(
  1086. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  1087. if (HasNewWork(initial_work)) {
  1088. return ResolveResult::Retry();
  1089. }
  1090. auto interface_val = context_.insts().Get(interface_val_id);
  1091. CARBON_CHECK(context_.types().Is<SemIR::GenericInterfaceType>(
  1092. interface_val.type_id()));
  1093. return {.const_id =
  1094. context_.types().GetConstantId(interface_val.type_id())};
  1095. }
  1096. auto TryResolveTypedInst(SemIR::ImportRefLoaded /*inst*/,
  1097. SemIR::InstId inst_id) -> ResolveResult {
  1098. auto initial_work = work_stack_.size();
  1099. // Return the constant for the instruction of the imported constant.
  1100. auto constant_id = import_ir_.constant_values().Get(inst_id);
  1101. if (!constant_id.is_valid()) {
  1102. return {.const_id = SemIR::ConstantId::Error};
  1103. }
  1104. if (!constant_id.is_constant()) {
  1105. context_.TODO(inst_id,
  1106. "Non-constant ImportRefLoaded (comes up with var)");
  1107. return {.const_id = SemIR::ConstantId::Error};
  1108. }
  1109. auto new_constant_id =
  1110. GetLocalConstantId(import_ir_.constant_values().GetInstId(constant_id));
  1111. if (HasNewWork(initial_work)) {
  1112. return ResolveResult::Retry();
  1113. }
  1114. return {.const_id = new_constant_id};
  1115. }
  1116. // Make a declaration of an interface. This is done as a separate step from
  1117. // importing the interface definition in order to resolve cycles.
  1118. auto MakeInterfaceDecl(const SemIR::Interface& import_interface)
  1119. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  1120. SemIR::InterfaceDecl interface_decl = {
  1121. .type_id = SemIR::TypeId::TypeType,
  1122. .interface_id = SemIR::InterfaceId::Invalid,
  1123. .decl_block_id = SemIR::InstBlockId::Empty};
  1124. auto interface_decl_id =
  1125. context_.AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst(
  1126. AddImportIRInst(import_interface.decl_id), interface_decl));
  1127. // TODO: Support for importing generics.
  1128. auto generic_id = GetLocalGeneric(import_interface.generic_id);
  1129. // Start with an incomplete interface.
  1130. interface_decl.interface_id = context_.interfaces().Add({
  1131. .name_id = GetLocalNameId(import_interface.name_id),
  1132. // These are set in the second pass once we've imported them. Import
  1133. // enough of the parameter lists that we know whether this interface is
  1134. // a generic interface and can build the right constant value for it.
  1135. // TODO: Add a better way to represent a generic `Interface` prior to
  1136. // importing the parameters.
  1137. .parent_scope_id = SemIR::NameScopeId::Invalid,
  1138. .generic_id = generic_id,
  1139. .implicit_param_refs_id =
  1140. import_interface.implicit_param_refs_id.is_valid()
  1141. ? SemIR::InstBlockId::Empty
  1142. : SemIR::InstBlockId::Invalid,
  1143. .param_refs_id = import_interface.param_refs_id.is_valid()
  1144. ? SemIR::InstBlockId::Empty
  1145. : SemIR::InstBlockId::Invalid,
  1146. .decl_id = interface_decl_id,
  1147. });
  1148. if (import_interface.is_generic()) {
  1149. interface_decl.type_id =
  1150. context_.GetGenericInterfaceType(interface_decl.interface_id);
  1151. }
  1152. // Write the interface ID into the InterfaceDecl.
  1153. context_.ReplaceInstBeforeConstantUse(interface_decl_id, interface_decl);
  1154. return {interface_decl.interface_id,
  1155. context_.constant_values().Get(interface_decl_id)};
  1156. }
  1157. // Imports the definition for an interface that has been imported as a forward
  1158. // declaration.
  1159. auto AddInterfaceDefinition(const SemIR::Interface& import_interface,
  1160. SemIR::Interface& new_interface,
  1161. SemIR::InstId self_param_id) -> void {
  1162. new_interface.scope_id = context_.name_scopes().Add(
  1163. new_interface.decl_id, SemIR::NameId::Invalid,
  1164. new_interface.parent_scope_id);
  1165. auto& new_scope = context_.name_scopes().Get(new_interface.scope_id);
  1166. const auto& import_scope =
  1167. import_ir_.name_scopes().Get(import_interface.scope_id);
  1168. // Push a block so that we can add scoped instructions to it.
  1169. context_.inst_block_stack().Push();
  1170. AddNameScopeImportRefs(import_scope, new_scope);
  1171. new_interface.associated_entities_id =
  1172. AddAssociatedEntities(import_interface.associated_entities_id);
  1173. new_interface.body_block_id = context_.inst_block_stack().Pop();
  1174. new_interface.self_param_id = self_param_id;
  1175. CARBON_CHECK(import_scope.extended_scopes.empty())
  1176. << "Interfaces don't currently have extended scopes to support.";
  1177. }
  1178. auto TryResolveTypedInst(SemIR::InterfaceDecl inst,
  1179. SemIR::ConstantId interface_const_id)
  1180. -> ResolveResult {
  1181. const auto& import_interface =
  1182. import_ir_.interfaces().Get(inst.interface_id);
  1183. SemIR::InterfaceId interface_id = SemIR::InterfaceId::Invalid;
  1184. if (!interface_const_id.is_valid()) {
  1185. // On the first pass, create a forward declaration of the interface.
  1186. std::tie(interface_id, interface_const_id) =
  1187. MakeInterfaceDecl(import_interface);
  1188. } else {
  1189. // On the second pass, compute the interface ID from the constant value of
  1190. // the declaration.
  1191. auto interface_const_inst = context_.insts().Get(
  1192. context_.constant_values().GetInstId(interface_const_id));
  1193. if (auto interface_type =
  1194. interface_const_inst.TryAs<SemIR::InterfaceType>()) {
  1195. interface_id = interface_type->interface_id;
  1196. } else {
  1197. auto generic_interface_type =
  1198. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1199. interface_const_inst.type_id());
  1200. interface_id = generic_interface_type.interface_id;
  1201. }
  1202. }
  1203. auto initial_work = work_stack_.size();
  1204. auto parent_scope_id =
  1205. GetLocalNameScopeId(import_interface.parent_scope_id);
  1206. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  1207. GetLocalParamConstantIds(import_interface.implicit_param_refs_id);
  1208. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  1209. GetLocalParamConstantIds(import_interface.param_refs_id);
  1210. auto self_param_id = GetLocalConstantInstId(import_interface.self_param_id);
  1211. if (HasNewWork(initial_work)) {
  1212. return ResolveResult::Retry(interface_const_id);
  1213. }
  1214. auto& new_interface = context_.interfaces().Get(interface_id);
  1215. new_interface.parent_scope_id = parent_scope_id;
  1216. new_interface.implicit_param_refs_id = GetLocalParamRefsId(
  1217. import_interface.implicit_param_refs_id, implicit_param_const_ids);
  1218. new_interface.param_refs_id =
  1219. GetLocalParamRefsId(import_interface.param_refs_id, param_const_ids);
  1220. if (import_interface.is_defined()) {
  1221. AddInterfaceDefinition(import_interface, new_interface, self_param_id);
  1222. }
  1223. return {.const_id = interface_const_id};
  1224. }
  1225. auto TryResolveTypedInst(SemIR::InterfaceType inst) -> ResolveResult {
  1226. auto initial_work = work_stack_.size();
  1227. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1228. auto interface_const_id = GetLocalConstantId(
  1229. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  1230. auto args = GetLocalGenericInstanceArgs(inst.instance_id);
  1231. if (HasNewWork(initial_work)) {
  1232. return ResolveResult::Retry();
  1233. }
  1234. // Find the corresponding interface type. For a non-generic interface, this
  1235. // is the type of the interface declaration. For a generic interface, build
  1236. // a interface type referencing this specialization of the generic
  1237. // interface.
  1238. auto interface_const_inst = context_.insts().Get(
  1239. context_.constant_values().GetInstId(interface_const_id));
  1240. if (interface_const_inst.Is<SemIR::InterfaceType>()) {
  1241. return {.const_id = interface_const_id};
  1242. } else {
  1243. auto generic_interface_type =
  1244. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1245. interface_const_inst.type_id());
  1246. auto instance_id = GetLocalGenericInstance(inst.instance_id, args);
  1247. return ResolveAs<SemIR::InterfaceType>(
  1248. {.type_id = SemIR::TypeId::TypeType,
  1249. .interface_id = generic_interface_type.interface_id,
  1250. .instance_id = instance_id});
  1251. }
  1252. }
  1253. auto TryResolveTypedInst(SemIR::InterfaceWitness inst) -> ResolveResult {
  1254. auto initial_work = work_stack_.size();
  1255. auto elements = GetLocalInstBlockContents(inst.elements_id);
  1256. if (HasNewWork(initial_work)) {
  1257. return ResolveResult::Retry();
  1258. }
  1259. auto elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elements);
  1260. return ResolveAs<SemIR::InterfaceWitness>(
  1261. {.type_id = context_.GetBuiltinType(SemIR::BuiltinKind::WitnessType),
  1262. .elements_id = elements_id});
  1263. }
  1264. auto TryResolveTypedInst(SemIR::IntLiteral inst) -> ResolveResult {
  1265. auto initial_work = work_stack_.size();
  1266. auto type_id = GetLocalConstantId(inst.type_id);
  1267. if (HasNewWork(initial_work)) {
  1268. return ResolveResult::Retry();
  1269. }
  1270. return ResolveAs<SemIR::IntLiteral>(
  1271. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1272. .int_id = context_.ints().Add(import_ir_.ints().Get(inst.int_id))});
  1273. }
  1274. auto TryResolveTypedInst(SemIR::PointerType inst) -> ResolveResult {
  1275. auto initial_work = work_stack_.size();
  1276. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1277. auto pointee_const_id = GetLocalConstantId(inst.pointee_id);
  1278. if (HasNewWork(initial_work)) {
  1279. return ResolveResult::Retry();
  1280. }
  1281. auto pointee_type_id = context_.GetTypeIdForTypeConstant(pointee_const_id);
  1282. return ResolveAs<SemIR::PointerType>(
  1283. {.type_id = SemIR::TypeId::TypeType, .pointee_id = pointee_type_id});
  1284. }
  1285. auto TryResolveTypedInst(SemIR::StructType inst, SemIR::InstId import_inst_id)
  1286. -> ResolveResult {
  1287. // Collect all constants first, locating unresolved ones in a single pass.
  1288. auto initial_work = work_stack_.size();
  1289. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1290. auto orig_fields = import_ir_.inst_blocks().Get(inst.fields_id);
  1291. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  1292. field_const_ids.reserve(orig_fields.size());
  1293. for (auto field_id : orig_fields) {
  1294. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1295. field_const_ids.push_back(GetLocalConstantId(field.field_type_id));
  1296. }
  1297. if (HasNewWork(initial_work)) {
  1298. return ResolveResult::Retry();
  1299. }
  1300. // Prepare a vector of fields for GetStructType.
  1301. // TODO: Should we have field constants so that we can deduplicate fields
  1302. // without creating instructions here?
  1303. llvm::SmallVector<SemIR::InstId> fields;
  1304. fields.reserve(orig_fields.size());
  1305. for (auto [field_id, field_const_id] :
  1306. llvm::zip(orig_fields, field_const_ids)) {
  1307. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1308. auto name_id = GetLocalNameId(field.name_id);
  1309. auto field_type_id = context_.GetTypeIdForTypeConstant(field_const_id);
  1310. fields.push_back(context_.AddInstInNoBlock<SemIR::StructTypeField>(
  1311. AddImportIRInst(import_inst_id),
  1312. {.name_id = name_id, .field_type_id = field_type_id}));
  1313. }
  1314. return ResolveAs<SemIR::StructType>(
  1315. {.type_id = SemIR::TypeId::TypeType,
  1316. .fields_id = context_.inst_blocks().AddCanonical(fields)});
  1317. }
  1318. auto TryResolveTypedInst(SemIR::StructValue inst) -> ResolveResult {
  1319. auto initial_work = work_stack_.size();
  1320. auto type_id = GetLocalConstantId(inst.type_id);
  1321. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1322. if (HasNewWork(initial_work)) {
  1323. return ResolveResult::Retry();
  1324. }
  1325. return ResolveAs<SemIR::StructValue>(
  1326. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1327. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1328. }
  1329. auto TryResolveTypedInst(SemIR::TupleType inst) -> ResolveResult {
  1330. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1331. // Collect all constants first, locating unresolved ones in a single pass.
  1332. auto initial_work = work_stack_.size();
  1333. auto orig_elem_type_ids = import_ir_.type_blocks().Get(inst.elements_id);
  1334. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  1335. elem_const_ids.reserve(orig_elem_type_ids.size());
  1336. for (auto elem_type_id : orig_elem_type_ids) {
  1337. elem_const_ids.push_back(GetLocalConstantId(elem_type_id));
  1338. }
  1339. if (HasNewWork(initial_work)) {
  1340. return ResolveResult::Retry();
  1341. }
  1342. // Prepare a vector of the tuple types for GetTupleType.
  1343. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  1344. elem_type_ids.reserve(orig_elem_type_ids.size());
  1345. for (auto elem_const_id : elem_const_ids) {
  1346. elem_type_ids.push_back(context_.GetTypeIdForTypeConstant(elem_const_id));
  1347. }
  1348. return {.const_id = context_.types().GetConstantId(
  1349. context_.GetTupleType(elem_type_ids))};
  1350. }
  1351. auto TryResolveTypedInst(SemIR::TupleValue inst) -> ResolveResult {
  1352. auto initial_work = work_stack_.size();
  1353. auto type_id = GetLocalConstantId(inst.type_id);
  1354. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1355. if (HasNewWork(initial_work)) {
  1356. return ResolveResult::Retry();
  1357. }
  1358. return ResolveAs<SemIR::TupleValue>(
  1359. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1360. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1361. }
  1362. auto TryResolveTypedInst(SemIR::UnboundElementType inst) -> ResolveResult {
  1363. auto initial_work = work_stack_.size();
  1364. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1365. auto class_const_id = GetLocalConstantId(inst.class_type_id);
  1366. auto elem_const_id = GetLocalConstantId(inst.element_type_id);
  1367. if (HasNewWork(initial_work)) {
  1368. return ResolveResult::Retry();
  1369. }
  1370. return ResolveAs<SemIR::UnboundElementType>(
  1371. {.type_id = SemIR::TypeId::TypeType,
  1372. .class_type_id = context_.GetTypeIdForTypeConstant(class_const_id),
  1373. .element_type_id = context_.GetTypeIdForTypeConstant(elem_const_id)});
  1374. }
  1375. auto import_ir_constant_values() -> SemIR::ConstantValueStore& {
  1376. return context_.import_ir_constant_values()[import_ir_id_.index];
  1377. }
  1378. Context& context_;
  1379. SemIR::ImportIRId import_ir_id_;
  1380. const SemIR::File& import_ir_;
  1381. llvm::SmallVector<Work> work_stack_;
  1382. };
  1383. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  1384. // loaded (including the one pointed at directly by the ImportRef), and the
  1385. // final instruction's type ID.
  1386. //
  1387. // This addresses cases where an ImportRefUnloaded may point at another
  1388. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  1389. // constant-evaluated version of the instruction to work with.
  1390. static auto GetInstForLoad(Context& context,
  1391. SemIR::ImportIRInstId import_ir_inst_id)
  1392. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  1393. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  1394. {}, SemIR::TypeId::Invalid};
  1395. auto& [import_ir_insts, type_id] = result;
  1396. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  1397. // The first ImportIRInst is added directly because the IR doesn't need to be
  1398. // localized.
  1399. import_ir_insts.push_back(import_ir_inst);
  1400. const auto* cursor_ir = context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1401. while (true) {
  1402. auto cursor_inst = cursor_ir->insts().Get(import_ir_inst.inst_id);
  1403. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  1404. if (!import_ref) {
  1405. type_id = cursor_inst.type_id();
  1406. return result;
  1407. }
  1408. import_ir_inst =
  1409. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  1410. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1411. import_ir_insts.push_back(
  1412. {.ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  1413. .is_export = false,
  1414. .sem_ir = cursor_ir}),
  1415. .inst_id = import_ir_inst.inst_id});
  1416. }
  1417. }
  1418. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  1419. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  1420. if (!inst) {
  1421. return;
  1422. }
  1423. auto [indirect_insts, load_type_id] =
  1424. GetInstForLoad(context, inst->import_ir_inst_id);
  1425. // The last indirect instruction is the one to resolve. Pop it here because
  1426. // Resolve will assign the constant.
  1427. auto load_ir_inst = indirect_insts.pop_back_val();
  1428. ImportRefResolver resolver(context, load_ir_inst.ir_id);
  1429. // The resolver calls into Context to create instructions. Don't register
  1430. // those instructions as part of the enclosing generic scope if they're
  1431. // dependent on a generic parameter.
  1432. context.generic_region_stack().Push();
  1433. auto type_id = resolver.ResolveType(load_type_id);
  1434. auto constant_id = resolver.Resolve(load_ir_inst.inst_id);
  1435. context.generic_region_stack().Pop();
  1436. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  1437. // doesn't use ReplaceInstBeforeConstantUse because it would trigger
  1438. // TryEvalInst, which we want to avoid with ImportRefs.
  1439. context.sem_ir().insts().Set(
  1440. inst_id,
  1441. SemIR::ImportRefLoaded{.type_id = type_id,
  1442. .import_ir_inst_id = inst->import_ir_inst_id,
  1443. .bind_name_id = inst->bind_name_id});
  1444. // Store the constant for both the ImportRefLoaded and indirect instructions.
  1445. context.constant_values().Set(inst_id, constant_id);
  1446. for (const auto& import_ir_inst : indirect_insts) {
  1447. context.import_ir_constant_values()[import_ir_inst.ir_id.index].Set(
  1448. import_ir_inst.inst_id, constant_id);
  1449. }
  1450. }
  1451. // Imports the impl `import_impl_id` from the imported IR `import_ir`.
  1452. static auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  1453. const SemIR::File& import_ir,
  1454. SemIR::ImplId import_impl_id) -> void {
  1455. // Resolve the imported impl to a local impl ID.
  1456. ImportRefResolver resolver(context, import_ir_id);
  1457. const auto& import_impl = import_ir.impls().Get(import_impl_id);
  1458. auto self_id = resolver.ResolveType(import_impl.self_id);
  1459. auto constraint_id = resolver.ResolveType(import_impl.constraint_id);
  1460. // Import the definition if the impl is defined.
  1461. // TODO: Do we need to check for multiple definitions?
  1462. auto impl_id = context.impls().LookupOrAdd(self_id, constraint_id);
  1463. if (import_impl.is_defined()) {
  1464. // TODO: Create a scope for the `impl` if necessary.
  1465. // TODO: Consider importing the definition_id.
  1466. auto& impl = context.impls().Get(impl_id);
  1467. impl.witness_id = AddImportRef(
  1468. context, {.ir_id = import_ir_id, .inst_id = import_impl.witness_id},
  1469. SemIR::BindNameId::Invalid);
  1470. }
  1471. }
  1472. // TODO: This doesn't belong in this file. Consider moving the import resolver
  1473. // and this file elsewhere.
  1474. auto ImportImpls(Context& context) -> void {
  1475. for (auto [import_index, import_ir] :
  1476. llvm::enumerate(context.import_irs().array_ref())) {
  1477. if (!import_ir.sem_ir) {
  1478. continue;
  1479. }
  1480. auto import_ir_id = SemIR::ImportIRId(import_index);
  1481. for (auto impl_index : llvm::seq(import_ir.sem_ir->impls().size())) {
  1482. auto impl_id = SemIR::ImplId(impl_index);
  1483. ImportImpl(context, import_ir_id, *import_ir.sem_ir, impl_id);
  1484. }
  1485. }
  1486. }
  1487. } // namespace Carbon::Check