import_ref.cpp 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628
  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. // Gets a local version of an imported generic.
  373. auto GetLocalGeneric(SemIR::GenericId generic_id) -> SemIR::GenericId {
  374. if (!generic_id.is_valid()) {
  375. return SemIR::GenericId::Invalid;
  376. }
  377. // TODO: Support importing generics. Note that this comes up in the prelude,
  378. // so for now we fall back to producing `Invalid` and treating imported
  379. // generics as non-generic.
  380. return SemIR::GenericId::Invalid;
  381. }
  382. // Gets a local argument list corresponding to the arguments of an imported
  383. // generic instance.
  384. auto GetLocalGenericInstanceArgs(SemIR::GenericInstanceId instance_id)
  385. -> llvm::SmallVector<SemIR::InstId> {
  386. if (!instance_id.is_valid()) {
  387. return {};
  388. }
  389. return GetLocalInstBlockContents(
  390. import_ir_.generic_instances().Get(instance_id).args_id);
  391. }
  392. // Gets a local generic instance whose arguments were already imported by
  393. // GetLocalGenericInstanceArgs. Does not add any new work.
  394. auto GetLocalGenericInstance(SemIR::GenericInstanceId instance_id,
  395. llvm::ArrayRef<SemIR::InstId> args)
  396. -> SemIR::GenericInstanceId {
  397. if (!instance_id.is_valid()) {
  398. return SemIR::GenericInstanceId::Invalid;
  399. }
  400. const auto& instance = import_ir_.generic_instances().Get(instance_id);
  401. // TODO: Import the generic.
  402. auto generic_id = SemIR::GenericId::Invalid;
  403. auto args_id = GetLocalCanonicalInstBlockId(instance.args_id, args);
  404. // TODO: Also import the generic instance.
  405. return context_.generic_instances().GetOrAdd(generic_id, args_id);
  406. }
  407. // Returns the ConstantId for each parameter's type. Adds unresolved constants
  408. // to work_stack_.
  409. auto GetLocalParamConstantIds(SemIR::InstBlockId param_refs_id)
  410. -> llvm::SmallVector<SemIR::ConstantId> {
  411. llvm::SmallVector<SemIR::ConstantId> const_ids;
  412. if (!param_refs_id.is_valid() ||
  413. param_refs_id == SemIR::InstBlockId::Empty) {
  414. return const_ids;
  415. }
  416. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  417. const_ids.reserve(param_refs.size());
  418. for (auto inst_id : param_refs) {
  419. const_ids.push_back(
  420. GetLocalConstantId(import_ir_.insts().Get(inst_id).type_id()));
  421. // If the parameter is a symbolic binding, build the BindSymbolicName
  422. // constant.
  423. auto bind_id = inst_id;
  424. if (auto addr =
  425. import_ir_.insts().TryGetAs<SemIR::AddrPattern>(bind_id)) {
  426. bind_id = addr->inner_id;
  427. }
  428. GetLocalConstantId(bind_id);
  429. }
  430. return const_ids;
  431. }
  432. // Given a param_refs_id and const_ids from GetLocalParamConstantIds, returns
  433. // a version of param_refs_id localized to the current IR.
  434. auto GetLocalParamRefsId(
  435. SemIR::InstBlockId param_refs_id,
  436. const llvm::SmallVector<SemIR::ConstantId>& const_ids)
  437. -> SemIR::InstBlockId {
  438. if (!param_refs_id.is_valid() ||
  439. param_refs_id == SemIR::InstBlockId::Empty) {
  440. return param_refs_id;
  441. }
  442. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  443. llvm::SmallVector<SemIR::InstId> new_param_refs;
  444. for (auto [ref_id, const_id] : llvm::zip(param_refs, const_ids)) {
  445. // Figure out the param structure. This echoes
  446. // Function::GetParamFromParamRefId.
  447. // TODO: Consider a different parameter handling to simplify import logic.
  448. auto inst = import_ir_.insts().Get(ref_id);
  449. auto addr_inst = inst.TryAs<SemIR::AddrPattern>();
  450. auto bind_id = ref_id;
  451. auto param_id = ref_id;
  452. if (addr_inst) {
  453. bind_id = addr_inst->inner_id;
  454. param_id = bind_id;
  455. inst = import_ir_.insts().Get(bind_id);
  456. }
  457. auto bind_inst = inst.TryAs<SemIR::AnyBindName>();
  458. if (bind_inst) {
  459. param_id = bind_inst->value_id;
  460. inst = import_ir_.insts().Get(param_id);
  461. }
  462. auto param_inst = inst.As<SemIR::Param>();
  463. // Rebuild the param instruction.
  464. auto name_id = GetLocalNameId(param_inst.name_id);
  465. auto type_id = context_.GetTypeIdForTypeConstant(const_id);
  466. auto new_param_id = context_.AddInstInNoBlock<SemIR::Param>(
  467. AddImportIRInst(param_id), {.type_id = type_id, .name_id = name_id});
  468. if (bind_inst) {
  469. switch (bind_inst->kind) {
  470. case SemIR::BindName::Kind: {
  471. auto bind_name_id = context_.bind_names().Add(
  472. {.name_id = name_id,
  473. .parent_scope_id = SemIR::NameScopeId::Invalid,
  474. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  475. new_param_id = context_.AddInstInNoBlock<SemIR::BindName>(
  476. AddImportIRInst(bind_id), {.type_id = type_id,
  477. .bind_name_id = bind_name_id,
  478. .value_id = new_param_id});
  479. break;
  480. }
  481. case SemIR::BindSymbolicName::Kind: {
  482. // The symbolic name will be created on first reference, so might
  483. // already exist. Update the value in it to refer to the parameter.
  484. auto new_bind_inst_id = GetLocalConstantInstId(bind_id);
  485. auto new_bind_inst =
  486. context_.insts().GetAs<SemIR::BindSymbolicName>(
  487. new_bind_inst_id);
  488. new_bind_inst.value_id = new_param_id;
  489. // This is not before constant use, but doesn't change the
  490. // constant value of the instruction.
  491. context_.ReplaceInstBeforeConstantUse(new_bind_inst_id,
  492. new_bind_inst);
  493. new_param_id = new_bind_inst_id;
  494. break;
  495. }
  496. default: {
  497. CARBON_FATAL() << "Unexpected kind: " << bind_inst->kind;
  498. }
  499. }
  500. }
  501. if (addr_inst) {
  502. new_param_id = context_.AddInstInNoBlock<SemIR::AddrPattern>(
  503. AddImportIRInst(ref_id),
  504. {.type_id = type_id, .inner_id = new_param_id});
  505. }
  506. new_param_refs.push_back(new_param_id);
  507. }
  508. return context_.inst_blocks().Add(new_param_refs);
  509. }
  510. // Translates a NameId from the import IR to a local NameId.
  511. auto GetLocalNameId(SemIR::NameId import_name_id) -> SemIR::NameId {
  512. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.is_valid()) {
  513. return SemIR::NameId::ForIdentifier(
  514. context_.identifiers().Add(import_ir_.identifiers().Get(ident_id)));
  515. }
  516. return import_name_id;
  517. }
  518. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  519. // unresolved constants to the work stack.
  520. auto GetLocalNameScopeId(SemIR::NameScopeId name_scope_id)
  521. -> SemIR::NameScopeId {
  522. auto [inst_id, inst] =
  523. import_ir_.name_scopes().GetInstIfValid(name_scope_id);
  524. if (!inst) {
  525. // Map scopes that aren't associated with an instruction to invalid
  526. // scopes. For now, such scopes aren't used, and we don't have a good way
  527. // to remap them.
  528. return SemIR::NameScopeId::Invalid;
  529. }
  530. if (inst->Is<SemIR::ImplDecl>()) {
  531. // TODO: Import the scope for an `impl` definition.
  532. return SemIR::NameScopeId::Invalid;
  533. }
  534. auto const_inst_id = GetLocalConstantInstId(inst_id);
  535. if (!const_inst_id.is_valid()) {
  536. return SemIR::NameScopeId::Invalid;
  537. }
  538. auto name_scope_inst = context_.insts().Get(const_inst_id);
  539. CARBON_KIND_SWITCH(name_scope_inst) {
  540. case CARBON_KIND(SemIR::Namespace inst): {
  541. return inst.name_scope_id;
  542. }
  543. case CARBON_KIND(SemIR::ClassType inst): {
  544. return context_.classes().Get(inst.class_id).scope_id;
  545. }
  546. case CARBON_KIND(SemIR::InterfaceType inst): {
  547. return context_.interfaces().Get(inst.interface_id).scope_id;
  548. }
  549. case SemIR::StructValue::Kind: {
  550. auto type_inst = context_.types().GetAsInst(name_scope_inst.type_id());
  551. CARBON_KIND_SWITCH(type_inst) {
  552. case CARBON_KIND(SemIR::GenericClassType inst): {
  553. return context_.classes().Get(inst.class_id).scope_id;
  554. }
  555. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  556. return context_.interfaces().Get(inst.interface_id).scope_id;
  557. }
  558. default: {
  559. break;
  560. }
  561. }
  562. break;
  563. }
  564. default: {
  565. if (const_inst_id == SemIR::InstId::BuiltinError) {
  566. return SemIR::NameScopeId::Invalid;
  567. }
  568. break;
  569. }
  570. }
  571. CARBON_FATAL() << "Unexpected instruction kind for name scope: "
  572. << name_scope_inst;
  573. }
  574. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  575. // lookup.
  576. auto AddNameScopeImportRefs(const SemIR::NameScope& import_scope,
  577. SemIR::NameScope& new_scope) -> void {
  578. for (auto entry : import_scope.names) {
  579. auto ref_id = AddImportRef(
  580. context_, {.ir_id = import_ir_id_, .inst_id = entry.inst_id},
  581. SemIR::BindNameId::Invalid);
  582. new_scope.AddRequired({.name_id = GetLocalNameId(entry.name_id),
  583. .inst_id = ref_id,
  584. .access_kind = entry.access_kind});
  585. }
  586. }
  587. // Given a block ID for a list of associated entities of a witness, returns a
  588. // version localized to the current IR.
  589. auto AddAssociatedEntities(SemIR::InstBlockId associated_entities_id)
  590. -> SemIR::InstBlockId {
  591. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  592. return SemIR::InstBlockId::Empty;
  593. }
  594. auto associated_entities =
  595. import_ir_.inst_blocks().Get(associated_entities_id);
  596. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  597. new_associated_entities.reserve(associated_entities.size());
  598. for (auto inst_id : associated_entities) {
  599. new_associated_entities.push_back(
  600. AddImportRef(context_, {.ir_id = import_ir_id_, .inst_id = inst_id},
  601. SemIR::BindNameId::Invalid));
  602. }
  603. return context_.inst_blocks().Add(new_associated_entities);
  604. }
  605. // Tries to resolve the InstId, returning a constant when ready, or Invalid if
  606. // more has been added to the stack. A similar API is followed for all
  607. // following TryResolveTypedInst helper functions.
  608. //
  609. // `const_id` is Invalid unless we've tried to resolve this instruction
  610. // before, in which case it's the previous result.
  611. //
  612. // TODO: Error is returned when support is missing, but that should go away.
  613. auto TryResolveInst(SemIR::InstId inst_id, SemIR::ConstantId const_id)
  614. -> ResolveResult {
  615. if (inst_id.is_builtin()) {
  616. CARBON_CHECK(!const_id.is_valid());
  617. // Constants for builtins can be directly copied.
  618. return {.const_id = context_.constant_values().Get(inst_id)};
  619. }
  620. auto untyped_inst = import_ir_.insts().Get(inst_id);
  621. CARBON_KIND_SWITCH(untyped_inst) {
  622. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  623. return TryResolveTypedInst(inst);
  624. }
  625. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  626. return TryResolveTypedInst(inst);
  627. }
  628. case CARBON_KIND(SemIR::BaseDecl inst): {
  629. return TryResolveTypedInst(inst, inst_id);
  630. }
  631. case CARBON_KIND(SemIR::BindAlias inst): {
  632. return TryResolveTypedInst(inst);
  633. }
  634. case CARBON_KIND(SemIR::BindName inst): {
  635. // TODO: This always returns `ConstantId::NotConstant`.
  636. return {.const_id = TryEvalInst(context_, inst_id, inst)};
  637. }
  638. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  639. return TryResolveTypedInst(inst);
  640. }
  641. case CARBON_KIND(SemIR::ClassDecl inst): {
  642. return TryResolveTypedInst(inst, const_id);
  643. }
  644. case CARBON_KIND(SemIR::ClassType inst): {
  645. return TryResolveTypedInst(inst);
  646. }
  647. case CARBON_KIND(SemIR::ConstType inst): {
  648. return TryResolveTypedInst(inst);
  649. }
  650. case CARBON_KIND(SemIR::ExportDecl inst): {
  651. return TryResolveTypedInst(inst);
  652. }
  653. case CARBON_KIND(SemIR::FieldDecl inst): {
  654. return TryResolveTypedInst(inst, inst_id);
  655. }
  656. case CARBON_KIND(SemIR::FunctionDecl inst): {
  657. return TryResolveTypedInst(inst);
  658. }
  659. case CARBON_KIND(SemIR::FunctionType inst): {
  660. return TryResolveTypedInst(inst);
  661. }
  662. case CARBON_KIND(SemIR::GenericClassType inst): {
  663. return TryResolveTypedInst(inst);
  664. }
  665. case CARBON_KIND(SemIR::GenericInterfaceType inst): {
  666. return TryResolveTypedInst(inst);
  667. }
  668. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  669. return TryResolveTypedInst(inst, inst_id);
  670. }
  671. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  672. return TryResolveTypedInst(inst, const_id);
  673. }
  674. case CARBON_KIND(SemIR::InterfaceWitness inst): {
  675. return TryResolveTypedInst(inst);
  676. }
  677. case CARBON_KIND(SemIR::InterfaceType inst): {
  678. return TryResolveTypedInst(inst);
  679. }
  680. case CARBON_KIND(SemIR::IntLiteral inst): {
  681. return TryResolveTypedInst(inst);
  682. }
  683. case CARBON_KIND(SemIR::PointerType inst): {
  684. return TryResolveTypedInst(inst);
  685. }
  686. case CARBON_KIND(SemIR::StructType inst): {
  687. return TryResolveTypedInst(inst, inst_id);
  688. }
  689. case CARBON_KIND(SemIR::StructValue inst): {
  690. return TryResolveTypedInst(inst);
  691. }
  692. case CARBON_KIND(SemIR::TupleType inst): {
  693. return TryResolveTypedInst(inst);
  694. }
  695. case CARBON_KIND(SemIR::TupleValue inst): {
  696. return TryResolveTypedInst(inst);
  697. }
  698. case CARBON_KIND(SemIR::UnboundElementType inst): {
  699. return TryResolveTypedInst(inst);
  700. }
  701. default:
  702. context_.TODO(
  703. SemIR::LocId(AddImportIRInst(inst_id)),
  704. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  705. return {.const_id = SemIR::ConstantId::Error};
  706. }
  707. }
  708. // Produce a resolve result for the given instruction that describes a
  709. // constant value. This should only be used for instructions that describe
  710. // constants, and not for instructions that represent declarations. For a
  711. // declaration, we need an associated location, so AddInstInNoBlock should be
  712. // used instead.
  713. auto ResolveAsUntyped(SemIR::Inst inst) -> ResolveResult {
  714. auto result = TryEvalInst(context_, SemIR::InstId::Invalid, inst);
  715. CARBON_CHECK(result.is_constant()) << inst << " is not constant";
  716. return {.const_id = result};
  717. }
  718. // Same as ResolveAsUntyped, but with an explicit type for convenience.
  719. template <typename InstT>
  720. auto ResolveAs(InstT inst) -> ResolveResult {
  721. return ResolveAsUntyped(inst);
  722. }
  723. auto TryResolveTypedInst(SemIR::AssociatedEntity inst) -> ResolveResult {
  724. auto initial_work = work_stack_.size();
  725. auto type_const_id = GetLocalConstantId(inst.type_id);
  726. if (HasNewWork(initial_work)) {
  727. return ResolveResult::Retry();
  728. }
  729. // Add a lazy reference to the target declaration.
  730. auto decl_id = AddImportRef(
  731. context_, {.ir_id = import_ir_id_, .inst_id = inst.decl_id},
  732. SemIR::BindNameId::Invalid);
  733. return ResolveAs<SemIR::AssociatedEntity>(
  734. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  735. .index = inst.index,
  736. .decl_id = decl_id});
  737. }
  738. auto TryResolveTypedInst(SemIR::AssociatedEntityType inst) -> ResolveResult {
  739. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  740. auto initial_work = work_stack_.size();
  741. auto entity_type_const_id = GetLocalConstantId(inst.entity_type_id);
  742. auto interface_inst_id = GetLocalConstantInstId(
  743. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  744. if (HasNewWork(initial_work)) {
  745. return ResolveResult::Retry();
  746. }
  747. return ResolveAs<SemIR::AssociatedEntityType>(
  748. {.type_id = SemIR::TypeId::TypeType,
  749. .interface_id = context_.insts()
  750. .GetAs<SemIR::InterfaceType>(interface_inst_id)
  751. .interface_id,
  752. .entity_type_id =
  753. context_.GetTypeIdForTypeConstant(entity_type_const_id)});
  754. }
  755. auto TryResolveTypedInst(SemIR::BaseDecl inst, SemIR::InstId import_inst_id)
  756. -> ResolveResult {
  757. auto initial_work = work_stack_.size();
  758. auto type_const_id = GetLocalConstantId(inst.type_id);
  759. auto base_type_const_id = GetLocalConstantId(inst.base_type_id);
  760. if (HasNewWork(initial_work)) {
  761. return ResolveResult::Retry();
  762. }
  763. // Import the instruction in order to update contained base_type_id and
  764. // track the import location.
  765. auto inst_id = context_.AddInstInNoBlock<SemIR::BaseDecl>(
  766. AddImportIRInst(import_inst_id),
  767. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  768. .base_type_id = context_.GetTypeIdForTypeConstant(base_type_const_id),
  769. .index = inst.index});
  770. return {.const_id = context_.constant_values().Get(inst_id)};
  771. }
  772. auto TryResolveTypedInst(SemIR::BindAlias inst) -> ResolveResult {
  773. auto initial_work = work_stack_.size();
  774. auto value_id = GetLocalConstantId(inst.value_id);
  775. if (HasNewWork(initial_work)) {
  776. return ResolveResult::Retry();
  777. }
  778. return {.const_id = value_id};
  779. }
  780. auto TryResolveTypedInst(SemIR::BindSymbolicName inst) -> ResolveResult {
  781. auto initial_work = work_stack_.size();
  782. auto type_id = GetLocalConstantId(inst.type_id);
  783. if (HasNewWork(initial_work)) {
  784. return ResolveResult::Retry();
  785. }
  786. const auto& import_bind_info =
  787. import_ir_.bind_names().Get(inst.bind_name_id);
  788. auto name_id = GetLocalNameId(import_bind_info.name_id);
  789. auto bind_name_id = context_.bind_names().Add(
  790. {.name_id = name_id,
  791. .parent_scope_id = SemIR::NameScopeId::Invalid,
  792. .bind_index = import_bind_info.bind_index});
  793. return ResolveAs<SemIR::BindSymbolicName>(
  794. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  795. .bind_name_id = bind_name_id,
  796. .value_id = SemIR::InstId::Invalid});
  797. }
  798. // Makes an incomplete class. This is necessary even with classes with a
  799. // complete declaration, because things such as `Self` may refer back to the
  800. // type.
  801. auto MakeIncompleteClass(const SemIR::Class& import_class)
  802. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  803. SemIR::ClassDecl class_decl = {.type_id = SemIR::TypeId::TypeType,
  804. .class_id = SemIR::ClassId::Invalid,
  805. .decl_block_id = SemIR::InstBlockId::Empty};
  806. auto class_decl_id = context_.AddPlaceholderInstInNoBlock(
  807. SemIR::LocIdAndInst(AddImportIRInst(import_class.decl_id), class_decl));
  808. // TODO: Support for importing generics.
  809. auto generic_id = GetLocalGeneric(import_class.generic_id);
  810. // Regardless of whether ClassDecl is a complete type, we first need an
  811. // incomplete type so that any references have something to point at.
  812. class_decl.class_id = context_.classes().Add({
  813. .name_id = GetLocalNameId(import_class.name_id),
  814. // These are set in the second pass once we've imported them. Import
  815. // enough of the parameter lists that we know whether this class is a
  816. // generic class and can build the right constant value for it.
  817. // TODO: Add a better way to represent a generic `Class` prior to
  818. // importing the parameters.
  819. .parent_scope_id = SemIR::NameScopeId::Invalid,
  820. .generic_id = generic_id,
  821. .implicit_param_refs_id = import_class.implicit_param_refs_id.is_valid()
  822. ? SemIR::InstBlockId::Empty
  823. : SemIR::InstBlockId::Invalid,
  824. .param_refs_id = import_class.param_refs_id.is_valid()
  825. ? SemIR::InstBlockId::Empty
  826. : SemIR::InstBlockId::Invalid,
  827. .self_type_id = SemIR::TypeId::Invalid,
  828. // These fields can be set immediately.
  829. .decl_id = class_decl_id,
  830. .inheritance_kind = import_class.inheritance_kind,
  831. });
  832. if (import_class.is_generic()) {
  833. class_decl.type_id = context_.GetGenericClassType(class_decl.class_id);
  834. }
  835. // Write the class ID into the ClassDecl.
  836. context_.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  837. auto self_const_id = context_.constant_values().Get(class_decl_id);
  838. return {class_decl.class_id, self_const_id};
  839. }
  840. // Fills out the class definition for an incomplete class.
  841. auto AddClassDefinition(const SemIR::Class& import_class,
  842. SemIR::Class& new_class,
  843. SemIR::ConstantId object_repr_const_id,
  844. SemIR::InstId base_id) -> void {
  845. new_class.definition_id = new_class.decl_id;
  846. new_class.object_repr_id =
  847. context_.GetTypeIdForTypeConstant(object_repr_const_id);
  848. new_class.scope_id = context_.name_scopes().Add(
  849. new_class.decl_id, SemIR::NameId::Invalid, new_class.parent_scope_id);
  850. auto& new_scope = context_.name_scopes().Get(new_class.scope_id);
  851. const auto& import_scope =
  852. import_ir_.name_scopes().Get(import_class.scope_id);
  853. // Push a block so that we can add scoped instructions to it.
  854. context_.inst_block_stack().Push();
  855. AddNameScopeImportRefs(import_scope, new_scope);
  856. new_class.body_block_id = context_.inst_block_stack().Pop();
  857. if (import_class.base_id.is_valid()) {
  858. new_class.base_id = base_id;
  859. // Add the base scope to extended scopes.
  860. auto base_inst_id = context_.types().GetInstId(
  861. context_.insts()
  862. .GetAs<SemIR::BaseDecl>(new_class.base_id)
  863. .base_type_id);
  864. const auto& base_class = context_.classes().Get(
  865. context_.insts().GetAs<SemIR::ClassType>(base_inst_id).class_id);
  866. new_scope.extended_scopes.push_back(base_class.scope_id);
  867. }
  868. CARBON_CHECK(new_scope.extended_scopes.size() ==
  869. import_scope.extended_scopes.size());
  870. }
  871. auto TryResolveTypedInst(SemIR::ClassDecl inst,
  872. SemIR::ConstantId class_const_id) -> ResolveResult {
  873. // TODO: The handling of interfaces repeats a lot with the handling of
  874. // classes, and will likely also be repeated for named constraints and
  875. // choice types. Factor out some of this functionality.
  876. const auto& import_class = import_ir_.classes().Get(inst.class_id);
  877. SemIR::ClassId class_id = SemIR::ClassId::Invalid;
  878. if (!class_const_id.is_valid()) {
  879. // On the first pass, create a forward declaration of the class for any
  880. // recursive references.
  881. std::tie(class_id, class_const_id) = MakeIncompleteClass(import_class);
  882. } else {
  883. // On the second pass, compute the class ID from the constant value of the
  884. // declaration.
  885. auto class_const_inst = context_.insts().Get(
  886. context_.constant_values().GetInstId(class_const_id));
  887. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  888. class_id = class_type->class_id;
  889. } else {
  890. auto generic_class_type =
  891. context_.types().GetAs<SemIR::GenericClassType>(
  892. class_const_inst.type_id());
  893. class_id = generic_class_type.class_id;
  894. }
  895. }
  896. // Load constants for the definition.
  897. auto initial_work = work_stack_.size();
  898. auto parent_scope_id = GetLocalNameScopeId(import_class.parent_scope_id);
  899. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  900. GetLocalParamConstantIds(import_class.implicit_param_refs_id);
  901. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  902. GetLocalParamConstantIds(import_class.param_refs_id);
  903. auto self_const_id = GetLocalConstantId(import_class.self_type_id);
  904. auto object_repr_const_id =
  905. import_class.object_repr_id.is_valid()
  906. ? GetLocalConstantId(import_class.object_repr_id)
  907. : SemIR::ConstantId::Invalid;
  908. auto base_id = import_class.base_id.is_valid()
  909. ? GetLocalConstantInstId(import_class.base_id)
  910. : SemIR::InstId::Invalid;
  911. if (HasNewWork(initial_work)) {
  912. return ResolveResult::Retry(class_const_id);
  913. }
  914. auto& new_class = context_.classes().Get(class_id);
  915. new_class.parent_scope_id = parent_scope_id;
  916. new_class.implicit_param_refs_id = GetLocalParamRefsId(
  917. import_class.implicit_param_refs_id, implicit_param_const_ids);
  918. new_class.param_refs_id =
  919. GetLocalParamRefsId(import_class.param_refs_id, param_const_ids);
  920. new_class.self_type_id = context_.GetTypeIdForTypeConstant(self_const_id);
  921. if (import_class.is_defined()) {
  922. AddClassDefinition(import_class, new_class, object_repr_const_id,
  923. base_id);
  924. }
  925. return {.const_id = class_const_id};
  926. }
  927. auto TryResolveTypedInst(SemIR::ClassType inst) -> ResolveResult {
  928. auto initial_work = work_stack_.size();
  929. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  930. auto class_const_id =
  931. GetLocalConstantId(import_ir_.classes().Get(inst.class_id).decl_id);
  932. auto args = GetLocalGenericInstanceArgs(inst.instance_id);
  933. if (HasNewWork(initial_work)) {
  934. return ResolveResult::Retry();
  935. }
  936. // Find the corresponding class type. For a non-generic class, this is the
  937. // type of the class declaration. For a generic class, build a class type
  938. // referencing this specialization of the generic class.
  939. auto class_const_inst = context_.insts().Get(
  940. context_.constant_values().GetInstId(class_const_id));
  941. if (class_const_inst.Is<SemIR::ClassType>()) {
  942. return {.const_id = class_const_id};
  943. } else {
  944. auto generic_class_type = context_.types().GetAs<SemIR::GenericClassType>(
  945. class_const_inst.type_id());
  946. auto instance_id = GetLocalGenericInstance(inst.instance_id, args);
  947. return ResolveAs<SemIR::ClassType>(
  948. {.type_id = SemIR::TypeId::TypeType,
  949. .class_id = generic_class_type.class_id,
  950. .instance_id = instance_id});
  951. }
  952. }
  953. auto TryResolveTypedInst(SemIR::ConstType inst) -> ResolveResult {
  954. auto initial_work = work_stack_.size();
  955. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  956. auto inner_const_id = GetLocalConstantId(inst.inner_id);
  957. if (HasNewWork(initial_work)) {
  958. return ResolveResult::Retry();
  959. }
  960. auto inner_type_id = context_.GetTypeIdForTypeConstant(inner_const_id);
  961. return ResolveAs<SemIR::ConstType>(
  962. {.type_id = SemIR::TypeId::TypeType, .inner_id = inner_type_id});
  963. }
  964. auto TryResolveTypedInst(SemIR::ExportDecl inst) -> ResolveResult {
  965. auto initial_work = work_stack_.size();
  966. auto value_id = GetLocalConstantId(inst.value_id);
  967. if (HasNewWork(initial_work)) {
  968. return ResolveResult::Retry();
  969. }
  970. return {.const_id = value_id};
  971. }
  972. auto TryResolveTypedInst(SemIR::FieldDecl inst, SemIR::InstId import_inst_id)
  973. -> ResolveResult {
  974. auto initial_work = work_stack_.size();
  975. auto const_id = GetLocalConstantId(inst.type_id);
  976. if (HasNewWork(initial_work)) {
  977. return ResolveResult::Retry();
  978. }
  979. auto inst_id = context_.AddInstInNoBlock<SemIR::FieldDecl>(
  980. AddImportIRInst(import_inst_id),
  981. {.type_id = context_.GetTypeIdForTypeConstant(const_id),
  982. .name_id = GetLocalNameId(inst.name_id),
  983. .index = inst.index});
  984. return {.const_id = context_.constant_values().Get(inst_id)};
  985. }
  986. auto TryResolveTypedInst(SemIR::FunctionDecl inst) -> ResolveResult {
  987. auto initial_work = work_stack_.size();
  988. const auto& function = import_ir_.functions().Get(inst.function_id);
  989. auto return_type_const_id = SemIR::ConstantId::Invalid;
  990. if (function.return_storage_id.is_valid()) {
  991. return_type_const_id =
  992. GetLocalConstantId(function.declared_return_type(import_ir_));
  993. }
  994. auto parent_scope_id = GetLocalNameScopeId(function.parent_scope_id);
  995. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  996. GetLocalParamConstantIds(function.implicit_param_refs_id);
  997. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  998. GetLocalParamConstantIds(function.param_refs_id);
  999. if (HasNewWork(initial_work)) {
  1000. return ResolveResult::Retry();
  1001. }
  1002. // Add the function declaration.
  1003. SemIR::FunctionDecl function_decl = {
  1004. .type_id = SemIR::TypeId::Invalid,
  1005. .function_id = SemIR::FunctionId::Invalid,
  1006. .decl_block_id = SemIR::InstBlockId::Empty};
  1007. // Prefer pointing diagnostics towards a definition.
  1008. auto import_ir_inst_id = AddImportIRInst(function.definition_id.is_valid()
  1009. ? function.definition_id
  1010. : function.decl_id);
  1011. auto function_decl_id = context_.AddPlaceholderInstInNoBlock(
  1012. SemIR::LocIdAndInst(import_ir_inst_id, function_decl));
  1013. // TODO: Implement import for generics.
  1014. auto generic_id = GetLocalGeneric(function.generic_id);
  1015. auto new_return_storage = SemIR::InstId::Invalid;
  1016. if (function.return_storage_id.is_valid()) {
  1017. // Recreate the return slot from scratch.
  1018. // TODO: Once we import function definitions, we'll need to make sure we
  1019. // use the same return storage variable in the declaration and definition.
  1020. new_return_storage = context_.AddInstInNoBlock<SemIR::VarStorage>(
  1021. AddImportIRInst(function.return_storage_id),
  1022. {.type_id = context_.GetTypeIdForTypeConstant(return_type_const_id),
  1023. .name_id = SemIR::NameId::ReturnSlot});
  1024. }
  1025. function_decl.function_id = context_.functions().Add(
  1026. {.name_id = GetLocalNameId(function.name_id),
  1027. .parent_scope_id = parent_scope_id,
  1028. .decl_id = function_decl_id,
  1029. .generic_id = generic_id,
  1030. .implicit_param_refs_id = GetLocalParamRefsId(
  1031. function.implicit_param_refs_id, implicit_param_const_ids),
  1032. .param_refs_id =
  1033. GetLocalParamRefsId(function.param_refs_id, param_const_ids),
  1034. .return_storage_id = new_return_storage,
  1035. .is_extern = function.is_extern,
  1036. .return_slot = function.return_slot,
  1037. .builtin_kind = function.builtin_kind,
  1038. .definition_id = function.definition_id.is_valid()
  1039. ? function_decl_id
  1040. : SemIR::InstId::Invalid});
  1041. function_decl.type_id = context_.GetFunctionType(function_decl.function_id);
  1042. // Write the function ID into the FunctionDecl.
  1043. context_.ReplaceInstBeforeConstantUse(function_decl_id, function_decl);
  1044. return {.const_id = context_.constant_values().Get(function_decl_id)};
  1045. }
  1046. auto TryResolveTypedInst(SemIR::FunctionType inst) -> ResolveResult {
  1047. auto initial_work = work_stack_.size();
  1048. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1049. auto fn_val_id = GetLocalConstantInstId(
  1050. import_ir_.functions().Get(inst.function_id).decl_id);
  1051. if (HasNewWork(initial_work)) {
  1052. return ResolveResult::Retry();
  1053. }
  1054. auto fn_val = context_.insts().Get(fn_val_id);
  1055. CARBON_CHECK(context_.types().Is<SemIR::FunctionType>(fn_val.type_id()));
  1056. return {.const_id = context_.types().GetConstantId(fn_val.type_id())};
  1057. }
  1058. auto TryResolveTypedInst(SemIR::GenericClassType inst) -> ResolveResult {
  1059. auto initial_work = work_stack_.size();
  1060. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1061. auto class_val_id =
  1062. GetLocalConstantInstId(import_ir_.classes().Get(inst.class_id).decl_id);
  1063. if (HasNewWork(initial_work)) {
  1064. return ResolveResult::Retry();
  1065. }
  1066. auto class_val = context_.insts().Get(class_val_id);
  1067. CARBON_CHECK(
  1068. context_.types().Is<SemIR::GenericClassType>(class_val.type_id()));
  1069. return {.const_id = context_.types().GetConstantId(class_val.type_id())};
  1070. }
  1071. auto TryResolveTypedInst(SemIR::GenericInterfaceType inst) -> ResolveResult {
  1072. auto initial_work = work_stack_.size();
  1073. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1074. auto interface_val_id = GetLocalConstantInstId(
  1075. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  1076. if (HasNewWork(initial_work)) {
  1077. return ResolveResult::Retry();
  1078. }
  1079. auto interface_val = context_.insts().Get(interface_val_id);
  1080. CARBON_CHECK(context_.types().Is<SemIR::GenericInterfaceType>(
  1081. interface_val.type_id()));
  1082. return {.const_id =
  1083. context_.types().GetConstantId(interface_val.type_id())};
  1084. }
  1085. auto TryResolveTypedInst(SemIR::ImportRefLoaded /*inst*/,
  1086. SemIR::InstId inst_id) -> ResolveResult {
  1087. auto initial_work = work_stack_.size();
  1088. // Return the constant for the instruction of the imported constant.
  1089. auto constant_id = import_ir_.constant_values().Get(inst_id);
  1090. if (!constant_id.is_valid()) {
  1091. return {.const_id = SemIR::ConstantId::Error};
  1092. }
  1093. if (!constant_id.is_constant()) {
  1094. context_.TODO(inst_id,
  1095. "Non-constant ImportRefLoaded (comes up with var)");
  1096. return {.const_id = SemIR::ConstantId::Error};
  1097. }
  1098. auto new_constant_id =
  1099. GetLocalConstantId(import_ir_.constant_values().GetInstId(constant_id));
  1100. if (HasNewWork(initial_work)) {
  1101. return ResolveResult::Retry();
  1102. }
  1103. return {.const_id = new_constant_id};
  1104. }
  1105. // Make a declaration of an interface. This is done as a separate step from
  1106. // importing the interface definition in order to resolve cycles.
  1107. auto MakeInterfaceDecl(const SemIR::Interface& import_interface)
  1108. -> std::pair<SemIR::InterfaceId, SemIR::ConstantId> {
  1109. SemIR::InterfaceDecl interface_decl = {
  1110. .type_id = SemIR::TypeId::TypeType,
  1111. .interface_id = SemIR::InterfaceId::Invalid,
  1112. .decl_block_id = SemIR::InstBlockId::Empty};
  1113. auto interface_decl_id =
  1114. context_.AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst(
  1115. AddImportIRInst(import_interface.decl_id), interface_decl));
  1116. // TODO: Support for importing generics.
  1117. auto generic_id = GetLocalGeneric(import_interface.generic_id);
  1118. // Start with an incomplete interface.
  1119. interface_decl.interface_id = context_.interfaces().Add({
  1120. .name_id = GetLocalNameId(import_interface.name_id),
  1121. // These are set in the second pass once we've imported them. Import
  1122. // enough of the parameter lists that we know whether this interface is
  1123. // a generic interface and can build the right constant value for it.
  1124. // TODO: Add a better way to represent a generic `Interface` prior to
  1125. // importing the parameters.
  1126. .parent_scope_id = SemIR::NameScopeId::Invalid,
  1127. .generic_id = generic_id,
  1128. .implicit_param_refs_id =
  1129. import_interface.implicit_param_refs_id.is_valid()
  1130. ? SemIR::InstBlockId::Empty
  1131. : SemIR::InstBlockId::Invalid,
  1132. .param_refs_id = import_interface.param_refs_id.is_valid()
  1133. ? SemIR::InstBlockId::Empty
  1134. : SemIR::InstBlockId::Invalid,
  1135. .decl_id = interface_decl_id,
  1136. });
  1137. if (import_interface.is_generic()) {
  1138. interface_decl.type_id =
  1139. context_.GetGenericInterfaceType(interface_decl.interface_id);
  1140. }
  1141. // Write the interface ID into the InterfaceDecl.
  1142. context_.ReplaceInstBeforeConstantUse(interface_decl_id, interface_decl);
  1143. return {interface_decl.interface_id,
  1144. context_.constant_values().Get(interface_decl_id)};
  1145. }
  1146. // Imports the definition for an interface that has been imported as a forward
  1147. // declaration.
  1148. auto AddInterfaceDefinition(const SemIR::Interface& import_interface,
  1149. SemIR::Interface& new_interface,
  1150. SemIR::InstId self_param_id) -> void {
  1151. new_interface.scope_id = context_.name_scopes().Add(
  1152. new_interface.decl_id, SemIR::NameId::Invalid,
  1153. new_interface.parent_scope_id);
  1154. auto& new_scope = context_.name_scopes().Get(new_interface.scope_id);
  1155. const auto& import_scope =
  1156. import_ir_.name_scopes().Get(import_interface.scope_id);
  1157. // Push a block so that we can add scoped instructions to it.
  1158. context_.inst_block_stack().Push();
  1159. AddNameScopeImportRefs(import_scope, new_scope);
  1160. new_interface.associated_entities_id =
  1161. AddAssociatedEntities(import_interface.associated_entities_id);
  1162. new_interface.body_block_id = context_.inst_block_stack().Pop();
  1163. new_interface.self_param_id = self_param_id;
  1164. CARBON_CHECK(import_scope.extended_scopes.empty())
  1165. << "Interfaces don't currently have extended scopes to support.";
  1166. }
  1167. auto TryResolveTypedInst(SemIR::InterfaceDecl inst,
  1168. SemIR::ConstantId interface_const_id)
  1169. -> ResolveResult {
  1170. const auto& import_interface =
  1171. import_ir_.interfaces().Get(inst.interface_id);
  1172. SemIR::InterfaceId interface_id = SemIR::InterfaceId::Invalid;
  1173. if (!interface_const_id.is_valid()) {
  1174. // On the first pass, create a forward declaration of the interface.
  1175. std::tie(interface_id, interface_const_id) =
  1176. MakeInterfaceDecl(import_interface);
  1177. } else {
  1178. // On the second pass, compute the interface ID from the constant value of
  1179. // the declaration.
  1180. auto interface_const_inst = context_.insts().Get(
  1181. context_.constant_values().GetInstId(interface_const_id));
  1182. if (auto interface_type =
  1183. interface_const_inst.TryAs<SemIR::InterfaceType>()) {
  1184. interface_id = interface_type->interface_id;
  1185. } else {
  1186. auto generic_interface_type =
  1187. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1188. interface_const_inst.type_id());
  1189. interface_id = generic_interface_type.interface_id;
  1190. }
  1191. }
  1192. auto initial_work = work_stack_.size();
  1193. auto parent_scope_id =
  1194. GetLocalNameScopeId(import_interface.parent_scope_id);
  1195. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  1196. GetLocalParamConstantIds(import_interface.implicit_param_refs_id);
  1197. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  1198. GetLocalParamConstantIds(import_interface.param_refs_id);
  1199. auto self_param_id = GetLocalConstantInstId(import_interface.self_param_id);
  1200. if (HasNewWork(initial_work)) {
  1201. return ResolveResult::Retry(interface_const_id);
  1202. }
  1203. auto& new_interface = context_.interfaces().Get(interface_id);
  1204. new_interface.parent_scope_id = parent_scope_id;
  1205. new_interface.implicit_param_refs_id = GetLocalParamRefsId(
  1206. import_interface.implicit_param_refs_id, implicit_param_const_ids);
  1207. new_interface.param_refs_id =
  1208. GetLocalParamRefsId(import_interface.param_refs_id, param_const_ids);
  1209. if (import_interface.is_defined()) {
  1210. AddInterfaceDefinition(import_interface, new_interface, self_param_id);
  1211. }
  1212. return {.const_id = interface_const_id};
  1213. }
  1214. auto TryResolveTypedInst(SemIR::InterfaceType inst) -> ResolveResult {
  1215. auto initial_work = work_stack_.size();
  1216. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1217. auto interface_const_id = GetLocalConstantId(
  1218. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  1219. auto args = GetLocalGenericInstanceArgs(inst.instance_id);
  1220. if (HasNewWork(initial_work)) {
  1221. return ResolveResult::Retry();
  1222. }
  1223. // Find the corresponding interface type. For a non-generic interface, this
  1224. // is the type of the interface declaration. For a generic interface, build
  1225. // a interface type referencing this specialization of the generic
  1226. // interface.
  1227. auto interface_const_inst = context_.insts().Get(
  1228. context_.constant_values().GetInstId(interface_const_id));
  1229. if (interface_const_inst.Is<SemIR::InterfaceType>()) {
  1230. return {.const_id = interface_const_id};
  1231. } else {
  1232. auto generic_interface_type =
  1233. context_.types().GetAs<SemIR::GenericInterfaceType>(
  1234. interface_const_inst.type_id());
  1235. auto instance_id = GetLocalGenericInstance(inst.instance_id, args);
  1236. return ResolveAs<SemIR::InterfaceType>(
  1237. {.type_id = SemIR::TypeId::TypeType,
  1238. .interface_id = generic_interface_type.interface_id,
  1239. .instance_id = instance_id});
  1240. }
  1241. }
  1242. auto TryResolveTypedInst(SemIR::InterfaceWitness inst) -> ResolveResult {
  1243. auto initial_work = work_stack_.size();
  1244. auto elements = GetLocalInstBlockContents(inst.elements_id);
  1245. if (HasNewWork(initial_work)) {
  1246. return ResolveResult::Retry();
  1247. }
  1248. auto elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elements);
  1249. return ResolveAs<SemIR::InterfaceWitness>(
  1250. {.type_id = context_.GetBuiltinType(SemIR::BuiltinKind::WitnessType),
  1251. .elements_id = elements_id});
  1252. }
  1253. auto TryResolveTypedInst(SemIR::IntLiteral inst) -> ResolveResult {
  1254. auto initial_work = work_stack_.size();
  1255. auto type_id = GetLocalConstantId(inst.type_id);
  1256. if (HasNewWork(initial_work)) {
  1257. return ResolveResult::Retry();
  1258. }
  1259. return ResolveAs<SemIR::IntLiteral>(
  1260. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1261. .int_id = context_.ints().Add(import_ir_.ints().Get(inst.int_id))});
  1262. }
  1263. auto TryResolveTypedInst(SemIR::PointerType inst) -> ResolveResult {
  1264. auto initial_work = work_stack_.size();
  1265. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1266. auto pointee_const_id = GetLocalConstantId(inst.pointee_id);
  1267. if (HasNewWork(initial_work)) {
  1268. return ResolveResult::Retry();
  1269. }
  1270. auto pointee_type_id = context_.GetTypeIdForTypeConstant(pointee_const_id);
  1271. return ResolveAs<SemIR::PointerType>(
  1272. {.type_id = SemIR::TypeId::TypeType, .pointee_id = pointee_type_id});
  1273. }
  1274. auto TryResolveTypedInst(SemIR::StructType inst, SemIR::InstId import_inst_id)
  1275. -> ResolveResult {
  1276. // Collect all constants first, locating unresolved ones in a single pass.
  1277. auto initial_work = work_stack_.size();
  1278. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1279. auto orig_fields = import_ir_.inst_blocks().Get(inst.fields_id);
  1280. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  1281. field_const_ids.reserve(orig_fields.size());
  1282. for (auto field_id : orig_fields) {
  1283. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1284. field_const_ids.push_back(GetLocalConstantId(field.field_type_id));
  1285. }
  1286. if (HasNewWork(initial_work)) {
  1287. return ResolveResult::Retry();
  1288. }
  1289. // Prepare a vector of fields for GetStructType.
  1290. // TODO: Should we have field constants so that we can deduplicate fields
  1291. // without creating instructions here?
  1292. llvm::SmallVector<SemIR::InstId> fields;
  1293. fields.reserve(orig_fields.size());
  1294. for (auto [field_id, field_const_id] :
  1295. llvm::zip(orig_fields, field_const_ids)) {
  1296. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1297. auto name_id = GetLocalNameId(field.name_id);
  1298. auto field_type_id = context_.GetTypeIdForTypeConstant(field_const_id);
  1299. fields.push_back(context_.AddInstInNoBlock<SemIR::StructTypeField>(
  1300. AddImportIRInst(import_inst_id),
  1301. {.name_id = name_id, .field_type_id = field_type_id}));
  1302. }
  1303. return ResolveAs<SemIR::StructType>(
  1304. {.type_id = SemIR::TypeId::TypeType,
  1305. .fields_id = context_.inst_blocks().AddCanonical(fields)});
  1306. }
  1307. auto TryResolveTypedInst(SemIR::StructValue inst) -> ResolveResult {
  1308. auto initial_work = work_stack_.size();
  1309. auto type_id = GetLocalConstantId(inst.type_id);
  1310. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1311. if (HasNewWork(initial_work)) {
  1312. return ResolveResult::Retry();
  1313. }
  1314. return ResolveAs<SemIR::StructValue>(
  1315. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1316. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1317. }
  1318. auto TryResolveTypedInst(SemIR::TupleType inst) -> ResolveResult {
  1319. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1320. // Collect all constants first, locating unresolved ones in a single pass.
  1321. auto initial_work = work_stack_.size();
  1322. auto orig_elem_type_ids = import_ir_.type_blocks().Get(inst.elements_id);
  1323. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  1324. elem_const_ids.reserve(orig_elem_type_ids.size());
  1325. for (auto elem_type_id : orig_elem_type_ids) {
  1326. elem_const_ids.push_back(GetLocalConstantId(elem_type_id));
  1327. }
  1328. if (HasNewWork(initial_work)) {
  1329. return ResolveResult::Retry();
  1330. }
  1331. // Prepare a vector of the tuple types for GetTupleType.
  1332. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  1333. elem_type_ids.reserve(orig_elem_type_ids.size());
  1334. for (auto elem_const_id : elem_const_ids) {
  1335. elem_type_ids.push_back(context_.GetTypeIdForTypeConstant(elem_const_id));
  1336. }
  1337. return {.const_id = context_.types().GetConstantId(
  1338. context_.GetTupleType(elem_type_ids))};
  1339. }
  1340. auto TryResolveTypedInst(SemIR::TupleValue inst) -> ResolveResult {
  1341. auto initial_work = work_stack_.size();
  1342. auto type_id = GetLocalConstantId(inst.type_id);
  1343. auto elems = GetLocalInstBlockContents(inst.elements_id);
  1344. if (HasNewWork(initial_work)) {
  1345. return ResolveResult::Retry();
  1346. }
  1347. return ResolveAs<SemIR::TupleValue>(
  1348. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  1349. .elements_id = GetLocalCanonicalInstBlockId(inst.elements_id, elems)});
  1350. }
  1351. auto TryResolveTypedInst(SemIR::UnboundElementType inst) -> ResolveResult {
  1352. auto initial_work = work_stack_.size();
  1353. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1354. auto class_const_id = GetLocalConstantId(inst.class_type_id);
  1355. auto elem_const_id = GetLocalConstantId(inst.element_type_id);
  1356. if (HasNewWork(initial_work)) {
  1357. return ResolveResult::Retry();
  1358. }
  1359. return ResolveAs<SemIR::UnboundElementType>(
  1360. {.type_id = SemIR::TypeId::TypeType,
  1361. .class_type_id = context_.GetTypeIdForTypeConstant(class_const_id),
  1362. .element_type_id = context_.GetTypeIdForTypeConstant(elem_const_id)});
  1363. }
  1364. auto import_ir_constant_values() -> SemIR::ConstantValueStore& {
  1365. return context_.import_ir_constant_values()[import_ir_id_.index];
  1366. }
  1367. Context& context_;
  1368. SemIR::ImportIRId import_ir_id_;
  1369. const SemIR::File& import_ir_;
  1370. llvm::SmallVector<Work> work_stack_;
  1371. };
  1372. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  1373. // loaded (including the one pointed at directly by the ImportRef), and the
  1374. // final instruction's type ID.
  1375. //
  1376. // This addresses cases where an ImportRefUnloaded may point at another
  1377. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  1378. // constant-evaluated version of the instruction to work with.
  1379. static auto GetInstForLoad(Context& context,
  1380. SemIR::ImportIRInstId import_ir_inst_id)
  1381. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  1382. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  1383. {}, SemIR::TypeId::Invalid};
  1384. auto& [import_ir_insts, type_id] = result;
  1385. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  1386. // The first ImportIRInst is added directly because the IR doesn't need to be
  1387. // localized.
  1388. import_ir_insts.push_back(import_ir_inst);
  1389. const auto* cursor_ir = context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1390. while (true) {
  1391. auto cursor_inst = cursor_ir->insts().Get(import_ir_inst.inst_id);
  1392. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  1393. if (!import_ref) {
  1394. type_id = cursor_inst.type_id();
  1395. return result;
  1396. }
  1397. import_ir_inst =
  1398. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  1399. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1400. import_ir_insts.push_back({.ir_id = context.GetImportIRId(*cursor_ir),
  1401. .inst_id = import_ir_inst.inst_id});
  1402. }
  1403. }
  1404. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  1405. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  1406. if (!inst) {
  1407. return;
  1408. }
  1409. auto [indirect_insts, load_type_id] =
  1410. GetInstForLoad(context, inst->import_ir_inst_id);
  1411. // The last indirect instruction is the one to resolve. Pop it here because
  1412. // Resolve will assign the constant.
  1413. auto load_ir_inst = indirect_insts.pop_back_val();
  1414. ImportRefResolver resolver(context, load_ir_inst.ir_id);
  1415. auto type_id = resolver.ResolveType(load_type_id);
  1416. auto constant_id = resolver.Resolve(load_ir_inst.inst_id);
  1417. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  1418. // doesn't use ReplaceInstBeforeConstantUse because it would trigger
  1419. // TryEvalInst, which we want to avoid with ImportRefs.
  1420. context.sem_ir().insts().Set(
  1421. inst_id,
  1422. SemIR::ImportRefLoaded{.type_id = type_id,
  1423. .import_ir_inst_id = inst->import_ir_inst_id,
  1424. .bind_name_id = inst->bind_name_id});
  1425. // Store the constant for both the ImportRefLoaded and indirect instructions.
  1426. context.constant_values().Set(inst_id, constant_id);
  1427. for (const auto& import_ir_inst : indirect_insts) {
  1428. context.import_ir_constant_values()[import_ir_inst.ir_id.index].Set(
  1429. import_ir_inst.inst_id, constant_id);
  1430. }
  1431. }
  1432. // Imports the impl `import_impl_id` from the imported IR `import_ir`.
  1433. static auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  1434. const SemIR::File& import_ir,
  1435. SemIR::ImplId import_impl_id) -> void {
  1436. // Resolve the imported impl to a local impl ID.
  1437. ImportRefResolver resolver(context, import_ir_id);
  1438. const auto& import_impl = import_ir.impls().Get(import_impl_id);
  1439. auto self_id = resolver.ResolveType(import_impl.self_id);
  1440. auto constraint_id = resolver.ResolveType(import_impl.constraint_id);
  1441. // Import the definition if the impl is defined.
  1442. // TODO: Do we need to check for multiple definitions?
  1443. auto impl_id = context.impls().LookupOrAdd(self_id, constraint_id);
  1444. if (import_impl.is_defined()) {
  1445. // TODO: Create a scope for the `impl` if necessary.
  1446. // TODO: Consider importing the definition_id.
  1447. auto& impl = context.impls().Get(impl_id);
  1448. impl.witness_id = AddImportRef(
  1449. context, {.ir_id = import_ir_id, .inst_id = import_impl.witness_id},
  1450. SemIR::BindNameId::Invalid);
  1451. }
  1452. }
  1453. // TODO: This doesn't belong in this file. Consider moving the import resolver
  1454. // and this file elsewhere.
  1455. auto ImportImpls(Context& context) -> void {
  1456. for (auto [import_index, import_ir] :
  1457. llvm::enumerate(context.import_irs().array_ref())) {
  1458. if (!import_ir.sem_ir) {
  1459. continue;
  1460. }
  1461. auto import_ir_id = SemIR::ImportIRId(import_index);
  1462. for (auto impl_index : llvm::seq(import_ir.sem_ir->impls().size())) {
  1463. auto impl_id = SemIR::ImplId(impl_index);
  1464. ImportImpl(context, import_ir_id, *import_ir.sem_ir, impl_id);
  1465. }
  1466. }
  1467. }
  1468. } // namespace Carbon::Check