import_ref.cpp 56 KB

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