generic.cpp 18 KB

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