subst.cpp 16 KB

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