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