generic.cpp 22 KB

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