import_ref.cpp 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385
  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});
  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});
  327. }
  328. return const_id;
  329. }
  330. // Returns the ConstantId for a TypeId. Adds unresolved constants to
  331. // work_stack_.
  332. auto GetLocalConstantId(SemIR::TypeId type_id) -> SemIR::ConstantId {
  333. return GetLocalConstantId(import_ir_.types().GetInstId(type_id));
  334. }
  335. // Returns the ConstantId for each parameter's type. Adds unresolved constants
  336. // to work_stack_.
  337. auto GetLocalParamConstantIds(SemIR::InstBlockId param_refs_id)
  338. -> llvm::SmallVector<SemIR::ConstantId> {
  339. llvm::SmallVector<SemIR::ConstantId> const_ids;
  340. if (!param_refs_id.is_valid() ||
  341. param_refs_id == SemIR::InstBlockId::Empty) {
  342. return const_ids;
  343. }
  344. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  345. const_ids.reserve(param_refs.size());
  346. for (auto inst_id : param_refs) {
  347. const_ids.push_back(
  348. GetLocalConstantId(import_ir_.insts().Get(inst_id).type_id()));
  349. // If the parameter is a symbolic binding, build the BindSymbolicName
  350. // constant.
  351. auto bind_id = inst_id;
  352. if (auto addr =
  353. import_ir_.insts().TryGetAs<SemIR::AddrPattern>(bind_id)) {
  354. bind_id = addr->inner_id;
  355. }
  356. GetLocalConstantId(bind_id);
  357. }
  358. return const_ids;
  359. }
  360. // Given a param_refs_id and const_ids from GetLocalParamConstantIds, returns
  361. // a version of param_refs_id localized to the current IR.
  362. auto GetLocalParamRefsId(
  363. SemIR::InstBlockId param_refs_id,
  364. const llvm::SmallVector<SemIR::ConstantId>& const_ids)
  365. -> SemIR::InstBlockId {
  366. if (!param_refs_id.is_valid() ||
  367. param_refs_id == SemIR::InstBlockId::Empty) {
  368. return param_refs_id;
  369. }
  370. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  371. llvm::SmallVector<SemIR::InstId> new_param_refs;
  372. for (auto [ref_id, const_id] : llvm::zip(param_refs, const_ids)) {
  373. // Figure out the param structure. This echoes
  374. // Function::GetParamFromParamRefId.
  375. // TODO: Consider a different parameter handling to simplify import logic.
  376. auto inst = import_ir_.insts().Get(ref_id);
  377. auto addr_inst = inst.TryAs<SemIR::AddrPattern>();
  378. auto bind_id = ref_id;
  379. auto param_id = ref_id;
  380. if (addr_inst) {
  381. bind_id = addr_inst->inner_id;
  382. param_id = bind_id;
  383. inst = import_ir_.insts().Get(bind_id);
  384. }
  385. auto bind_inst = inst.TryAs<SemIR::AnyBindName>();
  386. if (bind_inst) {
  387. param_id = bind_inst->value_id;
  388. inst = import_ir_.insts().Get(param_id);
  389. }
  390. auto param_inst = inst.As<SemIR::Param>();
  391. // Rebuild the param instruction.
  392. auto name_id = GetLocalNameId(param_inst.name_id);
  393. auto type_id = context_.GetTypeIdForTypeConstant(const_id);
  394. auto new_param_id = context_.AddInstInNoBlock<SemIR::Param>(
  395. AddImportIRInst(param_id), {.type_id = type_id, .name_id = name_id});
  396. if (bind_inst) {
  397. switch (bind_inst->kind) {
  398. case SemIR::BindName::Kind: {
  399. auto bind_name_id = context_.bind_names().Add(
  400. {.name_id = name_id,
  401. .enclosing_scope_id = SemIR::NameScopeId::Invalid,
  402. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  403. new_param_id = context_.AddInstInNoBlock<SemIR::BindName>(
  404. AddImportIRInst(bind_id), {.type_id = type_id,
  405. .bind_name_id = bind_name_id,
  406. .value_id = new_param_id});
  407. break;
  408. }
  409. case SemIR::BindSymbolicName::Kind: {
  410. // The symbolic name will be created on first reference, so might
  411. // already exist. Update the value in it to refer to the parameter.
  412. auto new_bind_inst_id = GetLocalConstantId(bind_id).inst_id();
  413. auto new_bind_inst =
  414. context_.insts().GetAs<SemIR::BindSymbolicName>(
  415. new_bind_inst_id);
  416. new_bind_inst.value_id = new_param_id;
  417. // This is not before constant use, but doesn't change the
  418. // constant value of the instruction.
  419. context_.ReplaceInstBeforeConstantUse(new_bind_inst_id,
  420. new_bind_inst);
  421. new_param_id = new_bind_inst_id;
  422. break;
  423. }
  424. default: {
  425. CARBON_FATAL() << "Unexpected kind: " << bind_inst->kind;
  426. }
  427. }
  428. }
  429. if (addr_inst) {
  430. new_param_id = context_.AddInstInNoBlock<SemIR::AddrPattern>(
  431. AddImportIRInst(ref_id),
  432. {.type_id = type_id, .inner_id = new_param_id});
  433. }
  434. new_param_refs.push_back(new_param_id);
  435. }
  436. return context_.inst_blocks().Add(new_param_refs);
  437. }
  438. // Translates a NameId from the import IR to a local NameId.
  439. auto GetLocalNameId(SemIR::NameId import_name_id) -> SemIR::NameId {
  440. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.is_valid()) {
  441. return SemIR::NameId::ForIdentifier(
  442. context_.identifiers().Add(import_ir_.identifiers().Get(ident_id)));
  443. }
  444. return import_name_id;
  445. }
  446. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  447. // unresolved constants to the work stack.
  448. auto GetLocalNameScopeId(SemIR::NameScopeId name_scope_id)
  449. -> SemIR::NameScopeId {
  450. auto [inst_id, inst] =
  451. import_ir_.name_scopes().GetInstIfValid(name_scope_id);
  452. if (!inst) {
  453. // Map scopes that aren't associated with an instruction to invalid
  454. // scopes. For now, such scopes aren't used, and we don't have a good way
  455. // to remap them.
  456. return SemIR::NameScopeId::Invalid;
  457. }
  458. if (inst->Is<SemIR::ImplDecl>()) {
  459. // TODO: Import the scope for an `impl` definition.
  460. return SemIR::NameScopeId::Invalid;
  461. }
  462. auto const_id = GetLocalConstantId(inst_id);
  463. if (!const_id.is_valid()) {
  464. return SemIR::NameScopeId::Invalid;
  465. }
  466. auto name_scope_inst = context_.insts().Get(const_id.inst_id());
  467. CARBON_KIND_SWITCH(name_scope_inst) {
  468. case CARBON_KIND(SemIR::Namespace inst): {
  469. return inst.name_scope_id;
  470. }
  471. case CARBON_KIND(SemIR::ClassType inst): {
  472. return context_.classes().Get(inst.class_id).scope_id;
  473. }
  474. case CARBON_KIND(SemIR::InterfaceType inst): {
  475. return context_.interfaces().Get(inst.interface_id).scope_id;
  476. }
  477. default:
  478. if (const_id == SemIR::ConstantId::Error) {
  479. return SemIR::NameScopeId::Invalid;
  480. }
  481. CARBON_FATAL() << "Unexpected instruction kind for name scope: "
  482. << name_scope_inst;
  483. }
  484. }
  485. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  486. // lookup.
  487. auto AddNameScopeImportRefs(const SemIR::NameScope& import_scope,
  488. SemIR::NameScope& new_scope) -> void {
  489. for (auto [entry_name_id, entry_inst_id] : import_scope.names) {
  490. auto ref_id = AddImportRef(
  491. context_, {.ir_id = import_ir_id_, .inst_id = entry_inst_id},
  492. SemIR::BindNameId::Invalid);
  493. CARBON_CHECK(
  494. new_scope.names.insert({GetLocalNameId(entry_name_id), ref_id})
  495. .second);
  496. }
  497. }
  498. // Given a block ID for a list of associated entities of a witness, returns a
  499. // version localized to the current IR.
  500. auto AddAssociatedEntities(SemIR::InstBlockId associated_entities_id)
  501. -> SemIR::InstBlockId {
  502. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  503. return SemIR::InstBlockId::Empty;
  504. }
  505. auto associated_entities =
  506. import_ir_.inst_blocks().Get(associated_entities_id);
  507. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  508. new_associated_entities.reserve(associated_entities.size());
  509. for (auto inst_id : associated_entities) {
  510. new_associated_entities.push_back(
  511. AddImportRef(context_, {.ir_id = import_ir_id_, .inst_id = inst_id},
  512. SemIR::BindNameId::Invalid));
  513. }
  514. return context_.inst_blocks().Add(new_associated_entities);
  515. }
  516. // Tries to resolve the InstId, returning a constant when ready, or Invalid if
  517. // more has been added to the stack. A similar API is followed for all
  518. // following TryResolveTypedInst helper functions.
  519. //
  520. // `const_id` is Invalid unless we've tried to resolve this instruction
  521. // before, in which case it's the previous result.
  522. //
  523. // TODO: Error is returned when support is missing, but that should go away.
  524. auto TryResolveInst(SemIR::InstId inst_id, SemIR::ConstantId const_id)
  525. -> ResolveResult {
  526. if (inst_id.is_builtin()) {
  527. CARBON_CHECK(!const_id.is_valid());
  528. // Constants for builtins can be directly copied.
  529. return {context_.constant_values().Get(inst_id)};
  530. }
  531. auto untyped_inst = import_ir_.insts().Get(inst_id);
  532. CARBON_KIND_SWITCH(untyped_inst) {
  533. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  534. return TryResolveTypedInst(inst);
  535. }
  536. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  537. return TryResolveTypedInst(inst);
  538. }
  539. case CARBON_KIND(SemIR::BaseDecl inst): {
  540. return TryResolveTypedInst(inst, inst_id);
  541. }
  542. case CARBON_KIND(SemIR::BindAlias inst): {
  543. return TryResolveTypedInst(inst);
  544. }
  545. case CARBON_KIND(SemIR::BindName inst): {
  546. // TODO: This always returns `ConstantId::NotConstant`.
  547. return {TryEvalInst(context_, inst_id, inst)};
  548. }
  549. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  550. return TryResolveTypedInst(inst, inst_id);
  551. }
  552. case CARBON_KIND(SemIR::ClassDecl inst): {
  553. return TryResolveTypedInst(inst, const_id);
  554. }
  555. case CARBON_KIND(SemIR::ClassType inst): {
  556. return TryResolveTypedInst(inst);
  557. }
  558. case CARBON_KIND(SemIR::ConstType inst): {
  559. return TryResolveTypedInst(inst);
  560. }
  561. case CARBON_KIND(SemIR::ExportDecl inst): {
  562. return TryResolveTypedInst(inst);
  563. }
  564. case CARBON_KIND(SemIR::FieldDecl inst): {
  565. return TryResolveTypedInst(inst, inst_id);
  566. }
  567. case CARBON_KIND(SemIR::FunctionDecl inst): {
  568. return TryResolveTypedInst(inst);
  569. }
  570. case CARBON_KIND(SemIR::FunctionType inst): {
  571. return TryResolveTypedInst(inst);
  572. }
  573. case CARBON_KIND(SemIR::GenericClassType inst): {
  574. return TryResolveTypedInst(inst);
  575. }
  576. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  577. return TryResolveTypedInst(inst, inst_id);
  578. }
  579. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  580. return TryResolveTypedInst(inst, const_id);
  581. }
  582. case CARBON_KIND(SemIR::InterfaceWitness inst): {
  583. return TryResolveTypedInst(inst);
  584. }
  585. case CARBON_KIND(SemIR::InterfaceType inst): {
  586. return TryResolveTypedInst(inst);
  587. }
  588. case CARBON_KIND(SemIR::PointerType inst): {
  589. return TryResolveTypedInst(inst);
  590. }
  591. case CARBON_KIND(SemIR::StructType inst): {
  592. return TryResolveTypedInst(inst, inst_id);
  593. }
  594. case CARBON_KIND(SemIR::TupleType inst): {
  595. return TryResolveTypedInst(inst);
  596. }
  597. case CARBON_KIND(SemIR::UnboundElementType inst): {
  598. return TryResolveTypedInst(inst);
  599. }
  600. default:
  601. context_.TODO(
  602. SemIR::LocId(AddImportIRInst(inst_id)),
  603. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  604. return {SemIR::ConstantId::Error};
  605. }
  606. }
  607. auto TryResolveTypedInst(SemIR::AssociatedEntity inst) -> ResolveResult {
  608. auto initial_work = work_stack_.size();
  609. auto type_const_id = GetLocalConstantId(inst.type_id);
  610. if (HasNewWork(initial_work)) {
  611. return ResolveResult::Retry();
  612. }
  613. // Add a lazy reference to the target declaration.
  614. auto decl_id = AddImportRef(
  615. context_, {.ir_id = import_ir_id_, .inst_id = inst.decl_id},
  616. SemIR::BindNameId::Invalid);
  617. auto inst_id = context_.AddInstInNoBlock<SemIR::AssociatedEntity>(
  618. AddImportIRInst(inst.decl_id),
  619. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  620. .index = inst.index,
  621. .decl_id = decl_id});
  622. return {context_.constant_values().Get(inst_id)};
  623. }
  624. auto TryResolveTypedInst(SemIR::AssociatedEntityType inst) -> ResolveResult {
  625. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  626. auto initial_work = work_stack_.size();
  627. auto entity_type_const_id = GetLocalConstantId(inst.entity_type_id);
  628. auto interface_const_id = GetLocalConstantId(
  629. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  630. if (HasNewWork(initial_work)) {
  631. return ResolveResult::Retry();
  632. }
  633. // TODO: Should this track the source?
  634. auto inst_id = context_.AddInstInNoBlock(
  635. SemIR::LocIdAndInst::NoLoc(SemIR::AssociatedEntityType{
  636. SemIR::TypeId::TypeType,
  637. context_.insts()
  638. .GetAs<SemIR::InterfaceType>(interface_const_id.inst_id())
  639. .interface_id,
  640. context_.GetTypeIdForTypeConstant(entity_type_const_id)}));
  641. return {context_.constant_values().Get(inst_id)};
  642. }
  643. auto TryResolveTypedInst(SemIR::BaseDecl inst, SemIR::InstId import_inst_id)
  644. -> ResolveResult {
  645. auto initial_work = work_stack_.size();
  646. auto type_const_id = GetLocalConstantId(inst.type_id);
  647. auto base_type_const_id = GetLocalConstantId(inst.base_type_id);
  648. if (HasNewWork(initial_work)) {
  649. return ResolveResult::Retry();
  650. }
  651. // Import the instruction in order to update contained base_type_id.
  652. auto inst_id = context_.AddInstInNoBlock<SemIR::BaseDecl>(
  653. AddImportIRInst(import_inst_id),
  654. {.type_id = context_.GetTypeIdForTypeConstant(type_const_id),
  655. .base_type_id = context_.GetTypeIdForTypeConstant(base_type_const_id),
  656. .index = inst.index});
  657. return {context_.constant_values().Get(inst_id)};
  658. }
  659. auto TryResolveTypedInst(SemIR::BindAlias inst) -> ResolveResult {
  660. auto initial_work = work_stack_.size();
  661. auto value_id = GetLocalConstantId(inst.value_id);
  662. if (HasNewWork(initial_work)) {
  663. return ResolveResult::Retry();
  664. }
  665. return {value_id};
  666. }
  667. auto TryResolveTypedInst(SemIR::BindSymbolicName inst,
  668. SemIR::InstId import_inst_id) -> ResolveResult {
  669. auto initial_work = work_stack_.size();
  670. auto type_id = GetLocalConstantId(inst.type_id);
  671. if (HasNewWork(initial_work)) {
  672. return ResolveResult::Retry();
  673. }
  674. const auto& import_bind_info =
  675. import_ir_.bind_names().Get(inst.bind_name_id);
  676. auto name_id = GetLocalNameId(import_bind_info.name_id);
  677. auto bind_name_id = context_.bind_names().Add(
  678. {.name_id = name_id,
  679. .enclosing_scope_id = SemIR::NameScopeId::Invalid,
  680. .bind_index = import_bind_info.bind_index});
  681. auto new_bind_id = context_.AddInstInNoBlock<SemIR::BindSymbolicName>(
  682. AddImportIRInst(import_inst_id),
  683. {.type_id = context_.GetTypeIdForTypeConstant(type_id),
  684. .bind_name_id = bind_name_id,
  685. .value_id = SemIR::InstId::Invalid});
  686. return {context_.constant_values().Get(new_bind_id)};
  687. }
  688. // Makes an incomplete class. This is necessary even with classes with a
  689. // complete declaration, because things such as `Self` may refer back to the
  690. // type.
  691. auto MakeIncompleteClass(const SemIR::Class& import_class)
  692. -> std::pair<SemIR::ClassId, SemIR::ConstantId> {
  693. auto class_decl =
  694. SemIR::ClassDecl{SemIR::TypeId::TypeType, SemIR::ClassId::Invalid,
  695. SemIR::InstBlockId::Empty};
  696. auto class_decl_id = context_.AddPlaceholderInstInNoBlock(
  697. SemIR::LocIdAndInst(AddImportIRInst(import_class.decl_id), class_decl));
  698. // Regardless of whether ClassDecl is a complete type, we first need an
  699. // incomplete type so that any references have something to point at.
  700. class_decl.class_id = context_.classes().Add({
  701. .name_id = GetLocalNameId(import_class.name_id),
  702. // These are set in the second pass once we've imported them. Import
  703. // enough of the parameter lists that we know whether this class is a
  704. // generic class and can build the right constant value for it.
  705. // TODO: Add a better way to represent a generic `Class` prior to
  706. // importing the parameters.
  707. .enclosing_scope_id = SemIR::NameScopeId::Invalid,
  708. .implicit_param_refs_id = import_class.implicit_param_refs_id.is_valid()
  709. ? SemIR::InstBlockId::Empty
  710. : SemIR::InstBlockId::Invalid,
  711. .param_refs_id = import_class.param_refs_id.is_valid()
  712. ? SemIR::InstBlockId::Empty
  713. : SemIR::InstBlockId::Invalid,
  714. .self_type_id = SemIR::TypeId::Invalid,
  715. // These fields can be set immediately.
  716. .decl_id = class_decl_id,
  717. .inheritance_kind = import_class.inheritance_kind,
  718. });
  719. if (import_class.is_generic()) {
  720. class_decl.type_id = context_.GetGenericClassType(class_decl.class_id);
  721. }
  722. // Write the class ID into the ClassDecl.
  723. context_.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  724. auto self_const_id = context_.constant_values().Get(class_decl_id);
  725. return {class_decl.class_id, self_const_id};
  726. }
  727. // Fills out the class definition for an incomplete class.
  728. auto AddClassDefinition(const SemIR::Class& import_class,
  729. SemIR::Class& new_class,
  730. SemIR::ConstantId object_repr_const_id,
  731. SemIR::ConstantId base_const_id) -> void {
  732. new_class.definition_id = new_class.decl_id;
  733. new_class.object_repr_id =
  734. context_.GetTypeIdForTypeConstant(object_repr_const_id);
  735. new_class.scope_id =
  736. context_.name_scopes().Add(new_class.decl_id, SemIR::NameId::Invalid,
  737. new_class.enclosing_scope_id);
  738. auto& new_scope = context_.name_scopes().Get(new_class.scope_id);
  739. const auto& import_scope =
  740. import_ir_.name_scopes().Get(import_class.scope_id);
  741. // Push a block so that we can add scoped instructions to it.
  742. context_.inst_block_stack().Push();
  743. AddNameScopeImportRefs(import_scope, new_scope);
  744. new_class.body_block_id = context_.inst_block_stack().Pop();
  745. if (import_class.base_id.is_valid()) {
  746. new_class.base_id = base_const_id.inst_id();
  747. // Add the base scope to extended scopes.
  748. auto base_inst_id = context_.types().GetInstId(
  749. context_.insts()
  750. .GetAs<SemIR::BaseDecl>(new_class.base_id)
  751. .base_type_id);
  752. const auto& base_class = context_.classes().Get(
  753. context_.insts().GetAs<SemIR::ClassType>(base_inst_id).class_id);
  754. new_scope.extended_scopes.push_back(base_class.scope_id);
  755. }
  756. CARBON_CHECK(new_scope.extended_scopes.size() ==
  757. import_scope.extended_scopes.size());
  758. }
  759. auto TryResolveTypedInst(SemIR::ClassDecl inst,
  760. SemIR::ConstantId class_const_id) -> ResolveResult {
  761. const auto& import_class = import_ir_.classes().Get(inst.class_id);
  762. SemIR::ClassId class_id = SemIR::ClassId::Invalid;
  763. if (!class_const_id.is_valid()) {
  764. // On the first pass, create a forward declaration of the class for any
  765. // recursive references.
  766. std::tie(class_id, class_const_id) = MakeIncompleteClass(import_class);
  767. } else {
  768. // On the second pass, compute the class ID from the constant value of the
  769. // declaration.
  770. auto class_const_inst = context_.insts().Get(class_const_id.inst_id());
  771. if (auto class_type = class_const_inst.TryAs<SemIR::ClassType>()) {
  772. class_id = class_type->class_id;
  773. } else {
  774. auto generic_class_type =
  775. context_.types().GetAs<SemIR::GenericClassType>(
  776. class_const_inst.type_id());
  777. class_id = generic_class_type.class_id;
  778. }
  779. }
  780. // Load constants for the definition.
  781. auto initial_work = work_stack_.size();
  782. auto enclosing_scope_id =
  783. GetLocalNameScopeId(import_class.enclosing_scope_id);
  784. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  785. GetLocalParamConstantIds(import_class.implicit_param_refs_id);
  786. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  787. GetLocalParamConstantIds(import_class.param_refs_id);
  788. auto self_const_id = GetLocalConstantId(import_class.self_type_id);
  789. auto object_repr_const_id =
  790. import_class.object_repr_id.is_valid()
  791. ? GetLocalConstantId(import_class.object_repr_id)
  792. : SemIR::ConstantId::Invalid;
  793. auto base_const_id = import_class.base_id.is_valid()
  794. ? GetLocalConstantId(import_class.base_id)
  795. : SemIR::ConstantId::Invalid;
  796. if (HasNewWork(initial_work)) {
  797. return ResolveResult::Retry(class_const_id);
  798. }
  799. auto& new_class = context_.classes().Get(class_id);
  800. new_class.enclosing_scope_id = enclosing_scope_id;
  801. new_class.implicit_param_refs_id = GetLocalParamRefsId(
  802. import_class.implicit_param_refs_id, implicit_param_const_ids);
  803. new_class.param_refs_id =
  804. GetLocalParamRefsId(import_class.param_refs_id, param_const_ids);
  805. new_class.self_type_id = context_.GetTypeIdForTypeConstant(self_const_id);
  806. if (import_class.is_defined()) {
  807. AddClassDefinition(import_class, new_class, object_repr_const_id,
  808. base_const_id);
  809. }
  810. return {class_const_id};
  811. }
  812. auto TryResolveTypedInst(SemIR::ClassType inst) -> ResolveResult {
  813. auto initial_work = work_stack_.size();
  814. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  815. auto class_const_id =
  816. GetLocalConstantId(import_ir_.classes().Get(inst.class_id).decl_id);
  817. if (HasNewWork(initial_work)) {
  818. return ResolveResult::Retry();
  819. }
  820. return {class_const_id};
  821. }
  822. auto TryResolveTypedInst(SemIR::ConstType inst) -> ResolveResult {
  823. auto initial_work = work_stack_.size();
  824. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  825. auto inner_const_id = GetLocalConstantId(inst.inner_id);
  826. if (HasNewWork(initial_work)) {
  827. return ResolveResult::Retry();
  828. }
  829. auto inner_type_id = context_.GetTypeIdForTypeConstant(inner_const_id);
  830. // TODO: Should ConstType have a wrapper for this similar to the others?
  831. return {
  832. TryEvalInst(context_, SemIR::InstId::Invalid,
  833. SemIR::ConstType{SemIR::TypeId::TypeType, inner_type_id})};
  834. }
  835. auto TryResolveTypedInst(SemIR::ExportDecl inst) -> ResolveResult {
  836. auto initial_work = work_stack_.size();
  837. auto value_id = GetLocalConstantId(inst.value_id);
  838. if (HasNewWork(initial_work)) {
  839. return ResolveResult::Retry();
  840. }
  841. return {value_id};
  842. }
  843. auto TryResolveTypedInst(SemIR::FieldDecl inst, SemIR::InstId import_inst_id)
  844. -> ResolveResult {
  845. auto initial_work = work_stack_.size();
  846. auto const_id = GetLocalConstantId(inst.type_id);
  847. if (HasNewWork(initial_work)) {
  848. return ResolveResult::Retry();
  849. }
  850. auto inst_id = context_.AddInstInNoBlock<SemIR::FieldDecl>(
  851. AddImportIRInst(import_inst_id),
  852. {.type_id = context_.GetTypeIdForTypeConstant(const_id),
  853. .name_id = GetLocalNameId(inst.name_id),
  854. .index = inst.index});
  855. return {context_.constant_values().Get(inst_id)};
  856. }
  857. auto TryResolveTypedInst(SemIR::FunctionDecl inst) -> ResolveResult {
  858. auto initial_work = work_stack_.size();
  859. const auto& function = import_ir_.functions().Get(inst.function_id);
  860. auto return_type_const_id = SemIR::ConstantId::Invalid;
  861. if (function.return_type_id.is_valid()) {
  862. return_type_const_id = GetLocalConstantId(function.return_type_id);
  863. }
  864. auto enclosing_scope_id = GetLocalNameScopeId(function.enclosing_scope_id);
  865. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  866. GetLocalParamConstantIds(function.implicit_param_refs_id);
  867. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  868. GetLocalParamConstantIds(function.param_refs_id);
  869. if (HasNewWork(initial_work)) {
  870. return ResolveResult::Retry();
  871. }
  872. // Add the function declaration.
  873. auto function_decl =
  874. SemIR::FunctionDecl{SemIR::TypeId::Invalid, SemIR::FunctionId::Invalid,
  875. SemIR::InstBlockId::Empty};
  876. // Prefer pointing diagnostics towards a definition.
  877. auto import_ir_inst_id = AddImportIRInst(function.definition_id.is_valid()
  878. ? function.definition_id
  879. : function.decl_id);
  880. auto function_decl_id = context_.AddPlaceholderInstInNoBlock(
  881. SemIR::LocIdAndInst(import_ir_inst_id, function_decl));
  882. auto new_return_type_id =
  883. return_type_const_id.is_valid()
  884. ? context_.GetTypeIdForTypeConstant(return_type_const_id)
  885. : SemIR::TypeId::Invalid;
  886. auto new_return_storage = SemIR::InstId::Invalid;
  887. if (function.return_storage_id.is_valid()) {
  888. // Recreate the return slot from scratch.
  889. // TODO: Once we import function definitions, we'll need to make sure we
  890. // use the same return storage variable in the declaration and definition.
  891. new_return_storage = context_.AddInstInNoBlock<SemIR::VarStorage>(
  892. AddImportIRInst(function.return_storage_id),
  893. {.type_id = new_return_type_id,
  894. .name_id = SemIR::NameId::ReturnSlot});
  895. }
  896. function_decl.function_id = context_.functions().Add(
  897. {.name_id = GetLocalNameId(function.name_id),
  898. .enclosing_scope_id = enclosing_scope_id,
  899. .decl_id = function_decl_id,
  900. .implicit_param_refs_id = GetLocalParamRefsId(
  901. function.implicit_param_refs_id, implicit_param_const_ids),
  902. .param_refs_id =
  903. GetLocalParamRefsId(function.param_refs_id, param_const_ids),
  904. .return_type_id = new_return_type_id,
  905. .return_storage_id = new_return_storage,
  906. .is_extern = function.is_extern,
  907. .return_slot = function.return_slot,
  908. .builtin_kind = function.builtin_kind,
  909. .definition_id = function.definition_id.is_valid()
  910. ? function_decl_id
  911. : SemIR::InstId::Invalid});
  912. function_decl.type_id = context_.GetFunctionType(function_decl.function_id);
  913. // Write the function ID into the FunctionDecl.
  914. context_.ReplaceInstBeforeConstantUse(function_decl_id, function_decl);
  915. return {context_.constant_values().Get(function_decl_id)};
  916. }
  917. auto TryResolveTypedInst(SemIR::FunctionType inst) -> ResolveResult {
  918. auto initial_work = work_stack_.size();
  919. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  920. auto fn_const_id = GetLocalConstantId(
  921. import_ir_.functions().Get(inst.function_id).decl_id);
  922. if (HasNewWork(initial_work)) {
  923. return ResolveResult::Retry();
  924. }
  925. auto fn_val = context_.insts().Get(fn_const_id.inst_id());
  926. CARBON_CHECK(context_.types().Is<SemIR::FunctionType>(fn_val.type_id()));
  927. return {context_.types().GetConstantId(fn_val.type_id())};
  928. }
  929. auto TryResolveTypedInst(SemIR::GenericClassType inst) -> ResolveResult {
  930. auto initial_work = work_stack_.size();
  931. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  932. auto class_const_id =
  933. GetLocalConstantId(import_ir_.classes().Get(inst.class_id).decl_id);
  934. if (HasNewWork(initial_work)) {
  935. return ResolveResult::Retry();
  936. }
  937. auto class_val = context_.insts().Get(class_const_id.inst_id());
  938. CARBON_CHECK(
  939. context_.types().Is<SemIR::GenericClassType>(class_val.type_id()));
  940. return {context_.types().GetConstantId(class_val.type_id())};
  941. }
  942. auto TryResolveTypedInst(SemIR::ImportRefLoaded /*inst*/,
  943. SemIR::InstId inst_id) -> ResolveResult {
  944. auto initial_work = work_stack_.size();
  945. // Return the constant for the instruction of the imported constant.
  946. auto constant_id = import_ir_.constant_values().Get(inst_id);
  947. if (!constant_id.is_valid()) {
  948. return {SemIR::ConstantId::Error};
  949. }
  950. if (!constant_id.is_constant()) {
  951. context_.TODO(inst_id,
  952. "Non-constant ImportRefLoaded (comes up with var)");
  953. return {SemIR::ConstantId::Error};
  954. }
  955. auto new_constant_id = GetLocalConstantId(constant_id.inst_id());
  956. if (HasNewWork(initial_work)) {
  957. return ResolveResult::Retry();
  958. }
  959. return {new_constant_id};
  960. }
  961. // Make a declaration of an interface. This is done as a separate step from
  962. // importing the interface definition in order to resolve cycles.
  963. auto MakeInterfaceDecl(const SemIR::Interface& import_interface)
  964. -> SemIR::ConstantId {
  965. auto interface_decl = SemIR::InterfaceDecl{SemIR::TypeId::TypeType,
  966. SemIR::InterfaceId::Invalid,
  967. SemIR::InstBlockId::Empty};
  968. auto interface_decl_id =
  969. context_.AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst(
  970. AddImportIRInst(import_interface.decl_id), interface_decl));
  971. // Start with an incomplete interface.
  972. SemIR::Interface new_interface = {
  973. .name_id = GetLocalNameId(import_interface.name_id),
  974. // Set in the second pass once we've imported it.
  975. .enclosing_scope_id = SemIR::NameScopeId::Invalid,
  976. .decl_id = interface_decl_id,
  977. };
  978. // Write the interface ID into the InterfaceDecl.
  979. interface_decl.interface_id = context_.interfaces().Add(new_interface);
  980. context_.ReplaceInstBeforeConstantUse(interface_decl_id, interface_decl);
  981. // Set the constant value for the imported interface.
  982. return context_.constant_values().Get(interface_decl_id);
  983. }
  984. // Imports the definition for an interface that has been imported as a forward
  985. // declaration.
  986. auto AddInterfaceDefinition(const SemIR::Interface& import_interface,
  987. SemIR::Interface& new_interface,
  988. SemIR::ConstantId self_param_id) -> void {
  989. new_interface.scope_id = context_.name_scopes().Add(
  990. new_interface.decl_id, SemIR::NameId::Invalid,
  991. new_interface.enclosing_scope_id);
  992. auto& new_scope = context_.name_scopes().Get(new_interface.scope_id);
  993. const auto& import_scope =
  994. import_ir_.name_scopes().Get(import_interface.scope_id);
  995. // Push a block so that we can add scoped instructions to it.
  996. context_.inst_block_stack().Push();
  997. AddNameScopeImportRefs(import_scope, new_scope);
  998. new_interface.associated_entities_id =
  999. AddAssociatedEntities(import_interface.associated_entities_id);
  1000. new_interface.body_block_id = context_.inst_block_stack().Pop();
  1001. new_interface.self_param_id = self_param_id.inst_id();
  1002. CARBON_CHECK(import_scope.extended_scopes.empty())
  1003. << "Interfaces don't currently have extended scopes to support.";
  1004. }
  1005. auto TryResolveTypedInst(SemIR::InterfaceDecl inst,
  1006. SemIR::ConstantId interface_const_id)
  1007. -> ResolveResult {
  1008. const auto& import_interface =
  1009. import_ir_.interfaces().Get(inst.interface_id);
  1010. // On the first pass, create a forward declaration of the interface.
  1011. if (!interface_const_id.is_valid()) {
  1012. interface_const_id = MakeInterfaceDecl(import_interface);
  1013. }
  1014. auto initial_work = work_stack_.size();
  1015. auto enclosing_scope_id =
  1016. GetLocalNameScopeId(import_interface.enclosing_scope_id);
  1017. auto self_param_id = GetLocalConstantId(import_interface.self_param_id);
  1018. if (HasNewWork(initial_work)) {
  1019. return ResolveResult::Retry(interface_const_id);
  1020. }
  1021. auto& new_interface = context_.interfaces().Get(
  1022. context_.insts()
  1023. .GetAs<SemIR::InterfaceType>(interface_const_id.inst_id())
  1024. .interface_id);
  1025. new_interface.enclosing_scope_id = enclosing_scope_id;
  1026. if (import_interface.is_defined()) {
  1027. AddInterfaceDefinition(import_interface, new_interface, self_param_id);
  1028. }
  1029. return {interface_const_id};
  1030. }
  1031. auto TryResolveTypedInst(SemIR::InterfaceType inst) -> ResolveResult {
  1032. auto initial_work = work_stack_.size();
  1033. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1034. auto interface_const_id = GetLocalConstantId(
  1035. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  1036. if (HasNewWork(initial_work)) {
  1037. return ResolveResult::Retry();
  1038. }
  1039. return {interface_const_id};
  1040. }
  1041. auto TryResolveTypedInst(SemIR::InterfaceWitness inst) -> ResolveResult {
  1042. auto initial_work = work_stack_.size();
  1043. llvm::SmallVector<SemIR::InstId> elements;
  1044. auto import_elements = import_ir_.inst_blocks().Get(inst.elements_id);
  1045. elements.reserve(import_elements.size());
  1046. for (auto import_elem_id : import_elements) {
  1047. if (auto const_id = GetLocalConstantId(import_elem_id);
  1048. const_id.is_valid()) {
  1049. elements.push_back(const_id.inst_id());
  1050. }
  1051. }
  1052. if (HasNewWork(initial_work)) {
  1053. return ResolveResult::Retry();
  1054. }
  1055. CARBON_CHECK(elements.size() == import_elements.size())
  1056. << "Failed to import an element without adding new work.";
  1057. auto elements_id = context_.inst_blocks().Add(elements);
  1058. return {TryEvalInst(
  1059. context_, SemIR::InstId::Invalid,
  1060. SemIR::InterfaceWitness{
  1061. context_.GetBuiltinType(SemIR::BuiltinKind::WitnessType),
  1062. elements_id})};
  1063. }
  1064. auto TryResolveTypedInst(SemIR::PointerType inst) -> ResolveResult {
  1065. auto initial_work = work_stack_.size();
  1066. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1067. auto pointee_const_id = GetLocalConstantId(inst.pointee_id);
  1068. if (HasNewWork(initial_work)) {
  1069. return ResolveResult::Retry();
  1070. }
  1071. auto pointee_type_id = context_.GetTypeIdForTypeConstant(pointee_const_id);
  1072. return {context_.types().GetConstantId(
  1073. context_.GetPointerType(pointee_type_id))};
  1074. }
  1075. auto TryResolveTypedInst(SemIR::StructType inst, SemIR::InstId import_inst_id)
  1076. -> ResolveResult {
  1077. // Collect all constants first, locating unresolved ones in a single pass.
  1078. auto initial_work = work_stack_.size();
  1079. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1080. auto orig_fields = import_ir_.inst_blocks().Get(inst.fields_id);
  1081. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  1082. field_const_ids.reserve(orig_fields.size());
  1083. for (auto field_id : orig_fields) {
  1084. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1085. field_const_ids.push_back(GetLocalConstantId(field.field_type_id));
  1086. }
  1087. if (HasNewWork(initial_work)) {
  1088. return ResolveResult::Retry();
  1089. }
  1090. // Prepare a vector of fields for GetStructType.
  1091. // TODO: Should we have field constants so that we can deduplicate fields
  1092. // without creating instructions here?
  1093. llvm::SmallVector<SemIR::InstId> fields;
  1094. fields.reserve(orig_fields.size());
  1095. for (auto [field_id, field_const_id] :
  1096. llvm::zip(orig_fields, field_const_ids)) {
  1097. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  1098. auto name_id = GetLocalNameId(field.name_id);
  1099. auto field_type_id = context_.GetTypeIdForTypeConstant(field_const_id);
  1100. fields.push_back(context_.AddInstInNoBlock<SemIR::StructTypeField>(
  1101. AddImportIRInst(import_inst_id),
  1102. {.name_id = name_id, .field_type_id = field_type_id}));
  1103. }
  1104. return {context_.types().GetConstantId(
  1105. context_.GetStructType(context_.inst_blocks().Add(fields)))};
  1106. }
  1107. auto TryResolveTypedInst(SemIR::TupleType inst) -> ResolveResult {
  1108. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1109. // Collect all constants first, locating unresolved ones in a single pass.
  1110. auto initial_work = work_stack_.size();
  1111. auto orig_elem_type_ids = import_ir_.type_blocks().Get(inst.elements_id);
  1112. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  1113. elem_const_ids.reserve(orig_elem_type_ids.size());
  1114. for (auto elem_type_id : orig_elem_type_ids) {
  1115. elem_const_ids.push_back(GetLocalConstantId(elem_type_id));
  1116. }
  1117. if (HasNewWork(initial_work)) {
  1118. return ResolveResult::Retry();
  1119. }
  1120. // Prepare a vector of the tuple types for GetTupleType.
  1121. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  1122. elem_type_ids.reserve(orig_elem_type_ids.size());
  1123. for (auto elem_const_id : elem_const_ids) {
  1124. elem_type_ids.push_back(context_.GetTypeIdForTypeConstant(elem_const_id));
  1125. }
  1126. return {
  1127. context_.types().GetConstantId(context_.GetTupleType(elem_type_ids))};
  1128. }
  1129. auto TryResolveTypedInst(SemIR::UnboundElementType inst) -> ResolveResult {
  1130. auto initial_work = work_stack_.size();
  1131. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  1132. auto class_const_id = GetLocalConstantId(inst.class_type_id);
  1133. auto elem_const_id = GetLocalConstantId(inst.element_type_id);
  1134. if (HasNewWork(initial_work)) {
  1135. return ResolveResult::Retry();
  1136. }
  1137. return {context_.types().GetConstantId(context_.GetUnboundElementType(
  1138. context_.GetTypeIdForTypeConstant(class_const_id),
  1139. context_.GetTypeIdForTypeConstant(elem_const_id)))};
  1140. }
  1141. auto import_ir_constant_values() -> SemIR::ConstantValueStore& {
  1142. return context_.import_ir_constant_values()[import_ir_id_.index];
  1143. }
  1144. Context& context_;
  1145. SemIR::ImportIRId import_ir_id_;
  1146. const SemIR::File& import_ir_;
  1147. llvm::SmallVector<Work> work_stack_;
  1148. };
  1149. // Returns a list of ImportIRInsts equivalent to the ImportRef currently being
  1150. // loaded (including the one pointed at directly by the ImportRef), and the
  1151. // final instruction's type ID.
  1152. //
  1153. // This addresses cases where an ImportRefUnloaded may point at another
  1154. // ImportRefUnloaded. The ImportRefResolver requires a SemIR with a
  1155. // constant-evaluated version of the instruction to work with.
  1156. static auto GetInstForLoad(Context& context,
  1157. SemIR::ImportIRInstId import_ir_inst_id)
  1158. -> std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> {
  1159. std::pair<llvm::SmallVector<SemIR::ImportIRInst>, SemIR::TypeId> result = {
  1160. {}, SemIR::TypeId::Invalid};
  1161. auto& [import_ir_insts, type_id] = result;
  1162. auto import_ir_inst = context.import_ir_insts().Get(import_ir_inst_id);
  1163. // The first ImportIRInst is added directly because the IR doesn't need to be
  1164. // localized.
  1165. import_ir_insts.push_back(import_ir_inst);
  1166. const auto* cursor_ir = context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1167. while (true) {
  1168. auto cursor_inst = cursor_ir->insts().Get(import_ir_inst.inst_id);
  1169. auto import_ref = cursor_inst.TryAs<SemIR::ImportRefUnloaded>();
  1170. if (!import_ref) {
  1171. type_id = cursor_inst.type_id();
  1172. return result;
  1173. }
  1174. import_ir_inst =
  1175. cursor_ir->import_ir_insts().Get(import_ref->import_ir_inst_id);
  1176. cursor_ir = cursor_ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  1177. import_ir_insts.push_back({.ir_id = context.GetImportIRId(*cursor_ir),
  1178. .inst_id = import_ir_inst.inst_id});
  1179. }
  1180. }
  1181. auto LoadImportRef(Context& context, SemIR::InstId inst_id) -> void {
  1182. auto inst = context.insts().TryGetAs<SemIR::ImportRefUnloaded>(inst_id);
  1183. if (!inst) {
  1184. return;
  1185. }
  1186. auto [indirect_insts, load_type_id] =
  1187. GetInstForLoad(context, inst->import_ir_inst_id);
  1188. // The last indirect instruction is the one to resolve. Pop it here because
  1189. // Resolve will assign the constant.
  1190. auto load_ir_inst = indirect_insts.pop_back_val();
  1191. ImportRefResolver resolver(context, load_ir_inst.ir_id);
  1192. auto type_id = resolver.ResolveType(load_type_id);
  1193. auto constant_id = resolver.Resolve(load_ir_inst.inst_id);
  1194. // Replace the ImportRefUnloaded instruction with ImportRefLoaded. This
  1195. // doesn't use ReplaceInstBeforeConstantUse because it would trigger
  1196. // TryEvalInst, which we want to avoid with ImportRefs.
  1197. context.sem_ir().insts().Set(
  1198. inst_id,
  1199. SemIR::ImportRefLoaded{.type_id = type_id,
  1200. .import_ir_inst_id = inst->import_ir_inst_id,
  1201. .bind_name_id = inst->bind_name_id});
  1202. // Store the constant for both the ImportRefLoaded and indirect instructions.
  1203. context.constant_values().Set(inst_id, constant_id);
  1204. for (const auto& import_ir_inst : indirect_insts) {
  1205. context.import_ir_constant_values()[import_ir_inst.ir_id.index].Set(
  1206. import_ir_inst.inst_id, constant_id);
  1207. }
  1208. }
  1209. // Imports the impl `import_impl_id` from the imported IR `import_ir`.
  1210. static auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  1211. const SemIR::File& import_ir,
  1212. SemIR::ImplId import_impl_id) -> void {
  1213. // Resolve the imported impl to a local impl ID.
  1214. ImportRefResolver resolver(context, import_ir_id);
  1215. const auto& import_impl = import_ir.impls().Get(import_impl_id);
  1216. auto self_id = resolver.ResolveType(import_impl.self_id);
  1217. auto constraint_id = resolver.ResolveType(import_impl.constraint_id);
  1218. // Import the definition if the impl is defined.
  1219. // TODO: Do we need to check for multiple definitions?
  1220. auto impl_id = context.impls().LookupOrAdd(self_id, constraint_id);
  1221. if (import_impl.is_defined()) {
  1222. // TODO: Create a scope for the `impl` if necessary.
  1223. // TODO: Consider importing the definition_id.
  1224. auto& impl = context.impls().Get(impl_id);
  1225. impl.witness_id = AddImportRef(
  1226. context, {.ir_id = import_ir_id, .inst_id = import_impl.witness_id},
  1227. SemIR::BindNameId::Invalid);
  1228. }
  1229. }
  1230. // TODO: This doesn't belong in this file. Consider moving the import resolver
  1231. // and this file elsewhere.
  1232. auto ImportImpls(Context& context) -> void {
  1233. for (auto [import_index, import_ir] :
  1234. llvm::enumerate(context.import_irs().array_ref())) {
  1235. if (!import_ir.sem_ir) {
  1236. continue;
  1237. }
  1238. auto import_ir_id = SemIR::ImportIRId(import_index);
  1239. for (auto impl_index : llvm::seq(import_ir.sem_ir->impls().size())) {
  1240. auto impl_id = SemIR::ImplId(impl_index);
  1241. ImportImpl(context, import_ir_id, *import_ir.sem_ir, impl_id);
  1242. }
  1243. }
  1244. }
  1245. } // namespace Carbon::Check