InstructionSimplify.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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/PatternMatch.h"
  42. namespace llvm {
  43. template <typename T, typename... TArgs> class AnalysisManager;
  44. template <class T> class ArrayRef;
  45. class AssumptionCache;
  46. class BinaryOperator;
  47. class CallBase;
  48. class DataLayout;
  49. class DominatorTree;
  50. class Function;
  51. class Instruction;
  52. struct LoopStandardAnalysisResults;
  53. class MDNode;
  54. class OptimizationRemarkEmitter;
  55. class Pass;
  56. template <class T, unsigned n> class SmallSetVector;
  57. class TargetLibraryInfo;
  58. class Type;
  59. class Value;
  60. /// InstrInfoQuery provides an interface to query additional information for
  61. /// instructions like metadata or keywords like nsw, which provides conservative
  62. /// results if the users specified it is safe to use.
  63. struct InstrInfoQuery {
  64. InstrInfoQuery(bool UMD) : UseInstrInfo(UMD) {}
  65. InstrInfoQuery() = default;
  66. bool UseInstrInfo = true;
  67. MDNode *getMetadata(const Instruction *I, unsigned KindID) const {
  68. if (UseInstrInfo)
  69. return I->getMetadata(KindID);
  70. return nullptr;
  71. }
  72. template <class InstT> bool hasNoUnsignedWrap(const InstT *Op) const {
  73. if (UseInstrInfo)
  74. return Op->hasNoUnsignedWrap();
  75. return false;
  76. }
  77. template <class InstT> bool hasNoSignedWrap(const InstT *Op) const {
  78. if (UseInstrInfo)
  79. return Op->hasNoSignedWrap();
  80. return false;
  81. }
  82. bool isExact(const BinaryOperator *Op) const {
  83. if (UseInstrInfo && isa<PossiblyExactOperator>(Op))
  84. return cast<PossiblyExactOperator>(Op)->isExact();
  85. return false;
  86. }
  87. };
  88. struct SimplifyQuery {
  89. const DataLayout &DL;
  90. const TargetLibraryInfo *TLI = nullptr;
  91. const DominatorTree *DT = nullptr;
  92. AssumptionCache *AC = nullptr;
  93. const Instruction *CxtI = nullptr;
  94. // Wrapper to query additional information for instructions like metadata or
  95. // keywords like nsw, which provides conservative results if those cannot
  96. // be safely used.
  97. const InstrInfoQuery IIQ;
  98. /// Controls whether simplifications are allowed to constrain the range of
  99. /// possible values for uses of undef. If it is false, simplifications are not
  100. /// allowed to assume a particular value for a use of undef for example.
  101. bool CanUseUndef = true;
  102. SimplifyQuery(const DataLayout &DL, const Instruction *CXTI = nullptr)
  103. : DL(DL), CxtI(CXTI) {}
  104. SimplifyQuery(const DataLayout &DL, const TargetLibraryInfo *TLI,
  105. const DominatorTree *DT = nullptr,
  106. AssumptionCache *AC = nullptr,
  107. const Instruction *CXTI = nullptr, bool UseInstrInfo = true,
  108. bool CanUseUndef = true)
  109. : DL(DL), TLI(TLI), DT(DT), AC(AC), CxtI(CXTI), IIQ(UseInstrInfo),
  110. CanUseUndef(CanUseUndef) {}
  111. SimplifyQuery getWithInstruction(Instruction *I) const {
  112. SimplifyQuery Copy(*this);
  113. Copy.CxtI = I;
  114. return Copy;
  115. }
  116. SimplifyQuery getWithoutUndef() const {
  117. SimplifyQuery Copy(*this);
  118. Copy.CanUseUndef = false;
  119. return Copy;
  120. }
  121. /// If CanUseUndef is true, returns whether \p V is undef.
  122. /// Otherwise always return false.
  123. bool isUndefValue(Value *V) const {
  124. if (!CanUseUndef)
  125. return false;
  126. using namespace PatternMatch;
  127. return match(V, m_Undef());
  128. }
  129. };
  130. // NOTE: the explicit multiple argument versions of these functions are
  131. // deprecated.
  132. // Please use the SimplifyQuery versions in new code.
  133. /// Given operands for an Add, fold the result or return null.
  134. Value *simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW,
  135. const SimplifyQuery &Q);
  136. /// Given operands for a Sub, fold the result or return null.
  137. Value *simplifySubInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW,
  138. const SimplifyQuery &Q);
  139. /// Given operands for a Mul, fold the result or return null.
  140. Value *simplifyMulInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW,
  141. const SimplifyQuery &Q);
  142. /// Given operands for an SDiv, fold the result or return null.
  143. Value *simplifySDivInst(Value *LHS, Value *RHS, bool IsExact,
  144. const SimplifyQuery &Q);
  145. /// Given operands for a UDiv, fold the result or return null.
  146. Value *simplifyUDivInst(Value *LHS, Value *RHS, bool IsExact,
  147. const SimplifyQuery &Q);
  148. /// Given operands for an SRem, fold the result or return null.
  149. Value *simplifySRemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
  150. /// Given operands for a URem, fold the result or return null.
  151. Value *simplifyURemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
  152. /// Given operand for an FNeg, fold the result or return null.
  153. Value *simplifyFNegInst(Value *Op, FastMathFlags FMF, const SimplifyQuery &Q);
  154. /// Given operands for an FAdd, fold the result or return null.
  155. Value *
  156. simplifyFAddInst(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 an FSub, fold the result or return null.
  161. Value *
  162. simplifyFSubInst(Value *LHS, Value *RHS, FastMathFlags FMF,
  163. const SimplifyQuery &Q,
  164. fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
  165. RoundingMode Rounding = RoundingMode::NearestTiesToEven);
  166. /// Given operands for an FMul, fold the result or return null.
  167. Value *
  168. simplifyFMulInst(Value *LHS, Value *RHS, FastMathFlags FMF,
  169. const SimplifyQuery &Q,
  170. fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
  171. RoundingMode Rounding = RoundingMode::NearestTiesToEven);
  172. /// Given operands for the multiplication of a FMA, fold the result or return
  173. /// null. In contrast to simplifyFMulInst, this function will not perform
  174. /// simplifications whose unrounded results differ when rounded to the argument
  175. /// type.
  176. Value *simplifyFMAFMul(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 FDiv, fold the result or return null.
  181. Value *
  182. simplifyFDivInst(Value *LHS, Value *RHS, FastMathFlags FMF,
  183. const SimplifyQuery &Q,
  184. fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
  185. RoundingMode Rounding = RoundingMode::NearestTiesToEven);
  186. /// Given operands for an FRem, fold the result or return null.
  187. Value *
  188. simplifyFRemInst(Value *LHS, Value *RHS, FastMathFlags FMF,
  189. const SimplifyQuery &Q,
  190. fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
  191. RoundingMode Rounding = RoundingMode::NearestTiesToEven);
  192. /// Given operands for a Shl, fold the result or return null.
  193. Value *simplifyShlInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
  194. const SimplifyQuery &Q);
  195. /// Given operands for a LShr, fold the result or return null.
  196. Value *simplifyLShrInst(Value *Op0, Value *Op1, bool IsExact,
  197. const SimplifyQuery &Q);
  198. /// Given operands for a AShr, fold the result or return nulll.
  199. Value *simplifyAShrInst(Value *Op0, Value *Op1, bool IsExact,
  200. const SimplifyQuery &Q);
  201. /// Given operands for an And, fold the result or return null.
  202. Value *simplifyAndInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
  203. /// Given operands for an Or, fold the result or return null.
  204. Value *simplifyOrInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
  205. /// Given operands for an Xor, fold the result or return null.
  206. Value *simplifyXorInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
  207. /// Given operands for an ICmpInst, fold the result or return null.
  208. Value *simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
  209. const SimplifyQuery &Q);
  210. /// Given operands for an FCmpInst, fold the result or return null.
  211. Value *simplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
  212. FastMathFlags FMF, const SimplifyQuery &Q);
  213. /// Given operands for a SelectInst, fold the result or return null.
  214. Value *simplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
  215. const SimplifyQuery &Q);
  216. /// Given operands for a GetElementPtrInst, fold the result or return null.
  217. Value *simplifyGEPInst(Type *SrcTy, Value *Ptr, ArrayRef<Value *> Indices,
  218. bool InBounds, const SimplifyQuery &Q);
  219. /// Given operands for an InsertValueInst, fold the result or return null.
  220. Value *simplifyInsertValueInst(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
  221. const SimplifyQuery &Q);
  222. /// Given operands for an InsertElement, fold the result or return null.
  223. Value *simplifyInsertElementInst(Value *Vec, Value *Elt, Value *Idx,
  224. const SimplifyQuery &Q);
  225. /// Given operands for an ExtractValueInst, fold the result or return null.
  226. Value *simplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
  227. const SimplifyQuery &Q);
  228. /// Given operands for an ExtractElementInst, fold the result or return null.
  229. Value *simplifyExtractElementInst(Value *Vec, Value *Idx,
  230. const SimplifyQuery &Q);
  231. /// Given operands for a CastInst, fold the result or return null.
  232. Value *simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
  233. const SimplifyQuery &Q);
  234. /// Given operands for a ShuffleVectorInst, fold the result or return null.
  235. /// See class ShuffleVectorInst for a description of the mask representation.
  236. Value *simplifyShuffleVectorInst(Value *Op0, Value *Op1, ArrayRef<int> Mask,
  237. Type *RetTy, const SimplifyQuery &Q);
  238. //=== Helper functions for higher up the class hierarchy.
  239. /// Given operands for a CmpInst, fold the result or return null.
  240. Value *simplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
  241. const SimplifyQuery &Q);
  242. /// Given operand for a UnaryOperator, fold the result or return null.
  243. Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q);
  244. /// Given operand for a UnaryOperator, fold the result or return null.
  245. /// Try to use FastMathFlags when folding the result.
  246. Value *simplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
  247. const SimplifyQuery &Q);
  248. /// Given operands for a BinaryOperator, fold the result or return null.
  249. Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
  250. const SimplifyQuery &Q);
  251. /// Given operands for a BinaryOperator, fold the result or return null.
  252. /// Try to use FastMathFlags when folding the result.
  253. Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, FastMathFlags FMF,
  254. const SimplifyQuery &Q);
  255. /// Given a callsite, fold the result or return null.
  256. Value *simplifyCall(CallBase *Call, const SimplifyQuery &Q);
  257. /// Given a constrained FP intrinsic call, tries to compute its simplified
  258. /// version. Returns a simplified result or null.
  259. ///
  260. /// This function provides an additional contract: it guarantees that if
  261. /// simplification succeeds that the intrinsic is side effect free. As a result,
  262. /// successful simplification can be used to delete the intrinsic not just
  263. /// replace its result.
  264. Value *simplifyConstrainedFPCall(CallBase *Call, const SimplifyQuery &Q);
  265. /// Given an operand for a Freeze, see if we can fold the result.
  266. /// If not, this returns null.
  267. Value *simplifyFreezeInst(Value *Op, const SimplifyQuery &Q);
  268. /// See if we can compute a simplified version of this instruction. If not,
  269. /// return null.
  270. Value *simplifyInstruction(Instruction *I, const SimplifyQuery &Q,
  271. OptimizationRemarkEmitter *ORE = nullptr);
  272. /// Like \p simplifyInstruction but the operands of \p I are replaced with
  273. /// \p NewOps. Returns a simplified value, or null if none was found.
  274. Value *
  275. simplifyInstructionWithOperands(Instruction *I, ArrayRef<Value *> NewOps,
  276. const SimplifyQuery &Q,
  277. OptimizationRemarkEmitter *ORE = nullptr);
  278. /// See if V simplifies when its operand Op is replaced with RepOp. If not,
  279. /// return null.
  280. /// AllowRefinement specifies whether the simplification can be a refinement
  281. /// (e.g. 0 instead of poison), or whether it needs to be strictly identical.
  282. Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
  283. const SimplifyQuery &Q, bool AllowRefinement);
  284. /// Replace all uses of 'I' with 'SimpleV' and simplify the uses recursively.
  285. ///
  286. /// This first performs a normal RAUW of I with SimpleV. It then recursively
  287. /// attempts to simplify those users updated by the operation. The 'I'
  288. /// instruction must not be equal to the simplified value 'SimpleV'.
  289. /// If UnsimplifiedUsers is provided, instructions that could not be simplified
  290. /// are added to it.
  291. ///
  292. /// The function returns true if any simplifications were performed.
  293. bool replaceAndRecursivelySimplify(
  294. Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI = nullptr,
  295. const DominatorTree *DT = nullptr, AssumptionCache *AC = nullptr,
  296. SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr);
  297. // These helper functions return a SimplifyQuery structure that contains as
  298. // many of the optional analysis we use as are currently valid. This is the
  299. // strongly preferred way of constructing SimplifyQuery in passes.
  300. const SimplifyQuery getBestSimplifyQuery(Pass &, Function &);
  301. template <class T, class... TArgs>
  302. const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &,
  303. Function &);
  304. const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &,
  305. const DataLayout &);
  306. } // end namespace llvm
  307. #endif
  308. #ifdef __GNUC__
  309. #pragma GCC diagnostic pop
  310. #endif