generic.cpp 12 KB

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