subst.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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::TypeInstId 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::TypeInstId 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(
  170. i,
  171. {.name_id = old_fields[i].name_id,
  172. .type_inst_id = context.types().GetAsTypeInstId(worklist.Pop())});
  173. }
  174. return new_fields.GetCanonical().index;
  175. }
  176. case CARBON_KIND(SemIR::SpecificId specific_id): {
  177. return pop_specific(specific_id).index;
  178. }
  179. case CARBON_KIND(SemIR::SpecificInterfaceId interface_id): {
  180. auto interface = context.specific_interfaces().Get(interface_id);
  181. auto specific_id = pop_specific(interface.specific_id);
  182. return context.specific_interfaces()
  183. .Add({
  184. .interface_id = interface.interface_id,
  185. .specific_id = specific_id,
  186. })
  187. .index;
  188. }
  189. case CARBON_KIND(SemIR::FacetTypeId facet_type_id): {
  190. const auto& old_facet_type_info =
  191. context.facet_types().Get(facet_type_id);
  192. SemIR::FacetTypeInfo new_facet_type_info;
  193. // Since these were added to a stack, we get them back in reverse order.
  194. new_facet_type_info.rewrite_constraints.resize(
  195. old_facet_type_info.rewrite_constraints.size(),
  196. SemIR::FacetTypeInfo::RewriteConstraint::None);
  197. for (auto& new_constraint :
  198. llvm::reverse(new_facet_type_info.rewrite_constraints)) {
  199. auto rhs_id = worklist.Pop();
  200. auto lhs_id = worklist.Pop();
  201. new_constraint = {.lhs_id = lhs_id, .rhs_id = rhs_id};
  202. }
  203. new_facet_type_info.self_impls_constraints.resize(
  204. old_facet_type_info.self_impls_constraints.size(),
  205. SemIR::SpecificInterface::None);
  206. for (auto [old_constraint, new_constraint] : llvm::reverse(
  207. llvm::zip(old_facet_type_info.self_impls_constraints,
  208. new_facet_type_info.self_impls_constraints))) {
  209. new_constraint = {
  210. .interface_id = old_constraint.interface_id,
  211. .specific_id = pop_specific(old_constraint.specific_id)};
  212. }
  213. new_facet_type_info.extend_constraints.resize(
  214. old_facet_type_info.extend_constraints.size(),
  215. SemIR::SpecificInterface::None);
  216. for (auto [old_constraint, new_constraint] :
  217. llvm::reverse(llvm::zip(old_facet_type_info.extend_constraints,
  218. new_facet_type_info.extend_constraints))) {
  219. new_constraint = {
  220. .interface_id = old_constraint.interface_id,
  221. .specific_id = pop_specific(old_constraint.specific_id)};
  222. }
  223. new_facet_type_info.other_requirements =
  224. old_facet_type_info.other_requirements;
  225. new_facet_type_info.Canonicalize();
  226. return context.facet_types().Add(new_facet_type_info).index;
  227. }
  228. default:
  229. return arg.value();
  230. }
  231. }
  232. // Pops the operands of the specified instruction off the worklist and rebuilds
  233. // the instruction with the updated operands if it has changed.
  234. static auto Rebuild(Context& context, Worklist& worklist, SemIR::InstId inst_id,
  235. const SubstInstCallbacks& callbacks) -> SemIR::InstId {
  236. auto inst = context.insts().Get(inst_id);
  237. // Note that we pop in reverse order because we pushed them in forwards order.
  238. int32_t arg1 = PopOperand(context, worklist, inst.arg1_and_kind());
  239. int32_t arg0 = PopOperand(context, worklist, inst.arg0_and_kind());
  240. auto type_id = inst.type_id().has_value()
  241. ? context.types().GetTypeIdForTypeInstId(worklist.Pop())
  242. : SemIR::TypeId::None;
  243. if (type_id == inst.type_id() && arg0 == inst.arg0() && arg1 == inst.arg1()) {
  244. return callbacks.ReuseUnchanged(inst_id);
  245. }
  246. // TODO: Do we need to require this type to be complete?
  247. inst.SetType(type_id);
  248. inst.SetArgs(arg0, arg1);
  249. return callbacks.Rebuild(inst_id, inst);
  250. }
  251. auto SubstInst(Context& context, SemIR::InstId inst_id,
  252. const SubstInstCallbacks& callbacks) -> SemIR::InstId {
  253. Worklist worklist(inst_id);
  254. // For each instruction that forms part of the constant, we will visit it
  255. // twice:
  256. //
  257. // - First, we visit it with `is_expanded == false`, we add all of its
  258. // operands onto the worklist, and process them by following this same
  259. // process.
  260. // - Then, once all operands are processed, we visit the instruction with
  261. // `is_expanded == true`, pop the operands back off the worklist, and if any
  262. // of them changed, rebuild this instruction.
  263. //
  264. // The second step is skipped if we can detect in the first step that the
  265. // instruction will not need to be rebuilt.
  266. int index = 0;
  267. while (index != -1) {
  268. auto& item = worklist[index];
  269. if (item.is_expanded) {
  270. // Rebuild this item if necessary. Note that this might pop items from the
  271. // worklist but does not reallocate, so does not invalidate `item`.
  272. item.inst_id = Rebuild(context, worklist, item.inst_id, callbacks);
  273. index = item.next_index;
  274. continue;
  275. }
  276. if (callbacks.Subst(item.inst_id)) {
  277. index = item.next_index;
  278. continue;
  279. }
  280. // Extract the operands of this item into the worklist. Note that this
  281. // modifies the worklist, so it's not safe to use `item` after
  282. // `ExpandOperands` returns.
  283. item.is_expanded = true;
  284. int first_operand = worklist.size();
  285. int next_index = item.next_index;
  286. ExpandOperands(context, worklist, item.inst_id);
  287. // If there are any operands, go and update them before rebuilding this
  288. // item.
  289. if (worklist.size() > first_operand) {
  290. worklist.back().next_index = index;
  291. index = first_operand;
  292. } else {
  293. // No need to rebuild this instruction: its operands can't be changed by
  294. // substitution because it has none.
  295. index = next_index;
  296. }
  297. }
  298. CARBON_CHECK(worklist.size() == 1,
  299. "Unexpected data left behind in work list");
  300. return worklist.back().inst_id;
  301. }
  302. auto SubstInst(Context& context, SemIR::TypeInstId inst_id,
  303. const SubstInstCallbacks& callbacks) -> SemIR::TypeInstId {
  304. return context.types().GetAsTypeInstId(
  305. SubstInst(context, static_cast<SemIR::InstId>(inst_id), callbacks));
  306. }
  307. namespace {
  308. // Callbacks for performing substitution of a set of Substitutions into a
  309. // symbolic constant.
  310. class SubstConstantCallbacks final : public SubstInstCallbacks {
  311. public:
  312. // `context` must not be null.
  313. SubstConstantCallbacks(Context* context, Substitutions substitutions)
  314. : context_(context), substitutions_(substitutions) {}
  315. // Applies the given Substitutions to an instruction, in order to replace
  316. // BindSymbolicName instructions with the value of the binding.
  317. auto Subst(SemIR::InstId& inst_id) const -> bool override {
  318. if (context_->constant_values().Get(inst_id).is_concrete()) {
  319. // This instruction is a concrete constant, so can't contain any
  320. // bindings that need to be substituted.
  321. return true;
  322. }
  323. auto entity_name_id = SemIR::EntityNameId::None;
  324. if (auto bind =
  325. context_->insts().TryGetAs<SemIR::BindSymbolicName>(inst_id)) {
  326. entity_name_id = bind->entity_name_id;
  327. } else if (auto bind =
  328. context_->insts().TryGetAs<SemIR::SymbolicBindingPattern>(
  329. inst_id)) {
  330. entity_name_id = bind->entity_name_id;
  331. } else {
  332. return false;
  333. }
  334. // This is a symbolic binding. Check if we're substituting it.
  335. // TODO: Consider building a hash map for substitutions. We might have a
  336. // lot of them.
  337. for (auto [bind_index, replacement_id] : substitutions_) {
  338. if (context_->entity_names().Get(entity_name_id).bind_index() ==
  339. bind_index) {
  340. // This is the binding we're replacing. Perform substitution.
  341. inst_id = context_->constant_values().GetInstId(replacement_id);
  342. return true;
  343. }
  344. }
  345. // If it's not being substituted, don't look through it. Its constant
  346. // value doesn't depend on its operand.
  347. return true;
  348. }
  349. // Rebuilds an instruction by building a new constant.
  350. auto Rebuild(SemIR::InstId old_inst_id, SemIR::Inst new_inst) const
  351. -> SemIR::InstId override {
  352. auto const_id = EvalOrAddInst(
  353. *context_,
  354. SemIR::LocIdAndInst::UncheckedLoc(
  355. context_->insts().GetCanonicalLocId(old_inst_id).ToImplicit(),
  356. new_inst));
  357. CARBON_CHECK(const_id.has_value(),
  358. "Substitution into constant produced non-constant");
  359. return context_->constant_values().GetInstId(const_id);
  360. }
  361. private:
  362. Context* context_;
  363. Substitutions substitutions_;
  364. };
  365. } // namespace
  366. auto SubstConstant(Context& context, SemIR::ConstantId const_id,
  367. Substitutions substitutions) -> SemIR::ConstantId {
  368. CARBON_CHECK(const_id.is_constant(), "Substituting into non-constant");
  369. if (substitutions.empty()) {
  370. // Nothing to substitute.
  371. return const_id;
  372. }
  373. if (!const_id.is_symbolic()) {
  374. // A concrete constant can't contain a reference to a symbolic binding.
  375. return const_id;
  376. }
  377. auto subst_inst_id =
  378. SubstInst(context, context.constant_values().GetInstId(const_id),
  379. SubstConstantCallbacks(&context, substitutions));
  380. return context.constant_values().Get(subst_inst_id);
  381. }
  382. } // namespace Carbon::Check