import_ref.cpp 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899
  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/check/generic.h"
  10. #include "toolchain/parse/node_ids.h"
  11. #include "toolchain/sem_ir/constant.h"
  12. #include "toolchain/sem_ir/file.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. #include "toolchain/sem_ir/import_ir.h"
  15. #include "toolchain/sem_ir/inst.h"
  16. #include "toolchain/sem_ir/inst_kind.h"
  17. #include "toolchain/sem_ir/typed_insts.h"
  18. namespace Carbon::Check {
  19. // Adds the ImportIR, excluding the update to the check_ir_map.
  20. static auto InternalAddImportIR(Context& context, SemIR::ImportIR import_ir)
  21. -> SemIR::ImportIRId {
  22. context.import_ir_constant_values().push_back(
  23. SemIR::ConstantValueStore(SemIR::ConstantId::Invalid));
  24. return context.import_irs().Add(import_ir);
  25. }
  26. auto SetApiImportIR(Context& context, SemIR::ImportIR import_ir) -> void {
  27. auto ir_id = SemIR::ImportIRId::Invalid;
  28. if (import_ir.sem_ir != nullptr) {
  29. ir_id = AddImportIR(context, import_ir);
  30. } else {
  31. // We don't have a check_ir_id, so add without touching check_ir_map.
  32. ir_id = InternalAddImportIR(context, import_ir);
  33. }
  34. CARBON_CHECK(ir_id == SemIR::ImportIRId::ApiForImpl)
  35. << "ApiForImpl must be the first IR";
  36. }
  37. auto AddImportIR(Context& context, SemIR::ImportIR import_ir)
  38. -> SemIR::ImportIRId {
  39. auto& ir_id = context.GetImportIRId(*import_ir.sem_ir);
  40. if (!ir_id.is_valid()) {
  41. // Note this updates check_ir_map.
  42. ir_id = InternalAddImportIR(context, import_ir);
  43. } else if (import_ir.is_export) {
  44. // We're processing an `export import`. In case the IR was indirectly added
  45. // as a non-export, mark it as an export.
  46. context.import_irs().Get(ir_id).is_export = true;
  47. }
  48. return ir_id;
  49. }
  50. auto AddImportRef(Context& context, SemIR::ImportIRInst import_ir_inst,
  51. SemIR::EntityNameId entity_name_id) -> SemIR::InstId {
  52. auto import_ir_inst_id = context.import_ir_insts().Add(import_ir_inst);
  53. SemIR::ImportRefUnloaded inst = {.import_ir_inst_id = import_ir_inst_id,
  54. .entity_name_id = entity_name_id};
  55. auto import_ref_id = context.AddPlaceholderInstInNoBlock(
  56. SemIR::LocIdAndInst(import_ir_inst_id, inst));
  57. // ImportRefs have a dedicated block because this may be called during
  58. // processing where the instruction shouldn't be inserted in the current inst
  59. // block.
  60. context.import_ref_ids().push_back(import_ref_id);
  61. return import_ref_id;
  62. }
  63. auto GetCanonicalImportIRInst(Context& context, const SemIR::File* cursor_ir,
  64. SemIR::InstId cursor_inst_id)
  65. -> SemIR::ImportIRInst {
  66. while (true) {
  67. auto inst = cursor_ir->insts().Get(cursor_inst_id);
  68. CARBON_KIND_SWITCH(inst) {
  69. case CARBON_KIND(SemIR::ExportDecl bind_export): {
  70. cursor_inst_id = bind_export.value_id;
  71. continue;
  72. }
  73. case SemIR::ImportRefLoaded::Kind:
  74. case SemIR::ImportRefUnloaded::Kind: {
  75. auto import_ref = inst.As<SemIR::AnyImportRef>();
  76. auto import_ir_inst =
  77. cursor_ir->import_ir_insts().Get(import_ref.import_ir_inst_id);
  78. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  79. cursor_inst_id = import_ir_inst.inst_id;
  80. continue;
  81. }
  82. default: {
  83. auto ir_id = SemIR::ImportIRId::Invalid;
  84. if (cursor_ir != &context.sem_ir()) {
  85. // This uses AddImportIR in case it was indirectly found, which can
  86. // happen with two or more steps of exports.
  87. ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  88. .is_export = false,
  89. .sem_ir = cursor_ir});
  90. }
  91. return {.ir_id = ir_id, .inst_id = cursor_inst_id};
  92. }
  93. }
  94. }
  95. }
  96. auto VerifySameCanonicalImportIRInst(Context& context, SemIR::InstId prev_id,
  97. SemIR::ImportIRInst prev_import_ir_inst,
  98. SemIR::ImportIRId new_ir_id,
  99. const SemIR::File* new_import_ir,
  100. SemIR::InstId new_inst_id) -> void {
  101. auto new_import_ir_inst =
  102. GetCanonicalImportIRInst(context, new_import_ir, new_inst_id);
  103. if (new_import_ir_inst == prev_import_ir_inst) {
  104. return;
  105. }
  106. auto conflict_id =
  107. AddImportRef(context, {.ir_id = new_ir_id, .inst_id = new_inst_id},
  108. SemIR::EntityNameId::Invalid);
  109. context.DiagnoseDuplicateName(conflict_id, prev_id);
  110. }
  111. // Resolves an instruction from an imported IR into a constant referring to the
  112. // current IR.
  113. //
  114. // Calling Resolve on an instruction operates in an iterative manner, tracking
  115. // Work items on work_stack_. At a high level, the loop is:
  116. //
  117. // 1. If a constant value is already known for the work item, and we're
  118. // processing it for the first time, it's considered resolved.
  119. // - The constant check avoids performance costs of deduplication on add.
  120. // - If `retry` is set, we process it again, because it didn't complete last
  121. // time, even though we have a constant value already.
  122. // 2. Resolve the instruction: (TryResolveInst/TryResolveTypedInst)
  123. // - For a symbolic constant within a generic, find the generic itself. If it
  124. // needs to be imported, return Retry() to import the generic before we
  125. // import the constant.
  126. // - For instructions that can be forward declared, if we don't already have
  127. // a constant value from a previous attempt at resolution, start by making
  128. // a forward declared constant value to address circular references.
  129. // - Gather all input constants.
  130. // - Gathering constants directly adds unresolved values to work_stack_.
  131. // - If any need to be resolved (HasNewWork), return Retry(): this
  132. // instruction needs another call to complete.
  133. // - If the constant value is already known because we have made a forward
  134. // declaration, pass it to Retry(). It will be passed to future attempts
  135. // to resolve this instruction so the earlier work can be found, and will
  136. // be made available for other instructions to use.
  137. // - The subsequent attempt to resolve this instruction must produce the
  138. // same constant, because the value may have already been used by
  139. // resolved instructions.
  140. // - Build any necessary IR structures, and return the output constant.
  141. // 3. If resolve didn't return Retry(), pop the work. Otherwise, it needs to
  142. // remain, and may no longer be at the top of the stack; set `retry` on it so
  143. // we'll make sure to run it again later.
  144. //
  145. // TryResolveInst can complete in one call for a given instruction, but should
  146. // always complete within three calls:
  147. //
  148. // - TryResolveInst can retry once if the generic is not yet loaded.
  149. // - TryResolveTypedInst can retry once if its inputs are not yet loaded.
  150. // - The third call should succeed.
  151. //
  152. // Due to the chance of a second call to TryResolveTypedInst, it's important to
  153. // reserve all expensive logic until it's been established that input constants
  154. // are available.
  155. //
  156. // TODO: Fix class `extern` handling and merging, rewrite tests.
  157. // - check/testdata/class/cross_package_import.carbon
  158. // - check/testdata/class/extern.carbon
  159. // TODO: Fix function `extern` handling and merging, rewrite tests.
  160. // - check/testdata/function/declaration/import.carbon
  161. // - check/testdata/packages/cross_package_import.carbon
  162. class ImportRefResolver {
  163. public:
  164. explicit ImportRefResolver(Context& context, SemIR::ImportIRId import_ir_id)
  165. : context_(context),
  166. import_ir_id_(import_ir_id),
  167. import_ir_(*context_.import_irs().Get(import_ir_id).sem_ir) {}
  168. // Iteratively resolves an imported instruction's inner references until a
  169. // constant ID referencing the current IR is produced. See the class comment
  170. // for more details.
  171. auto Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId {
  172. work_stack_.push_back({.inst_id = inst_id});
  173. while (!work_stack_.empty()) {
  174. auto work = work_stack_.back();
  175. CARBON_CHECK(work.inst_id.is_valid());
  176. // Step 1: check for a constant value.
  177. auto existing = FindResolvedConstId(work.inst_id);
  178. if (existing.const_id.is_valid() && !work.retry) {
  179. work_stack_.pop_back();
  180. continue;
  181. }
  182. // Step 2: resolve the instruction.
  183. auto initial_work = work_stack_.size();
  184. auto [new_const_id, finished] =
  185. TryResolveInst(work.inst_id, existing.const_id);
  186. CARBON_CHECK(finished == !HasNewWork(initial_work));
  187. CARBON_CHECK(!existing.const_id.is_valid() ||
  188. existing.const_id == new_const_id)
  189. << "Constant value changed in second pass.";
  190. if (!existing.const_id.is_valid()) {
  191. SetResolvedConstId(work.inst_id, existing.indirect_insts, new_const_id);
  192. }
  193. // Step 3: pop or retry.
  194. if (finished) {
  195. work_stack_.pop_back();
  196. } else {
  197. work_stack_[initial_work - 1].retry = true;
  198. }
  199. }
  200. auto constant_id = import_ir_constant_values().Get(inst_id);
  201. CARBON_CHECK(constant_id.is_valid());
  202. return constant_id;
  203. }
  204. // Wraps constant evaluation with logic to handle constants.
  205. auto ResolveConstant(SemIR::ConstantId import_const_id) -> SemIR::ConstantId {
  206. if (!import_const_id.is_valid()) {
  207. return import_const_id;
  208. }
  209. // For template constants, the corresponding instruction has the desired
  210. // constant value.
  211. if (!import_const_id.is_symbolic()) {
  212. return Resolve(import_ir_.constant_values().GetInstId(import_const_id));
  213. }
  214. // For abstract symbolic constants, the corresponding instruction has the
  215. // desired constant value.
  216. const auto& symbolic_const =
  217. import_ir_.constant_values().GetSymbolicConstant(import_const_id);
  218. if (!symbolic_const.generic_id.is_valid()) {
  219. return Resolve(import_ir_.constant_values().GetInstId(import_const_id));
  220. }
  221. // For a symbolic constant in a generic, pick the corresponding instruction
  222. // out of the eval block for the generic and resolve its constant value.
  223. const auto& generic = import_ir_.generics().Get(symbolic_const.generic_id);
  224. auto block = generic.GetEvalBlock(symbolic_const.index.region());
  225. return Resolve(
  226. import_ir_.inst_blocks().Get(block)[symbolic_const.index.index()]);
  227. }
  228. // Wraps constant evaluation with logic to handle types.
  229. auto ResolveType(SemIR::TypeId import_type_id) -> SemIR::TypeId {
  230. if (!import_type_id.is_valid()) {
  231. return import_type_id;
  232. }
  233. auto import_type_const_id =
  234. import_ir_.types().GetConstantId(import_type_id);
  235. CARBON_CHECK(import_type_const_id.is_valid());
  236. if (auto import_type_inst_id =
  237. import_ir_.constant_values().GetInstId(import_type_const_id);
  238. import_type_inst_id.is_builtin()) {
  239. // Builtins don't require constant resolution; we can use them directly.
  240. return context_.GetBuiltinType(import_type_inst_id.builtin_inst_kind());
  241. } else {
  242. return context_.GetTypeIdForTypeConstant(
  243. ResolveConstant(import_type_id.AsConstantId()));
  244. }
  245. }
  246. private:
  247. // A step in work_stack_.
  248. struct Work {
  249. // The instruction to work on.
  250. SemIR::InstId inst_id;
  251. // True if another pass was requested last time this was run.
  252. bool retry = false;
  253. };
  254. // The result of attempting to resolve an imported instruction to a constant.
  255. struct ResolveResult {
  256. // Try resolving this function again. If `const_id` is specified, it will be
  257. // passed to the next resolution attempt.
  258. static auto Retry(SemIR::ConstantId const_id = SemIR::ConstantId::Invalid)
  259. -> ResolveResult {
  260. return {.const_id = const_id, .finished = false};
  261. }
  262. // The new constant value, if known.
  263. SemIR::ConstantId const_id;
  264. // Whether resolution has finished. If false, `TryResolveInst` will be
  265. // called again. Note that this is not strictly necessary, and we can get
  266. // the same information by checking whether new work was added to the stack.
  267. // However, we use this for consistency checks between resolve actions and
  268. // the work stack.
  269. bool finished = true;
  270. };
  271. // The constant found by FindResolvedConstId.
  272. struct ResolvedConstId {
  273. // The constant for the instruction. Invalid if not yet resolved.
  274. SemIR::ConstantId const_id = SemIR::ConstantId::Invalid;
  275. // Instructions which are indirect but equivalent to the current instruction
  276. // being resolved, and should have their constant set to the same. Empty
  277. // when const_id is valid.
  278. llvm::SmallVector<SemIR::ImportIRInst> indirect_insts = {};
  279. };
  280. // Local information associated with an imported generic.
  281. struct GenericData {
  282. llvm::SmallVector<SemIR::InstId> bindings;
  283. // TODO: Add data for the self specific.
  284. llvm::SmallVector<SemIR::InstId> decl_block;
  285. llvm::SmallVector<SemIR::InstId> definition_block;
  286. };
  287. // Local information associated with an imported specific.
  288. struct SpecificData {
  289. SemIR::ConstantId generic_const_id;
  290. llvm::SmallVector<SemIR::InstId> args;
  291. llvm::SmallVector<SemIR::InstId> decl_block;
  292. llvm::SmallVector<SemIR::InstId> definition_block;
  293. };
  294. // Looks to see if an instruction has been resolved. If a constant is only
  295. // found indirectly, sets the constant for any indirect steps that don't
  296. // already have the constant. If a constant isn't found, returns the indirect
  297. // instructions so that they can have the resolved constant assigned later.
  298. auto FindResolvedConstId(SemIR::InstId inst_id) -> ResolvedConstId {
  299. ResolvedConstId result;
  300. if (auto existing_const_id = import_ir_constant_values().Get(inst_id);
  301. existing_const_id.is_valid()) {
  302. result.const_id = existing_const_id;
  303. return result;
  304. }
  305. const auto* cursor_ir = &import_ir_;
  306. auto cursor_ir_id = SemIR::ImportIRId::Invalid;
  307. auto cursor_inst_id = inst_id;
  308. while (true) {
  309. auto loc_id = cursor_ir->insts().GetLocId(cursor_inst_id);
  310. if (!loc_id.is_import_ir_inst_id()) {
  311. return result;
  312. }
  313. auto ir_inst =
  314. cursor_ir->import_ir_insts().Get(loc_id.import_ir_inst_id());
  315. const auto* prev_ir = cursor_ir;
  316. auto prev_inst_id = cursor_inst_id;
  317. cursor_ir = cursor_ir->import_irs().Get(ir_inst.ir_id).sem_ir;
  318. cursor_ir_id = context_.GetImportIRId(*cursor_ir);
  319. if (!cursor_ir_id.is_valid()) {
  320. // TODO: Should we figure out a location to assign here?
  321. cursor_ir_id = AddImportIR(context_, {.decl_id = SemIR::InstId::Invalid,
  322. .is_export = false,
  323. .sem_ir = cursor_ir});
  324. }
  325. cursor_inst_id = ir_inst.inst_id;
  326. CARBON_CHECK(cursor_ir != prev_ir || cursor_inst_id != prev_inst_id)
  327. << cursor_ir->insts().Get(cursor_inst_id);
  328. if (auto const_id =
  329. context_.import_ir_constant_values()[cursor_ir_id.index].Get(
  330. cursor_inst_id);
  331. const_id.is_valid()) {
  332. SetResolvedConstId(inst_id, result.indirect_insts, const_id);
  333. result.const_id = const_id;
  334. result.indirect_insts.clear();
  335. return result;
  336. } else {
  337. result.indirect_insts.push_back(
  338. {.ir_id = cursor_ir_id, .inst_id = cursor_inst_id});
  339. }
  340. }
  341. }
  342. // Sets a resolved constant into the current and indirect instructions.
  343. auto SetResolvedConstId(SemIR::InstId inst_id,
  344. llvm::ArrayRef<SemIR::ImportIRInst> indirect_insts,
  345. SemIR::ConstantId const_id) -> void {
  346. import_ir_constant_values().Set(inst_id, const_id);
  347. for (auto indirect_inst : indirect_insts) {
  348. context_.import_ir_constant_values()[indirect_inst.ir_id.index].Set(
  349. indirect_inst.inst_id, const_id);
  350. }
  351. }
  352. // Returns true if new unresolved constants were found.
  353. //
  354. // At the start of a function, do:
  355. // auto initial_work = work_stack_.size();
  356. // Then when determining:
  357. // if (HasNewWork(initial_work)) { ... }
  358. auto HasNewWork(size_t initial_work) -> bool {
  359. CARBON_CHECK(initial_work <= work_stack_.size())
  360. << "Work shouldn't decrease";
  361. return initial_work < work_stack_.size();
  362. }
  363. auto AddImportIRInst(SemIR::InstId inst_id) -> SemIR::ImportIRInstId {
  364. return context_.import_ir_insts().Add(
  365. {.ir_id = import_ir_id_, .inst_id = inst_id});
  366. }
  367. // Returns the ConstantId for an InstId. Adds unresolved constants to
  368. // work_stack_.
  369. auto GetLocalConstantId(SemIR::InstId inst_id) -> SemIR::ConstantId {
  370. auto const_id = import_ir_constant_values().Get(inst_id);
  371. if (!const_id.is_valid()) {
  372. work_stack_.push_back({.inst_id = inst_id});
  373. }
  374. return const_id;
  375. }
  376. // Returns the local constant InstId for an imported InstId.
  377. auto GetLocalConstantInstId(SemIR::InstId inst_id) -> SemIR::InstId {
  378. auto const_id = import_ir_constant_values().Get(inst_id);
  379. if (!const_id.is_valid()) {
  380. work_stack_.push_back({.inst_id = inst_id});
  381. return SemIR::InstId::Invalid;
  382. }
  383. return context_.constant_values().GetInstId(const_id);
  384. }
  385. // Returns the ConstantId for a TypeId. Adds unresolved constants to
  386. // work_stack_.
  387. auto GetLocalConstantId(SemIR::TypeId type_id) -> SemIR::ConstantId {
  388. return GetLocalConstantId(import_ir_.types().GetInstId(type_id));
  389. }
  390. // Gets the local constant values corresponding to an imported inst block.
  391. auto GetLocalInstBlockContents(SemIR::InstBlockId import_block_id)
  392. -> llvm::SmallVector<SemIR::InstId> {
  393. llvm::SmallVector<SemIR::InstId> inst_ids;
  394. if (!import_block_id.is_valid() ||
  395. import_block_id == SemIR::InstBlockId::Empty) {
  396. return inst_ids;
  397. }
  398. // Import all the values in the block.
  399. auto import_block = import_ir_.inst_blocks().Get(import_block_id);
  400. inst_ids.reserve(import_block.size());
  401. for (auto import_inst_id : import_block) {
  402. auto const_id = GetLocalConstantId(import_inst_id);
  403. inst_ids.push_back(context_.constant_values().GetInstIdIfValid(const_id));
  404. }
  405. return inst_ids;
  406. }
  407. // Gets a local instruction block ID corresponding to an imported inst block
  408. // whose contents were already imported, for example by
  409. // GetLocalInstBlockContents.
  410. auto GetLocalInstBlockId(SemIR::InstBlockId import_block_id,
  411. llvm::ArrayRef<SemIR::InstId> contents)
  412. -> SemIR::InstBlockId {
  413. if (!import_block_id.is_valid()) {
  414. return SemIR::InstBlockId::Invalid;
  415. }
  416. return context_.inst_blocks().Add(contents);
  417. }
  418. // Gets a local canonical instruction block ID corresponding to an imported
  419. // inst block whose contents were already imported, for example by
  420. // GetLocalInstBlockContents.
  421. auto GetLocalCanonicalInstBlockId(SemIR::InstBlockId import_block_id,
  422. llvm::ArrayRef<SemIR::InstId> contents)
  423. -> SemIR::InstBlockId {
  424. if (!import_block_id.is_valid()) {
  425. return SemIR::InstBlockId::Invalid;
  426. }
  427. return context_.inst_blocks().AddCanonical(contents);
  428. }
  429. // Gets an incomplete local version of an imported generic. Most fields are
  430. // set in the second pass.
  431. auto MakeIncompleteGeneric(SemIR::InstId decl_id, SemIR::GenericId generic_id)
  432. -> SemIR::GenericId {
  433. if (!generic_id.is_valid()) {
  434. return SemIR::GenericId::Invalid;
  435. }
  436. return context_.generics().Add(
  437. {.decl_id = decl_id,
  438. .bindings_id = SemIR::InstBlockId::Invalid,
  439. .self_specific_id = SemIR::SpecificId::Invalid});
  440. }
  441. // Gets a local version of the data associated with a generic.
  442. auto GetLocalGenericData(SemIR::GenericId generic_id) -> GenericData {
  443. if (!generic_id.is_valid()) {
  444. return GenericData();
  445. }
  446. const auto& generic = import_ir_.generics().Get(generic_id);
  447. return {
  448. .bindings = GetLocalInstBlockContents(generic.bindings_id),
  449. .decl_block = GetLocalInstBlockContents(generic.decl_block_id),
  450. .definition_block =
  451. GetLocalInstBlockContents(generic.definition_block_id),
  452. };
  453. }
  454. // Given the local constant values for the elements of the eval block, builds
  455. // and returns the eval block for a region of a generic.
  456. auto GetLocalEvalBlock(const SemIR::Generic& import_generic,
  457. SemIR::GenericId generic_id,
  458. SemIR::GenericInstIndex::Region region,
  459. llvm::ArrayRef<SemIR::InstId> inst_ids)
  460. -> SemIR::InstBlockId {
  461. auto import_block_id = import_generic.GetEvalBlock(region);
  462. if (!import_block_id.is_valid()) {
  463. return SemIR::InstBlockId::Invalid;
  464. }
  465. return RebuildGenericEvalBlock(context_, generic_id, region, inst_ids);
  466. }
  467. // Adds the given local generic data to the given generic.
  468. auto SetGenericData(SemIR::GenericId import_generic_id,
  469. SemIR::GenericId new_generic_id,
  470. const GenericData& generic_data) -> void {
  471. if (!import_generic_id.is_valid()) {
  472. return;
  473. }
  474. const auto& import_generic = import_ir_.generics().Get(import_generic_id);
  475. auto& new_generic = context_.generics().Get(new_generic_id);
  476. new_generic.bindings_id = GetLocalCanonicalInstBlockId(
  477. import_generic.bindings_id, generic_data.bindings);
  478. // TODO: Import or rebuild the self specific.
  479. new_generic.decl_block_id = GetLocalEvalBlock(
  480. import_generic, new_generic_id,
  481. SemIR::GenericInstIndex::Region::Declaration, generic_data.decl_block);
  482. new_generic.definition_block_id =
  483. GetLocalEvalBlock(import_generic, new_generic_id,
  484. SemIR::GenericInstIndex::Region::Definition,
  485. generic_data.definition_block);
  486. }
  487. // Gets a local constant value corresponding to an imported generic ID. May
  488. // add work to the work stack and return `Invalid`.
  489. auto GetLocalConstantId(SemIR::GenericId generic_id) -> SemIR::ConstantId {
  490. if (!generic_id.is_valid()) {
  491. return SemIR::ConstantId::Invalid;
  492. }
  493. return GetLocalConstantId(
  494. import_ir_.insts()
  495. .Get(import_ir_.generics().Get(generic_id).decl_id)
  496. .type_id());
  497. }
  498. // Gets a local generic ID given the corresponding local constant ID returned
  499. // by GetLocalConstantId for the imported generic. Does not add any new work.
  500. auto GetLocalGenericId(SemIR::ConstantId local_const_id) -> SemIR::GenericId {
  501. if (!local_const_id.is_valid()) {
  502. return SemIR::GenericId::Invalid;
  503. }
  504. auto type = context_.insts().Get(
  505. context_.constant_values().GetInstId(local_const_id));
  506. CARBON_KIND_SWITCH(type) {
  507. case CARBON_KIND(SemIR::FunctionType fn_type): {
  508. return context_.functions().Get(fn_type.function_id).generic_id;
  509. }
  510. case CARBON_KIND(SemIR::GenericClassType class_type): {
  511. return context_.classes().Get(class_type.class_id).generic_id;
  512. }
  513. case CARBON_KIND(SemIR::GenericInterfaceType interface_type): {
  514. return context_.interfaces()
  515. .Get(interface_type.interface_id)
  516. .generic_id;
  517. }
  518. default: {
  519. CARBON_FATAL() << "Unexpected type for generic declaration: " << type;
  520. }
  521. }
  522. }
  523. // Gets local information about an imported specific.
  524. auto GetLocalSpecificData(SemIR::SpecificId specific_id) -> SpecificData {
  525. if (!specific_id.is_valid()) {
  526. return {.generic_const_id = SemIR::ConstantId::Invalid, .args = {}};
  527. }
  528. const auto& specific = import_ir_.specifics().Get(specific_id);
  529. return {
  530. .generic_const_id = GetLocalConstantId(specific.generic_id),
  531. .args = GetLocalInstBlockContents(specific.args_id),
  532. .decl_block = GetLocalInstBlockContents(specific.decl_block_id),
  533. .definition_block =
  534. GetLocalInstBlockContents(specific.definition_block_id),
  535. };
  536. }
  537. // Gets a local specific whose data was already imported by
  538. // GetLocalSpecificData. Does not add any new work.
  539. auto GetOrAddLocalSpecific(SemIR::SpecificId import_specific_id,
  540. const SpecificData& data) -> SemIR::SpecificId {
  541. if (!import_specific_id.is_valid()) {
  542. return SemIR::SpecificId::Invalid;
  543. }
  544. // Form a corresponding local specific ID.
  545. const auto& import_specific =
  546. import_ir_.specifics().Get(import_specific_id);
  547. auto generic_id = GetLocalGenericId(data.generic_const_id);
  548. auto args_id =
  549. GetLocalCanonicalInstBlockId(import_specific.args_id, data.args);
  550. // Populate the specific. Note that we might get data from multiple
  551. // different import IRs, so only import data we don't already have.
  552. auto specific_id = context_.specifics().GetOrAdd(generic_id, args_id);
  553. auto& specific = context_.specifics().Get(specific_id);
  554. if (!specific.decl_block_id.is_valid()) {
  555. specific.decl_block_id =
  556. GetLocalInstBlockId(import_specific.decl_block_id, data.decl_block);
  557. }
  558. if (!specific.definition_block_id.is_valid()) {
  559. specific.definition_block_id = GetLocalInstBlockId(
  560. import_specific.definition_block_id, data.definition_block);
  561. }
  562. return specific_id;
  563. }
  564. // Returns the ConstantId for each parameter's type. Adds unresolved constants
  565. // to work_stack_.
  566. auto GetLocalParamConstantIds(SemIR::InstBlockId param_refs_id)
  567. -> llvm::SmallVector<SemIR::ConstantId> {
  568. llvm::SmallVector<SemIR::ConstantId> const_ids;
  569. if (!param_refs_id.is_valid() ||
  570. param_refs_id == SemIR::InstBlockId::Empty) {
  571. return const_ids;
  572. }
  573. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  574. const_ids.reserve(param_refs.size());
  575. for (auto inst_id : param_refs) {
  576. const_ids.push_back(
  577. GetLocalConstantId(import_ir_.insts().Get(inst_id).type_id()));
  578. // If the parameter is a symbolic binding, build the BindSymbolicName
  579. // constant.
  580. auto bind_id = inst_id;
  581. if (auto addr =
  582. import_ir_.insts().TryGetAs<SemIR::AddrPattern>(bind_id)) {
  583. bind_id = addr->inner_id;
  584. }
  585. GetLocalConstantId(bind_id);
  586. }
  587. return const_ids;
  588. }
  589. // Given a param_refs_id and const_ids from GetLocalParamConstantIds, returns
  590. // a version of param_refs_id localized to the current IR.
  591. auto GetLocalParamRefsId(
  592. SemIR::InstBlockId param_refs_id,
  593. const llvm::SmallVector<SemIR::ConstantId>& const_ids)
  594. -> SemIR::InstBlockId {
  595. if (!param_refs_id.is_valid() ||
  596. param_refs_id == SemIR::InstBlockId::Empty) {
  597. return param_refs_id;
  598. }
  599. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  600. llvm::SmallVector<SemIR::InstId> new_param_refs;
  601. for (auto [ref_id, const_id] : llvm::zip(param_refs, const_ids)) {
  602. // Figure out the param structure. This echoes
  603. // Function::GetParamFromParamRefId.
  604. // TODO: Consider a different parameter handling to simplify import logic.
  605. auto inst = import_ir_.insts().Get(ref_id);
  606. auto addr_inst = inst.TryAs<SemIR::AddrPattern>();
  607. auto bind_id = ref_id;
  608. auto param_id = ref_id;
  609. if (addr_inst) {
  610. bind_id = addr_inst->inner_id;
  611. param_id = bind_id;
  612. inst = import_ir_.insts().Get(bind_id);
  613. }
  614. auto bind_inst = inst.TryAs<SemIR::AnyBindName>();
  615. if (bind_inst) {
  616. param_id = bind_inst->value_id;
  617. inst = import_ir_.insts().Get(param_id);
  618. }
  619. auto param_inst = inst.As<SemIR::Param>();
  620. // Rebuild the param instruction.
  621. auto name_id = GetLocalNameId(param_inst.name_id);
  622. auto type_id = context_.GetTypeIdForTypeConstant(const_id);
  623. auto new_param_id = context_.AddInstInNoBlock<SemIR::Param>(
  624. AddImportIRInst(param_id), {.type_id = type_id, .name_id = name_id});
  625. if (bind_inst) {
  626. switch (bind_inst->kind) {
  627. case SemIR::BindName::Kind: {
  628. auto entity_name_id = context_.entity_names().Add(
  629. {.name_id = name_id,
  630. .parent_scope_id = SemIR::NameScopeId::Invalid,
  631. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  632. new_param_id = context_.AddInstInNoBlock<SemIR::BindName>(
  633. AddImportIRInst(bind_id), {.type_id = type_id,
  634. .entity_name_id = entity_name_id,
  635. .value_id = new_param_id});
  636. break;
  637. }
  638. case SemIR::BindSymbolicName::Kind: {
  639. // We already imported a constant value for this symbolic binding.
  640. // We can reuse most of it.
  641. auto new_bind_inst_id = GetLocalConstantInstId(bind_id);
  642. auto new_bind_inst =
  643. context_.insts().GetAs<SemIR::BindSymbolicName>(
  644. new_bind_inst_id);
  645. new_bind_inst.value_id = new_param_id;
  646. new_param_id = context_.AddInstInNoBlock(AddImportIRInst(bind_id),
  647. new_bind_inst);
  648. break;
  649. }
  650. default: {
  651. CARBON_FATAL() << "Unexpected kind: " << bind_inst->kind;
  652. }
  653. }
  654. }
  655. if (addr_inst) {
  656. new_param_id = context_.AddInstInNoBlock<SemIR::AddrPattern>(
  657. AddImportIRInst(ref_id),
  658. {.type_id = type_id, .inner_id = new_param_id});
  659. }
  660. new_param_refs.push_back(new_param_id);
  661. }
  662. return context_.inst_blocks().Add(new_param_refs);
  663. }
  664. // Translates a NameId from the import IR to a local NameId.
  665. auto GetLocalNameId(SemIR::NameId import_name_id) -> SemIR::NameId {
  666. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.is_valid()) {
  667. return SemIR::NameId::ForIdentifier(
  668. context_.identifiers().Add(import_ir_.identifiers().Get(ident_id)));
  669. }
  670. return import_name_id;
  671. }
  672. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  673. // unresolved constants to the work stack.
  674. auto GetLocalNameScopeId(SemIR::NameScopeId name_scope_id)
  675. -> SemIR::NameScopeId {
  676. // Get the instruction that created the scope.
  677. auto [inst_id, inst] =
  678. import_ir_.name_scopes().GetInstIfValid(name_scope_id);
  679. if (!inst) {
  680. // Map scopes that aren't associated with an instruction to invalid
  681. // scopes. For now, such scopes aren't used, and we don't have a good way
  682. // to remap them.
  683. return SemIR::NameScopeId::Invalid;
  684. }
  685. // Get the constant value for the scope.
  686. auto const_id = SemIR::ConstantId::Invalid;
  687. CARBON_KIND_SWITCH(*inst) {
  688. case SemIR::ImplDecl::Kind:
  689. // TODO: Import the scope for an `impl` definition.
  690. return SemIR::NameScopeId::Invalid;
  691. case SemIR::Namespace::Kind:
  692. // If the namespace has already been imported, we can use its constant.
  693. // However, if it hasn't, we use Invalid instead of adding it to the
  694. // work stack. That's expected to be okay when resolving references.
  695. const_id = import_ir_constant_values().Get(inst_id);
  696. break;
  697. default:
  698. const_id = GetLocalConstantId(inst_id);
  699. }
  700. if (!const_id.is_valid()) {
  701. return SemIR::NameScopeId::Invalid;
  702. }
  703. auto const_inst_id = context_.constant_values().GetInstId(const_id);
  704. auto name_scope_inst = context_.insts().Get(const_inst_id);
  705. CARBON_KIND_SWITCH(name_scope_inst) {
  706. case CARBON_KIND(SemIR::Namespace inst): {
  707. return inst.name_scope_id;
  708. }
  709. case CARBON_KIND(SemIR::ClassType inst): {
  710. return context_.classes().Get(inst.class_id).scope_id;
  711. }
  712. case CARBON_KIND(SemIR::InterfaceType inst): {
  713. return context_.interfaces().Get(inst.interface_id).scope_id;
  714. }
  715. case SemIR::StructValue::Kind: {
  716. auto type_inst = context_.types().GetAsInst(name_scope_inst.type_id());
  717. CARBON_KIND_SWITCH(type_inst) {
  718. case CARBON_KIND(SemIR::GenericClassType inst): {
  719. return context_.classes().Get(inst.class_id).scope_id;
  720. }
  721. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  722. return context_.interfaces().Get(inst.interface_id).scope_id;
  723. }
  724. default: {
  725. break;
  726. }
  727. }
  728. break;
  729. }
  730. default: {
  731. if (const_inst_id == SemIR::InstId::BuiltinError) {
  732. return SemIR::NameScopeId::Invalid;
  733. }
  734. break;
  735. }
  736. }
  737. CARBON_FATAL() << "Unexpected instruction kind for name scope: "
  738. << name_scope_inst;
  739. }
  740. // Given an imported entity base, returns an incomplete, local version of it.
  741. //
  742. // Most fields are set in the second pass once they're imported. Import enough
  743. // of the parameter lists that we know whether this interface is a generic
  744. // interface and can build the right constant value for it.
  745. //
  746. // TODO: Add a better way to represent a generic prior to importing the
  747. // parameters.
  748. auto GetIncompleteLocalEntityBase(
  749. SemIR::InstId decl_id, const SemIR::EntityWithParamsBase& import_base)
  750. -> SemIR::EntityWithParamsBase {
  751. return {
  752. .name_id = GetLocalNameId(import_base.name_id),
  753. .parent_scope_id = SemIR::NameScopeId::Invalid,
  754. .generic_id = MakeIncompleteGeneric(decl_id, import_base.generic_id),
  755. .first_param_node_id = Parse::NodeId::Invalid,
  756. .last_param_node_id = Parse::NodeId::Invalid,
  757. .implicit_param_refs_id = import_base.implicit_param_refs_id.is_valid()
  758. ? SemIR::InstBlockId::Empty
  759. : SemIR::InstBlockId::Invalid,
  760. .param_refs_id = import_base.param_refs_id.is_valid()
  761. ? SemIR::InstBlockId::Empty
  762. : SemIR::InstBlockId::Invalid,
  763. .decl_id = decl_id,
  764. };
  765. }
  766. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  767. // lookup.
  768. auto AddNameScopeImportRefs(const SemIR::NameScope& import_scope,
  769. SemIR::NameScope& new_scope) -> void {
  770. for (auto entry : import_scope.names) {
  771. auto ref_id = AddImportRef(
  772. context_, {.ir_id = import_ir_id_, .inst_id = entry.inst_id},
  773. SemIR::EntityNameId::Invalid);
  774. new_scope.AddRequired({.name_id = GetLocalNameId(entry.name_id),
  775. .inst_id = ref_id,
  776. .access_kind = entry.access_kind});
  777. }
  778. }
  779. // Given a block ID for a list of associated entities of a witness, returns a
  780. // version localized to the current IR.
  781. auto AddAssociatedEntities(SemIR::InstBlockId associated_entities_id)
  782. -> SemIR::InstBlockId {
  783. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  784. return SemIR::InstBlockId::Empty;
  785. }
  786. auto associated_entities =
  787. import_ir_.inst_blocks().Get(associated_entities_id);
  788. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  789. new_associated_entities.reserve(associated_entities.size());
  790. for (auto inst_id : associated_entities) {
  791. new_associated_entities.push_back(
  792. AddImportRef(context_, {.ir_id = import_ir_id_, .inst_id = inst_id},
  793. SemIR::EntityNameId::Invalid));
  794. }
  795. return context_.inst_blocks().Add(new_associated_entities);
  796. }
  797. // Tries to resolve the InstId, returning a constant when ready, or Invalid if
  798. // more has been added to the stack. A similar API is followed for all
  799. // following TryResolveTypedInst helper functions.
  800. //
  801. // `const_id` is Invalid unless we've tried to resolve this instruction
  802. // before, in which case it's the previous result.
  803. //
  804. // TODO: Error is returned when support is missing, but that should go away.
  805. auto TryResolveInst(SemIR::InstId inst_id, SemIR::ConstantId const_id)
  806. -> ResolveResult {
  807. auto inst_const_id = import_ir_.constant_values().Get(inst_id);
  808. if (!inst_const_id.is_valid() || !inst_const_id.is_symbolic() ||
  809. const_id.is_valid()) {
  810. return TryResolveInstCanonical(inst_id, const_id);
  811. }
  812. // Try to import the generic, and retry if it's not ready yet. Note that if
  813. // this retries, we can require three passes to import an instruction.
  814. const auto& symbolic_const =
  815. import_ir_.constant_values().GetSymbolicConstant(inst_const_id);
  816. auto initial_work = work_stack_.size();
  817. auto generic_const_id = GetLocalConstantId(symbolic_const.generic_id);
  818. if (HasNewWork(initial_work)) {
  819. return ResolveResult::Retry();
  820. }
  821. // Import the constant and rebuild the symbolic constant data.
  822. auto result = TryResolveInstCanonical(inst_id, const_id);
  823. if (result.const_id.is_valid()) {
  824. result.const_id = context_.constant_values().AddSymbolicConstant(
  825. {.inst_id = context_.constant_values().GetInstId(result.const_id),
  826. .generic_id = GetLocalGenericId(generic_const_id),
  827. .index = symbolic_const.index});
  828. }
  829. return result;
  830. }
  831. // Tries to resolve the InstId, returning a canonical constant when ready, or
  832. // Invalid if more has been added to the stack. This is the same as
  833. // TryResolveInst, except that it may resolve symbolic constants as canonical
  834. // constants instead of as constants associated with a particular generic.
  835. auto TryResolveInstCanonical(SemIR::InstId inst_id,
  836. SemIR::ConstantId const_id) -> ResolveResult {
  837. if (inst_id.is_builtin()) {
  838. CARBON_CHECK(!const_id.is_valid());
  839. // Constants for builtins can be directly copied.
  840. return {.const_id = context_.constant_values().Get(inst_id)};
  841. }
  842. auto untyped_inst = import_ir_.insts().Get(inst_id);
  843. CARBON_KIND_SWITCH(untyped_inst) {
  844. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  845. return TryResolveTypedInst(inst);
  846. }
  847. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  848. return TryResolveTypedInst(inst);
  849. }
  850. case CARBON_KIND(SemIR::BaseDecl inst): {
  851. return TryResolveTypedInst(inst, inst_id);
  852. }
  853. case CARBON_KIND(SemIR::BindAlias inst): {
  854. return TryResolveTypedInst(inst);
  855. }
  856. case CARBON_KIND(SemIR::BindName inst): {
  857. // TODO: This always returns `ConstantId::NotConstant`.
  858. return {.const_id = TryEvalInst(context_, inst_id, inst)};
  859. }
  860. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  861. return TryResolveTypedInst(inst);
  862. }
  863. case CARBON_KIND(SemIR::ClassDecl inst): {
  864. return TryResolveTypedInst(inst, const_id);
  865. }
  866. case CARBON_KIND(SemIR::ClassType inst): {
  867. return TryResolveTypedInst(inst);
  868. }
  869. case CARBON_KIND(SemIR::ConstType inst): {
  870. return TryResolveTypedInst(inst);
  871. }
  872. case CARBON_KIND(SemIR::ExportDecl inst): {
  873. return TryResolveTypedInst(inst);
  874. }
  875. case CARBON_KIND(SemIR::FieldDecl inst): {
  876. return TryResolveTypedInst(inst, inst_id);
  877. }
  878. case CARBON_KIND(SemIR::FunctionDecl inst): {
  879. return TryResolveTypedInst(inst, const_id);
  880. }
  881. case CARBON_KIND(SemIR::FunctionType inst): {
  882. return TryResolveTypedInst(inst);
  883. }
  884. case CARBON_KIND(SemIR::GenericClassType inst): {
  885. return TryResolveTypedInst(inst);
  886. }
  887. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  888. return TryResolveTypedInst(inst);
  889. }
  890. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  891. return TryResolveTypedInst(inst, inst_id);
  892. }
  893. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  894. return TryResolveTypedInst(inst, const_id);
  895. }
  896. case CARBON_KIND(SemIR::InterfaceWitness inst): {
  897. return TryResolveTypedInst(inst);
  898. }
  899. case CARBON_KIND(SemIR::InterfaceType inst): {
  900. return TryResolveTypedInst(inst);
  901. }
  902. case CARBON_KIND(SemIR::IntLiteral inst): {
  903. return TryResolveTypedInst(inst);
  904. }
  905. case CARBON_KIND(SemIR::Namespace inst): {
  906. CARBON_FATAL() << "Namespaces shouldn't need resolution this way: "
  907. << inst;
  908. }
  909. case CARBON_KIND(SemIR::PointerType inst): {
  910. return TryResolveTypedInst(inst);
  911. }
  912. case CARBON_KIND(SemIR::StructType inst): {
  913. return TryResolveTypedInst(inst, inst_id);
  914. }
  915. case CARBON_KIND(SemIR::StructValue inst): {
  916. return TryResolveTypedInst(inst);
  917. }
  918. case CARBON_KIND(SemIR::TupleType inst): {
  919. return TryResolveTypedInst(inst);
  920. }
  921. case CARBON_KIND(SemIR::TupleValue inst): {
  922. return TryResolveTypedInst(inst);
  923. }
  924. case CARBON_KIND(SemIR::UnboundElementType inst): {
  925. return TryResolveTypedInst(inst);
  926. }
  927. default:
  928. context_.TODO(
  929. SemIR::LocId(AddImportIRInst(inst_id)),
  930. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  931. return {.const_id = SemIR::ConstantId::Error};
  932. }
  933. }
  934. // Produce a resolve result for the given instruction that describes a
  935. // constant value. This should only be used for instructions that describe
  936. // constants, and not for instructions that represent declarations. For a
  937. // declaration, we need an associated location, so AddInstInNoBlock should be
  938. // used instead.
  939. auto ResolveAsUntyped(SemIR::Inst inst) -> ResolveResult {
  940. auto result = TryEvalInst(context_, SemIR::InstId::Invalid, inst);
  941. CARBON_CHECK(result.is_constant()) << inst << " is not constant";
  942. return {.const_id = result};
  943. }
  944. // Same as ResolveAsUntyped, but with an explicit type for convenience.
  945. template <typename InstT>
  946. auto ResolveAs(InstT inst) -> ResolveResult {
  947. return ResolveAsUntyped(inst);
  948. }
  949. auto TryResolveTypedInst(SemIR::AssociatedEntity inst) -> ResolveResult {
  950. auto initial_work = work_stack_.size();
  951. auto type_const_id = GetLocalConstantId(inst.type_id);
  952. if (HasNewWork(initial_work)) {
  953. return ResolveResult::Retry();
  954. }
  955. // Add a lazy reference to the target declaration.
  956. auto decl_id = AddImportRef(
  957. context_, {.ir_id = import_ir_id_, .inst_id = inst.decl_id},
  958. SemIR::EntityNameId::Invalid);
  959. return ResolveAs<SemIR::AssociatedEntity>(
  960. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  961. .index = inst.index,
  962. .decl_id = decl_id});
  963. }
  964. auto TryResolveTypedInst(SemIR::AssociatedEntityType inst) -> ResolveResult {
  965. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  966. auto initial_work = work_stack_.size();
  967. auto entity_type_const_id = GetLocalConstantId(inst.entity_type_id);
  968. auto interface_inst_id = GetLocalConstantId(inst.interface_type_id);
  969. if (HasNewWork(initial_work)) {
  970. return ResolveResult::Retry();
  971. }
  972. return ResolveAs<SemIR::AssociatedEntityType>(
  973. {.type_id = SemIR::TypeId::TypeType,
  974. .interface_type_id =
  975. context_.GetTypeIdForTypeConstant(interface_inst_id),
  976. .entity_type_id =
  977. context_.GetTypeIdForTypeConstant(entity_type_const_id)});
  978. }
  979. auto TryResolveTypedInst(SemIR::BaseDecl inst, SemIR::InstId import_inst_id)
  980. -> ResolveResult {
  981. auto initial_work = work_stack_.size();
  982. auto type_const_id = GetLocalConstantId(inst.type_id);
  983. auto base_type_const_id = GetLocalConstantId(inst.base_type_id);
  984. if (HasNewWork(initial_work)) {
  985. return ResolveResult::Retry();
  986. }
  987. // Import the instruction in order to update contained base_type_id and
  988. // track the import location.
  989. auto inst_id = context_.AddInstInNoBlock<SemIR::BaseDecl>(
  990. AddImportIRInst(import_inst_id),
  991. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  992. .base_type_id = context_.GetTypeIdForTypeConstant(base_type_const_id),
  993. .index = inst.index});
  994. return {.const_id = context_.constant_values().Get(inst_id)};
  995. }
  996. auto TryResolveTypedInst(SemIR::BindAlias inst) -> ResolveResult {
  997. auto initial_work = work_stack_.size();
  998. auto value_id = GetLocalConstantId(inst.value_id);
  999. if (HasNewWork(initial_work)) {
  1000. return ResolveResult::Retry();
  1001. }
  1002. return {.const_id = value_id};
  1003. }
  1004. auto TryResolveTypedInst(SemIR::BindSymbolicName inst) -> ResolveResult {
  1005. auto initial_work = work_stack_.size();
  1006. auto type_id = GetLocalConstantId(inst.type_id);
  1007. if (HasNewWork(initial_work)) {
  1008. return ResolveResult::Retry();
  1009. }
  1010. const auto& import_entity_name =
  1011. import_ir_.entity_names().Get(inst.entity_name_id);
  1012. auto name_id = GetLocalNameId(import_entity_name.name_id);
  1013. auto entity_name_id = context_.entity_names().Add(
  1014. {.name_id = name_id,
  1015. .parent_scope_id = SemIR::NameScopeId::Invalid,
  1016. .bind_index = import_entity_name.bind_index});
  1017. return ResolveAs<SemIR::BindSymbolicName>(
  1018. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1019. .entity_name_id = entity_name_id,
  1020. .value_id = SemIR::InstId::Invalid});
  1021. }
  1022. // Makes an incomplete class. This is necessary even with classes with a
  1023. // complete declaration, because things such as `Self` may refer back to the
  1024. // type.
  1025. auto MakeIncompleteClass(const SemIR::Class& import_class)
  1026. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  1027. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeId::TypeType,
  1028. .class_id = SemIR::ClassId::Invalid,
  1029. .decl_block_id = SemIR::InstBlockId::Empty};
  1030. auto class_decl_id = context_.AddPlaceholderInstInNoBlock(
  1031. SemIR::LocIdAndInst(AddImportIRInst(import_class.decl_id), class_decl));
  1032. // Regardless of whether ClassDecl is a complete type, we first need an
  1033. // incomplete type so that any references have something to point at.
  1034. class_decl.class_id = context_.classes().Add(
  1035. {GetIncompleteLocalEntityBase(class_decl_id, import_class),
  1036. {.self_type_id = SemIR::TypeId::Invalid,
  1037. .inheritance_kind = import_class.inheritance_kind}});
  1038. if (import_class.is_generic()) {
  1039. class_decl.type_id = context_.GetGenericClassType(class_decl.class_id);
  1040. }
  1041. // Write the class ID into the ClassDecl.
  1042. context_.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  1043. auto self_const_id = context_.constant_values().Get(class_decl_id);
  1044. return {class_decl.class_id, self_const_id};
  1045. }
  1046. // Fills out the class definition for an incomplete class.
  1047. auto AddClassDefinition(const SemIR::Class& import_class,
  1048. SemIR::Class& new_class,
  1049. SemIR::ConstantId object_repr_const_id,
  1050. SemIR::InstId base_id) -> void {
  1051. new_class.definition_id = new_class.decl_id;
  1052. new_class.object_repr_id =
  1053. context_.GetTypeIdForTypeConstant(object_repr_const_id);
  1054. new_class.scope_id = context_.name_scopes().Add(
  1055. new_class.decl_id, SemIR::NameId::Invalid, new_class.parent_scope_id);
  1056. auto& new_scope = context_.name_scopes().Get(new_class.scope_id);
  1057. const auto& import_scope =
  1058. import_ir_.name_scopes().Get(import_class.scope_id);
  1059. // Push a block so that we can add scoped instructions to it.
  1060. context_.inst_block_stack().Push();
  1061. AddNameScopeImportRefs(import_scope, new_scope);
  1062. new_class.body_block_id = context_.inst_block_stack().Pop();
  1063. if (import_class.base_id.is_valid()) {
  1064. new_class.base_id = base_id;
  1065. // Add the base scope to extended scopes.
  1066. auto base_inst_id = context_.types().GetInstId(
  1067. context_.insts()
  1068. .GetAs<SemIR::BaseDecl>(new_class.base_id)
  1069. .base_type_id);
  1070. const auto& base_class = context_.classes().Get(
  1071. context_.insts().GetAs<SemIR::ClassType>(base_inst_id).class_id);
  1072. new_scope.extended_scopes.push_back(base_class.scope_id);
  1073. }
  1074. CARBON_CHECK(new_scope.extended_scopes.size() ==
  1075. import_scope.extended_scopes.size());
  1076. }
  1077. auto TryResolveTypedInst(SemIR::ClassDecl inst,
  1078. SemIR::ConstantId class_const_id) -> ResolveResult {
  1079. // TODO: The handling of interfaces repeats a lot with the handling of
  1080. // classes, and will likely also be repeated for named constraints and
  1081. // choice types. Factor out some of this functionality.
  1082. const auto& import_class = import_ir_.classes().Get(inst.class_id);
  1083. SemIR::ClassId class_id = SemIR::ClassId::Invalid;
  1084. if (!class_const_id.is_valid()) {
  1085. // On the first pass, create a forward declaration of the class for any
  1086. // recursive references.
  1087. std::tie(class_id, class_const_id) = MakeIncompleteClass(import_class);
  1088. } else {
  1089. // On the second pass, compute the class ID from the constant value of the
  1090. // declaration.
  1091. auto class_const_inst = context_.insts().Get(
  1092. context_.constant_values().GetInstId(class_const_id));
  1093. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  1094. class_id = class_type->class_id;
  1095. } else {
  1096. auto generic_class_type =
  1097. context_.types().GetAs<SemIR::GenericClassType>(
  1098. class_const_inst.type_id());
  1099. class_id = generic_class_type.class_id;
  1100. }
  1101. }
  1102. // Load constants for the definition.
  1103. auto initial_work = work_stack_.size();
  1104. auto parent_scope_id = GetLocalNameScopeId(import_class.parent_scope_id);
  1105. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  1106. GetLocalParamConstantIds(import_class.implicit_param_refs_id);
  1107. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  1108. GetLocalParamConstantIds(import_class.param_refs_id);
  1109. auto generic_data = GetLocalGenericData(import_class.generic_id);
  1110. auto self_const_id = GetLocalConstantId(import_class.self_type_id);
  1111. auto object_repr_const_id =
  1112. import_class.object_repr_id.is_valid()
  1113. ? GetLocalConstantId(import_class.object_repr_id)
  1114. : SemIR::ConstantId::Invalid;
  1115. auto base_id = import_class.base_id.is_valid()
  1116. ? GetLocalConstantInstId(import_class.base_id)
  1117. : SemIR::InstId::Invalid;
  1118. if (HasNewWork(initial_work)) {
  1119. return ResolveResult::Retry(class_const_id);
  1120. }
  1121. auto& new_class = context_.classes().Get(class_id);
  1122. new_class.parent_scope_id = parent_scope_id;
  1123. new_class.implicit_param_refs_id = GetLocalParamRefsId(
  1124. import_class.implicit_param_refs_id, implicit_param_const_ids);
  1125. new_class.param_refs_id =
  1126. GetLocalParamRefsId(import_class.param_refs_id, param_const_ids);
  1127. SetGenericData(import_class.generic_id, new_class.generic_id, generic_data);
  1128. new_class.self_type_id = context_.GetTypeIdForTypeConstant(self_const_id);
  1129. if (import_class.is_defined()) {
  1130. AddClassDefinition(import_class, new_class, object_repr_const_id,
  1131. base_id);
  1132. }
  1133. return {.const_id = class_const_id};
  1134. }
  1135. auto TryResolveTypedInst(SemIR::ClassType inst) -> ResolveResult {
  1136. auto initial_work = work_stack_.size();
  1137. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1138. auto class_const_id =
  1139. GetLocalConstantId(import_ir_.classes().Get(inst.class_id).decl_id);
  1140. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1141. if (HasNewWork(initial_work)) {
  1142. return ResolveResult::Retry();
  1143. }
  1144. // Find the corresponding class type. For a non-generic class, this is the
  1145. // type of the class declaration. For a generic class, build a class type
  1146. // referencing this specialization of the generic class.
  1147. auto class_const_inst = context_.insts().Get(
  1148. context_.constant_values().GetInstId(class_const_id));
  1149. if (class_const_inst.Is<SemIR::ClassType>()) {
  1150. return {.const_id = class_const_id};
  1151. } else {
  1152. auto generic_class_type = context_.types().GetAs<SemIR::GenericClassType>(
  1153. class_const_inst.type_id());
  1154. auto specific_id = GetOrAddLocalSpecific(inst.specific_id, specific_data);
  1155. return ResolveAs<SemIR::ClassType>(
  1156. {.type_id = SemIR::TypeId::TypeType,
  1157. .class_id = generic_class_type.class_id,
  1158. .specific_id = specific_id});
  1159. }
  1160. }
  1161. auto TryResolveTypedInst(SemIR::ConstType inst) -> ResolveResult {
  1162. auto initial_work = work_stack_.size();
  1163. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1164. auto inner_const_id = GetLocalConstantId(inst.inner_id);
  1165. if (HasNewWork(initial_work)) {
  1166. return ResolveResult::Retry();
  1167. }
  1168. auto inner_type_id = context_.GetTypeIdForTypeConstant(inner_const_id);
  1169. return ResolveAs<SemIR::ConstType>(
  1170. {.type_id = SemIR::TypeId::TypeType, .inner_id = inner_type_id});
  1171. }
  1172. auto TryResolveTypedInst(SemIR::ExportDecl inst) -> ResolveResult {
  1173. auto initial_work = work_stack_.size();
  1174. auto value_id = GetLocalConstantId(inst.value_id);
  1175. if (HasNewWork(initial_work)) {
  1176. return ResolveResult::Retry();
  1177. }
  1178. return {.const_id = value_id};
  1179. }
  1180. auto TryResolveTypedInst(SemIR::FieldDecl inst, SemIR::InstId import_inst_id)
  1181. -> ResolveResult {
  1182. auto initial_work = work_stack_.size();
  1183. auto const_id = GetLocalConstantId(inst.type_id);
  1184. if (HasNewWork(initial_work)) {
  1185. return ResolveResult::Retry();
  1186. }
  1187. auto inst_id = context_.AddInstInNoBlock<SemIR::FieldDecl>(
  1188. AddImportIRInst(import_inst_id),
  1189. {.type_id = context_.GetTypeIdForTypeConstant(const_id),
  1190. .name_id = GetLocalNameId(inst.name_id),
  1191. .index = inst.index});
  1192. return {.const_id = context_.constant_values().Get(inst_id)};
  1193. }
  1194. // Make a declaration of a function. This is done as a separate step from
  1195. // importing the function declaration in order to resolve cycles.
  1196. auto MakeFunctionDecl(const SemIR::Function& import_function)
  1197. -> std::pair<SemIR::FunctionId, SemIR::ConstantId> {
  1198. SemIR::FunctionDecl function_decl = {
  1199. .type_id = SemIR::TypeId::Invalid,
  1200. .function_id = SemIR::FunctionId::Invalid,
  1201. .decl_block_id = SemIR::InstBlockId::Empty};
  1202. auto function_decl_id =
  1203. context_.AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst(
  1204. AddImportIRInst(import_function.latest_decl_id()), function_decl));
  1205. // Start with an incomplete function.
  1206. function_decl.function_id = context_.functions().Add(
  1207. {GetIncompleteLocalEntityBase(function_decl_id, import_function),
  1208. {.return_storage_id = SemIR::InstId::Invalid,
  1209. .is_extern = import_function.is_extern,
  1210. .builtin_function_kind = import_function.builtin_function_kind}});
  1211. // TODO: Import this or recompute it.
  1212. auto specific_id = SemIR::SpecificId::Invalid;
  1213. function_decl.type_id =
  1214. context_.GetFunctionType(function_decl.function_id, specific_id);
  1215. // Write the function ID and type into the FunctionDecl.
  1216. context_.ReplaceInstBeforeConstantUse(function_decl_id, function_decl);
  1217. return {function_decl.function_id,
  1218. context_.constant_values().Get(function_decl_id)};
  1219. }
  1220. auto TryResolveTypedInst(SemIR::FunctionDecl inst,
  1221. SemIR::ConstantId function_const_id)
  1222. -> ResolveResult {
  1223. const auto& import_function = import_ir_.functions().Get(inst.function_id);
  1224. SemIR::FunctionId function_id = SemIR::FunctionId::Invalid;
  1225. if (!function_const_id.is_valid()) {
  1226. // On the first pass, create a forward declaration of the interface.
  1227. std::tie(function_id, function_const_id) =
  1228. MakeFunctionDecl(import_function);
  1229. } else {
  1230. // On the second pass, compute the function ID from the constant value of
  1231. // the declaration.
  1232. auto function_const_inst = context_.insts().Get(
  1233. context_.constant_values().GetInstId(function_const_id));
  1234. auto function_type = context_.types().GetAs<SemIR::FunctionType>(
  1235. function_const_inst.type_id());
  1236. function_id = function_type.function_id;
  1237. }
  1238. auto initial_work = work_stack_.size();
  1239. auto return_type_const_id = SemIR::ConstantId::Invalid;
  1240. if (import_function.return_storage_id.is_valid()) {
  1241. return_type_const_id =
  1242. GetLocalConstantId(import_function.GetDeclaredReturnType(import_ir_));
  1243. }
  1244. auto parent_scope_id = GetLocalNameScopeId(import_function.parent_scope_id);
  1245. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  1246. GetLocalParamConstantIds(import_function.implicit_param_refs_id);
  1247. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  1248. GetLocalParamConstantIds(import_function.param_refs_id);
  1249. auto generic_data = GetLocalGenericData(import_function.generic_id);
  1250. if (HasNewWork(initial_work)) {
  1251. return ResolveResult::Retry(function_const_id);
  1252. }
  1253. // Add the function declaration.
  1254. auto& new_function = context_.functions().Get(function_id);
  1255. new_function.parent_scope_id = parent_scope_id;
  1256. new_function.implicit_param_refs_id = GetLocalParamRefsId(
  1257. import_function.implicit_param_refs_id, implicit_param_const_ids);
  1258. new_function.param_refs_id =
  1259. GetLocalParamRefsId(import_function.param_refs_id, param_const_ids);
  1260. SetGenericData(import_function.generic_id, new_function.generic_id,
  1261. generic_data);
  1262. if (import_function.return_storage_id.is_valid()) {
  1263. // Recreate the return slot from scratch.
  1264. // TODO: Once we import function definitions, we'll need to make sure we
  1265. // use the same return storage variable in the declaration and definition.
  1266. new_function.return_storage_id =
  1267. context_.AddInstInNoBlock<SemIR::VarStorage>(
  1268. AddImportIRInst(import_function.return_storage_id),
  1269. {.type_id =
  1270. context_.GetTypeIdForTypeConstant(return_type_const_id),
  1271. .name_id = SemIR::NameId::ReturnSlot});
  1272. }
  1273. if (import_function.definition_id.is_valid()) {
  1274. new_function.definition_id = new_function.decl_id;
  1275. }
  1276. return {.const_id = function_const_id};
  1277. }
  1278. auto TryResolveTypedInst(SemIR::FunctionType inst) -> ResolveResult {
  1279. auto initial_work = work_stack_.size();
  1280. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1281. auto fn_val_id = GetLocalConstantInstId(
  1282. import_ir_.functions().Get(inst.function_id).decl_id);
  1283. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1284. if (HasNewWork(initial_work)) {
  1285. return ResolveResult::Retry();
  1286. }
  1287. auto fn_type_id = context_.insts().Get(fn_val_id).type_id();
  1288. return ResolveAs<SemIR::FunctionType>(
  1289. {.type_id = SemIR::TypeId::TypeType,
  1290. .function_id = context_.types()
  1291. .GetAs<SemIR::FunctionType>(fn_type_id)
  1292. .function_id,
  1293. .specific_id =
  1294. GetOrAddLocalSpecific(inst.specific_id, specific_data)});
  1295. }
  1296. auto TryResolveTypedInst(SemIR::GenericClassType inst) -> ResolveResult {
  1297. auto initial_work = work_stack_.size();
  1298. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1299. auto class_val_id =
  1300. GetLocalConstantInstId(import_ir_.classes().Get(inst.class_id).decl_id);
  1301. if (HasNewWork(initial_work)) {
  1302. return ResolveResult::Retry();
  1303. }
  1304. auto class_val = context_.insts().Get(class_val_id);
  1305. CARBON_CHECK(
  1306. context_.types().Is<SemIR::GenericClassType>(class_val.type_id()));
  1307. return {.const_id = context_.types().GetConstantId(class_val.type_id())};
  1308. }
  1309. auto TryResolveTypedInst(SemIR::GenericInterfaceType inst) -> ResolveResult {
  1310. auto initial_work = work_stack_.size();
  1311. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1312. auto interface_val_id = GetLocalConstantInstId(
  1313. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  1314. if (HasNewWork(initial_work)) {
  1315. return ResolveResult::Retry();
  1316. }
  1317. auto interface_val = context_.insts().Get(interface_val_id);
  1318. CARBON_CHECK(context_.types().Is<SemIR::GenericInterfaceType>(
  1319. interface_val.type_id()));
  1320. return {.const_id =
  1321. context_.types().GetConstantId(interface_val.type_id())};
  1322. }
  1323. auto TryResolveTypedInst(SemIR::ImportRefLoaded /*inst*/,
  1324. SemIR::InstId inst_id) -> ResolveResult {
  1325. auto initial_work = work_stack_.size();
  1326. // Return the constant for the instruction of the imported constant.
  1327. auto constant_id = import_ir_.constant_values().Get(inst_id);
  1328. if (!constant_id.is_valid()) {
  1329. return {.const_id = SemIR::ConstantId::Error};
  1330. }
  1331. if (!constant_id.is_constant()) {
  1332. context_.TODO(inst_id,
  1333. "Non-constant ImportRefLoaded (comes up with var)");
  1334. return {.const_id = SemIR::ConstantId::Error};
  1335. }
  1336. auto new_constant_id =
  1337. GetLocalConstantId(import_ir_.constant_values().GetInstId(constant_id));
  1338. if (HasNewWork(initial_work)) {
  1339. return ResolveResult::Retry();
  1340. }
  1341. return {.const_id = new_constant_id};
  1342. }
  1343. // Make a declaration of an interface. This is done as a separate step from
  1344. // importing the interface definition in order to resolve cycles.
  1345. auto MakeInterfaceDecl(const SemIR::Interface& import_interface)
  1346. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  1347. SemIR::InterfaceDecl interface_decl = {
  1348. .type_id = SemIR::TypeId::TypeType,
  1349. .interface_id = SemIR::InterfaceId::Invalid,
  1350. .decl_block_id = SemIR::InstBlockId::Empty};
  1351. auto interface_decl_id =
  1352. context_.AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst(
  1353. AddImportIRInst(import_interface.decl_id), interface_decl));
  1354. // Start with an incomplete interface.
  1355. interface_decl.interface_id = context_.interfaces().Add(
  1356. {GetIncompleteLocalEntityBase(interface_decl_id, import_interface),
  1357. {}});
  1358. if (import_interface.is_generic()) {
  1359. interface_decl.type_id =
  1360. context_.GetGenericInterfaceType(interface_decl.interface_id);
  1361. }
  1362. // Write the interface ID into the InterfaceDecl.
  1363. context_.ReplaceInstBeforeConstantUse(interface_decl_id, interface_decl);
  1364. return {interface_decl.interface_id,
  1365. context_.constant_values().Get(interface_decl_id)};
  1366. }
  1367. // Imports the definition for an interface that has been imported as a forward
  1368. // declaration.
  1369. auto AddInterfaceDefinition(const SemIR::Interface& import_interface,
  1370. SemIR::Interface& new_interface,
  1371. SemIR::InstId self_param_id) -> void {
  1372. new_interface.scope_id = context_.name_scopes().Add(
  1373. new_interface.decl_id, SemIR::NameId::Invalid,
  1374. new_interface.parent_scope_id);
  1375. auto& new_scope = context_.name_scopes().Get(new_interface.scope_id);
  1376. const auto& import_scope =
  1377. import_ir_.name_scopes().Get(import_interface.scope_id);
  1378. // Push a block so that we can add scoped instructions to it.
  1379. context_.inst_block_stack().Push();
  1380. AddNameScopeImportRefs(import_scope, new_scope);
  1381. new_interface.associated_entities_id =
  1382. AddAssociatedEntities(import_interface.associated_entities_id);
  1383. new_interface.body_block_id = context_.inst_block_stack().Pop();
  1384. new_interface.self_param_id = self_param_id;
  1385. CARBON_CHECK(import_scope.extended_scopes.empty())
  1386. << "Interfaces don't currently have extended scopes to support.";
  1387. }
  1388. auto TryResolveTypedInst(SemIR::InterfaceDecl inst,
  1389. SemIR::ConstantId interface_const_id)
  1390. -> ResolveResult {
  1391. const auto& import_interface =
  1392. import_ir_.interfaces().Get(inst.interface_id);
  1393. SemIR::InterfaceId interface_id = SemIR::InterfaceId::Invalid;
  1394. if (!interface_const_id.is_valid()) {
  1395. // On the first pass, create a forward declaration of the interface.
  1396. std::tie(interface_id, interface_const_id) =
  1397. MakeInterfaceDecl(import_interface);
  1398. } else {
  1399. // On the second pass, compute the interface ID from the constant value of
  1400. // the declaration.
  1401. auto interface_const_inst = context_.insts().Get(
  1402. context_.constant_values().GetInstId(interface_const_id));
  1403. if (auto interface_type =
  1404. interface_const_inst.TryAs<SemIR::InterfaceType>()) {
  1405. interface_id = interface_type->interface_id;
  1406. } else {
  1407. auto generic_interface_type =
  1408. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1409. interface_const_inst.type_id());
  1410. interface_id = generic_interface_type.interface_id;
  1411. }
  1412. }
  1413. auto initial_work = work_stack_.size();
  1414. auto parent_scope_id =
  1415. GetLocalNameScopeId(import_interface.parent_scope_id);
  1416. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  1417. GetLocalParamConstantIds(import_interface.implicit_param_refs_id);
  1418. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  1419. GetLocalParamConstantIds(import_interface.param_refs_id);
  1420. auto generic_data = GetLocalGenericData(import_interface.generic_id);
  1421. std::optional<SemIR::InstId> self_param_id;
  1422. if (import_interface.is_defined()) {
  1423. self_param_id = GetLocalConstantInstId(import_interface.self_param_id);
  1424. }
  1425. if (HasNewWork(initial_work)) {
  1426. return ResolveResult::Retry(interface_const_id);
  1427. }
  1428. auto& new_interface = context_.interfaces().Get(interface_id);
  1429. new_interface.parent_scope_id = parent_scope_id;
  1430. new_interface.implicit_param_refs_id = GetLocalParamRefsId(
  1431. import_interface.implicit_param_refs_id, implicit_param_const_ids);
  1432. new_interface.param_refs_id =
  1433. GetLocalParamRefsId(import_interface.param_refs_id, param_const_ids);
  1434. SetGenericData(import_interface.generic_id, new_interface.generic_id,
  1435. generic_data);
  1436. if (import_interface.is_defined()) {
  1437. CARBON_CHECK(self_param_id);
  1438. AddInterfaceDefinition(import_interface, new_interface, *self_param_id);
  1439. }
  1440. return {.const_id = interface_const_id};
  1441. }
  1442. auto TryResolveTypedInst(SemIR::InterfaceType inst) -> ResolveResult {
  1443. auto initial_work = work_stack_.size();
  1444. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1445. auto interface_const_id = GetLocalConstantId(
  1446. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  1447. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1448. if (HasNewWork(initial_work)) {
  1449. return ResolveResult::Retry();
  1450. }
  1451. // Find the corresponding interface type. For a non-generic interface, this
  1452. // is the type of the interface declaration. For a generic interface, build
  1453. // a interface type referencing this specialization of the generic
  1454. // interface.
  1455. auto interface_const_inst = context_.insts().Get(
  1456. context_.constant_values().GetInstId(interface_const_id));
  1457. if (interface_const_inst.Is<SemIR::InterfaceType>()) {
  1458. return {.const_id = interface_const_id};
  1459. } else {
  1460. auto generic_interface_type =
  1461. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1462. interface_const_inst.type_id());
  1463. auto specific_id = GetOrAddLocalSpecific(inst.specific_id, specific_data);
  1464. return ResolveAs<SemIR::InterfaceType>(
  1465. {.type_id = SemIR::TypeId::TypeType,
  1466. .interface_id = generic_interface_type.interface_id,
  1467. .specific_id = specific_id});
  1468. }
  1469. }
  1470. auto TryResolveTypedInst(SemIR::InterfaceWitness inst) -> ResolveResult {
  1471. auto initial_work = work_stack_.size();
  1472. auto elements = GetLocalInstBlockContents(inst.elements_id);
  1473. if (HasNewWork(initial_work)) {
  1474. return ResolveResult::Retry();
  1475. }
  1476. auto elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elements);
  1477. return ResolveAs<SemIR::InterfaceWitness>(
  1478. {.type_id =
  1479. context_.GetBuiltinType(SemIR::BuiltinInstKind::WitnessType),
  1480. .elements_id = elements_id});
  1481. }
  1482. auto TryResolveTypedInst(SemIR::IntLiteral inst) -> ResolveResult {
  1483. auto initial_work = work_stack_.size();
  1484. auto type_id = GetLocalConstantId(inst.type_id);
  1485. if (HasNewWork(initial_work)) {
  1486. return ResolveResult::Retry();
  1487. }
  1488. return ResolveAs<SemIR::IntLiteral>(
  1489. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1490. .int_id = context_.ints().Add(import_ir_.ints().Get(inst.int_id))});
  1491. }
  1492. auto TryResolveTypedInst(SemIR::PointerType inst) -> ResolveResult {
  1493. auto initial_work = work_stack_.size();
  1494. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1495. auto pointee_const_id = GetLocalConstantId(inst.pointee_id);
  1496. if (HasNewWork(initial_work)) {
  1497. return ResolveResult::Retry();
  1498. }
  1499. auto pointee_type_id = context_.GetTypeIdForTypeConstant(pointee_const_id);
  1500. return ResolveAs<SemIR::PointerType>(
  1501. {.type_id = SemIR::TypeId::TypeType, .pointee_id = pointee_type_id});
  1502. }
  1503. auto TryResolveTypedInst(SemIR::StructType inst, SemIR::InstId import_inst_id)
  1504. -> ResolveResult {
  1505. // Collect all constants first, locating unresolved ones in a single pass.
  1506. auto initial_work = work_stack_.size();
  1507. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1508. auto orig_fields = import_ir_.inst_blocks().Get(inst.fields_id);
  1509. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  1510. field_const_ids.reserve(orig_fields.size());
  1511. for (auto field_id : orig_fields) {
  1512. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1513. field_const_ids.push_back(GetLocalConstantId(field.field_type_id));
  1514. }
  1515. if (HasNewWork(initial_work)) {
  1516. return ResolveResult::Retry();
  1517. }
  1518. // Prepare a vector of fields for GetStructType.
  1519. // TODO: Should we have field constants so that we can deduplicate fields
  1520. // without creating instructions here?
  1521. llvm::SmallVector<SemIR::InstId> fields;
  1522. fields.reserve(orig_fields.size());
  1523. for (auto [field_id, field_const_id] :
  1524. llvm::zip(orig_fields, field_const_ids)) {
  1525. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1526. auto name_id = GetLocalNameId(field.name_id);
  1527. auto field_type_id = context_.GetTypeIdForTypeConstant(field_const_id);
  1528. fields.push_back(context_.AddInstInNoBlock<SemIR::StructTypeField>(
  1529. AddImportIRInst(import_inst_id),
  1530. {.name_id = name_id, .field_type_id = field_type_id}));
  1531. }
  1532. return ResolveAs<SemIR::StructType>(
  1533. {.type_id = SemIR::TypeId::TypeType,
  1534. .fields_id = context_.inst_blocks().AddCanonical(fields)});
  1535. }
  1536. auto TryResolveTypedInst(SemIR::StructValue inst) -> ResolveResult {
  1537. auto initial_work = work_stack_.size();
  1538. auto type_id = GetLocalConstantId(inst.type_id);
  1539. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1540. if (HasNewWork(initial_work)) {
  1541. return ResolveResult::Retry();
  1542. }
  1543. return ResolveAs<SemIR::StructValue>(
  1544. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1545. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1546. }
  1547. auto TryResolveTypedInst(SemIR::TupleType inst) -> ResolveResult {
  1548. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1549. // Collect all constants first, locating unresolved ones in a single pass.
  1550. auto initial_work = work_stack_.size();
  1551. auto orig_elem_type_ids = import_ir_.type_blocks().Get(inst.elements_id);
  1552. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  1553. elem_const_ids.reserve(orig_elem_type_ids.size());
  1554. for (auto elem_type_id : orig_elem_type_ids) {
  1555. elem_const_ids.push_back(GetLocalConstantId(elem_type_id));
  1556. }
  1557. if (HasNewWork(initial_work)) {
  1558. return ResolveResult::Retry();
  1559. }
  1560. // Prepare a vector of the tuple types for GetTupleType.
  1561. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  1562. elem_type_ids.reserve(orig_elem_type_ids.size());
  1563. for (auto elem_const_id : elem_const_ids) {
  1564. elem_type_ids.push_back(context_.GetTypeIdForTypeConstant(elem_const_id));
  1565. }
  1566. return {.const_id = context_.types().GetConstantId(
  1567. context_.GetTupleType(elem_type_ids))};
  1568. }
  1569. auto TryResolveTypedInst(SemIR::TupleValue inst) -> ResolveResult {
  1570. auto initial_work = work_stack_.size();
  1571. auto type_id = GetLocalConstantId(inst.type_id);
  1572. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1573. if (HasNewWork(initial_work)) {
  1574. return ResolveResult::Retry();
  1575. }
  1576. return ResolveAs<SemIR::TupleValue>(
  1577. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1578. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1579. }
  1580. auto TryResolveTypedInst(SemIR::UnboundElementType inst) -> ResolveResult {
  1581. auto initial_work = work_stack_.size();
  1582. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1583. auto class_const_id = GetLocalConstantId(inst.class_type_id);
  1584. auto elem_const_id = GetLocalConstantId(inst.element_type_id);
  1585. if (HasNewWork(initial_work)) {
  1586. return ResolveResult::Retry();
  1587. }
  1588. return ResolveAs<SemIR::UnboundElementType>(
  1589. {.type_id = SemIR::TypeId::TypeType,
  1590. .class_type_id = context_.GetTypeIdForTypeConstant(class_const_id),
  1591. .element_type_id = context_.GetTypeIdForTypeConstant(elem_const_id)});
  1592. }
  1593. auto import_ir_constant_values() -> SemIR::ConstantValueStore& {
  1594. return context_.import_ir_constant_values()[import_ir_id_.index];
  1595. }
  1596. Context& context_;
  1597. SemIR::ImportIRId import_ir_id_;
  1598. const SemIR::File& import_ir_;
  1599. llvm::SmallVector<Work> work_stack_;
  1600. };
  1601. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  1602. // loaded (including the one pointed at directly by the ImportRef), and the
  1603. // final instruction's type ID.
  1604. //
  1605. // This addresses cases where an ImportRefUnloaded may point at another
  1606. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  1607. // constant-evaluated version of the instruction to work with.
  1608. static auto GetInstForLoad(Context& context,
  1609. SemIR::ImportIRInstId import_ir_inst_id)
  1610. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  1611. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  1612. {}, SemIR::TypeId::Invalid};
  1613. auto& [import_ir_insts, type_id] = result;
  1614. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  1615. // The first ImportIRInst is added directly because the IR doesn't need to be
  1616. // localized.
  1617. import_ir_insts.push_back(import_ir_inst);
  1618. const auto* cursor_ir = context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1619. while (true) {
  1620. auto cursor_inst = cursor_ir->insts().Get(import_ir_inst.inst_id);
  1621. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  1622. if (!import_ref) {
  1623. type_id = cursor_inst.type_id();
  1624. return result;
  1625. }
  1626. import_ir_inst =
  1627. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  1628. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1629. import_ir_insts.push_back(
  1630. {.ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  1631. .is_export = false,
  1632. .sem_ir = cursor_ir}),
  1633. .inst_id = import_ir_inst.inst_id});
  1634. }
  1635. }
  1636. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  1637. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  1638. if (!inst) {
  1639. return;
  1640. }
  1641. auto [indirect_insts, load_type_id] =
  1642. GetInstForLoad(context, inst->import_ir_inst_id);
  1643. // The last indirect instruction is the one to resolve. Pop it here because
  1644. // Resolve will assign the constant.
  1645. auto load_ir_inst = indirect_insts.pop_back_val();
  1646. ImportRefResolver resolver(context, load_ir_inst.ir_id);
  1647. // The resolver calls into Context to create instructions. Don't register
  1648. // those instructions as part of the enclosing generic scope if they're
  1649. // dependent on a generic parameter.
  1650. context.generic_region_stack().Push();
  1651. auto type_id = resolver.ResolveType(load_type_id);
  1652. auto constant_id = resolver.Resolve(load_ir_inst.inst_id);
  1653. context.generic_region_stack().Pop();
  1654. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  1655. // doesn't use ReplaceInstBeforeConstantUse because it would trigger
  1656. // TryEvalInst, which we want to avoid with ImportRefs.
  1657. context.sem_ir().insts().Set(
  1658. inst_id,
  1659. SemIR::ImportRefLoaded{.type_id = type_id,
  1660. .import_ir_inst_id = inst->import_ir_inst_id,
  1661. .entity_name_id = inst->entity_name_id});
  1662. // Store the constant for both the ImportRefLoaded and indirect instructions.
  1663. context.constant_values().Set(inst_id, constant_id);
  1664. for (const auto& import_ir_inst : indirect_insts) {
  1665. context.import_ir_constant_values()[import_ir_inst.ir_id.index].Set(
  1666. import_ir_inst.inst_id, constant_id);
  1667. }
  1668. }
  1669. // Imports the impl `import_impl_id` from the imported IR `import_ir`.
  1670. static auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  1671. const SemIR::File& import_ir,
  1672. SemIR::ImplId import_impl_id) -> void {
  1673. // Resolve the imported impl to a local impl ID.
  1674. ImportRefResolver resolver(context, import_ir_id);
  1675. const auto& import_impl = import_ir.impls().Get(import_impl_id);
  1676. auto self_id = resolver.ResolveType(import_impl.self_id);
  1677. auto constraint_id = resolver.ResolveType(import_impl.constraint_id);
  1678. // Import the definition if the impl is defined.
  1679. // TODO: Do we need to check for multiple definitions?
  1680. auto impl_id = context.impls().LookupOrAdd(self_id, constraint_id);
  1681. if (import_impl.is_defined()) {
  1682. // TODO: Create a scope for the `impl` if necessary.
  1683. // TODO: Consider importing the definition_id.
  1684. auto& impl = context.impls().Get(impl_id);
  1685. impl.witness_id = AddImportRef(
  1686. context, {.ir_id = import_ir_id, .inst_id = import_impl.witness_id},
  1687. SemIR::EntityNameId::Invalid);
  1688. }
  1689. }
  1690. // TODO: This doesn't belong in this file. Consider moving the import resolver
  1691. // and this file elsewhere.
  1692. auto ImportImpls(Context& context) -> void {
  1693. for (auto [import_index, import_ir] :
  1694. llvm::enumerate(context.import_irs().array_ref())) {
  1695. if (!import_ir.sem_ir) {
  1696. continue;
  1697. }
  1698. auto import_ir_id = SemIR::ImportIRId(import_index);
  1699. for (auto impl_index : llvm::seq(import_ir.sem_ir->impls().size())) {
  1700. auto impl_id = SemIR::ImplId(impl_index);
  1701. ImportImpl(context, import_ir_id, *import_ir.sem_ir, impl_id);
  1702. }
  1703. }
  1704. }
  1705. } // namespace Carbon::Check