xref: /freebsd-src/contrib/llvm-project/llvm/lib/Analysis/IVDescriptors.cpp (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
1 //===- llvm/Analysis/IVDescriptors.cpp - IndVar Descriptors -----*- 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 "describes" induction and recurrence variables.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Analysis/IVDescriptors.h"
14 #include "llvm/ADT/ScopeExit.h"
15 #include "llvm/Analysis/BasicAliasAnalysis.h"
16 #include "llvm/Analysis/DemandedBits.h"
17 #include "llvm/Analysis/DomTreeUpdater.h"
18 #include "llvm/Analysis/GlobalsModRef.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/Analysis/MustExecute.h"
23 #include "llvm/Analysis/ScalarEvolution.h"
24 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
25 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
26 #include "llvm/Analysis/TargetTransformInfo.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/PatternMatch.h"
32 #include "llvm/IR/ValueHandle.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/KnownBits.h"
36 
37 using namespace llvm;
38 using namespace llvm::PatternMatch;
39 
40 #define DEBUG_TYPE "iv-descriptors"
41 
42 bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
43                                         SmallPtrSetImpl<Instruction *> &Set) {
44   for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
45     if (!Set.count(dyn_cast<Instruction>(*Use)))
46       return false;
47   return true;
48 }
49 
50 bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurKind Kind) {
51   switch (Kind) {
52   default:
53     break;
54   case RecurKind::Add:
55   case RecurKind::Mul:
56   case RecurKind::Or:
57   case RecurKind::And:
58   case RecurKind::Xor:
59   case RecurKind::SMax:
60   case RecurKind::SMin:
61   case RecurKind::UMax:
62   case RecurKind::UMin:
63     return true;
64   }
65   return false;
66 }
67 
68 bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurKind Kind) {
69   return (Kind != RecurKind::None) && !isIntegerRecurrenceKind(Kind);
70 }
71 
72 bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurKind Kind) {
73   switch (Kind) {
74   default:
75     break;
76   case RecurKind::Add:
77   case RecurKind::Mul:
78   case RecurKind::FAdd:
79   case RecurKind::FMul:
80     return true;
81   }
82   return false;
83 }
84 
85 /// Determines if Phi may have been type-promoted. If Phi has a single user
86 /// that ANDs the Phi with a type mask, return the user. RT is updated to
87 /// account for the narrower bit width represented by the mask, and the AND
88 /// instruction is added to CI.
89 static Instruction *lookThroughAnd(PHINode *Phi, Type *&RT,
90                                    SmallPtrSetImpl<Instruction *> &Visited,
91                                    SmallPtrSetImpl<Instruction *> &CI) {
92   if (!Phi->hasOneUse())
93     return Phi;
94 
95   const APInt *M = nullptr;
96   Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
97 
98   // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
99   // with a new integer type of the corresponding bit width.
100   if (match(J, m_c_And(m_Instruction(I), m_APInt(M)))) {
101     int32_t Bits = (*M + 1).exactLogBase2();
102     if (Bits > 0) {
103       RT = IntegerType::get(Phi->getContext(), Bits);
104       Visited.insert(Phi);
105       CI.insert(J);
106       return J;
107     }
108   }
109   return Phi;
110 }
111 
112 /// Compute the minimal bit width needed to represent a reduction whose exit
113 /// instruction is given by Exit.
114 static std::pair<Type *, bool> computeRecurrenceType(Instruction *Exit,
115                                                      DemandedBits *DB,
116                                                      AssumptionCache *AC,
117                                                      DominatorTree *DT) {
118   bool IsSigned = false;
119   const DataLayout &DL = Exit->getModule()->getDataLayout();
120   uint64_t MaxBitWidth = DL.getTypeSizeInBits(Exit->getType());
121 
122   if (DB) {
123     // Use the demanded bits analysis to determine the bits that are live out
124     // of the exit instruction, rounding up to the nearest power of two. If the
125     // use of demanded bits results in a smaller bit width, we know the value
126     // must be positive (i.e., IsSigned = false), because if this were not the
127     // case, the sign bit would have been demanded.
128     auto Mask = DB->getDemandedBits(Exit);
129     MaxBitWidth = Mask.getBitWidth() - Mask.countLeadingZeros();
130   }
131 
132   if (MaxBitWidth == DL.getTypeSizeInBits(Exit->getType()) && AC && DT) {
133     // If demanded bits wasn't able to limit the bit width, we can try to use
134     // value tracking instead. This can be the case, for example, if the value
135     // may be negative.
136     auto NumSignBits = ComputeNumSignBits(Exit, DL, 0, AC, nullptr, DT);
137     auto NumTypeBits = DL.getTypeSizeInBits(Exit->getType());
138     MaxBitWidth = NumTypeBits - NumSignBits;
139     KnownBits Bits = computeKnownBits(Exit, DL);
140     if (!Bits.isNonNegative()) {
141       // If the value is not known to be non-negative, we set IsSigned to true,
142       // meaning that we will use sext instructions instead of zext
143       // instructions to restore the original type.
144       IsSigned = true;
145       if (!Bits.isNegative())
146         // If the value is not known to be negative, we don't known what the
147         // upper bit is, and therefore, we don't know what kind of extend we
148         // will need. In this case, just increase the bit width by one bit and
149         // use sext.
150         ++MaxBitWidth;
151     }
152   }
153   if (!isPowerOf2_64(MaxBitWidth))
154     MaxBitWidth = NextPowerOf2(MaxBitWidth);
155 
156   return std::make_pair(Type::getIntNTy(Exit->getContext(), MaxBitWidth),
157                         IsSigned);
158 }
159 
160 /// Collect cast instructions that can be ignored in the vectorizer's cost
161 /// model, given a reduction exit value and the minimal type in which the
162 /// reduction can be represented.
163 static void collectCastsToIgnore(Loop *TheLoop, Instruction *Exit,
164                                  Type *RecurrenceType,
165                                  SmallPtrSetImpl<Instruction *> &Casts) {
166 
167   SmallVector<Instruction *, 8> Worklist;
168   SmallPtrSet<Instruction *, 8> Visited;
169   Worklist.push_back(Exit);
170 
171   while (!Worklist.empty()) {
172     Instruction *Val = Worklist.pop_back_val();
173     Visited.insert(Val);
174     if (auto *Cast = dyn_cast<CastInst>(Val))
175       if (Cast->getSrcTy() == RecurrenceType) {
176         // If the source type of a cast instruction is equal to the recurrence
177         // type, it will be eliminated, and should be ignored in the vectorizer
178         // cost model.
179         Casts.insert(Cast);
180         continue;
181       }
182 
183     // Add all operands to the work list if they are loop-varying values that
184     // we haven't yet visited.
185     for (Value *O : cast<User>(Val)->operands())
186       if (auto *I = dyn_cast<Instruction>(O))
187         if (TheLoop->contains(I) && !Visited.count(I))
188           Worklist.push_back(I);
189   }
190 }
191 
192 bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurKind Kind,
193                                            Loop *TheLoop, bool HasFunNoNaNAttr,
194                                            RecurrenceDescriptor &RedDes,
195                                            DemandedBits *DB,
196                                            AssumptionCache *AC,
197                                            DominatorTree *DT) {
198   if (Phi->getNumIncomingValues() != 2)
199     return false;
200 
201   // Reduction variables are only found in the loop header block.
202   if (Phi->getParent() != TheLoop->getHeader())
203     return false;
204 
205   // Obtain the reduction start value from the value that comes from the loop
206   // preheader.
207   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
208 
209   // ExitInstruction is the single value which is used outside the loop.
210   // We only allow for a single reduction value to be used outside the loop.
211   // This includes users of the reduction, variables (which form a cycle
212   // which ends in the phi node).
213   Instruction *ExitInstruction = nullptr;
214   // Indicates that we found a reduction operation in our scan.
215   bool FoundReduxOp = false;
216 
217   // We start with the PHI node and scan for all of the users of this
218   // instruction. All users must be instructions that can be used as reduction
219   // variables (such as ADD). We must have a single out-of-block user. The cycle
220   // must include the original PHI.
221   bool FoundStartPHI = false;
222 
223   // To recognize min/max patterns formed by a icmp select sequence, we store
224   // the number of instruction we saw from the recognized min/max pattern,
225   //  to make sure we only see exactly the two instructions.
226   unsigned NumCmpSelectPatternInst = 0;
227   InstDesc ReduxDesc(false, nullptr);
228 
229   // Data used for determining if the recurrence has been type-promoted.
230   Type *RecurrenceType = Phi->getType();
231   SmallPtrSet<Instruction *, 4> CastInsts;
232   Instruction *Start = Phi;
233   bool IsSigned = false;
234 
235   SmallPtrSet<Instruction *, 8> VisitedInsts;
236   SmallVector<Instruction *, 8> Worklist;
237 
238   // Return early if the recurrence kind does not match the type of Phi. If the
239   // recurrence kind is arithmetic, we attempt to look through AND operations
240   // resulting from the type promotion performed by InstCombine.  Vector
241   // operations are not limited to the legal integer widths, so we may be able
242   // to evaluate the reduction in the narrower width.
243   if (RecurrenceType->isFloatingPointTy()) {
244     if (!isFloatingPointRecurrenceKind(Kind))
245       return false;
246   } else {
247     if (!isIntegerRecurrenceKind(Kind))
248       return false;
249     if (isArithmeticRecurrenceKind(Kind))
250       Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
251   }
252 
253   Worklist.push_back(Start);
254   VisitedInsts.insert(Start);
255 
256   // Start with all flags set because we will intersect this with the reduction
257   // flags from all the reduction operations.
258   FastMathFlags FMF = FastMathFlags::getFast();
259 
260   // A value in the reduction can be used:
261   //  - By the reduction:
262   //      - Reduction operation:
263   //        - One use of reduction value (safe).
264   //        - Multiple use of reduction value (not safe).
265   //      - PHI:
266   //        - All uses of the PHI must be the reduction (safe).
267   //        - Otherwise, not safe.
268   //  - By instructions outside of the loop (safe).
269   //      * One value may have several outside users, but all outside
270   //        uses must be of the same value.
271   //  - By an instruction that is not part of the reduction (not safe).
272   //    This is either:
273   //      * An instruction type other than PHI or the reduction operation.
274   //      * A PHI in the header other than the initial PHI.
275   while (!Worklist.empty()) {
276     Instruction *Cur = Worklist.pop_back_val();
277 
278     // No Users.
279     // If the instruction has no users then this is a broken chain and can't be
280     // a reduction variable.
281     if (Cur->use_empty())
282       return false;
283 
284     bool IsAPhi = isa<PHINode>(Cur);
285 
286     // A header PHI use other than the original PHI.
287     if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
288       return false;
289 
290     // Reductions of instructions such as Div, and Sub is only possible if the
291     // LHS is the reduction variable.
292     if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
293         !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
294         !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
295       return false;
296 
297     // Any reduction instruction must be of one of the allowed kinds. We ignore
298     // the starting value (the Phi or an AND instruction if the Phi has been
299     // type-promoted).
300     if (Cur != Start) {
301       ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
302       if (!ReduxDesc.isRecurrence())
303         return false;
304       // FIXME: FMF is allowed on phi, but propagation is not handled correctly.
305       if (isa<FPMathOperator>(ReduxDesc.getPatternInst()) && !IsAPhi)
306         FMF &= ReduxDesc.getPatternInst()->getFastMathFlags();
307       // Update this reduction kind if we matched a new instruction.
308       // TODO: Can we eliminate the need for a 2nd InstDesc by keeping 'Kind'
309       //       state accurate while processing the worklist?
310       if (ReduxDesc.getRecKind() != RecurKind::None)
311         Kind = ReduxDesc.getRecKind();
312     }
313 
314     bool IsASelect = isa<SelectInst>(Cur);
315 
316     // A conditional reduction operation must only have 2 or less uses in
317     // VisitedInsts.
318     if (IsASelect && (Kind == RecurKind::FAdd || Kind == RecurKind::FMul) &&
319         hasMultipleUsesOf(Cur, VisitedInsts, 2))
320       return false;
321 
322     // A reduction operation must only have one use of the reduction value.
323     if (!IsAPhi && !IsASelect && !isMinMaxRecurrenceKind(Kind) &&
324         hasMultipleUsesOf(Cur, VisitedInsts, 1))
325       return false;
326 
327     // All inputs to a PHI node must be a reduction value.
328     if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
329       return false;
330 
331     if (isIntMinMaxRecurrenceKind(Kind) &&
332         (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
333       ++NumCmpSelectPatternInst;
334     if (isFPMinMaxRecurrenceKind(Kind) &&
335         (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
336       ++NumCmpSelectPatternInst;
337 
338     // Check  whether we found a reduction operator.
339     FoundReduxOp |= !IsAPhi && Cur != Start;
340 
341     // Process users of current instruction. Push non-PHI nodes after PHI nodes
342     // onto the stack. This way we are going to have seen all inputs to PHI
343     // nodes once we get to them.
344     SmallVector<Instruction *, 8> NonPHIs;
345     SmallVector<Instruction *, 8> PHIs;
346     for (User *U : Cur->users()) {
347       Instruction *UI = cast<Instruction>(U);
348 
349       // Check if we found the exit user.
350       BasicBlock *Parent = UI->getParent();
351       if (!TheLoop->contains(Parent)) {
352         // If we already know this instruction is used externally, move on to
353         // the next user.
354         if (ExitInstruction == Cur)
355           continue;
356 
357         // Exit if you find multiple values used outside or if the header phi
358         // node is being used. In this case the user uses the value of the
359         // previous iteration, in which case we would loose "VF-1" iterations of
360         // the reduction operation if we vectorize.
361         if (ExitInstruction != nullptr || Cur == Phi)
362           return false;
363 
364         // The instruction used by an outside user must be the last instruction
365         // before we feed back to the reduction phi. Otherwise, we loose VF-1
366         // operations on the value.
367         if (!is_contained(Phi->operands(), Cur))
368           return false;
369 
370         ExitInstruction = Cur;
371         continue;
372       }
373 
374       // Process instructions only once (termination). Each reduction cycle
375       // value must only be used once, except by phi nodes and min/max
376       // reductions which are represented as a cmp followed by a select.
377       InstDesc IgnoredVal(false, nullptr);
378       if (VisitedInsts.insert(UI).second) {
379         if (isa<PHINode>(UI))
380           PHIs.push_back(UI);
381         else
382           NonPHIs.push_back(UI);
383       } else if (!isa<PHINode>(UI) &&
384                  ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
385                    !isa<SelectInst>(UI)) ||
386                   (!isConditionalRdxPattern(Kind, UI).isRecurrence() &&
387                    !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence())))
388         return false;
389 
390       // Remember that we completed the cycle.
391       if (UI == Phi)
392         FoundStartPHI = true;
393     }
394     Worklist.append(PHIs.begin(), PHIs.end());
395     Worklist.append(NonPHIs.begin(), NonPHIs.end());
396   }
397 
398   // This means we have seen one but not the other instruction of the
399   // pattern or more than just a select and cmp.
400   if (isMinMaxRecurrenceKind(Kind) && NumCmpSelectPatternInst != 2)
401     return false;
402 
403   if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
404     return false;
405 
406   if (Start != Phi) {
407     // If the starting value is not the same as the phi node, we speculatively
408     // looked through an 'and' instruction when evaluating a potential
409     // arithmetic reduction to determine if it may have been type-promoted.
410     //
411     // We now compute the minimal bit width that is required to represent the
412     // reduction. If this is the same width that was indicated by the 'and', we
413     // can represent the reduction in the smaller type. The 'and' instruction
414     // will be eliminated since it will essentially be a cast instruction that
415     // can be ignore in the cost model. If we compute a different type than we
416     // did when evaluating the 'and', the 'and' will not be eliminated, and we
417     // will end up with different kinds of operations in the recurrence
418     // expression (e.g., IntegerAND, IntegerADD). We give up if this is
419     // the case.
420     //
421     // The vectorizer relies on InstCombine to perform the actual
422     // type-shrinking. It does this by inserting instructions to truncate the
423     // exit value of the reduction to the width indicated by RecurrenceType and
424     // then extend this value back to the original width. If IsSigned is false,
425     // a 'zext' instruction will be generated; otherwise, a 'sext' will be
426     // used.
427     //
428     // TODO: We should not rely on InstCombine to rewrite the reduction in the
429     //       smaller type. We should just generate a correctly typed expression
430     //       to begin with.
431     Type *ComputedType;
432     std::tie(ComputedType, IsSigned) =
433         computeRecurrenceType(ExitInstruction, DB, AC, DT);
434     if (ComputedType != RecurrenceType)
435       return false;
436 
437     // The recurrence expression will be represented in a narrower type. If
438     // there are any cast instructions that will be unnecessary, collect them
439     // in CastInsts. Note that the 'and' instruction was already included in
440     // this list.
441     //
442     // TODO: A better way to represent this may be to tag in some way all the
443     //       instructions that are a part of the reduction. The vectorizer cost
444     //       model could then apply the recurrence type to these instructions,
445     //       without needing a white list of instructions to ignore.
446     //       This may also be useful for the inloop reductions, if it can be
447     //       kept simple enough.
448     collectCastsToIgnore(TheLoop, ExitInstruction, RecurrenceType, CastInsts);
449   }
450 
451   // We found a reduction var if we have reached the original phi node and we
452   // only have a single instruction with out-of-loop users.
453 
454   // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
455   // is saved as part of the RecurrenceDescriptor.
456 
457   // Save the description of this reduction variable.
458   RecurrenceDescriptor RD(RdxStart, ExitInstruction, Kind, FMF,
459                           ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType,
460                           IsSigned, CastInsts);
461   RedDes = RD;
462 
463   return true;
464 }
465 
466 RecurrenceDescriptor::InstDesc
467 RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I,
468                                                const InstDesc &Prev) {
469   assert((isa<CmpInst>(I) || isa<SelectInst>(I)) &&
470          "Expected a cmp or select instruction");
471 
472   // We must handle the select(cmp()) as a single instruction. Advance to the
473   // select.
474   CmpInst::Predicate Pred;
475   if (match(I, m_OneUse(m_Cmp(Pred, m_Value(), m_Value())))) {
476     if (auto *Select = dyn_cast<SelectInst>(*I->user_begin()))
477       return InstDesc(Select, Prev.getRecKind());
478   }
479 
480   // Only match select with single use cmp condition.
481   if (!match(I, m_Select(m_OneUse(m_Cmp(Pred, m_Value(), m_Value())), m_Value(),
482                          m_Value())))
483     return InstDesc(false, I);
484 
485   // Look for a min/max pattern.
486   if (match(I, m_UMin(m_Value(), m_Value())))
487     return InstDesc(I, RecurKind::UMin);
488   if (match(I, m_UMax(m_Value(), m_Value())))
489     return InstDesc(I, RecurKind::UMax);
490   if (match(I, m_SMax(m_Value(), m_Value())))
491     return InstDesc(I, RecurKind::SMax);
492   if (match(I, m_SMin(m_Value(), m_Value())))
493     return InstDesc(I, RecurKind::SMin);
494   if (match(I, m_OrdFMin(m_Value(), m_Value())))
495     return InstDesc(I, RecurKind::FMin);
496   if (match(I, m_OrdFMax(m_Value(), m_Value())))
497     return InstDesc(I, RecurKind::FMax);
498   if (match(I, m_UnordFMin(m_Value(), m_Value())))
499     return InstDesc(I, RecurKind::FMin);
500   if (match(I, m_UnordFMax(m_Value(), m_Value())))
501     return InstDesc(I, RecurKind::FMax);
502 
503   return InstDesc(false, I);
504 }
505 
506 /// Returns true if the select instruction has users in the compare-and-add
507 /// reduction pattern below. The select instruction argument is the last one
508 /// in the sequence.
509 ///
510 /// %sum.1 = phi ...
511 /// ...
512 /// %cmp = fcmp pred %0, %CFP
513 /// %add = fadd %0, %sum.1
514 /// %sum.2 = select %cmp, %add, %sum.1
515 RecurrenceDescriptor::InstDesc
516 RecurrenceDescriptor::isConditionalRdxPattern(RecurKind Kind, Instruction *I) {
517   SelectInst *SI = dyn_cast<SelectInst>(I);
518   if (!SI)
519     return InstDesc(false, I);
520 
521   CmpInst *CI = dyn_cast<CmpInst>(SI->getCondition());
522   // Only handle single use cases for now.
523   if (!CI || !CI->hasOneUse())
524     return InstDesc(false, I);
525 
526   Value *TrueVal = SI->getTrueValue();
527   Value *FalseVal = SI->getFalseValue();
528   // Handle only when either of operands of select instruction is a PHI
529   // node for now.
530   if ((isa<PHINode>(*TrueVal) && isa<PHINode>(*FalseVal)) ||
531       (!isa<PHINode>(*TrueVal) && !isa<PHINode>(*FalseVal)))
532     return InstDesc(false, I);
533 
534   Instruction *I1 =
535       isa<PHINode>(*TrueVal) ? dyn_cast<Instruction>(FalseVal)
536                              : dyn_cast<Instruction>(TrueVal);
537   if (!I1 || !I1->isBinaryOp())
538     return InstDesc(false, I);
539 
540   Value *Op1, *Op2;
541   if ((m_FAdd(m_Value(Op1), m_Value(Op2)).match(I1)  ||
542        m_FSub(m_Value(Op1), m_Value(Op2)).match(I1)) &&
543       I1->isFast())
544     return InstDesc(Kind == RecurKind::FAdd, SI);
545 
546   if (m_FMul(m_Value(Op1), m_Value(Op2)).match(I1) && (I1->isFast()))
547     return InstDesc(Kind == RecurKind::FMul, SI);
548 
549   return InstDesc(false, I);
550 }
551 
552 RecurrenceDescriptor::InstDesc
553 RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurKind Kind,
554                                         InstDesc &Prev, bool HasFunNoNaNAttr) {
555   Instruction *UAI = Prev.getUnsafeAlgebraInst();
556   if (!UAI && isa<FPMathOperator>(I) && !I->hasAllowReassoc())
557     UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
558 
559   switch (I->getOpcode()) {
560   default:
561     return InstDesc(false, I);
562   case Instruction::PHI:
563     return InstDesc(I, Prev.getRecKind(), Prev.getUnsafeAlgebraInst());
564   case Instruction::Sub:
565   case Instruction::Add:
566     return InstDesc(Kind == RecurKind::Add, I);
567   case Instruction::Mul:
568     return InstDesc(Kind == RecurKind::Mul, I);
569   case Instruction::And:
570     return InstDesc(Kind == RecurKind::And, I);
571   case Instruction::Or:
572     return InstDesc(Kind == RecurKind::Or, I);
573   case Instruction::Xor:
574     return InstDesc(Kind == RecurKind::Xor, I);
575   case Instruction::FDiv:
576   case Instruction::FMul:
577     return InstDesc(Kind == RecurKind::FMul, I, UAI);
578   case Instruction::FSub:
579   case Instruction::FAdd:
580     return InstDesc(Kind == RecurKind::FAdd, I, UAI);
581   case Instruction::Select:
582     if (Kind == RecurKind::FAdd || Kind == RecurKind::FMul)
583       return isConditionalRdxPattern(Kind, I);
584     LLVM_FALLTHROUGH;
585   case Instruction::FCmp:
586   case Instruction::ICmp:
587     if (!isIntMinMaxRecurrenceKind(Kind) &&
588         (!HasFunNoNaNAttr || !isFPMinMaxRecurrenceKind(Kind)))
589       return InstDesc(false, I);
590     return isMinMaxSelectCmpPattern(I, Prev);
591   }
592 }
593 
594 bool RecurrenceDescriptor::hasMultipleUsesOf(
595     Instruction *I, SmallPtrSetImpl<Instruction *> &Insts,
596     unsigned MaxNumUses) {
597   unsigned NumUses = 0;
598   for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
599        ++Use) {
600     if (Insts.count(dyn_cast<Instruction>(*Use)))
601       ++NumUses;
602     if (NumUses > MaxNumUses)
603       return true;
604   }
605 
606   return false;
607 }
608 bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
609                                           RecurrenceDescriptor &RedDes,
610                                           DemandedBits *DB, AssumptionCache *AC,
611                                           DominatorTree *DT) {
612 
613   BasicBlock *Header = TheLoop->getHeader();
614   Function &F = *Header->getParent();
615   bool HasFunNoNaNAttr =
616       F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
617 
618   if (AddReductionVar(Phi, RecurKind::Add, TheLoop, HasFunNoNaNAttr, RedDes, DB,
619                       AC, DT)) {
620     LLVM_DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
621     return true;
622   }
623   if (AddReductionVar(Phi, RecurKind::Mul, TheLoop, HasFunNoNaNAttr, RedDes, DB,
624                       AC, DT)) {
625     LLVM_DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
626     return true;
627   }
628   if (AddReductionVar(Phi, RecurKind::Or, TheLoop, HasFunNoNaNAttr, RedDes, DB,
629                       AC, DT)) {
630     LLVM_DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
631     return true;
632   }
633   if (AddReductionVar(Phi, RecurKind::And, TheLoop, HasFunNoNaNAttr, RedDes, DB,
634                       AC, DT)) {
635     LLVM_DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
636     return true;
637   }
638   if (AddReductionVar(Phi, RecurKind::Xor, TheLoop, HasFunNoNaNAttr, RedDes, DB,
639                       AC, DT)) {
640     LLVM_DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
641     return true;
642   }
643   if (AddReductionVar(Phi, RecurKind::SMax, TheLoop, HasFunNoNaNAttr, RedDes,
644                       DB, AC, DT)) {
645     LLVM_DEBUG(dbgs() << "Found a SMAX reduction PHI." << *Phi << "\n");
646     return true;
647   }
648   if (AddReductionVar(Phi, RecurKind::SMin, TheLoop, HasFunNoNaNAttr, RedDes,
649                       DB, AC, DT)) {
650     LLVM_DEBUG(dbgs() << "Found a SMIN reduction PHI." << *Phi << "\n");
651     return true;
652   }
653   if (AddReductionVar(Phi, RecurKind::UMax, TheLoop, HasFunNoNaNAttr, RedDes,
654                       DB, AC, DT)) {
655     LLVM_DEBUG(dbgs() << "Found a UMAX reduction PHI." << *Phi << "\n");
656     return true;
657   }
658   if (AddReductionVar(Phi, RecurKind::UMin, TheLoop, HasFunNoNaNAttr, RedDes,
659                       DB, AC, DT)) {
660     LLVM_DEBUG(dbgs() << "Found a UMIN reduction PHI." << *Phi << "\n");
661     return true;
662   }
663   if (AddReductionVar(Phi, RecurKind::FMul, TheLoop, HasFunNoNaNAttr, RedDes,
664                       DB, AC, DT)) {
665     LLVM_DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
666     return true;
667   }
668   if (AddReductionVar(Phi, RecurKind::FAdd, TheLoop, HasFunNoNaNAttr, RedDes,
669                       DB, AC, DT)) {
670     LLVM_DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
671     return true;
672   }
673   if (AddReductionVar(Phi, RecurKind::FMax, TheLoop, HasFunNoNaNAttr, RedDes,
674                       DB, AC, DT)) {
675     LLVM_DEBUG(dbgs() << "Found a float MAX reduction PHI." << *Phi << "\n");
676     return true;
677   }
678   if (AddReductionVar(Phi, RecurKind::FMin, TheLoop, HasFunNoNaNAttr, RedDes,
679                       DB, AC, DT)) {
680     LLVM_DEBUG(dbgs() << "Found a float MIN reduction PHI." << *Phi << "\n");
681     return true;
682   }
683   // Not a reduction of known type.
684   return false;
685 }
686 
687 bool RecurrenceDescriptor::isFirstOrderRecurrence(
688     PHINode *Phi, Loop *TheLoop,
689     DenseMap<Instruction *, Instruction *> &SinkAfter, DominatorTree *DT) {
690 
691   // Ensure the phi node is in the loop header and has two incoming values.
692   if (Phi->getParent() != TheLoop->getHeader() ||
693       Phi->getNumIncomingValues() != 2)
694     return false;
695 
696   // Ensure the loop has a preheader and a single latch block. The loop
697   // vectorizer will need the latch to set up the next iteration of the loop.
698   auto *Preheader = TheLoop->getLoopPreheader();
699   auto *Latch = TheLoop->getLoopLatch();
700   if (!Preheader || !Latch)
701     return false;
702 
703   // Ensure the phi node's incoming blocks are the loop preheader and latch.
704   if (Phi->getBasicBlockIndex(Preheader) < 0 ||
705       Phi->getBasicBlockIndex(Latch) < 0)
706     return false;
707 
708   // Get the previous value. The previous value comes from the latch edge while
709   // the initial value comes form the preheader edge.
710   auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
711   if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous) ||
712       SinkAfter.count(Previous)) // Cannot rely on dominance due to motion.
713     return false;
714 
715   // Ensure every user of the phi node is dominated by the previous value.
716   // The dominance requirement ensures the loop vectorizer will not need to
717   // vectorize the initial value prior to the first iteration of the loop.
718   // TODO: Consider extending this sinking to handle memory instructions and
719   // phis with multiple users.
720 
721   // Returns true, if all users of I are dominated by DominatedBy.
722   auto allUsesDominatedBy = [DT](Instruction *I, Instruction *DominatedBy) {
723     return all_of(I->uses(), [DT, DominatedBy](Use &U) {
724       return DT->dominates(DominatedBy, U);
725     });
726   };
727 
728   if (Phi->hasOneUse()) {
729     Instruction *I = Phi->user_back();
730 
731     // If the user of the PHI is also the incoming value, we potentially have a
732     // reduction and which cannot be handled by sinking.
733     if (Previous == I)
734       return false;
735 
736     // We cannot sink terminator instructions.
737     if (I->getParent()->getTerminator() == I)
738       return false;
739 
740     // Do not try to sink an instruction multiple times (if multiple operands
741     // are first order recurrences).
742     // TODO: We can support this case, by sinking the instruction after the
743     // 'deepest' previous instruction.
744     if (SinkAfter.find(I) != SinkAfter.end())
745       return false;
746 
747     if (DT->dominates(Previous, I)) // We already are good w/o sinking.
748       return true;
749 
750     // We can sink any instruction without side effects, as long as all users
751     // are dominated by the instruction we are sinking after.
752     if (I->getParent() == Phi->getParent() && !I->mayHaveSideEffects() &&
753         allUsesDominatedBy(I, Previous)) {
754       SinkAfter[I] = Previous;
755       return true;
756     }
757   }
758 
759   return allUsesDominatedBy(Phi, Previous);
760 }
761 
762 /// This function returns the identity element (or neutral element) for
763 /// the operation K.
764 Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurKind K, Type *Tp) {
765   switch (K) {
766   case RecurKind::Xor:
767   case RecurKind::Add:
768   case RecurKind::Or:
769     // Adding, Xoring, Oring zero to a number does not change it.
770     return ConstantInt::get(Tp, 0);
771   case RecurKind::Mul:
772     // Multiplying a number by 1 does not change it.
773     return ConstantInt::get(Tp, 1);
774   case RecurKind::And:
775     // AND-ing a number with an all-1 value does not change it.
776     return ConstantInt::get(Tp, -1, true);
777   case RecurKind::FMul:
778     // Multiplying a number by 1 does not change it.
779     return ConstantFP::get(Tp, 1.0L);
780   case RecurKind::FAdd:
781     // Adding zero to a number does not change it.
782     return ConstantFP::get(Tp, 0.0L);
783   case RecurKind::UMin:
784     return ConstantInt::get(Tp, -1);
785   case RecurKind::UMax:
786     return ConstantInt::get(Tp, 0);
787   case RecurKind::SMin:
788     return ConstantInt::get(Tp,
789                             APInt::getSignedMaxValue(Tp->getIntegerBitWidth()));
790   case RecurKind::SMax:
791     return ConstantInt::get(Tp,
792                             APInt::getSignedMinValue(Tp->getIntegerBitWidth()));
793   case RecurKind::FMin:
794     return ConstantFP::getInfinity(Tp, true);
795   case RecurKind::FMax:
796     return ConstantFP::getInfinity(Tp, false);
797   default:
798     llvm_unreachable("Unknown recurrence kind");
799   }
800 }
801 
802 unsigned RecurrenceDescriptor::getOpcode(RecurKind Kind) {
803   switch (Kind) {
804   case RecurKind::Add:
805     return Instruction::Add;
806   case RecurKind::Mul:
807     return Instruction::Mul;
808   case RecurKind::Or:
809     return Instruction::Or;
810   case RecurKind::And:
811     return Instruction::And;
812   case RecurKind::Xor:
813     return Instruction::Xor;
814   case RecurKind::FMul:
815     return Instruction::FMul;
816   case RecurKind::FAdd:
817     return Instruction::FAdd;
818   case RecurKind::SMax:
819   case RecurKind::SMin:
820   case RecurKind::UMax:
821   case RecurKind::UMin:
822     return Instruction::ICmp;
823   case RecurKind::FMax:
824   case RecurKind::FMin:
825     return Instruction::FCmp;
826   default:
827     llvm_unreachable("Unknown recurrence operation");
828   }
829 }
830 
831 SmallVector<Instruction *, 4>
832 RecurrenceDescriptor::getReductionOpChain(PHINode *Phi, Loop *L) const {
833   SmallVector<Instruction *, 4> ReductionOperations;
834   unsigned RedOp = getOpcode(Kind);
835 
836   // Search down from the Phi to the LoopExitInstr, looking for instructions
837   // with a single user of the correct type for the reduction.
838 
839   // Note that we check that the type of the operand is correct for each item in
840   // the chain, including the last (the loop exit value). This can come up from
841   // sub, which would otherwise be treated as an add reduction. MinMax also need
842   // to check for a pair of icmp/select, for which we use getNextInstruction and
843   // isCorrectOpcode functions to step the right number of instruction, and
844   // check the icmp/select pair.
845   // FIXME: We also do not attempt to look through Phi/Select's yet, which might
846   // be part of the reduction chain, or attempt to looks through And's to find a
847   // smaller bitwidth. Subs are also currently not allowed (which are usually
848   // treated as part of a add reduction) as they are expected to generally be
849   // more expensive than out-of-loop reductions, and need to be costed more
850   // carefully.
851   unsigned ExpectedUses = 1;
852   if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp)
853     ExpectedUses = 2;
854 
855   auto getNextInstruction = [&](Instruction *Cur) {
856     if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp) {
857       // We are expecting a icmp/select pair, which we go to the next select
858       // instruction if we can. We already know that Cur has 2 uses.
859       if (isa<SelectInst>(*Cur->user_begin()))
860         return cast<Instruction>(*Cur->user_begin());
861       else
862         return cast<Instruction>(*std::next(Cur->user_begin()));
863     }
864     return cast<Instruction>(*Cur->user_begin());
865   };
866   auto isCorrectOpcode = [&](Instruction *Cur) {
867     if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp) {
868       Value *LHS, *RHS;
869       return SelectPatternResult::isMinOrMax(
870           matchSelectPattern(Cur, LHS, RHS).Flavor);
871     }
872     return Cur->getOpcode() == RedOp;
873   };
874 
875   // The loop exit instruction we check first (as a quick test) but add last. We
876   // check the opcode is correct (and dont allow them to be Subs) and that they
877   // have expected to have the expected number of uses. They will have one use
878   // from the phi and one from a LCSSA value, no matter the type.
879   if (!isCorrectOpcode(LoopExitInstr) || !LoopExitInstr->hasNUses(2))
880     return {};
881 
882   // Check that the Phi has one (or two for min/max) uses.
883   if (!Phi->hasNUses(ExpectedUses))
884     return {};
885   Instruction *Cur = getNextInstruction(Phi);
886 
887   // Each other instruction in the chain should have the expected number of uses
888   // and be the correct opcode.
889   while (Cur != LoopExitInstr) {
890     if (!isCorrectOpcode(Cur) || !Cur->hasNUses(ExpectedUses))
891       return {};
892 
893     ReductionOperations.push_back(Cur);
894     Cur = getNextInstruction(Cur);
895   }
896 
897   ReductionOperations.push_back(Cur);
898   return ReductionOperations;
899 }
900 
901 InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
902                                          const SCEV *Step, BinaryOperator *BOp,
903                                          SmallVectorImpl<Instruction *> *Casts)
904     : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
905   assert(IK != IK_NoInduction && "Not an induction");
906 
907   // Start value type should match the induction kind and the value
908   // itself should not be null.
909   assert(StartValue && "StartValue is null");
910   assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
911          "StartValue is not a pointer for pointer induction");
912   assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
913          "StartValue is not an integer for integer induction");
914 
915   // Check the Step Value. It should be non-zero integer value.
916   assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
917          "Step value is zero");
918 
919   assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
920          "Step value should be constant for pointer induction");
921   assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
922          "StepValue is not an integer");
923 
924   assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
925          "StepValue is not FP for FpInduction");
926   assert((IK != IK_FpInduction ||
927           (InductionBinOp &&
928            (InductionBinOp->getOpcode() == Instruction::FAdd ||
929             InductionBinOp->getOpcode() == Instruction::FSub))) &&
930          "Binary opcode should be specified for FP induction");
931 
932   if (Casts) {
933     for (auto &Inst : *Casts) {
934       RedundantCasts.push_back(Inst);
935     }
936   }
937 }
938 
939 ConstantInt *InductionDescriptor::getConstIntStepValue() const {
940   if (isa<SCEVConstant>(Step))
941     return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
942   return nullptr;
943 }
944 
945 bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop,
946                                            ScalarEvolution *SE,
947                                            InductionDescriptor &D) {
948 
949   // Here we only handle FP induction variables.
950   assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
951 
952   if (TheLoop->getHeader() != Phi->getParent())
953     return false;
954 
955   // The loop may have multiple entrances or multiple exits; we can analyze
956   // this phi if it has a unique entry value and a unique backedge value.
957   if (Phi->getNumIncomingValues() != 2)
958     return false;
959   Value *BEValue = nullptr, *StartValue = nullptr;
960   if (TheLoop->contains(Phi->getIncomingBlock(0))) {
961     BEValue = Phi->getIncomingValue(0);
962     StartValue = Phi->getIncomingValue(1);
963   } else {
964     assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
965            "Unexpected Phi node in the loop");
966     BEValue = Phi->getIncomingValue(1);
967     StartValue = Phi->getIncomingValue(0);
968   }
969 
970   BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue);
971   if (!BOp)
972     return false;
973 
974   Value *Addend = nullptr;
975   if (BOp->getOpcode() == Instruction::FAdd) {
976     if (BOp->getOperand(0) == Phi)
977       Addend = BOp->getOperand(1);
978     else if (BOp->getOperand(1) == Phi)
979       Addend = BOp->getOperand(0);
980   } else if (BOp->getOpcode() == Instruction::FSub)
981     if (BOp->getOperand(0) == Phi)
982       Addend = BOp->getOperand(1);
983 
984   if (!Addend)
985     return false;
986 
987   // The addend should be loop invariant
988   if (auto *I = dyn_cast<Instruction>(Addend))
989     if (TheLoop->contains(I))
990       return false;
991 
992   // FP Step has unknown SCEV
993   const SCEV *Step = SE->getUnknown(Addend);
994   D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
995   return true;
996 }
997 
998 /// This function is called when we suspect that the update-chain of a phi node
999 /// (whose symbolic SCEV expression sin \p PhiScev) contains redundant casts,
1000 /// that can be ignored. (This can happen when the PSCEV rewriter adds a runtime
1001 /// predicate P under which the SCEV expression for the phi can be the
1002 /// AddRecurrence \p AR; See createAddRecFromPHIWithCast). We want to find the
1003 /// cast instructions that are involved in the update-chain of this induction.
1004 /// A caller that adds the required runtime predicate can be free to drop these
1005 /// cast instructions, and compute the phi using \p AR (instead of some scev
1006 /// expression with casts).
1007 ///
1008 /// For example, without a predicate the scev expression can take the following
1009 /// form:
1010 ///      (Ext ix (Trunc iy ( Start + i*Step ) to ix) to iy)
1011 ///
1012 /// It corresponds to the following IR sequence:
1013 /// %for.body:
1014 ///   %x = phi i64 [ 0, %ph ], [ %add, %for.body ]
1015 ///   %casted_phi = "ExtTrunc i64 %x"
1016 ///   %add = add i64 %casted_phi, %step
1017 ///
1018 /// where %x is given in \p PN,
1019 /// PSE.getSCEV(%x) is equal to PSE.getSCEV(%casted_phi) under a predicate,
1020 /// and the IR sequence that "ExtTrunc i64 %x" represents can take one of
1021 /// several forms, for example, such as:
1022 ///   ExtTrunc1:    %casted_phi = and  %x, 2^n-1
1023 /// or:
1024 ///   ExtTrunc2:    %t = shl %x, m
1025 ///                 %casted_phi = ashr %t, m
1026 ///
1027 /// If we are able to find such sequence, we return the instructions
1028 /// we found, namely %casted_phi and the instructions on its use-def chain up
1029 /// to the phi (not including the phi).
1030 static bool getCastsForInductionPHI(PredicatedScalarEvolution &PSE,
1031                                     const SCEVUnknown *PhiScev,
1032                                     const SCEVAddRecExpr *AR,
1033                                     SmallVectorImpl<Instruction *> &CastInsts) {
1034 
1035   assert(CastInsts.empty() && "CastInsts is expected to be empty.");
1036   auto *PN = cast<PHINode>(PhiScev->getValue());
1037   assert(PSE.getSCEV(PN) == AR && "Unexpected phi node SCEV expression");
1038   const Loop *L = AR->getLoop();
1039 
1040   // Find any cast instructions that participate in the def-use chain of
1041   // PhiScev in the loop.
1042   // FORNOW/TODO: We currently expect the def-use chain to include only
1043   // two-operand instructions, where one of the operands is an invariant.
1044   // createAddRecFromPHIWithCasts() currently does not support anything more
1045   // involved than that, so we keep the search simple. This can be
1046   // extended/generalized as needed.
1047 
1048   auto getDef = [&](const Value *Val) -> Value * {
1049     const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val);
1050     if (!BinOp)
1051       return nullptr;
1052     Value *Op0 = BinOp->getOperand(0);
1053     Value *Op1 = BinOp->getOperand(1);
1054     Value *Def = nullptr;
1055     if (L->isLoopInvariant(Op0))
1056       Def = Op1;
1057     else if (L->isLoopInvariant(Op1))
1058       Def = Op0;
1059     return Def;
1060   };
1061 
1062   // Look for the instruction that defines the induction via the
1063   // loop backedge.
1064   BasicBlock *Latch = L->getLoopLatch();
1065   if (!Latch)
1066     return false;
1067   Value *Val = PN->getIncomingValueForBlock(Latch);
1068   if (!Val)
1069     return false;
1070 
1071   // Follow the def-use chain until the induction phi is reached.
1072   // If on the way we encounter a Value that has the same SCEV Expr as the
1073   // phi node, we can consider the instructions we visit from that point
1074   // as part of the cast-sequence that can be ignored.
1075   bool InCastSequence = false;
1076   auto *Inst = dyn_cast<Instruction>(Val);
1077   while (Val != PN) {
1078     // If we encountered a phi node other than PN, or if we left the loop,
1079     // we bail out.
1080     if (!Inst || !L->contains(Inst)) {
1081       return false;
1082     }
1083     auto *AddRec = dyn_cast<SCEVAddRecExpr>(PSE.getSCEV(Val));
1084     if (AddRec && PSE.areAddRecsEqualWithPreds(AddRec, AR))
1085       InCastSequence = true;
1086     if (InCastSequence) {
1087       // Only the last instruction in the cast sequence is expected to have
1088       // uses outside the induction def-use chain.
1089       if (!CastInsts.empty())
1090         if (!Inst->hasOneUse())
1091           return false;
1092       CastInsts.push_back(Inst);
1093     }
1094     Val = getDef(Val);
1095     if (!Val)
1096       return false;
1097     Inst = dyn_cast<Instruction>(Val);
1098   }
1099 
1100   return InCastSequence;
1101 }
1102 
1103 bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
1104                                          PredicatedScalarEvolution &PSE,
1105                                          InductionDescriptor &D, bool Assume) {
1106   Type *PhiTy = Phi->getType();
1107 
1108   // Handle integer and pointer inductions variables.
1109   // Now we handle also FP induction but not trying to make a
1110   // recurrent expression from the PHI node in-place.
1111 
1112   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() && !PhiTy->isFloatTy() &&
1113       !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
1114     return false;
1115 
1116   if (PhiTy->isFloatingPointTy())
1117     return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
1118 
1119   const SCEV *PhiScev = PSE.getSCEV(Phi);
1120   const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1121 
1122   // We need this expression to be an AddRecExpr.
1123   if (Assume && !AR)
1124     AR = PSE.getAsAddRec(Phi);
1125 
1126   if (!AR) {
1127     LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1128     return false;
1129   }
1130 
1131   // Record any Cast instructions that participate in the induction update
1132   const auto *SymbolicPhi = dyn_cast<SCEVUnknown>(PhiScev);
1133   // If we started from an UnknownSCEV, and managed to build an addRecurrence
1134   // only after enabling Assume with PSCEV, this means we may have encountered
1135   // cast instructions that required adding a runtime check in order to
1136   // guarantee the correctness of the AddRecurrence respresentation of the
1137   // induction.
1138   if (PhiScev != AR && SymbolicPhi) {
1139     SmallVector<Instruction *, 2> Casts;
1140     if (getCastsForInductionPHI(PSE, SymbolicPhi, AR, Casts))
1141       return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR, &Casts);
1142   }
1143 
1144   return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
1145 }
1146 
1147 bool InductionDescriptor::isInductionPHI(
1148     PHINode *Phi, const Loop *TheLoop, ScalarEvolution *SE,
1149     InductionDescriptor &D, const SCEV *Expr,
1150     SmallVectorImpl<Instruction *> *CastsToIgnore) {
1151   Type *PhiTy = Phi->getType();
1152   // We only handle integer and pointer inductions variables.
1153   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
1154     return false;
1155 
1156   // Check that the PHI is consecutive.
1157   const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
1158   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1159 
1160   if (!AR) {
1161     LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1162     return false;
1163   }
1164 
1165   if (AR->getLoop() != TheLoop) {
1166     // FIXME: We should treat this as a uniform. Unfortunately, we
1167     // don't currently know how to handled uniform PHIs.
1168     LLVM_DEBUG(
1169         dbgs() << "LV: PHI is a recurrence with respect to an outer loop.\n");
1170     return false;
1171   }
1172 
1173   Value *StartValue =
1174       Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
1175 
1176   BasicBlock *Latch = AR->getLoop()->getLoopLatch();
1177   if (!Latch)
1178     return false;
1179   BinaryOperator *BOp =
1180       dyn_cast<BinaryOperator>(Phi->getIncomingValueForBlock(Latch));
1181 
1182   const SCEV *Step = AR->getStepRecurrence(*SE);
1183   // Calculate the pointer stride and check if it is consecutive.
1184   // The stride may be a constant or a loop invariant integer value.
1185   const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
1186   if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop))
1187     return false;
1188 
1189   if (PhiTy->isIntegerTy()) {
1190     D = InductionDescriptor(StartValue, IK_IntInduction, Step, BOp,
1191                             CastsToIgnore);
1192     return true;
1193   }
1194 
1195   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1196   // Pointer induction should be a constant.
1197   if (!ConstStep)
1198     return false;
1199 
1200   ConstantInt *CV = ConstStep->getValue();
1201   Type *PointerElementType = PhiTy->getPointerElementType();
1202   // The pointer stride cannot be determined if the pointer element type is not
1203   // sized.
1204   if (!PointerElementType->isSized())
1205     return false;
1206 
1207   const DataLayout &DL = Phi->getModule()->getDataLayout();
1208   int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
1209   if (!Size)
1210     return false;
1211 
1212   int64_t CVSize = CV->getSExtValue();
1213   if (CVSize % Size)
1214     return false;
1215   auto *StepValue =
1216       SE->getConstant(CV->getType(), CVSize / Size, true /* signed */);
1217   D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue, BOp);
1218   return true;
1219 }
1220