import_ref.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  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/file.h"
  11. #include "toolchain/sem_ir/ids.h"
  12. #include "toolchain/sem_ir/inst.h"
  13. #include "toolchain/sem_ir/inst_kind.h"
  14. #include "toolchain/sem_ir/typed_insts.h"
  15. namespace Carbon::Check {
  16. // Resolves an instruction from an imported IR into a constant referring to the
  17. // current IR.
  18. //
  19. // Calling Resolve on an instruction operates in an iterative manner, tracking
  20. // Work items on work_stack_. At a high level, the loop is:
  21. //
  22. // 1. If a constant value is already known for the work item, and we're
  23. // processing it for the first time, it's considered resolved.
  24. // - The constant check avoids performance costs of deduplication on add.
  25. // - If `retry` is set, we process it again, because it didn't complete last
  26. // time, even though we have a constant value already.
  27. // 2. Resolve the instruction: (TryResolveInst/TryResolveTypedInst)
  28. // - For instructions that can be forward declared, if we don't already have
  29. // a constant value from a previous attempt at resolution, start by making
  30. // a forward declared constant value to address circular references.
  31. // - Gather all input constants.
  32. // - Gathering constants directly adds unresolved values to work_stack_.
  33. // - If any need to be resolved (HasNewWork), return Retry(): this
  34. // instruction needs two calls to complete.
  35. // - If the constant value is already known because we have made a forward
  36. // declaration, pass it to Retry(). It will be passed to future attempts
  37. // to resolve this instruction so the earlier work can be found, and will
  38. // be made available for other instructions to use.
  39. // - The second attempt to resolve this instruction must produce the same
  40. // constant, because the value may have already been used by resolved
  41. // instructions.
  42. // - Build any necessary IR structures, and return the output constant.
  43. // 3. If resolve didn't return Retry(), pop the work. Otherwise, it needs to
  44. // remain, and may no longer be at the top of the stack; set `retry` on it so
  45. // we'll make sure to run it again later.
  46. //
  47. // TryResolveInst/TryResolveTypedInst can complete in one call for a given
  48. // instruction, but should always complete within two calls. However, due to the
  49. // chance of a second call, it's important to reserve all expensive logic until
  50. // it's been established that input constants are available; this in particular
  51. // includes GetTypeIdForTypeConstant calls which do a hash table lookup.
  52. class ImportRefResolver {
  53. public:
  54. explicit ImportRefResolver(Context& context, SemIR::ImportIRId import_ir_id)
  55. : context_(context),
  56. import_ir_id_(import_ir_id),
  57. import_ir_(*context_.import_irs().Get(import_ir_id).sem_ir),
  58. import_ir_constant_values_(
  59. context_.import_ir_constant_values()[import_ir_id.index]) {}
  60. // Iteratively resolves an imported instruction's inner references until a
  61. // constant ID referencing the current IR is produced. See the class comment
  62. // for more details.
  63. auto Resolve(SemIR::InstId inst_id) -> SemIR::ConstantId {
  64. work_stack_.push_back({inst_id});
  65. while (!work_stack_.empty()) {
  66. auto work = work_stack_.back();
  67. CARBON_CHECK(work.inst_id.is_valid());
  68. // Step 1: check for a constant value.
  69. auto existing_const_id = import_ir_constant_values_.Get(work.inst_id);
  70. if (existing_const_id.is_valid() && !work.retry) {
  71. work_stack_.pop_back();
  72. continue;
  73. }
  74. // Step 2: resolve the instruction.
  75. auto initial_work = work_stack_.size();
  76. auto [new_const_id, finished] =
  77. TryResolveInst(work.inst_id, existing_const_id);
  78. CARBON_CHECK(finished == !HasNewWork(initial_work));
  79. CARBON_CHECK(!existing_const_id.is_valid() ||
  80. existing_const_id == new_const_id)
  81. << "Constant value changed in second pass.";
  82. import_ir_constant_values_.Set(work.inst_id, new_const_id);
  83. // Step 3: pop or retry.
  84. if (finished) {
  85. work_stack_.pop_back();
  86. } else {
  87. work_stack_[initial_work - 1].retry = true;
  88. }
  89. }
  90. auto constant_id = import_ir_constant_values_.Get(inst_id);
  91. CARBON_CHECK(constant_id.is_valid());
  92. return constant_id;
  93. }
  94. // Wraps constant evaluation with logic to handle types.
  95. auto ResolveType(SemIR::TypeId import_type_id) -> SemIR::TypeId {
  96. if (!import_type_id.is_valid()) {
  97. return import_type_id;
  98. }
  99. auto import_type_inst_id = import_ir_.types().GetInstId(import_type_id);
  100. CARBON_CHECK(import_type_inst_id.is_valid());
  101. if (import_type_inst_id.is_builtin()) {
  102. // Builtins don't require constant resolution; we can use them directly.
  103. return context_.GetBuiltinType(import_type_inst_id.builtin_kind());
  104. } else {
  105. return context_.GetTypeIdForTypeConstant(Resolve(import_type_inst_id));
  106. }
  107. }
  108. private:
  109. // A step in work_stack_.
  110. struct Work {
  111. // The instruction to work on.
  112. SemIR::InstId inst_id;
  113. // True if another pass was requested last time this was run.
  114. bool retry = false;
  115. };
  116. // The result of attempting to resolve an imported instruction to a constant.
  117. struct ResolveResult {
  118. // Try resolving this function again. If `const_id` is specified, it will be
  119. // passed to the next resolution attempt.
  120. static auto Retry(SemIR::ConstantId const_id = SemIR::ConstantId::Invalid)
  121. -> ResolveResult {
  122. return {.const_id = const_id, .finished = false};
  123. }
  124. // The new constant value, if known.
  125. SemIR::ConstantId const_id;
  126. // Whether resolution has finished. If false, `TryResolveInst` will be
  127. // called again. Note that this is not strictly necessary, and we can get
  128. // the same information by checking whether new work was added to the stack.
  129. // However, we use this for consistency checks between resolve actions and
  130. // the work stack.
  131. bool finished = true;
  132. };
  133. // Returns true if new unresolved constants were found.
  134. //
  135. // At the start of a function, do:
  136. // auto initial_work = work_stack_.size();
  137. // Then when determining:
  138. // if (HasNewWork(initial_work)) { ... }
  139. auto HasNewWork(size_t initial_work) -> bool {
  140. CARBON_CHECK(initial_work <= work_stack_.size())
  141. << "Work shouldn't decrease";
  142. return initial_work < work_stack_.size();
  143. }
  144. auto AddImportIRInst(SemIR::InstId inst_id) -> SemIR::LocId {
  145. return context_.import_ir_insts().Add(
  146. {.ir_id = import_ir_id_, .inst_id = inst_id});
  147. }
  148. // Returns the ConstantId for an InstId. Adds unresolved constants to
  149. // work_stack_.
  150. auto GetLocalConstantId(SemIR::InstId inst_id) -> SemIR::ConstantId {
  151. auto const_id = import_ir_constant_values_.Get(inst_id);
  152. if (!const_id.is_valid()) {
  153. work_stack_.push_back({inst_id});
  154. }
  155. return const_id;
  156. }
  157. // Returns the ConstantId for a TypeId. Adds unresolved constants to
  158. // work_stack_.
  159. auto GetLocalConstantId(SemIR::TypeId type_id) -> SemIR::ConstantId {
  160. return GetLocalConstantId(import_ir_.types().GetInstId(type_id));
  161. }
  162. // Returns the ConstantId for each parameter's type. Adds unresolved constants
  163. // to work_stack_.
  164. auto GetLocalParamConstantIds(SemIR::InstBlockId param_refs_id)
  165. -> llvm::SmallVector<SemIR::ConstantId> {
  166. if (param_refs_id == SemIR::InstBlockId::Empty) {
  167. return {};
  168. }
  169. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  170. llvm::SmallVector<SemIR::ConstantId> const_ids;
  171. const_ids.reserve(param_refs.size());
  172. for (auto inst_id : param_refs) {
  173. const_ids.push_back(
  174. GetLocalConstantId(import_ir_.insts().Get(inst_id).type_id()));
  175. // If the parameter is a symbolic binding, build the BindSymbolicName
  176. // constant.
  177. auto bind_id = inst_id;
  178. if (auto addr =
  179. import_ir_.insts().TryGetAs<SemIR::AddrPattern>(bind_id)) {
  180. bind_id = addr->inner_id;
  181. }
  182. GetLocalConstantId(bind_id);
  183. }
  184. return const_ids;
  185. }
  186. // Given a param_refs_id and const_ids from GetLocalParamConstantIds, returns
  187. // a version of param_refs_id localized to the current IR.
  188. auto GetLocalParamRefsId(
  189. SemIR::InstBlockId param_refs_id,
  190. const llvm::SmallVector<SemIR::ConstantId>& const_ids)
  191. -> SemIR::InstBlockId {
  192. if (param_refs_id == SemIR::InstBlockId::Empty) {
  193. return SemIR::InstBlockId::Empty;
  194. }
  195. const auto& param_refs = import_ir_.inst_blocks().Get(param_refs_id);
  196. llvm::SmallVector<SemIR::InstId> new_param_refs;
  197. for (auto [ref_id, const_id] : llvm::zip(param_refs, const_ids)) {
  198. // Figure out the param structure. This echoes
  199. // Function::GetParamFromParamRefId.
  200. // TODO: Consider a different parameter handling to simplify import logic.
  201. auto inst = import_ir_.insts().Get(ref_id);
  202. auto addr_inst = inst.TryAs<SemIR::AddrPattern>();
  203. auto bind_id = ref_id;
  204. auto param_id = ref_id;
  205. if (addr_inst) {
  206. bind_id = addr_inst->inner_id;
  207. param_id = bind_id;
  208. inst = import_ir_.insts().Get(bind_id);
  209. }
  210. auto bind_inst = inst.TryAs<SemIR::AnyBindName>();
  211. if (bind_inst) {
  212. param_id = bind_inst->value_id;
  213. inst = import_ir_.insts().Get(param_id);
  214. }
  215. auto param_inst = inst.As<SemIR::Param>();
  216. // Rebuild the param instruction.
  217. auto name_id = GetLocalNameId(param_inst.name_id);
  218. auto type_id = context_.GetTypeIdForTypeConstant(const_id);
  219. auto new_param_id = context_.AddInstInNoBlock(
  220. {AddImportIRInst(param_id), SemIR::Param{type_id, name_id}});
  221. if (bind_inst) {
  222. switch (bind_inst->kind) {
  223. case SemIR::BindName::Kind: {
  224. auto bind_name_id = context_.bind_names().Add(
  225. {.name_id = name_id,
  226. .enclosing_scope_id = SemIR::NameScopeId::Invalid,
  227. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  228. new_param_id = context_.AddInstInNoBlock(
  229. {AddImportIRInst(bind_id),
  230. SemIR::BindName{type_id, bind_name_id, new_param_id}});
  231. break;
  232. }
  233. case SemIR::BindSymbolicName::Kind: {
  234. // The symbolic name will be created on first reference, so might
  235. // already exist. Update the value in it to refer to the parameter.
  236. auto new_bind_inst =
  237. context_.insts().GetAs<SemIR::BindSymbolicName>(
  238. GetLocalConstantId(bind_id).inst_id());
  239. new_bind_inst.value_id = new_param_id;
  240. // This is not before constant use, but doesn't change the
  241. // constant value of the instruction.
  242. context_.ReplaceInstBeforeConstantUse(bind_id, new_bind_inst);
  243. break;
  244. }
  245. default: {
  246. CARBON_FATAL() << "Unexpected kind: " << bind_inst->kind;
  247. }
  248. }
  249. }
  250. if (addr_inst) {
  251. new_param_id = context_.AddInstInNoBlock(SemIR::LocIdAndInst::Untyped(
  252. AddImportIRInst(ref_id),
  253. SemIR::AddrPattern{type_id, new_param_id}));
  254. }
  255. new_param_refs.push_back(new_param_id);
  256. }
  257. return context_.inst_blocks().Add(new_param_refs);
  258. }
  259. // Translates a NameId from the import IR to a local NameId.
  260. auto GetLocalNameId(SemIR::NameId import_name_id) -> SemIR::NameId {
  261. if (auto ident_id = import_name_id.AsIdentifierId(); ident_id.is_valid()) {
  262. return SemIR::NameId::ForIdentifier(
  263. context_.identifiers().Add(import_ir_.identifiers().Get(ident_id)));
  264. }
  265. return import_name_id;
  266. }
  267. // Translates a NameScopeId from the import IR to a local NameScopeId. Adds
  268. // unresolved constants to the work stack.
  269. auto GetLocalNameScopeId(SemIR::NameScopeId name_scope_id)
  270. -> SemIR::NameScopeId {
  271. auto inst_id = import_ir_.name_scopes().GetInstIdIfValid(name_scope_id);
  272. if (!inst_id.is_valid()) {
  273. // Map scopes that aren't associated with an instruction to invalid
  274. // scopes. For now, such scopes aren't used, and we don't have a good way
  275. // to remap them.
  276. return SemIR::NameScopeId::Invalid;
  277. }
  278. if (import_ir_.insts().Is<SemIR::ImplDecl>(inst_id)) {
  279. // TODO: Import the scope for an `impl` definition.
  280. return SemIR::NameScopeId::Invalid;
  281. }
  282. auto const_id = GetLocalConstantId(inst_id);
  283. if (!const_id.is_valid()) {
  284. return SemIR::NameScopeId::Invalid;
  285. }
  286. auto name_scope_inst = context_.insts().Get(const_id.inst_id());
  287. CARBON_KIND_SWITCH(name_scope_inst) {
  288. case CARBON_KIND(SemIR::Namespace inst): {
  289. return inst.name_scope_id;
  290. }
  291. case CARBON_KIND(SemIR::ClassType inst): {
  292. return context_.classes().Get(inst.class_id).scope_id;
  293. }
  294. case CARBON_KIND(SemIR::InterfaceType inst): {
  295. return context_.interfaces().Get(inst.interface_id).scope_id;
  296. }
  297. default:
  298. if (const_id == SemIR::ConstantId::Error) {
  299. return SemIR::NameScopeId::Invalid;
  300. }
  301. CARBON_FATAL() << "Unexpected instruction kind for name scope: "
  302. << name_scope_inst;
  303. }
  304. }
  305. // Adds ImportRefUnloaded entries for members of the imported scope, for name
  306. // lookup.
  307. auto AddNameScopeImportRefs(const SemIR::NameScope& import_scope,
  308. SemIR::NameScope& new_scope) -> void {
  309. for (auto [entry_name_id, entry_inst_id] : import_scope.names) {
  310. auto ref_id = context_.AddImportRef(
  311. {.ir_id = import_ir_id_, .inst_id = entry_inst_id});
  312. CARBON_CHECK(
  313. new_scope.names.insert({GetLocalNameId(entry_name_id), ref_id})
  314. .second);
  315. }
  316. }
  317. // Given a block ID for a list of associated entities of a witness, returns a
  318. // version localized to the current IR.
  319. auto AddAssociatedEntities(SemIR::InstBlockId associated_entities_id)
  320. -> SemIR::InstBlockId {
  321. if (associated_entities_id == SemIR::InstBlockId::Empty) {
  322. return SemIR::InstBlockId::Empty;
  323. }
  324. auto associated_entities =
  325. import_ir_.inst_blocks().Get(associated_entities_id);
  326. llvm::SmallVector<SemIR::InstId> new_associated_entities;
  327. new_associated_entities.reserve(associated_entities.size());
  328. for (auto inst_id : associated_entities) {
  329. new_associated_entities.push_back(
  330. context_.AddImportRef({.ir_id = import_ir_id_, .inst_id = inst_id}));
  331. }
  332. return context_.inst_blocks().Add(new_associated_entities);
  333. }
  334. // Tries to resolve the InstId, returning a constant when ready, or Invalid if
  335. // more has been added to the stack. A similar API is followed for all
  336. // following TryResolveTypedInst helper functions.
  337. //
  338. // `const_id` is Invalid unless we've tried to resolve this instruction
  339. // before, in which case it's the previous result.
  340. //
  341. // TODO: Error is returned when support is missing, but that should go away.
  342. auto TryResolveInst(SemIR::InstId inst_id, SemIR::ConstantId const_id)
  343. -> ResolveResult {
  344. if (inst_id.is_builtin()) {
  345. CARBON_CHECK(!const_id.is_valid());
  346. // Constants for builtins can be directly copied.
  347. return {context_.constant_values().Get(inst_id)};
  348. }
  349. auto untyped_inst = import_ir_.insts().Get(inst_id);
  350. CARBON_KIND_SWITCH(untyped_inst) {
  351. case CARBON_KIND(SemIR::AssociatedEntity inst): {
  352. return TryResolveTypedInst(inst);
  353. }
  354. case CARBON_KIND(SemIR::AssociatedEntityType inst): {
  355. return TryResolveTypedInst(inst);
  356. }
  357. case CARBON_KIND(SemIR::BaseDecl inst): {
  358. return TryResolveTypedInst(inst, inst_id);
  359. }
  360. case CARBON_KIND(SemIR::BindAlias inst): {
  361. return TryResolveTypedInst(inst);
  362. }
  363. case CARBON_KIND(SemIR::BindName inst): {
  364. // TODO: This always returns `ConstantId::NotConstant`.
  365. return {TryEvalInst(context_, inst_id, inst)};
  366. }
  367. case CARBON_KIND(SemIR::BindSymbolicName inst): {
  368. return TryResolveTypedInst(inst, inst_id);
  369. }
  370. case CARBON_KIND(SemIR::ClassDecl inst): {
  371. return TryResolveTypedInst(inst, const_id);
  372. }
  373. case CARBON_KIND(SemIR::ClassType inst): {
  374. return TryResolveTypedInst(inst);
  375. }
  376. case CARBON_KIND(SemIR::ConstType inst): {
  377. return TryResolveTypedInst(inst);
  378. }
  379. case CARBON_KIND(SemIR::ExternDecl inst): {
  380. return TryResolveTypedInst(inst);
  381. }
  382. case CARBON_KIND(SemIR::FieldDecl inst): {
  383. return TryResolveTypedInst(inst, inst_id);
  384. }
  385. case CARBON_KIND(SemIR::FunctionDecl inst): {
  386. return TryResolveTypedInst(inst);
  387. }
  388. case CARBON_KIND(SemIR::ImportRefUsed inst): {
  389. return TryResolveTypedInst(inst, inst_id);
  390. }
  391. case CARBON_KIND(SemIR::InterfaceDecl inst): {
  392. return TryResolveTypedInst(inst, const_id);
  393. }
  394. case CARBON_KIND(SemIR::InterfaceWitness inst): {
  395. return TryResolveTypedInst(inst);
  396. }
  397. case CARBON_KIND(SemIR::InterfaceType inst): {
  398. return TryResolveTypedInst(inst);
  399. }
  400. case CARBON_KIND(SemIR::PointerType inst): {
  401. return TryResolveTypedInst(inst);
  402. }
  403. case CARBON_KIND(SemIR::StructType inst): {
  404. return TryResolveTypedInst(inst, inst_id);
  405. }
  406. case CARBON_KIND(SemIR::TupleType inst): {
  407. return TryResolveTypedInst(inst);
  408. }
  409. case CARBON_KIND(SemIR::UnboundElementType inst): {
  410. return TryResolveTypedInst(inst);
  411. }
  412. default:
  413. context_.TODO(
  414. AddImportIRInst(inst_id),
  415. llvm::formatv("TryResolveInst on {0}", untyped_inst.kind()).str());
  416. return {SemIR::ConstantId::Error};
  417. }
  418. }
  419. auto TryResolveTypedInst(SemIR::AssociatedEntity inst) -> ResolveResult {
  420. auto initial_work = work_stack_.size();
  421. auto type_const_id = GetLocalConstantId(inst.type_id);
  422. if (HasNewWork(initial_work)) {
  423. return ResolveResult::Retry();
  424. }
  425. // Add a lazy reference to the target declaration.
  426. auto decl_id = context_.AddImportRef(
  427. {.ir_id = import_ir_id_, .inst_id = inst.decl_id});
  428. auto inst_id = context_.AddInstInNoBlock(
  429. {AddImportIRInst(inst.decl_id),
  430. SemIR::AssociatedEntity{
  431. context_.GetTypeIdForTypeConstant(type_const_id), inst.index,
  432. decl_id}});
  433. return {context_.constant_values().Get(inst_id)};
  434. }
  435. auto TryResolveTypedInst(SemIR::AssociatedEntityType inst) -> ResolveResult {
  436. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  437. auto initial_work = work_stack_.size();
  438. auto entity_type_const_id = GetLocalConstantId(inst.entity_type_id);
  439. auto interface_const_id = GetLocalConstantId(
  440. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  441. if (HasNewWork(initial_work)) {
  442. return ResolveResult::Retry();
  443. }
  444. auto inst_id = context_.AddInstInNoBlock(SemIR::AssociatedEntityType{
  445. SemIR::TypeId::TypeType,
  446. context_.insts()
  447. .GetAs<SemIR::InterfaceType>(interface_const_id.inst_id())
  448. .interface_id,
  449. context_.GetTypeIdForTypeConstant(entity_type_const_id)});
  450. return {context_.constant_values().Get(inst_id)};
  451. }
  452. auto TryResolveTypedInst(SemIR::BaseDecl inst, SemIR::InstId import_inst_id)
  453. -> ResolveResult {
  454. auto initial_work = work_stack_.size();
  455. auto type_const_id = GetLocalConstantId(inst.type_id);
  456. auto base_type_const_id = GetLocalConstantId(inst.base_type_id);
  457. if (HasNewWork(initial_work)) {
  458. return ResolveResult::Retry();
  459. }
  460. // Import the instruction in order to update contained base_type_id.
  461. auto inst_id = context_.AddInstInNoBlock(SemIR::LocIdAndInst::Untyped(
  462. AddImportIRInst(import_inst_id),
  463. SemIR::BaseDecl{context_.GetTypeIdForTypeConstant(type_const_id),
  464. context_.GetTypeIdForTypeConstant(base_type_const_id),
  465. inst.index}));
  466. return {context_.constant_values().Get(inst_id)};
  467. }
  468. auto TryResolveTypedInst(SemIR::BindAlias inst) -> ResolveResult {
  469. auto initial_work = work_stack_.size();
  470. auto value_id = GetLocalConstantId(inst.value_id);
  471. if (HasNewWork(initial_work)) {
  472. return ResolveResult::Retry();
  473. }
  474. return {value_id};
  475. }
  476. auto TryResolveTypedInst(SemIR::BindSymbolicName inst,
  477. SemIR::InstId import_inst_id) -> ResolveResult {
  478. auto initial_work = work_stack_.size();
  479. auto type_id = GetLocalConstantId(inst.type_id);
  480. if (HasNewWork(initial_work)) {
  481. return ResolveResult::Retry();
  482. }
  483. const auto& import_bind_info =
  484. import_ir_.bind_names().Get(inst.bind_name_id);
  485. auto name_id = GetLocalNameId(import_bind_info.name_id);
  486. auto bind_name_id = context_.bind_names().Add(
  487. {.name_id = name_id,
  488. .enclosing_scope_id = SemIR::NameScopeId::Invalid,
  489. .bind_index = import_bind_info.bind_index});
  490. auto new_bind_id = context_.AddInstInNoBlock(
  491. {AddImportIRInst(import_inst_id),
  492. SemIR::BindSymbolicName{context_.GetTypeIdForTypeConstant(type_id),
  493. bind_name_id, SemIR::InstId::Invalid}});
  494. return {context_.constant_values().Get(new_bind_id)};
  495. }
  496. // Makes an incomplete class. This is necessary even with classes with a
  497. // complete declaration, because things such as `Self` may refer back to the
  498. // type.
  499. auto MakeIncompleteClass(const SemIR::Class& import_class)
  500. -> SemIR::ConstantId {
  501. auto class_decl =
  502. SemIR::ClassDecl{SemIR::TypeId::TypeType, SemIR::ClassId::Invalid,
  503. SemIR::InstBlockId::Empty};
  504. auto class_decl_id =
  505. context_.AddPlaceholderInst(SemIR::LocIdAndInst::Untyped(
  506. AddImportIRInst(import_class.decl_id), class_decl));
  507. // Regardless of whether ClassDecl is a complete type, we first need an
  508. // incomplete type so that any references have something to point at.
  509. class_decl.class_id = context_.classes().Add({
  510. .name_id = GetLocalNameId(import_class.name_id),
  511. // Set in the second pass once we've imported it.
  512. .enclosing_scope_id = SemIR::NameScopeId::Invalid,
  513. // `.self_type_id` depends on the ClassType, so is set below.
  514. .self_type_id = SemIR::TypeId::Invalid,
  515. .decl_id = class_decl_id,
  516. .inheritance_kind = import_class.inheritance_kind,
  517. });
  518. // Write the class ID into the ClassDecl.
  519. context_.ReplaceInstBeforeConstantUse(class_decl_id, class_decl);
  520. auto self_const_id = context_.constant_values().Get(class_decl_id);
  521. // Build the `Self` type using the resulting type constant.
  522. auto& class_info = context_.classes().Get(class_decl.class_id);
  523. class_info.self_type_id = context_.GetTypeIdForTypeConstant(self_const_id);
  524. return self_const_id;
  525. }
  526. // Fills out the class definition for an incomplete class.
  527. auto AddClassDefinition(const SemIR::Class& import_class,
  528. SemIR::Class& new_class,
  529. SemIR::ConstantId object_repr_const_id,
  530. SemIR::ConstantId base_const_id) -> void {
  531. new_class.definition_id = new_class.decl_id;
  532. new_class.object_repr_id =
  533. context_.GetTypeIdForTypeConstant(object_repr_const_id);
  534. new_class.scope_id =
  535. context_.name_scopes().Add(new_class.decl_id, SemIR::NameId::Invalid,
  536. new_class.enclosing_scope_id);
  537. auto& new_scope = context_.name_scopes().Get(new_class.scope_id);
  538. const auto& import_scope =
  539. import_ir_.name_scopes().Get(import_class.scope_id);
  540. // Push a block so that we can add scoped instructions to it.
  541. context_.inst_block_stack().Push();
  542. AddNameScopeImportRefs(import_scope, new_scope);
  543. new_class.body_block_id = context_.inst_block_stack().Pop();
  544. if (import_class.base_id.is_valid()) {
  545. new_class.base_id = base_const_id.inst_id();
  546. // Add the base scope to extended scopes.
  547. auto base_inst_id = context_.types().GetInstId(
  548. context_.insts()
  549. .GetAs<SemIR::BaseDecl>(new_class.base_id)
  550. .base_type_id);
  551. const auto& base_class = context_.classes().Get(
  552. context_.insts().GetAs<SemIR::ClassType>(base_inst_id).class_id);
  553. new_scope.extended_scopes.push_back(base_class.scope_id);
  554. }
  555. CARBON_CHECK(new_scope.extended_scopes.size() ==
  556. import_scope.extended_scopes.size());
  557. }
  558. auto TryResolveTypedInst(SemIR::ClassDecl inst,
  559. SemIR::ConstantId class_const_id) -> ResolveResult {
  560. const auto& import_class = import_ir_.classes().Get(inst.class_id);
  561. // On the first pass, create a forward declaration of the class for any
  562. // recursive references.
  563. if (!class_const_id.is_valid()) {
  564. class_const_id = MakeIncompleteClass(import_class);
  565. }
  566. // Load constants for the definition.
  567. auto initial_work = work_stack_.size();
  568. auto enclosing_scope_id =
  569. GetLocalNameScopeId(import_class.enclosing_scope_id);
  570. auto object_repr_const_id =
  571. import_class.object_repr_id.is_valid()
  572. ? GetLocalConstantId(import_class.object_repr_id)
  573. : SemIR::ConstantId::Invalid;
  574. auto base_const_id = import_class.base_id.is_valid()
  575. ? GetLocalConstantId(import_class.base_id)
  576. : SemIR::ConstantId::Invalid;
  577. if (HasNewWork(initial_work)) {
  578. return ResolveResult::Retry(class_const_id);
  579. }
  580. auto& new_class = context_.classes().Get(
  581. context_.insts()
  582. .GetAs<SemIR::ClassType>(class_const_id.inst_id())
  583. .class_id);
  584. new_class.enclosing_scope_id = enclosing_scope_id;
  585. if (import_class.is_defined()) {
  586. AddClassDefinition(import_class, new_class, object_repr_const_id,
  587. base_const_id);
  588. }
  589. return {class_const_id};
  590. }
  591. auto TryResolveTypedInst(SemIR::ClassType inst) -> ResolveResult {
  592. auto initial_work = work_stack_.size();
  593. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  594. auto class_const_id =
  595. GetLocalConstantId(import_ir_.classes().Get(inst.class_id).decl_id);
  596. if (HasNewWork(initial_work)) {
  597. return ResolveResult::Retry();
  598. }
  599. return {class_const_id};
  600. }
  601. auto TryResolveTypedInst(SemIR::ConstType inst) -> ResolveResult {
  602. auto initial_work = work_stack_.size();
  603. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  604. auto inner_const_id = GetLocalConstantId(inst.inner_id);
  605. if (HasNewWork(initial_work)) {
  606. return ResolveResult::Retry();
  607. }
  608. auto inner_type_id = context_.GetTypeIdForTypeConstant(inner_const_id);
  609. // TODO: Should ConstType have a wrapper for this similar to the others?
  610. return {
  611. TryEvalInst(context_, SemIR::InstId::Invalid,
  612. SemIR::ConstType{SemIR::TypeId::TypeType, inner_type_id})};
  613. }
  614. auto TryResolveTypedInst(SemIR::ExternDecl inst) -> ResolveResult {
  615. auto initial_work = work_stack_.size();
  616. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  617. auto decl_const_id = GetLocalConstantId(inst.decl_id);
  618. if (HasNewWork(initial_work)) {
  619. return ResolveResult::Retry();
  620. }
  621. auto extern_id = context_.AddInstInNoBlock(SemIR::LocIdAndInst::Untyped(
  622. AddImportIRInst(inst.decl_id),
  623. SemIR::ExternDecl{SemIR::TypeId::TypeType, decl_const_id.inst_id()}));
  624. return {context_.constant_values().Get(extern_id)};
  625. }
  626. auto TryResolveTypedInst(SemIR::FieldDecl inst, SemIR::InstId import_inst_id)
  627. -> ResolveResult {
  628. auto initial_work = work_stack_.size();
  629. auto const_id = GetLocalConstantId(inst.type_id);
  630. if (HasNewWork(initial_work)) {
  631. return ResolveResult::Retry();
  632. }
  633. auto inst_id = context_.AddInstInNoBlock(SemIR::LocIdAndInst::Untyped(
  634. AddImportIRInst(import_inst_id),
  635. SemIR::FieldDecl{context_.GetTypeIdForTypeConstant(const_id),
  636. GetLocalNameId(inst.name_id), inst.index}));
  637. return {context_.constant_values().Get(inst_id)};
  638. }
  639. auto TryResolveTypedInst(SemIR::FunctionDecl inst) -> ResolveResult {
  640. auto initial_work = work_stack_.size();
  641. auto type_const_id = GetLocalConstantId(inst.type_id);
  642. const auto& function = import_ir_.functions().Get(inst.function_id);
  643. auto return_type_const_id = SemIR::ConstantId::Invalid;
  644. if (function.return_type_id.is_valid()) {
  645. return_type_const_id = GetLocalConstantId(function.return_type_id);
  646. }
  647. auto enclosing_scope_id = GetLocalNameScopeId(function.enclosing_scope_id);
  648. llvm::SmallVector<SemIR::ConstantId> implicit_param_const_ids =
  649. GetLocalParamConstantIds(function.implicit_param_refs_id);
  650. llvm::SmallVector<SemIR::ConstantId> param_const_ids =
  651. GetLocalParamConstantIds(function.param_refs_id);
  652. if (HasNewWork(initial_work)) {
  653. return ResolveResult::Retry();
  654. }
  655. // Add the function declaration.
  656. auto function_decl = SemIR::FunctionDecl{
  657. context_.GetTypeIdForTypeConstant(type_const_id),
  658. SemIR::FunctionId::Invalid, SemIR::InstBlockId::Empty};
  659. // Prefer pointing diagnostics towards a definition.
  660. auto imported_loc_id = AddImportIRInst(function.definition_id.is_valid()
  661. ? function.definition_id
  662. : function.decl_id);
  663. auto function_decl_id = context_.AddPlaceholderInstInNoBlock(
  664. SemIR::LocIdAndInst::Untyped(imported_loc_id, function_decl));
  665. auto new_return_type_id =
  666. return_type_const_id.is_valid()
  667. ? context_.GetTypeIdForTypeConstant(return_type_const_id)
  668. : SemIR::TypeId::Invalid;
  669. auto new_return_storage = SemIR::InstId::Invalid;
  670. if (function.return_storage_id.is_valid()) {
  671. // Recreate the return slot from scratch.
  672. // TODO: Once we import function definitions, we'll need to make sure we
  673. // use the same return storage variable in the declaration and definition.
  674. new_return_storage = context_.AddInstInNoBlock(
  675. {AddImportIRInst(function.return_storage_id),
  676. SemIR::VarStorage{new_return_type_id, SemIR::NameId::ReturnSlot}});
  677. }
  678. function_decl.function_id = context_.functions().Add(
  679. {.name_id = GetLocalNameId(function.name_id),
  680. .enclosing_scope_id = enclosing_scope_id,
  681. .decl_id = function_decl_id,
  682. .implicit_param_refs_id = GetLocalParamRefsId(
  683. function.implicit_param_refs_id, implicit_param_const_ids),
  684. .param_refs_id =
  685. GetLocalParamRefsId(function.param_refs_id, param_const_ids),
  686. .return_type_id = new_return_type_id,
  687. .return_storage_id = new_return_storage,
  688. .is_extern = function.is_extern,
  689. .return_slot = function.return_slot,
  690. .builtin_kind = function.builtin_kind,
  691. .definition_id = function.definition_id.is_valid()
  692. ? function_decl_id
  693. : SemIR::InstId::Invalid});
  694. // Write the function ID into the FunctionDecl.
  695. context_.ReplaceInstBeforeConstantUse(function_decl_id, function_decl);
  696. return {context_.constant_values().Get(function_decl_id)};
  697. }
  698. auto TryResolveTypedInst(SemIR::ImportRefUsed /*inst*/, SemIR::InstId inst_id)
  699. -> ResolveResult {
  700. auto initial_work = work_stack_.size();
  701. // Return the constant for the instruction of the imported constant.
  702. auto constant_id = import_ir_.constant_values().Get(inst_id);
  703. if (!constant_id.is_valid()) {
  704. return {SemIR::ConstantId::Error};
  705. }
  706. if (!constant_id.is_constant()) {
  707. context_.TODO(inst_id, "Non-constant ImportRefUsed (comes up with var)");
  708. return {SemIR::ConstantId::Error};
  709. }
  710. auto new_constant_id = GetLocalConstantId(constant_id.inst_id());
  711. if (HasNewWork(initial_work)) {
  712. return ResolveResult::Retry();
  713. }
  714. return {new_constant_id};
  715. }
  716. // Make a declaration of an interface. This is done as a separate step from
  717. // importing the interface definition in order to resolve cycles.
  718. auto MakeInterfaceDecl(const SemIR::Interface& import_interface)
  719. -> SemIR::ConstantId {
  720. auto interface_decl = SemIR::InterfaceDecl{SemIR::TypeId::TypeType,
  721. SemIR::InterfaceId::Invalid,
  722. SemIR::InstBlockId::Empty};
  723. auto interface_decl_id =
  724. context_.AddPlaceholderInst(SemIR::LocIdAndInst::Untyped(
  725. AddImportIRInst(import_interface.decl_id), interface_decl));
  726. // Start with an incomplete interface.
  727. SemIR::Interface new_interface = {
  728. .name_id = GetLocalNameId(import_interface.name_id),
  729. // Set in the second pass once we've imported it.
  730. .enclosing_scope_id = SemIR::NameScopeId::Invalid,
  731. .decl_id = interface_decl_id,
  732. };
  733. // Write the interface ID into the InterfaceDecl.
  734. interface_decl.interface_id = context_.interfaces().Add(new_interface);
  735. context_.ReplaceInstBeforeConstantUse(interface_decl_id, interface_decl);
  736. // Set the constant value for the imported interface.
  737. return context_.constant_values().Get(interface_decl_id);
  738. }
  739. // Imports the definition for an interface that has been imported as a forward
  740. // declaration.
  741. auto AddInterfaceDefinition(const SemIR::Interface& import_interface,
  742. SemIR::Interface& new_interface,
  743. SemIR::ConstantId self_param_id) -> void {
  744. new_interface.scope_id = context_.name_scopes().Add(
  745. new_interface.decl_id, SemIR::NameId::Invalid,
  746. new_interface.enclosing_scope_id);
  747. auto& new_scope = context_.name_scopes().Get(new_interface.scope_id);
  748. const auto& import_scope =
  749. import_ir_.name_scopes().Get(import_interface.scope_id);
  750. // Push a block so that we can add scoped instructions to it.
  751. context_.inst_block_stack().Push();
  752. AddNameScopeImportRefs(import_scope, new_scope);
  753. new_interface.associated_entities_id =
  754. AddAssociatedEntities(import_interface.associated_entities_id);
  755. new_interface.body_block_id = context_.inst_block_stack().Pop();
  756. new_interface.self_param_id = self_param_id.inst_id();
  757. CARBON_CHECK(import_scope.extended_scopes.empty())
  758. << "Interfaces don't currently have extended scopes to support.";
  759. }
  760. auto TryResolveTypedInst(SemIR::InterfaceDecl inst,
  761. SemIR::ConstantId interface_const_id)
  762. -> ResolveResult {
  763. const auto& import_interface =
  764. import_ir_.interfaces().Get(inst.interface_id);
  765. // On the first pass, create a forward declaration of the interface.
  766. if (!interface_const_id.is_valid()) {
  767. interface_const_id = MakeInterfaceDecl(import_interface);
  768. }
  769. auto initial_work = work_stack_.size();
  770. auto enclosing_scope_id =
  771. GetLocalNameScopeId(import_interface.enclosing_scope_id);
  772. auto self_param_id = GetLocalConstantId(import_interface.self_param_id);
  773. if (HasNewWork(initial_work)) {
  774. return ResolveResult::Retry(interface_const_id);
  775. }
  776. auto& new_interface = context_.interfaces().Get(
  777. context_.insts()
  778. .GetAs<SemIR::InterfaceType>(interface_const_id.inst_id())
  779. .interface_id);
  780. new_interface.enclosing_scope_id = enclosing_scope_id;
  781. if (import_interface.is_defined()) {
  782. AddInterfaceDefinition(import_interface, new_interface, self_param_id);
  783. }
  784. return {interface_const_id};
  785. }
  786. auto TryResolveTypedInst(SemIR::InterfaceType inst) -> ResolveResult {
  787. auto initial_work = work_stack_.size();
  788. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  789. auto interface_const_id = GetLocalConstantId(
  790. import_ir_.interfaces().Get(inst.interface_id).decl_id);
  791. if (HasNewWork(initial_work)) {
  792. return ResolveResult::Retry();
  793. }
  794. return {interface_const_id};
  795. }
  796. auto TryResolveTypedInst(SemIR::InterfaceWitness inst) -> ResolveResult {
  797. auto initial_work = work_stack_.size();
  798. llvm::SmallVector<SemIR::InstId> elements;
  799. auto import_elements = import_ir_.inst_blocks().Get(inst.elements_id);
  800. elements.reserve(import_elements.size());
  801. for (auto import_elem_id : import_elements) {
  802. if (auto const_id = GetLocalConstantId(import_elem_id);
  803. const_id.is_valid()) {
  804. elements.push_back(const_id.inst_id());
  805. }
  806. }
  807. if (HasNewWork(initial_work)) {
  808. return ResolveResult::Retry();
  809. }
  810. CARBON_CHECK(elements.size() == import_elements.size())
  811. << "Failed to import an element without adding new work.";
  812. auto elements_id = context_.inst_blocks().Add(elements);
  813. return {TryEvalInst(
  814. context_, SemIR::InstId::Invalid,
  815. SemIR::InterfaceWitness{
  816. context_.GetBuiltinType(SemIR::BuiltinKind::WitnessType),
  817. elements_id})};
  818. }
  819. auto TryResolveTypedInst(SemIR::PointerType inst) -> ResolveResult {
  820. auto initial_work = work_stack_.size();
  821. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  822. auto pointee_const_id = GetLocalConstantId(inst.pointee_id);
  823. if (HasNewWork(initial_work)) {
  824. return ResolveResult::Retry();
  825. }
  826. auto pointee_type_id = context_.GetTypeIdForTypeConstant(pointee_const_id);
  827. return {context_.types().GetConstantId(
  828. context_.GetPointerType(pointee_type_id))};
  829. }
  830. auto TryResolveTypedInst(SemIR::StructType inst, SemIR::InstId import_inst_id)
  831. -> ResolveResult {
  832. // Collect all constants first, locating unresolved ones in a single pass.
  833. auto initial_work = work_stack_.size();
  834. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  835. auto orig_fields = import_ir_.inst_blocks().Get(inst.fields_id);
  836. llvm::SmallVector<SemIR::ConstantId> field_const_ids;
  837. field_const_ids.reserve(orig_fields.size());
  838. for (auto field_id : orig_fields) {
  839. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  840. field_const_ids.push_back(GetLocalConstantId(field.field_type_id));
  841. }
  842. if (HasNewWork(initial_work)) {
  843. return ResolveResult::Retry();
  844. }
  845. // Prepare a vector of fields for GetStructType.
  846. // TODO: Should we have field constants so that we can deduplicate fields
  847. // without creating instructions here?
  848. llvm::SmallVector<SemIR::InstId> fields;
  849. fields.reserve(orig_fields.size());
  850. for (auto [field_id, field_const_id] :
  851. llvm::zip(orig_fields, field_const_ids)) {
  852. auto field = import_ir_.insts().GetAs<SemIR::StructTypeField>(field_id);
  853. auto name_id = GetLocalNameId(field.name_id);
  854. auto field_type_id = context_.GetTypeIdForTypeConstant(field_const_id);
  855. fields.push_back(context_.AddInstInNoBlock(
  856. {AddImportIRInst(import_inst_id),
  857. SemIR::StructTypeField{.name_id = name_id,
  858. .field_type_id = field_type_id}}));
  859. }
  860. return {context_.types().GetConstantId(
  861. context_.GetStructType(context_.inst_blocks().Add(fields)))};
  862. }
  863. auto TryResolveTypedInst(SemIR::TupleType inst) -> ResolveResult {
  864. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  865. // Collect all constants first, locating unresolved ones in a single pass.
  866. auto initial_work = work_stack_.size();
  867. auto orig_elem_type_ids = import_ir_.type_blocks().Get(inst.elements_id);
  868. llvm::SmallVector<SemIR::ConstantId> elem_const_ids;
  869. elem_const_ids.reserve(orig_elem_type_ids.size());
  870. for (auto elem_type_id : orig_elem_type_ids) {
  871. elem_const_ids.push_back(GetLocalConstantId(elem_type_id));
  872. }
  873. if (HasNewWork(initial_work)) {
  874. return ResolveResult::Retry();
  875. }
  876. // Prepare a vector of the tuple types for GetTupleType.
  877. llvm::SmallVector<SemIR::TypeId> elem_type_ids;
  878. elem_type_ids.reserve(orig_elem_type_ids.size());
  879. for (auto elem_const_id : elem_const_ids) {
  880. elem_type_ids.push_back(context_.GetTypeIdForTypeConstant(elem_const_id));
  881. }
  882. return {
  883. context_.types().GetConstantId(context_.GetTupleType(elem_type_ids))};
  884. }
  885. auto TryResolveTypedInst(SemIR::UnboundElementType inst) -> ResolveResult {
  886. auto initial_work = work_stack_.size();
  887. CARBON_CHECK(inst.type_id == SemIR::TypeId::TypeType);
  888. auto class_const_id = GetLocalConstantId(inst.class_type_id);
  889. auto elem_const_id = GetLocalConstantId(inst.element_type_id);
  890. if (HasNewWork(initial_work)) {
  891. return ResolveResult::Retry();
  892. }
  893. return {context_.types().GetConstantId(context_.GetUnboundElementType(
  894. context_.GetTypeIdForTypeConstant(class_const_id),
  895. context_.GetTypeIdForTypeConstant(elem_const_id)))};
  896. }
  897. Context& context_;
  898. SemIR::ImportIRId import_ir_id_;
  899. const SemIR::File& import_ir_;
  900. SemIR::ConstantValueStore& import_ir_constant_values_;
  901. llvm::SmallVector<Work> work_stack_;
  902. };
  903. // Returns the LocId corresponding to the input location.
  904. static auto SemIRLocToLocId(Context& context, SemIRLoc loc) -> SemIR::LocId {
  905. if (loc.is_inst_id) {
  906. return context.insts().GetLocId(loc.inst_id);
  907. } else {
  908. return loc.loc_id;
  909. }
  910. }
  911. // Replace the ImportRefUnloaded instruction with an appropriate ImportRef. This
  912. // doesn't use ReplaceInstBeforeConstantUse because it would trigger
  913. // TryEvalInst, which we want to avoid with ImportRefs.
  914. static auto SetInst(Context& context, SemIR::InstId inst_id,
  915. SemIR::TypeId type_id,
  916. SemIR::ImportIRInstId import_ir_inst_id, SemIRLoc loc,
  917. bool set_if_invalid_loc) -> void {
  918. if (auto loc_id = SemIRLocToLocId(context, loc); loc_id.is_valid()) {
  919. context.sem_ir().insts().Set(
  920. inst_id, SemIR::ImportRefUsed{type_id, import_ir_inst_id, loc_id});
  921. } else if (set_if_invalid_loc) {
  922. context.sem_ir().insts().Set(
  923. inst_id, SemIR::ImportRefLoaded{type_id, import_ir_inst_id});
  924. }
  925. }
  926. auto LoadImportRef(Context& context, SemIR::InstId inst_id, SemIRLoc loc)
  927. -> void {
  928. CARBON_KIND_SWITCH(context.insts().Get(inst_id)) {
  929. case CARBON_KIND(SemIR::ImportRefLoaded inst): {
  930. SetInst(context, inst_id, inst.type_id, inst.import_ir_inst_id, loc,
  931. /*set_if_invalid_loc=*/false);
  932. return;
  933. }
  934. case CARBON_KIND(SemIR::ImportRefUnloaded inst): {
  935. auto import_ir_inst =
  936. context.import_ir_insts().Get(inst.import_ir_inst_id);
  937. const SemIR::File& import_ir =
  938. *context.import_irs().Get(import_ir_inst.ir_id).sem_ir;
  939. auto import_inst = import_ir.insts().Get(import_ir_inst.inst_id);
  940. ImportRefResolver resolver(context, import_ir_inst.ir_id);
  941. auto type_id = resolver.ResolveType(import_inst.type_id());
  942. auto constant_id = resolver.Resolve(import_ir_inst.inst_id);
  943. SetInst(context, inst_id, type_id, inst.import_ir_inst_id, loc,
  944. /*set_if_invalid_loc=*/true);
  945. // Store the constant for both the ImportRefUsed and imported instruction.
  946. context.constant_values().Set(inst_id, constant_id);
  947. return;
  948. }
  949. default:
  950. return;
  951. }
  952. }
  953. // Imports the impl `import_impl_id` from the imported IR `import_ir`.
  954. static auto ImportImpl(Context& context, SemIR::ImportIRId import_ir_id,
  955. const SemIR::File& import_ir,
  956. SemIR::ImplId import_impl_id) -> void {
  957. // Resolve the imported impl to a local impl ID.
  958. ImportRefResolver resolver(context, import_ir_id);
  959. const auto& import_impl = import_ir.impls().Get(import_impl_id);
  960. auto self_id = resolver.ResolveType(import_impl.self_id);
  961. auto constraint_id = resolver.ResolveType(import_impl.constraint_id);
  962. // Import the definition if the impl is defined.
  963. // TODO: Do we need to check for multiple definitions?
  964. auto impl_id = context.impls().LookupOrAdd(self_id, constraint_id);
  965. if (import_impl.is_defined()) {
  966. // TODO: Create a scope for the `impl` if necessary.
  967. // TODO: Consider importing the definition_id.
  968. auto& impl = context.impls().Get(impl_id);
  969. impl.witness_id = context.AddImportRef(
  970. {.ir_id = import_ir_id, .inst_id = import_impl.witness_id});
  971. }
  972. }
  973. // TODO: This doesn't belong in this file. Consider moving the import resolver
  974. // and this file elsewhere.
  975. auto ImportImpls(Context& context) -> void {
  976. for (auto [import_index, import_ir] :
  977. llvm::enumerate(context.import_irs().array_ref())) {
  978. if (!import_ir.sem_ir) {
  979. continue;
  980. }
  981. auto import_ir_id = SemIR::ImportIRId(import_index);
  982. for (auto impl_index : llvm::seq(import_ir.sem_ir->impls().size())) {
  983. auto impl_id = SemIR::ImplId(impl_index);
  984. ImportImpl(context, import_ir_id, *import_ir.sem_ir, impl_id);
  985. }
  986. }
  987. }
  988. } // namespace Carbon::Check