import_ref.cpp 65 KB

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