subst.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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/subst.h"
  5. #include "toolchain/check/eval.h"
  6. #include "toolchain/check/generic.h"
  7. #include "toolchain/sem_ir/copy_on_write_block.h"
  8. #include "toolchain/sem_ir/ids.h"
  9. #include "toolchain/sem_ir/inst.h"
  10. namespace Carbon::Check {
  11. namespace {
  12. // Information about an instruction that we are substituting into.
  13. struct WorklistItem {
  14. // The instruction that we are substituting into.
  15. SemIR::InstId inst_id;
  16. // Whether the operands of this instruction have been added to the worklist.
  17. bool is_expanded : 1;
  18. // The index of the worklist item to process after we finish updating this
  19. // one. For the final child of an instruction, this is the parent. For any
  20. // other child, this is the index of the next child of the parent. For the
  21. // root, this is -1.
  22. int next_index : 31;
  23. };
  24. // A list of instructions that we're currently in the process of substituting
  25. // into. For details of the algorithm used here, see `SubstConstant`.
  26. class Worklist {
  27. public:
  28. explicit Worklist(SemIR::InstId root_id) {
  29. worklist_.push_back(
  30. {.inst_id = root_id, .is_expanded = false, .next_index = -1});
  31. }
  32. auto operator[](int index) -> WorklistItem& { return worklist_[index]; }
  33. auto size() -> int { return worklist_.size(); }
  34. auto back() -> WorklistItem& { return worklist_.back(); }
  35. auto Push(SemIR::InstId inst_id) -> void {
  36. CARBON_CHECK(inst_id.has_value());
  37. worklist_.push_back({.inst_id = inst_id,
  38. .is_expanded = false,
  39. .next_index = static_cast<int>(worklist_.size() + 1)});
  40. CARBON_CHECK(worklist_.back().next_index > 0, "Constant too large.");
  41. }
  42. auto Pop() -> SemIR::InstId { return worklist_.pop_back_val().inst_id; }
  43. private:
  44. // Constants can get pretty large, so use a large worklist. This should be
  45. // about 4KiB, which should be small enough to comfortably fit on the stack,
  46. // but large enough that it's unlikely that we'll need a heap allocation.
  47. llvm::SmallVector<WorklistItem, 512> worklist_;
  48. };
  49. } // namespace
  50. // Pushes the specified operand onto the worklist.
  51. static auto PushOperand(Context& context, Worklist& worklist,
  52. SemIR::IdKind kind, int32_t arg) -> void {
  53. auto push_block = [&](SemIR::InstBlockId block_id) {
  54. for (auto inst_id :
  55. context.inst_blocks().Get(SemIR::InstBlockId(block_id))) {
  56. worklist.Push(inst_id);
  57. }
  58. };
  59. auto push_specific = [&](SemIR::SpecificId specific_id) {
  60. if (specific_id.has_value()) {
  61. push_block(context.specifics().Get(specific_id).args_id);
  62. }
  63. };
  64. switch (kind) {
  65. case SemIR::IdKind::For<SemIR::InstId>:
  66. if (SemIR::InstId inst_id(arg); inst_id.has_value()) {
  67. worklist.Push(inst_id);
  68. }
  69. break;
  70. case SemIR::IdKind::For<SemIR::TypeId>:
  71. if (SemIR::TypeId type_id(arg); type_id.has_value()) {
  72. worklist.Push(context.types().GetInstId(type_id));
  73. }
  74. break;
  75. case SemIR::IdKind::For<SemIR::InstBlockId>:
  76. push_block(SemIR::InstBlockId(arg));
  77. break;
  78. case SemIR::IdKind::For<SemIR::StructTypeFieldsId>: {
  79. for (auto field :
  80. context.struct_type_fields().Get(SemIR::StructTypeFieldsId(arg))) {
  81. worklist.Push(context.types().GetInstId(field.type_id));
  82. }
  83. break;
  84. }
  85. case SemIR::IdKind::For<SemIR::TypeBlockId>:
  86. for (auto type_id : context.type_blocks().Get(SemIR::TypeBlockId(arg))) {
  87. worklist.Push(context.types().GetInstId(type_id));
  88. }
  89. break;
  90. case SemIR::IdKind::For<SemIR::SpecificId>:
  91. push_specific(SemIR::SpecificId(arg));
  92. break;
  93. case SemIR::IdKind::For<SemIR::FacetTypeId>: {
  94. const auto& facet_type_info =
  95. context.facet_types().Get(SemIR::FacetTypeId(arg));
  96. for (auto interface : facet_type_info.impls_constraints) {
  97. push_specific(interface.specific_id);
  98. }
  99. for (auto rewrite : facet_type_info.rewrite_constraints) {
  100. auto lhs_inst_id =
  101. context.constant_values().GetInstId(rewrite.lhs_const_id);
  102. auto rhs_inst_id =
  103. context.constant_values().GetInstId(rewrite.rhs_const_id);
  104. worklist.Push(lhs_inst_id);
  105. worklist.Push(rhs_inst_id);
  106. }
  107. // TODO: Process other requirements as well.
  108. break;
  109. }
  110. default:
  111. break;
  112. }
  113. }
  114. // Converts the operands of this instruction into `InstId`s and pushes them onto
  115. // the worklist.
  116. static auto ExpandOperands(Context& context, Worklist& worklist,
  117. SemIR::InstId inst_id) -> void {
  118. auto inst = context.insts().Get(inst_id);
  119. auto kinds = inst.ArgKinds();
  120. PushOperand(context, worklist, SemIR::IdKind::For<SemIR::TypeId>,
  121. inst.type_id().index);
  122. PushOperand(context, worklist, kinds.first, inst.arg0());
  123. PushOperand(context, worklist, kinds.second, inst.arg1());
  124. }
  125. // Pops the specified operand from the worklist and returns it.
  126. static auto PopOperand(Context& context, Worklist& worklist, SemIR::IdKind kind,
  127. int32_t arg) -> int32_t {
  128. auto pop_block_id = [&](SemIR::InstBlockId old_inst_block_id) {
  129. auto size = context.inst_blocks().Get(old_inst_block_id).size();
  130. SemIR::CopyOnWriteInstBlock new_inst_block(context.sem_ir(),
  131. old_inst_block_id);
  132. for (auto i : llvm::reverse(llvm::seq(size))) {
  133. new_inst_block.Set(i, worklist.Pop());
  134. }
  135. return new_inst_block.GetCanonical();
  136. };
  137. auto pop_specific = [&](SemIR::SpecificId specific_id) {
  138. if (!specific_id.has_value()) {
  139. return specific_id;
  140. }
  141. auto& specific = context.specifics().Get(specific_id);
  142. auto args_id = pop_block_id(specific.args_id);
  143. return context.specifics().GetOrAdd(specific.generic_id, args_id);
  144. };
  145. switch (kind) {
  146. case SemIR::IdKind::For<SemIR::InstId>: {
  147. SemIR::InstId inst_id(arg);
  148. if (!inst_id.has_value()) {
  149. return arg;
  150. }
  151. return worklist.Pop().index;
  152. }
  153. case SemIR::IdKind::For<SemIR::TypeId>: {
  154. SemIR::TypeId type_id(arg);
  155. if (!type_id.has_value()) {
  156. return arg;
  157. }
  158. return context.GetTypeIdForTypeInst(worklist.Pop()).index;
  159. }
  160. case SemIR::IdKind::For<SemIR::InstBlockId>: {
  161. return pop_block_id(SemIR::InstBlockId(arg)).index;
  162. }
  163. case SemIR::IdKind::For<SemIR::StructTypeFieldsId>: {
  164. SemIR::StructTypeFieldsId old_fields_id(arg);
  165. auto old_fields = context.struct_type_fields().Get(old_fields_id);
  166. SemIR::CopyOnWriteStructTypeFieldsBlock new_fields(context.sem_ir(),
  167. old_fields_id);
  168. for (auto i : llvm::reverse(llvm::seq(old_fields.size()))) {
  169. new_fields.Set(
  170. i, {.name_id = old_fields[i].name_id,
  171. .type_id = context.GetTypeIdForTypeInst(worklist.Pop())});
  172. }
  173. return new_fields.GetCanonical().index;
  174. }
  175. case SemIR::IdKind::For<SemIR::TypeBlockId>: {
  176. SemIR::TypeBlockId old_type_block_id(arg);
  177. auto size = context.type_blocks().Get(old_type_block_id).size();
  178. SemIR::CopyOnWriteTypeBlock new_type_block(context.sem_ir(),
  179. old_type_block_id);
  180. for (auto i : llvm::reverse(llvm::seq(size))) {
  181. new_type_block.Set(i, context.GetTypeIdForTypeInst(worklist.Pop()));
  182. }
  183. return new_type_block.GetCanonical().index;
  184. }
  185. case SemIR::IdKind::For<SemIR::SpecificId>: {
  186. return pop_specific(SemIR::SpecificId(arg)).index;
  187. }
  188. case SemIR::IdKind::For<SemIR::FacetTypeId>: {
  189. const auto& old_facet_type_info =
  190. context.facet_types().Get(SemIR::FacetTypeId(arg));
  191. SemIR::FacetTypeInfo new_facet_type_info = old_facet_type_info;
  192. // Since these were added to a stack, we get them back in reverse order.
  193. for (auto i : llvm::reverse(
  194. llvm::seq(old_facet_type_info.rewrite_constraints.size()))) {
  195. auto rhs_id = context.constant_values().Get(worklist.Pop());
  196. auto lhs_id = context.constant_values().Get(worklist.Pop());
  197. new_facet_type_info.rewrite_constraints[i].rhs_const_id = rhs_id;
  198. new_facet_type_info.rewrite_constraints[i].lhs_const_id = lhs_id;
  199. }
  200. for (auto i : llvm::reverse(
  201. llvm::seq(old_facet_type_info.impls_constraints.size()))) {
  202. new_facet_type_info.impls_constraints[i].specific_id =
  203. pop_specific(old_facet_type_info.impls_constraints[i].specific_id);
  204. }
  205. new_facet_type_info.Canonicalize();
  206. return context.facet_types().Add(new_facet_type_info).index;
  207. }
  208. default:
  209. return arg;
  210. }
  211. }
  212. // Pops the operands of the specified instruction off the worklist and rebuilds
  213. // the instruction with the updated operands if it has changed.
  214. static auto Rebuild(Context& context, Worklist& worklist, SemIR::InstId inst_id,
  215. const SubstInstCallbacks& callbacks) -> SemIR::InstId {
  216. auto inst = context.insts().Get(inst_id);
  217. auto kinds = inst.ArgKinds();
  218. // Note that we pop in reverse order because we pushed them in forwards order.
  219. int32_t arg1 = PopOperand(context, worklist, kinds.second, inst.arg1());
  220. int32_t arg0 = PopOperand(context, worklist, kinds.first, inst.arg0());
  221. int32_t type_id =
  222. PopOperand(context, worklist, SemIR::IdKind::For<SemIR::TypeId>,
  223. inst.type_id().index);
  224. if (type_id == inst.type_id().index && arg0 == inst.arg0() &&
  225. arg1 == inst.arg1()) {
  226. return inst_id;
  227. }
  228. // TODO: Do we need to require this type to be complete?
  229. inst.SetType(SemIR::TypeId(type_id));
  230. inst.SetArgs(arg0, arg1);
  231. return callbacks.Rebuild(inst_id, inst);
  232. }
  233. auto SubstInst(Context& context, SemIR::InstId inst_id,
  234. const SubstInstCallbacks& callbacks) -> SemIR::InstId {
  235. Worklist worklist(inst_id);
  236. // For each instruction that forms part of the constant, we will visit it
  237. // twice:
  238. //
  239. // - First, we visit it with `is_expanded == false`, we add all of its
  240. // operands onto the worklist, and process them by following this same
  241. // process.
  242. // - Then, once all operands are processed, we visit the instruction with
  243. // `is_expanded == true`, pop the operands back off the worklist, and if any
  244. // of them changed, rebuild this instruction.
  245. //
  246. // The second step is skipped if we can detect in the first step that the
  247. // instruction will not need to be rebuilt.
  248. int index = 0;
  249. while (index != -1) {
  250. auto& item = worklist[index];
  251. if (item.is_expanded) {
  252. // Rebuild this item if necessary. Note that this might pop items from the
  253. // worklist but does not reallocate, so does not invalidate `item`.
  254. item.inst_id = Rebuild(context, worklist, item.inst_id, callbacks);
  255. index = item.next_index;
  256. continue;
  257. }
  258. if (callbacks.Subst(item.inst_id)) {
  259. index = item.next_index;
  260. continue;
  261. }
  262. // Extract the operands of this item into the worklist. Note that this
  263. // modifies the worklist, so it's not safe to use `item` after
  264. // `ExpandOperands` returns.
  265. item.is_expanded = true;
  266. int first_operand = worklist.size();
  267. int next_index = item.next_index;
  268. ExpandOperands(context, worklist, item.inst_id);
  269. // If there are any operands, go and update them before rebuilding this
  270. // item.
  271. if (worklist.size() > first_operand) {
  272. worklist.back().next_index = index;
  273. index = first_operand;
  274. } else {
  275. // No need to rebuild this instruction: its operands can't be changed by
  276. // substitution because it has none.
  277. index = next_index;
  278. }
  279. }
  280. CARBON_CHECK(worklist.size() == 1,
  281. "Unexpected data left behind in work list");
  282. return worklist.back().inst_id;
  283. }
  284. namespace {
  285. // Callbacks for performing substitution of a set of Substitutions into a
  286. // symbolic constant.
  287. class SubstConstantCallbacks final : public SubstInstCallbacks {
  288. public:
  289. SubstConstantCallbacks(Context& context, Substitutions substitutions)
  290. : context_(context), substitutions_(substitutions) {}
  291. // Applies the given Substitutions to an instruction, in order to replace
  292. // BindSymbolicName instructions with the value of the binding.
  293. auto Subst(SemIR::InstId& inst_id) const -> bool override {
  294. if (context_.constant_values().Get(inst_id).is_template()) {
  295. // This instruction is a template constant, so can't contain any
  296. // bindings that need to be substituted.
  297. return true;
  298. }
  299. auto entity_name_id = SemIR::EntityNameId::None;
  300. if (auto bind =
  301. context_.insts().TryGetAs<SemIR::BindSymbolicName>(inst_id)) {
  302. entity_name_id = bind->entity_name_id;
  303. } else if (auto bind =
  304. context_.insts().TryGetAs<SemIR::SymbolicBindingPattern>(
  305. inst_id)) {
  306. entity_name_id = bind->entity_name_id;
  307. } else {
  308. return false;
  309. }
  310. // This is a symbolic binding. Check if we're substituting it.
  311. // TODO: Consider building a hash map for substitutions. We might have a
  312. // lot of them.
  313. for (auto [bind_index, replacement_id] : substitutions_) {
  314. if (context_.entity_names().Get(entity_name_id).bind_index ==
  315. bind_index) {
  316. // This is the binding we're replacing. Perform substitution.
  317. inst_id = context_.constant_values().GetInstId(replacement_id);
  318. return true;
  319. }
  320. }
  321. // If it's not being substituted, don't look through it. Its constant
  322. // value doesn't depend on its operand.
  323. return true;
  324. }
  325. // Rebuilds an instruction by building a new constant.
  326. auto Rebuild(SemIR::InstId /*old_inst_id*/, SemIR::Inst new_inst) const
  327. -> SemIR::InstId override {
  328. auto result_id = TryEvalInst(context_, SemIR::InstId::None, new_inst);
  329. CARBON_CHECK(result_id.is_constant(),
  330. "Substitution into constant produced non-constant");
  331. return context_.constant_values().GetInstId(result_id);
  332. }
  333. private:
  334. Context& context_;
  335. Substitutions substitutions_;
  336. };
  337. } // namespace
  338. auto SubstConstant(Context& context, SemIR::ConstantId const_id,
  339. Substitutions substitutions) -> SemIR::ConstantId {
  340. CARBON_CHECK(const_id.is_constant(), "Substituting into non-constant");
  341. if (substitutions.empty()) {
  342. // Nothing to substitute.
  343. return const_id;
  344. }
  345. if (!const_id.is_symbolic()) {
  346. // A template constant can't contain a reference to a symbolic binding.
  347. return const_id;
  348. }
  349. auto subst_inst_id =
  350. SubstInst(context, context.constant_values().GetInstId(const_id),
  351. SubstConstantCallbacks(context, substitutions));
  352. return context.constant_values().Get(subst_inst_id);
  353. }
  354. } // namespace Carbon::Check