import_ref.cpp 40 KB

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