import_ref.cpp 56 KB

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