import_ref.cpp 38 KB

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