generic.cpp 20 KB

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