subst.cpp 16 KB

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