• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- InstructionSimplify.h - Fold instrs into simpler forms --*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
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.
15 //
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.
21 //
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).
28 //
29 // Additionally, these routines can't simplify to the instructions that are not
30 // def-reachable, meaning we can't just scan the basic block for instructions
31 // to simplify to.
32 //
33 //===----------------------------------------------------------------------===//
34 
35 #ifndef LLVM_ANALYSIS_INSTRUCTIONSIMPLIFY_H
36 #define LLVM_ANALYSIS_INSTRUCTIONSIMPLIFY_H
37 
38 #include "llvm/IR/Instruction.h"
39 #include "llvm/IR/Operator.h"
40 
41 namespace llvm {
42 
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 struct LoopStandardAnalysisResults;
52 class MDNode;
53 class OptimizationRemarkEmitter;
54 class Pass;
55 template <class T, unsigned n> class SmallSetVector;
56 class TargetLibraryInfo;
57 class Type;
58 class Value;
59 
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 {
InstrInfoQueryInstrInfoQuery64   InstrInfoQuery(bool UMD) : UseInstrInfo(UMD) {}
InstrInfoQueryInstrInfoQuery65   InstrInfoQuery() : UseInstrInfo(true) {}
66   bool UseInstrInfo = true;
67 
getMetadataInstrInfoQuery68   MDNode *getMetadata(const Instruction *I, unsigned KindID) const {
69     if (UseInstrInfo)
70       return I->getMetadata(KindID);
71     return nullptr;
72   }
73 
hasNoUnsignedWrapInstrInfoQuery74   template <class InstT> bool hasNoUnsignedWrap(const InstT *Op) const {
75     if (UseInstrInfo)
76       return Op->hasNoUnsignedWrap();
77     return false;
78   }
79 
hasNoSignedWrapInstrInfoQuery80   template <class InstT> bool hasNoSignedWrap(const InstT *Op) const {
81     if (UseInstrInfo)
82       return Op->hasNoSignedWrap();
83     return false;
84   }
85 
isExactInstrInfoQuery86   bool isExact(const BinaryOperator *Op) const {
87     if (UseInstrInfo && isa<PossiblyExactOperator>(Op))
88       return cast<PossiblyExactOperator>(Op)->isExact();
89     return false;
90   }
91 };
92 
93 struct SimplifyQuery {
94   const DataLayout &DL;
95   const TargetLibraryInfo *TLI = nullptr;
96   const DominatorTree *DT = nullptr;
97   AssumptionCache *AC = nullptr;
98   const Instruction *CxtI = nullptr;
99 
100   // Wrapper to query additional information for instructions like metadata or
101   // keywords like nsw, which provides conservative results if those cannot
102   // be safely used.
103   const InstrInfoQuery IIQ;
104 
105   /// Controls whether simplifications are allowed to constrain the range of
106   /// possible values for uses of undef. If it is false, simplifications are not
107   /// allowed to assume a particular value for a use of undef for example.
108   bool CanUseUndef = true;
109 
110   SimplifyQuery(const DataLayout &DL, const Instruction *CXTI = nullptr)
DLSimplifyQuery111       : DL(DL), CxtI(CXTI) {}
112 
113   SimplifyQuery(const DataLayout &DL, const TargetLibraryInfo *TLI,
114                 const DominatorTree *DT = nullptr,
115                 AssumptionCache *AC = nullptr,
116                 const Instruction *CXTI = nullptr, bool UseInstrInfo = true,
117                 bool CanUseUndef = true)
DLSimplifyQuery118       : DL(DL), TLI(TLI), DT(DT), AC(AC), CxtI(CXTI), IIQ(UseInstrInfo),
119         CanUseUndef(CanUseUndef) {}
getWithInstructionSimplifyQuery120   SimplifyQuery getWithInstruction(Instruction *I) const {
121     SimplifyQuery Copy(*this);
122     Copy.CxtI = I;
123     return Copy;
124   }
getWithoutUndefSimplifyQuery125   SimplifyQuery getWithoutUndef() const {
126     SimplifyQuery Copy(*this);
127     Copy.CanUseUndef = false;
128     return Copy;
129   }
130 
131   /// If CanUseUndef is true, returns whether \p V is undef.
132   /// Otherwise always return false.
isUndefValueSimplifyQuery133   bool isUndefValue(Value *V) const {
134     if (!CanUseUndef)
135       return false;
136     return isa<UndefValue>(V);
137   }
138 };
139 
140 // NOTE: the explicit multiple argument versions of these functions are
141 // deprecated.
142 // Please use the SimplifyQuery versions in new code.
143 
144 /// Given operand for an FNeg, fold the result or return null.
145 Value *SimplifyFNegInst(Value *Op, FastMathFlags FMF,
146                         const SimplifyQuery &Q);
147 
148 /// Given operands for an Add, fold the result or return null.
149 Value *SimplifyAddInst(Value *LHS, Value *RHS, bool isNSW, bool isNUW,
150                        const SimplifyQuery &Q);
151 
152 /// Given operands for a Sub, fold the result or return null.
153 Value *SimplifySubInst(Value *LHS, Value *RHS, bool isNSW, bool isNUW,
154                        const SimplifyQuery &Q);
155 
156 /// Given operands for an FAdd, fold the result or return null.
157 Value *SimplifyFAddInst(Value *LHS, Value *RHS, FastMathFlags FMF,
158                         const SimplifyQuery &Q);
159 
160 /// Given operands for an FSub, fold the result or return null.
161 Value *SimplifyFSubInst(Value *LHS, Value *RHS, FastMathFlags FMF,
162                         const SimplifyQuery &Q);
163 
164 /// Given operands for an FMul, fold the result or return null.
165 Value *SimplifyFMulInst(Value *LHS, Value *RHS, FastMathFlags FMF,
166                         const SimplifyQuery &Q);
167 
168 /// Given operands for the multiplication of a FMA, fold the result or return
169 /// null. In contrast to SimplifyFMulInst, this function will not perform
170 /// simplifications whose unrounded results differ when rounded to the argument
171 /// type.
172 Value *SimplifyFMAFMul(Value *LHS, Value *RHS, FastMathFlags FMF,
173                        const SimplifyQuery &Q);
174 
175 /// Given operands for a Mul, fold the result or return null.
176 Value *SimplifyMulInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
177 
178 /// Given operands for an SDiv, fold the result or return null.
179 Value *SimplifySDivInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
180 
181 /// Given operands for a UDiv, fold the result or return null.
182 Value *SimplifyUDivInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
183 
184 /// Given operands for an FDiv, fold the result or return null.
185 Value *SimplifyFDivInst(Value *LHS, Value *RHS, FastMathFlags FMF,
186                         const SimplifyQuery &Q);
187 
188 /// Given operands for an SRem, fold the result or return null.
189 Value *SimplifySRemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
190 
191 /// Given operands for a URem, fold the result or return null.
192 Value *SimplifyURemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
193 
194 /// Given operands for an FRem, fold the result or return null.
195 Value *SimplifyFRemInst(Value *LHS, Value *RHS, FastMathFlags FMF,
196                         const SimplifyQuery &Q);
197 
198 /// Given operands for a Shl, fold the result or return null.
199 Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
200                        const SimplifyQuery &Q);
201 
202 /// Given operands for a LShr, fold the result or return null.
203 Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
204                         const SimplifyQuery &Q);
205 
206 /// Given operands for a AShr, fold the result or return nulll.
207 Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
208                         const SimplifyQuery &Q);
209 
210 /// Given operands for an And, fold the result or return null.
211 Value *SimplifyAndInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
212 
213 /// Given operands for an Or, fold the result or return null.
214 Value *SimplifyOrInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
215 
216 /// Given operands for an Xor, fold the result or return null.
217 Value *SimplifyXorInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
218 
219 /// Given operands for an ICmpInst, fold the result or return null.
220 Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
221                         const SimplifyQuery &Q);
222 
223 /// Given operands for an FCmpInst, fold the result or return null.
224 Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
225                         FastMathFlags FMF, const SimplifyQuery &Q);
226 
227 /// Given operands for a SelectInst, fold the result or return null.
228 Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
229                           const SimplifyQuery &Q);
230 
231 /// Given operands for a GetElementPtrInst, fold the result or return null.
232 Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
233                        const SimplifyQuery &Q);
234 
235 /// Given operands for an InsertValueInst, fold the result or return null.
236 Value *SimplifyInsertValueInst(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
237                                const SimplifyQuery &Q);
238 
239 /// Given operands for an InsertElement, fold the result or return null.
240 Value *SimplifyInsertElementInst(Value *Vec, Value *Elt, Value *Idx,
241                                  const SimplifyQuery &Q);
242 
243 /// Given operands for an ExtractValueInst, fold the result or return null.
244 Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
245                                 const SimplifyQuery &Q);
246 
247 /// Given operands for an ExtractElementInst, fold the result or return null.
248 Value *SimplifyExtractElementInst(Value *Vec, Value *Idx,
249                                   const SimplifyQuery &Q);
250 
251 /// Given operands for a CastInst, fold the result or return null.
252 Value *SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
253                         const SimplifyQuery &Q);
254 
255 /// Given operands for a ShuffleVectorInst, fold the result or return null.
256 /// See class ShuffleVectorInst for a description of the mask representation.
257 Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, ArrayRef<int> Mask,
258                                  Type *RetTy, const SimplifyQuery &Q);
259 
260 //=== Helper functions for higher up the class hierarchy.
261 
262 /// Given operands for a CmpInst, fold the result or return null.
263 Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
264                        const SimplifyQuery &Q);
265 
266 /// Given operand for a UnaryOperator, fold the result or return null.
267 Value *SimplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q);
268 
269 /// Given operand for a UnaryOperator, fold the result or return null.
270 /// Try to use FastMathFlags when folding the result.
271 Value *SimplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
272                     const SimplifyQuery &Q);
273 
274 /// Given operands for a BinaryOperator, fold the result or return null.
275 Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
276                      const SimplifyQuery &Q);
277 
278 /// Given operands for a BinaryOperator, fold the result or return null.
279 /// Try to use FastMathFlags when folding the result.
280 Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
281                      FastMathFlags FMF, const SimplifyQuery &Q);
282 
283 /// Given a callsite, fold the result or return null.
284 Value *SimplifyCall(CallBase *Call, const SimplifyQuery &Q);
285 
286 /// Given an operand for a Freeze, see if we can fold the result.
287 /// If not, this returns null.
288 Value *SimplifyFreezeInst(Value *Op, const SimplifyQuery &Q);
289 
290 /// See if we can compute a simplified version of this instruction. If not,
291 /// return null.
292 Value *SimplifyInstruction(Instruction *I, const SimplifyQuery &Q,
293                            OptimizationRemarkEmitter *ORE = nullptr);
294 
295 /// See if V simplifies when its operand Op is replaced with RepOp. If not,
296 /// return null.
297 /// AllowRefinement specifies whether the simplification can be a refinement,
298 /// or whether it needs to be strictly identical.
299 Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
300                               const SimplifyQuery &Q, bool AllowRefinement);
301 
302 /// Replace all uses of 'I' with 'SimpleV' and simplify the uses recursively.
303 ///
304 /// This first performs a normal RAUW of I with SimpleV. It then recursively
305 /// attempts to simplify those users updated by the operation. The 'I'
306 /// instruction must not be equal to the simplified value 'SimpleV'.
307 /// If UnsimplifiedUsers is provided, instructions that could not be simplified
308 /// are added to it.
309 ///
310 /// The function returns true if any simplifications were performed.
311 bool replaceAndRecursivelySimplify(
312     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI = nullptr,
313     const DominatorTree *DT = nullptr, AssumptionCache *AC = nullptr,
314     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr);
315 
316 /// Recursively attempt to simplify an instruction.
317 ///
318 /// This routine uses SimplifyInstruction to simplify 'I', and if successful
319 /// replaces uses of 'I' with the simplified value. It then recurses on each
320 /// of the users impacted. It returns true if any simplifications were
321 /// performed.
322 bool recursivelySimplifyInstruction(Instruction *I,
323                                     const TargetLibraryInfo *TLI = nullptr,
324                                     const DominatorTree *DT = nullptr,
325                                     AssumptionCache *AC = nullptr);
326 
327 // These helper functions return a SimplifyQuery structure that contains as
328 // many of the optional analysis we use as are currently valid.  This is the
329 // strongly preferred way of constructing SimplifyQuery in passes.
330 const SimplifyQuery getBestSimplifyQuery(Pass &, Function &);
331 template <class T, class... TArgs>
332 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &,
333                                          Function &);
334 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &,
335                                          const DataLayout &);
336 } // end namespace llvm
337 
338 #endif
339 
340