generic.cpp 18 KB

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