InstructionSimplify.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===-- InstructionSimplify.h - Fold instrs into simpler forms --*- 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. // This file declares routines for folding instructions into simpler forms
  15. // that do not require creating new instructions. This does constant folding
  16. // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
  17. // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
  18. // ("and i32 %x, %x" -> "%x"). If the simplification is also an instruction
  19. // then it dominates the original instruction.
  20. //
  21. // These routines implicitly resolve undef uses. The easiest way to be safe when
  22. // using these routines to obtain simplified values for existing instructions is
  23. // to always replace all uses of the instructions with the resulting simplified
  24. // values. This will prevent other code from seeing the same undef uses and
  25. // resolving them to different values.
  26. //
  27. // These routines are designed to tolerate moderately incomplete IR, such as
  28. // instructions that are not connected to basic blocks yet. However, they do
  29. // require that all the IR that they encounter be valid. In particular, they
  30. // require that all non-constant values be defined in the same function, and the
  31. // same call context of that function (and not split between caller and callee
  32. // contexts of a directly recursive call, for example).
  33. //
  34. // Additionally, these routines can't simplify to the instructions that are not
  35. // def-reachable, meaning we can't just scan the basic block for instructions
  36. // to simplify to.
  37. //
  38. //===----------------------------------------------------------------------===//
  39. #ifndef LLVM_ANALYSIS_INSTRUCTIONSIMPLIFY_H
  40. #define LLVM_ANALYSIS_INSTRUCTIONSIMPLIFY_H
  41. #include "llvm/IR/Instruction.h"
  42. #include "llvm/IR/Operator.h"
  43. #include "llvm/IR/PatternMatch.h"
  44. namespace llvm {
  45. template <typename T, typename... TArgs> class AnalysisManager;
  46. template <class T> class ArrayRef;
  47. class AssumptionCache;
  48. class BinaryOperator;
  49. class CallBase;
  50. class DataLayout;
  51. class DominatorTree;
  52. class Function;
  53. struct LoopStandardAnalysisResults;
  54. class MDNode;
  55. class OptimizationRemarkEmitter;
  56. class Pass;
  57. template <class T, unsigned n> class SmallSetVector;
  58. class TargetLibraryInfo;
  59. class Type;
  60. class Value;
  61. /// InstrInfoQuery provides an interface to query additional information for
  62. /// instructions like metadata or keywords like nsw, which provides conservative
  63. /// results if the users specified it is safe to use.
  64. struct InstrInfoQuery {
  65. InstrInfoQuery(bool UMD) : UseInstrInfo(UMD) {}
  66. InstrInfoQuery() = default;
  67. bool UseInstrInfo = true;
  68. MDNode *getMetadata(const Instruction *I, unsigned KindID) const {
  69. if (UseInstrInfo)
  70. return I->getMetadata(KindID);
  71. return nullptr;
  72. }
  73. template <class InstT> bool hasNoUnsignedWrap(const InstT *Op) const {
  74. if (UseInstrInfo)
  75. return Op->hasNoUnsignedWrap();
  76. return false;
  77. }
  78. template <class InstT> bool hasNoSignedWrap(const InstT *Op) const {
  79. if (UseInstrInfo)
  80. return Op->hasNoSignedWrap();
  81. return false;
  82. }
  83. bool isExact(const BinaryOperator *Op) const {
  84. if (UseInstrInfo && isa<PossiblyExactOperator>(Op))
  85. return cast<PossiblyExactOperator>(Op)->isExact();
  86. return false;
  87. }
  88. };
  89. struct SimplifyQuery {
  90. const DataLayout &DL;
  91. const TargetLibraryInfo *TLI = nullptr;
  92. const DominatorTree *DT = nullptr;
  93. AssumptionCache *AC = nullptr;
  94. const Instruction *CxtI = nullptr;
  95. // Wrapper to query additional information for instructions like metadata or
  96. // keywords like nsw, which provides conservative results if those cannot
  97. // be safely used.
  98. const InstrInfoQuery IIQ;
  99. /// Controls whether simplifications are allowed to constrain the range of
  100. /// possible values for uses of undef. If it is false, simplifications are not
  101. /// allowed to assume a particular value for a use of undef for example.
  102. bool CanUseUndef = true;
  103. SimplifyQuery(const DataLayout &DL, const Instruction *CXTI = nullptr)
  104. : DL(DL), CxtI(CXTI) {}
  105. SimplifyQuery(const DataLayout &DL, const TargetLibraryInfo *TLI,
  106. const DominatorTree *DT = nullptr,
  107. AssumptionCache *AC = nullptr,
  108. const Instruction *CXTI = nullptr, bool UseInstrInfo = true,
  109. bool CanUseUndef = true)
  110. : DL(DL), TLI(TLI), DT(DT), AC(AC), CxtI(CXTI), IIQ(UseInstrInfo),
  111. CanUseUndef(CanUseUndef) {}
  112. SimplifyQuery getWithInstruction(Instruction *I) const {
  113. SimplifyQuery Copy(*this);
  114. Copy.CxtI = I;
  115. return Copy;
  116. }
  117. SimplifyQuery getWithoutUndef() const {
  118. SimplifyQuery Copy(*this);
  119. Copy.CanUseUndef = false;
  120. return Copy;
  121. }
  122. /// If CanUseUndef is true, returns whether \p V is undef.
  123. /// Otherwise always return false.
  124. bool isUndefValue(Value *V) const {
  125. if (!CanUseUndef)
  126. return false;
  127. using namespace PatternMatch;
  128. return match(V, m_Undef());
  129. }
  130. };
  131. // NOTE: the explicit multiple argument versions of these functions are
  132. // deprecated.
  133. // Please use the SimplifyQuery versions in new code.
  134. /// Given operand for an FNeg, fold the result or return null.
  135. Value *SimplifyFNegInst(Value *Op, FastMathFlags FMF, const SimplifyQuery &Q);
  136. /// Given operands for an Add, fold the result or return null.
  137. Value *SimplifyAddInst(Value *LHS, Value *RHS, bool isNSW, bool isNUW,
  138. const SimplifyQuery &Q);
  139. /// Given operands for a Sub, fold the result or return null.
  140. Value *SimplifySubInst(Value *LHS, Value *RHS, bool isNSW, bool isNUW,
  141. const SimplifyQuery &Q);
  142. /// Given operands for an FAdd, fold the result or return null.
  143. Value *
  144. SimplifyFAddInst(Value *LHS, Value *RHS, FastMathFlags FMF,
  145. const SimplifyQuery &Q,
  146. fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
  147. RoundingMode Rounding = RoundingMode::NearestTiesToEven);
  148. /// Given operands for an FSub, fold the result or return null.
  149. Value *
  150. SimplifyFSubInst(Value *LHS, Value *RHS, FastMathFlags FMF,
  151. const SimplifyQuery &Q,
  152. fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
  153. RoundingMode Rounding = RoundingMode::NearestTiesToEven);
  154. /// Given operands for an FMul, fold the result or return null.
  155. Value *
  156. SimplifyFMulInst(Value *LHS, Value *RHS, FastMathFlags FMF,
  157. const SimplifyQuery &Q,
  158. fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
  159. RoundingMode Rounding = RoundingMode::NearestTiesToEven);
  160. /// Given operands for the multiplication of a FMA, fold the result or return
  161. /// null. In contrast to SimplifyFMulInst, this function will not perform
  162. /// simplifications whose unrounded results differ when rounded to the argument
  163. /// type.
  164. Value *SimplifyFMAFMul(Value *LHS, Value *RHS, FastMathFlags FMF,
  165. const SimplifyQuery &Q,
  166. fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
  167. RoundingMode Rounding = RoundingMode::NearestTiesToEven);
  168. /// Given operands for a Mul, fold the result or return null.
  169. Value *SimplifyMulInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
  170. /// Given operands for an SDiv, fold the result or return null.
  171. Value *SimplifySDivInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
  172. /// Given operands for a UDiv, fold the result or return null.
  173. Value *SimplifyUDivInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
  174. /// Given operands for an FDiv, fold the result or return null.
  175. Value *
  176. SimplifyFDivInst(Value *LHS, Value *RHS, FastMathFlags FMF,
  177. const SimplifyQuery &Q,
  178. fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
  179. RoundingMode Rounding = RoundingMode::NearestTiesToEven);
  180. /// Given operands for an SRem, fold the result or return null.
  181. Value *SimplifySRemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
  182. /// Given operands for a URem, fold the result or return null.
  183. Value *SimplifyURemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
  184. /// Given operands for an FRem, fold the result or return null.
  185. Value *
  186. SimplifyFRemInst(Value *LHS, Value *RHS, FastMathFlags FMF,
  187. const SimplifyQuery &Q,
  188. fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
  189. RoundingMode Rounding = RoundingMode::NearestTiesToEven);
  190. /// Given operands for a Shl, fold the result or return null.
  191. Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
  192. const SimplifyQuery &Q);
  193. /// Given operands for a LShr, fold the result or return null.
  194. Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
  195. const SimplifyQuery &Q);
  196. /// Given operands for a AShr, fold the result or return nulll.
  197. Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
  198. const SimplifyQuery &Q);
  199. /// Given operands for an And, fold the result or return null.
  200. Value *SimplifyAndInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
  201. /// Given operands for an Or, fold the result or return null.
  202. Value *SimplifyOrInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
  203. /// Given operands for an Xor, fold the result or return null.
  204. Value *SimplifyXorInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
  205. /// Given operands for an ICmpInst, fold the result or return null.
  206. Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
  207. const SimplifyQuery &Q);
  208. /// Given operands for an FCmpInst, fold the result or return null.
  209. Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
  210. FastMathFlags FMF, const SimplifyQuery &Q);
  211. /// Given operands for a SelectInst, fold the result or return null.
  212. Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
  213. const SimplifyQuery &Q);
  214. /// Given operands for a GetElementPtrInst, fold the result or return null.
  215. Value *SimplifyGEPInst(Type *SrcTy, Value *Ptr, ArrayRef<Value *> Indices,
  216. bool InBounds, const SimplifyQuery &Q);
  217. /// Given operands for an InsertValueInst, fold the result or return null.
  218. Value *SimplifyInsertValueInst(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
  219. const SimplifyQuery &Q);
  220. /// Given operands for an InsertElement, fold the result or return null.
  221. Value *SimplifyInsertElementInst(Value *Vec, Value *Elt, Value *Idx,
  222. const SimplifyQuery &Q);
  223. /// Given operands for an ExtractValueInst, fold the result or return null.
  224. Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
  225. const SimplifyQuery &Q);
  226. /// Given operands for an ExtractElementInst, fold the result or return null.
  227. Value *SimplifyExtractElementInst(Value *Vec, Value *Idx,
  228. const SimplifyQuery &Q);
  229. /// Given operands for a CastInst, fold the result or return null.
  230. Value *SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
  231. const SimplifyQuery &Q);
  232. /// Given operands for a ShuffleVectorInst, fold the result or return null.
  233. /// See class ShuffleVectorInst for a description of the mask representation.
  234. Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, ArrayRef<int> Mask,
  235. Type *RetTy, const SimplifyQuery &Q);
  236. //=== Helper functions for higher up the class hierarchy.
  237. /// Given operands for a CmpInst, fold the result or return null.
  238. Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
  239. const SimplifyQuery &Q);
  240. /// Given operand for a UnaryOperator, fold the result or return null.
  241. Value *SimplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q);
  242. /// Given operand for a UnaryOperator, fold the result or return null.
  243. /// Try to use FastMathFlags when folding the result.
  244. Value *SimplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
  245. const SimplifyQuery &Q);
  246. /// Given operands for a BinaryOperator, fold the result or return null.
  247. Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
  248. const SimplifyQuery &Q);
  249. /// Given operands for a BinaryOperator, fold the result or return null.
  250. /// Try to use FastMathFlags when folding the result.
  251. Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, FastMathFlags FMF,
  252. const SimplifyQuery &Q);
  253. /// Given a callsite, fold the result or return null.
  254. Value *SimplifyCall(CallBase *Call, const SimplifyQuery &Q);
  255. /// Given an operand for a Freeze, see if we can fold the result.
  256. /// If not, this returns null.
  257. Value *SimplifyFreezeInst(Value *Op, const SimplifyQuery &Q);
  258. /// See if we can compute a simplified version of this instruction. If not,
  259. /// return null.
  260. Value *SimplifyInstruction(Instruction *I, const SimplifyQuery &Q,
  261. OptimizationRemarkEmitter *ORE = nullptr);
  262. /// Like \p SimplifyInstruction but the operands of \p I are replaced with
  263. /// \p NewOps. Returns a simplified value, or null if none was found.
  264. Value *
  265. SimplifyInstructionWithOperands(Instruction *I, ArrayRef<Value *> NewOps,
  266. const SimplifyQuery &Q,
  267. OptimizationRemarkEmitter *ORE = nullptr);
  268. /// See if V simplifies when its operand Op is replaced with RepOp. If not,
  269. /// return null.
  270. /// AllowRefinement specifies whether the simplification can be a refinement
  271. /// (e.g. 0 instead of poison), or whether it needs to be strictly identical.
  272. Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
  273. const SimplifyQuery &Q, bool AllowRefinement);
  274. /// Replace all uses of 'I' with 'SimpleV' and simplify the uses recursively.
  275. ///
  276. /// This first performs a normal RAUW of I with SimpleV. It then recursively
  277. /// attempts to simplify those users updated by the operation. The 'I'
  278. /// instruction must not be equal to the simplified value 'SimpleV'.
  279. /// If UnsimplifiedUsers is provided, instructions that could not be simplified
  280. /// are added to it.
  281. ///
  282. /// The function returns true if any simplifications were performed.
  283. bool replaceAndRecursivelySimplify(
  284. Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI = nullptr,
  285. const DominatorTree *DT = nullptr, AssumptionCache *AC = nullptr,
  286. SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr);
  287. // These helper functions return a SimplifyQuery structure that contains as
  288. // many of the optional analysis we use as are currently valid. This is the
  289. // strongly preferred way of constructing SimplifyQuery in passes.
  290. const SimplifyQuery getBestSimplifyQuery(Pass &, Function &);
  291. template <class T, class... TArgs>
  292. const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &,
  293. Function &);
  294. const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &,
  295. const DataLayout &);
  296. } // end namespace llvm
  297. #endif
  298. #ifdef __GNUC__
  299. #pragma GCC diagnostic pop
  300. #endif