generic.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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/generic.h"
  5. #include "common/map.h"
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/diagnostic_helpers.h"
  8. #include "toolchain/check/eval.h"
  9. #include "toolchain/check/generic_region_stack.h"
  10. #include "toolchain/check/inst.h"
  11. #include "toolchain/check/subst.h"
  12. #include "toolchain/check/type.h"
  13. #include "toolchain/check/type_completion.h"
  14. #include "toolchain/diagnostics/diagnostic.h"
  15. #include "toolchain/sem_ir/constant.h"
  16. #include "toolchain/sem_ir/generic.h"
  17. #include "toolchain/sem_ir/ids.h"
  18. #include "toolchain/sem_ir/inst.h"
  19. #include "toolchain/sem_ir/typed_insts.h"
  20. namespace Carbon::Check {
  21. static auto MakeSelfSpecificId(Context& context, SemIR::GenericId generic_id)
  22. -> SemIR::SpecificId;
  23. auto StartGenericDecl(Context& context) -> void {
  24. context.generic_region_stack().Push();
  25. }
  26. auto StartGenericDefinition(Context& context) -> void {
  27. // Push a generic region even if we don't have a generic_id. We might still
  28. // have locally-introduced generic parameters to track:
  29. //
  30. // fn F() {
  31. // let T:! type = i32;
  32. // var x: T;
  33. // }
  34. context.generic_region_stack().Push();
  35. }
  36. // Adds an instruction `generic_inst_id` to the eval block for a generic region,
  37. // which is the current instruction block. The instruction `generic_inst_id` is
  38. // expected to compute the value of the constant described by `const_inst_id` in
  39. // each specific. Forms and returns a corresponding symbolic constant ID that
  40. // refers to the substituted value of that instruction in each specific.
  41. static auto AddGenericConstantInstToEvalBlock(
  42. Context& context, SemIR::GenericId generic_id,
  43. SemIR::GenericInstIndex::Region region, SemIR::InstId const_inst_id,
  44. SemIR::InstId generic_inst_id, SemIR::ConstantDependence dependence)
  45. -> SemIR::ConstantId {
  46. auto index = SemIR::GenericInstIndex(
  47. region, context.inst_block_stack().PeekCurrentBlockContents().size());
  48. context.inst_block_stack().AddInstId(generic_inst_id);
  49. return context.constant_values().AddSymbolicConstant(
  50. {.inst_id = const_inst_id,
  51. .generic_id = generic_id,
  52. .index = index,
  53. .dependence = dependence});
  54. }
  55. namespace {
  56. // A map from an instruction ID representing a canonical symbolic constant to an
  57. // instruction within an eval block of the generic that computes the specific
  58. // value for that constant.
  59. //
  60. // We arbitrarily use a small size of 256 bytes for the map.
  61. // TODO: Determine a better number based on measurements.
  62. using ConstantsInGenericMap = Map<SemIR::InstId, SemIR::InstId, 256>;
  63. // Substitution callbacks to rebuild a generic constant in the eval block for a
  64. // generic region.
  65. class RebuildGenericConstantInEvalBlockCallbacks : public SubstInstCallbacks {
  66. public:
  67. RebuildGenericConstantInEvalBlockCallbacks(
  68. Context& context, SemIR::GenericId generic_id,
  69. SemIR::GenericInstIndex::Region region, SemIR::LocId loc_id,
  70. ConstantsInGenericMap& constants_in_generic, bool inside_redeclaration)
  71. : context_(context),
  72. generic_id_(generic_id),
  73. region_(region),
  74. loc_id_(loc_id),
  75. constants_in_generic_(constants_in_generic),
  76. inside_redeclaration_(inside_redeclaration) {}
  77. auto context() const -> Context& { return context_; }
  78. // Check for instructions for which we already have a mapping into the eval
  79. // block, and substitute them for the instructions in the eval block.
  80. auto Subst(SemIR::InstId& inst_id) const -> bool override {
  81. auto const_id = context_.constant_values().Get(inst_id);
  82. if (!const_id.has_value()) {
  83. // An unloaded import ref should never contain anything we need to
  84. // substitute into. Don't trigger loading it here.
  85. CARBON_CHECK(
  86. context_.insts().Is<SemIR::ImportRefUnloaded>(inst_id),
  87. "Substituting into instruction with invalid constant ID: {0}",
  88. context_.insts().Get(inst_id));
  89. return true;
  90. }
  91. if (!context_.constant_values().DependsOnGenericParameter(const_id)) {
  92. // This instruction doesn't have a symbolic constant value, so can't
  93. // contain any bindings that need to be substituted.
  94. return true;
  95. }
  96. // If this instruction is in the map, return the known result.
  97. if (auto result = constants_in_generic_.Lookup(
  98. context_.constant_values().GetInstId(const_id))) {
  99. // In order to reuse instructions from the generic as often as possible,
  100. // keep this instruction as-is if it already has the desired symbolic
  101. // constant value.
  102. if (const_id != context_.constant_values().Get(result.value())) {
  103. inst_id = result.value();
  104. }
  105. CARBON_CHECK(inst_id.has_value());
  106. return true;
  107. }
  108. return false;
  109. }
  110. // Build a new instruction in the eval block corresponding to the given
  111. // constant.
  112. auto Rebuild(SemIR::InstId orig_inst_id, SemIR::Inst new_inst) const
  113. -> SemIR::InstId override {
  114. auto& orig_symbolic_const = context_.constant_values().GetSymbolicConstant(
  115. context_.constant_values().Get(orig_inst_id));
  116. auto const_inst_id = orig_symbolic_const.inst_id;
  117. auto dependence = orig_symbolic_const.dependence;
  118. // We might already have an instruction in the eval block if a transitive
  119. // operand of this instruction has the same constant value.
  120. auto result = constants_in_generic_.Insert(const_inst_id, [&] {
  121. if (inside_redeclaration_) {
  122. // Adding instructions to a redeclaration causes crashes later since it
  123. // causes us to produce invalid indices into the original declaration's
  124. // set of instructions. So we terminate now and avoid adding a new
  125. // instruction and new index. It should not be possible to create this
  126. // situation where a generic redeclaration introduces new instructions
  127. // to the eval block.
  128. CARBON_FATAL("generic redeclaration differs from previous declaration");
  129. }
  130. // TODO: Add a function on `Context` to add the instruction without
  131. // inserting it into the dependent instructions list or computing a
  132. // constant value for it.
  133. // TODO: Is the location we pick here always appropriate for the new
  134. // instruction?
  135. auto inst_id = context_.sem_ir().insts().AddInNoBlock(
  136. SemIR::LocIdAndInst::UncheckedLoc(loc_id_, new_inst));
  137. auto const_id = AddGenericConstantInstToEvalBlock(
  138. context_, generic_id_, region_, const_inst_id, inst_id, dependence);
  139. context_.constant_values().Set(inst_id, const_id);
  140. return inst_id;
  141. });
  142. return result.value();
  143. }
  144. auto ReuseUnchanged(SemIR::InstId orig_inst_id) const
  145. -> SemIR::InstId override {
  146. auto inst = context_.insts().Get(orig_inst_id);
  147. CARBON_CHECK(
  148. inst.Is<SemIR::BindSymbolicName>() ||
  149. inst.Is<SemIR::SymbolicBindingPattern>(),
  150. "Instruction {0} has symbolic constant value but no symbolic operands",
  151. inst);
  152. // Rebuild the instruction anyway so that it's included in the eval block.
  153. // TODO: Can we just reuse the instruction in this case?
  154. return Rebuild(orig_inst_id, inst);
  155. }
  156. private:
  157. Context& context_;
  158. SemIR::GenericId generic_id_;
  159. SemIR::GenericInstIndex::Region region_;
  160. SemIR::LocId loc_id_;
  161. ConstantsInGenericMap& constants_in_generic_;
  162. bool inside_redeclaration_;
  163. };
  164. // Substitution callbacks to rebuild a template action. This rebuilds the action
  165. // instruction in-place if it needs to be modified.
  166. class RebuildTemplateActionInEvalBlockCallbacks final
  167. : public RebuildGenericConstantInEvalBlockCallbacks {
  168. public:
  169. RebuildTemplateActionInEvalBlockCallbacks(
  170. Context& context, SemIR::GenericId generic_id,
  171. SemIR::GenericInstIndex::Region region, SemIR::LocId loc_id,
  172. ConstantsInGenericMap& constants_in_generic, bool inside_redeclaration,
  173. SemIR::InstId action_inst_id)
  174. : RebuildGenericConstantInEvalBlockCallbacks(context, generic_id, region,
  175. loc_id, constants_in_generic,
  176. inside_redeclaration),
  177. action_inst_id_(action_inst_id) {}
  178. auto Rebuild(SemIR::InstId orig_inst_id, SemIR::Inst new_inst) const
  179. -> SemIR::InstId override {
  180. if (orig_inst_id == action_inst_id_) {
  181. // TODO: We want to ReplaceInstPreservingConstantValue here, but don't
  182. // want to evaluate the action to check the value hasn't changed.
  183. context().sem_ir().insts().Set(orig_inst_id, new_inst);
  184. return orig_inst_id;
  185. }
  186. return RebuildGenericConstantInEvalBlockCallbacks::Rebuild(orig_inst_id,
  187. new_inst);
  188. }
  189. auto ReuseUnchanged(SemIR::InstId orig_inst_id) const
  190. -> SemIR::InstId override {
  191. if (orig_inst_id == action_inst_id_) {
  192. return orig_inst_id;
  193. }
  194. return RebuildGenericConstantInEvalBlockCallbacks::ReuseUnchanged(
  195. orig_inst_id);
  196. }
  197. private:
  198. SemIR::InstId action_inst_id_;
  199. };
  200. } // namespace
  201. // Adds instructions to compute the substituted version of `type_id` in each
  202. // specific into the eval block for the generic, which is the current
  203. // instruction block. Returns a symbolic type ID that refers to the substituted
  204. // type in each specific.
  205. static auto AddGenericTypeToEvalBlock(
  206. Context& context, SemIR::GenericId generic_id,
  207. SemIR::GenericInstIndex::Region region, SemIR::LocId loc_id,
  208. ConstantsInGenericMap& constants_in_generic, bool inside_redeclaration,
  209. SemIR::TypeId type_id) -> SemIR::TypeId {
  210. // Substitute into the type's constant instruction and rebuild it in the eval
  211. // block.
  212. auto type_inst_id =
  213. SubstInst(context, context.types().GetInstId(type_id),
  214. RebuildGenericConstantInEvalBlockCallbacks(
  215. context, generic_id, region, loc_id, constants_in_generic,
  216. inside_redeclaration));
  217. return context.types().GetTypeIdForTypeInstId(type_inst_id);
  218. }
  219. // Adds instructions to compute the substituted value of `inst_id` in each
  220. // specific into the eval block for the generic, which is the current
  221. // instruction block. Returns a symbolic constant instruction ID that refers to
  222. // the substituted constant value in each specific.
  223. static auto AddGenericConstantToEvalBlock(
  224. Context& context, SemIR::GenericId generic_id,
  225. SemIR::GenericInstIndex::Region region,
  226. ConstantsInGenericMap& constants_in_generic, bool inside_redeclaration,
  227. SemIR::InstId inst_id) -> SemIR::ConstantId {
  228. // Substitute into the constant value and rebuild it in the eval block if
  229. // we've not encountered it before.
  230. auto const_inst_id = context.constant_values().GetConstantInstId(inst_id);
  231. auto callbacks = RebuildGenericConstantInEvalBlockCallbacks(
  232. context, generic_id, region, context.insts().GetLocId(inst_id),
  233. constants_in_generic, inside_redeclaration);
  234. auto new_inst_id = SubstInst(context, const_inst_id, callbacks);
  235. CARBON_CHECK(new_inst_id != const_inst_id,
  236. "No substitutions performed for generic constant {0}",
  237. context.insts().Get(inst_id));
  238. return context.constant_values().Get(new_inst_id);
  239. }
  240. // Adds an instruction that performs a template action to the eval block for the
  241. // generic. The instruction should not yet have been added to any block. The
  242. // instruction might refer to types and constants that need to be rewritten, so
  243. // substitute into it first.
  244. static auto AddTemplateActionToEvalBlock(
  245. Context& context, SemIR::GenericId generic_id,
  246. SemIR::GenericInstIndex::Region region,
  247. ConstantsInGenericMap& constants_in_generic, bool inside_redeclaration,
  248. SemIR::InstId inst_id) -> void {
  249. // Substitute into the constant value and rebuild it in the eval block.
  250. auto new_inst_id = SubstInst(
  251. context, inst_id,
  252. RebuildTemplateActionInEvalBlockCallbacks(
  253. context, generic_id, region, context.insts().GetLocId(inst_id),
  254. constants_in_generic, inside_redeclaration, inst_id));
  255. CARBON_CHECK(new_inst_id == inst_id,
  256. "Substitution changed InstId of template action");
  257. constants_in_generic.Insert(inst_id, inst_id);
  258. // Add the action to the eval block and point its constant value back to its
  259. // index within the block.
  260. auto& symbolic_constant = context.constant_values().GetSymbolicConstant(
  261. context.constant_values().Get(inst_id));
  262. symbolic_constant.generic_id = generic_id;
  263. symbolic_constant.index = SemIR::GenericInstIndex(
  264. region, context.inst_block_stack().PeekCurrentBlockContents().size());
  265. context.inst_block_stack().AddInstId(inst_id);
  266. }
  267. // Populates a map of constants in a generic from the constants in the
  268. // declaration region, in preparation for building the definition region.
  269. static auto PopulateConstantsFromDeclaration(
  270. Context& context, SemIR::GenericId generic_id,
  271. ConstantsInGenericMap& constants_in_generic) {
  272. // For the definition region, populate constants from the declaration.
  273. auto decl_eval_block = context.inst_blocks().Get(
  274. context.generics().Get(generic_id).decl_block_id);
  275. constants_in_generic.GrowForInsertCount(decl_eval_block.size());
  276. for (auto inst_id : decl_eval_block) {
  277. auto const_inst_id = context.constant_values().GetConstantInstId(inst_id);
  278. auto result = constants_in_generic.Insert(const_inst_id, inst_id);
  279. CARBON_CHECK(result.is_inserted(),
  280. "Duplicate constant in generic decl eval block: {0}",
  281. context.insts().Get(const_inst_id));
  282. }
  283. }
  284. // Builds and returns a block of instructions whose constant values need to be
  285. // evaluated in order to resolve a generic to a specific.
  286. static auto MakeGenericEvalBlock(Context& context, SemIR::GenericId generic_id,
  287. SemIR::GenericInstIndex::Region region,
  288. bool inside_redeclaration)
  289. -> SemIR::InstBlockId {
  290. context.inst_block_stack().Push();
  291. ConstantsInGenericMap constants_in_generic;
  292. if (region == SemIR::GenericInstIndex::Region::Definition ||
  293. inside_redeclaration) {
  294. PopulateConstantsFromDeclaration(context, generic_id, constants_in_generic);
  295. }
  296. // The work done in this loop might invalidate iterators into the generic
  297. // region stack, but shouldn't add new dependent instructions to the current
  298. // region.
  299. auto num_dependent_insts =
  300. context.generic_region_stack().PeekDependentInsts().size();
  301. for (auto i : llvm::seq(num_dependent_insts)) {
  302. auto [inst_id, dep_kind] =
  303. context.generic_region_stack().PeekDependentInsts()[i];
  304. // If the type is symbolic, replace it with a type specific to this generic.
  305. if ((dep_kind & GenericRegionStack::DependencyKind::SymbolicType) !=
  306. GenericRegionStack::DependencyKind::None) {
  307. auto inst = context.insts().Get(inst_id);
  308. auto type_id = AddGenericTypeToEvalBlock(
  309. context, generic_id, region, context.insts().GetLocId(inst_id),
  310. constants_in_generic, inside_redeclaration, inst.type_id());
  311. // If the generic declaration is invalid, it can result in an error.
  312. if (type_id == SemIR::ErrorInst::SingletonTypeId) {
  313. break;
  314. }
  315. // TODO: Eventually, completeness requirements should be modeled as
  316. // constraints on the generic rather than properties of the type. For now,
  317. // require the transformed type to be complete if the original was.
  318. if (context.types().IsComplete(inst.type_id())) {
  319. CompleteTypeOrCheckFail(context, type_id);
  320. }
  321. inst.SetType(type_id);
  322. context.sem_ir().insts().Set(inst_id, inst);
  323. }
  324. // If the instruction has a symbolic constant value, then make a note that
  325. // we'll need to evaluate this instruction when forming the specific. Update
  326. // the constant value of the instruction to refer to the result of that
  327. // eventual evaluation.
  328. if ((dep_kind & GenericRegionStack::DependencyKind::SymbolicConstant) !=
  329. GenericRegionStack::DependencyKind::None) {
  330. // Update the constant value to refer to this generic.
  331. context.constant_values().Set(
  332. inst_id, AddGenericConstantToEvalBlock(
  333. context, generic_id, region, constants_in_generic,
  334. inside_redeclaration, inst_id));
  335. }
  336. // If the instruction is a template action, add it directly to this position
  337. // in the eval block.
  338. if ((dep_kind & GenericRegionStack::DependencyKind::Template) !=
  339. GenericRegionStack::DependencyKind::None) {
  340. AddTemplateActionToEvalBlock(context, generic_id, region,
  341. constants_in_generic, inside_redeclaration,
  342. inst_id);
  343. }
  344. }
  345. CARBON_CHECK(
  346. num_dependent_insts ==
  347. context.generic_region_stack().PeekDependentInsts().size(),
  348. "Building eval block added new dependent insts, for example {0}",
  349. context.insts().Get(context.generic_region_stack()
  350. .PeekDependentInsts()[num_dependent_insts]
  351. .inst_id));
  352. return context.inst_block_stack().Pop();
  353. }
  354. // Builds and returns an eval block, given the list of canonical symbolic
  355. // constants that the instructions in the eval block should produce. This is
  356. // used when importing a generic.
  357. auto RebuildGenericEvalBlock(Context& context, SemIR::GenericId generic_id,
  358. SemIR::GenericInstIndex::Region region,
  359. llvm::ArrayRef<SemIR::InstId> const_ids)
  360. -> SemIR::InstBlockId {
  361. context.inst_block_stack().Push();
  362. // We say we are not inside a redeclaration since this function is used for
  363. // import and there's no redeclaration there.
  364. bool inside_redeclaration = false;
  365. ConstantsInGenericMap constants_in_generic;
  366. // For the definition region, populate constants from the declaration.
  367. if (inside_redeclaration ||
  368. region == SemIR::GenericInstIndex::Region::Definition) {
  369. PopulateConstantsFromDeclaration(context, generic_id, constants_in_generic);
  370. }
  371. constants_in_generic.GrowForInsertCount(const_ids.size());
  372. for (auto [i, inst_id] : llvm::enumerate(const_ids)) {
  373. // Build a constant in the inst block.
  374. AddGenericConstantToEvalBlock(context, generic_id, region,
  375. constants_in_generic, inside_redeclaration,
  376. inst_id);
  377. CARBON_CHECK(
  378. context.inst_block_stack().PeekCurrentBlockContents().size() == i + 1,
  379. "Produced {0} instructions when importing {1}",
  380. (context.inst_block_stack().PeekCurrentBlockContents().size() - i),
  381. context.insts().Get(inst_id));
  382. }
  383. return context.inst_block_stack().Pop();
  384. }
  385. auto DiscardGenericDecl(Context& context) -> void {
  386. context.generic_region_stack().Pop();
  387. }
  388. auto BuildGeneric(Context& context, SemIR::InstId decl_id) -> SemIR::GenericId {
  389. auto all_bindings =
  390. context.scope_stack().compile_time_bindings_stack().PeekAllValues();
  391. if (all_bindings.empty()) {
  392. CARBON_CHECK(context.generic_region_stack().PeekDependentInsts().empty(),
  393. "Have dependent instruction {0} in declaration {1} but no "
  394. "compile time bindings are in scope.",
  395. context.insts().Get(context.generic_region_stack()
  396. .PeekDependentInsts()
  397. .front()
  398. .inst_id),
  399. context.insts().Get(decl_id));
  400. context.generic_region_stack().Pop();
  401. return SemIR::GenericId::None;
  402. }
  403. // Build the new Generic object. Note that we intentionally do not hold a
  404. // persistent reference to it throughout this function, because the `generics`
  405. // collection can have items added to it by import resolution while we are
  406. // building this generic.
  407. auto bindings_id = context.inst_blocks().Add(all_bindings);
  408. SemIR::GenericId generic_id = context.generics().Add(
  409. SemIR::Generic{.decl_id = decl_id,
  410. .bindings_id = bindings_id,
  411. .self_specific_id = SemIR::SpecificId::None});
  412. // MakeSelfSpecificId could cause something to be imported, which would
  413. // invalidate the return value of `context.generics().Get(generic_id)`.
  414. auto self_specific_id = MakeSelfSpecificId(context, generic_id);
  415. context.generics().Get(generic_id).self_specific_id = self_specific_id;
  416. return generic_id;
  417. }
  418. auto FinishGenericDecl(Context& context, SemIRLoc loc,
  419. SemIR::GenericId generic_id) -> void {
  420. if (!generic_id.has_value()) {
  421. return;
  422. }
  423. auto decl_block_id = MakeGenericEvalBlock(
  424. context, generic_id, SemIR::GenericInstIndex::Region::Declaration,
  425. /*inside_redeclaration=*/false);
  426. context.generic_region_stack().Pop();
  427. context.generics().Get(generic_id).decl_block_id = decl_block_id;
  428. ResolveSpecificDeclaration(context, loc,
  429. context.generics().GetSelfSpecific(generic_id));
  430. }
  431. auto BuildGenericDecl(Context& context, SemIR::InstId decl_id)
  432. -> SemIR::GenericId {
  433. SemIR::GenericId generic_id = BuildGeneric(context, decl_id);
  434. if (generic_id.has_value()) {
  435. FinishGenericDecl(context, decl_id, generic_id);
  436. }
  437. return generic_id;
  438. }
  439. auto FinishGenericRedecl(Context& context, SemIR::GenericId generic_id)
  440. -> void {
  441. if (!generic_id.has_value()) {
  442. context.generic_region_stack().Pop();
  443. return;
  444. }
  445. auto definition_block_id = MakeGenericEvalBlock(
  446. context, generic_id, SemIR::GenericInstIndex::Region::Declaration,
  447. /*inside_redeclaration=*/true);
  448. CARBON_CHECK(definition_block_id == SemIR::InstBlockId::Empty);
  449. context.generic_region_stack().Pop();
  450. }
  451. auto FinishGenericDefinition(Context& context, SemIR::GenericId generic_id)
  452. -> void {
  453. if (!generic_id.has_value()) {
  454. // TODO: We can have symbolic constants in a context that had a non-generic
  455. // declaration, for example if there's a local generic let binding in a
  456. // function definition. Handle this case somehow -- perhaps by forming
  457. // substituted constant values now.
  458. context.generic_region_stack().Pop();
  459. return;
  460. }
  461. auto definition_block_id = MakeGenericEvalBlock(
  462. context, generic_id, SemIR::GenericInstIndex::Region::Definition,
  463. /*inside_redeclaration=*/false);
  464. context.generics().Get(generic_id).definition_block_id = definition_block_id;
  465. context.generic_region_stack().Pop();
  466. }
  467. auto ResolveSpecificDeclaration(Context& context, SemIRLoc loc,
  468. SemIR::SpecificId specific_id) -> void {
  469. // If this is the first time we've formed this specific, evaluate its decl
  470. // block to form information about the specific.
  471. if (!context.specifics().Get(specific_id).decl_block_id.has_value()) {
  472. // Set a placeholder value as the decl block ID so we won't attempt to
  473. // recursively resolve the same specific.
  474. context.specifics().Get(specific_id).decl_block_id =
  475. SemIR::InstBlockId::Empty;
  476. auto decl_block_id =
  477. TryEvalBlockForSpecific(context, loc, specific_id,
  478. SemIR::GenericInstIndex::Region::Declaration);
  479. // Note that TryEvalBlockForSpecific may reallocate the list of specifics,
  480. // so re-lookup the specific here.
  481. context.specifics().Get(specific_id).decl_block_id = decl_block_id;
  482. }
  483. }
  484. auto MakeSpecific(Context& context, SemIRLoc loc, SemIR::GenericId generic_id,
  485. SemIR::InstBlockId args_id) -> SemIR::SpecificId {
  486. auto specific_id = context.specifics().GetOrAdd(generic_id, args_id);
  487. ResolveSpecificDeclaration(context, loc, specific_id);
  488. return specific_id;
  489. }
  490. auto MakeSpecific(Context& context, SemIRLoc loc, SemIR::GenericId generic_id,
  491. llvm::ArrayRef<SemIR::InstId> args) -> SemIR::SpecificId {
  492. auto args_id = context.inst_blocks().AddCanonical(args);
  493. return MakeSpecific(context, loc, generic_id, args_id);
  494. }
  495. static auto MakeSelfSpecificId(Context& context, SemIR::GenericId generic_id)
  496. -> SemIR::SpecificId {
  497. if (!generic_id.has_value()) {
  498. return SemIR::SpecificId::None;
  499. }
  500. auto& generic = context.generics().Get(generic_id);
  501. auto args = context.inst_blocks().Get(generic.bindings_id);
  502. // Form a canonical argument list for the generic.
  503. llvm::SmallVector<SemIR::InstId> arg_ids;
  504. arg_ids.reserve(args.size());
  505. for (auto arg_id : args) {
  506. arg_ids.push_back(context.constant_values().GetConstantInstId(arg_id));
  507. }
  508. auto args_id = context.inst_blocks().AddCanonical(arg_ids);
  509. return context.specifics().GetOrAdd(generic_id, args_id);
  510. }
  511. auto MakeSelfSpecific(Context& context, SemIRLoc loc,
  512. SemIR::GenericId generic_id) -> SemIR::SpecificId {
  513. // Build a corresponding specific.
  514. SemIR::SpecificId specific_id = MakeSelfSpecificId(context, generic_id);
  515. // TODO: This could be made more efficient. We don't need to perform
  516. // substitution here; we know we want identity mappings for all constants and
  517. // types. We could also consider not storing the mapping at all in this case.
  518. ResolveSpecificDeclaration(context, loc, specific_id);
  519. return specific_id;
  520. }
  521. auto ResolveSpecificDefinition(Context& context, SemIRLoc loc,
  522. SemIR::SpecificId specific_id) -> bool {
  523. // TODO: Handle recursive resolution of the same generic definition.
  524. auto& specific = context.specifics().Get(specific_id);
  525. auto generic_id = specific.generic_id;
  526. CARBON_CHECK(generic_id.has_value(), "Specific with no generic ID");
  527. if (!specific.definition_block_id.has_value()) {
  528. // Evaluate the eval block for the definition of the generic.
  529. auto& generic = context.generics().Get(generic_id);
  530. if (!generic.definition_block_id.has_value()) {
  531. // The generic is not defined yet.
  532. return false;
  533. }
  534. auto definition_block_id = TryEvalBlockForSpecific(
  535. context, loc, specific_id, SemIR::GenericInstIndex::Region::Definition);
  536. // Note that TryEvalBlockForSpecific may reallocate the list of specifics,
  537. // so re-lookup the specific here.
  538. context.specifics().Get(specific_id).definition_block_id =
  539. definition_block_id;
  540. }
  541. return true;
  542. }
  543. auto GetInstForSpecific(Context& context, SemIR::SpecificId specific_id)
  544. -> SemIR::InstId {
  545. CARBON_CHECK(specific_id.has_value());
  546. const auto& specific = context.specifics().Get(specific_id);
  547. const auto& generic = context.generics().Get(specific.generic_id);
  548. auto decl = context.insts().Get(generic.decl_id);
  549. CARBON_KIND_SWITCH(decl) {
  550. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  551. return context.types().GetInstId(
  552. GetClassType(context, class_decl.class_id, specific_id));
  553. }
  554. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  555. return context.types().GetInstId(
  556. GetInterfaceType(context, interface_decl.interface_id, specific_id));
  557. }
  558. case SemIR::FunctionDecl::Kind: {
  559. return context.constant_values().GetInstId(TryEvalInst(
  560. context, SemIR::InstId::None,
  561. SemIR::SpecificFunction{
  562. .type_id = GetSingletonType(
  563. context, SemIR::SpecificFunctionType::SingletonInstId),
  564. .callee_id = generic.decl_id,
  565. .specific_id = specific_id}));
  566. }
  567. case SemIR::AssociatedConstantDecl::Kind: {
  568. // TODO: We don't have a good instruction to use here.
  569. return generic.decl_id;
  570. }
  571. default: {
  572. CARBON_FATAL("Unknown kind for generic declaration {0}", decl);
  573. }
  574. }
  575. }
  576. auto DiagnoseIfGenericMissingExplicitParameters(
  577. Context& context, SemIR::EntityWithParamsBase& entity_base) -> void {
  578. if (!entity_base.implicit_param_patterns_id.has_value() ||
  579. entity_base.param_patterns_id.has_value()) {
  580. return;
  581. }
  582. CARBON_DIAGNOSTIC(GenericMissingExplicitParameters, Error,
  583. "expected explicit parameters after implicit parameters");
  584. context.emitter().Emit(entity_base.last_param_node_id,
  585. GenericMissingExplicitParameters);
  586. }
  587. } // namespace Carbon::Check