import_ref.cpp 54 KB

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