generic.cpp 18 KB

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