import_ref.cpp 82 KB

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