import_ref.cpp 48 KB

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