subst.cpp 14 KB

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