import_ref.cpp 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101
  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. context.MakeImportedLocAndInst(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(
  229. !existing.const_id.is_valid() || 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. "{0}", 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: {0}", 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),
  633. {.type_id = type_id,
  634. .name_id = name_id,
  635. .runtime_index = param_inst.runtime_index});
  636. if (bind_inst) {
  637. switch (bind_inst->kind) {
  638. case SemIR::BindName::Kind: {
  639. auto entity_name_id = context_.entity_names().Add(
  640. {.name_id = name_id,
  641. .parent_scope_id = SemIR::NameScopeId::Invalid,
  642. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  643. new_param_id = context_.AddInstInNoBlock<SemIR::BindName>(
  644. AddImportIRInst(bind_id), {.type_id = type_id,
  645. .entity_name_id = entity_name_id,
  646. .value_id = new_param_id});
  647. break;
  648. }
  649. case SemIR::BindSymbolicName::Kind: {
  650. // We already imported a constant value for this symbolic binding.
  651. // We can reuse most of it, but update the value to point to our
  652. // specific parameter, and preserve the constant value.
  653. auto new_bind_inst =
  654. context_.insts().GetAs<SemIR::BindSymbolicName>(
  655. context_.constant_values().GetInstId(
  656. param_data.bind_const_id));
  657. new_bind_inst.value_id = new_param_id;
  658. new_param_id = context_.AddInstInNoBlock(AddImportIRInst(bind_id),
  659. new_bind_inst);
  660. context_.constant_values().Set(new_param_id,
  661. param_data.bind_const_id);
  662. break;
  663. }
  664. default: {
  665. CARBON_FATAL("Unexpected kind: {0}", bind_inst->kind);
  666. }
  667. }
  668. }
  669. if (addr_inst) {
  670. new_param_id = context_.AddInstInNoBlock(
  671. context_.MakeImportedLocAndInst<SemIR::AddrPattern>(
  672. AddImportIRInst(ref_id),
  673. {.type_id = type_id, .inner_id = new_param_id}));
  674. }
  675. new_param_refs.push_back(new_param_id);
  676. }
  677. return context_.inst_blocks().Add(new_param_refs);
  678. }
  679. // Translates a NameId from the import IR to a local NameId.
  680. auto GetLocalNameId(SemIR::NameId import_name_id) -> SemIR::NameId {
  681. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.is_valid()) {
  682. return SemIR::NameId::ForIdentifier(
  683. context_.identifiers().Add(import_ir_.identifiers().Get(ident_id)));
  684. }
  685. return import_name_id;
  686. }
  687. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  688. // unresolved constants to the work stack.
  689. auto GetLocalNameScopeId(SemIR::NameScopeId name_scope_id)
  690. -> SemIR::NameScopeId {
  691. // Get the instruction that created the scope.
  692. auto [inst_id, inst] =
  693. import_ir_.name_scopes().GetInstIfValid(name_scope_id);
  694. if (!inst) {
  695. // Map scopes that aren't associated with an instruction to invalid
  696. // scopes. For now, such scopes aren't used, and we don't have a good way
  697. // to remap them.
  698. return SemIR::NameScopeId::Invalid;
  699. }
  700. // Get the constant value for the scope.
  701. auto const_id = SemIR::ConstantId::Invalid;
  702. CARBON_KIND_SWITCH(*inst) {
  703. case SemIR::ImplDecl::Kind:
  704. // TODO: Import the scope for an `impl` definition.
  705. return SemIR::NameScopeId::Invalid;
  706. case SemIR::Namespace::Kind:
  707. // If the namespace has already been imported, we can use its constant.
  708. // However, if it hasn't, we use Invalid instead of adding it to the
  709. // work stack. That's expected to be okay when resolving references.
  710. const_id = import_ir_constant_values().Get(inst_id);
  711. break;
  712. default:
  713. const_id = GetLocalConstantId(inst_id);
  714. }
  715. if (!const_id.is_valid()) {
  716. return SemIR::NameScopeId::Invalid;
  717. }
  718. auto const_inst_id = context_.constant_values().GetInstId(const_id);
  719. auto name_scope_inst = context_.insts().Get(const_inst_id);
  720. CARBON_KIND_SWITCH(name_scope_inst) {
  721. case CARBON_KIND(SemIR::Namespace inst): {
  722. return inst.name_scope_id;
  723. }
  724. case CARBON_KIND(SemIR::ClassType inst): {
  725. return context_.classes().Get(inst.class_id).scope_id;
  726. }
  727. case CARBON_KIND(SemIR::InterfaceType inst): {
  728. return context_.interfaces().Get(inst.interface_id).scope_id;
  729. }
  730. case SemIR::StructValue::Kind: {
  731. auto type_inst = context_.types().GetAsInst(name_scope_inst.type_id());
  732. CARBON_KIND_SWITCH(type_inst) {
  733. case CARBON_KIND(SemIR::GenericClassType inst): {
  734. return context_.classes().Get(inst.class_id).scope_id;
  735. }
  736. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  737. return context_.interfaces().Get(inst.interface_id).scope_id;
  738. }
  739. default: {
  740. break;
  741. }
  742. }
  743. break;
  744. }
  745. default: {
  746. if (const_inst_id == SemIR::InstId::BuiltinError) {
  747. return SemIR::NameScopeId::Invalid;
  748. }
  749. break;
  750. }
  751. }
  752. CARBON_FATAL("Unexpected instruction kind for name scope: {0}",
  753. name_scope_inst);
  754. }
  755. // Given an imported entity base, returns an incomplete, local version of it.
  756. //
  757. // Most fields are set in the third phase once they're imported. Import enough
  758. // of the parameter lists that we know whether this interface is a generic
  759. // interface and can build the right constant value for it.
  760. //
  761. // TODO: Support extern.
  762. // TODO: Add a better way to represent a generic prior to importing the
  763. // parameters.
  764. auto GetIncompleteLocalEntityBase(
  765. SemIR::InstId decl_id, const SemIR::EntityWithParamsBase& import_base)
  766. -> SemIR::EntityWithParamsBase {
  767. // Translate the extern_library_id if present.
  768. auto extern_library_id = SemIR::LibraryNameId::Invalid;
  769. if (import_base.extern_library_id.is_valid()) {
  770. if (import_base.extern_library_id.index >= 0) {
  771. auto val = import_ir_.string_literal_values().Get(
  772. import_base.extern_library_id.AsStringLiteralValueId());
  773. extern_library_id = SemIR::LibraryNameId::ForStringLiteralValueId(
  774. context_.string_literal_values().Add(val));
  775. } else {
  776. extern_library_id = import_base.extern_library_id;
  777. }
  778. }
  779. return {
  780. .name_id = GetLocalNameId(import_base.name_id),
  781. .parent_scope_id = SemIR::NameScopeId::Invalid,
  782. .generic_id = MakeIncompleteGeneric(decl_id, import_base.generic_id),
  783. .first_param_node_id = Parse::NodeId::Invalid,
  784. .last_param_node_id = Parse::NodeId::Invalid,
  785. .implicit_param_refs_id = import_base.implicit_param_refs_id.is_valid()
  786. ? SemIR::InstBlockId::Empty
  787. : SemIR::InstBlockId::Invalid,
  788. .param_refs_id = import_base.param_refs_id.is_valid()
  789. ? SemIR::InstBlockId::Empty
  790. : SemIR::InstBlockId::Invalid,
  791. .is_extern = import_base.is_extern,
  792. .extern_library_id = extern_library_id,
  793. .non_owning_decl_id = import_base.non_owning_decl_id.is_valid()
  794. ? decl_id
  795. : SemIR::InstId::Invalid,
  796. .first_owning_decl_id = import_base.first_owning_decl_id.is_valid()
  797. ? decl_id
  798. : SemIR::InstId::Invalid,
  799. };
  800. }
  801. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  802. // lookup.
  803. auto AddNameScopeImportRefs(const SemIR::NameScope& import_scope,
  804. SemIR::NameScope& new_scope) -> void {
  805. for (auto entry : import_scope.names) {
  806. auto ref_id = AddImportRef(
  807. context_, {.ir_id = import_ir_id_, .inst_id = entry.inst_id},
  808. SemIR::EntityNameId::Invalid);
  809. new_scope.AddRequired({.name_id = GetLocalNameId(entry.name_id),
  810. .inst_id = ref_id,
  811. .access_kind = entry.access_kind});
  812. }
  813. }
  814. // Given a block ID for a list of associated entities of a witness, returns a
  815. // version localized to the current IR.
  816. auto AddAssociatedEntities(SemIR::InstBlockId associated_entities_id)
  817. -> SemIR::InstBlockId {
  818. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  819. return SemIR::InstBlockId::Empty;
  820. }
  821. auto associated_entities =
  822. import_ir_.inst_blocks().Get(associated_entities_id);
  823. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  824. new_associated_entities.reserve(associated_entities.size());
  825. for (auto inst_id : associated_entities) {
  826. new_associated_entities.push_back(
  827. AddImportRef(context_, {.ir_id = import_ir_id_, .inst_id = inst_id},
  828. SemIR::EntityNameId::Invalid));
  829. }
  830. return context_.inst_blocks().Add(new_associated_entities);
  831. }
  832. // Tries to resolve the InstId, returning a constant when ready, or Invalid if
  833. // more has been added to the stack. A similar API is followed for all
  834. // following TryResolveTypedInst helper functions.
  835. //
  836. // `const_id` is Invalid unless we've tried to resolve this instruction
  837. // before, in which case it's the previous result.
  838. //
  839. // TODO: Error is returned when support is missing, but that should go away.
  840. auto TryResolveInst(SemIR::InstId inst_id, SemIR::ConstantId const_id)
  841. -> ResolveResult {
  842. auto inst_const_id = import_ir_.constant_values().Get(inst_id);
  843. if (!inst_const_id.is_valid() || !inst_const_id.is_symbolic()) {
  844. return TryResolveInstCanonical(inst_id, const_id);
  845. }
  846. // Try to import the generic. This might add new work.
  847. const auto& symbolic_const =
  848. import_ir_.constant_values().GetSymbolicConstant(inst_const_id);
  849. auto generic_const_id = GetLocalConstantId(symbolic_const.generic_id);
  850. auto inner_const_id = SemIR::ConstantId::Invalid;
  851. if (const_id.is_valid()) {
  852. // For the third phase, extract the constant value that
  853. // TryResolveInstCanonical produced previously.
  854. inner_const_id = context_.constant_values().Get(
  855. context_.constant_values().GetSymbolicConstant(const_id).inst_id);
  856. }
  857. // Import the constant and rebuild the symbolic constant data.
  858. auto result = TryResolveInstCanonical(inst_id, inner_const_id);
  859. if (!result.const_id.is_valid()) {
  860. // First phase: TryResolveInstCanoncial needs a retry.
  861. return result;
  862. }
  863. if (!const_id.is_valid()) {
  864. // Second phase: we have created an abstract constant. Create a
  865. // corresponding generic constant.
  866. if (symbolic_const.generic_id.is_valid()) {
  867. result.const_id = context_.constant_values().AddSymbolicConstant(
  868. {.inst_id = context_.constant_values().GetInstId(result.const_id),
  869. .generic_id = GetLocalGenericId(generic_const_id),
  870. .index = symbolic_const.index});
  871. }
  872. } else {
  873. // Third phase: perform a consistency check and produce the constant we
  874. // created in the second phase.
  875. CARBON_CHECK(result.const_id == inner_const_id,
  876. "Constant value changed in third phase.");
  877. result.const_id = const_id;
  878. }
  879. return result;
  880. }
  881. // Tries to resolve the InstId, returning a canonical constant when ready, or
  882. // Invalid if more has been added to the stack. This is the same as
  883. // TryResolveInst, except that it may resolve symbolic constants as canonical
  884. // constants instead of as constants associated with a particular generic.
  885. auto TryResolveInstCanonical(SemIR::InstId inst_id,
  886. SemIR::ConstantId const_id) -> ResolveResult {
  887. if (inst_id.is_builtin()) {
  888. CARBON_CHECK(!const_id.is_valid());
  889. // Constants for builtins can be directly copied.
  890. return ResolveAsConstant(context_.constant_values().Get(inst_id));
  891. }
  892. auto untyped_inst = import_ir_.insts().Get(inst_id);
  893. CARBON_KIND_SWITCH(untyped_inst) {
  894. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  895. return TryResolveTypedInst(inst);
  896. }
  897. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  898. return TryResolveTypedInst(inst);
  899. }
  900. case CARBON_KIND(SemIR::BaseDecl inst): {
  901. return TryResolveTypedInst(inst, inst_id);
  902. }
  903. case CARBON_KIND(SemIR::BindAlias inst): {
  904. return TryResolveTypedInst(inst);
  905. }
  906. case SemIR::BindName::Kind: {
  907. // TODO: Should we be resolving BindNames at all?
  908. return ResolveAsConstant(SemIR::ConstantId::NotConstant);
  909. }
  910. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  911. return TryResolveTypedInst(inst);
  912. }
  913. case CARBON_KIND(SemIR::ClassDecl inst): {
  914. return TryResolveTypedInst(inst, const_id);
  915. }
  916. case CARBON_KIND(SemIR::ClassType inst): {
  917. return TryResolveTypedInst(inst);
  918. }
  919. case CARBON_KIND(SemIR::ConstType inst): {
  920. return TryResolveTypedInst(inst);
  921. }
  922. case CARBON_KIND(SemIR::ExportDecl inst): {
  923. return TryResolveTypedInst(inst);
  924. }
  925. case CARBON_KIND(SemIR::FieldDecl inst): {
  926. return TryResolveTypedInst(inst, inst_id);
  927. }
  928. case CARBON_KIND(SemIR::FunctionDecl inst): {
  929. return TryResolveTypedInst(inst, const_id);
  930. }
  931. case CARBON_KIND(SemIR::FunctionType inst): {
  932. return TryResolveTypedInst(inst);
  933. }
  934. case CARBON_KIND(SemIR::GenericClassType inst): {
  935. return TryResolveTypedInst(inst);
  936. }
  937. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  938. return TryResolveTypedInst(inst);
  939. }
  940. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  941. return TryResolveTypedInst(inst, inst_id);
  942. }
  943. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  944. return TryResolveTypedInst(inst, const_id);
  945. }
  946. case CARBON_KIND(SemIR::InterfaceWitness inst): {
  947. return TryResolveTypedInst(inst);
  948. }
  949. case CARBON_KIND(SemIR::InterfaceType inst): {
  950. return TryResolveTypedInst(inst);
  951. }
  952. case CARBON_KIND(SemIR::IntLiteral inst): {
  953. return TryResolveTypedInst(inst);
  954. }
  955. case CARBON_KIND(SemIR::PointerType inst): {
  956. return TryResolveTypedInst(inst);
  957. }
  958. case CARBON_KIND(SemIR::StructType inst): {
  959. return TryResolveTypedInst(inst, inst_id);
  960. }
  961. case CARBON_KIND(SemIR::StructValue inst): {
  962. return TryResolveTypedInst(inst);
  963. }
  964. case CARBON_KIND(SemIR::TupleType inst): {
  965. return TryResolveTypedInst(inst);
  966. }
  967. case CARBON_KIND(SemIR::TupleValue inst): {
  968. return TryResolveTypedInst(inst);
  969. }
  970. case CARBON_KIND(SemIR::UnboundElementType inst): {
  971. return TryResolveTypedInst(inst);
  972. }
  973. default:
  974. context_.TODO(
  975. SemIR::LocId(AddImportIRInst(inst_id)),
  976. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  977. return {.const_id = SemIR::ConstantId::Error};
  978. }
  979. }
  980. // Produces a resolve result that tries resolving this instruction again. If
  981. // `const_id` is specified, then this is the end of the second phase, and the
  982. // constant value will be passed to the next resolution attempt. Otherwise,
  983. // this is the end of the first phase.
  984. auto Retry(SemIR::ConstantId const_id = SemIR::ConstantId::Invalid)
  985. -> ResolveResult {
  986. CARBON_CHECK(HasNewWork());
  987. return {.const_id = const_id, .retry = true};
  988. }
  989. // Produces a resolve result that provides the given constant value. Requires
  990. // that there is no new work.
  991. auto ResolveAsConstant(SemIR::ConstantId const_id) -> ResolveResult {
  992. CARBON_CHECK(!HasNewWork());
  993. return {.const_id = const_id};
  994. }
  995. // Produces a resolve result that provides the given constant value. Retries
  996. // instead if work has been added.
  997. auto RetryOrResolveAsConstant(SemIR::ConstantId const_id) -> ResolveResult {
  998. if (HasNewWork()) {
  999. return Retry();
  1000. }
  1001. return ResolveAsConstant(const_id);
  1002. }
  1003. // Produces a resolve result for the given instruction that describes a
  1004. // constant value. This should only be used for instructions that describe
  1005. // constants, and not for instructions that represent declarations. For a
  1006. // declaration, we need an associated location, so AddInstInNoBlock should be
  1007. // used instead. Requires that there is no new work.
  1008. auto ResolveAsUntyped(SemIR::Inst inst) -> ResolveResult {
  1009. CARBON_CHECK(!HasNewWork());
  1010. auto result = TryEvalInst(context_, SemIR::InstId::Invalid, inst);
  1011. CARBON_CHECK(result.is_constant(), "{0} is not constant", inst);
  1012. return {.const_id = result};
  1013. }
  1014. // Same as ResolveAsUntyped, but with an explicit type for convenience.
  1015. template <typename InstT>
  1016. auto ResolveAs(InstT inst) -> ResolveResult {
  1017. return ResolveAsUntyped(inst);
  1018. }
  1019. auto TryResolveTypedInst(SemIR::AssociatedEntity inst) -> ResolveResult {
  1020. auto type_const_id = GetLocalConstantId(inst.type_id);
  1021. if (HasNewWork()) {
  1022. return Retry();
  1023. }
  1024. // Add a lazy reference to the target declaration.
  1025. auto decl_id = AddImportRef(
  1026. context_, {.ir_id = import_ir_id_, .inst_id = inst.decl_id},
  1027. SemIR::EntityNameId::Invalid);
  1028. return ResolveAs<SemIR::AssociatedEntity>(
  1029. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  1030. .index = inst.index,
  1031. .decl_id = decl_id});
  1032. }
  1033. auto TryResolveTypedInst(SemIR::AssociatedEntityType inst) -> ResolveResult {
  1034. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1035. auto entity_type_const_id = GetLocalConstantId(inst.entity_type_id);
  1036. auto interface_inst_id = GetLocalConstantId(inst.interface_type_id);
  1037. if (HasNewWork()) {
  1038. return Retry();
  1039. }
  1040. return ResolveAs<SemIR::AssociatedEntityType>(
  1041. {.type_id = SemIR::TypeId::TypeType,
  1042. .interface_type_id =
  1043. context_.GetTypeIdForTypeConstant(interface_inst_id),
  1044. .entity_type_id =
  1045. context_.GetTypeIdForTypeConstant(entity_type_const_id)});
  1046. }
  1047. auto TryResolveTypedInst(SemIR::BaseDecl inst, SemIR::InstId import_inst_id)
  1048. -> ResolveResult {
  1049. auto type_const_id = GetLocalConstantId(inst.type_id);
  1050. auto base_type_const_id = GetLocalConstantId(inst.base_type_id);
  1051. if (HasNewWork()) {
  1052. return Retry();
  1053. }
  1054. // Import the instruction in order to update contained base_type_id and
  1055. // track the import location.
  1056. auto inst_id = context_.AddInstInNoBlock(
  1057. context_.MakeImportedLocAndInst<SemIR::BaseDecl>(
  1058. AddImportIRInst(import_inst_id),
  1059. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  1060. .base_type_id =
  1061. context_.GetTypeIdForTypeConstant(base_type_const_id),
  1062. .index = inst.index}));
  1063. return ResolveAsConstant(context_.constant_values().Get(inst_id));
  1064. }
  1065. auto TryResolveTypedInst(SemIR::BindAlias inst) -> ResolveResult {
  1066. auto value_id = GetLocalConstantId(inst.value_id);
  1067. return RetryOrResolveAsConstant(value_id);
  1068. }
  1069. auto TryResolveTypedInst(SemIR::BindSymbolicName inst) -> ResolveResult {
  1070. auto type_id = GetLocalConstantId(inst.type_id);
  1071. if (HasNewWork()) {
  1072. return Retry();
  1073. }
  1074. const auto& import_entity_name =
  1075. import_ir_.entity_names().Get(inst.entity_name_id);
  1076. auto name_id = GetLocalNameId(import_entity_name.name_id);
  1077. auto entity_name_id = context_.entity_names().Add(
  1078. {.name_id = name_id,
  1079. .parent_scope_id = SemIR::NameScopeId::Invalid,
  1080. .bind_index = import_entity_name.bind_index});
  1081. return ResolveAs<SemIR::BindSymbolicName>(
  1082. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1083. .entity_name_id = entity_name_id,
  1084. .value_id = SemIR::InstId::Invalid});
  1085. }
  1086. // Makes an incomplete class. This is necessary even with classes with a
  1087. // complete declaration, because things such as `Self` may refer back to the
  1088. // type.
  1089. auto MakeIncompleteClass(const SemIR::Class& import_class,
  1090. SemIR::SpecificId enclosing_specific_id)
  1091. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  1092. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeId::TypeType,
  1093. .class_id = SemIR::ClassId::Invalid,
  1094. .decl_block_id = SemIR::InstBlockId::Empty};
  1095. auto class_decl_id =
  1096. context_.AddPlaceholderInstInNoBlock(context_.MakeImportedLocAndInst(
  1097. AddImportIRInst(import_class.latest_decl_id()), class_decl));
  1098. // Regardless of whether ClassDecl is a complete type, we first need an
  1099. // incomplete type so that any references have something to point at.
  1100. class_decl.class_id = context_.classes().Add(
  1101. {GetIncompleteLocalEntityBase(class_decl_id, import_class),
  1102. {.self_type_id = SemIR::TypeId::Invalid,
  1103. .inheritance_kind = import_class.inheritance_kind}});
  1104. if (import_class.has_parameters()) {
  1105. class_decl.type_id = context_.GetGenericClassType(class_decl.class_id,
  1106. enclosing_specific_id);
  1107. }
  1108. // Write the class ID into the ClassDecl.
  1109. context_.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  1110. auto self_const_id = context_.constant_values().Get(class_decl_id);
  1111. return {class_decl.class_id, self_const_id};
  1112. }
  1113. // Fills out the class definition for an incomplete class.
  1114. auto AddClassDefinition(const SemIR::Class& import_class,
  1115. SemIR::Class& new_class,
  1116. SemIR::ConstantId object_repr_const_id,
  1117. SemIR::InstId base_id) -> void {
  1118. new_class.definition_id = new_class.first_owning_decl_id;
  1119. new_class.object_repr_id =
  1120. context_.GetTypeIdForTypeConstant(object_repr_const_id);
  1121. new_class.scope_id = context_.name_scopes().Add(
  1122. new_class.first_owning_decl_id, SemIR::NameId::Invalid,
  1123. new_class.parent_scope_id);
  1124. auto& new_scope = context_.name_scopes().Get(new_class.scope_id);
  1125. const auto& import_scope =
  1126. import_ir_.name_scopes().Get(import_class.scope_id);
  1127. // Push a block so that we can add scoped instructions to it.
  1128. context_.inst_block_stack().Push();
  1129. AddNameScopeImportRefs(import_scope, new_scope);
  1130. new_class.body_block_id = context_.inst_block_stack().Pop();
  1131. if (import_class.base_id.is_valid()) {
  1132. new_class.base_id = base_id;
  1133. // Add the base scope to extended scopes.
  1134. auto base_inst_id = context_.types().GetInstId(
  1135. context_.insts()
  1136. .GetAs<SemIR::BaseDecl>(new_class.base_id)
  1137. .base_type_id);
  1138. const auto& base_class = context_.classes().Get(
  1139. context_.insts().GetAs<SemIR::ClassType>(base_inst_id).class_id);
  1140. new_scope.extended_scopes.push_back(base_class.scope_id);
  1141. }
  1142. CARBON_CHECK(new_scope.extended_scopes.size() ==
  1143. import_scope.extended_scopes.size());
  1144. }
  1145. auto TryResolveTypedInst(SemIR::ClassDecl inst,
  1146. SemIR::ConstantId class_const_id) -> ResolveResult {
  1147. // TODO: The handling of interfaces repeats a lot with the handling of
  1148. // classes, and will likely also be repeated for named constraints and
  1149. // choice types. Factor out some of this functionality.
  1150. const auto& import_class = import_ir_.classes().Get(inst.class_id);
  1151. SemIR::ClassId class_id = SemIR::ClassId::Invalid;
  1152. if (!class_const_id.is_valid()) {
  1153. auto import_specific_id = SemIR::SpecificId::Invalid;
  1154. if (auto import_generic_class_type =
  1155. import_ir_.types().TryGetAs<SemIR::GenericClassType>(
  1156. inst.type_id)) {
  1157. import_specific_id = import_generic_class_type->enclosing_specific_id;
  1158. }
  1159. auto specific_data = GetLocalSpecificData(import_specific_id);
  1160. if (HasNewWork()) {
  1161. // This is the end of the first phase. Don't make a new class yet if
  1162. // we already have new work.
  1163. return Retry();
  1164. }
  1165. // On the second phase, create a forward declaration of the class for any
  1166. // recursive references.
  1167. auto enclosing_specific_id =
  1168. GetOrAddLocalSpecific(import_specific_id, specific_data);
  1169. std::tie(class_id, class_const_id) =
  1170. MakeIncompleteClass(import_class, enclosing_specific_id);
  1171. } else {
  1172. // On the third phase, compute the class ID from the constant
  1173. // value of the declaration.
  1174. auto class_const_inst = context_.insts().Get(
  1175. context_.constant_values().GetInstId(class_const_id));
  1176. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  1177. class_id = class_type->class_id;
  1178. } else {
  1179. auto generic_class_type =
  1180. context_.types().GetAs<SemIR::GenericClassType>(
  1181. class_const_inst.type_id());
  1182. class_id = generic_class_type.class_id;
  1183. }
  1184. }
  1185. // Load constants for the definition.
  1186. auto parent_scope_id = GetLocalNameScopeId(import_class.parent_scope_id);
  1187. auto implicit_param_const_ids =
  1188. GetLocalParamConstantIds(import_class.implicit_param_refs_id);
  1189. auto param_const_ids = GetLocalParamConstantIds(import_class.param_refs_id);
  1190. auto generic_data = GetLocalGenericData(import_class.generic_id);
  1191. auto self_const_id = GetLocalConstantId(import_class.self_type_id);
  1192. auto object_repr_const_id =
  1193. import_class.object_repr_id.is_valid()
  1194. ? GetLocalConstantId(import_class.object_repr_id)
  1195. : SemIR::ConstantId::Invalid;
  1196. auto base_id = import_class.base_id.is_valid()
  1197. ? GetLocalConstantInstId(import_class.base_id)
  1198. : SemIR::InstId::Invalid;
  1199. if (HasNewWork()) {
  1200. return Retry(class_const_id);
  1201. }
  1202. auto& new_class = context_.classes().Get(class_id);
  1203. new_class.parent_scope_id = parent_scope_id;
  1204. new_class.implicit_param_refs_id = GetLocalParamRefsId(
  1205. import_class.implicit_param_refs_id, implicit_param_const_ids);
  1206. new_class.param_refs_id =
  1207. GetLocalParamRefsId(import_class.param_refs_id, param_const_ids);
  1208. SetGenericData(import_class.generic_id, new_class.generic_id, generic_data);
  1209. new_class.self_type_id = context_.GetTypeIdForTypeConstant(self_const_id);
  1210. if (import_class.is_defined()) {
  1211. AddClassDefinition(import_class, new_class, object_repr_const_id,
  1212. base_id);
  1213. }
  1214. return ResolveAsConstant(class_const_id);
  1215. }
  1216. auto TryResolveTypedInst(SemIR::ClassType inst) -> ResolveResult {
  1217. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1218. auto class_const_id = GetLocalConstantId(
  1219. import_ir_.classes().Get(inst.class_id).first_owning_decl_id);
  1220. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1221. if (HasNewWork()) {
  1222. return Retry();
  1223. }
  1224. // Find the corresponding class type. For a non-generic class, this is the
  1225. // type of the class declaration. For a generic class, build a class type
  1226. // referencing this specialization of the generic class.
  1227. auto class_const_inst = context_.insts().Get(
  1228. context_.constant_values().GetInstId(class_const_id));
  1229. if (class_const_inst.Is<SemIR::ClassType>()) {
  1230. return ResolveAsConstant(class_const_id);
  1231. } else {
  1232. auto generic_class_type = context_.types().GetAs<SemIR::GenericClassType>(
  1233. class_const_inst.type_id());
  1234. auto specific_id = GetOrAddLocalSpecific(inst.specific_id, specific_data);
  1235. return ResolveAs<SemIR::ClassType>(
  1236. {.type_id = SemIR::TypeId::TypeType,
  1237. .class_id = generic_class_type.class_id,
  1238. .specific_id = specific_id});
  1239. }
  1240. }
  1241. auto TryResolveTypedInst(SemIR::ConstType inst) -> ResolveResult {
  1242. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1243. auto inner_const_id = GetLocalConstantId(inst.inner_id);
  1244. if (HasNewWork()) {
  1245. return Retry();
  1246. }
  1247. auto inner_type_id = context_.GetTypeIdForTypeConstant(inner_const_id);
  1248. return ResolveAs<SemIR::ConstType>(
  1249. {.type_id = SemIR::TypeId::TypeType, .inner_id = inner_type_id});
  1250. }
  1251. auto TryResolveTypedInst(SemIR::ExportDecl inst) -> ResolveResult {
  1252. auto value_id = GetLocalConstantId(inst.value_id);
  1253. return RetryOrResolveAsConstant(value_id);
  1254. }
  1255. auto TryResolveTypedInst(SemIR::FieldDecl inst, SemIR::InstId import_inst_id)
  1256. -> ResolveResult {
  1257. auto const_id = GetLocalConstantId(inst.type_id);
  1258. if (HasNewWork()) {
  1259. return Retry();
  1260. }
  1261. auto inst_id = context_.AddInstInNoBlock(
  1262. context_.MakeImportedLocAndInst<SemIR::FieldDecl>(
  1263. AddImportIRInst(import_inst_id),
  1264. {.type_id = context_.GetTypeIdForTypeConstant(const_id),
  1265. .name_id = GetLocalNameId(inst.name_id),
  1266. .index = inst.index}));
  1267. return {.const_id = context_.constant_values().Get(inst_id)};
  1268. }
  1269. // Make a declaration of a function. This is done as a separate step from
  1270. // importing the function declaration in order to resolve cycles.
  1271. auto MakeFunctionDecl(const SemIR::Function& import_function,
  1272. SemIR::SpecificId specific_id)
  1273. -> std::pair<SemIR::FunctionId, SemIR::ConstantId> {
  1274. SemIR::FunctionDecl function_decl = {
  1275. .type_id = SemIR::TypeId::Invalid,
  1276. .function_id = SemIR::FunctionId::Invalid,
  1277. .decl_block_id = SemIR::InstBlockId::Empty};
  1278. auto function_decl_id =
  1279. context_.AddPlaceholderInstInNoBlock(context_.MakeImportedLocAndInst(
  1280. AddImportIRInst(import_function.first_decl_id()), function_decl));
  1281. // Start with an incomplete function.
  1282. function_decl.function_id = context_.functions().Add(
  1283. {GetIncompleteLocalEntityBase(function_decl_id, import_function),
  1284. {.return_storage_id = SemIR::InstId::Invalid,
  1285. .builtin_function_kind = import_function.builtin_function_kind}});
  1286. function_decl.type_id =
  1287. context_.GetFunctionType(function_decl.function_id, specific_id);
  1288. // Write the function ID and type into the FunctionDecl.
  1289. context_.ReplaceInstBeforeConstantUse(function_decl_id, function_decl);
  1290. return {function_decl.function_id,
  1291. context_.constant_values().Get(function_decl_id)};
  1292. }
  1293. auto TryResolveTypedInst(SemIR::FunctionDecl inst,
  1294. SemIR::ConstantId function_const_id)
  1295. -> ResolveResult {
  1296. const auto& import_function = import_ir_.functions().Get(inst.function_id);
  1297. SemIR::FunctionId function_id = SemIR::FunctionId::Invalid;
  1298. if (!function_const_id.is_valid()) {
  1299. auto import_specific_id = import_ir_.types()
  1300. .GetAs<SemIR::FunctionType>(inst.type_id)
  1301. .specific_id;
  1302. auto specific_data = GetLocalSpecificData(import_specific_id);
  1303. if (HasNewWork()) {
  1304. // This is the end of the first phase. Don't make a new function yet if
  1305. // we already have new work.
  1306. return Retry();
  1307. }
  1308. // On the second phase, create a forward declaration of the interface.
  1309. auto specific_id =
  1310. GetOrAddLocalSpecific(import_specific_id, specific_data);
  1311. std::tie(function_id, function_const_id) =
  1312. MakeFunctionDecl(import_function, specific_id);
  1313. } else {
  1314. // On the third phase, compute the function ID from the constant value of
  1315. // the declaration.
  1316. auto function_const_inst = context_.insts().Get(
  1317. context_.constant_values().GetInstId(function_const_id));
  1318. auto function_type = context_.types().GetAs<SemIR::FunctionType>(
  1319. function_const_inst.type_id());
  1320. function_id = function_type.function_id;
  1321. }
  1322. auto return_type_const_id = SemIR::ConstantId::Invalid;
  1323. if (import_function.return_storage_id.is_valid()) {
  1324. return_type_const_id = GetLocalConstantId(
  1325. import_ir_.insts().Get(import_function.return_storage_id).type_id());
  1326. }
  1327. auto parent_scope_id = GetLocalNameScopeId(import_function.parent_scope_id);
  1328. auto implicit_param_const_ids =
  1329. GetLocalParamConstantIds(import_function.implicit_param_refs_id);
  1330. auto param_const_ids =
  1331. GetLocalParamConstantIds(import_function.param_refs_id);
  1332. auto generic_data = GetLocalGenericData(import_function.generic_id);
  1333. if (HasNewWork()) {
  1334. return Retry(function_const_id);
  1335. }
  1336. // Add the function declaration.
  1337. auto& new_function = context_.functions().Get(function_id);
  1338. new_function.parent_scope_id = parent_scope_id;
  1339. new_function.implicit_param_refs_id = GetLocalParamRefsId(
  1340. import_function.implicit_param_refs_id, implicit_param_const_ids);
  1341. new_function.param_refs_id =
  1342. GetLocalParamRefsId(import_function.param_refs_id, param_const_ids);
  1343. SetGenericData(import_function.generic_id, new_function.generic_id,
  1344. generic_data);
  1345. if (import_function.return_storage_id.is_valid()) {
  1346. // Recreate the return slot from scratch.
  1347. // TODO: Once we import function definitions, we'll need to make sure we
  1348. // use the same return storage variable in the declaration and definition.
  1349. new_function.return_storage_id =
  1350. context_.AddInstInNoBlock<SemIR::VarStorage>(
  1351. AddImportIRInst(import_function.return_storage_id),
  1352. {.type_id =
  1353. context_.GetTypeIdForTypeConstant(return_type_const_id),
  1354. .name_id = SemIR::NameId::ReturnSlot});
  1355. }
  1356. if (import_function.definition_id.is_valid()) {
  1357. new_function.definition_id = new_function.first_owning_decl_id;
  1358. }
  1359. return ResolveAsConstant(function_const_id);
  1360. }
  1361. auto TryResolveTypedInst(SemIR::FunctionType inst) -> ResolveResult {
  1362. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1363. auto fn_val_id = GetLocalConstantInstId(
  1364. import_ir_.functions().Get(inst.function_id).first_decl_id());
  1365. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1366. if (HasNewWork()) {
  1367. return Retry();
  1368. }
  1369. auto fn_type_id = context_.insts().Get(fn_val_id).type_id();
  1370. return ResolveAs<SemIR::FunctionType>(
  1371. {.type_id = SemIR::TypeId::TypeType,
  1372. .function_id = context_.types()
  1373. .GetAs<SemIR::FunctionType>(fn_type_id)
  1374. .function_id,
  1375. .specific_id =
  1376. GetOrAddLocalSpecific(inst.specific_id, specific_data)});
  1377. }
  1378. auto TryResolveTypedInst(SemIR::GenericClassType inst) -> ResolveResult {
  1379. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1380. auto class_val_id = GetLocalConstantInstId(
  1381. import_ir_.classes().Get(inst.class_id).first_owning_decl_id);
  1382. if (HasNewWork()) {
  1383. return Retry();
  1384. }
  1385. auto class_val = context_.insts().Get(class_val_id);
  1386. CARBON_CHECK(
  1387. context_.types().Is<SemIR::GenericClassType>(class_val.type_id()));
  1388. return ResolveAsConstant(
  1389. context_.types().GetConstantId(class_val.type_id()));
  1390. }
  1391. auto TryResolveTypedInst(SemIR::GenericInterfaceType inst) -> ResolveResult {
  1392. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1393. auto interface_val_id = GetLocalConstantInstId(
  1394. import_ir_.interfaces().Get(inst.interface_id).first_owning_decl_id);
  1395. if (HasNewWork()) {
  1396. return Retry();
  1397. }
  1398. auto interface_val = context_.insts().Get(interface_val_id);
  1399. CARBON_CHECK(context_.types().Is<SemIR::GenericInterfaceType>(
  1400. interface_val.type_id()));
  1401. return ResolveAsConstant(
  1402. context_.types().GetConstantId(interface_val.type_id()));
  1403. }
  1404. auto TryResolveTypedInst(SemIR::ImportRefLoaded /*inst*/,
  1405. SemIR::InstId inst_id) -> ResolveResult {
  1406. // Return the constant for the instruction of the imported constant.
  1407. auto constant_id = import_ir_.constant_values().Get(inst_id);
  1408. if (!constant_id.is_valid()) {
  1409. return ResolveAsConstant(SemIR::ConstantId::Error);
  1410. }
  1411. if (!constant_id.is_constant()) {
  1412. context_.TODO(inst_id,
  1413. "Non-constant ImportRefLoaded (comes up with var)");
  1414. return ResolveAsConstant(SemIR::ConstantId::Error);
  1415. }
  1416. auto new_constant_id =
  1417. GetLocalConstantId(import_ir_.constant_values().GetInstId(constant_id));
  1418. return RetryOrResolveAsConstant(new_constant_id);
  1419. }
  1420. // Make a declaration of an interface. This is done as a separate step from
  1421. // importing the interface definition in order to resolve cycles.
  1422. auto MakeInterfaceDecl(const SemIR::Interface& import_interface,
  1423. SemIR::SpecificId enclosing_specific_id)
  1424. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  1425. SemIR::InterfaceDecl interface_decl = {
  1426. .type_id = SemIR::TypeId::TypeType,
  1427. .interface_id = SemIR::InterfaceId::Invalid,
  1428. .decl_block_id = SemIR::InstBlockId::Empty};
  1429. auto interface_decl_id =
  1430. context_.AddPlaceholderInstInNoBlock(context_.MakeImportedLocAndInst(
  1431. AddImportIRInst(import_interface.first_owning_decl_id),
  1432. interface_decl));
  1433. // Start with an incomplete interface.
  1434. interface_decl.interface_id = context_.interfaces().Add(
  1435. {GetIncompleteLocalEntityBase(interface_decl_id, import_interface),
  1436. {}});
  1437. if (import_interface.has_parameters()) {
  1438. interface_decl.type_id = context_.GetGenericInterfaceType(
  1439. interface_decl.interface_id, enclosing_specific_id);
  1440. }
  1441. // Write the interface ID into the InterfaceDecl.
  1442. context_.ReplaceInstBeforeConstantUse(interface_decl_id, interface_decl);
  1443. return {interface_decl.interface_id,
  1444. context_.constant_values().Get(interface_decl_id)};
  1445. }
  1446. // Imports the definition for an interface that has been imported as a forward
  1447. // declaration.
  1448. auto AddInterfaceDefinition(const SemIR::Interface& import_interface,
  1449. SemIR::Interface& new_interface,
  1450. SemIR::InstId self_param_id) -> void {
  1451. new_interface.scope_id = context_.name_scopes().Add(
  1452. new_interface.first_owning_decl_id, SemIR::NameId::Invalid,
  1453. new_interface.parent_scope_id);
  1454. auto& new_scope = context_.name_scopes().Get(new_interface.scope_id);
  1455. const auto& import_scope =
  1456. import_ir_.name_scopes().Get(import_interface.scope_id);
  1457. // Push a block so that we can add scoped instructions to it.
  1458. context_.inst_block_stack().Push();
  1459. AddNameScopeImportRefs(import_scope, new_scope);
  1460. new_interface.associated_entities_id =
  1461. AddAssociatedEntities(import_interface.associated_entities_id);
  1462. new_interface.body_block_id = context_.inst_block_stack().Pop();
  1463. new_interface.self_param_id = self_param_id;
  1464. CARBON_CHECK(import_scope.extended_scopes.empty(),
  1465. "Interfaces don't currently have extended scopes to support.");
  1466. }
  1467. auto TryResolveTypedInst(SemIR::InterfaceDecl inst,
  1468. SemIR::ConstantId interface_const_id)
  1469. -> ResolveResult {
  1470. const auto& import_interface =
  1471. import_ir_.interfaces().Get(inst.interface_id);
  1472. SemIR::InterfaceId interface_id = SemIR::InterfaceId::Invalid;
  1473. if (!interface_const_id.is_valid()) {
  1474. auto import_specific_id = SemIR::SpecificId::Invalid;
  1475. if (auto import_generic_interface_type =
  1476. import_ir_.types().TryGetAs<SemIR::GenericInterfaceType>(
  1477. inst.type_id)) {
  1478. import_specific_id =
  1479. import_generic_interface_type->enclosing_specific_id;
  1480. }
  1481. auto specific_data = GetLocalSpecificData(import_specific_id);
  1482. if (HasNewWork()) {
  1483. // This is the end of the first phase. Don't make a new interface yet if
  1484. // we already have new work.
  1485. return Retry();
  1486. }
  1487. // On the second phase, create a forward declaration of the interface.
  1488. auto enclosing_specific_id =
  1489. GetOrAddLocalSpecific(import_specific_id, specific_data);
  1490. std::tie(interface_id, interface_const_id) =
  1491. MakeInterfaceDecl(import_interface, enclosing_specific_id);
  1492. } else {
  1493. // On the third phase, compute the interface ID from the constant value of
  1494. // the declaration.
  1495. auto interface_const_inst = context_.insts().Get(
  1496. context_.constant_values().GetInstId(interface_const_id));
  1497. if (auto interface_type =
  1498. interface_const_inst.TryAs<SemIR::InterfaceType>()) {
  1499. interface_id = interface_type->interface_id;
  1500. } else {
  1501. auto generic_interface_type =
  1502. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1503. interface_const_inst.type_id());
  1504. interface_id = generic_interface_type.interface_id;
  1505. }
  1506. }
  1507. auto parent_scope_id =
  1508. GetLocalNameScopeId(import_interface.parent_scope_id);
  1509. auto implicit_param_const_ids =
  1510. GetLocalParamConstantIds(import_interface.implicit_param_refs_id);
  1511. auto param_const_ids =
  1512. GetLocalParamConstantIds(import_interface.param_refs_id);
  1513. auto generic_data = GetLocalGenericData(import_interface.generic_id);
  1514. std::optional<SemIR::InstId> self_param_id;
  1515. if (import_interface.is_defined()) {
  1516. self_param_id = GetLocalConstantInstId(import_interface.self_param_id);
  1517. }
  1518. if (HasNewWork()) {
  1519. return Retry(interface_const_id);
  1520. }
  1521. auto& new_interface = context_.interfaces().Get(interface_id);
  1522. new_interface.parent_scope_id = parent_scope_id;
  1523. new_interface.implicit_param_refs_id = GetLocalParamRefsId(
  1524. import_interface.implicit_param_refs_id, implicit_param_const_ids);
  1525. new_interface.param_refs_id =
  1526. GetLocalParamRefsId(import_interface.param_refs_id, param_const_ids);
  1527. SetGenericData(import_interface.generic_id, new_interface.generic_id,
  1528. generic_data);
  1529. if (import_interface.is_defined()) {
  1530. CARBON_CHECK(self_param_id);
  1531. AddInterfaceDefinition(import_interface, new_interface, *self_param_id);
  1532. }
  1533. return ResolveAsConstant(interface_const_id);
  1534. }
  1535. auto TryResolveTypedInst(SemIR::InterfaceType inst) -> ResolveResult {
  1536. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1537. auto interface_const_id = GetLocalConstantId(
  1538. import_ir_.interfaces().Get(inst.interface_id).first_owning_decl_id);
  1539. auto specific_data = GetLocalSpecificData(inst.specific_id);
  1540. if (HasNewWork()) {
  1541. return Retry();
  1542. }
  1543. // Find the corresponding interface type. For a non-generic interface, this
  1544. // is the type of the interface declaration. For a generic interface, build
  1545. // a interface type referencing this specialization of the generic
  1546. // interface.
  1547. auto interface_const_inst = context_.insts().Get(
  1548. context_.constant_values().GetInstId(interface_const_id));
  1549. if (interface_const_inst.Is<SemIR::InterfaceType>()) {
  1550. return ResolveAsConstant(interface_const_id);
  1551. } else {
  1552. auto generic_interface_type =
  1553. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1554. interface_const_inst.type_id());
  1555. auto specific_id = GetOrAddLocalSpecific(inst.specific_id, specific_data);
  1556. return ResolveAs<SemIR::InterfaceType>(
  1557. {.type_id = SemIR::TypeId::TypeType,
  1558. .interface_id = generic_interface_type.interface_id,
  1559. .specific_id = specific_id});
  1560. }
  1561. }
  1562. auto TryResolveTypedInst(SemIR::InterfaceWitness inst) -> ResolveResult {
  1563. auto elements = GetLocalInstBlockContents(inst.elements_id);
  1564. if (HasNewWork()) {
  1565. return Retry();
  1566. }
  1567. auto elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elements);
  1568. return ResolveAs<SemIR::InterfaceWitness>(
  1569. {.type_id =
  1570. context_.GetBuiltinType(SemIR::BuiltinInstKind::WitnessType),
  1571. .elements_id = elements_id});
  1572. }
  1573. auto TryResolveTypedInst(SemIR::IntLiteral inst) -> ResolveResult {
  1574. auto type_id = GetLocalConstantId(inst.type_id);
  1575. if (HasNewWork()) {
  1576. return Retry();
  1577. }
  1578. return ResolveAs<SemIR::IntLiteral>(
  1579. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1580. .int_id = context_.ints().Add(import_ir_.ints().Get(inst.int_id))});
  1581. }
  1582. auto TryResolveTypedInst(SemIR::PointerType inst) -> ResolveResult {
  1583. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1584. auto pointee_const_id = GetLocalConstantId(inst.pointee_id);
  1585. if (HasNewWork()) {
  1586. return Retry();
  1587. }
  1588. auto pointee_type_id = context_.GetTypeIdForTypeConstant(pointee_const_id);
  1589. return ResolveAs<SemIR::PointerType>(
  1590. {.type_id = SemIR::TypeId::TypeType, .pointee_id = pointee_type_id});
  1591. }
  1592. auto TryResolveTypedInst(SemIR::StructType inst, SemIR::InstId import_inst_id)
  1593. -> ResolveResult {
  1594. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1595. auto orig_fields = import_ir_.inst_blocks().Get(inst.fields_id);
  1596. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  1597. field_const_ids.reserve(orig_fields.size());
  1598. for (auto field_id : orig_fields) {
  1599. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1600. field_const_ids.push_back(GetLocalConstantId(field.field_type_id));
  1601. }
  1602. if (HasNewWork()) {
  1603. return Retry();
  1604. }
  1605. // Prepare a vector of fields for GetStructType.
  1606. // TODO: Should we have field constants so that we can deduplicate fields
  1607. // without creating instructions here?
  1608. llvm::SmallVector<SemIR::InstId> fields;
  1609. fields.reserve(orig_fields.size());
  1610. for (auto [field_id, field_const_id] :
  1611. llvm::zip(orig_fields, field_const_ids)) {
  1612. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1613. auto name_id = GetLocalNameId(field.name_id);
  1614. auto field_type_id = context_.GetTypeIdForTypeConstant(field_const_id);
  1615. fields.push_back(context_.AddInstInNoBlock<SemIR::StructTypeField>(
  1616. AddImportIRInst(import_inst_id),
  1617. {.name_id = name_id, .field_type_id = field_type_id}));
  1618. }
  1619. return ResolveAs<SemIR::StructType>(
  1620. {.type_id = SemIR::TypeId::TypeType,
  1621. .fields_id = context_.inst_blocks().AddCanonical(fields)});
  1622. }
  1623. auto TryResolveTypedInst(SemIR::StructValue inst) -> ResolveResult {
  1624. auto type_id = GetLocalConstantId(inst.type_id);
  1625. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1626. if (HasNewWork()) {
  1627. return Retry();
  1628. }
  1629. return ResolveAs<SemIR::StructValue>(
  1630. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1631. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1632. }
  1633. auto TryResolveTypedInst(SemIR::TupleType inst) -> ResolveResult {
  1634. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1635. auto orig_elem_type_ids = import_ir_.type_blocks().Get(inst.elements_id);
  1636. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  1637. elem_const_ids.reserve(orig_elem_type_ids.size());
  1638. for (auto elem_type_id : orig_elem_type_ids) {
  1639. elem_const_ids.push_back(GetLocalConstantId(elem_type_id));
  1640. }
  1641. if (HasNewWork()) {
  1642. return Retry();
  1643. }
  1644. // Prepare a vector of the tuple types for GetTupleType.
  1645. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  1646. elem_type_ids.reserve(orig_elem_type_ids.size());
  1647. for (auto elem_const_id : elem_const_ids) {
  1648. elem_type_ids.push_back(context_.GetTypeIdForTypeConstant(elem_const_id));
  1649. }
  1650. return ResolveAsConstant(
  1651. context_.types().GetConstantId(context_.GetTupleType(elem_type_ids)));
  1652. }
  1653. auto TryResolveTypedInst(SemIR::TupleValue inst) -> ResolveResult {
  1654. auto type_id = GetLocalConstantId(inst.type_id);
  1655. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1656. if (HasNewWork()) {
  1657. return Retry();
  1658. }
  1659. return ResolveAs<SemIR::TupleValue>(
  1660. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1661. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1662. }
  1663. auto TryResolveTypedInst(SemIR::UnboundElementType inst) -> ResolveResult {
  1664. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1665. auto class_const_id = GetLocalConstantId(inst.class_type_id);
  1666. auto elem_const_id = GetLocalConstantId(inst.element_type_id);
  1667. if (HasNewWork()) {
  1668. return Retry();
  1669. }
  1670. return ResolveAs<SemIR::UnboundElementType>(
  1671. {.type_id = SemIR::TypeId::TypeType,
  1672. .class_type_id = context_.GetTypeIdForTypeConstant(class_const_id),
  1673. .element_type_id = context_.GetTypeIdForTypeConstant(elem_const_id)});
  1674. }
  1675. // Perform any work that we deferred until the end of the main Resolve loop.
  1676. auto PerformPendingWork() -> void {
  1677. // Note that the individual Finish steps can add new pending work, so keep
  1678. // going until we have no more work to do.
  1679. while (!pending_generics_.empty() || !pending_specifics_.empty()) {
  1680. while (!pending_generics_.empty()) {
  1681. FinishPendingGeneric(pending_generics_.pop_back_val());
  1682. }
  1683. while (!pending_specifics_.empty()) {
  1684. FinishPendingSpecific(pending_specifics_.pop_back_val());
  1685. }
  1686. }
  1687. }
  1688. // Resolves and returns the local contents for an imported instruction block
  1689. // of constant instructions.
  1690. auto ResolveLocalInstBlockContents(SemIR::InstBlockId import_block_id)
  1691. -> llvm::SmallVector<SemIR::InstId> {
  1692. auto import_block = import_ir_.inst_blocks().Get(import_block_id);
  1693. llvm::SmallVector<SemIR::InstId> inst_ids;
  1694. inst_ids.reserve(import_block.size());
  1695. for (auto import_inst_id : import_block) {
  1696. inst_ids.push_back(
  1697. context_.constant_values().GetInstId(ResolveOneInst(import_inst_id)));
  1698. }
  1699. return inst_ids;
  1700. }
  1701. // Resolves and returns a local eval block for a region of an imported
  1702. // generic.
  1703. auto ResolveLocalEvalBlock(const SemIR::Generic& import_generic,
  1704. SemIR::GenericId generic_id,
  1705. SemIR::GenericInstIndex::Region region)
  1706. -> SemIR::InstBlockId {
  1707. auto import_block_id = import_generic.GetEvalBlock(region);
  1708. if (!import_block_id.is_valid()) {
  1709. return SemIR::InstBlockId::Invalid;
  1710. }
  1711. auto inst_ids = ResolveLocalInstBlockContents(import_block_id);
  1712. return RebuildGenericEvalBlock(context_, generic_id, region, inst_ids);
  1713. }
  1714. // Fills in the remaining information in a partially-imported generic.
  1715. auto FinishPendingGeneric(PendingGeneric pending) -> void {
  1716. const auto& import_generic = import_ir_.generics().Get(pending.import_id);
  1717. // Don't store the local generic between calls: the generics list can be
  1718. // reallocated by ResolveLocalEvalBlock importing more specifics.
  1719. auto decl_block_id =
  1720. ResolveLocalEvalBlock(import_generic, pending.local_id,
  1721. SemIR::GenericInstIndex::Region::Declaration);
  1722. context_.generics().Get(pending.local_id).decl_block_id = decl_block_id;
  1723. auto self_specific_id = MakeSelfSpecific(context_, pending.local_id);
  1724. context_.generics().Get(pending.local_id).self_specific_id =
  1725. self_specific_id;
  1726. pending_specifics_.push_back({.import_id = import_generic.self_specific_id,
  1727. .local_id = self_specific_id});
  1728. auto definition_block_id =
  1729. ResolveLocalEvalBlock(import_generic, pending.local_id,
  1730. SemIR::GenericInstIndex::Region::Definition);
  1731. context_.generics().Get(pending.local_id).definition_block_id =
  1732. definition_block_id;
  1733. }
  1734. // Resolves and returns a local inst block of constant instructions
  1735. // corresponding to an imported inst block.
  1736. auto ResolveLocalInstBlock(SemIR::InstBlockId import_block_id)
  1737. -> SemIR::InstBlockId {
  1738. if (!import_block_id.is_valid()) {
  1739. return SemIR::InstBlockId::Invalid;
  1740. }
  1741. auto inst_ids = ResolveLocalInstBlockContents(import_block_id);
  1742. return context_.inst_blocks().Add(inst_ids);
  1743. }
  1744. // Fills in the remaining information in a partially-imported specific.
  1745. auto FinishPendingSpecific(PendingSpecific pending) -> void {
  1746. const auto& import_specific = import_ir_.specifics().Get(pending.import_id);
  1747. // Don't store the local specific between calls: the specifics list can be
  1748. // reallocated by ResolveLocalInstBlock importing more specifics.
  1749. if (!context_.specifics().Get(pending.local_id).decl_block_id.is_valid()) {
  1750. auto decl_block_id = ResolveLocalInstBlock(import_specific.decl_block_id);
  1751. context_.specifics().Get(pending.local_id).decl_block_id = decl_block_id;
  1752. }
  1753. if (!context_.specifics()
  1754. .Get(pending.local_id)
  1755. .definition_block_id.is_valid() &&
  1756. import_specific.definition_block_id.is_valid()) {
  1757. auto definition_block_id =
  1758. ResolveLocalInstBlock(import_specific.definition_block_id);
  1759. context_.specifics().Get(pending.local_id).definition_block_id =
  1760. definition_block_id;
  1761. }
  1762. }
  1763. auto import_ir_constant_values() -> SemIR::ConstantValueStore& {
  1764. return context_.import_ir_constant_values()[import_ir_id_.index];
  1765. }
  1766. Context& context_;
  1767. SemIR::ImportIRId import_ir_id_;
  1768. const SemIR::File& import_ir_;
  1769. llvm::SmallVector<Work> work_stack_;
  1770. // The size of work_stack_ at the start of resolving the current instruction.
  1771. size_t initial_work_ = 0;
  1772. // Generics that we have partially imported but not yet finished importing.
  1773. llvm::SmallVector<PendingGeneric> pending_generics_;
  1774. // Specifics that we have partially imported but not yet finished importing.
  1775. llvm::SmallVector<PendingSpecific> pending_specifics_;
  1776. };
  1777. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  1778. // loaded (including the one pointed at directly by the ImportRef), and the
  1779. // final instruction's type ID.
  1780. //
  1781. // This addresses cases where an ImportRefUnloaded may point at another
  1782. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  1783. // constant-evaluated version of the instruction to work with.
  1784. static auto GetInstForLoad(Context& context,
  1785. SemIR::ImportIRInstId import_ir_inst_id)
  1786. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  1787. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  1788. {}, SemIR::TypeId::Invalid};
  1789. auto& [import_ir_insts, type_id] = result;
  1790. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  1791. // The first ImportIRInst is added directly because the IR doesn't need to be
  1792. // localized.
  1793. import_ir_insts.push_back(import_ir_inst);
  1794. const auto* cursor_ir = context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1795. while (true) {
  1796. auto cursor_inst = cursor_ir->insts().Get(import_ir_inst.inst_id);
  1797. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  1798. if (!import_ref) {
  1799. type_id = cursor_inst.type_id();
  1800. return result;
  1801. }
  1802. import_ir_inst =
  1803. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  1804. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1805. import_ir_insts.push_back(
  1806. {.ir_id = AddImportIR(context, {.decl_id = SemIR::InstId::Invalid,
  1807. .is_export = false,
  1808. .sem_ir = cursor_ir}),
  1809. .inst_id = import_ir_inst.inst_id});
  1810. }
  1811. }
  1812. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  1813. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  1814. if (!inst) {
  1815. return;
  1816. }
  1817. auto [indirect_insts, load_type_id] =
  1818. GetInstForLoad(context, inst->import_ir_inst_id);
  1819. // The last indirect instruction is the one to resolve. Pop it here because
  1820. // Resolve will assign the constant.
  1821. auto load_ir_inst = indirect_insts.pop_back_val();
  1822. ImportRefResolver resolver(context, load_ir_inst.ir_id);
  1823. // The resolver calls into Context to create instructions. Don't register
  1824. // those instructions as part of the enclosing generic scope if they're
  1825. // dependent on a generic parameter.
  1826. context.generic_region_stack().Push();
  1827. auto type_id = resolver.ResolveType(load_type_id);
  1828. auto constant_id = resolver.Resolve(load_ir_inst.inst_id);
  1829. context.generic_region_stack().Pop();
  1830. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  1831. // doesn't use ReplaceInstBeforeConstantUse because it would trigger
  1832. // TryEvalInst, which we want to avoid with ImportRefs.
  1833. context.sem_ir().insts().Set(
  1834. inst_id,
  1835. SemIR::ImportRefLoaded{.type_id = type_id,
  1836. .import_ir_inst_id = inst->import_ir_inst_id,
  1837. .entity_name_id = inst->entity_name_id});
  1838. // Store the constant for both the ImportRefLoaded and indirect instructions.
  1839. context.constant_values().Set(inst_id, constant_id);
  1840. for (const auto& import_ir_inst : indirect_insts) {
  1841. context.import_ir_constant_values()[import_ir_inst.ir_id.index].Set(
  1842. import_ir_inst.inst_id, constant_id);
  1843. }
  1844. }
  1845. // Imports the impl `import_impl_id` from the imported IR `import_ir`.
  1846. static auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  1847. const SemIR::File& import_ir,
  1848. SemIR::ImplId import_impl_id) -> void {
  1849. // Resolve the imported impl to a local impl ID.
  1850. ImportRefResolver resolver(context, import_ir_id);
  1851. const auto& import_impl = import_ir.impls().Get(import_impl_id);
  1852. auto self_id = resolver.ResolveType(import_impl.self_id);
  1853. auto constraint_id = resolver.ResolveType(import_impl.constraint_id);
  1854. // Import the definition if the impl is defined.
  1855. // TODO: Do we need to check for multiple definitions?
  1856. auto impl_id = context.impls().LookupOrAdd(self_id, constraint_id);
  1857. if (import_impl.is_defined()) {
  1858. // TODO: Create a scope for the `impl` if necessary.
  1859. // TODO: Consider importing the definition_id.
  1860. auto& impl = context.impls().Get(impl_id);
  1861. impl.witness_id = AddImportRef(
  1862. context, {.ir_id = import_ir_id, .inst_id = import_impl.witness_id},
  1863. SemIR::EntityNameId::Invalid);
  1864. }
  1865. }
  1866. // TODO: This doesn't belong in this file. Consider moving the import resolver
  1867. // and this file elsewhere.
  1868. auto ImportImpls(Context& context) -> void {
  1869. for (auto [import_index, import_ir] :
  1870. llvm::enumerate(context.import_irs().array_ref())) {
  1871. if (!import_ir.sem_ir) {
  1872. continue;
  1873. }
  1874. SemIR::ImportIRId import_ir_id(import_index);
  1875. for (auto impl_index : llvm::seq(import_ir.sem_ir->impls().size())) {
  1876. SemIR::ImplId impl_id(impl_index);
  1877. ImportImpl(context, import_ir_id, *import_ir.sem_ir, impl_id);
  1878. }
  1879. }
  1880. }
  1881. } // namespace Carbon::Check