LLVM  5.0.0
LoopUtils.h
Go to the documentation of this file.
1 //===- llvm/Transforms/Utils/LoopUtils.h - Loop utilities -------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines some loop transformation utilities.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_TRANSFORMS_UTILS_LOOPUTILS_H
15 #define LLVM_TRANSFORMS_UTILS_LOOPUTILS_H
16 
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/InstrTypes.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/IR/ValueHandle.h"
30 #include "llvm/Support/Casting.h"
31 
32 namespace llvm {
33 
34 class AliasSet;
35 class AliasSetTracker;
36 class BasicBlock;
37 class DataLayout;
38 class Loop;
39 class LoopInfo;
40 class OptimizationRemarkEmitter;
41 class PredicatedScalarEvolution;
42 class PredIteratorCache;
43 class ScalarEvolution;
44 class SCEV;
45 class TargetLibraryInfo;
46 class TargetTransformInfo;
47 
48 /// \brief Captures loop safety information.
49 /// It keep information for loop & its header may throw exception.
51  bool MayThrow = false; // The current loop contains an instruction which
52  // may throw.
53  bool HeaderMayThrow = false; // Same as previous, but specific to loop header
54  // Used to update funclet bundle operands.
56 
57  LoopSafetyInfo() = default;
58 };
59 
60 /// The RecurrenceDescriptor is used to identify recurrences variables in a
61 /// loop. Reduction is a special case of recurrence that has uses of the
62 /// recurrence variable outside the loop. The method isReductionPHI identifies
63 /// reductions that are basic recurrences.
64 ///
65 /// Basic recurrences are defined as the summation, product, OR, AND, XOR, min,
66 /// or max of a set of terms. For example: for(i=0; i<n; i++) { total +=
67 /// array[i]; } is a summation of array elements. Basic recurrences are a
68 /// special case of chains of recurrences (CR). See ScalarEvolution for CR
69 /// references.
70 
71 /// This struct holds information about recurrence variables.
73 public:
74  /// This enum represents the kinds of recurrences that we support.
76  RK_NoRecurrence, ///< Not a recurrence.
77  RK_IntegerAdd, ///< Sum of integers.
78  RK_IntegerMult, ///< Product of integers.
79  RK_IntegerOr, ///< Bitwise or logical OR of numbers.
80  RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
81  RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
82  RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
83  RK_FloatAdd, ///< Sum of floats.
84  RK_FloatMult, ///< Product of floats.
85  RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()).
86  };
87 
88  // This enum represents the kind of minmax recurrence.
97  };
98 
99  RecurrenceDescriptor() = default;
100 
102  MinMaxRecurrenceKind MK, Instruction *UAI, Type *RT,
104  : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK),
105  UnsafeAlgebraInst(UAI), RecurrenceType(RT), IsSigned(Signed) {
106  CastInsts.insert(CI.begin(), CI.end());
107  }
108 
109  /// This POD struct holds information about a potential recurrence operation.
110  class InstDesc {
111  public:
112  InstDesc(bool IsRecur, Instruction *I, Instruction *UAI = nullptr)
113  : IsRecurrence(IsRecur), PatternLastInst(I), MinMaxKind(MRK_Invalid),
114  UnsafeAlgebraInst(UAI) {}
115 
117  : IsRecurrence(true), PatternLastInst(I), MinMaxKind(K),
118  UnsafeAlgebraInst(UAI) {}
119 
120  bool isRecurrence() { return IsRecurrence; }
121 
122  bool hasUnsafeAlgebra() { return UnsafeAlgebraInst != nullptr; }
123 
124  Instruction *getUnsafeAlgebraInst() { return UnsafeAlgebraInst; }
125 
126  MinMaxRecurrenceKind getMinMaxKind() { return MinMaxKind; }
127 
128  Instruction *getPatternInst() { return PatternLastInst; }
129 
130  private:
131  // Is this instruction a recurrence candidate.
132  bool IsRecurrence;
133  // The last instruction in a min/max pattern (select of the select(icmp())
134  // pattern), or the current recurrence instruction otherwise.
135  Instruction *PatternLastInst;
136  // If this is a min/max pattern the comparison predicate.
137  MinMaxRecurrenceKind MinMaxKind;
138  // Recurrence has unsafe algebra.
139  Instruction *UnsafeAlgebraInst;
140  };
141 
142  /// Returns a struct describing if the instruction 'I' can be a recurrence
143  /// variable of type 'Kind'. If the recurrence is a min/max pattern of
144  /// select(icmp()) this function advances the instruction pointer 'I' from the
145  /// compare instruction to the select instruction and stores this pointer in
146  /// 'PatternLastInst' member of the returned struct.
147  static InstDesc isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
148  InstDesc &Prev, bool HasFunNoNaNAttr);
149 
150  /// Returns true if instruction I has multiple uses in Insts
151  static bool hasMultipleUsesOf(Instruction *I,
153 
154  /// Returns true if all uses of the instruction I is within the Set.
156 
157  /// Returns a struct describing if the instruction if the instruction is a
158  /// Select(ICmp(X, Y), X, Y) instruction pattern corresponding to a min(X, Y)
159  /// or max(X, Y).
160  static InstDesc isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev);
161 
162  /// Returns identity corresponding to the RecurrenceKind.
164 
165  /// Returns the opcode of binary operation corresponding to the
166  /// RecurrenceKind.
167  static unsigned getRecurrenceBinOp(RecurrenceKind Kind);
168 
169  /// Returns a Min/Max operation corresponding to MinMaxRecurrenceKind.
171  Value *Left, Value *Right);
172 
173  /// Returns true if Phi is a reduction of type Kind and adds it to the
174  /// RecurrenceDescriptor.
175  static bool AddReductionVar(PHINode *Phi, RecurrenceKind Kind, Loop *TheLoop,
176  bool HasFunNoNaNAttr,
177  RecurrenceDescriptor &RedDes);
178 
179  /// Returns true if Phi is a reduction in TheLoop. The RecurrenceDescriptor is
180  /// returned in RedDes.
181  static bool isReductionPHI(PHINode *Phi, Loop *TheLoop,
182  RecurrenceDescriptor &RedDes);
183 
184  /// Returns true if Phi is a first-order recurrence. A first-order recurrence
185  /// is a non-reduction recurrence relation in which the value of the
186  /// recurrence in the current loop iteration equals a value defined in the
187  /// previous iteration. \p SinkAfter includes pairs of instructions where the
188  /// first will be rescheduled to appear after the second if/when the loop is
189  /// vectorized. It may be augmented with additional pairs if needed in order
190  /// to handle Phi as a first-order recurrence.
191  static bool
192  isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop,
194  DominatorTree *DT);
195 
197 
199 
201 
202  Instruction *getLoopExitInstr() { return LoopExitInstr; }
203 
204  /// Returns true if the recurrence has unsafe algebra which requires a relaxed
205  /// floating-point model.
206  bool hasUnsafeAlgebra() { return UnsafeAlgebraInst != nullptr; }
207 
208  /// Returns first unsafe algebra instruction in the PHI node's use-chain.
209  Instruction *getUnsafeAlgebraInst() { return UnsafeAlgebraInst; }
210 
211  /// Returns true if the recurrence kind is an integer kind.
212  static bool isIntegerRecurrenceKind(RecurrenceKind Kind);
213 
214  /// Returns true if the recurrence kind is a floating point kind.
216 
217  /// Returns true if the recurrence kind is an arithmetic kind.
218  static bool isArithmeticRecurrenceKind(RecurrenceKind Kind);
219 
220  /// Determines if Phi may have been type-promoted. If Phi has a single user
221  /// that ANDs the Phi with a type mask, return the user. RT is updated to
222  /// account for the narrower bit width represented by the mask, and the AND
223  /// instruction is added to CI.
224  static Instruction *lookThroughAnd(PHINode *Phi, Type *&RT,
227 
228  /// Returns true if all the source operands of a recurrence are either
229  /// SExtInsts or ZExtInsts. This function is intended to be used with
230  /// lookThroughAnd to determine if the recurrence has been type-promoted. The
231  /// source operands are added to CI, and IsSigned is updated to indicate if
232  /// all source operands are SExtInsts.
233  static bool getSourceExtensionKind(Instruction *Start, Instruction *Exit,
234  Type *RT, bool &IsSigned,
237 
238  /// Returns the type of the recurrence. This type can be narrower than the
239  /// actual type of the Phi if the recurrence has been type-promoted.
240  Type *getRecurrenceType() { return RecurrenceType; }
241 
242  /// Returns a reference to the instructions used for type-promoting the
243  /// recurrence.
245 
246  /// Returns true if all source operands of the recurrence are SExtInsts.
247  bool isSigned() { return IsSigned; }
248 
249 private:
250  // The starting value of the recurrence.
251  // It does not have to be zero!
252  TrackingVH<Value> StartValue;
253  // The instruction who's value is used outside the loop.
254  Instruction *LoopExitInstr = nullptr;
255  // The kind of the recurrence.
257  // If this a min/max recurrence the kind of recurrence.
258  MinMaxRecurrenceKind MinMaxKind = MRK_Invalid;
259  // First occurrence of unasfe algebra in the PHI's use-chain.
260  Instruction *UnsafeAlgebraInst = nullptr;
261  // The type of the recurrence.
262  Type *RecurrenceType = nullptr;
263  // True if all source operands of the recurrence are SExtInsts.
264  bool IsSigned = false;
265  // Instructions used for type-promoting the recurrence.
267 };
268 
269 /// A struct for saving information about induction variables.
271 public:
272  /// This enum represents the kinds of inductions that we support.
274  IK_NoInduction, ///< Not an induction variable.
275  IK_IntInduction, ///< Integer induction variable. Step = C.
276  IK_PtrInduction, ///< Pointer induction var. Step = C / sizeof(elem).
277  IK_FpInduction ///< Floating point induction variable.
278  };
279 
280 public:
281  /// Default constructor - creates an invalid induction.
282  InductionDescriptor() = default;
283 
284  /// Get the consecutive direction. Returns:
285  /// 0 - unknown or non-consecutive.
286  /// 1 - consecutive and increasing.
287  /// -1 - consecutive and decreasing.
288  int getConsecutiveDirection() const;
289 
290  /// Compute the transformed value of Index at offset StartValue using step
291  /// StepValue.
292  /// For integer induction, returns StartValue + Index * StepValue.
293  /// For pointer induction, returns StartValue[Index * StepValue].
294  /// FIXME: The newly created binary instructions should contain nsw/nuw
295  /// flags, which can be found from the original scalar operations.
297  const DataLayout& DL) const;
298 
299  Value *getStartValue() const { return StartValue; }
300  InductionKind getKind() const { return IK; }
301  const SCEV *getStep() const { return Step; }
303 
304  /// Returns true if \p Phi is an induction in the loop \p L. If \p Phi is an
305  /// induction, the induction descriptor \p D will contain the data describing
306  /// this induction. If by some other means the caller has a better SCEV
307  /// expression for \p Phi than the one returned by the ScalarEvolution
308  /// analysis, it can be passed through \p Expr.
309  static bool isInductionPHI(PHINode *Phi, const Loop* L, ScalarEvolution *SE,
311  const SCEV *Expr = nullptr);
312 
313  /// Returns true if \p Phi is a floating point induction in the loop \p L.
314  /// If \p Phi is an induction, the induction descriptor \p D will contain
315  /// the data describing this induction.
316  static bool isFPInductionPHI(PHINode *Phi, const Loop* L,
318 
319  /// Returns true if \p Phi is a loop \p L induction, in the context associated
320  /// with the run-time predicate of PSE. If \p Assume is true, this can add
321  /// further SCEV predicates to \p PSE in order to prove that \p Phi is an
322  /// induction.
323  /// If \p Phi is an induction, \p D will contain the data describing this
324  /// induction.
325  static bool isInductionPHI(PHINode *Phi, const Loop* L,
327  InductionDescriptor &D, bool Assume = false);
328 
329  /// Returns true if the induction type is FP and the binary operator does
330  /// not have the "fast-math" property. Such operation requires a relaxed FP
331  /// mode.
333  return InductionBinOp &&
334  !cast<FPMathOperator>(InductionBinOp)->hasUnsafeAlgebra();
335  }
336 
337  /// Returns induction operator that does not have "fast-math" property
338  /// and requires FP unsafe mode.
340  if (!InductionBinOp ||
341  cast<FPMathOperator>(InductionBinOp)->hasUnsafeAlgebra())
342  return nullptr;
343  return InductionBinOp;
344  }
345 
346  /// Returns binary opcode of the induction operator.
348  return InductionBinOp ? InductionBinOp->getOpcode() :
349  Instruction::BinaryOpsEnd;
350  }
351 
352 private:
353  /// Private constructor - used by \c isInductionPHI.
354  InductionDescriptor(Value *Start, InductionKind K, const SCEV *Step,
355  BinaryOperator *InductionBinOp = nullptr);
356 
357  /// Start value.
358  TrackingVH<Value> StartValue;
359  /// Induction kind.
361  /// Step value.
362  const SCEV *Step = nullptr;
363  // Instruction that advances induction variable.
364  BinaryOperator *InductionBinOp = nullptr;
365 };
366 
367 BasicBlock *InsertPreheaderForLoop(Loop *L, DominatorTree *DT, LoopInfo *LI,
368  bool PreserveLCSSA);
369 
370 /// Ensure that all exit blocks of the loop are dedicated exits.
371 ///
372 /// For any loop exit block with non-loop predecessors, we split the loop
373 /// predecessors to use a dedicated loop exit block. We update the dominator
374 /// tree and loop info if provided, and will preserve LCSSA if requested.
375 bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
376  bool PreserveLCSSA);
377 
378 /// Ensures LCSSA form for every instruction from the Worklist in the scope of
379 /// innermost containing loop.
380 ///
381 /// For the given instruction which have uses outside of the loop, an LCSSA PHI
382 /// node is inserted and the uses outside the loop are rewritten to use this
383 /// node.
384 ///
385 /// LoopInfo and DominatorTree are required and, since the routine makes no
386 /// changes to CFG, preserved.
387 ///
388 /// Returns true if any modifications are made.
389 bool formLCSSAForInstructions(SmallVectorImpl<Instruction *> &Worklist,
390  DominatorTree &DT, LoopInfo &LI);
391 
392 /// \brief Put loop into LCSSA form.
393 ///
394 /// Looks at all instructions in the loop which have uses outside of the
395 /// current loop. For each, an LCSSA PHI node is inserted and the uses outside
396 /// the loop are rewritten to use this node.
397 ///
398 /// LoopInfo and DominatorTree are required and preserved.
399 ///
400 /// If ScalarEvolution is passed in, it will be preserved.
401 ///
402 /// Returns true if any modifications are made to the loop.
403 bool formLCSSA(Loop &L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE);
404 
405 /// \brief Put a loop nest into LCSSA form.
406 ///
407 /// This recursively forms LCSSA for a loop nest.
408 ///
409 /// LoopInfo and DominatorTree are required and preserved.
410 ///
411 /// If ScalarEvolution is passed in, it will be preserved.
412 ///
413 /// Returns true if any modifications are made to the loop.
414 bool formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI,
415  ScalarEvolution *SE);
416 
417 /// \brief Walk the specified region of the CFG (defined by all blocks
418 /// dominated by the specified block, and that are in the current loop) in
419 /// reverse depth first order w.r.t the DominatorTree. This allows us to visit
420 /// uses before definitions, allowing us to sink a loop body in one pass without
421 /// iteration. Takes DomTreeNode, AliasAnalysis, LoopInfo, DominatorTree,
422 /// DataLayout, TargetLibraryInfo, Loop, AliasSet information for all
423 /// instructions of the loop and loop safety information as
424 /// arguments. Diagnostics is emitted via \p ORE. It returns changed status.
425 bool sinkRegion(DomTreeNode *, AliasAnalysis *, LoopInfo *, DominatorTree *,
426  TargetLibraryInfo *, Loop *, AliasSetTracker *,
427  LoopSafetyInfo *, OptimizationRemarkEmitter *ORE);
428 
429 /// \brief Walk the specified region of the CFG (defined by all blocks
430 /// dominated by the specified block, and that are in the current loop) in depth
431 /// first order w.r.t the DominatorTree. This allows us to visit definitions
432 /// before uses, allowing us to hoist a loop body in one pass without iteration.
433 /// Takes DomTreeNode, AliasAnalysis, LoopInfo, DominatorTree, DataLayout,
434 /// TargetLibraryInfo, Loop, AliasSet information for all instructions of the
435 /// loop and loop safety information as arguments. Diagnostics is emitted via \p
436 /// ORE. It returns changed status.
437 bool hoistRegion(DomTreeNode *, AliasAnalysis *, LoopInfo *, DominatorTree *,
438  TargetLibraryInfo *, Loop *, AliasSetTracker *,
439  LoopSafetyInfo *, OptimizationRemarkEmitter *ORE);
440 
441 /// \brief Try to promote memory values to scalars by sinking stores out of
442 /// the loop and moving loads to before the loop. We do this by looping over
443 /// the stores in the loop, looking for stores to Must pointers which are
444 /// loop invariant. It takes AliasSet, Loop exit blocks vector, loop exit blocks
445 /// insertion point vector, PredIteratorCache, LoopInfo, DominatorTree, Loop,
446 /// AliasSet information for all instructions of the loop and loop safety
447 /// information as arguments. Diagnostics is emitted via \p ORE. It returns
448 /// changed status.
449 bool promoteLoopAccessesToScalars(AliasSet &, SmallVectorImpl<BasicBlock *> &,
450  SmallVectorImpl<Instruction *> &,
451  PredIteratorCache &, LoopInfo *,
452  DominatorTree *, const TargetLibraryInfo *,
453  Loop *, AliasSetTracker *, LoopSafetyInfo *,
454  OptimizationRemarkEmitter *);
455 
456 /// \brief Computes safety information for a loop
457 /// checks loop body & header for the possibility of may throw
458 /// exception, it takes LoopSafetyInfo and loop as argument.
459 /// Updates safety information in LoopSafetyInfo argument.
460 void computeLoopSafetyInfo(LoopSafetyInfo *, Loop *);
461 
462 /// Returns true if the instruction in a loop is guaranteed to execute at least
463 /// once.
464 bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT,
465  const Loop *CurLoop,
466  const LoopSafetyInfo *SafetyInfo);
467 
468 /// \brief Returns the instructions that use values defined in the loop.
469 SmallVector<Instruction *, 8> findDefsUsedOutsideOfLoop(Loop *L);
470 
471 /// \brief Find string metadata for loop
472 ///
473 /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
474 /// operand or null otherwise. If the string metadata is not found return
475 /// Optional's not-a-value.
476 Optional<const MDOperand *> findStringMetadataForLoop(Loop *TheLoop,
477  StringRef Name);
478 
479 /// \brief Set input string into loop metadata by keeping other values intact.
480 void addStringMetadataToLoop(Loop *TheLoop, const char *MDString,
481  unsigned V = 0);
482 
483 /// \brief Get a loop's estimated trip count based on branch weight metadata.
484 /// Returns 0 when the count is estimated to be 0, or None when a meaningful
485 /// estimate can not be made.
486 Optional<unsigned> getLoopEstimatedTripCount(Loop *L);
487 
488 /// Helper to consistently add the set of standard passes to a loop pass's \c
489 /// AnalysisUsage.
490 ///
491 /// All loop passes should call this as part of implementing their \c
492 /// getAnalysisUsage.
493 void getLoopAnalysisUsage(AnalysisUsage &AU);
494 
495 /// Returns true if the hoister and sinker can handle this instruction.
496 /// If SafetyInfo is null, we are checking for sinking instructions from
497 /// preheader to loop body (no speculation).
498 /// If SafetyInfo is not null, we are checking for hoisting/sinking
499 /// instructions from loop body to preheader/exit. Check if the instruction
500 /// can execute speculatively.
501 /// If \p ORE is set use it to emit optimization remarks.
502 bool canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,
503  Loop *CurLoop, AliasSetTracker *CurAST,
504  LoopSafetyInfo *SafetyInfo,
505  OptimizationRemarkEmitter *ORE = nullptr);
506 
507 /// Generates a vector reduction using shufflevectors to reduce the value.
508 Value *getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op,
511  ArrayRef<Value *> RedOps = ArrayRef<Value *>());
512 
513 /// Create a target reduction of the given vector. The reduction operation
514 /// is described by the \p Opcode parameter. min/max reductions require
515 /// additional information supplied in \p Flags.
516 /// The target is queried to determine if intrinsics or shuffle sequences are
517 /// required to implement the reduction.
518 Value *
519 createSimpleTargetReduction(IRBuilder<> &B, const TargetTransformInfo *TTI,
520  unsigned Opcode, Value *Src,
521  TargetTransformInfo::ReductionFlags Flags =
522  TargetTransformInfo::ReductionFlags(),
523  ArrayRef<Value *> RedOps = ArrayRef<Value *>());
524 
525 /// Create a generic target reduction using a recurrence descriptor \p Desc
526 /// The target is queried to determine if intrinsics or shuffle sequences are
527 /// required to implement the reduction.
528 Value *createTargetReduction(IRBuilder<> &B, const TargetTransformInfo *TTI,
529  RecurrenceDescriptor &Desc, Value *Src,
530  bool NoNaN = false);
531 
532 /// Get the intersection (logical and) of all of the potential IR flags
533 /// of each scalar operation (VL) that will be converted into a vector (I).
534 /// If OpValue is non-null, we only consider operations similar to OpValue
535 /// when intersecting.
536 /// Flag set: NSW, NUW, exact, and all of fast-math.
537 void propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue = nullptr);
538 
539 } // end namespace llvm
540 
541 #endif // LLVM_TRANSFORMS_UTILS_LOOPUTILS_H
MachineLoop * L
Bitwise or logical XOR of numbers.
Definition: LoopUtils.h:81
static bool isArithmeticRecurrenceKind(RecurrenceKind Kind)
Returns true if the recurrence kind is an arithmetic kind.
Definition: LoopUtils.cpp:67
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:109
static bool isFPInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D)
Returns true if Phi is a floating point induction in the loop L.
Definition: LoopUtils.cpp:790
InductionDescriptor()=default
Default constructor - creates an invalid induction.
Instruction * getUnsafeAlgebraInst()
Returns first unsafe algebra instruction in the PHI node's use-chain.
Definition: LoopUtils.h:209
Various leaf nodes.
Definition: ISDOpcodes.h:60
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
Min/max implemented in terms of select(cmp()).
Definition: LoopUtils.h:82
InstDesc(bool IsRecur, Instruction *I, Instruction *UAI=nullptr)
Definition: LoopUtils.h:112
The main scalar evolution driver.
MachineInstrBuilder MachineInstrBuilder &DefMI const MCInstrDesc & Desc
DataLayout DL
int getConsecutiveDirection() const
Get the consecutive direction.
Definition: LoopUtils.cpp:709
static bool isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes)
Returns true if Phi is a reduction in TheLoop.
Definition: LoopUtils.cpp:482
BasicBlock * InsertPreheaderForLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, bool PreserveLCSSA)
InsertPreheaderForLoop - Once we discover that a loop doesn't have a preheader, this method is called...
MinMaxRecurrenceKind getMinMaxRecurrenceKind()
Definition: LoopUtils.h:198
static InstDesc isRecurrenceInstr(Instruction *I, RecurrenceKind Kind, InstDesc &Prev, bool HasFunNoNaNAttr)
Returns a struct describing if the instruction 'I' can be a recurrence variable of type 'Kind'...
Definition: LoopUtils.cpp:431
static Instruction * lookThroughAnd(PHINode *Phi, Type *&RT, SmallPtrSetImpl< Instruction * > &Visited, SmallPtrSetImpl< Instruction * > &CI)
Determines if Phi may have been type-promoted.
Definition: LoopUtils.cpp:81
DenseMap< BasicBlock *, ColorVector > BlockColors
Definition: LoopUtils.h:55
static bool isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop, DenseMap< Instruction *, Instruction * > &SinkAfter, DominatorTree *DT)
Returns true if Phi is a first-order recurrence.
Definition: LoopUtils.cpp:531
bool formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition: LCSSA.cpp:332
bool isSigned()
Returns true if all source operands of the recurrence are SExtInsts.
Definition: LoopUtils.h:247
bool hasUnsafeAlgebra()
Returns true if the recurrence has unsafe algebra which requires a relaxed floating-point model...
Definition: LoopUtils.h:206
Value * createSimpleTargetReduction(IRBuilder<> &B, const TargetTransformInfo *TTI, unsigned Opcode, Value *Src, TargetTransformInfo::ReductionFlags Flags=TargetTransformInfo::ReductionFlags(), ArrayRef< Value * > RedOps=ArrayRef< Value * >())
Create a target reduction of the given vector.
Definition: LoopUtils.cpp:1248
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:664
static InstDesc isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev)
Returns a struct describing if the instruction if the instruction is a Select(ICmp(X, Y), X, Y) instruction pattern corresponding to a min(X, Y) or max(X, Y).
Definition: LoopUtils.cpp:382
ConstantInt * getConstIntStepValue() const
Definition: LoopUtils.cpp:716
SmallVector< Instruction *, 8 > findDefsUsedOutsideOfLoop(Loop *L)
Returns the instructions that use values defined in the loop.
Definition: LoopUtils.cpp:1004
void computeLoopSafetyInfo(LoopSafetyInfo *, Loop *)
Computes safety information for a loop checks loop body & header for the possibility of may throw exc...
Definition: LICM.cpp:479
Value * transform(IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL) const
Compute the transformed value of Index at offset StartValue using step StepValue. ...
Definition: LoopUtils.cpp:722
static bool areAllUsesIn(Instruction *I, SmallPtrSetImpl< Instruction * > &Set)
Returns true if all uses of the instruction I is within the Set.
Definition: LoopUtils.cpp:40
void propagateIRFlags(Value *I, ArrayRef< Value * > VL, Value *OpValue=nullptr)
Get the intersection (logical and) of all of the potential IR flags of each scalar operation (VL) tha...
Definition: LoopUtils.cpp:1379
LoopSafetyInfo()=default
Not an induction variable.
Definition: LoopUtils.h:274
This POD struct holds information about a potential recurrence operation.
Definition: LoopUtils.h:110
void addStringMetadataToLoop(Loop *TheLoop, const char *MDString, unsigned V=0)
Set input string into loop metadata by keeping other values intact.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:134
Bitwise or logical AND of numbers.
Definition: LoopUtils.h:80
const char * Name
static bool hasMultipleUsesOf(Instruction *I, SmallPtrSetImpl< Instruction * > &Insts)
Returns true if instruction I has multiple uses in Insts.
Definition: LoopUtils.cpp:469
Pointer induction var. Step = C / sizeof(elem).
Definition: LoopUtils.h:276
static bool AddReductionVar(PHINode *Phi, RecurrenceKind Kind, Loop *TheLoop, bool HasFunNoNaNAttr, RecurrenceDescriptor &RedDes)
Returns true if Phi is a reduction of type Kind and adds it to the RecurrenceDescriptor.
Definition: LoopUtils.cpp:165
Integer induction variable. Step = C.
Definition: LoopUtils.h:275
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
Min/max implemented in terms of select(cmp()).
Definition: LoopUtils.h:85
Value handle that tracks a Value across RAUW.
Definition: ValueHandle.h:337
This is an important base class in LLVM.
Definition: Constant.h:42
Instruction * getUnsafeAlgebraInst()
Returns induction operator that does not have "fast-math" property and requires FP unsafe mode...
Definition: LoopUtils.h:339
InstDesc(Instruction *I, MinMaxRecurrenceKind K, Instruction *UAI=nullptr)
Definition: LoopUtils.h:116
Instruction::BinaryOps getInductionOpcode() const
Returns binary opcode of the induction operator.
Definition: LoopUtils.h:347
iterator begin() const
Definition: SmallPtrSet.h:398
Optional< unsigned > getLoopEstimatedTripCount(Loop *L)
Get a loop's estimated trip count based on branch weight metadata.
Definition: LoopUtils.cpp:1160
bool promoteLoopAccessesToScalars(AliasSet &, SmallVectorImpl< BasicBlock * > &, SmallVectorImpl< Instruction * > &, PredIteratorCache &, LoopInfo *, DominatorTree *, const TargetLibraryInfo *, Loop *, AliasSetTracker *, LoopSafetyInfo *, OptimizationRemarkEmitter *)
Try to promote memory values to scalars by sinking stores out of the loop and moving loads to before ...
Definition: LICM.cpp:1018
RecurrenceKind getRecurrenceKind()
Definition: LoopUtils.h:196
Optional< const MDOperand * > findStringMetadataForLoop(Loop *TheLoop, StringRef Name)
Find string metadata for loop.
Definition: LoopUtils.cpp:1085
static unsigned getRecurrenceBinOp(RecurrenceKind Kind)
Returns the opcode of binary operation corresponding to the RecurrenceKind.
Definition: LoopUtils.cpp:610
Value * getStartValue() const
Definition: LoopUtils.h:299
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Definition: LoopUtils.h:72
bool formLCSSA(Loop &L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE)
Put loop into LCSSA form.
Definition: LCSSA.cpp:277
BinaryOps getOpcode() const
Definition: InstrTypes.h:523
MinMaxRecurrenceKind getMinMaxKind()
Definition: LoopUtils.h:126
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:423
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
A struct for saving information about induction variables.
Definition: LoopUtils.h:270
#define B
Definition: LargeTest.cpp:24
Bitwise or logical OR of numbers.
Definition: LoopUtils.h:79
bool formLCSSAForInstructions(SmallVectorImpl< Instruction * > &Worklist, DominatorTree &DT, LoopInfo &LI)
Ensures LCSSA form for every instruction from the Worklist in the scope of innermost containing loop...
Definition: LCSSA.cpp:72
static bool getSourceExtensionKind(Instruction *Start, Instruction *Exit, Type *RT, bool &IsSigned, SmallPtrSetImpl< Instruction * > &Visited, SmallPtrSetImpl< Instruction * > &CI)
Returns true if all the source operands of a recurrence are either SExtInsts or ZExtInsts.
Definition: LoopUtils.cpp:104
static bool isFloatingPointRecurrenceKind(RecurrenceKind Kind)
Returns true if the recurrence kind is a floating point kind.
Definition: LoopUtils.cpp:63
InductionKind getKind() const
Definition: LoopUtils.h:300
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
RecurrenceDescriptor(Value *Start, Instruction *Exit, RecurrenceKind K, MinMaxRecurrenceKind MK, Instruction *UAI, Type *RT, bool Signed, SmallPtrSetImpl< Instruction * > &CI)
Definition: LoopUtils.h:101
bool hoistRegion(DomTreeNode *, AliasAnalysis *, LoopInfo *, DominatorTree *, TargetLibraryInfo *, Loop *, AliasSetTracker *, LoopSafetyInfo *, OptimizationRemarkEmitter *ORE)
Walk the specified region of the CFG (defined by all blocks dominated by the specified block...
Definition: LICM.cpp:397
Value * createTargetReduction(IRBuilder<> &B, const TargetTransformInfo *TTI, RecurrenceDescriptor &Desc, Value *Src, bool NoNaN=false)
Create a generic target reduction using a recurrence descriptor Desc The target is queried to determi...
Definition: LoopUtils.cpp:1324
static Constant * getRecurrenceIdentity(RecurrenceKind K, Type *Tp)
Returns identity corresponding to the RecurrenceKind.
Definition: LoopUtils.cpp:584
bool sinkRegion(DomTreeNode *, AliasAnalysis *, LoopInfo *, DominatorTree *, TargetLibraryInfo *, Loop *, AliasSetTracker *, LoopSafetyInfo *, OptimizationRemarkEmitter *ORE)
Walk the specified region of the CFG (defined by all blocks dominated by the specified block...
Definition: LICM.cpp:337
static Value * createMinMaxOp(IRBuilder<> &Builder, MinMaxRecurrenceKind RK, Value *Left, Value *Right)
Returns a Min/Max operation corresponding to MinMaxRecurrenceKind.
Definition: LoopUtils.cpp:635
bool hasUnsafeAlgebra()
Returns true if the induction type is FP and the binary operator does not have the "fast-math" proper...
Definition: LoopUtils.h:332
static std::vector< std::string > Flags
Definition: FlagsTest.cpp:8
iterator end() const
Definition: SmallPtrSet.h:405
Basic Alias true
Captures loop safety information.
Definition: LoopUtils.h:50
This class represents an analyzed expression in the program.
static bool isIntegerRecurrenceKind(RecurrenceKind Kind)
Returns true if the recurrence kind is an integer kind.
Definition: LoopUtils.cpp:48
Floating point induction variable.
Definition: LoopUtils.h:277
Instruction * getLoopExitInstr()
Definition: LoopUtils.h:202
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:360
#define I(x, y, z)
Definition: MD5.cpp:58
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
Definition: LoopUtils.cpp:1022
const SCEV * getStep() const
Definition: LoopUtils.h:301
SmallPtrSet< Instruction *, 8 > & getCastInsts()
Returns a reference to the instructions used for type-promoting the recurrence.
Definition: LoopUtils.h:244
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition: Dominators.h:64
LLVM Value Representation.
Definition: Value.h:73
TrackingVH< Value > getRecurrenceStartValue()
Definition: LoopUtils.h:200
bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, bool PreserveLCSSA)
Ensure that all exit blocks of the loop are dedicated exits.
Definition: LoopUtils.cpp:940
Value * getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op, RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind=RecurrenceDescriptor::MRK_Invalid, ArrayRef< Value * > RedOps=ArrayRef< Value * >())
Generates a vector reduction using shufflevectors to reduce the value.
Definition: LoopUtils.cpp:1205
This pass exposes codegen information to IR-level passes.
bool canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT, Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE=nullptr)
Returns true if the hoister and sinker can handle this instruction.
Definition: LICM.cpp:565
InductionKind
This enum represents the kinds of inductions that we support.
Definition: LoopUtils.h:273
bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT, const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo)
Returns true if the instruction in a loop is guaranteed to execute at least once. ...
Definition: LoopUtils.cpp:1120
#define D
Definition: LargeTest.cpp:26
static bool isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, InductionDescriptor &D, const SCEV *Expr=nullptr)
Returns true if Phi is an induction in the loop L.
Definition: LoopUtils.cpp:875
RecurrenceKind
This enum represents the kinds of recurrences that we support.
Definition: LoopUtils.h:75
Type * getRecurrenceType()
Returns the type of the recurrence.
Definition: LoopUtils.h:240