Evaluator.h 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- Evaluator.h - LLVM IR evaluator --------------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // Function evaluator for LLVM IR.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_TRANSFORMS_UTILS_EVALUATOR_H
  18. #define LLVM_TRANSFORMS_UTILS_EVALUATOR_H
  19. #include "llvm/ADT/DenseMap.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/IR/BasicBlock.h"
  23. #include "llvm/IR/GlobalVariable.h"
  24. #include "llvm/IR/Instructions.h"
  25. #include "llvm/IR/Value.h"
  26. #include "llvm/Support/Casting.h"
  27. #include <cassert>
  28. #include <deque>
  29. #include <memory>
  30. namespace llvm {
  31. class DataLayout;
  32. class Function;
  33. class TargetLibraryInfo;
  34. /// This class evaluates LLVM IR, producing the Constant representing each SSA
  35. /// instruction. Changes to global variables are stored in a mapping that can
  36. /// be iterated over after the evaluation is complete. Once an evaluation call
  37. /// fails, the evaluation object should not be reused.
  38. class Evaluator {
  39. struct MutableAggregate;
  40. /// The evaluator represents values either as a Constant*, or as a
  41. /// MutableAggregate, which allows changing individual aggregate elements
  42. /// without creating a new interned Constant.
  43. class MutableValue {
  44. PointerUnion<Constant *, MutableAggregate *> Val;
  45. void clear();
  46. bool makeMutable();
  47. public:
  48. MutableValue(Constant *C) { Val = C; }
  49. MutableValue(const MutableValue &) = delete;
  50. MutableValue(MutableValue &&Other) {
  51. Val = Other.Val;
  52. Other.Val = nullptr;
  53. }
  54. ~MutableValue() { clear(); }
  55. Type *getType() const {
  56. if (auto *C = Val.dyn_cast<Constant *>())
  57. return C->getType();
  58. return Val.get<MutableAggregate *>()->Ty;
  59. }
  60. Constant *toConstant() const {
  61. if (auto *C = Val.dyn_cast<Constant *>())
  62. return C;
  63. return Val.get<MutableAggregate *>()->toConstant();
  64. }
  65. Constant *read(Type *Ty, APInt Offset, const DataLayout &DL) const;
  66. bool write(Constant *V, APInt Offset, const DataLayout &DL);
  67. };
  68. struct MutableAggregate {
  69. Type *Ty;
  70. SmallVector<MutableValue> Elements;
  71. MutableAggregate(Type *Ty) : Ty(Ty) {}
  72. Constant *toConstant() const;
  73. };
  74. public:
  75. Evaluator(const DataLayout &DL, const TargetLibraryInfo *TLI)
  76. : DL(DL), TLI(TLI) {
  77. ValueStack.emplace_back();
  78. }
  79. ~Evaluator() {
  80. for (auto &Tmp : AllocaTmps)
  81. // If there are still users of the alloca, the program is doing something
  82. // silly, e.g. storing the address of the alloca somewhere and using it
  83. // later. Since this is undefined, we'll just make it be null.
  84. if (!Tmp->use_empty())
  85. Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
  86. }
  87. /// Evaluate a call to function F, returning true if successful, false if we
  88. /// can't evaluate it. ActualArgs contains the formal arguments for the
  89. /// function.
  90. bool EvaluateFunction(Function *F, Constant *&RetVal,
  91. const SmallVectorImpl<Constant*> &ActualArgs);
  92. DenseMap<GlobalVariable *, Constant *> getMutatedInitializers() const {
  93. DenseMap<GlobalVariable *, Constant *> Result;
  94. for (auto &Pair : MutatedMemory)
  95. Result[Pair.first] = Pair.second.toConstant();
  96. return Result;
  97. }
  98. const SmallPtrSetImpl<GlobalVariable *> &getInvariants() const {
  99. return Invariants;
  100. }
  101. private:
  102. bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB,
  103. bool &StrippedPointerCastsForAliasAnalysis);
  104. Constant *getVal(Value *V) {
  105. if (Constant *CV = dyn_cast<Constant>(V)) return CV;
  106. Constant *R = ValueStack.back().lookup(V);
  107. assert(R && "Reference to an uncomputed value!");
  108. return R;
  109. }
  110. void setVal(Value *V, Constant *C) {
  111. ValueStack.back()[V] = C;
  112. }
  113. /// Casts call result to a type of bitcast call expression
  114. Constant *castCallResultIfNeeded(Type *ReturnType, Constant *RV);
  115. /// Given call site return callee and list of its formal arguments
  116. Function *getCalleeWithFormalArgs(CallBase &CB,
  117. SmallVectorImpl<Constant *> &Formals);
  118. /// Given call site and callee returns list of callee formal argument
  119. /// values converting them when necessary
  120. bool getFormalParams(CallBase &CB, Function *F,
  121. SmallVectorImpl<Constant *> &Formals);
  122. Constant *ComputeLoadResult(Constant *P, Type *Ty);
  123. /// As we compute SSA register values, we store their contents here. The back
  124. /// of the deque contains the current function and the stack contains the
  125. /// values in the calling frames.
  126. std::deque<DenseMap<Value*, Constant*>> ValueStack;
  127. /// This is used to detect recursion. In pathological situations we could hit
  128. /// exponential behavior, but at least there is nothing unbounded.
  129. SmallVector<Function*, 4> CallStack;
  130. /// For each store we execute, we update this map. Loads check this to get
  131. /// the most up-to-date value. If evaluation is successful, this state is
  132. /// committed to the process.
  133. DenseMap<GlobalVariable *, MutableValue> MutatedMemory;
  134. /// To 'execute' an alloca, we create a temporary global variable to represent
  135. /// its body. This vector is needed so we can delete the temporary globals
  136. /// when we are done.
  137. SmallVector<std::unique_ptr<GlobalVariable>, 32> AllocaTmps;
  138. /// These global variables have been marked invariant by the static
  139. /// constructor.
  140. SmallPtrSet<GlobalVariable*, 8> Invariants;
  141. /// These are constants we have checked and know to be simple enough to live
  142. /// in a static initializer of a global.
  143. SmallPtrSet<Constant*, 8> SimpleConstants;
  144. const DataLayout &DL;
  145. const TargetLibraryInfo *TLI;
  146. };
  147. } // end namespace llvm
  148. #endif // LLVM_TRANSFORMS_UTILS_EVALUATOR_H
  149. #ifdef __GNUC__
  150. #pragma GCC diagnostic pop
  151. #endif