import_ref.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411
  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. // 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 = 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 = 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<SemIR::Param>(
  395. AddImportIRInst(param_id), {.type_id = type_id, .name_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. .parent_scope_id = SemIR::NameScopeId::Invalid,
  402. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  403. new_param_id = context_.AddInstInNoBlock<SemIR::BindName>(
  404. AddImportIRInst(bind_id), {.type_id = type_id,
  405. .bind_name_id = bind_name_id,
  406. .value_id = new_param_id});
  407. break;
  408. }
  409. case SemIR::BindSymbolicName::Kind: {
  410. // The symbolic name will be created on first reference, so might
  411. // already exist. Update the value in it to refer to the parameter.
  412. auto new_bind_inst_id = GetLocalConstantId(bind_id).inst_id();
  413. auto new_bind_inst =
  414. context_.insts().GetAs<SemIR::BindSymbolicName>(
  415. new_bind_inst_id);
  416. new_bind_inst.value_id = new_param_id;
  417. // This is not before constant use, but doesn't change the
  418. // constant value of the instruction.
  419. context_.ReplaceInstBeforeConstantUse(new_bind_inst_id,
  420. new_bind_inst);
  421. new_param_id = new_bind_inst_id;
  422. break;
  423. }
  424. default: {
  425. CARBON_FATAL() << "Unexpected kind: " << bind_inst->kind;
  426. }
  427. }
  428. }
  429. if (addr_inst) {
  430. new_param_id = context_.AddInstInNoBlock<SemIR::AddrPattern>(
  431. AddImportIRInst(ref_id),
  432. {.type_id = type_id, .inner_id = new_param_id});
  433. }
  434. new_param_refs.push_back(new_param_id);
  435. }
  436. return context_.inst_blocks().Add(new_param_refs);
  437. }
  438. // Translates a NameId from the import IR to a local NameId.
  439. auto GetLocalNameId(SemIR::NameId import_name_id) -> SemIR::NameId {
  440. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.is_valid()) {
  441. return SemIR::NameId::ForIdentifier(
  442. context_.identifiers().Add(import_ir_.identifiers().Get(ident_id)));
  443. }
  444. return import_name_id;
  445. }
  446. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  447. // unresolved constants to the work stack.
  448. auto GetLocalNameScopeId(SemIR::NameScopeId name_scope_id)
  449. -> SemIR::NameScopeId {
  450. auto [inst_id, inst] =
  451. import_ir_.name_scopes().GetInstIfValid(name_scope_id);
  452. if (!inst) {
  453. // Map scopes that aren't associated with an instruction to invalid
  454. // scopes. For now, such scopes aren't used, and we don't have a good way
  455. // to remap them.
  456. return SemIR::NameScopeId::Invalid;
  457. }
  458. if (inst->Is<SemIR::ImplDecl>()) {
  459. // TODO: Import the scope for an `impl` definition.
  460. return SemIR::NameScopeId::Invalid;
  461. }
  462. auto const_id = GetLocalConstantId(inst_id);
  463. if (!const_id.is_valid()) {
  464. return SemIR::NameScopeId::Invalid;
  465. }
  466. auto name_scope_inst = context_.insts().Get(const_id.inst_id());
  467. CARBON_KIND_SWITCH(name_scope_inst) {
  468. case CARBON_KIND(SemIR::Namespace inst): {
  469. return inst.name_scope_id;
  470. }
  471. case CARBON_KIND(SemIR::ClassType inst): {
  472. return context_.classes().Get(inst.class_id).scope_id;
  473. }
  474. case CARBON_KIND(SemIR::InterfaceType inst): {
  475. return context_.interfaces().Get(inst.interface_id).scope_id;
  476. }
  477. default:
  478. if (const_id == SemIR::ConstantId::Error) {
  479. return SemIR::NameScopeId::Invalid;
  480. }
  481. CARBON_FATAL() << "Unexpected instruction kind for name scope: "
  482. << name_scope_inst;
  483. }
  484. }
  485. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  486. // lookup.
  487. auto AddNameScopeImportRefs(const SemIR::NameScope& import_scope,
  488. SemIR::NameScope& new_scope) -> void {
  489. for (auto [entry_name_id, entry_inst_id] : import_scope.names) {
  490. auto ref_id = AddImportRef(
  491. context_, {.ir_id = import_ir_id_, .inst_id = entry_inst_id},
  492. SemIR::BindNameId::Invalid);
  493. CARBON_CHECK(
  494. new_scope.names.insert({GetLocalNameId(entry_name_id), ref_id})
  495. .second);
  496. }
  497. }
  498. // Given a block ID for a list of associated entities of a witness, returns a
  499. // version localized to the current IR.
  500. auto AddAssociatedEntities(SemIR::InstBlockId associated_entities_id)
  501. -> SemIR::InstBlockId {
  502. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  503. return SemIR::InstBlockId::Empty;
  504. }
  505. auto associated_entities =
  506. import_ir_.inst_blocks().Get(associated_entities_id);
  507. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  508. new_associated_entities.reserve(associated_entities.size());
  509. for (auto inst_id : associated_entities) {
  510. new_associated_entities.push_back(
  511. AddImportRef(context_, {.ir_id = import_ir_id_, .inst_id = inst_id},
  512. SemIR::BindNameId::Invalid));
  513. }
  514. return context_.inst_blocks().Add(new_associated_entities);
  515. }
  516. // Tries to resolve the InstId, returning a constant when ready, or Invalid if
  517. // more has been added to the stack. A similar API is followed for all
  518. // following TryResolveTypedInst helper functions.
  519. //
  520. // `const_id` is Invalid unless we've tried to resolve this instruction
  521. // before, in which case it's the previous result.
  522. //
  523. // TODO: Error is returned when support is missing, but that should go away.
  524. auto TryResolveInst(SemIR::InstId inst_id, SemIR::ConstantId const_id)
  525. -> ResolveResult {
  526. if (inst_id.is_builtin()) {
  527. CARBON_CHECK(!const_id.is_valid());
  528. // Constants for builtins can be directly copied.
  529. return {.const_id = context_.constant_values().Get(inst_id)};
  530. }
  531. auto untyped_inst = import_ir_.insts().Get(inst_id);
  532. CARBON_KIND_SWITCH(untyped_inst) {
  533. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  534. return TryResolveTypedInst(inst);
  535. }
  536. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  537. return TryResolveTypedInst(inst);
  538. }
  539. case CARBON_KIND(SemIR::BaseDecl inst): {
  540. return TryResolveTypedInst(inst, inst_id);
  541. }
  542. case CARBON_KIND(SemIR::BindAlias inst): {
  543. return TryResolveTypedInst(inst);
  544. }
  545. case CARBON_KIND(SemIR::BindName inst): {
  546. // TODO: This always returns `ConstantId::NotConstant`.
  547. return {.const_id = TryEvalInst(context_, inst_id, inst)};
  548. }
  549. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  550. return TryResolveTypedInst(inst, inst_id);
  551. }
  552. case CARBON_KIND(SemIR::ClassDecl inst): {
  553. return TryResolveTypedInst(inst, const_id);
  554. }
  555. case CARBON_KIND(SemIR::ClassType inst): {
  556. return TryResolveTypedInst(inst);
  557. }
  558. case CARBON_KIND(SemIR::ConstType inst): {
  559. return TryResolveTypedInst(inst);
  560. }
  561. case CARBON_KIND(SemIR::ExportDecl inst): {
  562. return TryResolveTypedInst(inst);
  563. }
  564. case CARBON_KIND(SemIR::FieldDecl inst): {
  565. return TryResolveTypedInst(inst, inst_id);
  566. }
  567. case CARBON_KIND(SemIR::FunctionDecl inst): {
  568. return TryResolveTypedInst(inst);
  569. }
  570. case CARBON_KIND(SemIR::FunctionType inst): {
  571. return TryResolveTypedInst(inst);
  572. }
  573. case CARBON_KIND(SemIR::GenericClassType inst): {
  574. return TryResolveTypedInst(inst);
  575. }
  576. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  577. return TryResolveTypedInst(inst, inst_id);
  578. }
  579. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  580. return TryResolveTypedInst(inst, const_id);
  581. }
  582. case CARBON_KIND(SemIR::InterfaceWitness inst): {
  583. return TryResolveTypedInst(inst);
  584. }
  585. case CARBON_KIND(SemIR::InterfaceType inst): {
  586. return TryResolveTypedInst(inst);
  587. }
  588. case CARBON_KIND(SemIR::PointerType inst): {
  589. return TryResolveTypedInst(inst);
  590. }
  591. case CARBON_KIND(SemIR::StructType inst): {
  592. return TryResolveTypedInst(inst, inst_id);
  593. }
  594. case CARBON_KIND(SemIR::TupleType inst): {
  595. return TryResolveTypedInst(inst);
  596. }
  597. case CARBON_KIND(SemIR::UnboundElementType inst): {
  598. return TryResolveTypedInst(inst);
  599. }
  600. default:
  601. context_.TODO(
  602. SemIR::LocId(AddImportIRInst(inst_id)),
  603. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  604. return {.const_id = SemIR::ConstantId::Error};
  605. }
  606. }
  607. auto TryResolveTypedInst(SemIR::AssociatedEntity inst) -> ResolveResult {
  608. auto initial_work = work_stack_.size();
  609. auto type_const_id = GetLocalConstantId(inst.type_id);
  610. if (HasNewWork(initial_work)) {
  611. return ResolveResult::Retry();
  612. }
  613. // Add a lazy reference to the target declaration.
  614. auto decl_id = AddImportRef(
  615. context_, {.ir_id = import_ir_id_, .inst_id = inst.decl_id},
  616. SemIR::BindNameId::Invalid);
  617. auto inst_id = context_.AddInstInNoBlock<SemIR::AssociatedEntity>(
  618. AddImportIRInst(inst.decl_id),
  619. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  620. .index = inst.index,
  621. .decl_id = decl_id});
  622. return {.const_id = context_.constant_values().Get(inst_id)};
  623. }
  624. auto TryResolveTypedInst(SemIR::AssociatedEntityType inst) -> ResolveResult {
  625. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  626. auto initial_work = work_stack_.size();
  627. auto entity_type_const_id = GetLocalConstantId(inst.entity_type_id);
  628. auto interface_const_id = GetLocalConstantId(
  629. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  630. if (HasNewWork(initial_work)) {
  631. return ResolveResult::Retry();
  632. }
  633. // TODO: Should this track the source?
  634. auto inst_id = context_.AddInstInNoBlock(
  635. SemIR::LocIdAndInst::NoLoc<SemIR::AssociatedEntityType>(
  636. {.type_id = SemIR::TypeId::TypeType,
  637. .interface_id =
  638. context_.insts()
  639. .GetAs<SemIR::InterfaceType>(interface_const_id.inst_id())
  640. .interface_id,
  641. .entity_type_id =
  642. context_.GetTypeIdForTypeConstant(entity_type_const_id)}));
  643. return {.const_id = context_.constant_values().Get(inst_id)};
  644. }
  645. auto TryResolveTypedInst(SemIR::BaseDecl inst, SemIR::InstId import_inst_id)
  646. -> ResolveResult {
  647. auto initial_work = work_stack_.size();
  648. auto type_const_id = GetLocalConstantId(inst.type_id);
  649. auto base_type_const_id = GetLocalConstantId(inst.base_type_id);
  650. if (HasNewWork(initial_work)) {
  651. return ResolveResult::Retry();
  652. }
  653. // Import the instruction in order to update contained base_type_id.
  654. auto inst_id = context_.AddInstInNoBlock<SemIR::BaseDecl>(
  655. AddImportIRInst(import_inst_id),
  656. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  657. .base_type_id = context_.GetTypeIdForTypeConstant(base_type_const_id),
  658. .index = inst.index});
  659. return {.const_id = context_.constant_values().Get(inst_id)};
  660. }
  661. auto TryResolveTypedInst(SemIR::BindAlias inst) -> ResolveResult {
  662. auto initial_work = work_stack_.size();
  663. auto value_id = GetLocalConstantId(inst.value_id);
  664. if (HasNewWork(initial_work)) {
  665. return ResolveResult::Retry();
  666. }
  667. return {.const_id = value_id};
  668. }
  669. auto TryResolveTypedInst(SemIR::BindSymbolicName inst,
  670. SemIR::InstId import_inst_id) -> ResolveResult {
  671. auto initial_work = work_stack_.size();
  672. auto type_id = GetLocalConstantId(inst.type_id);
  673. if (HasNewWork(initial_work)) {
  674. return ResolveResult::Retry();
  675. }
  676. const auto& import_bind_info =
  677. import_ir_.bind_names().Get(inst.bind_name_id);
  678. auto name_id = GetLocalNameId(import_bind_info.name_id);
  679. auto bind_name_id = context_.bind_names().Add(
  680. {.name_id = name_id,
  681. .parent_scope_id = SemIR::NameScopeId::Invalid,
  682. .bind_index = import_bind_info.bind_index});
  683. auto new_bind_id = context_.AddInstInNoBlock<SemIR::BindSymbolicName>(
  684. AddImportIRInst(import_inst_id),
  685. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  686. .bind_name_id = bind_name_id,
  687. .value_id = SemIR::InstId::Invalid});
  688. return {.const_id = context_.constant_values().Get(new_bind_id)};
  689. }
  690. // Makes an incomplete class. This is necessary even with classes with a
  691. // complete declaration, because things such as `Self` may refer back to the
  692. // type.
  693. auto MakeIncompleteClass(const SemIR::Class& import_class)
  694. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  695. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeId::TypeType,
  696. .class_id = SemIR::ClassId::Invalid,
  697. .decl_block_id = SemIR::InstBlockId::Empty};
  698. auto class_decl_id = context_.AddPlaceholderInstInNoBlock(
  699. SemIR::LocIdAndInst(AddImportIRInst(import_class.decl_id), class_decl));
  700. // Regardless of whether ClassDecl is a complete type, we first need an
  701. // incomplete type so that any references have something to point at.
  702. class_decl.class_id = context_.classes().Add({
  703. .name_id = GetLocalNameId(import_class.name_id),
  704. // These are set in the second pass once we've imported them. Import
  705. // enough of the parameter lists that we know whether this class is a
  706. // generic class and can build the right constant value for it.
  707. // TODO: Add a better way to represent a generic `Class` prior to
  708. // importing the parameters.
  709. .parent_scope_id = SemIR::NameScopeId::Invalid,
  710. .implicit_param_refs_id = import_class.implicit_param_refs_id.is_valid()
  711. ? SemIR::InstBlockId::Empty
  712. : SemIR::InstBlockId::Invalid,
  713. .param_refs_id = import_class.param_refs_id.is_valid()
  714. ? SemIR::InstBlockId::Empty
  715. : SemIR::InstBlockId::Invalid,
  716. .self_type_id = SemIR::TypeId::Invalid,
  717. // These fields can be set immediately.
  718. .decl_id = class_decl_id,
  719. .inheritance_kind = import_class.inheritance_kind,
  720. });
  721. if (import_class.is_generic()) {
  722. class_decl.type_id = context_.GetGenericClassType(class_decl.class_id);
  723. }
  724. // Write the class ID into the ClassDecl.
  725. context_.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  726. auto self_const_id = context_.constant_values().Get(class_decl_id);
  727. return {class_decl.class_id, self_const_id};
  728. }
  729. // Fills out the class definition for an incomplete class.
  730. auto AddClassDefinition(const SemIR::Class& import_class,
  731. SemIR::Class& new_class,
  732. SemIR::ConstantId object_repr_const_id,
  733. SemIR::ConstantId base_const_id) -> void {
  734. new_class.definition_id = new_class.decl_id;
  735. new_class.object_repr_id =
  736. context_.GetTypeIdForTypeConstant(object_repr_const_id);
  737. new_class.scope_id = context_.name_scopes().Add(
  738. new_class.decl_id, SemIR::NameId::Invalid, new_class.parent_scope_id);
  739. auto& new_scope = context_.name_scopes().Get(new_class.scope_id);
  740. const auto& import_scope =
  741. import_ir_.name_scopes().Get(import_class.scope_id);
  742. // Push a block so that we can add scoped instructions to it.
  743. context_.inst_block_stack().Push();
  744. AddNameScopeImportRefs(import_scope, new_scope);
  745. new_class.body_block_id = context_.inst_block_stack().Pop();
  746. if (import_class.base_id.is_valid()) {
  747. new_class.base_id = base_const_id.inst_id();
  748. // Add the base scope to extended scopes.
  749. auto base_inst_id = context_.types().GetInstId(
  750. context_.insts()
  751. .GetAs<SemIR::BaseDecl>(new_class.base_id)
  752. .base_type_id);
  753. const auto& base_class = context_.classes().Get(
  754. context_.insts().GetAs<SemIR::ClassType>(base_inst_id).class_id);
  755. new_scope.extended_scopes.push_back(base_class.scope_id);
  756. }
  757. CARBON_CHECK(new_scope.extended_scopes.size() ==
  758. import_scope.extended_scopes.size());
  759. }
  760. auto TryResolveTypedInst(SemIR::ClassDecl inst,
  761. SemIR::ConstantId class_const_id) -> ResolveResult {
  762. // TODO: The handling of interfaces repeats a lot with the handling of
  763. // classes, and will likely also be repeated for named constraints and
  764. // choice types. Factor out some of this functionality.
  765. const auto& import_class = import_ir_.classes().Get(inst.class_id);
  766. SemIR::ClassId class_id = SemIR::ClassId::Invalid;
  767. if (!class_const_id.is_valid()) {
  768. // On the first pass, create a forward declaration of the class for any
  769. // recursive references.
  770. std::tie(class_id, class_const_id) = MakeIncompleteClass(import_class);
  771. } else {
  772. // On the second pass, compute the class ID from the constant value of the
  773. // declaration.
  774. auto class_const_inst = context_.insts().Get(class_const_id.inst_id());
  775. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  776. class_id = class_type->class_id;
  777. } else {
  778. auto generic_class_type =
  779. context_.types().GetAs<SemIR::GenericClassType>(
  780. class_const_inst.type_id());
  781. class_id = generic_class_type.class_id;
  782. }
  783. }
  784. // Load constants for the definition.
  785. auto initial_work = work_stack_.size();
  786. auto parent_scope_id = GetLocalNameScopeId(import_class.parent_scope_id);
  787. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  788. GetLocalParamConstantIds(import_class.implicit_param_refs_id);
  789. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  790. GetLocalParamConstantIds(import_class.param_refs_id);
  791. auto self_const_id = GetLocalConstantId(import_class.self_type_id);
  792. auto object_repr_const_id =
  793. import_class.object_repr_id.is_valid()
  794. ? GetLocalConstantId(import_class.object_repr_id)
  795. : SemIR::ConstantId::Invalid;
  796. auto base_const_id = import_class.base_id.is_valid()
  797. ? GetLocalConstantId(import_class.base_id)
  798. : SemIR::ConstantId::Invalid;
  799. if (HasNewWork(initial_work)) {
  800. return ResolveResult::Retry(class_const_id);
  801. }
  802. auto& new_class = context_.classes().Get(class_id);
  803. new_class.parent_scope_id = parent_scope_id;
  804. new_class.implicit_param_refs_id = GetLocalParamRefsId(
  805. import_class.implicit_param_refs_id, implicit_param_const_ids);
  806. new_class.param_refs_id =
  807. GetLocalParamRefsId(import_class.param_refs_id, param_const_ids);
  808. new_class.self_type_id = context_.GetTypeIdForTypeConstant(self_const_id);
  809. if (import_class.is_defined()) {
  810. AddClassDefinition(import_class, new_class, object_repr_const_id,
  811. base_const_id);
  812. }
  813. return {.const_id = class_const_id};
  814. }
  815. auto TryResolveTypedInst(SemIR::ClassType inst) -> ResolveResult {
  816. auto initial_work = work_stack_.size();
  817. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  818. auto class_const_id =
  819. GetLocalConstantId(import_ir_.classes().Get(inst.class_id).decl_id);
  820. if (HasNewWork(initial_work)) {
  821. return ResolveResult::Retry();
  822. }
  823. return {.const_id = class_const_id};
  824. }
  825. auto TryResolveTypedInst(SemIR::ConstType inst) -> ResolveResult {
  826. auto initial_work = work_stack_.size();
  827. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  828. auto inner_const_id = GetLocalConstantId(inst.inner_id);
  829. if (HasNewWork(initial_work)) {
  830. return ResolveResult::Retry();
  831. }
  832. auto inner_type_id = context_.GetTypeIdForTypeConstant(inner_const_id);
  833. // TODO: Should ConstType have a wrapper for this similar to the others?
  834. return {.const_id =
  835. TryEvalInst(context_, SemIR::InstId::Invalid,
  836. SemIR::ConstType{.type_id = SemIR::TypeId::TypeType,
  837. .inner_id = inner_type_id})};
  838. }
  839. auto TryResolveTypedInst(SemIR::ExportDecl inst) -> ResolveResult {
  840. auto initial_work = work_stack_.size();
  841. auto value_id = GetLocalConstantId(inst.value_id);
  842. if (HasNewWork(initial_work)) {
  843. return ResolveResult::Retry();
  844. }
  845. return {.const_id = value_id};
  846. }
  847. auto TryResolveTypedInst(SemIR::FieldDecl inst, SemIR::InstId import_inst_id)
  848. -> ResolveResult {
  849. auto initial_work = work_stack_.size();
  850. auto const_id = GetLocalConstantId(inst.type_id);
  851. if (HasNewWork(initial_work)) {
  852. return ResolveResult::Retry();
  853. }
  854. auto inst_id = context_.AddInstInNoBlock<SemIR::FieldDecl>(
  855. AddImportIRInst(import_inst_id),
  856. {.type_id = context_.GetTypeIdForTypeConstant(const_id),
  857. .name_id = GetLocalNameId(inst.name_id),
  858. .index = inst.index});
  859. return {.const_id = context_.constant_values().Get(inst_id)};
  860. }
  861. auto TryResolveTypedInst(SemIR::FunctionDecl inst) -> ResolveResult {
  862. auto initial_work = work_stack_.size();
  863. const auto& function = import_ir_.functions().Get(inst.function_id);
  864. auto return_type_const_id = SemIR::ConstantId::Invalid;
  865. if (function.return_type_id.is_valid()) {
  866. return_type_const_id = GetLocalConstantId(function.return_type_id);
  867. }
  868. auto parent_scope_id = GetLocalNameScopeId(function.parent_scope_id);
  869. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  870. GetLocalParamConstantIds(function.implicit_param_refs_id);
  871. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  872. GetLocalParamConstantIds(function.param_refs_id);
  873. if (HasNewWork(initial_work)) {
  874. return ResolveResult::Retry();
  875. }
  876. // Add the function declaration.
  877. SemIR::FunctionDecl function_decl = {
  878. .type_id = SemIR::TypeId::Invalid,
  879. .function_id = SemIR::FunctionId::Invalid,
  880. .decl_block_id = SemIR::InstBlockId::Empty};
  881. // Prefer pointing diagnostics towards a definition.
  882. auto import_ir_inst_id = AddImportIRInst(function.definition_id.is_valid()
  883. ? function.definition_id
  884. : function.decl_id);
  885. auto function_decl_id = context_.AddPlaceholderInstInNoBlock(
  886. SemIR::LocIdAndInst(import_ir_inst_id, function_decl));
  887. auto new_return_type_id =
  888. return_type_const_id.is_valid()
  889. ? context_.GetTypeIdForTypeConstant(return_type_const_id)
  890. : SemIR::TypeId::Invalid;
  891. auto new_return_storage = SemIR::InstId::Invalid;
  892. if (function.return_storage_id.is_valid()) {
  893. // Recreate the return slot from scratch.
  894. // TODO: Once we import function definitions, we'll need to make sure we
  895. // use the same return storage variable in the declaration and definition.
  896. new_return_storage = context_.AddInstInNoBlock<SemIR::VarStorage>(
  897. AddImportIRInst(function.return_storage_id),
  898. {.type_id = new_return_type_id,
  899. .name_id = SemIR::NameId::ReturnSlot});
  900. }
  901. function_decl.function_id = context_.functions().Add(
  902. {.name_id = GetLocalNameId(function.name_id),
  903. .parent_scope_id = parent_scope_id,
  904. .decl_id = function_decl_id,
  905. .implicit_param_refs_id = GetLocalParamRefsId(
  906. function.implicit_param_refs_id, implicit_param_const_ids),
  907. .param_refs_id =
  908. GetLocalParamRefsId(function.param_refs_id, param_const_ids),
  909. .return_type_id = new_return_type_id,
  910. .return_storage_id = new_return_storage,
  911. .is_extern = function.is_extern,
  912. .return_slot = function.return_slot,
  913. .builtin_kind = function.builtin_kind,
  914. .definition_id = function.definition_id.is_valid()
  915. ? function_decl_id
  916. : SemIR::InstId::Invalid});
  917. function_decl.type_id = context_.GetFunctionType(function_decl.function_id);
  918. // Write the function ID into the FunctionDecl.
  919. context_.ReplaceInstBeforeConstantUse(function_decl_id, function_decl);
  920. return {.const_id = context_.constant_values().Get(function_decl_id)};
  921. }
  922. auto TryResolveTypedInst(SemIR::FunctionType inst) -> ResolveResult {
  923. auto initial_work = work_stack_.size();
  924. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  925. auto fn_const_id = GetLocalConstantId(
  926. import_ir_.functions().Get(inst.function_id).decl_id);
  927. if (HasNewWork(initial_work)) {
  928. return ResolveResult::Retry();
  929. }
  930. auto fn_val = context_.insts().Get(fn_const_id.inst_id());
  931. CARBON_CHECK(context_.types().Is<SemIR::FunctionType>(fn_val.type_id()));
  932. return {.const_id = context_.types().GetConstantId(fn_val.type_id())};
  933. }
  934. auto TryResolveTypedInst(SemIR::GenericClassType inst) -> ResolveResult {
  935. auto initial_work = work_stack_.size();
  936. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  937. auto class_const_id =
  938. GetLocalConstantId(import_ir_.classes().Get(inst.class_id).decl_id);
  939. if (HasNewWork(initial_work)) {
  940. return ResolveResult::Retry();
  941. }
  942. auto class_val = context_.insts().Get(class_const_id.inst_id());
  943. CARBON_CHECK(
  944. context_.types().Is<SemIR::GenericClassType>(class_val.type_id()));
  945. return {.const_id = context_.types().GetConstantId(class_val.type_id())};
  946. }
  947. auto TryResolveTypedInst(SemIR::ImportRefLoaded /*inst*/,
  948. SemIR::InstId inst_id) -> ResolveResult {
  949. auto initial_work = work_stack_.size();
  950. // Return the constant for the instruction of the imported constant.
  951. auto constant_id = import_ir_.constant_values().Get(inst_id);
  952. if (!constant_id.is_valid()) {
  953. return {.const_id = SemIR::ConstantId::Error};
  954. }
  955. if (!constant_id.is_constant()) {
  956. context_.TODO(inst_id,
  957. "Non-constant ImportRefLoaded (comes up with var)");
  958. return {.const_id = SemIR::ConstantId::Error};
  959. }
  960. auto new_constant_id = GetLocalConstantId(constant_id.inst_id());
  961. if (HasNewWork(initial_work)) {
  962. return ResolveResult::Retry();
  963. }
  964. return {.const_id = new_constant_id};
  965. }
  966. // Make a declaration of an interface. This is done as a separate step from
  967. // importing the interface definition in order to resolve cycles.
  968. auto MakeInterfaceDecl(const SemIR::Interface& import_interface)
  969. -> SemIR::ConstantId {
  970. SemIR::InterfaceDecl interface_decl = {
  971. .type_id = SemIR::TypeId::TypeType,
  972. .interface_id = SemIR::InterfaceId::Invalid,
  973. .decl_block_id = SemIR::InstBlockId::Empty};
  974. auto interface_decl_id =
  975. context_.AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst(
  976. AddImportIRInst(import_interface.decl_id), interface_decl));
  977. // Start with an incomplete interface.
  978. SemIR::Interface new_interface = {
  979. .name_id = GetLocalNameId(import_interface.name_id),
  980. // These are set in the second pass once we've imported them. Import
  981. // enough of the parameter lists that we know whether this interface is
  982. // a generic interface and can build the right constant value for it.
  983. // TODO: Add a better way to represent a generic `Interface` prior to
  984. // importing the parameters.
  985. .parent_scope_id = SemIR::NameScopeId::Invalid,
  986. .implicit_param_refs_id =
  987. import_interface.implicit_param_refs_id.is_valid()
  988. ? SemIR::InstBlockId::Empty
  989. : SemIR::InstBlockId::Invalid,
  990. .param_refs_id = import_interface.param_refs_id.is_valid()
  991. ? SemIR::InstBlockId::Empty
  992. : SemIR::InstBlockId::Invalid,
  993. .decl_id = interface_decl_id,
  994. };
  995. // Write the interface ID into the InterfaceDecl.
  996. interface_decl.interface_id = context_.interfaces().Add(new_interface);
  997. context_.ReplaceInstBeforeConstantUse(interface_decl_id, interface_decl);
  998. // Set the constant value for the imported interface.
  999. return context_.constant_values().Get(interface_decl_id);
  1000. }
  1001. // Imports the definition for an interface that has been imported as a forward
  1002. // declaration.
  1003. auto AddInterfaceDefinition(const SemIR::Interface& import_interface,
  1004. SemIR::Interface& new_interface,
  1005. SemIR::ConstantId self_param_id) -> void {
  1006. new_interface.scope_id = context_.name_scopes().Add(
  1007. new_interface.decl_id, SemIR::NameId::Invalid,
  1008. new_interface.parent_scope_id);
  1009. auto& new_scope = context_.name_scopes().Get(new_interface.scope_id);
  1010. const auto& import_scope =
  1011. import_ir_.name_scopes().Get(import_interface.scope_id);
  1012. // Push a block so that we can add scoped instructions to it.
  1013. context_.inst_block_stack().Push();
  1014. AddNameScopeImportRefs(import_scope, new_scope);
  1015. new_interface.associated_entities_id =
  1016. AddAssociatedEntities(import_interface.associated_entities_id);
  1017. new_interface.body_block_id = context_.inst_block_stack().Pop();
  1018. new_interface.self_param_id = self_param_id.inst_id();
  1019. CARBON_CHECK(import_scope.extended_scopes.empty())
  1020. << "Interfaces don't currently have extended scopes to support.";
  1021. }
  1022. auto TryResolveTypedInst(SemIR::InterfaceDecl inst,
  1023. SemIR::ConstantId interface_const_id)
  1024. -> ResolveResult {
  1025. const auto& import_interface =
  1026. import_ir_.interfaces().Get(inst.interface_id);
  1027. // On the first pass, create a forward declaration of the interface.
  1028. if (!interface_const_id.is_valid()) {
  1029. interface_const_id = MakeInterfaceDecl(import_interface);
  1030. }
  1031. auto initial_work = work_stack_.size();
  1032. auto parent_scope_id =
  1033. GetLocalNameScopeId(import_interface.parent_scope_id);
  1034. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  1035. GetLocalParamConstantIds(import_interface.implicit_param_refs_id);
  1036. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  1037. GetLocalParamConstantIds(import_interface.param_refs_id);
  1038. auto self_param_id = GetLocalConstantId(import_interface.self_param_id);
  1039. if (HasNewWork(initial_work)) {
  1040. return ResolveResult::Retry(interface_const_id);
  1041. }
  1042. auto& new_interface = context_.interfaces().Get(
  1043. context_.insts()
  1044. .GetAs<SemIR::InterfaceType>(interface_const_id.inst_id())
  1045. .interface_id);
  1046. new_interface.parent_scope_id = parent_scope_id;
  1047. new_interface.implicit_param_refs_id = GetLocalParamRefsId(
  1048. import_interface.implicit_param_refs_id, implicit_param_const_ids);
  1049. new_interface.param_refs_id =
  1050. GetLocalParamRefsId(import_interface.param_refs_id, param_const_ids);
  1051. if (import_interface.is_defined()) {
  1052. AddInterfaceDefinition(import_interface, new_interface, self_param_id);
  1053. }
  1054. return {.const_id = interface_const_id};
  1055. }
  1056. auto TryResolveTypedInst(SemIR::InterfaceType inst) -> ResolveResult {
  1057. auto initial_work = work_stack_.size();
  1058. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1059. auto interface_const_id = GetLocalConstantId(
  1060. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  1061. if (HasNewWork(initial_work)) {
  1062. return ResolveResult::Retry();
  1063. }
  1064. return {.const_id = interface_const_id};
  1065. }
  1066. auto TryResolveTypedInst(SemIR::InterfaceWitness inst) -> ResolveResult {
  1067. auto initial_work = work_stack_.size();
  1068. llvm::SmallVector<SemIR::InstId> elements;
  1069. auto import_elements = import_ir_.inst_blocks().Get(inst.elements_id);
  1070. elements.reserve(import_elements.size());
  1071. for (auto import_elem_id : import_elements) {
  1072. if (auto const_id = GetLocalConstantId(import_elem_id);
  1073. const_id.is_valid()) {
  1074. elements.push_back(const_id.inst_id());
  1075. }
  1076. }
  1077. if (HasNewWork(initial_work)) {
  1078. return ResolveResult::Retry();
  1079. }
  1080. CARBON_CHECK(elements.size() == import_elements.size())
  1081. << "Failed to import an element without adding new work.";
  1082. auto elements_id = context_.inst_blocks().Add(elements);
  1083. return {.const_id = TryEvalInst(
  1084. context_, SemIR::InstId::Invalid,
  1085. SemIR::InterfaceWitness{.type_id = context_.GetBuiltinType(
  1086. SemIR::BuiltinKind::WitnessType),
  1087. .elements_id = elements_id})};
  1088. }
  1089. auto TryResolveTypedInst(SemIR::PointerType inst) -> ResolveResult {
  1090. auto initial_work = work_stack_.size();
  1091. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1092. auto pointee_const_id = GetLocalConstantId(inst.pointee_id);
  1093. if (HasNewWork(initial_work)) {
  1094. return ResolveResult::Retry();
  1095. }
  1096. auto pointee_type_id = context_.GetTypeIdForTypeConstant(pointee_const_id);
  1097. return {.const_id = context_.types().GetConstantId(
  1098. context_.GetPointerType(pointee_type_id))};
  1099. }
  1100. auto TryResolveTypedInst(SemIR::StructType inst, SemIR::InstId import_inst_id)
  1101. -> ResolveResult {
  1102. // Collect all constants first, locating unresolved ones in a single pass.
  1103. auto initial_work = work_stack_.size();
  1104. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1105. auto orig_fields = import_ir_.inst_blocks().Get(inst.fields_id);
  1106. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  1107. field_const_ids.reserve(orig_fields.size());
  1108. for (auto field_id : orig_fields) {
  1109. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1110. field_const_ids.push_back(GetLocalConstantId(field.field_type_id));
  1111. }
  1112. if (HasNewWork(initial_work)) {
  1113. return ResolveResult::Retry();
  1114. }
  1115. // Prepare a vector of fields for GetStructType.
  1116. // TODO: Should we have field constants so that we can deduplicate fields
  1117. // without creating instructions here?
  1118. llvm::SmallVector<SemIR::InstId> fields;
  1119. fields.reserve(orig_fields.size());
  1120. for (auto [field_id, field_const_id] :
  1121. llvm::zip(orig_fields, field_const_ids)) {
  1122. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1123. auto name_id = GetLocalNameId(field.name_id);
  1124. auto field_type_id = context_.GetTypeIdForTypeConstant(field_const_id);
  1125. fields.push_back(context_.AddInstInNoBlock<SemIR::StructTypeField>(
  1126. AddImportIRInst(import_inst_id),
  1127. {.name_id = name_id, .field_type_id = field_type_id}));
  1128. }
  1129. return {.const_id = context_.types().GetConstantId(
  1130. context_.GetStructType(context_.inst_blocks().Add(fields)))};
  1131. }
  1132. auto TryResolveTypedInst(SemIR::TupleType inst) -> ResolveResult {
  1133. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1134. // Collect all constants first, locating unresolved ones in a single pass.
  1135. auto initial_work = work_stack_.size();
  1136. auto orig_elem_type_ids = import_ir_.type_blocks().Get(inst.elements_id);
  1137. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  1138. elem_const_ids.reserve(orig_elem_type_ids.size());
  1139. for (auto elem_type_id : orig_elem_type_ids) {
  1140. elem_const_ids.push_back(GetLocalConstantId(elem_type_id));
  1141. }
  1142. if (HasNewWork(initial_work)) {
  1143. return ResolveResult::Retry();
  1144. }
  1145. // Prepare a vector of the tuple types for GetTupleType.
  1146. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  1147. elem_type_ids.reserve(orig_elem_type_ids.size());
  1148. for (auto elem_const_id : elem_const_ids) {
  1149. elem_type_ids.push_back(context_.GetTypeIdForTypeConstant(elem_const_id));
  1150. }
  1151. return {
  1152. context_.types().GetConstantId(context_.GetTupleType(elem_type_ids))};
  1153. }
  1154. auto TryResolveTypedInst(SemIR::UnboundElementType inst) -> ResolveResult {
  1155. auto initial_work = work_stack_.size();
  1156. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1157. auto class_const_id = GetLocalConstantId(inst.class_type_id);
  1158. auto elem_const_id = GetLocalConstantId(inst.element_type_id);
  1159. if (HasNewWork(initial_work)) {
  1160. return ResolveResult::Retry();
  1161. }
  1162. return {.const_id =
  1163. context_.types().GetConstantId(context_.GetUnboundElementType(
  1164. context_.GetTypeIdForTypeConstant(class_const_id),
  1165. context_.GetTypeIdForTypeConstant(elem_const_id)))};
  1166. }
  1167. auto import_ir_constant_values() -> SemIR::ConstantValueStore& {
  1168. return context_.import_ir_constant_values()[import_ir_id_.index];
  1169. }
  1170. Context& context_;
  1171. SemIR::ImportIRId import_ir_id_;
  1172. const SemIR::File& import_ir_;
  1173. llvm::SmallVector<Work> work_stack_;
  1174. };
  1175. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  1176. // loaded (including the one pointed at directly by the ImportRef), and the
  1177. // final instruction's type ID.
  1178. //
  1179. // This addresses cases where an ImportRefUnloaded may point at another
  1180. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  1181. // constant-evaluated version of the instruction to work with.
  1182. static auto GetInstForLoad(Context& context,
  1183. SemIR::ImportIRInstId import_ir_inst_id)
  1184. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  1185. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  1186. {}, SemIR::TypeId::Invalid};
  1187. auto& [import_ir_insts, type_id] = result;
  1188. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  1189. // The first ImportIRInst is added directly because the IR doesn't need to be
  1190. // localized.
  1191. import_ir_insts.push_back(import_ir_inst);
  1192. const auto* cursor_ir = context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1193. while (true) {
  1194. auto cursor_inst = cursor_ir->insts().Get(import_ir_inst.inst_id);
  1195. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  1196. if (!import_ref) {
  1197. type_id = cursor_inst.type_id();
  1198. return result;
  1199. }
  1200. import_ir_inst =
  1201. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  1202. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1203. import_ir_insts.push_back({.ir_id = context.GetImportIRId(*cursor_ir),
  1204. .inst_id = import_ir_inst.inst_id});
  1205. }
  1206. }
  1207. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  1208. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  1209. if (!inst) {
  1210. return;
  1211. }
  1212. auto [indirect_insts, load_type_id] =
  1213. GetInstForLoad(context, inst->import_ir_inst_id);
  1214. // The last indirect instruction is the one to resolve. Pop it here because
  1215. // Resolve will assign the constant.
  1216. auto load_ir_inst = indirect_insts.pop_back_val();
  1217. ImportRefResolver resolver(context, load_ir_inst.ir_id);
  1218. auto type_id = resolver.ResolveType(load_type_id);
  1219. auto constant_id = resolver.Resolve(load_ir_inst.inst_id);
  1220. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  1221. // doesn't use ReplaceInstBeforeConstantUse because it would trigger
  1222. // TryEvalInst, which we want to avoid with ImportRefs.
  1223. context.sem_ir().insts().Set(
  1224. inst_id,
  1225. SemIR::ImportRefLoaded{.type_id = type_id,
  1226. .import_ir_inst_id = inst->import_ir_inst_id,
  1227. .bind_name_id = inst->bind_name_id});
  1228. // Store the constant for both the ImportRefLoaded and indirect instructions.
  1229. context.constant_values().Set(inst_id, constant_id);
  1230. for (const auto& import_ir_inst : indirect_insts) {
  1231. context.import_ir_constant_values()[import_ir_inst.ir_id.index].Set(
  1232. import_ir_inst.inst_id, constant_id);
  1233. }
  1234. }
  1235. // Imports the impl `import_impl_id` from the imported IR `import_ir`.
  1236. static auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  1237. const SemIR::File& import_ir,
  1238. SemIR::ImplId import_impl_id) -> void {
  1239. // Resolve the imported impl to a local impl ID.
  1240. ImportRefResolver resolver(context, import_ir_id);
  1241. const auto& import_impl = import_ir.impls().Get(import_impl_id);
  1242. auto self_id = resolver.ResolveType(import_impl.self_id);
  1243. auto constraint_id = resolver.ResolveType(import_impl.constraint_id);
  1244. // Import the definition if the impl is defined.
  1245. // TODO: Do we need to check for multiple definitions?
  1246. auto impl_id = context.impls().LookupOrAdd(self_id, constraint_id);
  1247. if (import_impl.is_defined()) {
  1248. // TODO: Create a scope for the `impl` if necessary.
  1249. // TODO: Consider importing the definition_id.
  1250. auto& impl = context.impls().Get(impl_id);
  1251. impl.witness_id = AddImportRef(
  1252. context, {.ir_id = import_ir_id, .inst_id = import_impl.witness_id},
  1253. SemIR::BindNameId::Invalid);
  1254. }
  1255. }
  1256. // TODO: This doesn't belong in this file. Consider moving the import resolver
  1257. // and this file elsewhere.
  1258. auto ImportImpls(Context& context) -> void {
  1259. for (auto [import_index, import_ir] :
  1260. llvm::enumerate(context.import_irs().array_ref())) {
  1261. if (!import_ir.sem_ir) {
  1262. continue;
  1263. }
  1264. auto import_ir_id = SemIR::ImportIRId(import_index);
  1265. for (auto impl_index : llvm::seq(import_ir.sem_ir->impls().size())) {
  1266. auto impl_id = SemIR::ImplId(impl_index);
  1267. ImportImpl(context, import_ir_id, *import_ir.sem_ir, impl_id);
  1268. }
  1269. }
  1270. }
  1271. } // namespace Carbon::Check