import_ref.cpp 51 KB

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