subst.cpp 15 KB

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