subst.cpp 19 KB

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