xref: /openbsd-src/gnu/llvm/llvm/lib/Analysis/IVDescriptors.cpp (revision d415bd752c734aee168c4ee86ff32e8cc249eb16)
109467b48Spatrick //===- llvm/Analysis/IVDescriptors.cpp - IndVar Descriptors -----*- C++ -*-===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This file "describes" induction and recurrence variables.
1009467b48Spatrick //
1109467b48Spatrick //===----------------------------------------------------------------------===//
1209467b48Spatrick 
1309467b48Spatrick #include "llvm/Analysis/IVDescriptors.h"
14097a140dSpatrick #include "llvm/Analysis/DemandedBits.h"
1509467b48Spatrick #include "llvm/Analysis/LoopInfo.h"
1609467b48Spatrick #include "llvm/Analysis/ScalarEvolution.h"
1709467b48Spatrick #include "llvm/Analysis/ScalarEvolutionExpressions.h"
1809467b48Spatrick #include "llvm/Analysis/ValueTracking.h"
1909467b48Spatrick #include "llvm/IR/Dominators.h"
2009467b48Spatrick #include "llvm/IR/Instructions.h"
2109467b48Spatrick #include "llvm/IR/Module.h"
2209467b48Spatrick #include "llvm/IR/PatternMatch.h"
2309467b48Spatrick #include "llvm/IR/ValueHandle.h"
2409467b48Spatrick #include "llvm/Support/Debug.h"
2509467b48Spatrick #include "llvm/Support/KnownBits.h"
2609467b48Spatrick 
2773471bf0Spatrick #include <set>
2873471bf0Spatrick 
2909467b48Spatrick using namespace llvm;
3009467b48Spatrick using namespace llvm::PatternMatch;
3109467b48Spatrick 
3209467b48Spatrick #define DEBUG_TYPE "iv-descriptors"
3309467b48Spatrick 
areAllUsesIn(Instruction * I,SmallPtrSetImpl<Instruction * > & Set)3409467b48Spatrick bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
3509467b48Spatrick                                         SmallPtrSetImpl<Instruction *> &Set) {
36*d415bd75Srobert   for (const Use &Use : I->operands())
37*d415bd75Srobert     if (!Set.count(dyn_cast<Instruction>(Use)))
3809467b48Spatrick       return false;
3909467b48Spatrick   return true;
4009467b48Spatrick }
4109467b48Spatrick 
isIntegerRecurrenceKind(RecurKind Kind)4273471bf0Spatrick bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurKind Kind) {
4309467b48Spatrick   switch (Kind) {
4409467b48Spatrick   default:
4509467b48Spatrick     break;
4673471bf0Spatrick   case RecurKind::Add:
4773471bf0Spatrick   case RecurKind::Mul:
4873471bf0Spatrick   case RecurKind::Or:
4973471bf0Spatrick   case RecurKind::And:
5073471bf0Spatrick   case RecurKind::Xor:
5173471bf0Spatrick   case RecurKind::SMax:
5273471bf0Spatrick   case RecurKind::SMin:
5373471bf0Spatrick   case RecurKind::UMax:
5473471bf0Spatrick   case RecurKind::UMin:
55*d415bd75Srobert   case RecurKind::SelectICmp:
56*d415bd75Srobert   case RecurKind::SelectFCmp:
5709467b48Spatrick     return true;
5809467b48Spatrick   }
5909467b48Spatrick   return false;
6009467b48Spatrick }
6109467b48Spatrick 
isFloatingPointRecurrenceKind(RecurKind Kind)6273471bf0Spatrick bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurKind Kind) {
6373471bf0Spatrick   return (Kind != RecurKind::None) && !isIntegerRecurrenceKind(Kind);
6409467b48Spatrick }
6509467b48Spatrick 
6609467b48Spatrick /// Determines if Phi may have been type-promoted. If Phi has a single user
6709467b48Spatrick /// that ANDs the Phi with a type mask, return the user. RT is updated to
6809467b48Spatrick /// account for the narrower bit width represented by the mask, and the AND
6909467b48Spatrick /// instruction is added to CI.
lookThroughAnd(PHINode * Phi,Type * & RT,SmallPtrSetImpl<Instruction * > & Visited,SmallPtrSetImpl<Instruction * > & CI)7009467b48Spatrick static Instruction *lookThroughAnd(PHINode *Phi, Type *&RT,
7109467b48Spatrick                                    SmallPtrSetImpl<Instruction *> &Visited,
7209467b48Spatrick                                    SmallPtrSetImpl<Instruction *> &CI) {
7309467b48Spatrick   if (!Phi->hasOneUse())
7409467b48Spatrick     return Phi;
7509467b48Spatrick 
7609467b48Spatrick   const APInt *M = nullptr;
7709467b48Spatrick   Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
7809467b48Spatrick 
7909467b48Spatrick   // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
8009467b48Spatrick   // with a new integer type of the corresponding bit width.
8109467b48Spatrick   if (match(J, m_c_And(m_Instruction(I), m_APInt(M)))) {
8209467b48Spatrick     int32_t Bits = (*M + 1).exactLogBase2();
8309467b48Spatrick     if (Bits > 0) {
8409467b48Spatrick       RT = IntegerType::get(Phi->getContext(), Bits);
8509467b48Spatrick       Visited.insert(Phi);
8609467b48Spatrick       CI.insert(J);
8709467b48Spatrick       return J;
8809467b48Spatrick     }
8909467b48Spatrick   }
9009467b48Spatrick   return Phi;
9109467b48Spatrick }
9209467b48Spatrick 
9309467b48Spatrick /// Compute the minimal bit width needed to represent a reduction whose exit
9409467b48Spatrick /// instruction is given by Exit.
computeRecurrenceType(Instruction * Exit,DemandedBits * DB,AssumptionCache * AC,DominatorTree * DT)9509467b48Spatrick static std::pair<Type *, bool> computeRecurrenceType(Instruction *Exit,
9609467b48Spatrick                                                      DemandedBits *DB,
9709467b48Spatrick                                                      AssumptionCache *AC,
9809467b48Spatrick                                                      DominatorTree *DT) {
9909467b48Spatrick   bool IsSigned = false;
10009467b48Spatrick   const DataLayout &DL = Exit->getModule()->getDataLayout();
10109467b48Spatrick   uint64_t MaxBitWidth = DL.getTypeSizeInBits(Exit->getType());
10209467b48Spatrick 
10309467b48Spatrick   if (DB) {
10409467b48Spatrick     // Use the demanded bits analysis to determine the bits that are live out
10509467b48Spatrick     // of the exit instruction, rounding up to the nearest power of two. If the
10609467b48Spatrick     // use of demanded bits results in a smaller bit width, we know the value
10709467b48Spatrick     // must be positive (i.e., IsSigned = false), because if this were not the
10809467b48Spatrick     // case, the sign bit would have been demanded.
10909467b48Spatrick     auto Mask = DB->getDemandedBits(Exit);
11009467b48Spatrick     MaxBitWidth = Mask.getBitWidth() - Mask.countLeadingZeros();
11109467b48Spatrick   }
11209467b48Spatrick 
11309467b48Spatrick   if (MaxBitWidth == DL.getTypeSizeInBits(Exit->getType()) && AC && DT) {
11409467b48Spatrick     // If demanded bits wasn't able to limit the bit width, we can try to use
11509467b48Spatrick     // value tracking instead. This can be the case, for example, if the value
11609467b48Spatrick     // may be negative.
11709467b48Spatrick     auto NumSignBits = ComputeNumSignBits(Exit, DL, 0, AC, nullptr, DT);
11809467b48Spatrick     auto NumTypeBits = DL.getTypeSizeInBits(Exit->getType());
11909467b48Spatrick     MaxBitWidth = NumTypeBits - NumSignBits;
12009467b48Spatrick     KnownBits Bits = computeKnownBits(Exit, DL);
12109467b48Spatrick     if (!Bits.isNonNegative()) {
12209467b48Spatrick       // If the value is not known to be non-negative, we set IsSigned to true,
12309467b48Spatrick       // meaning that we will use sext instructions instead of zext
12409467b48Spatrick       // instructions to restore the original type.
12509467b48Spatrick       IsSigned = true;
126*d415bd75Srobert       // Make sure at at least one sign bit is included in the result, so it
127*d415bd75Srobert       // will get properly sign-extended.
12809467b48Spatrick       ++MaxBitWidth;
12909467b48Spatrick     }
13009467b48Spatrick   }
13109467b48Spatrick   if (!isPowerOf2_64(MaxBitWidth))
13209467b48Spatrick     MaxBitWidth = NextPowerOf2(MaxBitWidth);
13309467b48Spatrick 
13409467b48Spatrick   return std::make_pair(Type::getIntNTy(Exit->getContext(), MaxBitWidth),
13509467b48Spatrick                         IsSigned);
13609467b48Spatrick }
13709467b48Spatrick 
13809467b48Spatrick /// Collect cast instructions that can be ignored in the vectorizer's cost
13909467b48Spatrick /// model, given a reduction exit value and the minimal type in which the
140*d415bd75Srobert // reduction can be represented. Also search casts to the recurrence type
141*d415bd75Srobert // to find the minimum width used by the recurrence.
collectCastInstrs(Loop * TheLoop,Instruction * Exit,Type * RecurrenceType,SmallPtrSetImpl<Instruction * > & Casts,unsigned & MinWidthCastToRecurTy)142*d415bd75Srobert static void collectCastInstrs(Loop *TheLoop, Instruction *Exit,
14309467b48Spatrick                               Type *RecurrenceType,
144*d415bd75Srobert                               SmallPtrSetImpl<Instruction *> &Casts,
145*d415bd75Srobert                               unsigned &MinWidthCastToRecurTy) {
14609467b48Spatrick 
14709467b48Spatrick   SmallVector<Instruction *, 8> Worklist;
14809467b48Spatrick   SmallPtrSet<Instruction *, 8> Visited;
14909467b48Spatrick   Worklist.push_back(Exit);
150*d415bd75Srobert   MinWidthCastToRecurTy = -1U;
15109467b48Spatrick 
15209467b48Spatrick   while (!Worklist.empty()) {
15309467b48Spatrick     Instruction *Val = Worklist.pop_back_val();
15409467b48Spatrick     Visited.insert(Val);
155*d415bd75Srobert     if (auto *Cast = dyn_cast<CastInst>(Val)) {
15609467b48Spatrick       if (Cast->getSrcTy() == RecurrenceType) {
15709467b48Spatrick         // If the source type of a cast instruction is equal to the recurrence
15809467b48Spatrick         // type, it will be eliminated, and should be ignored in the vectorizer
15909467b48Spatrick         // cost model.
16009467b48Spatrick         Casts.insert(Cast);
16109467b48Spatrick         continue;
16209467b48Spatrick       }
163*d415bd75Srobert       if (Cast->getDestTy() == RecurrenceType) {
164*d415bd75Srobert         // The minimum width used by the recurrence is found by checking for
165*d415bd75Srobert         // casts on its operands. The minimum width is used by the vectorizer
166*d415bd75Srobert         // when finding the widest type for in-loop reductions without any
167*d415bd75Srobert         // loads/stores.
168*d415bd75Srobert         MinWidthCastToRecurTy = std::min<unsigned>(
169*d415bd75Srobert             MinWidthCastToRecurTy, Cast->getSrcTy()->getScalarSizeInBits());
170*d415bd75Srobert         continue;
171*d415bd75Srobert       }
172*d415bd75Srobert     }
17309467b48Spatrick     // Add all operands to the work list if they are loop-varying values that
17409467b48Spatrick     // we haven't yet visited.
17509467b48Spatrick     for (Value *O : cast<User>(Val)->operands())
17609467b48Spatrick       if (auto *I = dyn_cast<Instruction>(O))
17709467b48Spatrick         if (TheLoop->contains(I) && !Visited.count(I))
17809467b48Spatrick           Worklist.push_back(I);
17909467b48Spatrick   }
18009467b48Spatrick }
18109467b48Spatrick 
18273471bf0Spatrick // Check if a given Phi node can be recognized as an ordered reduction for
18373471bf0Spatrick // vectorizing floating point operations without unsafe math.
checkOrderedReduction(RecurKind Kind,Instruction * ExactFPMathInst,Instruction * Exit,PHINode * Phi)18473471bf0Spatrick static bool checkOrderedReduction(RecurKind Kind, Instruction *ExactFPMathInst,
18573471bf0Spatrick                                   Instruction *Exit, PHINode *Phi) {
186*d415bd75Srobert   // Currently only FAdd and FMulAdd are supported.
187*d415bd75Srobert   if (Kind != RecurKind::FAdd && Kind != RecurKind::FMulAdd)
18873471bf0Spatrick     return false;
18973471bf0Spatrick 
190*d415bd75Srobert   if (Kind == RecurKind::FAdd && Exit->getOpcode() != Instruction::FAdd)
191*d415bd75Srobert     return false;
192*d415bd75Srobert 
193*d415bd75Srobert   if (Kind == RecurKind::FMulAdd &&
194*d415bd75Srobert       !RecurrenceDescriptor::isFMulAddIntrinsic(Exit))
195*d415bd75Srobert     return false;
196*d415bd75Srobert 
197*d415bd75Srobert   // Ensure the exit instruction has only one user other than the reduction PHI
198*d415bd75Srobert   if (Exit != ExactFPMathInst || Exit->hasNUsesOrMore(3))
19973471bf0Spatrick     return false;
20073471bf0Spatrick 
20173471bf0Spatrick   // The only pattern accepted is the one in which the reduction PHI
20273471bf0Spatrick   // is used as one of the operands of the exit instruction
203*d415bd75Srobert   auto *Op0 = Exit->getOperand(0);
204*d415bd75Srobert   auto *Op1 = Exit->getOperand(1);
205*d415bd75Srobert   if (Kind == RecurKind::FAdd && Op0 != Phi && Op1 != Phi)
206*d415bd75Srobert     return false;
207*d415bd75Srobert   if (Kind == RecurKind::FMulAdd && Exit->getOperand(2) != Phi)
20873471bf0Spatrick     return false;
20973471bf0Spatrick 
21073471bf0Spatrick   LLVM_DEBUG(dbgs() << "LV: Found an ordered reduction: Phi: " << *Phi
21173471bf0Spatrick                     << ", ExitInst: " << *Exit << "\n");
21273471bf0Spatrick 
21373471bf0Spatrick   return true;
21473471bf0Spatrick }
21573471bf0Spatrick 
AddReductionVar(PHINode * Phi,RecurKind Kind,Loop * TheLoop,FastMathFlags FuncFMF,RecurrenceDescriptor & RedDes,DemandedBits * DB,AssumptionCache * AC,DominatorTree * DT,ScalarEvolution * SE)216*d415bd75Srobert bool RecurrenceDescriptor::AddReductionVar(
217*d415bd75Srobert     PHINode *Phi, RecurKind Kind, Loop *TheLoop, FastMathFlags FuncFMF,
218*d415bd75Srobert     RecurrenceDescriptor &RedDes, DemandedBits *DB, AssumptionCache *AC,
219*d415bd75Srobert     DominatorTree *DT, ScalarEvolution *SE) {
22009467b48Spatrick   if (Phi->getNumIncomingValues() != 2)
22109467b48Spatrick     return false;
22209467b48Spatrick 
22309467b48Spatrick   // Reduction variables are only found in the loop header block.
22409467b48Spatrick   if (Phi->getParent() != TheLoop->getHeader())
22509467b48Spatrick     return false;
22609467b48Spatrick 
22709467b48Spatrick   // Obtain the reduction start value from the value that comes from the loop
22809467b48Spatrick   // preheader.
22909467b48Spatrick   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
23009467b48Spatrick 
23109467b48Spatrick   // ExitInstruction is the single value which is used outside the loop.
23209467b48Spatrick   // We only allow for a single reduction value to be used outside the loop.
23309467b48Spatrick   // This includes users of the reduction, variables (which form a cycle
23409467b48Spatrick   // which ends in the phi node).
23509467b48Spatrick   Instruction *ExitInstruction = nullptr;
236*d415bd75Srobert 
237*d415bd75Srobert   // Variable to keep last visited store instruction. By the end of the
238*d415bd75Srobert   // algorithm this variable will be either empty or having intermediate
239*d415bd75Srobert   // reduction value stored in invariant address.
240*d415bd75Srobert   StoreInst *IntermediateStore = nullptr;
241*d415bd75Srobert 
24209467b48Spatrick   // Indicates that we found a reduction operation in our scan.
24309467b48Spatrick   bool FoundReduxOp = false;
24409467b48Spatrick 
24509467b48Spatrick   // We start with the PHI node and scan for all of the users of this
24609467b48Spatrick   // instruction. All users must be instructions that can be used as reduction
24709467b48Spatrick   // variables (such as ADD). We must have a single out-of-block user. The cycle
24809467b48Spatrick   // must include the original PHI.
24909467b48Spatrick   bool FoundStartPHI = false;
25009467b48Spatrick 
25109467b48Spatrick   // To recognize min/max patterns formed by a icmp select sequence, we store
25209467b48Spatrick   // the number of instruction we saw from the recognized min/max pattern,
25309467b48Spatrick   //  to make sure we only see exactly the two instructions.
25409467b48Spatrick   unsigned NumCmpSelectPatternInst = 0;
25509467b48Spatrick   InstDesc ReduxDesc(false, nullptr);
25609467b48Spatrick 
25709467b48Spatrick   // Data used for determining if the recurrence has been type-promoted.
25809467b48Spatrick   Type *RecurrenceType = Phi->getType();
25909467b48Spatrick   SmallPtrSet<Instruction *, 4> CastInsts;
260*d415bd75Srobert   unsigned MinWidthCastToRecurrenceType;
26109467b48Spatrick   Instruction *Start = Phi;
26209467b48Spatrick   bool IsSigned = false;
26309467b48Spatrick 
26409467b48Spatrick   SmallPtrSet<Instruction *, 8> VisitedInsts;
26509467b48Spatrick   SmallVector<Instruction *, 8> Worklist;
26609467b48Spatrick 
26709467b48Spatrick   // Return early if the recurrence kind does not match the type of Phi. If the
26809467b48Spatrick   // recurrence kind is arithmetic, we attempt to look through AND operations
26909467b48Spatrick   // resulting from the type promotion performed by InstCombine.  Vector
27009467b48Spatrick   // operations are not limited to the legal integer widths, so we may be able
27109467b48Spatrick   // to evaluate the reduction in the narrower width.
27209467b48Spatrick   if (RecurrenceType->isFloatingPointTy()) {
27309467b48Spatrick     if (!isFloatingPointRecurrenceKind(Kind))
27409467b48Spatrick       return false;
27573471bf0Spatrick   } else if (RecurrenceType->isIntegerTy()) {
27609467b48Spatrick     if (!isIntegerRecurrenceKind(Kind))
27709467b48Spatrick       return false;
278*d415bd75Srobert     if (!isMinMaxRecurrenceKind(Kind))
27909467b48Spatrick       Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
28073471bf0Spatrick   } else {
28173471bf0Spatrick     // Pointer min/max may exist, but it is not supported as a reduction op.
28273471bf0Spatrick     return false;
28309467b48Spatrick   }
28409467b48Spatrick 
28509467b48Spatrick   Worklist.push_back(Start);
28609467b48Spatrick   VisitedInsts.insert(Start);
28709467b48Spatrick 
28809467b48Spatrick   // Start with all flags set because we will intersect this with the reduction
28909467b48Spatrick   // flags from all the reduction operations.
29009467b48Spatrick   FastMathFlags FMF = FastMathFlags::getFast();
29109467b48Spatrick 
292*d415bd75Srobert   // The first instruction in the use-def chain of the Phi node that requires
293*d415bd75Srobert   // exact floating point operations.
294*d415bd75Srobert   Instruction *ExactFPMathInst = nullptr;
295*d415bd75Srobert 
29609467b48Spatrick   // A value in the reduction can be used:
29709467b48Spatrick   //  - By the reduction:
29809467b48Spatrick   //      - Reduction operation:
29909467b48Spatrick   //        - One use of reduction value (safe).
30009467b48Spatrick   //        - Multiple use of reduction value (not safe).
30109467b48Spatrick   //      - PHI:
30209467b48Spatrick   //        - All uses of the PHI must be the reduction (safe).
30309467b48Spatrick   //        - Otherwise, not safe.
30409467b48Spatrick   //  - By instructions outside of the loop (safe).
30509467b48Spatrick   //      * One value may have several outside users, but all outside
30609467b48Spatrick   //        uses must be of the same value.
307*d415bd75Srobert   //  - By store instructions with a loop invariant address (safe with
308*d415bd75Srobert   //    the following restrictions):
309*d415bd75Srobert   //      * If there are several stores, all must have the same address.
310*d415bd75Srobert   //      * Final value should be stored in that loop invariant address.
31109467b48Spatrick   //  - By an instruction that is not part of the reduction (not safe).
31209467b48Spatrick   //    This is either:
31309467b48Spatrick   //      * An instruction type other than PHI or the reduction operation.
31409467b48Spatrick   //      * A PHI in the header other than the initial PHI.
31509467b48Spatrick   while (!Worklist.empty()) {
31673471bf0Spatrick     Instruction *Cur = Worklist.pop_back_val();
31709467b48Spatrick 
318*d415bd75Srobert     // Store instructions are allowed iff it is the store of the reduction
319*d415bd75Srobert     // value to the same loop invariant memory location.
320*d415bd75Srobert     if (auto *SI = dyn_cast<StoreInst>(Cur)) {
321*d415bd75Srobert       if (!SE) {
322*d415bd75Srobert         LLVM_DEBUG(dbgs() << "Store instructions are not processed without "
323*d415bd75Srobert                           << "Scalar Evolution Analysis\n");
324*d415bd75Srobert         return false;
325*d415bd75Srobert       }
326*d415bd75Srobert 
327*d415bd75Srobert       const SCEV *PtrScev = SE->getSCEV(SI->getPointerOperand());
328*d415bd75Srobert       // Check it is the same address as previous stores
329*d415bd75Srobert       if (IntermediateStore) {
330*d415bd75Srobert         const SCEV *OtherScev =
331*d415bd75Srobert             SE->getSCEV(IntermediateStore->getPointerOperand());
332*d415bd75Srobert 
333*d415bd75Srobert         if (OtherScev != PtrScev) {
334*d415bd75Srobert           LLVM_DEBUG(dbgs() << "Storing reduction value to different addresses "
335*d415bd75Srobert                             << "inside the loop: " << *SI->getPointerOperand()
336*d415bd75Srobert                             << " and "
337*d415bd75Srobert                             << *IntermediateStore->getPointerOperand() << '\n');
338*d415bd75Srobert           return false;
339*d415bd75Srobert         }
340*d415bd75Srobert       }
341*d415bd75Srobert 
342*d415bd75Srobert       // Check the pointer is loop invariant
343*d415bd75Srobert       if (!SE->isLoopInvariant(PtrScev, TheLoop)) {
344*d415bd75Srobert         LLVM_DEBUG(dbgs() << "Storing reduction value to non-uniform address "
345*d415bd75Srobert                           << "inside the loop: " << *SI->getPointerOperand()
346*d415bd75Srobert                           << '\n');
347*d415bd75Srobert         return false;
348*d415bd75Srobert       }
349*d415bd75Srobert 
350*d415bd75Srobert       // IntermediateStore is always the last store in the loop.
351*d415bd75Srobert       IntermediateStore = SI;
352*d415bd75Srobert       continue;
353*d415bd75Srobert     }
354*d415bd75Srobert 
35509467b48Spatrick     // No Users.
35609467b48Spatrick     // If the instruction has no users then this is a broken chain and can't be
35709467b48Spatrick     // a reduction variable.
35809467b48Spatrick     if (Cur->use_empty())
35909467b48Spatrick       return false;
36009467b48Spatrick 
36109467b48Spatrick     bool IsAPhi = isa<PHINode>(Cur);
36209467b48Spatrick 
36309467b48Spatrick     // A header PHI use other than the original PHI.
36409467b48Spatrick     if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
36509467b48Spatrick       return false;
36609467b48Spatrick 
36709467b48Spatrick     // Reductions of instructions such as Div, and Sub is only possible if the
36809467b48Spatrick     // LHS is the reduction variable.
36909467b48Spatrick     if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
37009467b48Spatrick         !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
37109467b48Spatrick         !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
37209467b48Spatrick       return false;
37309467b48Spatrick 
37409467b48Spatrick     // Any reduction instruction must be of one of the allowed kinds. We ignore
37509467b48Spatrick     // the starting value (the Phi or an AND instruction if the Phi has been
37609467b48Spatrick     // type-promoted).
37709467b48Spatrick     if (Cur != Start) {
378*d415bd75Srobert       ReduxDesc =
379*d415bd75Srobert           isRecurrenceInstr(TheLoop, Phi, Cur, Kind, ReduxDesc, FuncFMF);
380*d415bd75Srobert       ExactFPMathInst = ExactFPMathInst == nullptr
381*d415bd75Srobert                             ? ReduxDesc.getExactFPMathInst()
382*d415bd75Srobert                             : ExactFPMathInst;
38309467b48Spatrick       if (!ReduxDesc.isRecurrence())
38409467b48Spatrick         return false;
38509467b48Spatrick       // FIXME: FMF is allowed on phi, but propagation is not handled correctly.
38673471bf0Spatrick       if (isa<FPMathOperator>(ReduxDesc.getPatternInst()) && !IsAPhi) {
38773471bf0Spatrick         FastMathFlags CurFMF = ReduxDesc.getPatternInst()->getFastMathFlags();
38873471bf0Spatrick         if (auto *Sel = dyn_cast<SelectInst>(ReduxDesc.getPatternInst())) {
38973471bf0Spatrick           // Accept FMF on either fcmp or select of a min/max idiom.
39073471bf0Spatrick           // TODO: This is a hack to work-around the fact that FMF may not be
39173471bf0Spatrick           //       assigned/propagated correctly. If that problem is fixed or we
39273471bf0Spatrick           //       standardize on fmin/fmax via intrinsics, this can be removed.
39373471bf0Spatrick           if (auto *FCmp = dyn_cast<FCmpInst>(Sel->getCondition()))
39473471bf0Spatrick             CurFMF |= FCmp->getFastMathFlags();
39573471bf0Spatrick         }
39673471bf0Spatrick         FMF &= CurFMF;
39773471bf0Spatrick       }
39873471bf0Spatrick       // Update this reduction kind if we matched a new instruction.
39973471bf0Spatrick       // TODO: Can we eliminate the need for a 2nd InstDesc by keeping 'Kind'
40073471bf0Spatrick       //       state accurate while processing the worklist?
40173471bf0Spatrick       if (ReduxDesc.getRecKind() != RecurKind::None)
40273471bf0Spatrick         Kind = ReduxDesc.getRecKind();
40309467b48Spatrick     }
40409467b48Spatrick 
40509467b48Spatrick     bool IsASelect = isa<SelectInst>(Cur);
40609467b48Spatrick 
40709467b48Spatrick     // A conditional reduction operation must only have 2 or less uses in
40809467b48Spatrick     // VisitedInsts.
40973471bf0Spatrick     if (IsASelect && (Kind == RecurKind::FAdd || Kind == RecurKind::FMul) &&
41009467b48Spatrick         hasMultipleUsesOf(Cur, VisitedInsts, 2))
41109467b48Spatrick       return false;
41209467b48Spatrick 
41309467b48Spatrick     // A reduction operation must only have one use of the reduction value.
41473471bf0Spatrick     if (!IsAPhi && !IsASelect && !isMinMaxRecurrenceKind(Kind) &&
415*d415bd75Srobert         !isSelectCmpRecurrenceKind(Kind) &&
41673471bf0Spatrick         hasMultipleUsesOf(Cur, VisitedInsts, 1))
41709467b48Spatrick       return false;
41809467b48Spatrick 
41909467b48Spatrick     // All inputs to a PHI node must be a reduction value.
42009467b48Spatrick     if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
42109467b48Spatrick       return false;
42209467b48Spatrick 
423*d415bd75Srobert     if ((isIntMinMaxRecurrenceKind(Kind) || Kind == RecurKind::SelectICmp) &&
42409467b48Spatrick         (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
42509467b48Spatrick       ++NumCmpSelectPatternInst;
426*d415bd75Srobert     if ((isFPMinMaxRecurrenceKind(Kind) || Kind == RecurKind::SelectFCmp) &&
42773471bf0Spatrick         (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
42809467b48Spatrick       ++NumCmpSelectPatternInst;
42909467b48Spatrick 
43009467b48Spatrick     // Check  whether we found a reduction operator.
43109467b48Spatrick     FoundReduxOp |= !IsAPhi && Cur != Start;
43209467b48Spatrick 
43309467b48Spatrick     // Process users of current instruction. Push non-PHI nodes after PHI nodes
43409467b48Spatrick     // onto the stack. This way we are going to have seen all inputs to PHI
43509467b48Spatrick     // nodes once we get to them.
43609467b48Spatrick     SmallVector<Instruction *, 8> NonPHIs;
43709467b48Spatrick     SmallVector<Instruction *, 8> PHIs;
43809467b48Spatrick     for (User *U : Cur->users()) {
43909467b48Spatrick       Instruction *UI = cast<Instruction>(U);
44009467b48Spatrick 
441*d415bd75Srobert       // If the user is a call to llvm.fmuladd then the instruction can only be
442*d415bd75Srobert       // the final operand.
443*d415bd75Srobert       if (isFMulAddIntrinsic(UI))
444*d415bd75Srobert         if (Cur == UI->getOperand(0) || Cur == UI->getOperand(1))
445*d415bd75Srobert           return false;
446*d415bd75Srobert 
44709467b48Spatrick       // Check if we found the exit user.
44809467b48Spatrick       BasicBlock *Parent = UI->getParent();
44909467b48Spatrick       if (!TheLoop->contains(Parent)) {
45009467b48Spatrick         // If we already know this instruction is used externally, move on to
45109467b48Spatrick         // the next user.
45209467b48Spatrick         if (ExitInstruction == Cur)
45309467b48Spatrick           continue;
45409467b48Spatrick 
45509467b48Spatrick         // Exit if you find multiple values used outside or if the header phi
45609467b48Spatrick         // node is being used. In this case the user uses the value of the
45709467b48Spatrick         // previous iteration, in which case we would loose "VF-1" iterations of
45809467b48Spatrick         // the reduction operation if we vectorize.
45909467b48Spatrick         if (ExitInstruction != nullptr || Cur == Phi)
46009467b48Spatrick           return false;
46109467b48Spatrick 
46209467b48Spatrick         // The instruction used by an outside user must be the last instruction
46309467b48Spatrick         // before we feed back to the reduction phi. Otherwise, we loose VF-1
46409467b48Spatrick         // operations on the value.
46509467b48Spatrick         if (!is_contained(Phi->operands(), Cur))
46609467b48Spatrick           return false;
46709467b48Spatrick 
46809467b48Spatrick         ExitInstruction = Cur;
46909467b48Spatrick         continue;
47009467b48Spatrick       }
47109467b48Spatrick 
47209467b48Spatrick       // Process instructions only once (termination). Each reduction cycle
47309467b48Spatrick       // value must only be used once, except by phi nodes and min/max
47409467b48Spatrick       // reductions which are represented as a cmp followed by a select.
47509467b48Spatrick       InstDesc IgnoredVal(false, nullptr);
47609467b48Spatrick       if (VisitedInsts.insert(UI).second) {
477*d415bd75Srobert         if (isa<PHINode>(UI)) {
47809467b48Spatrick           PHIs.push_back(UI);
479*d415bd75Srobert         } else {
480*d415bd75Srobert           StoreInst *SI = dyn_cast<StoreInst>(UI);
481*d415bd75Srobert           if (SI && SI->getPointerOperand() == Cur) {
482*d415bd75Srobert             // Reduction variable chain can only be stored somewhere but it
483*d415bd75Srobert             // can't be used as an address.
484*d415bd75Srobert             return false;
485*d415bd75Srobert           }
48609467b48Spatrick           NonPHIs.push_back(UI);
487*d415bd75Srobert         }
48809467b48Spatrick       } else if (!isa<PHINode>(UI) &&
48909467b48Spatrick                  ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
49009467b48Spatrick                    !isa<SelectInst>(UI)) ||
49109467b48Spatrick                   (!isConditionalRdxPattern(Kind, UI).isRecurrence() &&
492*d415bd75Srobert                    !isSelectCmpPattern(TheLoop, Phi, UI, IgnoredVal)
493*d415bd75Srobert                         .isRecurrence() &&
494*d415bd75Srobert                    !isMinMaxPattern(UI, Kind, IgnoredVal).isRecurrence())))
49509467b48Spatrick         return false;
49609467b48Spatrick 
49709467b48Spatrick       // Remember that we completed the cycle.
49809467b48Spatrick       if (UI == Phi)
49909467b48Spatrick         FoundStartPHI = true;
50009467b48Spatrick     }
50109467b48Spatrick     Worklist.append(PHIs.begin(), PHIs.end());
50209467b48Spatrick     Worklist.append(NonPHIs.begin(), NonPHIs.end());
50309467b48Spatrick   }
50409467b48Spatrick 
50509467b48Spatrick   // This means we have seen one but not the other instruction of the
506*d415bd75Srobert   // pattern or more than just a select and cmp. Zero implies that we saw a
507*d415bd75Srobert   // llvm.min/max intrinsic, which is always OK.
508*d415bd75Srobert   if (isMinMaxRecurrenceKind(Kind) && NumCmpSelectPatternInst != 2 &&
509*d415bd75Srobert       NumCmpSelectPatternInst != 0)
51009467b48Spatrick     return false;
51109467b48Spatrick 
512*d415bd75Srobert   if (isSelectCmpRecurrenceKind(Kind) && NumCmpSelectPatternInst != 1)
513*d415bd75Srobert     return false;
514*d415bd75Srobert 
515*d415bd75Srobert   if (IntermediateStore) {
516*d415bd75Srobert     // Check that stored value goes to the phi node again. This way we make sure
517*d415bd75Srobert     // that the value stored in IntermediateStore is indeed the final reduction
518*d415bd75Srobert     // value.
519*d415bd75Srobert     if (!is_contained(Phi->operands(), IntermediateStore->getValueOperand())) {
520*d415bd75Srobert       LLVM_DEBUG(dbgs() << "Not a final reduction value stored: "
521*d415bd75Srobert                         << *IntermediateStore << '\n');
522*d415bd75Srobert       return false;
523*d415bd75Srobert     }
524*d415bd75Srobert 
525*d415bd75Srobert     // If there is an exit instruction it's value should be stored in
526*d415bd75Srobert     // IntermediateStore
527*d415bd75Srobert     if (ExitInstruction &&
528*d415bd75Srobert         IntermediateStore->getValueOperand() != ExitInstruction) {
529*d415bd75Srobert       LLVM_DEBUG(dbgs() << "Last store Instruction of reduction value does not "
530*d415bd75Srobert                            "store last calculated value of the reduction: "
531*d415bd75Srobert                         << *IntermediateStore << '\n');
532*d415bd75Srobert       return false;
533*d415bd75Srobert     }
534*d415bd75Srobert 
535*d415bd75Srobert     // If all uses are inside the loop (intermediate stores), then the
536*d415bd75Srobert     // reduction value after the loop will be the one used in the last store.
537*d415bd75Srobert     if (!ExitInstruction)
538*d415bd75Srobert       ExitInstruction = cast<Instruction>(IntermediateStore->getValueOperand());
539*d415bd75Srobert   }
540*d415bd75Srobert 
54109467b48Spatrick   if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
54209467b48Spatrick     return false;
54309467b48Spatrick 
544*d415bd75Srobert   const bool IsOrdered =
545*d415bd75Srobert       checkOrderedReduction(Kind, ExactFPMathInst, ExitInstruction, Phi);
54673471bf0Spatrick 
54709467b48Spatrick   if (Start != Phi) {
54809467b48Spatrick     // If the starting value is not the same as the phi node, we speculatively
54909467b48Spatrick     // looked through an 'and' instruction when evaluating a potential
55009467b48Spatrick     // arithmetic reduction to determine if it may have been type-promoted.
55109467b48Spatrick     //
55209467b48Spatrick     // We now compute the minimal bit width that is required to represent the
55309467b48Spatrick     // reduction. If this is the same width that was indicated by the 'and', we
55409467b48Spatrick     // can represent the reduction in the smaller type. The 'and' instruction
55509467b48Spatrick     // will be eliminated since it will essentially be a cast instruction that
55609467b48Spatrick     // can be ignore in the cost model. If we compute a different type than we
55709467b48Spatrick     // did when evaluating the 'and', the 'and' will not be eliminated, and we
55809467b48Spatrick     // will end up with different kinds of operations in the recurrence
55973471bf0Spatrick     // expression (e.g., IntegerAND, IntegerADD). We give up if this is
56009467b48Spatrick     // the case.
56109467b48Spatrick     //
56209467b48Spatrick     // The vectorizer relies on InstCombine to perform the actual
56309467b48Spatrick     // type-shrinking. It does this by inserting instructions to truncate the
56409467b48Spatrick     // exit value of the reduction to the width indicated by RecurrenceType and
56509467b48Spatrick     // then extend this value back to the original width. If IsSigned is false,
56609467b48Spatrick     // a 'zext' instruction will be generated; otherwise, a 'sext' will be
56709467b48Spatrick     // used.
56809467b48Spatrick     //
56909467b48Spatrick     // TODO: We should not rely on InstCombine to rewrite the reduction in the
57009467b48Spatrick     //       smaller type. We should just generate a correctly typed expression
57109467b48Spatrick     //       to begin with.
57209467b48Spatrick     Type *ComputedType;
57309467b48Spatrick     std::tie(ComputedType, IsSigned) =
57409467b48Spatrick         computeRecurrenceType(ExitInstruction, DB, AC, DT);
57509467b48Spatrick     if (ComputedType != RecurrenceType)
57609467b48Spatrick       return false;
577*d415bd75Srobert   }
57809467b48Spatrick 
579*d415bd75Srobert   // Collect cast instructions and the minimum width used by the recurrence.
580*d415bd75Srobert   // If the starting value is not the same as the phi node and the computed
581*d415bd75Srobert   // recurrence type is equal to the recurrence type, the recurrence expression
582*d415bd75Srobert   // will be represented in a narrower or wider type. If there are any cast
583*d415bd75Srobert   // instructions that will be unnecessary, collect them in CastsFromRecurTy.
584*d415bd75Srobert   // Note that the 'and' instruction was already included in this list.
58509467b48Spatrick   //
58609467b48Spatrick   // TODO: A better way to represent this may be to tag in some way all the
58709467b48Spatrick   //       instructions that are a part of the reduction. The vectorizer cost
58809467b48Spatrick   //       model could then apply the recurrence type to these instructions,
58909467b48Spatrick   //       without needing a white list of instructions to ignore.
59073471bf0Spatrick   //       This may also be useful for the inloop reductions, if it can be
59173471bf0Spatrick   //       kept simple enough.
592*d415bd75Srobert   collectCastInstrs(TheLoop, ExitInstruction, RecurrenceType, CastInsts,
593*d415bd75Srobert                     MinWidthCastToRecurrenceType);
59409467b48Spatrick 
59509467b48Spatrick   // We found a reduction var if we have reached the original phi node and we
59609467b48Spatrick   // only have a single instruction with out-of-loop users.
59709467b48Spatrick 
59809467b48Spatrick   // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
59909467b48Spatrick   // is saved as part of the RecurrenceDescriptor.
60009467b48Spatrick 
60109467b48Spatrick   // Save the description of this reduction variable.
602*d415bd75Srobert   RecurrenceDescriptor RD(RdxStart, ExitInstruction, IntermediateStore, Kind,
603*d415bd75Srobert                           FMF, ExactFPMathInst, RecurrenceType, IsSigned,
604*d415bd75Srobert                           IsOrdered, CastInsts, MinWidthCastToRecurrenceType);
60509467b48Spatrick   RedDes = RD;
60609467b48Spatrick 
60709467b48Spatrick   return true;
60809467b48Spatrick }
60909467b48Spatrick 
610*d415bd75Srobert // We are looking for loops that do something like this:
611*d415bd75Srobert //   int r = 0;
612*d415bd75Srobert //   for (int i = 0; i < n; i++) {
613*d415bd75Srobert //     if (src[i] > 3)
614*d415bd75Srobert //       r = 3;
615*d415bd75Srobert //   }
616*d415bd75Srobert // where the reduction value (r) only has two states, in this example 0 or 3.
617*d415bd75Srobert // The generated LLVM IR for this type of loop will be like this:
618*d415bd75Srobert //   for.body:
619*d415bd75Srobert //     %r = phi i32 [ %spec.select, %for.body ], [ 0, %entry ]
620*d415bd75Srobert //     ...
621*d415bd75Srobert //     %cmp = icmp sgt i32 %5, 3
622*d415bd75Srobert //     %spec.select = select i1 %cmp, i32 3, i32 %r
623*d415bd75Srobert //     ...
624*d415bd75Srobert // In general we can support vectorization of loops where 'r' flips between
625*d415bd75Srobert // any two non-constants, provided they are loop invariant. The only thing
626*d415bd75Srobert // we actually care about at the end of the loop is whether or not any lane
627*d415bd75Srobert // in the selected vector is different from the start value. The final
628*d415bd75Srobert // across-vector reduction after the loop simply involves choosing the start
629*d415bd75Srobert // value if nothing changed (0 in the example above) or the other selected
630*d415bd75Srobert // value (3 in the example above).
63109467b48Spatrick RecurrenceDescriptor::InstDesc
isSelectCmpPattern(Loop * Loop,PHINode * OrigPhi,Instruction * I,InstDesc & Prev)632*d415bd75Srobert RecurrenceDescriptor::isSelectCmpPattern(Loop *Loop, PHINode *OrigPhi,
633*d415bd75Srobert                                          Instruction *I, InstDesc &Prev) {
634*d415bd75Srobert   // We must handle the select(cmp(),x,y) as a single instruction. Advance to
635*d415bd75Srobert   // the select.
63673471bf0Spatrick   CmpInst::Predicate Pred;
63773471bf0Spatrick   if (match(I, m_OneUse(m_Cmp(Pred, m_Value(), m_Value())))) {
63873471bf0Spatrick     if (auto *Select = dyn_cast<SelectInst>(*I->user_begin()))
63973471bf0Spatrick       return InstDesc(Select, Prev.getRecKind());
64009467b48Spatrick   }
64109467b48Spatrick 
64273471bf0Spatrick   // Only match select with single use cmp condition.
64373471bf0Spatrick   if (!match(I, m_Select(m_OneUse(m_Cmp(Pred, m_Value(), m_Value())), m_Value(),
64473471bf0Spatrick                          m_Value())))
64509467b48Spatrick     return InstDesc(false, I);
64609467b48Spatrick 
647*d415bd75Srobert   SelectInst *SI = cast<SelectInst>(I);
648*d415bd75Srobert   Value *NonPhi = nullptr;
649*d415bd75Srobert 
650*d415bd75Srobert   if (OrigPhi == dyn_cast<PHINode>(SI->getTrueValue()))
651*d415bd75Srobert     NonPhi = SI->getFalseValue();
652*d415bd75Srobert   else if (OrigPhi == dyn_cast<PHINode>(SI->getFalseValue()))
653*d415bd75Srobert     NonPhi = SI->getTrueValue();
654*d415bd75Srobert   else
655*d415bd75Srobert     return InstDesc(false, I);
656*d415bd75Srobert 
657*d415bd75Srobert   // We are looking for selects of the form:
658*d415bd75Srobert   //   select(cmp(), phi, loop_invariant) or
659*d415bd75Srobert   //   select(cmp(), loop_invariant, phi)
660*d415bd75Srobert   if (!Loop->isLoopInvariant(NonPhi))
661*d415bd75Srobert     return InstDesc(false, I);
662*d415bd75Srobert 
663*d415bd75Srobert   return InstDesc(I, isa<ICmpInst>(I->getOperand(0)) ? RecurKind::SelectICmp
664*d415bd75Srobert                                                      : RecurKind::SelectFCmp);
665*d415bd75Srobert }
666*d415bd75Srobert 
667*d415bd75Srobert RecurrenceDescriptor::InstDesc
isMinMaxPattern(Instruction * I,RecurKind Kind,const InstDesc & Prev)668*d415bd75Srobert RecurrenceDescriptor::isMinMaxPattern(Instruction *I, RecurKind Kind,
669*d415bd75Srobert                                       const InstDesc &Prev) {
670*d415bd75Srobert   assert((isa<CmpInst>(I) || isa<SelectInst>(I) || isa<CallInst>(I)) &&
671*d415bd75Srobert          "Expected a cmp or select or call instruction");
672*d415bd75Srobert   if (!isMinMaxRecurrenceKind(Kind))
673*d415bd75Srobert     return InstDesc(false, I);
674*d415bd75Srobert 
675*d415bd75Srobert   // We must handle the select(cmp()) as a single instruction. Advance to the
676*d415bd75Srobert   // select.
677*d415bd75Srobert   CmpInst::Predicate Pred;
678*d415bd75Srobert   if (match(I, m_OneUse(m_Cmp(Pred, m_Value(), m_Value())))) {
679*d415bd75Srobert     if (auto *Select = dyn_cast<SelectInst>(*I->user_begin()))
680*d415bd75Srobert       return InstDesc(Select, Prev.getRecKind());
681*d415bd75Srobert   }
682*d415bd75Srobert 
683*d415bd75Srobert   // Only match select with single use cmp condition, or a min/max intrinsic.
684*d415bd75Srobert   if (!isa<IntrinsicInst>(I) &&
685*d415bd75Srobert       !match(I, m_Select(m_OneUse(m_Cmp(Pred, m_Value(), m_Value())), m_Value(),
686*d415bd75Srobert                          m_Value())))
687*d415bd75Srobert     return InstDesc(false, I);
688*d415bd75Srobert 
68909467b48Spatrick   // Look for a min/max pattern.
69073471bf0Spatrick   if (match(I, m_UMin(m_Value(), m_Value())))
691*d415bd75Srobert     return InstDesc(Kind == RecurKind::UMin, I);
69273471bf0Spatrick   if (match(I, m_UMax(m_Value(), m_Value())))
693*d415bd75Srobert     return InstDesc(Kind == RecurKind::UMax, I);
69473471bf0Spatrick   if (match(I, m_SMax(m_Value(), m_Value())))
695*d415bd75Srobert     return InstDesc(Kind == RecurKind::SMax, I);
69673471bf0Spatrick   if (match(I, m_SMin(m_Value(), m_Value())))
697*d415bd75Srobert     return InstDesc(Kind == RecurKind::SMin, I);
69873471bf0Spatrick   if (match(I, m_OrdFMin(m_Value(), m_Value())))
699*d415bd75Srobert     return InstDesc(Kind == RecurKind::FMin, I);
70073471bf0Spatrick   if (match(I, m_OrdFMax(m_Value(), m_Value())))
701*d415bd75Srobert     return InstDesc(Kind == RecurKind::FMax, I);
70273471bf0Spatrick   if (match(I, m_UnordFMin(m_Value(), m_Value())))
703*d415bd75Srobert     return InstDesc(Kind == RecurKind::FMin, I);
70473471bf0Spatrick   if (match(I, m_UnordFMax(m_Value(), m_Value())))
705*d415bd75Srobert     return InstDesc(Kind == RecurKind::FMax, I);
706*d415bd75Srobert   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
707*d415bd75Srobert     return InstDesc(Kind == RecurKind::FMin, I);
708*d415bd75Srobert   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
709*d415bd75Srobert     return InstDesc(Kind == RecurKind::FMax, I);
71009467b48Spatrick 
71109467b48Spatrick   return InstDesc(false, I);
71209467b48Spatrick }
71309467b48Spatrick 
71409467b48Spatrick /// Returns true if the select instruction has users in the compare-and-add
71509467b48Spatrick /// reduction pattern below. The select instruction argument is the last one
71609467b48Spatrick /// in the sequence.
71709467b48Spatrick ///
71809467b48Spatrick /// %sum.1 = phi ...
71909467b48Spatrick /// ...
72009467b48Spatrick /// %cmp = fcmp pred %0, %CFP
72109467b48Spatrick /// %add = fadd %0, %sum.1
72209467b48Spatrick /// %sum.2 = select %cmp, %add, %sum.1
72309467b48Spatrick RecurrenceDescriptor::InstDesc
isConditionalRdxPattern(RecurKind Kind,Instruction * I)72473471bf0Spatrick RecurrenceDescriptor::isConditionalRdxPattern(RecurKind Kind, Instruction *I) {
72509467b48Spatrick   SelectInst *SI = dyn_cast<SelectInst>(I);
72609467b48Spatrick   if (!SI)
72709467b48Spatrick     return InstDesc(false, I);
72809467b48Spatrick 
72909467b48Spatrick   CmpInst *CI = dyn_cast<CmpInst>(SI->getCondition());
73009467b48Spatrick   // Only handle single use cases for now.
73109467b48Spatrick   if (!CI || !CI->hasOneUse())
73209467b48Spatrick     return InstDesc(false, I);
73309467b48Spatrick 
73409467b48Spatrick   Value *TrueVal = SI->getTrueValue();
73509467b48Spatrick   Value *FalseVal = SI->getFalseValue();
73609467b48Spatrick   // Handle only when either of operands of select instruction is a PHI
73709467b48Spatrick   // node for now.
73809467b48Spatrick   if ((isa<PHINode>(*TrueVal) && isa<PHINode>(*FalseVal)) ||
73909467b48Spatrick       (!isa<PHINode>(*TrueVal) && !isa<PHINode>(*FalseVal)))
74009467b48Spatrick     return InstDesc(false, I);
74109467b48Spatrick 
74209467b48Spatrick   Instruction *I1 =
74309467b48Spatrick       isa<PHINode>(*TrueVal) ? dyn_cast<Instruction>(FalseVal)
74409467b48Spatrick                              : dyn_cast<Instruction>(TrueVal);
74509467b48Spatrick   if (!I1 || !I1->isBinaryOp())
74609467b48Spatrick     return InstDesc(false, I);
74709467b48Spatrick 
74809467b48Spatrick   Value *Op1, *Op2;
74909467b48Spatrick   if ((m_FAdd(m_Value(Op1), m_Value(Op2)).match(I1)  ||
75009467b48Spatrick        m_FSub(m_Value(Op1), m_Value(Op2)).match(I1)) &&
75109467b48Spatrick       I1->isFast())
75273471bf0Spatrick     return InstDesc(Kind == RecurKind::FAdd, SI);
75309467b48Spatrick 
75409467b48Spatrick   if (m_FMul(m_Value(Op1), m_Value(Op2)).match(I1) && (I1->isFast()))
75573471bf0Spatrick     return InstDesc(Kind == RecurKind::FMul, SI);
75609467b48Spatrick 
75709467b48Spatrick   return InstDesc(false, I);
75809467b48Spatrick }
75909467b48Spatrick 
76009467b48Spatrick RecurrenceDescriptor::InstDesc
isRecurrenceInstr(Loop * L,PHINode * OrigPhi,Instruction * I,RecurKind Kind,InstDesc & Prev,FastMathFlags FuncFMF)761*d415bd75Srobert RecurrenceDescriptor::isRecurrenceInstr(Loop *L, PHINode *OrigPhi,
762*d415bd75Srobert                                         Instruction *I, RecurKind Kind,
763*d415bd75Srobert                                         InstDesc &Prev, FastMathFlags FuncFMF) {
764*d415bd75Srobert   assert(Prev.getRecKind() == RecurKind::None || Prev.getRecKind() == Kind);
76509467b48Spatrick   switch (I->getOpcode()) {
76609467b48Spatrick   default:
76709467b48Spatrick     return InstDesc(false, I);
76809467b48Spatrick   case Instruction::PHI:
76973471bf0Spatrick     return InstDesc(I, Prev.getRecKind(), Prev.getExactFPMathInst());
77009467b48Spatrick   case Instruction::Sub:
77109467b48Spatrick   case Instruction::Add:
77273471bf0Spatrick     return InstDesc(Kind == RecurKind::Add, I);
77309467b48Spatrick   case Instruction::Mul:
77473471bf0Spatrick     return InstDesc(Kind == RecurKind::Mul, I);
77509467b48Spatrick   case Instruction::And:
77673471bf0Spatrick     return InstDesc(Kind == RecurKind::And, I);
77709467b48Spatrick   case Instruction::Or:
77873471bf0Spatrick     return InstDesc(Kind == RecurKind::Or, I);
77909467b48Spatrick   case Instruction::Xor:
78073471bf0Spatrick     return InstDesc(Kind == RecurKind::Xor, I);
78173471bf0Spatrick   case Instruction::FDiv:
78209467b48Spatrick   case Instruction::FMul:
78373471bf0Spatrick     return InstDesc(Kind == RecurKind::FMul, I,
78473471bf0Spatrick                     I->hasAllowReassoc() ? nullptr : I);
78509467b48Spatrick   case Instruction::FSub:
78609467b48Spatrick   case Instruction::FAdd:
78773471bf0Spatrick     return InstDesc(Kind == RecurKind::FAdd, I,
78873471bf0Spatrick                     I->hasAllowReassoc() ? nullptr : I);
78909467b48Spatrick   case Instruction::Select:
79073471bf0Spatrick     if (Kind == RecurKind::FAdd || Kind == RecurKind::FMul)
79109467b48Spatrick       return isConditionalRdxPattern(Kind, I);
792*d415bd75Srobert     [[fallthrough]];
79309467b48Spatrick   case Instruction::FCmp:
79409467b48Spatrick   case Instruction::ICmp:
795*d415bd75Srobert   case Instruction::Call:
796*d415bd75Srobert     if (isSelectCmpRecurrenceKind(Kind))
797*d415bd75Srobert       return isSelectCmpPattern(L, OrigPhi, I, Prev);
79873471bf0Spatrick     if (isIntMinMaxRecurrenceKind(Kind) ||
799*d415bd75Srobert         (((FuncFMF.noNaNs() && FuncFMF.noSignedZeros()) ||
800*d415bd75Srobert           (isa<FPMathOperator>(I) && I->hasNoNaNs() &&
801*d415bd75Srobert            I->hasNoSignedZeros())) &&
802*d415bd75Srobert          isFPMinMaxRecurrenceKind(Kind)))
803*d415bd75Srobert       return isMinMaxPattern(I, Kind, Prev);
804*d415bd75Srobert     else if (isFMulAddIntrinsic(I))
805*d415bd75Srobert       return InstDesc(Kind == RecurKind::FMulAdd, I,
806*d415bd75Srobert                       I->hasAllowReassoc() ? nullptr : I);
80773471bf0Spatrick     return InstDesc(false, I);
80809467b48Spatrick   }
80909467b48Spatrick }
81009467b48Spatrick 
hasMultipleUsesOf(Instruction * I,SmallPtrSetImpl<Instruction * > & Insts,unsigned MaxNumUses)81109467b48Spatrick bool RecurrenceDescriptor::hasMultipleUsesOf(
81209467b48Spatrick     Instruction *I, SmallPtrSetImpl<Instruction *> &Insts,
81309467b48Spatrick     unsigned MaxNumUses) {
81409467b48Spatrick   unsigned NumUses = 0;
81573471bf0Spatrick   for (const Use &U : I->operands()) {
81673471bf0Spatrick     if (Insts.count(dyn_cast<Instruction>(U)))
81709467b48Spatrick       ++NumUses;
81809467b48Spatrick     if (NumUses > MaxNumUses)
81909467b48Spatrick       return true;
82009467b48Spatrick   }
82109467b48Spatrick 
82209467b48Spatrick   return false;
82309467b48Spatrick }
82473471bf0Spatrick 
isReductionPHI(PHINode * Phi,Loop * TheLoop,RecurrenceDescriptor & RedDes,DemandedBits * DB,AssumptionCache * AC,DominatorTree * DT,ScalarEvolution * SE)82509467b48Spatrick bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
82609467b48Spatrick                                           RecurrenceDescriptor &RedDes,
82709467b48Spatrick                                           DemandedBits *DB, AssumptionCache *AC,
828*d415bd75Srobert                                           DominatorTree *DT,
829*d415bd75Srobert                                           ScalarEvolution *SE) {
83009467b48Spatrick   BasicBlock *Header = TheLoop->getHeader();
83109467b48Spatrick   Function &F = *Header->getParent();
83273471bf0Spatrick   FastMathFlags FMF;
83373471bf0Spatrick   FMF.setNoNaNs(
83473471bf0Spatrick       F.getFnAttribute("no-nans-fp-math").getValueAsBool());
83573471bf0Spatrick   FMF.setNoSignedZeros(
83673471bf0Spatrick       F.getFnAttribute("no-signed-zeros-fp-math").getValueAsBool());
83709467b48Spatrick 
838*d415bd75Srobert   if (AddReductionVar(Phi, RecurKind::Add, TheLoop, FMF, RedDes, DB, AC, DT,
839*d415bd75Srobert                       SE)) {
84009467b48Spatrick     LLVM_DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
84109467b48Spatrick     return true;
84209467b48Spatrick   }
843*d415bd75Srobert   if (AddReductionVar(Phi, RecurKind::Mul, TheLoop, FMF, RedDes, DB, AC, DT,
844*d415bd75Srobert                       SE)) {
84509467b48Spatrick     LLVM_DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
84609467b48Spatrick     return true;
84709467b48Spatrick   }
848*d415bd75Srobert   if (AddReductionVar(Phi, RecurKind::Or, TheLoop, FMF, RedDes, DB, AC, DT,
849*d415bd75Srobert                       SE)) {
85009467b48Spatrick     LLVM_DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
85109467b48Spatrick     return true;
85209467b48Spatrick   }
853*d415bd75Srobert   if (AddReductionVar(Phi, RecurKind::And, TheLoop, FMF, RedDes, DB, AC, DT,
854*d415bd75Srobert                       SE)) {
85509467b48Spatrick     LLVM_DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
85609467b48Spatrick     return true;
85709467b48Spatrick   }
858*d415bd75Srobert   if (AddReductionVar(Phi, RecurKind::Xor, TheLoop, FMF, RedDes, DB, AC, DT,
859*d415bd75Srobert                       SE)) {
86009467b48Spatrick     LLVM_DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
86109467b48Spatrick     return true;
86209467b48Spatrick   }
863*d415bd75Srobert   if (AddReductionVar(Phi, RecurKind::SMax, TheLoop, FMF, RedDes, DB, AC, DT,
864*d415bd75Srobert                       SE)) {
86573471bf0Spatrick     LLVM_DEBUG(dbgs() << "Found a SMAX reduction PHI." << *Phi << "\n");
86609467b48Spatrick     return true;
86709467b48Spatrick   }
868*d415bd75Srobert   if (AddReductionVar(Phi, RecurKind::SMin, TheLoop, FMF, RedDes, DB, AC, DT,
869*d415bd75Srobert                       SE)) {
87073471bf0Spatrick     LLVM_DEBUG(dbgs() << "Found a SMIN reduction PHI." << *Phi << "\n");
87173471bf0Spatrick     return true;
87273471bf0Spatrick   }
873*d415bd75Srobert   if (AddReductionVar(Phi, RecurKind::UMax, TheLoop, FMF, RedDes, DB, AC, DT,
874*d415bd75Srobert                       SE)) {
87573471bf0Spatrick     LLVM_DEBUG(dbgs() << "Found a UMAX reduction PHI." << *Phi << "\n");
87673471bf0Spatrick     return true;
87773471bf0Spatrick   }
878*d415bd75Srobert   if (AddReductionVar(Phi, RecurKind::UMin, TheLoop, FMF, RedDes, DB, AC, DT,
879*d415bd75Srobert                       SE)) {
88073471bf0Spatrick     LLVM_DEBUG(dbgs() << "Found a UMIN reduction PHI." << *Phi << "\n");
88173471bf0Spatrick     return true;
88273471bf0Spatrick   }
883*d415bd75Srobert   if (AddReductionVar(Phi, RecurKind::SelectICmp, TheLoop, FMF, RedDes, DB, AC,
884*d415bd75Srobert                       DT, SE)) {
885*d415bd75Srobert     LLVM_DEBUG(dbgs() << "Found an integer conditional select reduction PHI."
886*d415bd75Srobert                       << *Phi << "\n");
887*d415bd75Srobert     return true;
888*d415bd75Srobert   }
889*d415bd75Srobert   if (AddReductionVar(Phi, RecurKind::FMul, TheLoop, FMF, RedDes, DB, AC, DT,
890*d415bd75Srobert                       SE)) {
89109467b48Spatrick     LLVM_DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
89209467b48Spatrick     return true;
89309467b48Spatrick   }
894*d415bd75Srobert   if (AddReductionVar(Phi, RecurKind::FAdd, TheLoop, FMF, RedDes, DB, AC, DT,
895*d415bd75Srobert                       SE)) {
89609467b48Spatrick     LLVM_DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
89709467b48Spatrick     return true;
89809467b48Spatrick   }
899*d415bd75Srobert   if (AddReductionVar(Phi, RecurKind::FMax, TheLoop, FMF, RedDes, DB, AC, DT,
900*d415bd75Srobert                       SE)) {
90173471bf0Spatrick     LLVM_DEBUG(dbgs() << "Found a float MAX reduction PHI." << *Phi << "\n");
90273471bf0Spatrick     return true;
90373471bf0Spatrick   }
904*d415bd75Srobert   if (AddReductionVar(Phi, RecurKind::FMin, TheLoop, FMF, RedDes, DB, AC, DT,
905*d415bd75Srobert                       SE)) {
90673471bf0Spatrick     LLVM_DEBUG(dbgs() << "Found a float MIN reduction PHI." << *Phi << "\n");
90709467b48Spatrick     return true;
90809467b48Spatrick   }
909*d415bd75Srobert   if (AddReductionVar(Phi, RecurKind::SelectFCmp, TheLoop, FMF, RedDes, DB, AC,
910*d415bd75Srobert                       DT, SE)) {
911*d415bd75Srobert     LLVM_DEBUG(dbgs() << "Found a float conditional select reduction PHI."
912*d415bd75Srobert                       << " PHI." << *Phi << "\n");
913*d415bd75Srobert     return true;
914*d415bd75Srobert   }
915*d415bd75Srobert   if (AddReductionVar(Phi, RecurKind::FMulAdd, TheLoop, FMF, RedDes, DB, AC, DT,
916*d415bd75Srobert                       SE)) {
917*d415bd75Srobert     LLVM_DEBUG(dbgs() << "Found an FMulAdd reduction PHI." << *Phi << "\n");
918*d415bd75Srobert     return true;
919*d415bd75Srobert   }
92009467b48Spatrick   // Not a reduction of known type.
92109467b48Spatrick   return false;
92209467b48Spatrick }
92309467b48Spatrick 
isFixedOrderRecurrence(PHINode * Phi,Loop * TheLoop,MapVector<Instruction *,Instruction * > & SinkAfter,DominatorTree * DT)924*d415bd75Srobert bool RecurrenceDescriptor::isFixedOrderRecurrence(
92509467b48Spatrick     PHINode *Phi, Loop *TheLoop,
92673471bf0Spatrick     MapVector<Instruction *, Instruction *> &SinkAfter, DominatorTree *DT) {
92709467b48Spatrick 
92809467b48Spatrick   // Ensure the phi node is in the loop header and has two incoming values.
92909467b48Spatrick   if (Phi->getParent() != TheLoop->getHeader() ||
93009467b48Spatrick       Phi->getNumIncomingValues() != 2)
93109467b48Spatrick     return false;
93209467b48Spatrick 
93309467b48Spatrick   // Ensure the loop has a preheader and a single latch block. The loop
93409467b48Spatrick   // vectorizer will need the latch to set up the next iteration of the loop.
93509467b48Spatrick   auto *Preheader = TheLoop->getLoopPreheader();
93609467b48Spatrick   auto *Latch = TheLoop->getLoopLatch();
93709467b48Spatrick   if (!Preheader || !Latch)
93809467b48Spatrick     return false;
93909467b48Spatrick 
94009467b48Spatrick   // Ensure the phi node's incoming blocks are the loop preheader and latch.
94109467b48Spatrick   if (Phi->getBasicBlockIndex(Preheader) < 0 ||
94209467b48Spatrick       Phi->getBasicBlockIndex(Latch) < 0)
94309467b48Spatrick     return false;
94409467b48Spatrick 
94509467b48Spatrick   // Get the previous value. The previous value comes from the latch edge while
946*d415bd75Srobert   // the initial value comes from the preheader edge.
94709467b48Spatrick   auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
948*d415bd75Srobert 
949*d415bd75Srobert   // If Previous is a phi in the header, go through incoming values from the
950*d415bd75Srobert   // latch until we find a non-phi value. Use this as the new Previous, all uses
951*d415bd75Srobert   // in the header will be dominated by the original phi, but need to be moved
952*d415bd75Srobert   // after the non-phi previous value.
953*d415bd75Srobert   SmallPtrSet<PHINode *, 4> SeenPhis;
954*d415bd75Srobert   while (auto *PrevPhi = dyn_cast_or_null<PHINode>(Previous)) {
955*d415bd75Srobert     if (PrevPhi->getParent() != Phi->getParent())
956*d415bd75Srobert       return false;
957*d415bd75Srobert     if (!SeenPhis.insert(PrevPhi).second)
958*d415bd75Srobert       return false;
959*d415bd75Srobert     Previous = dyn_cast<Instruction>(PrevPhi->getIncomingValueForBlock(Latch));
960*d415bd75Srobert   }
961*d415bd75Srobert 
96209467b48Spatrick   if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous) ||
96309467b48Spatrick       SinkAfter.count(Previous)) // Cannot rely on dominance due to motion.
96409467b48Spatrick     return false;
96509467b48Spatrick 
96673471bf0Spatrick   // Ensure every user of the phi node (recursively) is dominated by the
96773471bf0Spatrick   // previous value. The dominance requirement ensures the loop vectorizer will
96873471bf0Spatrick   // not need to vectorize the initial value prior to the first iteration of the
96973471bf0Spatrick   // loop.
97073471bf0Spatrick   // TODO: Consider extending this sinking to handle memory instructions.
97109467b48Spatrick 
97273471bf0Spatrick   // We optimistically assume we can sink all users after Previous. Keep a set
97373471bf0Spatrick   // of instructions to sink after Previous ordered by dominance in the common
97473471bf0Spatrick   // basic block. It will be applied to SinkAfter if all users can be sunk.
97573471bf0Spatrick   auto CompareByComesBefore = [](const Instruction *A, const Instruction *B) {
97673471bf0Spatrick     return A->comesBefore(B);
97709467b48Spatrick   };
97873471bf0Spatrick   std::set<Instruction *, decltype(CompareByComesBefore)> InstrsToSink(
97973471bf0Spatrick       CompareByComesBefore);
98009467b48Spatrick 
98173471bf0Spatrick   BasicBlock *PhiBB = Phi->getParent();
98273471bf0Spatrick   SmallVector<Instruction *, 8> WorkList;
98373471bf0Spatrick   auto TryToPushSinkCandidate = [&](Instruction *SinkCandidate) {
98473471bf0Spatrick     // Already sunk SinkCandidate.
98573471bf0Spatrick     if (SinkCandidate->getParent() == PhiBB &&
98673471bf0Spatrick         InstrsToSink.find(SinkCandidate) != InstrsToSink.end())
98773471bf0Spatrick       return true;
98809467b48Spatrick 
98973471bf0Spatrick     // Cyclic dependence.
99073471bf0Spatrick     if (Previous == SinkCandidate)
99109467b48Spatrick       return false;
99209467b48Spatrick 
99373471bf0Spatrick     if (DT->dominates(Previous,
99473471bf0Spatrick                       SinkCandidate)) // We already are good w/o sinking.
99573471bf0Spatrick       return true;
99673471bf0Spatrick 
99773471bf0Spatrick     if (SinkCandidate->getParent() != PhiBB ||
99873471bf0Spatrick         SinkCandidate->mayHaveSideEffects() ||
99973471bf0Spatrick         SinkCandidate->mayReadFromMemory() || SinkCandidate->isTerminator())
100009467b48Spatrick       return false;
100109467b48Spatrick 
1002*d415bd75Srobert     // Avoid sinking an instruction multiple times (if multiple operands are
1003*d415bd75Srobert     // fixed order recurrences) by sinking once - after the latest 'previous'
1004*d415bd75Srobert     // instruction.
1005*d415bd75Srobert     auto It = SinkAfter.find(SinkCandidate);
1006*d415bd75Srobert     if (It != SinkAfter.end()) {
1007*d415bd75Srobert       auto *OtherPrev = It->second;
1008*d415bd75Srobert       // Find the earliest entry in the 'sink-after' chain. The last entry in
1009*d415bd75Srobert       // the chain is the original 'Previous' for a recurrence handled earlier.
1010*d415bd75Srobert       auto EarlierIt = SinkAfter.find(OtherPrev);
1011*d415bd75Srobert       while (EarlierIt != SinkAfter.end()) {
1012*d415bd75Srobert         Instruction *EarlierInst = EarlierIt->second;
1013*d415bd75Srobert         EarlierIt = SinkAfter.find(EarlierInst);
1014*d415bd75Srobert         // Bail out if order has not been preserved.
1015*d415bd75Srobert         if (EarlierIt != SinkAfter.end() &&
1016*d415bd75Srobert             !DT->dominates(EarlierInst, OtherPrev))
101709467b48Spatrick           return false;
1018*d415bd75Srobert         OtherPrev = EarlierInst;
1019*d415bd75Srobert       }
1020*d415bd75Srobert       // Bail out if order has not been preserved.
1021*d415bd75Srobert       if (OtherPrev != It->second && !DT->dominates(It->second, OtherPrev))
1022*d415bd75Srobert         return false;
1023*d415bd75Srobert 
1024*d415bd75Srobert       // SinkCandidate is already being sunk after an instruction after
1025*d415bd75Srobert       // Previous. Nothing left to do.
1026*d415bd75Srobert       if (DT->dominates(Previous, OtherPrev) || Previous == OtherPrev)
1027*d415bd75Srobert         return true;
1028*d415bd75Srobert 
1029*d415bd75Srobert       // If there are other instructions to be sunk after SinkCandidate, remove
1030*d415bd75Srobert       // and re-insert SinkCandidate can break those instructions. Bail out for
1031*d415bd75Srobert       // simplicity.
1032*d415bd75Srobert       if (any_of(SinkAfter,
1033*d415bd75Srobert           [SinkCandidate](const std::pair<Instruction *, Instruction *> &P) {
1034*d415bd75Srobert             return P.second == SinkCandidate;
1035*d415bd75Srobert           }))
1036*d415bd75Srobert         return false;
1037*d415bd75Srobert 
1038*d415bd75Srobert       // Otherwise, Previous comes after OtherPrev and SinkCandidate needs to be
1039*d415bd75Srobert       // re-sunk to Previous, instead of sinking to OtherPrev. Remove
1040*d415bd75Srobert       // SinkCandidate from SinkAfter to ensure it's insert position is updated.
1041*d415bd75Srobert       SinkAfter.erase(SinkCandidate);
1042*d415bd75Srobert     }
104309467b48Spatrick 
104473471bf0Spatrick     // If we reach a PHI node that is not dominated by Previous, we reached a
104573471bf0Spatrick     // header PHI. No need for sinking.
104673471bf0Spatrick     if (isa<PHINode>(SinkCandidate))
104709467b48Spatrick       return true;
104809467b48Spatrick 
104973471bf0Spatrick     // Sink User tentatively and check its users
105073471bf0Spatrick     InstrsToSink.insert(SinkCandidate);
105173471bf0Spatrick     WorkList.push_back(SinkCandidate);
105273471bf0Spatrick     return true;
105373471bf0Spatrick   };
105473471bf0Spatrick 
105573471bf0Spatrick   WorkList.push_back(Phi);
105673471bf0Spatrick   // Try to recursively sink instructions and their users after Previous.
105773471bf0Spatrick   while (!WorkList.empty()) {
105873471bf0Spatrick     Instruction *Current = WorkList.pop_back_val();
105973471bf0Spatrick     for (User *User : Current->users()) {
106073471bf0Spatrick       if (!TryToPushSinkCandidate(cast<Instruction>(User)))
106173471bf0Spatrick         return false;
106273471bf0Spatrick     }
106373471bf0Spatrick   }
106473471bf0Spatrick 
106573471bf0Spatrick   // We can sink all users of Phi. Update the mapping.
106673471bf0Spatrick   for (Instruction *I : InstrsToSink) {
106709467b48Spatrick     SinkAfter[I] = Previous;
106873471bf0Spatrick     Previous = I;
106973471bf0Spatrick   }
107009467b48Spatrick   return true;
107109467b48Spatrick }
107209467b48Spatrick 
107309467b48Spatrick /// This function returns the identity element (or neutral element) for
107409467b48Spatrick /// the operation K.
getRecurrenceIdentity(RecurKind K,Type * Tp,FastMathFlags FMF) const1075*d415bd75Srobert Value *RecurrenceDescriptor::getRecurrenceIdentity(RecurKind K, Type *Tp,
1076*d415bd75Srobert                                                    FastMathFlags FMF) const {
107709467b48Spatrick   switch (K) {
107873471bf0Spatrick   case RecurKind::Xor:
107973471bf0Spatrick   case RecurKind::Add:
108073471bf0Spatrick   case RecurKind::Or:
108109467b48Spatrick     // Adding, Xoring, Oring zero to a number does not change it.
108209467b48Spatrick     return ConstantInt::get(Tp, 0);
108373471bf0Spatrick   case RecurKind::Mul:
108409467b48Spatrick     // Multiplying a number by 1 does not change it.
108509467b48Spatrick     return ConstantInt::get(Tp, 1);
108673471bf0Spatrick   case RecurKind::And:
108709467b48Spatrick     // AND-ing a number with an all-1 value does not change it.
108809467b48Spatrick     return ConstantInt::get(Tp, -1, true);
108973471bf0Spatrick   case RecurKind::FMul:
109009467b48Spatrick     // Multiplying a number by 1 does not change it.
109109467b48Spatrick     return ConstantFP::get(Tp, 1.0L);
1092*d415bd75Srobert   case RecurKind::FMulAdd:
109373471bf0Spatrick   case RecurKind::FAdd:
109409467b48Spatrick     // Adding zero to a number does not change it.
109573471bf0Spatrick     // FIXME: Ideally we should not need to check FMF for FAdd and should always
109673471bf0Spatrick     // use -0.0. However, this will currently result in mixed vectors of 0.0/-0.0.
109773471bf0Spatrick     // Instead, we should ensure that 1) the FMF from FAdd are propagated to the PHI
109873471bf0Spatrick     // nodes where possible, and 2) PHIs with the nsz flag + -0.0 use 0.0. This would
109973471bf0Spatrick     // mean we can then remove the check for noSignedZeros() below (see D98963).
110073471bf0Spatrick     if (FMF.noSignedZeros())
110109467b48Spatrick       return ConstantFP::get(Tp, 0.0L);
110273471bf0Spatrick     return ConstantFP::get(Tp, -0.0L);
110373471bf0Spatrick   case RecurKind::UMin:
110473471bf0Spatrick     return ConstantInt::get(Tp, -1);
110573471bf0Spatrick   case RecurKind::UMax:
110673471bf0Spatrick     return ConstantInt::get(Tp, 0);
110773471bf0Spatrick   case RecurKind::SMin:
110873471bf0Spatrick     return ConstantInt::get(Tp,
110973471bf0Spatrick                             APInt::getSignedMaxValue(Tp->getIntegerBitWidth()));
111073471bf0Spatrick   case RecurKind::SMax:
111173471bf0Spatrick     return ConstantInt::get(Tp,
111273471bf0Spatrick                             APInt::getSignedMinValue(Tp->getIntegerBitWidth()));
111373471bf0Spatrick   case RecurKind::FMin:
1114*d415bd75Srobert     assert((FMF.noNaNs() && FMF.noSignedZeros()) &&
1115*d415bd75Srobert            "nnan, nsz is expected to be set for FP min reduction.");
1116*d415bd75Srobert     return ConstantFP::getInfinity(Tp, false /*Negative*/);
111773471bf0Spatrick   case RecurKind::FMax:
1118*d415bd75Srobert     assert((FMF.noNaNs() && FMF.noSignedZeros()) &&
1119*d415bd75Srobert            "nnan, nsz is expected to be set for FP max reduction.");
1120*d415bd75Srobert     return ConstantFP::getInfinity(Tp, true /*Negative*/);
1121*d415bd75Srobert   case RecurKind::SelectICmp:
1122*d415bd75Srobert   case RecurKind::SelectFCmp:
1123*d415bd75Srobert     return getRecurrenceStartValue();
1124*d415bd75Srobert     break;
112509467b48Spatrick   default:
112609467b48Spatrick     llvm_unreachable("Unknown recurrence kind");
112709467b48Spatrick   }
112809467b48Spatrick }
112909467b48Spatrick 
getOpcode(RecurKind Kind)113073471bf0Spatrick unsigned RecurrenceDescriptor::getOpcode(RecurKind Kind) {
113109467b48Spatrick   switch (Kind) {
113273471bf0Spatrick   case RecurKind::Add:
113309467b48Spatrick     return Instruction::Add;
113473471bf0Spatrick   case RecurKind::Mul:
113509467b48Spatrick     return Instruction::Mul;
113673471bf0Spatrick   case RecurKind::Or:
113709467b48Spatrick     return Instruction::Or;
113873471bf0Spatrick   case RecurKind::And:
113909467b48Spatrick     return Instruction::And;
114073471bf0Spatrick   case RecurKind::Xor:
114109467b48Spatrick     return Instruction::Xor;
114273471bf0Spatrick   case RecurKind::FMul:
114309467b48Spatrick     return Instruction::FMul;
1144*d415bd75Srobert   case RecurKind::FMulAdd:
114573471bf0Spatrick   case RecurKind::FAdd:
114609467b48Spatrick     return Instruction::FAdd;
114773471bf0Spatrick   case RecurKind::SMax:
114873471bf0Spatrick   case RecurKind::SMin:
114973471bf0Spatrick   case RecurKind::UMax:
115073471bf0Spatrick   case RecurKind::UMin:
1151*d415bd75Srobert   case RecurKind::SelectICmp:
115209467b48Spatrick     return Instruction::ICmp;
115373471bf0Spatrick   case RecurKind::FMax:
115473471bf0Spatrick   case RecurKind::FMin:
1155*d415bd75Srobert   case RecurKind::SelectFCmp:
115609467b48Spatrick     return Instruction::FCmp;
115709467b48Spatrick   default:
115809467b48Spatrick     llvm_unreachable("Unknown recurrence operation");
115909467b48Spatrick   }
116009467b48Spatrick }
116109467b48Spatrick 
116273471bf0Spatrick SmallVector<Instruction *, 4>
getReductionOpChain(PHINode * Phi,Loop * L) const116373471bf0Spatrick RecurrenceDescriptor::getReductionOpChain(PHINode *Phi, Loop *L) const {
116473471bf0Spatrick   SmallVector<Instruction *, 4> ReductionOperations;
116573471bf0Spatrick   unsigned RedOp = getOpcode(Kind);
116673471bf0Spatrick 
116773471bf0Spatrick   // Search down from the Phi to the LoopExitInstr, looking for instructions
116873471bf0Spatrick   // with a single user of the correct type for the reduction.
116973471bf0Spatrick 
117073471bf0Spatrick   // Note that we check that the type of the operand is correct for each item in
117173471bf0Spatrick   // the chain, including the last (the loop exit value). This can come up from
117273471bf0Spatrick   // sub, which would otherwise be treated as an add reduction. MinMax also need
117373471bf0Spatrick   // to check for a pair of icmp/select, for which we use getNextInstruction and
117473471bf0Spatrick   // isCorrectOpcode functions to step the right number of instruction, and
117573471bf0Spatrick   // check the icmp/select pair.
1176*d415bd75Srobert   // FIXME: We also do not attempt to look through Select's yet, which might
117773471bf0Spatrick   // be part of the reduction chain, or attempt to looks through And's to find a
117873471bf0Spatrick   // smaller bitwidth. Subs are also currently not allowed (which are usually
117973471bf0Spatrick   // treated as part of a add reduction) as they are expected to generally be
118073471bf0Spatrick   // more expensive than out-of-loop reductions, and need to be costed more
118173471bf0Spatrick   // carefully.
118273471bf0Spatrick   unsigned ExpectedUses = 1;
118373471bf0Spatrick   if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp)
118473471bf0Spatrick     ExpectedUses = 2;
118573471bf0Spatrick 
1186*d415bd75Srobert   auto getNextInstruction = [&](Instruction *Cur) -> Instruction * {
1187*d415bd75Srobert     for (auto *User : Cur->users()) {
1188*d415bd75Srobert       Instruction *UI = cast<Instruction>(User);
1189*d415bd75Srobert       if (isa<PHINode>(UI))
1190*d415bd75Srobert         continue;
119173471bf0Spatrick       if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp) {
119273471bf0Spatrick         // We are expecting a icmp/select pair, which we go to the next select
119373471bf0Spatrick         // instruction if we can. We already know that Cur has 2 uses.
1194*d415bd75Srobert         if (isa<SelectInst>(UI))
1195*d415bd75Srobert           return UI;
1196*d415bd75Srobert         continue;
119773471bf0Spatrick       }
1198*d415bd75Srobert       return UI;
1199*d415bd75Srobert     }
1200*d415bd75Srobert     return nullptr;
120173471bf0Spatrick   };
120273471bf0Spatrick   auto isCorrectOpcode = [&](Instruction *Cur) {
120373471bf0Spatrick     if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp) {
120473471bf0Spatrick       Value *LHS, *RHS;
120573471bf0Spatrick       return SelectPatternResult::isMinOrMax(
120673471bf0Spatrick           matchSelectPattern(Cur, LHS, RHS).Flavor);
120773471bf0Spatrick     }
1208*d415bd75Srobert     // Recognize a call to the llvm.fmuladd intrinsic.
1209*d415bd75Srobert     if (isFMulAddIntrinsic(Cur))
1210*d415bd75Srobert       return true;
1211*d415bd75Srobert 
121273471bf0Spatrick     return Cur->getOpcode() == RedOp;
121373471bf0Spatrick   };
121473471bf0Spatrick 
1215*d415bd75Srobert   // Attempt to look through Phis which are part of the reduction chain
1216*d415bd75Srobert   unsigned ExtraPhiUses = 0;
1217*d415bd75Srobert   Instruction *RdxInstr = LoopExitInstr;
1218*d415bd75Srobert   if (auto ExitPhi = dyn_cast<PHINode>(LoopExitInstr)) {
1219*d415bd75Srobert     if (ExitPhi->getNumIncomingValues() != 2)
1220*d415bd75Srobert       return {};
1221*d415bd75Srobert 
1222*d415bd75Srobert     Instruction *Inc0 = dyn_cast<Instruction>(ExitPhi->getIncomingValue(0));
1223*d415bd75Srobert     Instruction *Inc1 = dyn_cast<Instruction>(ExitPhi->getIncomingValue(1));
1224*d415bd75Srobert 
1225*d415bd75Srobert     Instruction *Chain = nullptr;
1226*d415bd75Srobert     if (Inc0 == Phi)
1227*d415bd75Srobert       Chain = Inc1;
1228*d415bd75Srobert     else if (Inc1 == Phi)
1229*d415bd75Srobert       Chain = Inc0;
1230*d415bd75Srobert     else
1231*d415bd75Srobert       return {};
1232*d415bd75Srobert 
1233*d415bd75Srobert     RdxInstr = Chain;
1234*d415bd75Srobert     ExtraPhiUses = 1;
1235*d415bd75Srobert   }
1236*d415bd75Srobert 
123773471bf0Spatrick   // The loop exit instruction we check first (as a quick test) but add last. We
123873471bf0Spatrick   // check the opcode is correct (and dont allow them to be Subs) and that they
123973471bf0Spatrick   // have expected to have the expected number of uses. They will have one use
124073471bf0Spatrick   // from the phi and one from a LCSSA value, no matter the type.
1241*d415bd75Srobert   if (!isCorrectOpcode(RdxInstr) || !LoopExitInstr->hasNUses(2))
124273471bf0Spatrick     return {};
124373471bf0Spatrick 
1244*d415bd75Srobert   // Check that the Phi has one (or two for min/max) uses, plus an extra use
1245*d415bd75Srobert   // for conditional reductions.
1246*d415bd75Srobert   if (!Phi->hasNUses(ExpectedUses + ExtraPhiUses))
124773471bf0Spatrick     return {};
1248*d415bd75Srobert 
124973471bf0Spatrick   Instruction *Cur = getNextInstruction(Phi);
125073471bf0Spatrick 
125173471bf0Spatrick   // Each other instruction in the chain should have the expected number of uses
125273471bf0Spatrick   // and be the correct opcode.
1253*d415bd75Srobert   while (Cur != RdxInstr) {
1254*d415bd75Srobert     if (!Cur || !isCorrectOpcode(Cur) || !Cur->hasNUses(ExpectedUses))
125573471bf0Spatrick       return {};
125673471bf0Spatrick 
125773471bf0Spatrick     ReductionOperations.push_back(Cur);
125873471bf0Spatrick     Cur = getNextInstruction(Cur);
125973471bf0Spatrick   }
126073471bf0Spatrick 
126173471bf0Spatrick   ReductionOperations.push_back(Cur);
126273471bf0Spatrick   return ReductionOperations;
126373471bf0Spatrick }
126473471bf0Spatrick 
InductionDescriptor(Value * Start,InductionKind K,const SCEV * Step,BinaryOperator * BOp,Type * ElementType,SmallVectorImpl<Instruction * > * Casts)126509467b48Spatrick InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
126609467b48Spatrick                                          const SCEV *Step, BinaryOperator *BOp,
1267*d415bd75Srobert                                          Type *ElementType,
126809467b48Spatrick                                          SmallVectorImpl<Instruction *> *Casts)
1269*d415bd75Srobert     : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp),
1270*d415bd75Srobert       ElementType(ElementType) {
127109467b48Spatrick   assert(IK != IK_NoInduction && "Not an induction");
127209467b48Spatrick 
127309467b48Spatrick   // Start value type should match the induction kind and the value
127409467b48Spatrick   // itself should not be null.
127509467b48Spatrick   assert(StartValue && "StartValue is null");
127609467b48Spatrick   assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
127709467b48Spatrick          "StartValue is not a pointer for pointer induction");
127809467b48Spatrick   assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
127909467b48Spatrick          "StartValue is not an integer for integer induction");
128009467b48Spatrick 
128109467b48Spatrick   // Check the Step Value. It should be non-zero integer value.
128209467b48Spatrick   assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
128309467b48Spatrick          "Step value is zero");
128409467b48Spatrick 
128509467b48Spatrick   assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
128609467b48Spatrick          "Step value should be constant for pointer induction");
128709467b48Spatrick   assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
128809467b48Spatrick          "StepValue is not an integer");
128909467b48Spatrick 
129009467b48Spatrick   assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
129109467b48Spatrick          "StepValue is not FP for FpInduction");
129209467b48Spatrick   assert((IK != IK_FpInduction ||
129309467b48Spatrick           (InductionBinOp &&
129409467b48Spatrick            (InductionBinOp->getOpcode() == Instruction::FAdd ||
129509467b48Spatrick             InductionBinOp->getOpcode() == Instruction::FSub))) &&
129609467b48Spatrick          "Binary opcode should be specified for FP induction");
129709467b48Spatrick 
1298*d415bd75Srobert   if (IK == IK_PtrInduction)
1299*d415bd75Srobert     assert(ElementType && "Pointer induction must have element type");
1300*d415bd75Srobert   else
1301*d415bd75Srobert     assert(!ElementType && "Non-pointer induction cannot have element type");
1302*d415bd75Srobert 
130309467b48Spatrick   if (Casts) {
130409467b48Spatrick     for (auto &Inst : *Casts) {
130509467b48Spatrick       RedundantCasts.push_back(Inst);
130609467b48Spatrick     }
130709467b48Spatrick   }
130809467b48Spatrick }
130909467b48Spatrick 
getConstIntStepValue() const131009467b48Spatrick ConstantInt *InductionDescriptor::getConstIntStepValue() const {
131109467b48Spatrick   if (isa<SCEVConstant>(Step))
131209467b48Spatrick     return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
131309467b48Spatrick   return nullptr;
131409467b48Spatrick }
131509467b48Spatrick 
isFPInductionPHI(PHINode * Phi,const Loop * TheLoop,ScalarEvolution * SE,InductionDescriptor & D)131609467b48Spatrick bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop,
131709467b48Spatrick                                            ScalarEvolution *SE,
131809467b48Spatrick                                            InductionDescriptor &D) {
131909467b48Spatrick 
132009467b48Spatrick   // Here we only handle FP induction variables.
132109467b48Spatrick   assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
132209467b48Spatrick 
132309467b48Spatrick   if (TheLoop->getHeader() != Phi->getParent())
132409467b48Spatrick     return false;
132509467b48Spatrick 
132609467b48Spatrick   // The loop may have multiple entrances or multiple exits; we can analyze
132709467b48Spatrick   // this phi if it has a unique entry value and a unique backedge value.
132809467b48Spatrick   if (Phi->getNumIncomingValues() != 2)
132909467b48Spatrick     return false;
133009467b48Spatrick   Value *BEValue = nullptr, *StartValue = nullptr;
133109467b48Spatrick   if (TheLoop->contains(Phi->getIncomingBlock(0))) {
133209467b48Spatrick     BEValue = Phi->getIncomingValue(0);
133309467b48Spatrick     StartValue = Phi->getIncomingValue(1);
133409467b48Spatrick   } else {
133509467b48Spatrick     assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
133609467b48Spatrick            "Unexpected Phi node in the loop");
133709467b48Spatrick     BEValue = Phi->getIncomingValue(1);
133809467b48Spatrick     StartValue = Phi->getIncomingValue(0);
133909467b48Spatrick   }
134009467b48Spatrick 
134109467b48Spatrick   BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue);
134209467b48Spatrick   if (!BOp)
134309467b48Spatrick     return false;
134409467b48Spatrick 
134509467b48Spatrick   Value *Addend = nullptr;
134609467b48Spatrick   if (BOp->getOpcode() == Instruction::FAdd) {
134709467b48Spatrick     if (BOp->getOperand(0) == Phi)
134809467b48Spatrick       Addend = BOp->getOperand(1);
134909467b48Spatrick     else if (BOp->getOperand(1) == Phi)
135009467b48Spatrick       Addend = BOp->getOperand(0);
135109467b48Spatrick   } else if (BOp->getOpcode() == Instruction::FSub)
135209467b48Spatrick     if (BOp->getOperand(0) == Phi)
135309467b48Spatrick       Addend = BOp->getOperand(1);
135409467b48Spatrick 
135509467b48Spatrick   if (!Addend)
135609467b48Spatrick     return false;
135709467b48Spatrick 
135809467b48Spatrick   // The addend should be loop invariant
135909467b48Spatrick   if (auto *I = dyn_cast<Instruction>(Addend))
136009467b48Spatrick     if (TheLoop->contains(I))
136109467b48Spatrick       return false;
136209467b48Spatrick 
136309467b48Spatrick   // FP Step has unknown SCEV
136409467b48Spatrick   const SCEV *Step = SE->getUnknown(Addend);
136509467b48Spatrick   D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
136609467b48Spatrick   return true;
136709467b48Spatrick }
136809467b48Spatrick 
136909467b48Spatrick /// This function is called when we suspect that the update-chain of a phi node
137009467b48Spatrick /// (whose symbolic SCEV expression sin \p PhiScev) contains redundant casts,
137109467b48Spatrick /// that can be ignored. (This can happen when the PSCEV rewriter adds a runtime
137209467b48Spatrick /// predicate P under which the SCEV expression for the phi can be the
137309467b48Spatrick /// AddRecurrence \p AR; See createAddRecFromPHIWithCast). We want to find the
137409467b48Spatrick /// cast instructions that are involved in the update-chain of this induction.
137509467b48Spatrick /// A caller that adds the required runtime predicate can be free to drop these
137609467b48Spatrick /// cast instructions, and compute the phi using \p AR (instead of some scev
137709467b48Spatrick /// expression with casts).
137809467b48Spatrick ///
137909467b48Spatrick /// For example, without a predicate the scev expression can take the following
138009467b48Spatrick /// form:
138109467b48Spatrick ///      (Ext ix (Trunc iy ( Start + i*Step ) to ix) to iy)
138209467b48Spatrick ///
138309467b48Spatrick /// It corresponds to the following IR sequence:
138409467b48Spatrick /// %for.body:
138509467b48Spatrick ///   %x = phi i64 [ 0, %ph ], [ %add, %for.body ]
138609467b48Spatrick ///   %casted_phi = "ExtTrunc i64 %x"
138709467b48Spatrick ///   %add = add i64 %casted_phi, %step
138809467b48Spatrick ///
138909467b48Spatrick /// where %x is given in \p PN,
139009467b48Spatrick /// PSE.getSCEV(%x) is equal to PSE.getSCEV(%casted_phi) under a predicate,
139109467b48Spatrick /// and the IR sequence that "ExtTrunc i64 %x" represents can take one of
139209467b48Spatrick /// several forms, for example, such as:
139309467b48Spatrick ///   ExtTrunc1:    %casted_phi = and  %x, 2^n-1
139409467b48Spatrick /// or:
139509467b48Spatrick ///   ExtTrunc2:    %t = shl %x, m
139609467b48Spatrick ///                 %casted_phi = ashr %t, m
139709467b48Spatrick ///
139809467b48Spatrick /// If we are able to find such sequence, we return the instructions
139909467b48Spatrick /// we found, namely %casted_phi and the instructions on its use-def chain up
140009467b48Spatrick /// to the phi (not including the phi).
getCastsForInductionPHI(PredicatedScalarEvolution & PSE,const SCEVUnknown * PhiScev,const SCEVAddRecExpr * AR,SmallVectorImpl<Instruction * > & CastInsts)140109467b48Spatrick static bool getCastsForInductionPHI(PredicatedScalarEvolution &PSE,
140209467b48Spatrick                                     const SCEVUnknown *PhiScev,
140309467b48Spatrick                                     const SCEVAddRecExpr *AR,
140409467b48Spatrick                                     SmallVectorImpl<Instruction *> &CastInsts) {
140509467b48Spatrick 
140609467b48Spatrick   assert(CastInsts.empty() && "CastInsts is expected to be empty.");
140709467b48Spatrick   auto *PN = cast<PHINode>(PhiScev->getValue());
140809467b48Spatrick   assert(PSE.getSCEV(PN) == AR && "Unexpected phi node SCEV expression");
140909467b48Spatrick   const Loop *L = AR->getLoop();
141009467b48Spatrick 
141109467b48Spatrick   // Find any cast instructions that participate in the def-use chain of
141209467b48Spatrick   // PhiScev in the loop.
141309467b48Spatrick   // FORNOW/TODO: We currently expect the def-use chain to include only
141409467b48Spatrick   // two-operand instructions, where one of the operands is an invariant.
141509467b48Spatrick   // createAddRecFromPHIWithCasts() currently does not support anything more
141609467b48Spatrick   // involved than that, so we keep the search simple. This can be
141709467b48Spatrick   // extended/generalized as needed.
141809467b48Spatrick 
141909467b48Spatrick   auto getDef = [&](const Value *Val) -> Value * {
142009467b48Spatrick     const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val);
142109467b48Spatrick     if (!BinOp)
142209467b48Spatrick       return nullptr;
142309467b48Spatrick     Value *Op0 = BinOp->getOperand(0);
142409467b48Spatrick     Value *Op1 = BinOp->getOperand(1);
142509467b48Spatrick     Value *Def = nullptr;
142609467b48Spatrick     if (L->isLoopInvariant(Op0))
142709467b48Spatrick       Def = Op1;
142809467b48Spatrick     else if (L->isLoopInvariant(Op1))
142909467b48Spatrick       Def = Op0;
143009467b48Spatrick     return Def;
143109467b48Spatrick   };
143209467b48Spatrick 
143309467b48Spatrick   // Look for the instruction that defines the induction via the
143409467b48Spatrick   // loop backedge.
143509467b48Spatrick   BasicBlock *Latch = L->getLoopLatch();
143609467b48Spatrick   if (!Latch)
143709467b48Spatrick     return false;
143809467b48Spatrick   Value *Val = PN->getIncomingValueForBlock(Latch);
143909467b48Spatrick   if (!Val)
144009467b48Spatrick     return false;
144109467b48Spatrick 
144209467b48Spatrick   // Follow the def-use chain until the induction phi is reached.
144309467b48Spatrick   // If on the way we encounter a Value that has the same SCEV Expr as the
144409467b48Spatrick   // phi node, we can consider the instructions we visit from that point
144509467b48Spatrick   // as part of the cast-sequence that can be ignored.
144609467b48Spatrick   bool InCastSequence = false;
144709467b48Spatrick   auto *Inst = dyn_cast<Instruction>(Val);
144809467b48Spatrick   while (Val != PN) {
144909467b48Spatrick     // If we encountered a phi node other than PN, or if we left the loop,
145009467b48Spatrick     // we bail out.
145109467b48Spatrick     if (!Inst || !L->contains(Inst)) {
145209467b48Spatrick       return false;
145309467b48Spatrick     }
145409467b48Spatrick     auto *AddRec = dyn_cast<SCEVAddRecExpr>(PSE.getSCEV(Val));
145509467b48Spatrick     if (AddRec && PSE.areAddRecsEqualWithPreds(AddRec, AR))
145609467b48Spatrick       InCastSequence = true;
145709467b48Spatrick     if (InCastSequence) {
145809467b48Spatrick       // Only the last instruction in the cast sequence is expected to have
145909467b48Spatrick       // uses outside the induction def-use chain.
146009467b48Spatrick       if (!CastInsts.empty())
146109467b48Spatrick         if (!Inst->hasOneUse())
146209467b48Spatrick           return false;
146309467b48Spatrick       CastInsts.push_back(Inst);
146409467b48Spatrick     }
146509467b48Spatrick     Val = getDef(Val);
146609467b48Spatrick     if (!Val)
146709467b48Spatrick       return false;
146809467b48Spatrick     Inst = dyn_cast<Instruction>(Val);
146909467b48Spatrick   }
147009467b48Spatrick 
147109467b48Spatrick   return InCastSequence;
147209467b48Spatrick }
147309467b48Spatrick 
isInductionPHI(PHINode * Phi,const Loop * TheLoop,PredicatedScalarEvolution & PSE,InductionDescriptor & D,bool Assume)147409467b48Spatrick bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
147509467b48Spatrick                                          PredicatedScalarEvolution &PSE,
147609467b48Spatrick                                          InductionDescriptor &D, bool Assume) {
147709467b48Spatrick   Type *PhiTy = Phi->getType();
147809467b48Spatrick 
147909467b48Spatrick   // Handle integer and pointer inductions variables.
148009467b48Spatrick   // Now we handle also FP induction but not trying to make a
148109467b48Spatrick   // recurrent expression from the PHI node in-place.
148209467b48Spatrick 
148309467b48Spatrick   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() && !PhiTy->isFloatTy() &&
148409467b48Spatrick       !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
148509467b48Spatrick     return false;
148609467b48Spatrick 
148709467b48Spatrick   if (PhiTy->isFloatingPointTy())
148809467b48Spatrick     return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
148909467b48Spatrick 
149009467b48Spatrick   const SCEV *PhiScev = PSE.getSCEV(Phi);
149109467b48Spatrick   const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
149209467b48Spatrick 
149309467b48Spatrick   // We need this expression to be an AddRecExpr.
149409467b48Spatrick   if (Assume && !AR)
149509467b48Spatrick     AR = PSE.getAsAddRec(Phi);
149609467b48Spatrick 
149709467b48Spatrick   if (!AR) {
149809467b48Spatrick     LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
149909467b48Spatrick     return false;
150009467b48Spatrick   }
150109467b48Spatrick 
150209467b48Spatrick   // Record any Cast instructions that participate in the induction update
150309467b48Spatrick   const auto *SymbolicPhi = dyn_cast<SCEVUnknown>(PhiScev);
150409467b48Spatrick   // If we started from an UnknownSCEV, and managed to build an addRecurrence
150509467b48Spatrick   // only after enabling Assume with PSCEV, this means we may have encountered
150609467b48Spatrick   // cast instructions that required adding a runtime check in order to
150709467b48Spatrick   // guarantee the correctness of the AddRecurrence respresentation of the
150809467b48Spatrick   // induction.
150909467b48Spatrick   if (PhiScev != AR && SymbolicPhi) {
151009467b48Spatrick     SmallVector<Instruction *, 2> Casts;
151109467b48Spatrick     if (getCastsForInductionPHI(PSE, SymbolicPhi, AR, Casts))
151209467b48Spatrick       return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR, &Casts);
151309467b48Spatrick   }
151409467b48Spatrick 
151509467b48Spatrick   return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
151609467b48Spatrick }
151709467b48Spatrick 
isInductionPHI(PHINode * Phi,const Loop * TheLoop,ScalarEvolution * SE,InductionDescriptor & D,const SCEV * Expr,SmallVectorImpl<Instruction * > * CastsToIgnore)151809467b48Spatrick bool InductionDescriptor::isInductionPHI(
151909467b48Spatrick     PHINode *Phi, const Loop *TheLoop, ScalarEvolution *SE,
152009467b48Spatrick     InductionDescriptor &D, const SCEV *Expr,
152109467b48Spatrick     SmallVectorImpl<Instruction *> *CastsToIgnore) {
152209467b48Spatrick   Type *PhiTy = Phi->getType();
152309467b48Spatrick   // We only handle integer and pointer inductions variables.
152409467b48Spatrick   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
152509467b48Spatrick     return false;
152609467b48Spatrick 
152709467b48Spatrick   // Check that the PHI is consecutive.
152809467b48Spatrick   const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
152909467b48Spatrick   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
153009467b48Spatrick 
153109467b48Spatrick   if (!AR) {
153209467b48Spatrick     LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
153309467b48Spatrick     return false;
153409467b48Spatrick   }
153509467b48Spatrick 
153609467b48Spatrick   if (AR->getLoop() != TheLoop) {
153709467b48Spatrick     // FIXME: We should treat this as a uniform. Unfortunately, we
153809467b48Spatrick     // don't currently know how to handled uniform PHIs.
153909467b48Spatrick     LLVM_DEBUG(
154009467b48Spatrick         dbgs() << "LV: PHI is a recurrence with respect to an outer loop.\n");
154109467b48Spatrick     return false;
154209467b48Spatrick   }
154309467b48Spatrick 
154409467b48Spatrick   Value *StartValue =
154509467b48Spatrick       Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
154609467b48Spatrick 
154709467b48Spatrick   BasicBlock *Latch = AR->getLoop()->getLoopLatch();
154809467b48Spatrick   if (!Latch)
154909467b48Spatrick     return false;
155009467b48Spatrick 
155109467b48Spatrick   const SCEV *Step = AR->getStepRecurrence(*SE);
155209467b48Spatrick   // Calculate the pointer stride and check if it is consecutive.
155309467b48Spatrick   // The stride may be a constant or a loop invariant integer value.
155409467b48Spatrick   const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
155509467b48Spatrick   if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop))
155609467b48Spatrick     return false;
155709467b48Spatrick 
155809467b48Spatrick   if (PhiTy->isIntegerTy()) {
1559*d415bd75Srobert     BinaryOperator *BOp =
1560*d415bd75Srobert         dyn_cast<BinaryOperator>(Phi->getIncomingValueForBlock(Latch));
156109467b48Spatrick     D = InductionDescriptor(StartValue, IK_IntInduction, Step, BOp,
1562*d415bd75Srobert                             /* ElementType */ nullptr, CastsToIgnore);
156309467b48Spatrick     return true;
156409467b48Spatrick   }
156509467b48Spatrick 
156609467b48Spatrick   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
156709467b48Spatrick   // Pointer induction should be a constant.
156809467b48Spatrick   if (!ConstStep)
156909467b48Spatrick     return false;
157009467b48Spatrick 
1571*d415bd75Srobert   // Always use i8 element type for opaque pointer inductions.
1572*d415bd75Srobert   PointerType *PtrTy = cast<PointerType>(PhiTy);
1573*d415bd75Srobert   Type *ElementType = PtrTy->isOpaque()
1574*d415bd75Srobert                           ? Type::getInt8Ty(PtrTy->getContext())
1575*d415bd75Srobert                           : PtrTy->getNonOpaquePointerElementType();
1576*d415bd75Srobert   if (!ElementType->isSized())
1577*d415bd75Srobert     return false;
1578*d415bd75Srobert 
157909467b48Spatrick   ConstantInt *CV = ConstStep->getValue();
158009467b48Spatrick   const DataLayout &DL = Phi->getModule()->getDataLayout();
1581*d415bd75Srobert   TypeSize TySize = DL.getTypeAllocSize(ElementType);
1582*d415bd75Srobert   // TODO: We could potentially support this for scalable vectors if we can
1583*d415bd75Srobert   // prove at compile time that the constant step is always a multiple of
1584*d415bd75Srobert   // the scalable type.
1585*d415bd75Srobert   if (TySize.isZero() || TySize.isScalable())
158609467b48Spatrick     return false;
158709467b48Spatrick 
1588*d415bd75Srobert   int64_t Size = static_cast<int64_t>(TySize.getFixedValue());
158909467b48Spatrick   int64_t CVSize = CV->getSExtValue();
159009467b48Spatrick   if (CVSize % Size)
159109467b48Spatrick     return false;
159209467b48Spatrick   auto *StepValue =
159309467b48Spatrick       SE->getConstant(CV->getType(), CVSize / Size, true /* signed */);
1594*d415bd75Srobert   D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue,
1595*d415bd75Srobert                           /* BinOp */ nullptr, ElementType);
159609467b48Spatrick   return true;
159709467b48Spatrick }
1598