import_ref.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  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/check/context.h"
  7. #include "toolchain/check/eval.h"
  8. #include "toolchain/parse/node_ids.h"
  9. #include "toolchain/sem_ir/file.h"
  10. #include "toolchain/sem_ir/ids.h"
  11. #include "toolchain/sem_ir/inst.h"
  12. #include "toolchain/sem_ir/inst_kind.h"
  13. #include "toolchain/sem_ir/typed_insts.h"
  14. namespace Carbon::Check {
  15. // Resolves an instruction from an imported IR into a constant referring to the
  16. // current IR.
  17. //
  18. // Calling Resolve on an instruction operates in an iterative manner, tracking
  19. // Work items on work_stack_. At a high level, the loop is:
  20. //
  21. // 1. If Work has received a constant, it's considered resolved.
  22. // - If made_incomplete_type, resolve unconditionally.
  23. // - The constant check avoids performance costs of deduplication on add.
  24. // 2. Resolve the instruction: (TryResolveInst/TryResolveTypedInst)
  25. // - For most cases:
  26. // A. For types which _can_ be incomplete, when not made_incomplete_type:
  27. // i. Start by making an incomplete type to address circular references.
  28. // ii. If the imported type is incomplete, return the constant.
  29. // iii. Otherwise, set made_incomplete_type and continue resolving.
  30. // - Creating an incomplete type will have set the constant, which
  31. // influences step (1); setting made_incomplete_type gets us a second
  32. // resolve pass when needed.
  33. // B. Gather all input constants.
  34. // - Gathering constants directly adds unresolved values to work_stack_.
  35. // C. If any need to be resolved (HasNewWork), return Invalid; this
  36. // instruction needs two calls to complete.
  37. // D. Build any necessary IR structures, and return the output constant.
  38. // - For trivial cases with zero or one input constants, this may return
  39. // a constant (if one, potentially Invalid) directly.
  40. // 3. If resolving returned a non-Invalid constant, pop the work; otherwise, it
  41. // needs to remain (and may no longer be at the top of the stack).
  42. //
  43. // TryResolveInst/TryResolveTypedInst can complete in one call for a given
  44. // instruction, but should always complete within two calls. However, due to the
  45. // chance of a second call, it's important to reserve all expensive logic until
  46. // it's been established that input constants are available; this in particular
  47. // includes GetTypeIdForTypeConstant calls which do a hash table lookup.
  48. class ImportRefResolver {
  49. public:
  50. explicit ImportRefResolver(Context& context, SemIR::ImportIRId import_ir_id)
  51. : context_(context),
  52. import_ir_id_(import_ir_id),
  53. import_ir_(*context_.import_irs().Get(import_ir_id)),
  54. import_ir_constant_values_(
  55. context_.import_ir_constant_values()[import_ir_id.index]) {}
  56. // Iteratively resolves an imported instruction's inner references until a
  57. // constant ID referencing the current IR is produced. When an outer
  58. // instruction has unresolved inner references, it will add them to the stack
  59. // for inner evaluation and reattempt outer evaluation after.
  60. auto Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId {
  61. work_stack_.push_back({inst_id});
  62. while (!work_stack_.empty()) {
  63. auto work = work_stack_.back();
  64. CARBON_CHECK(work.inst_id.is_valid());
  65. // Double-check that the constant still doesn't have a calculated value.
  66. // This should typically be checked before adding it, but a given
  67. // instruction may be added multiple times before its constant is
  68. // evaluated.
  69. if (!work.made_incomplete_type &&
  70. import_ir_constant_values_.Get(work.inst_id).is_valid()) {
  71. work_stack_.pop_back();
  72. } else if (auto new_const_id =
  73. TryResolveInst(work.inst_id, work.made_incomplete_type);
  74. new_const_id.is_valid()) {
  75. import_ir_constant_values_.Set(work.inst_id, new_const_id);
  76. work_stack_.pop_back();
  77. }
  78. }
  79. auto constant_id = import_ir_constant_values_.Get(inst_id);
  80. CARBON_CHECK(constant_id.is_valid());
  81. return constant_id;
  82. }
  83. // Wraps constant evaluation with logic to handle types.
  84. auto ResolveType(SemIR::TypeId import_type_id) -> SemIR::TypeId {
  85. if (!import_type_id.is_valid()) {
  86. return import_type_id;
  87. }
  88. auto import_type_inst_id = import_ir_.types().GetInstId(import_type_id);
  89. CARBON_CHECK(import_type_inst_id.is_valid());
  90. if (import_type_inst_id.is_builtin()) {
  91. // Builtins don't require constant resolution; we can use them directly.
  92. return context_.GetBuiltinType(import_type_inst_id.builtin_kind());
  93. } else {
  94. return context_.GetTypeIdForTypeConstant(Resolve(import_type_inst_id));
  95. }
  96. }
  97. private:
  98. // A step in work_stack_.
  99. struct Work {
  100. // The instruction to work on.
  101. SemIR::InstId inst_id;
  102. // True if a first pass made an incomplete type.
  103. bool made_incomplete_type = false;
  104. };
  105. // For imported entities, we use an invalid enclosing scope. This will be okay
  106. // if the scope isn't used later, but we may need to change logic for this if
  107. // the behavior changes.
  108. static constexpr SemIR::NameScopeId NoEnclosingScopeForImports =
  109. SemIR::NameScopeId::Invalid;
  110. // Returns true if new unresolved constants were found.
  111. //
  112. // At the start of a function, do:
  113. // auto initial_work = work_stack_.size();
  114. // Then when determining:
  115. // if (HasNewWork(initial_work)) { ... }
  116. auto HasNewWork(size_t initial_work) -> bool {
  117. CARBON_CHECK(initial_work <= work_stack_.size())
  118. << "Work shouldn't decrease";
  119. return initial_work < work_stack_.size();
  120. }
  121. // Returns the ConstantId for an InstId. Adds unresolved constants to
  122. // work_stack_.
  123. auto GetLocalConstantId(SemIR::InstId inst_id) -> SemIR::ConstantId {
  124. auto const_id = import_ir_constant_values_.Get(inst_id);
  125. if (!const_id.is_valid()) {
  126. work_stack_.push_back({inst_id});
  127. }
  128. return const_id;
  129. }
  130. // Returns the ConstantId for a TypeId. Adds unresolved constants to
  131. // work_stack_.
  132. auto GetLocalConstantId(SemIR::TypeId type_id) -> SemIR::ConstantId {
  133. return GetLocalConstantId(import_ir_.types().GetInstId(type_id));
  134. }
  135. // Returns the ConstantId for each parameter's type. Adds unresolved constants
  136. // to work_stack_.
  137. auto GetLocalParamConstantIds(SemIR::InstBlockId param_refs_id)
  138. -> llvm::SmallVector<SemIR::ConstantId> {
  139. if (param_refs_id == SemIR::InstBlockId::Empty) {
  140. return {};
  141. }
  142. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  143. llvm::SmallVector<SemIR::ConstantId> const_ids;
  144. const_ids.reserve(param_refs.size());
  145. for (auto inst_id : param_refs) {
  146. const_ids.push_back(
  147. GetLocalConstantId(import_ir_.insts().Get(inst_id).type_id()));
  148. }
  149. return const_ids;
  150. }
  151. // Given a param_refs_id and const_ids from GetLocalParamConstantIds, returns
  152. // a version of param_refs_id localized to the current IR.
  153. auto GetLocalParamRefsId(
  154. SemIR::InstBlockId param_refs_id,
  155. const llvm::SmallVector<SemIR::ConstantId>& const_ids)
  156. -> SemIR::InstBlockId {
  157. if (param_refs_id == SemIR::InstBlockId::Empty) {
  158. return SemIR::InstBlockId::Empty;
  159. }
  160. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  161. llvm::SmallVector<SemIR::InstId> new_param_refs;
  162. for (auto [ref_id, const_id] : llvm::zip(param_refs, const_ids)) {
  163. // Figure out the param structure. This echoes
  164. // Function::GetParamFromParamRefId.
  165. // TODO: Consider a different parameter handling to simplify import logic.
  166. auto inst = import_ir_.insts().Get(ref_id);
  167. auto addr_inst = inst.TryAs<SemIR::AddrPattern>();
  168. if (addr_inst) {
  169. inst = import_ir_.insts().Get(addr_inst->inner_id);
  170. }
  171. auto bind_inst = inst.TryAs<SemIR::AnyBindName>();
  172. if (bind_inst) {
  173. inst = import_ir_.insts().Get(bind_inst->value_id);
  174. }
  175. auto param_inst = inst.As<SemIR::Param>();
  176. // Rebuild the param instruction.
  177. auto name_id = GetLocalNameId(param_inst.name_id);
  178. auto type_id = context_.GetTypeIdForTypeConstant(const_id);
  179. auto new_param_id = context_.AddInstInNoBlock(
  180. {Parse::NodeId::Invalid, SemIR::Param{type_id, name_id}});
  181. if (bind_inst) {
  182. auto bind_name_id = context_.bind_names().Add(
  183. {.name_id = name_id,
  184. .enclosing_scope_id = SemIR::NameScopeId::Invalid});
  185. switch (bind_inst->kind) {
  186. case SemIR::InstKind::BindName:
  187. new_param_id = context_.AddInstInNoBlock(
  188. {Parse::NodeId::Invalid,
  189. SemIR::BindName{type_id, bind_name_id, new_param_id}});
  190. break;
  191. case SemIR::InstKind::BindSymbolicName:
  192. new_param_id = context_.AddInstInNoBlock(
  193. {Parse::NodeId::Invalid,
  194. SemIR::BindSymbolicName{type_id, bind_name_id, new_param_id}});
  195. break;
  196. default:
  197. CARBON_FATAL() << "Unexpected kind: " << bind_inst->kind;
  198. }
  199. }
  200. if (addr_inst) {
  201. new_param_id = context_.AddInstInNoBlock(
  202. {Parse::NodeId::Invalid,
  203. SemIR::AddrPattern{type_id, new_param_id}});
  204. }
  205. new_param_refs.push_back(new_param_id);
  206. }
  207. return context_.inst_blocks().Add(new_param_refs);
  208. }
  209. // Translates a NameId from the import IR to a local NameId.
  210. auto GetLocalNameId(SemIR::NameId import_name_id) -> SemIR::NameId {
  211. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.is_valid()) {
  212. return SemIR::NameId::ForIdentifier(
  213. context_.identifiers().Add(import_ir_.identifiers().Get(ident_id)));
  214. }
  215. return import_name_id;
  216. }
  217. // Adds ImportRefUnused entries for members of the imported scope, for name
  218. // lookup.
  219. auto AddNameScopeImportRefs(const SemIR::NameScope& import_scope,
  220. SemIR::NameScope& new_scope) -> void {
  221. for (auto [entry_name_id, entry_inst_id] : import_scope.names) {
  222. auto ref_id = context_.AddPlaceholderInst(
  223. SemIR::ImportRefUnused{import_ir_id_, entry_inst_id});
  224. CARBON_CHECK(
  225. new_scope.names.insert({GetLocalNameId(entry_name_id), ref_id})
  226. .second);
  227. }
  228. }
  229. // Given a block ID for a list of associated entities of a witness, returns a
  230. // version localized to the current IR.
  231. auto AddAssociatedEntities(SemIR::InstBlockId associated_entities_id)
  232. -> SemIR::InstBlockId {
  233. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  234. return SemIR::InstBlockId::Empty;
  235. }
  236. auto associated_entities =
  237. import_ir_.inst_blocks().Get(associated_entities_id);
  238. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  239. new_associated_entities.reserve(associated_entities.size());
  240. for (auto inst_id : associated_entities) {
  241. new_associated_entities.push_back(context_.AddPlaceholderInst(
  242. SemIR::ImportRefUnused{import_ir_id_, inst_id}));
  243. }
  244. return context_.inst_blocks().Add(new_associated_entities);
  245. }
  246. // Tries to resolve the InstId, returning a constant when ready, or Invalid if
  247. // more has been added to the stack. A similar API is followed for all
  248. // following TryResolveTypedInst helper functions.
  249. //
  250. // TODO: Error is returned when support is missing, but that should go away.
  251. auto TryResolveInst(SemIR::InstId inst_id, bool made_incomplete_type)
  252. -> SemIR::ConstantId {
  253. if (inst_id.is_builtin()) {
  254. CARBON_CHECK(!made_incomplete_type);
  255. // Constants for builtins can be directly copied.
  256. return context_.constant_values().Get(inst_id);
  257. }
  258. auto inst = import_ir_.insts().Get(inst_id);
  259. CARBON_CHECK(!made_incomplete_type ||
  260. inst.kind() == SemIR::InstKind::ClassDecl)
  261. << "Currently only decls with incomplete types should need "
  262. "made_incomplete_type states: "
  263. << inst.kind();
  264. switch (inst.kind()) {
  265. case SemIR::InstKind::BaseDecl:
  266. return TryResolveTypedInst(inst.As<SemIR::BaseDecl>());
  267. case SemIR::InstKind::BindAlias:
  268. return TryResolveTypedInst(inst.As<SemIR::BindAlias>());
  269. case SemIR::InstKind::ClassDecl:
  270. return TryResolveTypedInst(inst.As<SemIR::ClassDecl>(), inst_id,
  271. made_incomplete_type);
  272. case SemIR::InstKind::ClassType:
  273. return TryResolveTypedInst(inst.As<SemIR::ClassType>());
  274. case SemIR::InstKind::ConstType:
  275. return TryResolveTypedInst(inst.As<SemIR::ConstType>());
  276. case SemIR::InstKind::FieldDecl:
  277. return TryResolveTypedInst(inst.As<SemIR::FieldDecl>());
  278. case SemIR::InstKind::FunctionDecl:
  279. return TryResolveTypedInst(inst.As<SemIR::FunctionDecl>());
  280. case SemIR::InstKind::InterfaceDecl:
  281. return TryResolveTypedInst(inst.As<SemIR::InterfaceDecl>());
  282. case SemIR::InstKind::InterfaceType:
  283. return TryResolveTypedInst(inst.As<SemIR::InterfaceType>());
  284. case SemIR::InstKind::PointerType:
  285. return TryResolveTypedInst(inst.As<SemIR::PointerType>());
  286. case SemIR::InstKind::StructType:
  287. return TryResolveTypedInst(inst.As<SemIR::StructType>());
  288. case SemIR::InstKind::TupleType:
  289. return TryResolveTypedInst(inst.As<SemIR::TupleType>());
  290. case SemIR::InstKind::UnboundElementType:
  291. return TryResolveTypedInst(inst.As<SemIR::UnboundElementType>());
  292. case SemIR::InstKind::BindName:
  293. case SemIR::InstKind::BindSymbolicName:
  294. // Can use TryEvalInst because the resulting constant doesn't really use
  295. // `inst`.
  296. return TryEvalInst(context_, inst_id, inst);
  297. default:
  298. context_.TODO(
  299. Parse::NodeId::Invalid,
  300. llvm::formatv("TryResolveInst on {0}", inst.kind()).str());
  301. return SemIR::ConstantId::Error;
  302. }
  303. }
  304. auto TryResolveTypedInst(SemIR::BaseDecl inst) -> SemIR::ConstantId {
  305. auto initial_work = work_stack_.size();
  306. auto type_const_id = GetLocalConstantId(inst.type_id);
  307. auto base_type_const_id = GetLocalConstantId(inst.base_type_id);
  308. if (HasNewWork(initial_work)) {
  309. return SemIR::ConstantId::Invalid;
  310. }
  311. // Import the instruction in order to update contained base_type_id.
  312. auto inst_id = context_.AddInstInNoBlock(
  313. {Parse::NodeId::Invalid,
  314. SemIR::BaseDecl{context_.GetTypeIdForTypeConstant(type_const_id),
  315. context_.GetTypeIdForTypeConstant(base_type_const_id),
  316. inst.index}});
  317. return context_.constant_values().Get(inst_id);
  318. }
  319. auto TryResolveTypedInst(SemIR::BindAlias inst) -> SemIR::ConstantId {
  320. auto initial_work = work_stack_.size();
  321. auto value_id = GetLocalConstantId(inst.value_id);
  322. if (HasNewWork(initial_work)) {
  323. return SemIR::ConstantId::Invalid;
  324. }
  325. return value_id;
  326. }
  327. // Makes an incomplete class. This is necessary even with classes with a
  328. // complete declaration, because things such as `Self` may refer back to the
  329. // type.
  330. auto MakeIncompleteClass(SemIR::InstId inst_id,
  331. const SemIR::Class& import_class)
  332. -> SemIR::ConstantId {
  333. auto class_decl =
  334. SemIR::ClassDecl{SemIR::TypeId::Invalid, SemIR::ClassId::Invalid,
  335. SemIR::InstBlockId::Empty};
  336. auto class_decl_id =
  337. context_.AddPlaceholderInst({Parse::NodeId::Invalid, class_decl});
  338. // Regardless of whether ClassDecl is a complete type, we first need an
  339. // incomplete type so that any references have something to point at.
  340. class_decl.class_id = context_.classes().Add({
  341. .name_id = GetLocalNameId(import_class.name_id),
  342. .enclosing_scope_id = NoEnclosingScopeForImports,
  343. // `.self_type_id` depends on the ClassType, so is set below.
  344. .self_type_id = SemIR::TypeId::Invalid,
  345. .decl_id = class_decl_id,
  346. .inheritance_kind = import_class.inheritance_kind,
  347. });
  348. // Write the class ID into the ClassDecl.
  349. context_.ReplaceInstBeforeConstantUse(class_decl_id,
  350. {Parse::NodeId::Invalid, class_decl});
  351. auto self_const_id = context_.constant_values().Get(class_decl_id);
  352. // Build the `Self` type using the resulting type constant.
  353. auto& class_info = context_.classes().Get(class_decl.class_id);
  354. class_info.self_type_id = context_.GetTypeIdForTypeConstant(self_const_id);
  355. // Set a constant corresponding to the incomplete class.
  356. import_ir_constant_values_.Set(inst_id, self_const_id);
  357. return self_const_id;
  358. }
  359. // Fills out the class definition for an incomplete class.
  360. auto AddClassDefinition(const SemIR::Class& import_class,
  361. SemIR::ConstantId class_const_id,
  362. SemIR::ConstantId object_repr_const_id,
  363. SemIR::ConstantId base_const_id) -> void {
  364. auto& new_class = context_.classes().Get(
  365. context_.insts()
  366. .GetAs<SemIR::ClassType>(class_const_id.inst_id())
  367. .class_id);
  368. new_class.object_repr_id =
  369. context_.GetTypeIdForTypeConstant(object_repr_const_id);
  370. new_class.scope_id =
  371. context_.name_scopes().Add(new_class.decl_id, SemIR::NameId::Invalid,
  372. new_class.enclosing_scope_id);
  373. auto& new_scope = context_.name_scopes().Get(new_class.scope_id);
  374. const auto& import_scope =
  375. import_ir_.name_scopes().Get(import_class.scope_id);
  376. // Push a block so that we can add scoped instructions to it.
  377. context_.inst_block_stack().Push();
  378. AddNameScopeImportRefs(import_scope, new_scope);
  379. new_class.body_block_id = context_.inst_block_stack().Pop();
  380. if (import_class.base_id.is_valid()) {
  381. new_class.base_id = base_const_id.inst_id();
  382. // Add the base scope to extended scopes.
  383. auto base_inst_id = context_.types().GetInstId(
  384. context_.insts()
  385. .GetAs<SemIR::BaseDecl>(new_class.base_id)
  386. .base_type_id);
  387. const auto& base_class = context_.classes().Get(
  388. context_.insts().GetAs<SemIR::ClassType>(base_inst_id).class_id);
  389. new_scope.extended_scopes.push_back(base_class.scope_id);
  390. }
  391. CARBON_CHECK(new_scope.extended_scopes.size() ==
  392. import_scope.extended_scopes.size());
  393. }
  394. auto TryResolveTypedInst(SemIR::ClassDecl inst, SemIR::InstId inst_id,
  395. bool made_incomplete_type) -> SemIR::ConstantId {
  396. const auto& import_class = import_ir_.classes().Get(inst.class_id);
  397. SemIR::ConstantId class_const_id = SemIR::ConstantId::Invalid;
  398. // On the first pass, there's no incomplete type; start by adding one for
  399. // any recursive references.
  400. if (!made_incomplete_type) {
  401. class_const_id = MakeIncompleteClass(inst_id, import_class);
  402. // If there's only a forward declaration, we're done.
  403. if (!import_class.is_defined()) {
  404. return class_const_id;
  405. }
  406. // This may not be needed because all constants might be ready, but we do
  407. // it here so that we don't need to track which work item corresponds to
  408. // this instruction.
  409. work_stack_.back().made_incomplete_type = true;
  410. }
  411. CARBON_CHECK(import_class.is_defined())
  412. << "Only reachable when there's a definition.";
  413. // Load constants for the definition.
  414. auto initial_work = work_stack_.size();
  415. auto object_repr_const_id = GetLocalConstantId(import_class.object_repr_id);
  416. auto base_const_id = import_class.base_id.is_valid()
  417. ? GetLocalConstantId(import_class.base_id)
  418. : SemIR::ConstantId::Invalid;
  419. if (HasNewWork(initial_work)) {
  420. return SemIR::ConstantId::Invalid;
  421. }
  422. // On the first pass, we build the incomplete type's constant above. If we
  423. // get here on a subsequent pass we need to fetch the one we built in the
  424. // first pass.
  425. if (made_incomplete_type) {
  426. CARBON_CHECK(!class_const_id.is_valid())
  427. << "Shouldn't have a const yet when resuming";
  428. class_const_id = import_ir_constant_values_.Get(inst_id);
  429. }
  430. AddClassDefinition(import_class, class_const_id, object_repr_const_id,
  431. base_const_id);
  432. return class_const_id;
  433. }
  434. auto TryResolveTypedInst(SemIR::ClassType inst) -> SemIR::ConstantId {
  435. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  436. // ClassType uses a straight reference to the constant ID generated as part
  437. // of pulling in the ClassDecl, so there's no need to phase logic.
  438. return GetLocalConstantId(import_ir_.classes().Get(inst.class_id).decl_id);
  439. }
  440. auto TryResolveTypedInst(SemIR::ConstType inst) -> SemIR::ConstantId {
  441. auto initial_work = work_stack_.size();
  442. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  443. auto inner_const_id = GetLocalConstantId(inst.inner_id);
  444. if (HasNewWork(initial_work)) {
  445. return SemIR::ConstantId::Invalid;
  446. }
  447. auto inner_type_id = context_.GetTypeIdForTypeConstant(inner_const_id);
  448. // TODO: Should ConstType have a wrapper for this similar to the others?
  449. return TryEvalInst(
  450. context_, SemIR::InstId::Invalid,
  451. SemIR::ConstType{SemIR::TypeId::TypeType, inner_type_id});
  452. }
  453. auto TryResolveTypedInst(SemIR::FieldDecl inst) -> SemIR::ConstantId {
  454. auto initial_work = work_stack_.size();
  455. auto const_id = GetLocalConstantId(inst.type_id);
  456. if (HasNewWork(initial_work)) {
  457. return SemIR::ConstantId::Invalid;
  458. }
  459. auto inst_id = context_.AddInstInNoBlock(
  460. {Parse::NodeId::Invalid,
  461. SemIR::FieldDecl{context_.GetTypeIdForTypeConstant(const_id),
  462. GetLocalNameId(inst.name_id), inst.index}});
  463. return context_.constant_values().Get(inst_id);
  464. }
  465. auto TryResolveTypedInst(SemIR::FunctionDecl inst) -> SemIR::ConstantId {
  466. auto initial_work = work_stack_.size();
  467. auto type_const_id = GetLocalConstantId(inst.type_id);
  468. const auto& function = import_ir_.functions().Get(inst.function_id);
  469. auto return_type_const_id = SemIR::ConstantId::Invalid;
  470. if (function.return_type_id.is_valid()) {
  471. return_type_const_id = GetLocalConstantId(function.return_type_id);
  472. }
  473. auto return_slot_const_id = SemIR::ConstantId::Invalid;
  474. if (function.return_slot_id.is_valid()) {
  475. return_slot_const_id = GetLocalConstantId(function.return_slot_id);
  476. }
  477. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  478. GetLocalParamConstantIds(function.implicit_param_refs_id);
  479. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  480. GetLocalParamConstantIds(function.param_refs_id);
  481. if (HasNewWork(initial_work)) {
  482. return SemIR::ConstantId::Invalid;
  483. }
  484. // Add the function declaration.
  485. auto function_decl = SemIR::FunctionDecl{
  486. context_.GetTypeIdForTypeConstant(type_const_id),
  487. SemIR::FunctionId::Invalid, SemIR::InstBlockId::Empty};
  488. auto function_decl_id = context_.AddPlaceholderInstInNoBlock(
  489. {Parse::NodeId::Invalid, function_decl});
  490. auto new_return_type_id =
  491. return_type_const_id.is_valid()
  492. ? context_.GetTypeIdForTypeConstant(return_type_const_id)
  493. : SemIR::TypeId::Invalid;
  494. auto new_return_slot = SemIR::InstId::Invalid;
  495. if (function.return_slot_id.is_valid()) {
  496. context_.AddInstInNoBlock({SemIR::ImportRefUsed{
  497. context_.GetTypeIdForTypeConstant(return_slot_const_id),
  498. import_ir_id_, function.return_slot_id}});
  499. }
  500. function_decl.function_id = context_.functions().Add(
  501. {.name_id = GetLocalNameId(function.name_id),
  502. .enclosing_scope_id = NoEnclosingScopeForImports,
  503. .decl_id = function_decl_id,
  504. .implicit_param_refs_id = GetLocalParamRefsId(
  505. function.implicit_param_refs_id, implicit_param_const_ids),
  506. .param_refs_id =
  507. GetLocalParamRefsId(function.param_refs_id, param_const_ids),
  508. .return_type_id = new_return_type_id,
  509. .return_slot_id = new_return_slot});
  510. // Write the function ID into the FunctionDecl.
  511. context_.ReplaceInstBeforeConstantUse(
  512. function_decl_id, {Parse::NodeId::Invalid, function_decl});
  513. return context_.constant_values().Get(function_decl_id);
  514. }
  515. auto TryResolveTypedInst(SemIR::InterfaceDecl inst) -> SemIR::ConstantId {
  516. const auto& import_interface =
  517. import_ir_.interfaces().Get(inst.interface_id);
  518. auto interface_decl = SemIR::InterfaceDecl{SemIR::TypeId::Invalid,
  519. SemIR::InterfaceId::Invalid,
  520. SemIR::InstBlockId::Empty};
  521. auto interface_decl_id =
  522. context_.AddPlaceholderInst({Parse::NodeId::Invalid, interface_decl});
  523. // Start with an incomplete interface.
  524. SemIR::Interface new_interface = {
  525. .name_id = GetLocalNameId(import_interface.name_id),
  526. .enclosing_scope_id = NoEnclosingScopeForImports,
  527. .decl_id = interface_decl_id,
  528. };
  529. // If the interface is defined, we can complete it immediately. No constants
  530. // are required. Do this before adding it to interfaces.
  531. if (import_interface.is_defined()) {
  532. new_interface.scope_id = context_.name_scopes().Add(
  533. new_interface.decl_id, SemIR::NameId::Invalid,
  534. new_interface.enclosing_scope_id);
  535. auto& new_scope = context_.name_scopes().Get(new_interface.scope_id);
  536. const auto& import_scope =
  537. import_ir_.name_scopes().Get(import_interface.scope_id);
  538. // Push a block so that we can add scoped instructions to it.
  539. context_.inst_block_stack().Push();
  540. AddNameScopeImportRefs(import_scope, new_scope);
  541. new_interface.associated_entities_id =
  542. AddAssociatedEntities(import_interface.associated_entities_id);
  543. new_interface.body_block_id = context_.inst_block_stack().Pop();
  544. CARBON_CHECK(import_scope.extended_scopes.empty())
  545. << "Interfaces don't currently have extended scopes to support.";
  546. }
  547. // Write the interface ID into the InterfaceDecl.
  548. interface_decl.interface_id = context_.interfaces().Add(new_interface);
  549. context_.ReplaceInstBeforeConstantUse(
  550. interface_decl_id, {Parse::NodeId::Invalid, interface_decl});
  551. return context_.constant_values().Get(interface_decl_id);
  552. }
  553. auto TryResolveTypedInst(SemIR::InterfaceType inst) -> SemIR::ConstantId {
  554. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  555. // InterfaceType uses a straight reference to the constant ID generated as
  556. // part of pulling in the InterfaceDecl, so there's no need to phase logic.
  557. return GetLocalConstantId(
  558. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  559. }
  560. auto TryResolveTypedInst(SemIR::PointerType inst) -> SemIR::ConstantId {
  561. auto initial_work = work_stack_.size();
  562. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  563. auto pointee_const_id = GetLocalConstantId(inst.pointee_id);
  564. if (HasNewWork(initial_work)) {
  565. return SemIR::ConstantId::Invalid;
  566. }
  567. auto pointee_type_id = context_.GetTypeIdForTypeConstant(pointee_const_id);
  568. return context_.types().GetConstantId(
  569. context_.GetPointerType(pointee_type_id));
  570. }
  571. auto TryResolveTypedInst(SemIR::StructType inst) -> SemIR::ConstantId {
  572. // Collect all constants first, locating unresolved ones in a single pass.
  573. auto initial_work = work_stack_.size();
  574. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  575. auto orig_fields = import_ir_.inst_blocks().Get(inst.fields_id);
  576. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  577. field_const_ids.reserve(orig_fields.size());
  578. for (auto field_id : orig_fields) {
  579. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  580. field_const_ids.push_back(GetLocalConstantId(field.field_type_id));
  581. }
  582. if (HasNewWork(initial_work)) {
  583. return SemIR::ConstantId::Invalid;
  584. }
  585. // Prepare a vector of fields for GetStructType.
  586. // TODO: Should we have field constants so that we can deduplicate fields
  587. // without creating instructions here?
  588. llvm::SmallVector<SemIR::InstId> fields;
  589. fields.reserve(orig_fields.size());
  590. for (auto [field_id, field_const_id] :
  591. llvm::zip(orig_fields, field_const_ids)) {
  592. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  593. auto name_id = GetLocalNameId(field.name_id);
  594. auto field_type_id = context_.GetTypeIdForTypeConstant(field_const_id);
  595. fields.push_back(context_.AddInstInNoBlock(
  596. {Parse::NodeId::Invalid,
  597. SemIR::StructTypeField{.name_id = name_id,
  598. .field_type_id = field_type_id}}));
  599. }
  600. return context_.types().GetConstantId(
  601. context_.GetStructType(context_.inst_blocks().Add(fields)));
  602. }
  603. auto TryResolveTypedInst(SemIR::TupleType inst) -> SemIR::ConstantId {
  604. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  605. // Collect all constants first, locating unresolved ones in a single pass.
  606. auto initial_work = work_stack_.size();
  607. auto orig_elem_type_ids = import_ir_.type_blocks().Get(inst.elements_id);
  608. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  609. elem_const_ids.reserve(orig_elem_type_ids.size());
  610. for (auto elem_type_id : orig_elem_type_ids) {
  611. elem_const_ids.push_back(GetLocalConstantId(elem_type_id));
  612. }
  613. if (HasNewWork(initial_work)) {
  614. return SemIR::ConstantId::Invalid;
  615. }
  616. // Prepare a vector of the tuple types for GetTupleType.
  617. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  618. elem_type_ids.reserve(orig_elem_type_ids.size());
  619. for (auto elem_const_id : elem_const_ids) {
  620. elem_type_ids.push_back(context_.GetTypeIdForTypeConstant(elem_const_id));
  621. }
  622. return context_.types().GetConstantId(context_.GetTupleType(elem_type_ids));
  623. }
  624. auto TryResolveTypedInst(SemIR::UnboundElementType inst)
  625. -> SemIR::ConstantId {
  626. auto initial_work = work_stack_.size();
  627. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  628. auto class_const_id = GetLocalConstantId(inst.class_type_id);
  629. auto elem_const_id = GetLocalConstantId(inst.element_type_id);
  630. if (HasNewWork(initial_work)) {
  631. return SemIR::ConstantId::Invalid;
  632. }
  633. return context_.types().GetConstantId(context_.GetUnboundElementType(
  634. context_.GetTypeIdForTypeConstant(class_const_id),
  635. context_.GetTypeIdForTypeConstant(elem_const_id)));
  636. }
  637. Context& context_;
  638. SemIR::ImportIRId import_ir_id_;
  639. const SemIR::File& import_ir_;
  640. SemIR::ConstantValueStore& import_ir_constant_values_;
  641. llvm::SmallVector<Work> work_stack_;
  642. };
  643. auto TryResolveImportRefUnused(Context& context, SemIR::InstId inst_id)
  644. -> void {
  645. auto inst = context.insts().Get(inst_id);
  646. auto import_ref = inst.TryAs<SemIR::ImportRefUnused>();
  647. if (!import_ref) {
  648. return;
  649. }
  650. const SemIR::File& import_ir = *context.import_irs().Get(import_ref->ir_id);
  651. auto import_inst = import_ir.insts().Get(import_ref->inst_id);
  652. ImportRefResolver resolver(context, import_ref->ir_id);
  653. auto type_id = resolver.ResolveType(import_inst.type_id());
  654. auto constant_id = resolver.Resolve(import_ref->inst_id);
  655. // Replace the ImportRefUnused instruction with an ImportRefUsed. This doesn't
  656. // use ReplaceInstBeforeConstantUse because it would trigger TryEvalInst, and
  657. // we're instead doing constant evaluation here in order to minimize recursion
  658. // risks.
  659. context.sem_ir().insts().Set(
  660. inst_id,
  661. SemIR::ImportRefUsed{type_id, import_ref->ir_id, import_ref->inst_id});
  662. // Store the constant for both the ImportRefUsed and imported instruction.
  663. context.constant_values().Set(inst_id, constant_id);
  664. }
  665. } // namespace Carbon::Check