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/PatternMatch.h"
39 
40 namespace llvm {
41 
42 template <typename T, typename... TArgs> class AnalysisManager;
43 template <class T> class ArrayRef;
44 class AssumptionCache;
45 class BinaryOperator;
46 class CallBase;
47 class DataLayout;
48 class DominatorTree;
49 class Function;
50 class Instruction;
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 {
64   InstrInfoQuery(bool UMD) : UseInstrInfo(UMD) {}
65   InstrInfoQuery() = default;
66   bool UseInstrInfo = true;
67 
68   MDNode *getMetadata(const Instruction *I, unsigned KindID) const {
69     if (UseInstrInfo)
70       return I->getMetadata(KindID);
71     return nullptr;
72   }
73 
74   template <class InstT> bool hasNoUnsignedWrap(const InstT *Op) const {
75     if (UseInstrInfo)
76       return Op->hasNoUnsignedWrap();
77     return false;
78   }
79 
80   template <class InstT> bool hasNoSignedWrap(const InstT *Op) const {
81     if (UseInstrInfo)
82       return Op->hasNoSignedWrap();
83     return false;
84   }
85 
86   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)
111       : 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)
118       : DL(DL), TLI(TLI), DT(DT), AC(AC), CxtI(CXTI), IIQ(UseInstrInfo),
119         CanUseUndef(CanUseUndef) {}
120   SimplifyQuery getWithInstruction(Instruction *I) const {
121     SimplifyQuery Copy(*this);
122     Copy.CxtI = I;
123     return Copy;
124   }
125   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.
133   bool isUndefValue(Value *V) const {
134     if (!CanUseUndef)
135       return false;
136 
137     using namespace PatternMatch;
138     return match(V, m_Undef());
139   }
140 };
141 
142 // NOTE: the explicit multiple argument versions of these functions are
143 // deprecated.
144 // Please use the SimplifyQuery versions in new code.
145 
146 /// Given operand for an FNeg, fold the result or return null.
147 Value *simplifyFNegInst(Value *Op, FastMathFlags FMF, const SimplifyQuery &Q);
148 
149 /// Given operands for an Add, fold the result or return null.
150 Value *simplifyAddInst(Value *LHS, Value *RHS, bool isNSW, bool isNUW,
151                        const SimplifyQuery &Q);
152 
153 /// Given operands for a Sub, fold the result or return null.
154 Value *simplifySubInst(Value *LHS, Value *RHS, bool isNSW, bool isNUW,
155                        const SimplifyQuery &Q);
156 
157 /// Given operands for an FAdd, fold the result or return null.
158 Value *
159 simplifyFAddInst(Value *LHS, Value *RHS, FastMathFlags FMF,
160                  const SimplifyQuery &Q,
161                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
162                  RoundingMode Rounding = RoundingMode::NearestTiesToEven);
163 
164 /// Given operands for an FSub, fold the result or return null.
165 Value *
166 simplifyFSubInst(Value *LHS, Value *RHS, FastMathFlags FMF,
167                  const SimplifyQuery &Q,
168                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
169                  RoundingMode Rounding = RoundingMode::NearestTiesToEven);
170 
171 /// Given operands for an FMul, fold the result or return null.
172 Value *
173 simplifyFMulInst(Value *LHS, Value *RHS, FastMathFlags FMF,
174                  const SimplifyQuery &Q,
175                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
176                  RoundingMode Rounding = RoundingMode::NearestTiesToEven);
177 
178 /// Given operands for the multiplication of a FMA, fold the result or return
179 /// null. In contrast to simplifyFMulInst, this function will not perform
180 /// simplifications whose unrounded results differ when rounded to the argument
181 /// type.
182 Value *simplifyFMAFMul(Value *LHS, Value *RHS, FastMathFlags FMF,
183                        const SimplifyQuery &Q,
184                        fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
185                        RoundingMode Rounding = RoundingMode::NearestTiesToEven);
186 
187 /// Given operands for a Mul, fold the result or return null.
188 Value *simplifyMulInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
189 
190 /// Given operands for an SDiv, fold the result or return null.
191 Value *simplifySDivInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
192 
193 /// Given operands for a UDiv, fold the result or return null.
194 Value *simplifyUDivInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
195 
196 /// Given operands for an FDiv, fold the result or return null.
197 Value *
198 simplifyFDivInst(Value *LHS, Value *RHS, FastMathFlags FMF,
199                  const SimplifyQuery &Q,
200                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
201                  RoundingMode Rounding = RoundingMode::NearestTiesToEven);
202 
203 /// Given operands for an SRem, fold the result or return null.
204 Value *simplifySRemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
205 
206 /// Given operands for a URem, fold the result or return null.
207 Value *simplifyURemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
208 
209 /// Given operands for an FRem, fold the result or return null.
210 Value *
211 simplifyFRemInst(Value *LHS, Value *RHS, FastMathFlags FMF,
212                  const SimplifyQuery &Q,
213                  fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
214                  RoundingMode Rounding = RoundingMode::NearestTiesToEven);
215 
216 /// Given operands for a Shl, fold the result or return null.
217 Value *simplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
218                        const SimplifyQuery &Q);
219 
220 /// Given operands for a LShr, fold the result or return null.
221 Value *simplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
222                         const SimplifyQuery &Q);
223 
224 /// Given operands for a AShr, fold the result or return nulll.
225 Value *simplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
226                         const SimplifyQuery &Q);
227 
228 /// Given operands for an And, fold the result or return null.
229 Value *simplifyAndInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
230 
231 /// Given operands for an Or, fold the result or return null.
232 Value *simplifyOrInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
233 
234 /// Given operands for an Xor, fold the result or return null.
235 Value *simplifyXorInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
236 
237 /// Given operands for an ICmpInst, fold the result or return null.
238 Value *simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
239                         const SimplifyQuery &Q);
240 
241 /// Given operands for an FCmpInst, fold the result or return null.
242 Value *simplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
243                         FastMathFlags FMF, const SimplifyQuery &Q);
244 
245 /// Given operands for a SelectInst, fold the result or return null.
246 Value *simplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
247                           const SimplifyQuery &Q);
248 
249 /// Given operands for a GetElementPtrInst, fold the result or return null.
250 Value *simplifyGEPInst(Type *SrcTy, Value *Ptr, ArrayRef<Value *> Indices,
251                        bool InBounds, const SimplifyQuery &Q);
252 
253 /// Given operands for an InsertValueInst, fold the result or return null.
254 Value *simplifyInsertValueInst(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
255                                const SimplifyQuery &Q);
256 
257 /// Given operands for an InsertElement, fold the result or return null.
258 Value *simplifyInsertElementInst(Value *Vec, Value *Elt, Value *Idx,
259                                  const SimplifyQuery &Q);
260 
261 /// Given operands for an ExtractValueInst, fold the result or return null.
262 Value *simplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
263                                 const SimplifyQuery &Q);
264 
265 /// Given operands for an ExtractElementInst, fold the result or return null.
266 Value *simplifyExtractElementInst(Value *Vec, Value *Idx,
267                                   const SimplifyQuery &Q);
268 
269 /// Given operands for a CastInst, fold the result or return null.
270 Value *simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
271                         const SimplifyQuery &Q);
272 
273 /// Given operands for a ShuffleVectorInst, fold the result or return null.
274 /// See class ShuffleVectorInst for a description of the mask representation.
275 Value *simplifyShuffleVectorInst(Value *Op0, Value *Op1, ArrayRef<int> Mask,
276                                  Type *RetTy, const SimplifyQuery &Q);
277 
278 //=== Helper functions for higher up the class hierarchy.
279 
280 /// Given operands for a CmpInst, fold the result or return null.
281 Value *simplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
282                        const SimplifyQuery &Q);
283 
284 /// Given operand for a UnaryOperator, fold the result or return null.
285 Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q);
286 
287 /// Given operand for a UnaryOperator, fold the result or return null.
288 /// Try to use FastMathFlags when folding the result.
289 Value *simplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
290                     const SimplifyQuery &Q);
291 
292 /// Given operands for a BinaryOperator, fold the result or return null.
293 Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
294                      const SimplifyQuery &Q);
295 
296 /// Given operands for a BinaryOperator, fold the result or return null.
297 /// Try to use FastMathFlags when folding the result.
298 Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, FastMathFlags FMF,
299                      const SimplifyQuery &Q);
300 
301 /// Given a callsite, fold the result or return null.
302 Value *simplifyCall(CallBase *Call, const SimplifyQuery &Q);
303 
304 /// Given a constrained FP intrinsic call, tries to compute its simplified
305 /// version. Returns a simplified result or null.
306 ///
307 /// This function provides an additional contract: it guarantees that if
308 /// simplification succeeds that the intrinsic is side effect free. As a result,
309 /// successful simplification can be used to delete the intrinsic not just
310 /// replace its result.
311 Value *simplifyConstrainedFPCall(CallBase *Call, const SimplifyQuery &Q);
312 
313 /// Given an operand for a Freeze, see if we can fold the result.
314 /// If not, this returns null.
315 Value *simplifyFreezeInst(Value *Op, const SimplifyQuery &Q);
316 
317 /// See if we can compute a simplified version of this instruction. If not,
318 /// return null.
319 Value *simplifyInstruction(Instruction *I, const SimplifyQuery &Q,
320                            OptimizationRemarkEmitter *ORE = nullptr);
321 
322 /// Like \p simplifyInstruction but the operands of \p I are replaced with
323 /// \p NewOps. Returns a simplified value, or null if none was found.
324 Value *
325 simplifyInstructionWithOperands(Instruction *I, ArrayRef<Value *> NewOps,
326                                 const SimplifyQuery &Q,
327                                 OptimizationRemarkEmitter *ORE = nullptr);
328 
329 /// See if V simplifies when its operand Op is replaced with RepOp. If not,
330 /// return null.
331 /// AllowRefinement specifies whether the simplification can be a refinement
332 /// (e.g. 0 instead of poison), or whether it needs to be strictly identical.
333 Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
334                               const SimplifyQuery &Q, bool AllowRefinement);
335 
336 /// Replace all uses of 'I' with 'SimpleV' and simplify the uses recursively.
337 ///
338 /// This first performs a normal RAUW of I with SimpleV. It then recursively
339 /// attempts to simplify those users updated by the operation. The 'I'
340 /// instruction must not be equal to the simplified value 'SimpleV'.
341 /// If UnsimplifiedUsers is provided, instructions that could not be simplified
342 /// are added to it.
343 ///
344 /// The function returns true if any simplifications were performed.
345 bool replaceAndRecursivelySimplify(
346     Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI = nullptr,
347     const DominatorTree *DT = nullptr, AssumptionCache *AC = nullptr,
348     SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr);
349 
350 // These helper functions return a SimplifyQuery structure that contains as
351 // many of the optional analysis we use as are currently valid.  This is the
352 // strongly preferred way of constructing SimplifyQuery in passes.
353 const SimplifyQuery getBestSimplifyQuery(Pass &, Function &);
354 template <class T, class... TArgs>
355 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &,
356                                          Function &);
357 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &,
358                                          const DataLayout &);
359 } // end namespace llvm
360 
361 #endif
362