generic.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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/eval.h"
  8. #include "toolchain/check/generic_region_stack.h"
  9. #include "toolchain/check/subst.h"
  10. #include "toolchain/sem_ir/ids.h"
  11. #include "toolchain/sem_ir/inst.h"
  12. #include "toolchain/sem_ir/typed_insts.h"
  13. namespace Carbon::Check {
  14. auto StartGenericDecl(Context& context) -> void {
  15. context.generic_region_stack().Push();
  16. }
  17. auto StartGenericDefinition(Context& context) -> void {
  18. // Push a generic region even if we don't have a generic_id. We might still
  19. // have locally-introduced generic parameters to track:
  20. //
  21. // fn F() {
  22. // let T:! type = i32;
  23. // var x: T;
  24. // }
  25. context.generic_region_stack().Push();
  26. }
  27. // Adds an instruction `generic_inst_id` to the eval block for a generic region,
  28. // which is the current instruction block. The instruction `generic_inst_id` is
  29. // expected to compute the value of the constant described by `const_inst_id` in
  30. // each specific. Forms and returns a corresponding symbolic constant ID that
  31. // refers to the substituted value of that instruction in each specific.
  32. static auto AddGenericConstantInstToEvalBlock(
  33. Context& context, SemIR::GenericId generic_id,
  34. SemIR::GenericInstIndex::Region region, SemIR::InstId const_inst_id,
  35. SemIR::InstId generic_inst_id) -> SemIR::ConstantId {
  36. auto index = SemIR::GenericInstIndex(
  37. region, context.inst_block_stack().PeekCurrentBlockContents().size());
  38. context.inst_block_stack().AddInstId(generic_inst_id);
  39. return context.constant_values().AddSymbolicConstant(
  40. {.inst_id = const_inst_id, .generic_id = generic_id, .index = index});
  41. }
  42. namespace {
  43. // A map from an instruction ID representing a canonical symbolic constant to an
  44. // instruction within an eval block of the generic that computes the specific
  45. // value for that constant.
  46. //
  47. // We arbitrarily use a small size of 256 bytes for the map.
  48. // TODO: Determine a better number based on measurements.
  49. using ConstantsInGenericMap = Map<SemIR::InstId, SemIR::InstId, 256>;
  50. // Substitution callbacks to rebuild a generic constant in the eval block for a
  51. // generic region.
  52. class RebuildGenericConstantInEvalBlockCallbacks final
  53. : public SubstInstCallbacks {
  54. public:
  55. RebuildGenericConstantInEvalBlockCallbacks(
  56. Context& context, SemIR::GenericId generic_id,
  57. SemIR::GenericInstIndex::Region region, SemIR::LocId loc_id,
  58. ConstantsInGenericMap& constants_in_generic)
  59. : context_(context),
  60. generic_id_(generic_id),
  61. region_(region),
  62. loc_id_(loc_id),
  63. constants_in_generic_(constants_in_generic) {}
  64. // Check for instructions for which we already have a mapping into the eval
  65. // block, and substitute them for the instructions in the eval block.
  66. auto Subst(SemIR::InstId& inst_id) const -> bool override {
  67. auto const_id = context_.constant_values().Get(inst_id);
  68. if (!const_id.is_valid()) {
  69. // An unloaded import ref should never contain anything we need to
  70. // substitute into. Don't trigger loading it here.
  71. CARBON_CHECK(
  72. context_.insts().Is<SemIR::ImportRefUnloaded>(inst_id),
  73. "Substituting into instruction with invalid constant ID: {0}",
  74. context_.insts().Get(inst_id));
  75. return true;
  76. }
  77. if (!context_.constant_values().DependsOnGenericParameter(const_id)) {
  78. // This instruction doesn't have a symbolic constant value, so can't
  79. // contain any bindings that need to be substituted.
  80. return true;
  81. }
  82. // If this instruction is in the map, return the known result.
  83. if (auto result = constants_in_generic_.Lookup(
  84. context_.constant_values().GetInstId(const_id))) {
  85. // In order to reuse instructions from the generic as often as possible,
  86. // keep this instruction as-is if it already has the desired symbolic
  87. // constant value.
  88. if (const_id != context_.constant_values().Get(result.value())) {
  89. inst_id = result.value();
  90. }
  91. CARBON_CHECK(inst_id.is_valid());
  92. return true;
  93. }
  94. // If the instruction is a symbolic binding, build a version in the eval
  95. // block.
  96. if (auto binding =
  97. context_.insts().TryGetAs<SemIR::BindSymbolicName>(inst_id)) {
  98. if (context_.entity_names()
  99. .Get(binding->entity_name_id)
  100. .bind_index.is_valid()) {
  101. inst_id = Rebuild(inst_id, *binding);
  102. return true;
  103. }
  104. }
  105. if (auto pattern =
  106. context_.insts().TryGetAs<SemIR::SymbolicBindingPattern>(inst_id)) {
  107. inst_id = Rebuild(inst_id, *pattern);
  108. return true;
  109. }
  110. return false;
  111. }
  112. // Build a new instruction in the eval block corresponding to the given
  113. // constant.
  114. auto Rebuild(SemIR::InstId orig_inst_id, SemIR::Inst new_inst) const
  115. -> SemIR::InstId override {
  116. auto const_inst_id =
  117. context_.constant_values().GetConstantInstId(orig_inst_id);
  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. // TODO: Add a function on `Context` to add the instruction without
  122. // inserting it into the dependent instructions list or computing a
  123. // constant value for it.
  124. // TODO: Is the location we pick here always appropriate for the new
  125. // instruction?
  126. auto inst_id = context_.sem_ir().insts().AddInNoBlock(
  127. SemIR::LocIdAndInst::UncheckedLoc(loc_id_, new_inst));
  128. auto const_id = AddGenericConstantInstToEvalBlock(
  129. context_, generic_id_, region_, const_inst_id, inst_id);
  130. context_.constant_values().Set(inst_id, const_id);
  131. return inst_id;
  132. });
  133. return result.value();
  134. }
  135. private:
  136. Context& context_;
  137. SemIR::GenericId generic_id_;
  138. SemIR::GenericInstIndex::Region region_;
  139. SemIR::LocId loc_id_;
  140. ConstantsInGenericMap& constants_in_generic_;
  141. };
  142. } // namespace
  143. // Adds instructions to compute the substituted version of `type_id` in each
  144. // specific into the eval block for the generic, which is the current
  145. // instruction block. Returns a symbolic type ID that refers to the substituted
  146. // type in each specific.
  147. static auto AddGenericTypeToEvalBlock(
  148. Context& context, SemIR::GenericId generic_id,
  149. SemIR::GenericInstIndex::Region region, SemIR::LocId loc_id,
  150. ConstantsInGenericMap& constants_in_generic, SemIR::TypeId type_id)
  151. -> SemIR::TypeId {
  152. // Substitute into the type's constant instruction and rebuild it in the eval
  153. // block.
  154. auto type_inst_id =
  155. SubstInst(context, context.types().GetInstId(type_id),
  156. RebuildGenericConstantInEvalBlockCallbacks(
  157. context, generic_id, region, loc_id, constants_in_generic));
  158. return context.GetTypeIdForTypeInst(type_inst_id);
  159. }
  160. // Adds instructions to compute the substituted value of `inst_id` in each
  161. // specific into the eval block for the generic, which is the current
  162. // instruction block. Returns a symbolic constant instruction ID that refers to
  163. // the substituted constant value in each specific.
  164. static auto AddGenericConstantToEvalBlock(
  165. Context& context, SemIR::GenericId generic_id,
  166. SemIR::GenericInstIndex::Region region,
  167. ConstantsInGenericMap& constants_in_generic, SemIR::InstId inst_id)
  168. -> SemIR::ConstantId {
  169. // Substitute into the constant value and rebuild it in the eval block if
  170. // we've not encountered it before.
  171. auto const_inst_id = context.constant_values().GetConstantInstId(inst_id);
  172. auto new_inst_id =
  173. SubstInst(context, const_inst_id,
  174. RebuildGenericConstantInEvalBlockCallbacks(
  175. context, generic_id, region,
  176. context.insts().GetLocId(inst_id), constants_in_generic));
  177. CARBON_CHECK(new_inst_id != const_inst_id,
  178. "Did not apply any substitutions to symbolic constant {0}",
  179. context.insts().Get(const_inst_id));
  180. return context.constant_values().Get(new_inst_id);
  181. }
  182. // Populates a map of constants in a generic from the constants in the
  183. // declaration region, in preparation for building the definition region.
  184. static auto PopulateConstantsFromDeclaration(
  185. Context& context, SemIR::GenericId generic_id,
  186. ConstantsInGenericMap& constants_in_generic) {
  187. // For the definition region, populate constants from the declaration.
  188. auto decl_eval_block = context.inst_blocks().Get(
  189. context.generics().Get(generic_id).decl_block_id);
  190. constants_in_generic.GrowForInsertCount(decl_eval_block.size());
  191. for (auto inst_id : decl_eval_block) {
  192. auto const_inst_id = context.constant_values().GetConstantInstId(inst_id);
  193. auto result = constants_in_generic.Insert(const_inst_id, inst_id);
  194. CARBON_CHECK(result.is_inserted(),
  195. "Duplicate constant in generic decl eval block: {0}",
  196. context.insts().Get(const_inst_id));
  197. }
  198. }
  199. // Builds and returns a block of instructions whose constant values need to be
  200. // evaluated in order to resolve a generic to a specific.
  201. static auto MakeGenericEvalBlock(Context& context, SemIR::GenericId generic_id,
  202. SemIR::GenericInstIndex::Region region)
  203. -> SemIR::InstBlockId {
  204. context.inst_block_stack().Push();
  205. ConstantsInGenericMap constants_in_generic;
  206. // For the definition region, populate constants from the declaration.
  207. if (region == SemIR::GenericInstIndex::Region::Definition) {
  208. PopulateConstantsFromDeclaration(context, generic_id, constants_in_generic);
  209. }
  210. // The work done in this loop might invalidate iterators into the generic
  211. // region stack, but shouldn't add new dependent instructions to the current
  212. // region.
  213. auto num_dependent_insts =
  214. context.generic_region_stack().PeekDependentInsts().size();
  215. for (auto i : llvm::seq(num_dependent_insts)) {
  216. auto [inst_id, dep_kind] =
  217. context.generic_region_stack().PeekDependentInsts()[i];
  218. // If the type is symbolic, replace it with a type specific to this generic.
  219. if ((dep_kind & GenericRegionStack::DependencyKind::SymbolicType) !=
  220. GenericRegionStack::DependencyKind::None) {
  221. auto inst = context.insts().Get(inst_id);
  222. auto type_id = AddGenericTypeToEvalBlock(
  223. context, generic_id, region, context.insts().GetLocId(inst_id),
  224. constants_in_generic, inst.type_id());
  225. // TODO: Eventually, completeness requirements should be modeled as
  226. // constraints on the generic rather than properties of the type. For now,
  227. // require the transformed type to be complete if the original was.
  228. if (context.types().IsComplete(inst.type_id())) {
  229. context.CompleteTypeOrCheckFail(type_id);
  230. }
  231. inst.SetType(type_id);
  232. context.sem_ir().insts().Set(inst_id, inst);
  233. }
  234. // If the instruction has a symbolic constant value, then make a note that
  235. // we'll need to evaluate this instruction when forming the specific. Update
  236. // the constant value of the instruction to refer to the result of that
  237. // eventual evaluation.
  238. if ((dep_kind & GenericRegionStack::DependencyKind::SymbolicConstant) !=
  239. GenericRegionStack::DependencyKind::None) {
  240. // Update the constant value to refer to this generic.
  241. context.constant_values().Set(
  242. inst_id,
  243. AddGenericConstantToEvalBlock(context, generic_id, region,
  244. constants_in_generic, inst_id));
  245. }
  246. }
  247. CARBON_CHECK(
  248. num_dependent_insts ==
  249. context.generic_region_stack().PeekDependentInsts().size(),
  250. "Building eval block added new dependent insts, for example {0}",
  251. context.insts().Get(context.generic_region_stack()
  252. .PeekDependentInsts()[num_dependent_insts]
  253. .inst_id));
  254. return context.inst_block_stack().Pop();
  255. }
  256. // Builds and returns an eval block, given the list of canonical symbolic
  257. // constants that the instructions in the eval block should produce. This is
  258. // used when importing a generic.
  259. auto RebuildGenericEvalBlock(Context& context, SemIR::GenericId generic_id,
  260. SemIR::GenericInstIndex::Region region,
  261. llvm::ArrayRef<SemIR::InstId> const_ids)
  262. -> SemIR::InstBlockId {
  263. context.inst_block_stack().Push();
  264. ConstantsInGenericMap constants_in_generic;
  265. // For the definition region, populate constants from the declaration.
  266. if (region == SemIR::GenericInstIndex::Region::Definition) {
  267. PopulateConstantsFromDeclaration(context, generic_id, constants_in_generic);
  268. }
  269. constants_in_generic.GrowForInsertCount(const_ids.size());
  270. for (auto [i, inst_id] : llvm::enumerate(const_ids)) {
  271. // Build a constant in the inst block.
  272. AddGenericConstantToEvalBlock(context, generic_id, region,
  273. constants_in_generic, inst_id);
  274. CARBON_CHECK(
  275. context.inst_block_stack().PeekCurrentBlockContents().size() == i + 1,
  276. "Produced {0} instructions when importing {1}",
  277. (context.inst_block_stack().PeekCurrentBlockContents().size() - i),
  278. context.insts().Get(inst_id));
  279. }
  280. return context.inst_block_stack().Pop();
  281. }
  282. auto DiscardGenericDecl(Context& context) -> void {
  283. context.generic_region_stack().Pop();
  284. }
  285. auto FinishGenericDecl(Context& context, SemIR::InstId decl_id)
  286. -> SemIR::GenericId {
  287. auto all_bindings =
  288. context.scope_stack().compile_time_bindings_stack().PeekAllValues();
  289. if (all_bindings.empty()) {
  290. CARBON_CHECK(context.generic_region_stack().PeekDependentInsts().empty(),
  291. "Have dependent instructions but no compile time bindings are "
  292. "in scope.");
  293. context.generic_region_stack().Pop();
  294. return SemIR::GenericId::Invalid;
  295. }
  296. // Build the new Generic object. Note that we intentionally do not hold a
  297. // persistent reference to it throughout this function, because the `generics`
  298. // collection can have items added to it by import resolution while we are
  299. // building this generic.
  300. auto bindings_id = context.inst_blocks().Add(all_bindings);
  301. auto generic_id = context.generics().Add(
  302. SemIR::Generic{.decl_id = decl_id,
  303. .bindings_id = bindings_id,
  304. .self_specific_id = SemIR::SpecificId::Invalid});
  305. auto decl_block_id = MakeGenericEvalBlock(
  306. context, generic_id, SemIR::GenericInstIndex::Region::Declaration);
  307. context.generic_region_stack().Pop();
  308. context.generics().Get(generic_id).decl_block_id = decl_block_id;
  309. auto self_specific_id = MakeSelfSpecific(context, decl_id, generic_id);
  310. context.generics().Get(generic_id).self_specific_id = self_specific_id;
  311. return generic_id;
  312. }
  313. auto FinishGenericRedecl(Context& context, SemIR::InstId /*decl_id*/,
  314. SemIR::GenericId /*generic_id*/) -> void {
  315. // TODO: Compare contents of this declaration with the existing one on the
  316. // generic.
  317. context.generic_region_stack().Pop();
  318. }
  319. auto FinishGenericDefinition(Context& context, SemIR::GenericId generic_id)
  320. -> void {
  321. if (!generic_id.is_valid()) {
  322. // TODO: We can have symbolic constants in a context that had a non-generic
  323. // declaration, for example if there's a local generic let binding in a
  324. // function definition. Handle this case somehow -- perhaps by forming
  325. // substituted constant values now.
  326. context.generic_region_stack().Pop();
  327. return;
  328. }
  329. auto definition_block_id = MakeGenericEvalBlock(
  330. context, generic_id, SemIR::GenericInstIndex::Region::Definition);
  331. context.generics().Get(generic_id).definition_block_id = definition_block_id;
  332. context.generic_region_stack().Pop();
  333. }
  334. auto MakeSpecific(Context& context, SemIRLoc loc, SemIR::GenericId generic_id,
  335. SemIR::InstBlockId args_id) -> SemIR::SpecificId {
  336. auto specific_id = context.specifics().GetOrAdd(generic_id, args_id);
  337. // If this is the first time we've formed this specific, evaluate its decl
  338. // block to form information about the specific.
  339. if (!context.specifics().Get(specific_id).decl_block_id.is_valid()) {
  340. auto decl_block_id =
  341. TryEvalBlockForSpecific(context, loc, specific_id,
  342. SemIR::GenericInstIndex::Region::Declaration);
  343. // Note that TryEvalBlockForSpecific may reallocate the list of specifics,
  344. // so re-lookup the specific here.
  345. context.specifics().Get(specific_id).decl_block_id = decl_block_id;
  346. }
  347. return specific_id;
  348. }
  349. auto MakeSelfSpecific(Context& context, SemIRLoc loc,
  350. SemIR::GenericId generic_id) -> SemIR::SpecificId {
  351. if (!generic_id.is_valid()) {
  352. return SemIR::SpecificId::Invalid;
  353. }
  354. auto& generic = context.generics().Get(generic_id);
  355. auto args = context.inst_blocks().Get(generic.bindings_id);
  356. // Form a canonical argument list for the generic.
  357. llvm::SmallVector<SemIR::InstId> arg_ids;
  358. arg_ids.reserve(args.size());
  359. for (auto arg_id : args) {
  360. arg_ids.push_back(context.constant_values().GetConstantInstId(arg_id));
  361. }
  362. auto args_id = context.inst_blocks().AddCanonical(arg_ids);
  363. // Build a corresponding specific.
  364. // TODO: This could be made more efficient. We don't need to perform
  365. // substitution here; we know we want identity mappings for all constants and
  366. // types. We could also consider not storing the mapping at all in this case.
  367. return MakeSpecific(context, loc, generic_id, args_id);
  368. }
  369. auto ResolveSpecificDefinition(Context& context, SemIRLoc loc,
  370. SemIR::SpecificId specific_id) -> bool {
  371. auto& specific = context.specifics().Get(specific_id);
  372. auto generic_id = specific.generic_id;
  373. CARBON_CHECK(generic_id.is_valid(), "Specific with no generic ID");
  374. if (!specific.definition_block_id.is_valid()) {
  375. // Evaluate the eval block for the definition of the generic.
  376. auto& generic = context.generics().Get(generic_id);
  377. if (!generic.definition_block_id.is_valid()) {
  378. // The generic is not defined yet.
  379. return false;
  380. }
  381. auto definition_block_id = TryEvalBlockForSpecific(
  382. context, loc, specific_id, SemIR::GenericInstIndex::Region::Definition);
  383. // Note that TryEvalBlockForSpecific may reallocate the list of specifics,
  384. // so re-lookup the specific here.
  385. context.specifics().Get(specific_id).definition_block_id =
  386. definition_block_id;
  387. }
  388. return true;
  389. }
  390. auto GetInstForSpecific(Context& context, SemIR::SpecificId specific_id)
  391. -> SemIR::InstId {
  392. CARBON_CHECK(specific_id.is_valid());
  393. const auto& specific = context.specifics().Get(specific_id);
  394. const auto& generic = context.generics().Get(specific.generic_id);
  395. auto decl = context.insts().Get(generic.decl_id);
  396. CARBON_KIND_SWITCH(decl) {
  397. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  398. return context.types().GetInstId(
  399. context.GetClassType(class_decl.class_id, specific_id));
  400. }
  401. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  402. return context.types().GetInstId(
  403. context.GetInterfaceType(interface_decl.interface_id, specific_id));
  404. }
  405. case SemIR::FunctionDecl::Kind: {
  406. return context.constant_values().GetInstId(
  407. TryEvalInst(context, SemIR::InstId::Invalid,
  408. SemIR::SpecificFunction{
  409. .type_id = context.GetSingletonType(
  410. SemIR::SpecificFunctionType::SingletonInstId),
  411. .callee_id = generic.decl_id,
  412. .specific_id = specific_id}));
  413. }
  414. default: {
  415. CARBON_FATAL("Unknown kind for generic declaration {0}", decl);
  416. }
  417. }
  418. }
  419. } // namespace Carbon::Check