generic.cpp 21 KB

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