1 //===-- InstructionSimplify.h - Fold instrs into simpler forms --*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file declares routines for folding instructions into simpler forms
10 // that do not require creating new instructions. This does constant folding
11 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
12 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
13 // ("and i32 %x, %x" -> "%x"). If the simplification is also an instruction
14 // then it dominates the original instruction.
16 // These routines implicitly resolve undef uses. The easiest way to be safe when
17 // using these routines to obtain simplified values for existing instructions is
18 // to always replace all uses of the instructions with the resulting simplified
19 // values. This will prevent other code from seeing the same undef uses and
20 // resolving them to different values.
22 // These routines are designed to tolerate moderately incomplete IR, such as
23 // instructions that are not connected to basic blocks yet. However, they do
24 // require that all the IR that they encounter be valid. In particular, they
25 // require that all non-constant values be defined in the same function, and the
26 // same call context of that function (and not split between caller and callee
27 // contexts of a directly recursive call, for example).
29 //===----------------------------------------------------------------------===//
31 #ifndef LLVM_ANALYSIS_INSTRUCTIONSIMPLIFY_H
32 #define LLVM_ANALYSIS_INSTRUCTIONSIMPLIFY_H
34 #include "llvm/IR/Instruction.h"
35 #include "llvm/IR/Operator.h"
39 template <typename T, typename... TArgs> class AnalysisManager;
40 template <class T> class ArrayRef;
41 class AssumptionCache;
47 struct LoopStandardAnalysisResults;
49 class OptimizationRemarkEmitter;
51 template <class T, unsigned n> class SmallSetVector;
52 class TargetLibraryInfo;
56 /// InstrInfoQuery provides an interface to query additional information for
57 /// instructions like metadata or keywords like nsw, which provides conservative
58 /// results if the users specified it is safe to use.
59 struct InstrInfoQuery {
60 InstrInfoQuery(bool UMD) : UseInstrInfo(UMD) {}
61 InstrInfoQuery() : UseInstrInfo(true) {}
62 bool UseInstrInfo = true;
64 MDNode *getMetadata(const Instruction *I, unsigned KindID) const {
66 return I->getMetadata(KindID);
70 template <class InstT> bool hasNoUnsignedWrap(const InstT *Op) const {
72 return Op->hasNoUnsignedWrap();
76 template <class InstT> bool hasNoSignedWrap(const InstT *Op) const {
78 return Op->hasNoSignedWrap();
82 bool isExact(const BinaryOperator *Op) const {
83 if (UseInstrInfo && isa<PossiblyExactOperator>(Op))
84 return cast<PossiblyExactOperator>(Op)->isExact();
89 struct SimplifyQuery {
91 const TargetLibraryInfo *TLI = nullptr;
92 const DominatorTree *DT = nullptr;
93 AssumptionCache *AC = nullptr;
94 const Instruction *CxtI = nullptr;
96 // Wrapper to query additional information for instructions like metadata or
97 // keywords like nsw, which provides conservative results if those cannot
99 const InstrInfoQuery IIQ;
101 SimplifyQuery(const DataLayout &DL, const Instruction *CXTI = nullptr)
102 : 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 : DL(DL), TLI(TLI), DT(DT), AC(AC), CxtI(CXTI), IIQ(UseInstrInfo) {}
109 SimplifyQuery getWithInstruction(Instruction *I) const {
110 SimplifyQuery Copy(*this);
116 // NOTE: the explicit multiple argument versions of these functions are
118 // Please use the SimplifyQuery versions in new code.
120 /// Given operand for an FNeg, fold the result or return null.
121 Value *SimplifyFNegInst(Value *Op, FastMathFlags FMF,
122 const SimplifyQuery &Q);
124 /// Given operands for an Add, fold the result or return null.
125 Value *SimplifyAddInst(Value *LHS, Value *RHS, bool isNSW, bool isNUW,
126 const SimplifyQuery &Q);
128 /// Given operands for a Sub, fold the result or return null.
129 Value *SimplifySubInst(Value *LHS, Value *RHS, bool isNSW, bool isNUW,
130 const SimplifyQuery &Q);
132 /// Given operands for an FAdd, fold the result or return null.
133 Value *SimplifyFAddInst(Value *LHS, Value *RHS, FastMathFlags FMF,
134 const SimplifyQuery &Q);
136 /// Given operands for an FSub, fold the result or return null.
137 Value *SimplifyFSubInst(Value *LHS, Value *RHS, FastMathFlags FMF,
138 const SimplifyQuery &Q);
140 /// Given operands for an FMul, fold the result or return null.
141 Value *SimplifyFMulInst(Value *LHS, Value *RHS, FastMathFlags FMF,
142 const SimplifyQuery &Q);
144 /// Given operands for the multiplication of a FMA, fold the result or return
145 /// null. In contrast to SimplifyFMulInst, this function will not perform
146 /// simplifications whose unrounded results differ when rounded to the argument
148 Value *SimplifyFMAFMul(Value *LHS, Value *RHS, FastMathFlags FMF,
149 const SimplifyQuery &Q);
151 /// Given operands for a Mul, fold the result or return null.
152 Value *SimplifyMulInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
154 /// Given operands for an SDiv, fold the result or return null.
155 Value *SimplifySDivInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
157 /// Given operands for a UDiv, fold the result or return null.
158 Value *SimplifyUDivInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
160 /// Given operands for an FDiv, fold the result or return null.
161 Value *SimplifyFDivInst(Value *LHS, Value *RHS, FastMathFlags FMF,
162 const SimplifyQuery &Q);
164 /// Given operands for an SRem, fold the result or return null.
165 Value *SimplifySRemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
167 /// Given operands for a URem, fold the result or return null.
168 Value *SimplifyURemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
170 /// Given operands for an FRem, fold the result or return null.
171 Value *SimplifyFRemInst(Value *LHS, Value *RHS, FastMathFlags FMF,
172 const SimplifyQuery &Q);
174 /// Given operands for a Shl, fold the result or return null.
175 Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
176 const SimplifyQuery &Q);
178 /// Given operands for a LShr, fold the result or return null.
179 Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
180 const SimplifyQuery &Q);
182 /// Given operands for a AShr, fold the result or return nulll.
183 Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
184 const SimplifyQuery &Q);
186 /// Given operands for an And, fold the result or return null.
187 Value *SimplifyAndInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
189 /// Given operands for an Or, fold the result or return null.
190 Value *SimplifyOrInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
192 /// Given operands for an Xor, fold the result or return null.
193 Value *SimplifyXorInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
195 /// Given operands for an ICmpInst, fold the result or return null.
196 Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
197 const SimplifyQuery &Q);
199 /// Given operands for an FCmpInst, fold the result or return null.
200 Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
201 FastMathFlags FMF, const SimplifyQuery &Q);
203 /// Given operands for a SelectInst, fold the result or return null.
204 Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
205 const SimplifyQuery &Q);
207 /// Given operands for a GetElementPtrInst, fold the result or return null.
208 Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
209 const SimplifyQuery &Q);
211 /// Given operands for an InsertValueInst, fold the result or return null.
212 Value *SimplifyInsertValueInst(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
213 const SimplifyQuery &Q);
215 /// Given operands for an InsertElement, fold the result or return null.
216 Value *SimplifyInsertElementInst(Value *Vec, Value *Elt, Value *Idx,
217 const SimplifyQuery &Q);
219 /// Given operands for an ExtractValueInst, fold the result or return null.
220 Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
221 const SimplifyQuery &Q);
223 /// Given operands for an ExtractElementInst, fold the result or return null.
224 Value *SimplifyExtractElementInst(Value *Vec, Value *Idx,
225 const SimplifyQuery &Q);
227 /// Given operands for a CastInst, fold the result or return null.
228 Value *SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
229 const SimplifyQuery &Q);
231 /// Given operands for a ShuffleVectorInst, fold the result or return null.
232 /// See class ShuffleVectorInst for a description of the mask representation.
233 Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, ArrayRef<int> Mask,
234 Type *RetTy, const SimplifyQuery &Q);
236 //=== Helper functions for higher up the class hierarchy.
238 /// Given operands for a CmpInst, fold the result or return null.
239 Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
240 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);
245 /// Given operand for a UnaryOperator, fold the result or return null.
246 /// Try to use FastMathFlags when folding the result.
247 Value *SimplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
248 const SimplifyQuery &Q);
250 /// Given operands for a BinaryOperator, fold the result or return null.
251 Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
252 const SimplifyQuery &Q);
254 /// Given operands for a BinaryOperator, fold the result or return null.
255 /// Try to use FastMathFlags when folding the result.
256 Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
257 FastMathFlags FMF, const SimplifyQuery &Q);
259 /// Given a callsite, fold the result or return null.
260 Value *SimplifyCall(CallBase *Call, const SimplifyQuery &Q);
262 /// Given an operand for a Freeze, see if we can fold the result.
263 /// If not, this returns null.
264 Value *SimplifyFreezeInst(Value *Op, const SimplifyQuery &Q);
266 /// See if we can compute a simplified version of this instruction. If not,
268 Value *SimplifyInstruction(Instruction *I, const SimplifyQuery &Q,
269 OptimizationRemarkEmitter *ORE = nullptr);
271 /// See if V simplifies when its operand Op is replaced with RepOp.
272 /// AllowRefinement specifies whether the simplification can be a refinement,
273 /// or whether it needs to be strictly identical.
274 Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
275 const SimplifyQuery &Q, bool AllowRefinement);
277 /// Replace all uses of 'I' with 'SimpleV' and simplify the uses recursively.
279 /// This first performs a normal RAUW of I with SimpleV. It then recursively
280 /// attempts to simplify those users updated by the operation. The 'I'
281 /// instruction must not be equal to the simplified value 'SimpleV'.
282 /// If UnsimplifiedUsers is provided, instructions that could not be simplified
285 /// The function returns true if any simplifications were performed.
286 bool replaceAndRecursivelySimplify(
287 Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI = nullptr,
288 const DominatorTree *DT = nullptr, AssumptionCache *AC = nullptr,
289 SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr);
291 /// Recursively attempt to simplify an instruction.
293 /// This routine uses SimplifyInstruction to simplify 'I', and if successful
294 /// replaces uses of 'I' with the simplified value. It then recurses on each
295 /// of the users impacted. It returns true if any simplifications were
297 bool recursivelySimplifyInstruction(Instruction *I,
298 const TargetLibraryInfo *TLI = nullptr,
299 const DominatorTree *DT = nullptr,
300 AssumptionCache *AC = nullptr);
302 // These helper functions return a SimplifyQuery structure that contains as
303 // many of the optional analysis we use as are currently valid. This is the
304 // strongly preferred way of constructing SimplifyQuery in passes.
305 const SimplifyQuery getBestSimplifyQuery(Pass &, Function &);
306 template <class T, class... TArgs>
307 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &,
309 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &,
311 } // end namespace llvm