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