import_ref.cpp 52 KB

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