import_ref.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  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 a constant value is already known for the work item, and we're
  22. // processing it for the first time, it's considered resolved.
  23. // - The constant check avoids performance costs of deduplication on add.
  24. // - If `retry` is set, we process it again, because it didn't complete last
  25. // time, even though we have a constant value already.
  26. // 2. Resolve the instruction: (TryResolveInst/TryResolveTypedInst)
  27. // - For instructions that can be forward declared, if we don't already have
  28. // a constant value from a previous attempt at resolution, start by making
  29. // a forward declared constant value to address circular references.
  30. // - Gather all input constants.
  31. // - Gathering constants directly adds unresolved values to work_stack_.
  32. // - If any need to be resolved (HasNewWork), return Retry(): this
  33. // instruction needs two calls to complete.
  34. // - If the constant value is already known because we have made a forward
  35. // declaration, pass it to Retry(). It will be passed to future attempts
  36. // to resolve this instruction so the earlier work can be found, and will
  37. // be made available for other instructions to use.
  38. // - The second attempt to resolve this instruction must produce the same
  39. // constant, because the value may have already been used by resolved
  40. // instructions.
  41. // - Build any necessary IR structures, and return the output constant.
  42. // 3. If resolve didn't return Retry(), pop the work. Otherwise, it needs to
  43. // remain, and may no longer be at the top of the stack; set `retry` on it so
  44. // we'll make sure to run it again later.
  45. //
  46. // TryResolveInst/TryResolveTypedInst can complete in one call for a given
  47. // instruction, but should always complete within two calls. However, due to the
  48. // chance of a second call, it's important to reserve all expensive logic until
  49. // it's been established that input constants are available; this in particular
  50. // includes GetTypeIdForTypeConstant calls which do a hash table lookup.
  51. class ImportRefResolver {
  52. public:
  53. explicit ImportRefResolver(Context& context, SemIR::ImportIRId import_ir_id)
  54. : context_(context),
  55. import_ir_id_(import_ir_id),
  56. import_ir_(*context_.import_irs().Get(import_ir_id)),
  57. import_ir_constant_values_(
  58. context_.import_ir_constant_values()[import_ir_id.index]) {}
  59. // Iteratively resolves an imported instruction's inner references until a
  60. // constant ID referencing the current IR is produced. See the class comment
  61. // for more details.
  62. auto Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId {
  63. work_stack_.push_back({inst_id});
  64. while (!work_stack_.empty()) {
  65. auto work = work_stack_.back();
  66. CARBON_CHECK(work.inst_id.is_valid());
  67. // Step 1: check for a constant value.
  68. auto existing_const_id = import_ir_constant_values_.Get(work.inst_id);
  69. if (existing_const_id.is_valid() && !work.retry) {
  70. work_stack_.pop_back();
  71. continue;
  72. }
  73. // Step 2: resolve the instruction.
  74. auto initial_work = work_stack_.size();
  75. auto [new_const_id, finished] =
  76. TryResolveInst(work.inst_id, existing_const_id);
  77. CARBON_CHECK(finished == !HasNewWork(initial_work));
  78. CARBON_CHECK(!existing_const_id.is_valid() ||
  79. existing_const_id == new_const_id)
  80. << "Constant value changed in second pass.";
  81. import_ir_constant_values_.Set(work.inst_id, new_const_id);
  82. // Step 3: pop or retry.
  83. if (finished) {
  84. work_stack_.pop_back();
  85. } else {
  86. work_stack_[initial_work - 1].retry = true;
  87. }
  88. }
  89. auto constant_id = import_ir_constant_values_.Get(inst_id);
  90. CARBON_CHECK(constant_id.is_valid());
  91. return constant_id;
  92. }
  93. // Wraps constant evaluation with logic to handle types.
  94. auto ResolveType(SemIR::TypeId import_type_id) -> SemIR::TypeId {
  95. if (!import_type_id.is_valid()) {
  96. return import_type_id;
  97. }
  98. auto import_type_inst_id = import_ir_.types().GetInstId(import_type_id);
  99. CARBON_CHECK(import_type_inst_id.is_valid());
  100. if (import_type_inst_id.is_builtin()) {
  101. // Builtins don't require constant resolution; we can use them directly.
  102. return context_.GetBuiltinType(import_type_inst_id.builtin_kind());
  103. } else {
  104. return context_.GetTypeIdForTypeConstant(Resolve(import_type_inst_id));
  105. }
  106. }
  107. private:
  108. // A step in work_stack_.
  109. struct Work {
  110. // The instruction to work on.
  111. SemIR::InstId inst_id;
  112. // True if another pass was requested last time this was run.
  113. bool retry = false;
  114. };
  115. // The result of attempting to resolve an imported instruction to a constant.
  116. struct ResolveResult {
  117. // Try resolving this function again. If `const_id` is specified, it will be
  118. // passed to the next resolution attempt.
  119. static auto Retry(SemIR::ConstantId const_id = SemIR::ConstantId::Invalid)
  120. -> ResolveResult {
  121. return {.const_id = const_id, .finished = false};
  122. }
  123. // The new constant value, if known.
  124. SemIR::ConstantId const_id;
  125. // Whether resolution has finished. If false, `TryResolveInst` will be
  126. // called again. Note that this is not strictly necessary, and we can get
  127. // the same information by checking whether new work was added to the stack.
  128. // However, we use this for consistency checks between resolve actions and
  129. // the work stack.
  130. bool finished = true;
  131. };
  132. // Returns true if new unresolved constants were found.
  133. //
  134. // At the start of a function, do:
  135. // auto initial_work = work_stack_.size();
  136. // Then when determining:
  137. // if (HasNewWork(initial_work)) { ... }
  138. auto HasNewWork(size_t initial_work) -> bool {
  139. CARBON_CHECK(initial_work <= work_stack_.size())
  140. << "Work shouldn't decrease";
  141. return initial_work < work_stack_.size();
  142. }
  143. // Returns the ConstantId for an InstId. Adds unresolved constants to
  144. // work_stack_.
  145. auto GetLocalConstantId(SemIR::InstId inst_id) -> SemIR::ConstantId {
  146. auto const_id = import_ir_constant_values_.Get(inst_id);
  147. if (!const_id.is_valid()) {
  148. work_stack_.push_back({inst_id});
  149. }
  150. return const_id;
  151. }
  152. // Returns the ConstantId for a TypeId. Adds unresolved constants to
  153. // work_stack_.
  154. auto GetLocalConstantId(SemIR::TypeId type_id) -> SemIR::ConstantId {
  155. return GetLocalConstantId(import_ir_.types().GetInstId(type_id));
  156. }
  157. // Returns the ConstantId for each parameter's type. Adds unresolved constants
  158. // to work_stack_.
  159. auto GetLocalParamConstantIds(SemIR::InstBlockId param_refs_id)
  160. -> llvm::SmallVector<SemIR::ConstantId> {
  161. if (param_refs_id == SemIR::InstBlockId::Empty) {
  162. return {};
  163. }
  164. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  165. llvm::SmallVector<SemIR::ConstantId> const_ids;
  166. const_ids.reserve(param_refs.size());
  167. for (auto inst_id : param_refs) {
  168. const_ids.push_back(
  169. GetLocalConstantId(import_ir_.insts().Get(inst_id).type_id()));
  170. // If the parameter is a symbolic binding, build the BindSymbolicName
  171. // constant.
  172. auto bind_id = inst_id;
  173. if (auto addr =
  174. import_ir_.insts().TryGetAs<SemIR::AddrPattern>(bind_id)) {
  175. bind_id = addr->inner_id;
  176. }
  177. GetLocalConstantId(bind_id);
  178. }
  179. return const_ids;
  180. }
  181. // Given a param_refs_id and const_ids from GetLocalParamConstantIds, returns
  182. // a version of param_refs_id localized to the current IR.
  183. auto GetLocalParamRefsId(
  184. SemIR::InstBlockId param_refs_id,
  185. const llvm::SmallVector<SemIR::ConstantId>& const_ids)
  186. -> SemIR::InstBlockId {
  187. if (param_refs_id == SemIR::InstBlockId::Empty) {
  188. return SemIR::InstBlockId::Empty;
  189. }
  190. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  191. llvm::SmallVector<SemIR::InstId> new_param_refs;
  192. for (auto [ref_id, const_id] : llvm::zip(param_refs, const_ids)) {
  193. // Figure out the param structure. This echoes
  194. // Function::GetParamFromParamRefId.
  195. // TODO: Consider a different parameter handling to simplify import logic.
  196. auto inst = import_ir_.insts().Get(ref_id);
  197. auto addr_inst = inst.TryAs<SemIR::AddrPattern>();
  198. auto bind_id = ref_id;
  199. if (addr_inst) {
  200. bind_id = addr_inst->inner_id;
  201. inst = import_ir_.insts().Get(bind_id);
  202. }
  203. auto bind_inst = inst.TryAs<SemIR::AnyBindName>();
  204. if (bind_inst) {
  205. inst = import_ir_.insts().Get(bind_inst->value_id);
  206. }
  207. auto param_inst = inst.As<SemIR::Param>();
  208. // Rebuild the param instruction.
  209. auto name_id = GetLocalNameId(param_inst.name_id);
  210. auto type_id = context_.GetTypeIdForTypeConstant(const_id);
  211. auto new_param_id = context_.AddInstInNoBlock(
  212. {Parse::NodeId::Invalid, SemIR::Param{type_id, name_id}});
  213. if (bind_inst) {
  214. switch (bind_inst->kind) {
  215. case SemIR::InstKind::BindName: {
  216. auto bind_name_id = context_.bind_names().Add(
  217. {.name_id = name_id,
  218. .enclosing_scope_id = SemIR::NameScopeId::Invalid});
  219. new_param_id = context_.AddInstInNoBlock(
  220. {Parse::NodeId::Invalid,
  221. SemIR::BindName{type_id, bind_name_id, new_param_id}});
  222. break;
  223. }
  224. case SemIR::InstKind::BindSymbolicName: {
  225. // The symbolic name will be created on first reference, so might
  226. // already exist. Update the value in it to refer to the parameter.
  227. auto new_bind_inst =
  228. context_.insts().GetAs<SemIR::BindSymbolicName>(
  229. GetLocalConstantId(bind_id).inst_id());
  230. new_bind_inst.value_id = new_param_id;
  231. // This is not before constant use, but doesn't change the
  232. // constant value of the instruction.
  233. context_.ReplaceInstBeforeConstantUse(
  234. bind_id, {Parse::NodeId::Invalid, new_bind_inst});
  235. break;
  236. }
  237. default: {
  238. CARBON_FATAL() << "Unexpected kind: " << bind_inst->kind;
  239. }
  240. }
  241. }
  242. if (addr_inst) {
  243. new_param_id = context_.AddInstInNoBlock(
  244. {Parse::NodeId::Invalid,
  245. SemIR::AddrPattern{type_id, new_param_id}});
  246. }
  247. new_param_refs.push_back(new_param_id);
  248. }
  249. return context_.inst_blocks().Add(new_param_refs);
  250. }
  251. // Translates a NameId from the import IR to a local NameId.
  252. auto GetLocalNameId(SemIR::NameId import_name_id) -> SemIR::NameId {
  253. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.is_valid()) {
  254. return SemIR::NameId::ForIdentifier(
  255. context_.identifiers().Add(import_ir_.identifiers().Get(ident_id)));
  256. }
  257. return import_name_id;
  258. }
  259. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  260. // unresolved constants to the work stack.
  261. auto GetLocalNameScopeId(SemIR::NameScopeId name_scope_id)
  262. -> SemIR::NameScopeId {
  263. auto inst_id = import_ir_.name_scopes().GetInstIdIfValid(name_scope_id);
  264. if (!inst_id.is_valid()) {
  265. // Map scopes that aren't associated with an instruction to invalid
  266. // scopes. For now, such scopes aren't used, and we don't have a good way
  267. // to rmmap them.
  268. return SemIR::NameScopeId::Invalid;
  269. }
  270. auto const_id = GetLocalConstantId(inst_id);
  271. if (!const_id.is_valid()) {
  272. return SemIR::NameScopeId::Invalid;
  273. }
  274. switch (auto name_scope_inst = context_.insts().Get(const_id.inst_id());
  275. name_scope_inst.kind()) {
  276. case SemIR::Namespace::Kind:
  277. return name_scope_inst.As<SemIR::Namespace>().name_scope_id;
  278. case SemIR::ClassType::Kind:
  279. return context_.classes()
  280. .Get(name_scope_inst.As<SemIR::ClassType>().class_id)
  281. .scope_id;
  282. case SemIR::InterfaceType::Kind:
  283. return context_.interfaces()
  284. .Get(name_scope_inst.As<SemIR::InterfaceType>().interface_id)
  285. .scope_id;
  286. default:
  287. if (const_id == SemIR::ConstantId::Error) {
  288. return SemIR::NameScopeId::Invalid;
  289. }
  290. CARBON_FATAL() << "Unexpected instruction kind for name scope: "
  291. << name_scope_inst;
  292. }
  293. }
  294. // Adds ImportRefUnused entries for members of the imported scope, for name
  295. // lookup.
  296. auto AddNameScopeImportRefs(const SemIR::NameScope& import_scope,
  297. SemIR::NameScope& new_scope) -> void {
  298. for (auto [entry_name_id, entry_inst_id] : import_scope.names) {
  299. auto ref_id = context_.AddImportRef(import_ir_id_, entry_inst_id);
  300. CARBON_CHECK(
  301. new_scope.names.insert({GetLocalNameId(entry_name_id), ref_id})
  302. .second);
  303. }
  304. }
  305. // Given a block ID for a list of associated entities of a witness, returns a
  306. // version localized to the current IR.
  307. auto AddAssociatedEntities(SemIR::InstBlockId associated_entities_id)
  308. -> SemIR::InstBlockId {
  309. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  310. return SemIR::InstBlockId::Empty;
  311. }
  312. auto associated_entities =
  313. import_ir_.inst_blocks().Get(associated_entities_id);
  314. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  315. new_associated_entities.reserve(associated_entities.size());
  316. for (auto inst_id : associated_entities) {
  317. new_associated_entities.push_back(
  318. context_.AddImportRef(import_ir_id_, inst_id));
  319. }
  320. return context_.inst_blocks().Add(new_associated_entities);
  321. }
  322. // Tries to resolve the InstId, returning a constant when ready, or Invalid if
  323. // more has been added to the stack. A similar API is followed for all
  324. // following TryResolveTypedInst helper functions.
  325. //
  326. // `const_id` is Invalid unless we've tried to resolve this instruction
  327. // before, in which case it's the previous result.
  328. //
  329. // TODO: Error is returned when support is missing, but that should go away.
  330. auto TryResolveInst(SemIR::InstId inst_id, SemIR::ConstantId const_id)
  331. -> ResolveResult {
  332. if (inst_id.is_builtin()) {
  333. CARBON_CHECK(!const_id.is_valid());
  334. // Constants for builtins can be directly copied.
  335. return {context_.constant_values().Get(inst_id)};
  336. }
  337. auto inst = import_ir_.insts().Get(inst_id);
  338. switch (inst.kind()) {
  339. case SemIR::InstKind::AssociatedEntity:
  340. return TryResolveTypedInst(inst.As<SemIR::AssociatedEntity>());
  341. case SemIR::InstKind::AssociatedEntityType:
  342. return TryResolveTypedInst(inst.As<SemIR::AssociatedEntityType>());
  343. case SemIR::InstKind::BaseDecl:
  344. return TryResolveTypedInst(inst.As<SemIR::BaseDecl>());
  345. case SemIR::InstKind::BindAlias:
  346. return TryResolveTypedInst(inst.As<SemIR::BindAlias>());
  347. case SemIR::InstKind::ClassDecl:
  348. return TryResolveTypedInst(inst.As<SemIR::ClassDecl>(), const_id);
  349. case SemIR::InstKind::ClassType:
  350. return TryResolveTypedInst(inst.As<SemIR::ClassType>());
  351. case SemIR::InstKind::ConstType:
  352. return TryResolveTypedInst(inst.As<SemIR::ConstType>());
  353. case SemIR::InstKind::FieldDecl:
  354. return TryResolveTypedInst(inst.As<SemIR::FieldDecl>());
  355. case SemIR::InstKind::FunctionDecl:
  356. return TryResolveTypedInst(inst.As<SemIR::FunctionDecl>());
  357. case SemIR::InstKind::InterfaceDecl:
  358. return TryResolveTypedInst(inst.As<SemIR::InterfaceDecl>(), const_id);
  359. case SemIR::InstKind::InterfaceType:
  360. return TryResolveTypedInst(inst.As<SemIR::InterfaceType>());
  361. case SemIR::InstKind::PointerType:
  362. return TryResolveTypedInst(inst.As<SemIR::PointerType>());
  363. case SemIR::InstKind::StructType:
  364. return TryResolveTypedInst(inst.As<SemIR::StructType>());
  365. case SemIR::InstKind::TupleType:
  366. return TryResolveTypedInst(inst.As<SemIR::TupleType>());
  367. case SemIR::InstKind::UnboundElementType:
  368. return TryResolveTypedInst(inst.As<SemIR::UnboundElementType>());
  369. case SemIR::InstKind::BindName:
  370. // TODO: This always returns `ConstantId::NotConstant`.
  371. return {TryEvalInst(context_, inst_id, inst)};
  372. case SemIR::InstKind::BindSymbolicName:
  373. return TryResolveTypedInst(inst.As<SemIR::BindSymbolicName>());
  374. default:
  375. context_.TODO(
  376. Parse::NodeId(Parse::NodeId::Invalid),
  377. llvm::formatv("TryResolveInst on {0}", inst.kind()).str());
  378. return {SemIR::ConstantId::Error};
  379. }
  380. }
  381. auto TryResolveTypedInst(SemIR::AssociatedEntity inst) -> ResolveResult {
  382. auto initial_work = work_stack_.size();
  383. auto type_const_id = GetLocalConstantId(inst.type_id);
  384. if (HasNewWork(initial_work)) {
  385. return ResolveResult::Retry();
  386. }
  387. // Add a lazy reference to the target declaration.
  388. auto decl_id = context_.AddImportRef(import_ir_id_, inst.decl_id);
  389. auto inst_id = context_.AddInstInNoBlock(
  390. {Parse::NodeId::Invalid,
  391. SemIR::AssociatedEntity{
  392. context_.GetTypeIdForTypeConstant(type_const_id), inst.index,
  393. decl_id}});
  394. return {context_.constant_values().Get(inst_id)};
  395. }
  396. auto TryResolveTypedInst(SemIR::AssociatedEntityType inst) -> ResolveResult {
  397. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  398. auto initial_work = work_stack_.size();
  399. auto entity_type_const_id = GetLocalConstantId(inst.entity_type_id);
  400. auto interface_const_id = GetLocalConstantId(
  401. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  402. if (HasNewWork(initial_work)) {
  403. return ResolveResult::Retry();
  404. }
  405. auto inst_id = context_.AddInstInNoBlock(SemIR::AssociatedEntityType{
  406. SemIR::TypeId::TypeType,
  407. context_.insts()
  408. .GetAs<SemIR::InterfaceType>(interface_const_id.inst_id())
  409. .interface_id,
  410. context_.GetTypeIdForTypeConstant(entity_type_const_id)});
  411. return {context_.constant_values().Get(inst_id)};
  412. }
  413. auto TryResolveTypedInst(SemIR::BaseDecl inst) -> ResolveResult {
  414. auto initial_work = work_stack_.size();
  415. auto type_const_id = GetLocalConstantId(inst.type_id);
  416. auto base_type_const_id = GetLocalConstantId(inst.base_type_id);
  417. if (HasNewWork(initial_work)) {
  418. return ResolveResult::Retry();
  419. }
  420. // Import the instruction in order to update contained base_type_id.
  421. auto inst_id = context_.AddInstInNoBlock(
  422. {Parse::NodeId::Invalid,
  423. SemIR::BaseDecl{context_.GetTypeIdForTypeConstant(type_const_id),
  424. context_.GetTypeIdForTypeConstant(base_type_const_id),
  425. inst.index}});
  426. return {context_.constant_values().Get(inst_id)};
  427. }
  428. auto TryResolveTypedInst(SemIR::BindAlias inst) -> ResolveResult {
  429. auto initial_work = work_stack_.size();
  430. auto value_id = GetLocalConstantId(inst.value_id);
  431. if (HasNewWork(initial_work)) {
  432. return ResolveResult::Retry();
  433. }
  434. return {value_id};
  435. }
  436. auto TryResolveTypedInst(SemIR::BindSymbolicName inst) -> ResolveResult {
  437. auto initial_work = work_stack_.size();
  438. auto type_id = GetLocalConstantId(inst.type_id);
  439. if (HasNewWork(initial_work)) {
  440. return ResolveResult::Retry();
  441. }
  442. auto name_id =
  443. GetLocalNameId(import_ir_.bind_names().Get(inst.bind_name_id).name_id);
  444. auto bind_name_id = context_.bind_names().Add(
  445. {.name_id = name_id,
  446. .enclosing_scope_id = SemIR::NameScopeId::Invalid});
  447. auto new_bind_id = context_.AddInstInNoBlock(
  448. {Parse::NodeId::Invalid,
  449. SemIR::BindSymbolicName{context_.GetTypeIdForTypeConstant(type_id),
  450. bind_name_id, SemIR::InstId::Invalid}});
  451. return {context_.constant_values().Get(new_bind_id)};
  452. }
  453. // Makes an incomplete class. This is necessary even with classes with a
  454. // complete declaration, because things such as `Self` may refer back to the
  455. // type.
  456. auto MakeIncompleteClass(const SemIR::Class& import_class)
  457. -> SemIR::ConstantId {
  458. auto class_decl =
  459. SemIR::ClassDecl{SemIR::TypeId::Invalid, SemIR::ClassId::Invalid,
  460. SemIR::InstBlockId::Empty};
  461. auto class_decl_id =
  462. context_.AddPlaceholderInst({Parse::NodeId::Invalid, class_decl});
  463. // Regardless of whether ClassDecl is a complete type, we first need an
  464. // incomplete type so that any references have something to point at.
  465. class_decl.class_id = context_.classes().Add({
  466. .name_id = GetLocalNameId(import_class.name_id),
  467. // Set in the second pass once we've imported it.
  468. .enclosing_scope_id = SemIR::NameScopeId::Invalid,
  469. // `.self_type_id` depends on the ClassType, so is set below.
  470. .self_type_id = SemIR::TypeId::Invalid,
  471. .decl_id = class_decl_id,
  472. .inheritance_kind = import_class.inheritance_kind,
  473. });
  474. // Write the class ID into the ClassDecl.
  475. context_.ReplaceInstBeforeConstantUse(class_decl_id,
  476. {Parse::NodeId::Invalid, class_decl});
  477. auto self_const_id = context_.constant_values().Get(class_decl_id);
  478. // Build the `Self` type using the resulting type constant.
  479. auto& class_info = context_.classes().Get(class_decl.class_id);
  480. class_info.self_type_id = context_.GetTypeIdForTypeConstant(self_const_id);
  481. return self_const_id;
  482. }
  483. // Fills out the class definition for an incomplete class.
  484. auto AddClassDefinition(const SemIR::Class& import_class,
  485. SemIR::Class& new_class,
  486. SemIR::ConstantId object_repr_const_id,
  487. SemIR::ConstantId base_const_id) -> void {
  488. new_class.object_repr_id =
  489. context_.GetTypeIdForTypeConstant(object_repr_const_id);
  490. new_class.scope_id =
  491. context_.name_scopes().Add(new_class.decl_id, SemIR::NameId::Invalid,
  492. new_class.enclosing_scope_id);
  493. auto& new_scope = context_.name_scopes().Get(new_class.scope_id);
  494. const auto& import_scope =
  495. import_ir_.name_scopes().Get(import_class.scope_id);
  496. // Push a block so that we can add scoped instructions to it.
  497. context_.inst_block_stack().Push();
  498. AddNameScopeImportRefs(import_scope, new_scope);
  499. new_class.body_block_id = context_.inst_block_stack().Pop();
  500. if (import_class.base_id.is_valid()) {
  501. new_class.base_id = base_const_id.inst_id();
  502. // Add the base scope to extended scopes.
  503. auto base_inst_id = context_.types().GetInstId(
  504. context_.insts()
  505. .GetAs<SemIR::BaseDecl>(new_class.base_id)
  506. .base_type_id);
  507. const auto& base_class = context_.classes().Get(
  508. context_.insts().GetAs<SemIR::ClassType>(base_inst_id).class_id);
  509. new_scope.extended_scopes.push_back(base_class.scope_id);
  510. }
  511. CARBON_CHECK(new_scope.extended_scopes.size() ==
  512. import_scope.extended_scopes.size());
  513. }
  514. auto TryResolveTypedInst(SemIR::ClassDecl inst,
  515. SemIR::ConstantId class_const_id) -> ResolveResult {
  516. const auto& import_class = import_ir_.classes().Get(inst.class_id);
  517. // On the first pass, create a forward declaration of the class for any
  518. // recursive references.
  519. if (!class_const_id.is_valid()) {
  520. class_const_id = MakeIncompleteClass(import_class);
  521. }
  522. // Load constants for the definition.
  523. auto initial_work = work_stack_.size();
  524. auto enclosing_scope_id =
  525. GetLocalNameScopeId(import_class.enclosing_scope_id);
  526. auto object_repr_const_id =
  527. import_class.object_repr_id.is_valid()
  528. ? GetLocalConstantId(import_class.object_repr_id)
  529. : SemIR::ConstantId::Invalid;
  530. auto base_const_id = import_class.base_id.is_valid()
  531. ? GetLocalConstantId(import_class.base_id)
  532. : SemIR::ConstantId::Invalid;
  533. if (HasNewWork(initial_work)) {
  534. return ResolveResult::Retry(class_const_id);
  535. }
  536. auto& new_class = context_.classes().Get(
  537. context_.insts()
  538. .GetAs<SemIR::ClassType>(class_const_id.inst_id())
  539. .class_id);
  540. new_class.enclosing_scope_id = enclosing_scope_id;
  541. if (import_class.is_defined()) {
  542. AddClassDefinition(import_class, new_class, object_repr_const_id,
  543. base_const_id);
  544. }
  545. return {class_const_id};
  546. }
  547. auto TryResolveTypedInst(SemIR::ClassType inst) -> ResolveResult {
  548. auto initial_work = work_stack_.size();
  549. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  550. auto class_const_id =
  551. GetLocalConstantId(import_ir_.classes().Get(inst.class_id).decl_id);
  552. if (HasNewWork(initial_work)) {
  553. return ResolveResult::Retry();
  554. }
  555. return {class_const_id};
  556. }
  557. auto TryResolveTypedInst(SemIR::ConstType inst) -> ResolveResult {
  558. auto initial_work = work_stack_.size();
  559. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  560. auto inner_const_id = GetLocalConstantId(inst.inner_id);
  561. if (HasNewWork(initial_work)) {
  562. return ResolveResult::Retry();
  563. }
  564. auto inner_type_id = context_.GetTypeIdForTypeConstant(inner_const_id);
  565. // TODO: Should ConstType have a wrapper for this similar to the others?
  566. return {
  567. TryEvalInst(context_, SemIR::InstId::Invalid,
  568. SemIR::ConstType{SemIR::TypeId::TypeType, inner_type_id})};
  569. }
  570. auto TryResolveTypedInst(SemIR::FieldDecl inst) -> ResolveResult {
  571. auto initial_work = work_stack_.size();
  572. auto const_id = GetLocalConstantId(inst.type_id);
  573. if (HasNewWork(initial_work)) {
  574. return ResolveResult::Retry();
  575. }
  576. auto inst_id = context_.AddInstInNoBlock(
  577. {Parse::NodeId::Invalid,
  578. SemIR::FieldDecl{context_.GetTypeIdForTypeConstant(const_id),
  579. GetLocalNameId(inst.name_id), inst.index}});
  580. return {context_.constant_values().Get(inst_id)};
  581. }
  582. auto TryResolveTypedInst(SemIR::FunctionDecl inst) -> ResolveResult {
  583. auto initial_work = work_stack_.size();
  584. auto type_const_id = GetLocalConstantId(inst.type_id);
  585. const auto& function = import_ir_.functions().Get(inst.function_id);
  586. auto return_type_const_id = SemIR::ConstantId::Invalid;
  587. if (function.return_type_id.is_valid()) {
  588. return_type_const_id = GetLocalConstantId(function.return_type_id);
  589. }
  590. auto return_slot_const_id = SemIR::ConstantId::Invalid;
  591. if (function.return_slot_id.is_valid()) {
  592. return_slot_const_id = GetLocalConstantId(function.return_slot_id);
  593. }
  594. auto enclosing_scope_id = GetLocalNameScopeId(function.enclosing_scope_id);
  595. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  596. GetLocalParamConstantIds(function.implicit_param_refs_id);
  597. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  598. GetLocalParamConstantIds(function.param_refs_id);
  599. if (HasNewWork(initial_work)) {
  600. return ResolveResult::Retry();
  601. }
  602. // Add the function declaration.
  603. auto function_decl = SemIR::FunctionDecl{
  604. context_.GetTypeIdForTypeConstant(type_const_id),
  605. SemIR::FunctionId::Invalid, SemIR::InstBlockId::Empty};
  606. auto function_decl_id = context_.AddPlaceholderInstInNoBlock(
  607. {Parse::NodeId::Invalid, function_decl});
  608. auto new_return_type_id =
  609. return_type_const_id.is_valid()
  610. ? context_.GetTypeIdForTypeConstant(return_type_const_id)
  611. : SemIR::TypeId::Invalid;
  612. auto new_return_slot = SemIR::InstId::Invalid;
  613. if (function.return_slot_id.is_valid()) {
  614. context_.AddInstInNoBlock({SemIR::ImportRefUsed{
  615. context_.GetTypeIdForTypeConstant(return_slot_const_id),
  616. import_ir_id_, function.return_slot_id}});
  617. }
  618. function_decl.function_id = context_.functions().Add(
  619. {.name_id = GetLocalNameId(function.name_id),
  620. .enclosing_scope_id = enclosing_scope_id,
  621. .decl_id = function_decl_id,
  622. .implicit_param_refs_id = GetLocalParamRefsId(
  623. function.implicit_param_refs_id, implicit_param_const_ids),
  624. .param_refs_id =
  625. GetLocalParamRefsId(function.param_refs_id, param_const_ids),
  626. .return_type_id = new_return_type_id,
  627. .return_slot_id = new_return_slot});
  628. // Write the function ID into the FunctionDecl.
  629. context_.ReplaceInstBeforeConstantUse(
  630. function_decl_id, {Parse::NodeId::Invalid, function_decl});
  631. return {context_.constant_values().Get(function_decl_id)};
  632. }
  633. // Make a declaration of an interface. This is done as a separate step from
  634. // importing the interface definition in order to resolve cycles.
  635. auto MakeInterfaceDecl(const SemIR::Interface& import_interface)
  636. -> SemIR::ConstantId {
  637. auto interface_decl = SemIR::InterfaceDecl{SemIR::TypeId::Invalid,
  638. SemIR::InterfaceId::Invalid,
  639. SemIR::InstBlockId::Empty};
  640. auto interface_decl_id =
  641. context_.AddPlaceholderInst({Parse::NodeId::Invalid, interface_decl});
  642. // Start with an incomplete interface.
  643. SemIR::Interface new_interface = {
  644. .name_id = GetLocalNameId(import_interface.name_id),
  645. // Set in the second pass once we've imported it.
  646. .enclosing_scope_id = SemIR::NameScopeId::Invalid,
  647. .decl_id = interface_decl_id,
  648. };
  649. // Write the interface ID into the InterfaceDecl.
  650. interface_decl.interface_id = context_.interfaces().Add(new_interface);
  651. context_.ReplaceInstBeforeConstantUse(
  652. interface_decl_id, {Parse::NodeId::Invalid, interface_decl});
  653. // Set the constant value for the imported interface.
  654. return context_.constant_values().Get(interface_decl_id);
  655. }
  656. // Imports the definition for an interface that has been imported as a forward
  657. // declaration.
  658. auto AddInterfaceDefinition(const SemIR::Interface& import_interface,
  659. SemIR::Interface& new_interface,
  660. SemIR::ConstantId self_param_id) -> void {
  661. new_interface.scope_id = context_.name_scopes().Add(
  662. new_interface.decl_id, SemIR::NameId::Invalid,
  663. new_interface.enclosing_scope_id);
  664. auto& new_scope = context_.name_scopes().Get(new_interface.scope_id);
  665. const auto& import_scope =
  666. import_ir_.name_scopes().Get(import_interface.scope_id);
  667. // Push a block so that we can add scoped instructions to it.
  668. context_.inst_block_stack().Push();
  669. AddNameScopeImportRefs(import_scope, new_scope);
  670. new_interface.associated_entities_id =
  671. AddAssociatedEntities(import_interface.associated_entities_id);
  672. new_interface.body_block_id = context_.inst_block_stack().Pop();
  673. new_interface.self_param_id = self_param_id.inst_id();
  674. CARBON_CHECK(import_scope.extended_scopes.empty())
  675. << "Interfaces don't currently have extended scopes to support.";
  676. }
  677. auto TryResolveTypedInst(SemIR::InterfaceDecl inst,
  678. SemIR::ConstantId interface_const_id)
  679. -> ResolveResult {
  680. const auto& import_interface =
  681. import_ir_.interfaces().Get(inst.interface_id);
  682. // On the first pass, create a forward declaration of the interface.
  683. if (!interface_const_id.is_valid()) {
  684. interface_const_id = MakeInterfaceDecl(import_interface);
  685. }
  686. auto initial_work = work_stack_.size();
  687. auto enclosing_scope_id =
  688. GetLocalNameScopeId(import_interface.enclosing_scope_id);
  689. auto self_param_id = GetLocalConstantId(import_interface.self_param_id);
  690. if (HasNewWork(initial_work)) {
  691. return ResolveResult::Retry(interface_const_id);
  692. }
  693. auto& new_interface = context_.interfaces().Get(
  694. context_.insts()
  695. .GetAs<SemIR::InterfaceType>(interface_const_id.inst_id())
  696. .interface_id);
  697. new_interface.enclosing_scope_id = enclosing_scope_id;
  698. if (import_interface.is_defined()) {
  699. AddInterfaceDefinition(import_interface, new_interface, self_param_id);
  700. }
  701. return {interface_const_id};
  702. }
  703. auto TryResolveTypedInst(SemIR::InterfaceType inst) -> ResolveResult {
  704. auto initial_work = work_stack_.size();
  705. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  706. auto interface_const_id = GetLocalConstantId(
  707. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  708. if (HasNewWork(initial_work)) {
  709. return ResolveResult::Retry();
  710. }
  711. return {interface_const_id};
  712. }
  713. auto TryResolveTypedInst(SemIR::PointerType inst) -> ResolveResult {
  714. auto initial_work = work_stack_.size();
  715. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  716. auto pointee_const_id = GetLocalConstantId(inst.pointee_id);
  717. if (HasNewWork(initial_work)) {
  718. return ResolveResult::Retry();
  719. }
  720. auto pointee_type_id = context_.GetTypeIdForTypeConstant(pointee_const_id);
  721. return {context_.types().GetConstantId(
  722. context_.GetPointerType(pointee_type_id))};
  723. }
  724. auto TryResolveTypedInst(SemIR::StructType inst) -> ResolveResult {
  725. // Collect all constants first, locating unresolved ones in a single pass.
  726. auto initial_work = work_stack_.size();
  727. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  728. auto orig_fields = import_ir_.inst_blocks().Get(inst.fields_id);
  729. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  730. field_const_ids.reserve(orig_fields.size());
  731. for (auto field_id : orig_fields) {
  732. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  733. field_const_ids.push_back(GetLocalConstantId(field.field_type_id));
  734. }
  735. if (HasNewWork(initial_work)) {
  736. return ResolveResult::Retry();
  737. }
  738. // Prepare a vector of fields for GetStructType.
  739. // TODO: Should we have field constants so that we can deduplicate fields
  740. // without creating instructions here?
  741. llvm::SmallVector<SemIR::InstId> fields;
  742. fields.reserve(orig_fields.size());
  743. for (auto [field_id, field_const_id] :
  744. llvm::zip(orig_fields, field_const_ids)) {
  745. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  746. auto name_id = GetLocalNameId(field.name_id);
  747. auto field_type_id = context_.GetTypeIdForTypeConstant(field_const_id);
  748. fields.push_back(context_.AddInstInNoBlock(
  749. {Parse::NodeId::Invalid,
  750. SemIR::StructTypeField{.name_id = name_id,
  751. .field_type_id = field_type_id}}));
  752. }
  753. return {context_.types().GetConstantId(
  754. context_.GetStructType(context_.inst_blocks().Add(fields)))};
  755. }
  756. auto TryResolveTypedInst(SemIR::TupleType inst) -> ResolveResult {
  757. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  758. // Collect all constants first, locating unresolved ones in a single pass.
  759. auto initial_work = work_stack_.size();
  760. auto orig_elem_type_ids = import_ir_.type_blocks().Get(inst.elements_id);
  761. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  762. elem_const_ids.reserve(orig_elem_type_ids.size());
  763. for (auto elem_type_id : orig_elem_type_ids) {
  764. elem_const_ids.push_back(GetLocalConstantId(elem_type_id));
  765. }
  766. if (HasNewWork(initial_work)) {
  767. return ResolveResult::Retry();
  768. }
  769. // Prepare a vector of the tuple types for GetTupleType.
  770. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  771. elem_type_ids.reserve(orig_elem_type_ids.size());
  772. for (auto elem_const_id : elem_const_ids) {
  773. elem_type_ids.push_back(context_.GetTypeIdForTypeConstant(elem_const_id));
  774. }
  775. return {
  776. context_.types().GetConstantId(context_.GetTupleType(elem_type_ids))};
  777. }
  778. auto TryResolveTypedInst(SemIR::UnboundElementType inst) -> ResolveResult {
  779. auto initial_work = work_stack_.size();
  780. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  781. auto class_const_id = GetLocalConstantId(inst.class_type_id);
  782. auto elem_const_id = GetLocalConstantId(inst.element_type_id);
  783. if (HasNewWork(initial_work)) {
  784. return ResolveResult::Retry();
  785. }
  786. return {context_.types().GetConstantId(context_.GetUnboundElementType(
  787. context_.GetTypeIdForTypeConstant(class_const_id),
  788. context_.GetTypeIdForTypeConstant(elem_const_id)))};
  789. }
  790. Context& context_;
  791. SemIR::ImportIRId import_ir_id_;
  792. const SemIR::File& import_ir_;
  793. SemIR::ConstantValueStore& import_ir_constant_values_;
  794. llvm::SmallVector<Work> work_stack_;
  795. };
  796. auto TryResolveImportRefUnused(Context& context, SemIR::InstId inst_id)
  797. -> void {
  798. auto inst = context.insts().Get(inst_id);
  799. auto import_ref = inst.TryAs<SemIR::ImportRefUnused>();
  800. if (!import_ref) {
  801. return;
  802. }
  803. const SemIR::File& import_ir = *context.import_irs().Get(import_ref->ir_id);
  804. auto import_inst = import_ir.insts().Get(import_ref->inst_id);
  805. ImportRefResolver resolver(context, import_ref->ir_id);
  806. auto type_id = resolver.ResolveType(import_inst.type_id());
  807. auto constant_id = resolver.Resolve(import_ref->inst_id);
  808. // Replace the ImportRefUnused instruction with an ImportRefUsed. This doesn't
  809. // use ReplaceInstBeforeConstantUse because it would trigger TryEvalInst, and
  810. // we're instead doing constant evaluation here in order to minimize recursion
  811. // risks.
  812. context.sem_ir().insts().Set(
  813. inst_id,
  814. SemIR::ImportRefUsed{type_id, import_ref->ir_id, import_ref->inst_id});
  815. // Store the constant for both the ImportRefUsed and imported instruction.
  816. context.constant_values().Set(inst_id, constant_id);
  817. }
  818. } // namespace Carbon::Check