eval.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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_EVAL_H_
  5. #define CARBON_TOOLCHAIN_CHECK_EVAL_H_
  6. #include "toolchain/check/context.h"
  7. #include "toolchain/sem_ir/ids.h"
  8. #include "toolchain/sem_ir/inst.h"
  9. namespace Carbon::Check {
  10. // Adds a `ConstantId` for a constant that has been imported from another IR.
  11. // Does not evaluate the instruction, instead trusting that it is already in a
  12. // suitable form, but does canonicalize the operands if necessary.
  13. // TODO: Rely on import to canonicalize the operands to avoid this work.
  14. auto AddImportedConstant(Context& context, SemIR::Inst inst)
  15. -> SemIR::ConstantId;
  16. // Evaluates the instruction `inst`. If `inst_id` is specified, it is the ID of
  17. // the instruction; otherwise, evaluation of the instruction must not require an
  18. // `InstId` to be provided.
  19. auto TryEvalInstUnsafe(Context& context, SemIR::InstId inst_id,
  20. SemIR::Inst inst) -> SemIR::ConstantId;
  21. // Determines the phase of the instruction `inst_id`, and returns its constant
  22. // value if it has constant phase. If it has runtime phase, returns
  23. // `SemIR::ConstantId::NotConstant`.
  24. inline auto TryEvalInst(Context& context, SemIR::InstId inst_id)
  25. -> SemIR::ConstantId {
  26. return TryEvalInstUnsafe(context, inst_id, context.insts().Get(inst_id));
  27. }
  28. // Same, but for a typed instruction that doesn't have an InstId assigned yet,
  29. // in the case where evaluation doesn't need an InstId. This can be used to
  30. // avoid allocating an instruction in the case where you just want a constant
  31. // value and the instruction is known to not matter. However, even then care
  32. // should be taken: if the produced constant is symbolic, you may still need an
  33. // instruction to associate the constant with the enclosing generic.
  34. template <typename InstT>
  35. requires(!InstT::Kind.constant_needs_inst_id())
  36. auto TryEvalInst(Context& context, InstT inst) -> SemIR::ConstantId {
  37. return TryEvalInstUnsafe(context, SemIR::InstId::None, inst);
  38. }
  39. // Evaluates the eval block for a region of a specific. Produces a block
  40. // containing the evaluated constant values of the instructions in the eval
  41. // block.
  42. auto TryEvalBlockForSpecific(Context& context, SemIRLoc loc,
  43. SemIR::SpecificId specific_id,
  44. SemIR::GenericInstIndex::Region region)
  45. -> SemIR::InstBlockId;
  46. } // namespace Carbon::Check
  47. #endif // CARBON_TOOLCHAIN_CHECK_EVAL_H_