subst.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. #ifndef CARBON_TOOLCHAIN_CHECK_SUBST_H_
  5. #define CARBON_TOOLCHAIN_CHECK_SUBST_H_
  6. #include "toolchain/check/context.h"
  7. #include "toolchain/sem_ir/ids.h"
  8. namespace Carbon::Check {
  9. // Callbacks used by SubstInst to recursively substitute into and rebuild an
  10. // instruction.
  11. class SubstInstCallbacks {
  12. public:
  13. // Performs any needed substitution into an instruction. The instruction ID
  14. // should be updated as necessary to represent the new instruction. Returns
  15. // true if the resulting instruction ID is fully-substituted, or false if
  16. // substitution may be needed into operands of the instruction.
  17. virtual auto Subst(SemIR::InstId& inst_id) const -> bool = 0;
  18. // Rebuilds an instruction whose operands were changed by substitution.
  19. // `orig_inst_id` is the instruction prior to substitution, and `new_inst` is
  20. // the substituted instruction. Returns the new instruction ID to use to refer
  21. // to `new_inst`.
  22. virtual auto Rebuild(SemIR::InstId orig_inst_id, SemIR::Inst new_inst) const
  23. -> SemIR::InstId = 0;
  24. };
  25. // Performs substitution into `inst_id` and its operands recursively, using
  26. // `callbacks` to process each instruction. For each instruction encountered,
  27. // calls `Subst` to perform substitution on that instruction.
  28. //
  29. // If `Subst` returns false, the instruction is decomposed into its operands,
  30. // which are substituted recursively, and if any of them change then `Rebuild`
  31. // is used to build a new instruction with the substituted operands.
  32. auto SubstInst(Context& context, SemIR::InstId inst_id,
  33. const SubstInstCallbacks& callbacks) -> SemIR::InstId;
  34. // A substitution that is being performed.
  35. struct Substitution {
  36. // The index of a `BindSymbolicName` instruction that is being replaced.
  37. SemIR::CompileTimeBindIndex bind_id;
  38. // The replacement constant value to substitute.
  39. SemIR::ConstantId replacement_id;
  40. };
  41. using Substitutions = llvm::ArrayRef<Substitution>;
  42. // Replaces the `BindSymbolicName` instruction `bind_id` with `replacement_id`
  43. // throughout the constant `const_id`, and returns the substituted value.
  44. auto SubstConstant(Context& context, SemIR::ConstantId const_id,
  45. Substitutions substitutions) -> SemIR::ConstantId;
  46. } // namespace Carbon::Check
  47. #endif // CARBON_TOOLCHAIN_CHECK_SUBST_H_