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