generic.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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/check/eval.h"
  7. #include "toolchain/check/generic_region_stack.h"
  8. #include "toolchain/check/subst.h"
  9. #include "toolchain/sem_ir/ids.h"
  10. namespace Carbon::Check {
  11. auto StartGenericDecl(Context& context) -> void {
  12. context.generic_region_stack().Push();
  13. }
  14. auto StartGenericDefinition(Context& context) -> void {
  15. // Push a generic region even if we don't have a generic_id. We might still
  16. // have locally-introduced generic parameters to track:
  17. //
  18. // fn F() {
  19. // let T:! type = i32;
  20. // var x: T;
  21. // }
  22. context.generic_region_stack().Push();
  23. }
  24. // Adds an instruction `generic_inst_id` to the eval block for a generic region,
  25. // which is the current instruction block. The instruction `generic_inst_id` is
  26. // expected to compute the value of the constant described by `const_inst_id` in
  27. // each instance of the generic. Forms and returns a corresponding symbolic
  28. // constant ID that refers to the substituted value of that instruction in each
  29. // instance of the generic.
  30. static auto AddGenericConstantToEvalBlock(
  31. Context& context, SemIR::GenericId generic_id,
  32. SemIR::GenericInstIndex::Region region, SemIR::InstId const_inst_id,
  33. SemIR::InstId generic_inst_id) -> SemIR::ConstantId {
  34. auto index = SemIR::GenericInstIndex(
  35. region, context.inst_block_stack().PeekCurrentBlockContents().size());
  36. context.inst_block_stack().AddInstId(generic_inst_id);
  37. return context.constant_values().AddSymbolicConstant(
  38. {.inst_id = const_inst_id, .generic_id = generic_id, .index = index});
  39. }
  40. namespace {
  41. // Substitution callbacks to rebuild a generic type in the eval block for a
  42. // generic region.
  43. class RebuildGenericTypeInEvalBlockCallbacks : public SubstInstCallbacks {
  44. public:
  45. RebuildGenericTypeInEvalBlockCallbacks(
  46. Context& context, SemIR::GenericId generic_id,
  47. SemIR::GenericInstIndex::Region region,
  48. Map<SemIR::InstId, SemIR::InstId>& constants_in_generic)
  49. : context_(context),
  50. generic_id_(generic_id),
  51. region_(region),
  52. constants_in_generic_(constants_in_generic) {}
  53. // Check for instructions for which we already have a mapping into the eval
  54. // block, and substitute them for the instructions in the eval block. Note
  55. // that this will at least include mappings for the `BindSymbolicName`
  56. // instructions that introduce our parameters.
  57. auto Subst(SemIR::InstId& inst_id) const -> bool override {
  58. if (context_.constant_values().Get(inst_id).is_template()) {
  59. // This instruction is a template constant, so can't contain any
  60. // bindings that need to be substituted.
  61. return true;
  62. }
  63. // If this instruction is in the map, return the known result.
  64. if (auto result = constants_in_generic_.Lookup(inst_id)) {
  65. inst_id = result.value();
  66. CARBON_CHECK(inst_id.is_valid());
  67. return true;
  68. }
  69. return false;
  70. }
  71. // Build a new instruction in the eval block corresponding to the given
  72. // constant.
  73. auto Rebuild(SemIR::InstId orig_inst_id, SemIR::Inst new_inst) const
  74. -> SemIR::InstId override {
  75. // TODO: Add a function on `Context` to add the instruction without
  76. // inserting it into the dependent instructions list or computing a constant
  77. // value for it.
  78. auto inst_id = context_.sem_ir().insts().AddInNoBlock(
  79. SemIR::LocIdAndInst::NoLoc(new_inst));
  80. auto result = constants_in_generic_.Insert(orig_inst_id, inst_id);
  81. CARBON_CHECK(result.is_inserted())
  82. << "Substituted into an instruction that was already in the map.";
  83. auto const_id = AddGenericConstantToEvalBlock(
  84. context_, generic_id_, region_, orig_inst_id, inst_id);
  85. context_.constant_values().Set(inst_id, const_id);
  86. return inst_id;
  87. }
  88. private:
  89. Context& context_;
  90. SemIR::GenericId generic_id_;
  91. SemIR::GenericInstIndex::Region region_;
  92. Map<SemIR::InstId, SemIR::InstId>& constants_in_generic_;
  93. };
  94. } // namespace
  95. // Adds instructions to compute the substituted version of `type_id` in each
  96. // instance of a generic into the eval block for the generic, which is the
  97. // current instruction block. Returns a symbolic type ID that refers to the
  98. // substituted type in each instance of the generic.
  99. static auto AddGenericTypeToEvalBlock(
  100. Context& context, SemIR::GenericId generic_id,
  101. SemIR::GenericInstIndex::Region region,
  102. Map<SemIR::InstId, SemIR::InstId>& constants_in_generic,
  103. SemIR::TypeId type_id) -> SemIR::TypeId {
  104. // Substitute into the type's constant instruction and rebuild it in the eval
  105. // block.
  106. auto type_inst_id =
  107. SubstInst(context, context.types().GetInstId(type_id),
  108. RebuildGenericTypeInEvalBlockCallbacks(
  109. context, generic_id, region, constants_in_generic));
  110. return context.GetTypeIdForTypeInst(type_inst_id);
  111. }
  112. // Builds and returns a block of instructions whose constant values need to be
  113. // evaluated in order to resolve a generic instance.
  114. static auto MakeGenericEvalBlock(Context& context, SemIR::GenericId generic_id,
  115. SemIR::GenericInstIndex::Region region)
  116. -> SemIR::InstBlockId {
  117. context.inst_block_stack().Push();
  118. Map<SemIR::InstId, SemIR::InstId> constants_in_generic;
  119. // TODO: For the definition region, populate constants from the declaration.
  120. // The work done in this loop might invalidate iterators into the generic
  121. // region stack, but shouldn't add new dependent instructions to the current
  122. // region.
  123. auto num_dependent_insts =
  124. context.generic_region_stack().PeekDependentInsts().size();
  125. for (auto i : llvm::seq(num_dependent_insts)) {
  126. auto [inst_id, dep_kind] =
  127. context.generic_region_stack().PeekDependentInsts()[i];
  128. // If the type is symbolic, replace it with a type specific to this generic.
  129. if ((dep_kind & GenericRegionStack::DependencyKind::SymbolicType) !=
  130. GenericRegionStack::DependencyKind::None) {
  131. auto inst = context.insts().Get(inst_id);
  132. inst.SetType(AddGenericTypeToEvalBlock(
  133. context, generic_id, region, constants_in_generic, inst.type_id()));
  134. context.sem_ir().insts().Set(inst_id, inst);
  135. }
  136. // If the instruction has a symbolic constant value, then make a note that
  137. // we'll need to evaluate this instruction in the generic instance. Update
  138. // the constant value of the instruction to refer to the result of that
  139. // eventual evaluation.
  140. if ((dep_kind & GenericRegionStack::DependencyKind::SymbolicConstant) !=
  141. GenericRegionStack::DependencyKind::None) {
  142. auto const_inst_id = context.constant_values().GetConstantInstId(inst_id);
  143. // Create a new symbolic constant representing this instruction in this
  144. // generic, if it doesn't already exist.
  145. auto result = constants_in_generic.Insert(const_inst_id, inst_id);
  146. auto const_id =
  147. result.is_inserted()
  148. ? AddGenericConstantToEvalBlock(context, generic_id, region,
  149. const_inst_id, inst_id)
  150. : context.constant_values().Get(result.value());
  151. context.constant_values().Set(inst_id, const_id);
  152. }
  153. }
  154. CARBON_CHECK(num_dependent_insts ==
  155. context.generic_region_stack().PeekDependentInsts().size())
  156. << "Building eval block added new dependent insts, for example "
  157. << context.insts().Get(context.generic_region_stack()
  158. .PeekDependentInsts()[num_dependent_insts]
  159. .inst_id);
  160. return context.inst_block_stack().Pop();
  161. }
  162. auto FinishGenericDecl(Context& context, SemIR::InstId decl_id)
  163. -> SemIR::GenericId {
  164. auto all_bindings =
  165. context.scope_stack().compile_time_bindings_stack().PeekAllValues();
  166. if (all_bindings.empty()) {
  167. CARBON_CHECK(context.generic_region_stack().PeekDependentInsts().empty())
  168. << "Have dependent instructions but no compile time bindings are in "
  169. "scope.";
  170. context.generic_region_stack().Pop();
  171. return SemIR::GenericId::Invalid;
  172. }
  173. // Build the new Generic object. Note that we intentionally do not hold a
  174. // persistent reference to it throughout this function, because the `generics`
  175. // collection can have items added to it by import resolution while we are
  176. // building this generic.
  177. auto bindings_id = context.inst_blocks().Add(all_bindings);
  178. auto generic_id = context.generics().Add(
  179. SemIR::Generic{.decl_id = decl_id,
  180. .bindings_id = bindings_id,
  181. .self_instance_id = SemIR::GenericInstanceId::Invalid});
  182. auto decl_block_id = MakeGenericEvalBlock(
  183. context, generic_id, SemIR::GenericInstIndex::Region::Declaration);
  184. context.generic_region_stack().Pop();
  185. context.generics().Get(generic_id).decl_block_id = decl_block_id;
  186. auto self_instance_id = MakeGenericSelfInstance(context, generic_id);
  187. context.generics().Get(generic_id).self_instance_id = self_instance_id;
  188. return generic_id;
  189. }
  190. auto FinishGenericRedecl(Context& context, SemIR::InstId /*decl_id*/,
  191. SemIR::GenericId /*generic_id*/) -> void {
  192. // TODO: Compare contents of this declaration with the existing one on the
  193. // generic.
  194. context.generic_region_stack().Pop();
  195. }
  196. auto FinishGenericDefinition(Context& context, SemIR::GenericId generic_id)
  197. -> void {
  198. if (!generic_id.is_valid()) {
  199. // TODO: We can have symbolic constants in a context that had a non-generic
  200. // declaration, for example if there's a local generic let binding in a
  201. // function definition. Handle this case somehow -- perhaps by forming
  202. // substituted constant values now.
  203. context.generic_region_stack().Pop();
  204. return;
  205. }
  206. // TODO: Track the list of dependent instructions in this region.
  207. context.generic_region_stack().Pop();
  208. }
  209. auto MakeGenericInstance(Context& context, SemIR::GenericId generic_id,
  210. SemIR::InstBlockId args_id)
  211. -> SemIR::GenericInstanceId {
  212. auto instance_id = context.generic_instances().GetOrAdd(generic_id, args_id);
  213. // TODO: Remove this once we import generics properly.
  214. if (!generic_id.is_valid()) {
  215. return instance_id;
  216. }
  217. // If this is the first time we've formed this instance, evaluate its decl
  218. // block to form information about the instance.
  219. if (!context.generic_instances().Get(instance_id).decl_block_id.is_valid()) {
  220. auto decl_block_id = TryEvalBlockForSpecific(
  221. context, instance_id, SemIR::GenericInstIndex::Region::Declaration);
  222. // Note that TryEvalBlockForSpecific may reallocate the list of generic
  223. // instances, so re-lookup the instance here.
  224. context.generic_instances().Get(instance_id).decl_block_id = decl_block_id;
  225. }
  226. return instance_id;
  227. }
  228. auto MakeGenericSelfInstance(Context& context, SemIR::GenericId generic_id)
  229. -> SemIR::GenericInstanceId {
  230. if (!generic_id.is_valid()) {
  231. return SemIR::GenericInstanceId::Invalid;
  232. }
  233. auto& generic = context.generics().Get(generic_id);
  234. auto args = context.inst_blocks().Get(generic.bindings_id);
  235. // Form a canonical argument list for the generic.
  236. llvm::SmallVector<SemIR::InstId> arg_ids;
  237. arg_ids.reserve(args.size());
  238. for (auto arg_id : args) {
  239. arg_ids.push_back(context.constant_values().GetConstantInstId(arg_id));
  240. }
  241. auto args_id = context.inst_blocks().AddCanonical(arg_ids);
  242. // Build a corresponding instance.
  243. // TODO: This could be made more efficient. We don't need to perform
  244. // substitution here; we know we want identity mappings for all constants and
  245. // types. We could also consider not storing the mapping at all in this case.
  246. return MakeGenericInstance(context, generic_id, args_id);
  247. }
  248. auto GetTypeInInstance(Context& context, SemIR::GenericInstanceId instance_id,
  249. SemIR::TypeId type_id) -> SemIR::TypeId {
  250. auto const_id = context.types().GetConstantId(type_id);
  251. auto inst_const_id =
  252. GetConstantInInstance(context.sem_ir(), instance_id, const_id);
  253. if (inst_const_id == const_id) {
  254. // Common case: not an instance constant.
  255. return type_id;
  256. }
  257. return context.GetTypeIdForTypeConstant(inst_const_id);
  258. }
  259. } // namespace Carbon::Check