176aa662cSKarthik Bhat //===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
276aa662cSKarthik Bhat //
376aa662cSKarthik Bhat //                     The LLVM Compiler Infrastructure
476aa662cSKarthik Bhat //
576aa662cSKarthik Bhat // This file is distributed under the University of Illinois Open Source
676aa662cSKarthik Bhat // License. See LICENSE.TXT for details.
776aa662cSKarthik Bhat //
876aa662cSKarthik Bhat //===----------------------------------------------------------------------===//
976aa662cSKarthik Bhat //
1076aa662cSKarthik Bhat // This file defines common loop utility functions.
1176aa662cSKarthik Bhat //
1276aa662cSKarthik Bhat //===----------------------------------------------------------------------===//
1376aa662cSKarthik Bhat 
142f2bd8caSAdam Nemet #include "llvm/Transforms/Utils/LoopUtils.h"
154a000883SChandler Carruth #include "llvm/ADT/ScopeExit.h"
1631088a9dSChandler Carruth #include "llvm/Analysis/AliasAnalysis.h"
1731088a9dSChandler Carruth #include "llvm/Analysis/BasicAliasAnalysis.h"
1831088a9dSChandler Carruth #include "llvm/Analysis/GlobalsModRef.h"
19a21d5f1eSPhilip Reames #include "llvm/Analysis/InstructionSimplify.h"
202f2bd8caSAdam Nemet #include "llvm/Analysis/LoopInfo.h"
21c3ccf5d7SIgor Laevsky #include "llvm/Analysis/LoopPass.h"
22*23aed5efSPhilip Reames #include "llvm/Analysis/MustExecute.h"
2345d4cb9aSWeiming Zhao #include "llvm/Analysis/ScalarEvolution.h"
242f2bd8caSAdam Nemet #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
25c434d091SElena Demikhovsky #include "llvm/Analysis/ScalarEvolutionExpander.h"
2645d4cb9aSWeiming Zhao #include "llvm/Analysis/ScalarEvolutionExpressions.h"
276bda14b3SChandler Carruth #include "llvm/Analysis/TargetTransformInfo.h"
28a097bc69SChad Rosier #include "llvm/Analysis/ValueTracking.h"
2931088a9dSChandler Carruth #include "llvm/IR/Dominators.h"
3076aa662cSKarthik Bhat #include "llvm/IR/Instructions.h"
3145d4cb9aSWeiming Zhao #include "llvm/IR/Module.h"
3276aa662cSKarthik Bhat #include "llvm/IR/PatternMatch.h"
3376aa662cSKarthik Bhat #include "llvm/IR/ValueHandle.h"
3431088a9dSChandler Carruth #include "llvm/Pass.h"
3576aa662cSKarthik Bhat #include "llvm/Support/Debug.h"
36a097bc69SChad Rosier #include "llvm/Support/KnownBits.h"
374a000883SChandler Carruth #include "llvm/Transforms/Utils/BasicBlockUtils.h"
3876aa662cSKarthik Bhat 
3976aa662cSKarthik Bhat using namespace llvm;
4076aa662cSKarthik Bhat using namespace llvm::PatternMatch;
4176aa662cSKarthik Bhat 
4276aa662cSKarthik Bhat #define DEBUG_TYPE "loop-utils"
4376aa662cSKarthik Bhat 
440a91310cSTyler Nowicki bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
4576aa662cSKarthik Bhat                                         SmallPtrSetImpl<Instruction *> &Set) {
4676aa662cSKarthik Bhat   for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
4776aa662cSKarthik Bhat     if (!Set.count(dyn_cast<Instruction>(*Use)))
4876aa662cSKarthik Bhat       return false;
4976aa662cSKarthik Bhat   return true;
5076aa662cSKarthik Bhat }
5176aa662cSKarthik Bhat 
52c94f8e29SChad Rosier bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) {
53c94f8e29SChad Rosier   switch (Kind) {
54c94f8e29SChad Rosier   default:
55c94f8e29SChad Rosier     break;
56c94f8e29SChad Rosier   case RK_IntegerAdd:
57c94f8e29SChad Rosier   case RK_IntegerMult:
58c94f8e29SChad Rosier   case RK_IntegerOr:
59c94f8e29SChad Rosier   case RK_IntegerAnd:
60c94f8e29SChad Rosier   case RK_IntegerXor:
61c94f8e29SChad Rosier   case RK_IntegerMinMax:
62c94f8e29SChad Rosier     return true;
63c94f8e29SChad Rosier   }
64c94f8e29SChad Rosier   return false;
65c94f8e29SChad Rosier }
66c94f8e29SChad Rosier 
67c94f8e29SChad Rosier bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) {
68c94f8e29SChad Rosier   return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
69c94f8e29SChad Rosier }
70c94f8e29SChad Rosier 
71c94f8e29SChad Rosier bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) {
72c94f8e29SChad Rosier   switch (Kind) {
73c94f8e29SChad Rosier   default:
74c94f8e29SChad Rosier     break;
75c94f8e29SChad Rosier   case RK_IntegerAdd:
76c94f8e29SChad Rosier   case RK_IntegerMult:
77c94f8e29SChad Rosier   case RK_FloatAdd:
78c94f8e29SChad Rosier   case RK_FloatMult:
79c94f8e29SChad Rosier     return true;
80c94f8e29SChad Rosier   }
81c94f8e29SChad Rosier   return false;
82c94f8e29SChad Rosier }
83c94f8e29SChad Rosier 
84a097bc69SChad Rosier /// Determines if Phi may have been type-promoted. If Phi has a single user
85a097bc69SChad Rosier /// that ANDs the Phi with a type mask, return the user. RT is updated to
86a097bc69SChad Rosier /// account for the narrower bit width represented by the mask, and the AND
87a097bc69SChad Rosier /// instruction is added to CI.
88a097bc69SChad Rosier static Instruction *lookThroughAnd(PHINode *Phi, Type *&RT,
89c94f8e29SChad Rosier                                    SmallPtrSetImpl<Instruction *> &Visited,
90c94f8e29SChad Rosier                                    SmallPtrSetImpl<Instruction *> &CI) {
91c94f8e29SChad Rosier   if (!Phi->hasOneUse())
92c94f8e29SChad Rosier     return Phi;
93c94f8e29SChad Rosier 
94c94f8e29SChad Rosier   const APInt *M = nullptr;
95c94f8e29SChad Rosier   Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
96c94f8e29SChad Rosier 
97c94f8e29SChad Rosier   // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
98c94f8e29SChad Rosier   // with a new integer type of the corresponding bit width.
9972ee6945SCraig Topper   if (match(J, m_c_And(m_Instruction(I), m_APInt(M)))) {
100c94f8e29SChad Rosier     int32_t Bits = (*M + 1).exactLogBase2();
101c94f8e29SChad Rosier     if (Bits > 0) {
102c94f8e29SChad Rosier       RT = IntegerType::get(Phi->getContext(), Bits);
103c94f8e29SChad Rosier       Visited.insert(Phi);
104c94f8e29SChad Rosier       CI.insert(J);
105c94f8e29SChad Rosier       return J;
106c94f8e29SChad Rosier     }
107c94f8e29SChad Rosier   }
108c94f8e29SChad Rosier   return Phi;
109c94f8e29SChad Rosier }
110c94f8e29SChad Rosier 
111a097bc69SChad Rosier /// Compute the minimal bit width needed to represent a reduction whose exit
112a097bc69SChad Rosier /// instruction is given by Exit.
113a097bc69SChad Rosier static std::pair<Type *, bool> computeRecurrenceType(Instruction *Exit,
114a097bc69SChad Rosier                                                      DemandedBits *DB,
115a097bc69SChad Rosier                                                      AssumptionCache *AC,
116a097bc69SChad Rosier                                                      DominatorTree *DT) {
117a097bc69SChad Rosier   bool IsSigned = false;
118a097bc69SChad Rosier   const DataLayout &DL = Exit->getModule()->getDataLayout();
119a097bc69SChad Rosier   uint64_t MaxBitWidth = DL.getTypeSizeInBits(Exit->getType());
120a097bc69SChad Rosier 
121a097bc69SChad Rosier   if (DB) {
122a097bc69SChad Rosier     // Use the demanded bits analysis to determine the bits that are live out
123a097bc69SChad Rosier     // of the exit instruction, rounding up to the nearest power of two. If the
124a097bc69SChad Rosier     // use of demanded bits results in a smaller bit width, we know the value
125a097bc69SChad Rosier     // must be positive (i.e., IsSigned = false), because if this were not the
126a097bc69SChad Rosier     // case, the sign bit would have been demanded.
127a097bc69SChad Rosier     auto Mask = DB->getDemandedBits(Exit);
128a097bc69SChad Rosier     MaxBitWidth = Mask.getBitWidth() - Mask.countLeadingZeros();
129a097bc69SChad Rosier   }
130a097bc69SChad Rosier 
131a097bc69SChad Rosier   if (MaxBitWidth == DL.getTypeSizeInBits(Exit->getType()) && AC && DT) {
132a097bc69SChad Rosier     // If demanded bits wasn't able to limit the bit width, we can try to use
133a097bc69SChad Rosier     // value tracking instead. This can be the case, for example, if the value
134a097bc69SChad Rosier     // may be negative.
135a097bc69SChad Rosier     auto NumSignBits = ComputeNumSignBits(Exit, DL, 0, AC, nullptr, DT);
136a097bc69SChad Rosier     auto NumTypeBits = DL.getTypeSizeInBits(Exit->getType());
137a097bc69SChad Rosier     MaxBitWidth = NumTypeBits - NumSignBits;
138a097bc69SChad Rosier     KnownBits Bits = computeKnownBits(Exit, DL);
139a097bc69SChad Rosier     if (!Bits.isNonNegative()) {
140a097bc69SChad Rosier       // If the value is not known to be non-negative, we set IsSigned to true,
141a097bc69SChad Rosier       // meaning that we will use sext instructions instead of zext
142a097bc69SChad Rosier       // instructions to restore the original type.
143a097bc69SChad Rosier       IsSigned = true;
144a097bc69SChad Rosier       if (!Bits.isNegative())
145a097bc69SChad Rosier         // If the value is not known to be negative, we don't known what the
146a097bc69SChad Rosier         // upper bit is, and therefore, we don't know what kind of extend we
147a097bc69SChad Rosier         // will need. In this case, just increase the bit width by one bit and
148a097bc69SChad Rosier         // use sext.
149a097bc69SChad Rosier         ++MaxBitWidth;
150a097bc69SChad Rosier     }
151a097bc69SChad Rosier   }
152a097bc69SChad Rosier   if (!isPowerOf2_64(MaxBitWidth))
153a097bc69SChad Rosier     MaxBitWidth = NextPowerOf2(MaxBitWidth);
154a097bc69SChad Rosier 
155a097bc69SChad Rosier   return std::make_pair(Type::getIntNTy(Exit->getContext(), MaxBitWidth),
156a097bc69SChad Rosier                         IsSigned);
157a097bc69SChad Rosier }
158a097bc69SChad Rosier 
159a097bc69SChad Rosier /// Collect cast instructions that can be ignored in the vectorizer's cost
160a097bc69SChad Rosier /// model, given a reduction exit value and the minimal type in which the
161a097bc69SChad Rosier /// reduction can be represented.
162a097bc69SChad Rosier static void collectCastsToIgnore(Loop *TheLoop, Instruction *Exit,
163a097bc69SChad Rosier                                  Type *RecurrenceType,
164a097bc69SChad Rosier                                  SmallPtrSetImpl<Instruction *> &Casts) {
165c94f8e29SChad Rosier 
166c94f8e29SChad Rosier   SmallVector<Instruction *, 8> Worklist;
167a097bc69SChad Rosier   SmallPtrSet<Instruction *, 8> Visited;
168c94f8e29SChad Rosier   Worklist.push_back(Exit);
169c94f8e29SChad Rosier 
170c94f8e29SChad Rosier   while (!Worklist.empty()) {
171a097bc69SChad Rosier     Instruction *Val = Worklist.pop_back_val();
172a097bc69SChad Rosier     Visited.insert(Val);
173a097bc69SChad Rosier     if (auto *Cast = dyn_cast<CastInst>(Val))
174a097bc69SChad Rosier       if (Cast->getSrcTy() == RecurrenceType) {
175a097bc69SChad Rosier         // If the source type of a cast instruction is equal to the recurrence
176a097bc69SChad Rosier         // type, it will be eliminated, and should be ignored in the vectorizer
17729dc0f70SMatthew Simpson         // cost model.
178a097bc69SChad Rosier         Casts.insert(Cast);
179a097bc69SChad Rosier         continue;
180c94f8e29SChad Rosier       }
181a097bc69SChad Rosier 
182a097bc69SChad Rosier     // Add all operands to the work list if they are loop-varying values that
183a097bc69SChad Rosier     // we haven't yet visited.
184a097bc69SChad Rosier     for (Value *O : cast<User>(Val)->operands())
185a097bc69SChad Rosier       if (auto *I = dyn_cast<Instruction>(O))
186a097bc69SChad Rosier         if (TheLoop->contains(I) && !Visited.count(I))
187a097bc69SChad Rosier           Worklist.push_back(I);
188c94f8e29SChad Rosier   }
189c94f8e29SChad Rosier }
190c94f8e29SChad Rosier 
1910a91310cSTyler Nowicki bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind,
19276aa662cSKarthik Bhat                                            Loop *TheLoop, bool HasFunNoNaNAttr,
193a097bc69SChad Rosier                                            RecurrenceDescriptor &RedDes,
194a097bc69SChad Rosier                                            DemandedBits *DB,
195a097bc69SChad Rosier                                            AssumptionCache *AC,
196a097bc69SChad Rosier                                            DominatorTree *DT) {
19776aa662cSKarthik Bhat   if (Phi->getNumIncomingValues() != 2)
19876aa662cSKarthik Bhat     return false;
19976aa662cSKarthik Bhat 
20076aa662cSKarthik Bhat   // Reduction variables are only found in the loop header block.
20176aa662cSKarthik Bhat   if (Phi->getParent() != TheLoop->getHeader())
20276aa662cSKarthik Bhat     return false;
20376aa662cSKarthik Bhat 
20476aa662cSKarthik Bhat   // Obtain the reduction start value from the value that comes from the loop
20576aa662cSKarthik Bhat   // preheader.
20676aa662cSKarthik Bhat   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
20776aa662cSKarthik Bhat 
20876aa662cSKarthik Bhat   // ExitInstruction is the single value which is used outside the loop.
20976aa662cSKarthik Bhat   // We only allow for a single reduction value to be used outside the loop.
21076aa662cSKarthik Bhat   // This includes users of the reduction, variables (which form a cycle
21176aa662cSKarthik Bhat   // which ends in the phi node).
21276aa662cSKarthik Bhat   Instruction *ExitInstruction = nullptr;
21376aa662cSKarthik Bhat   // Indicates that we found a reduction operation in our scan.
21476aa662cSKarthik Bhat   bool FoundReduxOp = false;
21576aa662cSKarthik Bhat 
21676aa662cSKarthik Bhat   // We start with the PHI node and scan for all of the users of this
21776aa662cSKarthik Bhat   // instruction. All users must be instructions that can be used as reduction
21876aa662cSKarthik Bhat   // variables (such as ADD). We must have a single out-of-block user. The cycle
21976aa662cSKarthik Bhat   // must include the original PHI.
22076aa662cSKarthik Bhat   bool FoundStartPHI = false;
22176aa662cSKarthik Bhat 
22276aa662cSKarthik Bhat   // To recognize min/max patterns formed by a icmp select sequence, we store
22376aa662cSKarthik Bhat   // the number of instruction we saw from the recognized min/max pattern,
22476aa662cSKarthik Bhat   //  to make sure we only see exactly the two instructions.
22576aa662cSKarthik Bhat   unsigned NumCmpSelectPatternInst = 0;
22627b2c39eSTyler Nowicki   InstDesc ReduxDesc(false, nullptr);
22776aa662cSKarthik Bhat 
228c94f8e29SChad Rosier   // Data used for determining if the recurrence has been type-promoted.
229c94f8e29SChad Rosier   Type *RecurrenceType = Phi->getType();
230c94f8e29SChad Rosier   SmallPtrSet<Instruction *, 4> CastInsts;
231c94f8e29SChad Rosier   Instruction *Start = Phi;
232c94f8e29SChad Rosier   bool IsSigned = false;
233c94f8e29SChad Rosier 
23476aa662cSKarthik Bhat   SmallPtrSet<Instruction *, 8> VisitedInsts;
23576aa662cSKarthik Bhat   SmallVector<Instruction *, 8> Worklist;
236c94f8e29SChad Rosier 
237c94f8e29SChad Rosier   // Return early if the recurrence kind does not match the type of Phi. If the
238c94f8e29SChad Rosier   // recurrence kind is arithmetic, we attempt to look through AND operations
239c94f8e29SChad Rosier   // resulting from the type promotion performed by InstCombine.  Vector
240c94f8e29SChad Rosier   // operations are not limited to the legal integer widths, so we may be able
241c94f8e29SChad Rosier   // to evaluate the reduction in the narrower width.
242c94f8e29SChad Rosier   if (RecurrenceType->isFloatingPointTy()) {
243c94f8e29SChad Rosier     if (!isFloatingPointRecurrenceKind(Kind))
244c94f8e29SChad Rosier       return false;
245c94f8e29SChad Rosier   } else {
246c94f8e29SChad Rosier     if (!isIntegerRecurrenceKind(Kind))
247c94f8e29SChad Rosier       return false;
248c94f8e29SChad Rosier     if (isArithmeticRecurrenceKind(Kind))
249c94f8e29SChad Rosier       Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
250c94f8e29SChad Rosier   }
251c94f8e29SChad Rosier 
252c94f8e29SChad Rosier   Worklist.push_back(Start);
253c94f8e29SChad Rosier   VisitedInsts.insert(Start);
25476aa662cSKarthik Bhat 
25576aa662cSKarthik Bhat   // A value in the reduction can be used:
25676aa662cSKarthik Bhat   //  - By the reduction:
25776aa662cSKarthik Bhat   //      - Reduction operation:
25876aa662cSKarthik Bhat   //        - One use of reduction value (safe).
25976aa662cSKarthik Bhat   //        - Multiple use of reduction value (not safe).
26076aa662cSKarthik Bhat   //      - PHI:
26176aa662cSKarthik Bhat   //        - All uses of the PHI must be the reduction (safe).
26276aa662cSKarthik Bhat   //        - Otherwise, not safe.
2637cefb409SMichael Kuperstein   //  - By instructions outside of the loop (safe).
2647cefb409SMichael Kuperstein   //      * One value may have several outside users, but all outside
2657cefb409SMichael Kuperstein   //        uses must be of the same value.
26676aa662cSKarthik Bhat   //  - By an instruction that is not part of the reduction (not safe).
26776aa662cSKarthik Bhat   //    This is either:
26876aa662cSKarthik Bhat   //      * An instruction type other than PHI or the reduction operation.
26976aa662cSKarthik Bhat   //      * A PHI in the header other than the initial PHI.
27076aa662cSKarthik Bhat   while (!Worklist.empty()) {
27176aa662cSKarthik Bhat     Instruction *Cur = Worklist.back();
27276aa662cSKarthik Bhat     Worklist.pop_back();
27376aa662cSKarthik Bhat 
27476aa662cSKarthik Bhat     // No Users.
27576aa662cSKarthik Bhat     // If the instruction has no users then this is a broken chain and can't be
27676aa662cSKarthik Bhat     // a reduction variable.
27776aa662cSKarthik Bhat     if (Cur->use_empty())
27876aa662cSKarthik Bhat       return false;
27976aa662cSKarthik Bhat 
28076aa662cSKarthik Bhat     bool IsAPhi = isa<PHINode>(Cur);
28176aa662cSKarthik Bhat 
28276aa662cSKarthik Bhat     // A header PHI use other than the original PHI.
28376aa662cSKarthik Bhat     if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
28476aa662cSKarthik Bhat       return false;
28576aa662cSKarthik Bhat 
28676aa662cSKarthik Bhat     // Reductions of instructions such as Div, and Sub is only possible if the
28776aa662cSKarthik Bhat     // LHS is the reduction variable.
28876aa662cSKarthik Bhat     if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
28976aa662cSKarthik Bhat         !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
29076aa662cSKarthik Bhat         !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
29176aa662cSKarthik Bhat       return false;
29276aa662cSKarthik Bhat 
293c94f8e29SChad Rosier     // Any reduction instruction must be of one of the allowed kinds. We ignore
294c94f8e29SChad Rosier     // the starting value (the Phi or an AND instruction if the Phi has been
295c94f8e29SChad Rosier     // type-promoted).
296c94f8e29SChad Rosier     if (Cur != Start) {
2970a91310cSTyler Nowicki       ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
2980a91310cSTyler Nowicki       if (!ReduxDesc.isRecurrence())
29976aa662cSKarthik Bhat         return false;
300c94f8e29SChad Rosier     }
30176aa662cSKarthik Bhat 
30276aa662cSKarthik Bhat     // A reduction operation must only have one use of the reduction value.
30376aa662cSKarthik Bhat     if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
30476aa662cSKarthik Bhat         hasMultipleUsesOf(Cur, VisitedInsts))
30576aa662cSKarthik Bhat       return false;
30676aa662cSKarthik Bhat 
30776aa662cSKarthik Bhat     // All inputs to a PHI node must be a reduction value.
30876aa662cSKarthik Bhat     if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
30976aa662cSKarthik Bhat       return false;
31076aa662cSKarthik Bhat 
31176aa662cSKarthik Bhat     if (Kind == RK_IntegerMinMax &&
31276aa662cSKarthik Bhat         (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
31376aa662cSKarthik Bhat       ++NumCmpSelectPatternInst;
31476aa662cSKarthik Bhat     if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
31576aa662cSKarthik Bhat       ++NumCmpSelectPatternInst;
31676aa662cSKarthik Bhat 
31776aa662cSKarthik Bhat     // Check  whether we found a reduction operator.
318c94f8e29SChad Rosier     FoundReduxOp |= !IsAPhi && Cur != Start;
31976aa662cSKarthik Bhat 
32076aa662cSKarthik Bhat     // Process users of current instruction. Push non-PHI nodes after PHI nodes
32176aa662cSKarthik Bhat     // onto the stack. This way we are going to have seen all inputs to PHI
32276aa662cSKarthik Bhat     // nodes once we get to them.
32376aa662cSKarthik Bhat     SmallVector<Instruction *, 8> NonPHIs;
32476aa662cSKarthik Bhat     SmallVector<Instruction *, 8> PHIs;
32576aa662cSKarthik Bhat     for (User *U : Cur->users()) {
32676aa662cSKarthik Bhat       Instruction *UI = cast<Instruction>(U);
32776aa662cSKarthik Bhat 
32876aa662cSKarthik Bhat       // Check if we found the exit user.
32976aa662cSKarthik Bhat       BasicBlock *Parent = UI->getParent();
33076aa662cSKarthik Bhat       if (!TheLoop->contains(Parent)) {
3317cefb409SMichael Kuperstein         // If we already know this instruction is used externally, move on to
3327cefb409SMichael Kuperstein         // the next user.
3337cefb409SMichael Kuperstein         if (ExitInstruction == Cur)
3347cefb409SMichael Kuperstein           continue;
3357cefb409SMichael Kuperstein 
3367cefb409SMichael Kuperstein         // Exit if you find multiple values used outside or if the header phi
3377cefb409SMichael Kuperstein         // node is being used. In this case the user uses the value of the
3387cefb409SMichael Kuperstein         // previous iteration, in which case we would loose "VF-1" iterations of
3397cefb409SMichael Kuperstein         // the reduction operation if we vectorize.
34076aa662cSKarthik Bhat         if (ExitInstruction != nullptr || Cur == Phi)
34176aa662cSKarthik Bhat           return false;
34276aa662cSKarthik Bhat 
34376aa662cSKarthik Bhat         // The instruction used by an outside user must be the last instruction
34476aa662cSKarthik Bhat         // before we feed back to the reduction phi. Otherwise, we loose VF-1
34576aa662cSKarthik Bhat         // operations on the value.
34642531260SDavid Majnemer         if (!is_contained(Phi->operands(), Cur))
34776aa662cSKarthik Bhat           return false;
34876aa662cSKarthik Bhat 
34976aa662cSKarthik Bhat         ExitInstruction = Cur;
35076aa662cSKarthik Bhat         continue;
35176aa662cSKarthik Bhat       }
35276aa662cSKarthik Bhat 
35376aa662cSKarthik Bhat       // Process instructions only once (termination). Each reduction cycle
35476aa662cSKarthik Bhat       // value must only be used once, except by phi nodes and min/max
35576aa662cSKarthik Bhat       // reductions which are represented as a cmp followed by a select.
35627b2c39eSTyler Nowicki       InstDesc IgnoredVal(false, nullptr);
35776aa662cSKarthik Bhat       if (VisitedInsts.insert(UI).second) {
35876aa662cSKarthik Bhat         if (isa<PHINode>(UI))
35976aa662cSKarthik Bhat           PHIs.push_back(UI);
36076aa662cSKarthik Bhat         else
36176aa662cSKarthik Bhat           NonPHIs.push_back(UI);
36276aa662cSKarthik Bhat       } else if (!isa<PHINode>(UI) &&
36376aa662cSKarthik Bhat                  ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
36476aa662cSKarthik Bhat                    !isa<SelectInst>(UI)) ||
3650a91310cSTyler Nowicki                   !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence()))
36676aa662cSKarthik Bhat         return false;
36776aa662cSKarthik Bhat 
36876aa662cSKarthik Bhat       // Remember that we completed the cycle.
36976aa662cSKarthik Bhat       if (UI == Phi)
37076aa662cSKarthik Bhat         FoundStartPHI = true;
37176aa662cSKarthik Bhat     }
37276aa662cSKarthik Bhat     Worklist.append(PHIs.begin(), PHIs.end());
37376aa662cSKarthik Bhat     Worklist.append(NonPHIs.begin(), NonPHIs.end());
37476aa662cSKarthik Bhat   }
37576aa662cSKarthik Bhat 
37676aa662cSKarthik Bhat   // This means we have seen one but not the other instruction of the
37776aa662cSKarthik Bhat   // pattern or more than just a select and cmp.
37876aa662cSKarthik Bhat   if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
37976aa662cSKarthik Bhat       NumCmpSelectPatternInst != 2)
38076aa662cSKarthik Bhat     return false;
38176aa662cSKarthik Bhat 
38276aa662cSKarthik Bhat   if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
38376aa662cSKarthik Bhat     return false;
38476aa662cSKarthik Bhat 
385a097bc69SChad Rosier   if (Start != Phi) {
386a097bc69SChad Rosier     // If the starting value is not the same as the phi node, we speculatively
387a097bc69SChad Rosier     // looked through an 'and' instruction when evaluating a potential
388a097bc69SChad Rosier     // arithmetic reduction to determine if it may have been type-promoted.
389a097bc69SChad Rosier     //
390a097bc69SChad Rosier     // We now compute the minimal bit width that is required to represent the
391a097bc69SChad Rosier     // reduction. If this is the same width that was indicated by the 'and', we
392a097bc69SChad Rosier     // can represent the reduction in the smaller type. The 'and' instruction
393a097bc69SChad Rosier     // will be eliminated since it will essentially be a cast instruction that
394a097bc69SChad Rosier     // can be ignore in the cost model. If we compute a different type than we
395a097bc69SChad Rosier     // did when evaluating the 'and', the 'and' will not be eliminated, and we
396a097bc69SChad Rosier     // will end up with different kinds of operations in the recurrence
397a097bc69SChad Rosier     // expression (e.g., RK_IntegerAND, RK_IntegerADD). We give up if this is
398a097bc69SChad Rosier     // the case.
399a097bc69SChad Rosier     //
400a097bc69SChad Rosier     // The vectorizer relies on InstCombine to perform the actual
401a097bc69SChad Rosier     // type-shrinking. It does this by inserting instructions to truncate the
402a097bc69SChad Rosier     // exit value of the reduction to the width indicated by RecurrenceType and
403a097bc69SChad Rosier     // then extend this value back to the original width. If IsSigned is false,
404a097bc69SChad Rosier     // a 'zext' instruction will be generated; otherwise, a 'sext' will be
405a097bc69SChad Rosier     // used.
406a097bc69SChad Rosier     //
407a097bc69SChad Rosier     // TODO: We should not rely on InstCombine to rewrite the reduction in the
408a097bc69SChad Rosier     //       smaller type. We should just generate a correctly typed expression
409a097bc69SChad Rosier     //       to begin with.
410a097bc69SChad Rosier     Type *ComputedType;
411a097bc69SChad Rosier     std::tie(ComputedType, IsSigned) =
412a097bc69SChad Rosier         computeRecurrenceType(ExitInstruction, DB, AC, DT);
413a097bc69SChad Rosier     if (ComputedType != RecurrenceType)
414c94f8e29SChad Rosier       return false;
415c94f8e29SChad Rosier 
416a097bc69SChad Rosier     // The recurrence expression will be represented in a narrower type. If
417a097bc69SChad Rosier     // there are any cast instructions that will be unnecessary, collect them
418a097bc69SChad Rosier     // in CastInsts. Note that the 'and' instruction was already included in
419a097bc69SChad Rosier     // this list.
420a097bc69SChad Rosier     //
421a097bc69SChad Rosier     // TODO: A better way to represent this may be to tag in some way all the
422a097bc69SChad Rosier     //       instructions that are a part of the reduction. The vectorizer cost
423a097bc69SChad Rosier     //       model could then apply the recurrence type to these instructions,
424a097bc69SChad Rosier     //       without needing a white list of instructions to ignore.
425a097bc69SChad Rosier     collectCastsToIgnore(TheLoop, ExitInstruction, RecurrenceType, CastInsts);
426a097bc69SChad Rosier   }
427a097bc69SChad Rosier 
42876aa662cSKarthik Bhat   // We found a reduction var if we have reached the original phi node and we
42976aa662cSKarthik Bhat   // only have a single instruction with out-of-loop users.
43076aa662cSKarthik Bhat 
43176aa662cSKarthik Bhat   // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
4320a91310cSTyler Nowicki   // is saved as part of the RecurrenceDescriptor.
43376aa662cSKarthik Bhat 
43476aa662cSKarthik Bhat   // Save the description of this reduction variable.
435c94f8e29SChad Rosier   RecurrenceDescriptor RD(
436c94f8e29SChad Rosier       RdxStart, ExitInstruction, Kind, ReduxDesc.getMinMaxKind(),
437c94f8e29SChad Rosier       ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts);
43876aa662cSKarthik Bhat   RedDes = RD;
43976aa662cSKarthik Bhat 
44076aa662cSKarthik Bhat   return true;
44176aa662cSKarthik Bhat }
44276aa662cSKarthik Bhat 
44376aa662cSKarthik Bhat /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
44476aa662cSKarthik Bhat /// pattern corresponding to a min(X, Y) or max(X, Y).
44527b2c39eSTyler Nowicki RecurrenceDescriptor::InstDesc
44627b2c39eSTyler Nowicki RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) {
44776aa662cSKarthik Bhat 
44876aa662cSKarthik Bhat   assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
44976aa662cSKarthik Bhat          "Expect a select instruction");
45076aa662cSKarthik Bhat   Instruction *Cmp = nullptr;
45176aa662cSKarthik Bhat   SelectInst *Select = nullptr;
45276aa662cSKarthik Bhat 
45376aa662cSKarthik Bhat   // We must handle the select(cmp()) as a single instruction. Advance to the
45476aa662cSKarthik Bhat   // select.
45576aa662cSKarthik Bhat   if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
45676aa662cSKarthik Bhat     if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
45727b2c39eSTyler Nowicki       return InstDesc(false, I);
45827b2c39eSTyler Nowicki     return InstDesc(Select, Prev.getMinMaxKind());
45976aa662cSKarthik Bhat   }
46076aa662cSKarthik Bhat 
46176aa662cSKarthik Bhat   // Only handle single use cases for now.
46276aa662cSKarthik Bhat   if (!(Select = dyn_cast<SelectInst>(I)))
46327b2c39eSTyler Nowicki     return InstDesc(false, I);
46476aa662cSKarthik Bhat   if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
46576aa662cSKarthik Bhat       !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
46627b2c39eSTyler Nowicki     return InstDesc(false, I);
46776aa662cSKarthik Bhat   if (!Cmp->hasOneUse())
46827b2c39eSTyler Nowicki     return InstDesc(false, I);
46976aa662cSKarthik Bhat 
47076aa662cSKarthik Bhat   Value *CmpLeft;
47176aa662cSKarthik Bhat   Value *CmpRight;
47276aa662cSKarthik Bhat 
47376aa662cSKarthik Bhat   // Look for a min/max pattern.
47476aa662cSKarthik Bhat   if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
47527b2c39eSTyler Nowicki     return InstDesc(Select, MRK_UIntMin);
47676aa662cSKarthik Bhat   else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
47727b2c39eSTyler Nowicki     return InstDesc(Select, MRK_UIntMax);
47876aa662cSKarthik Bhat   else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
47927b2c39eSTyler Nowicki     return InstDesc(Select, MRK_SIntMax);
48076aa662cSKarthik Bhat   else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
48127b2c39eSTyler Nowicki     return InstDesc(Select, MRK_SIntMin);
48276aa662cSKarthik Bhat   else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
48327b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMin);
48476aa662cSKarthik Bhat   else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
48527b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMax);
48676aa662cSKarthik Bhat   else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
48727b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMin);
48876aa662cSKarthik Bhat   else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
48927b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMax);
49076aa662cSKarthik Bhat 
49127b2c39eSTyler Nowicki   return InstDesc(false, I);
49276aa662cSKarthik Bhat }
49376aa662cSKarthik Bhat 
49427b2c39eSTyler Nowicki RecurrenceDescriptor::InstDesc
4950a91310cSTyler Nowicki RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
49627b2c39eSTyler Nowicki                                         InstDesc &Prev, bool HasFunNoNaNAttr) {
49776aa662cSKarthik Bhat   bool FP = I->getType()->isFloatingPointTy();
498c1a86f58STyler Nowicki   Instruction *UAI = Prev.getUnsafeAlgebraInst();
499629c4115SSanjay Patel   if (!UAI && FP && !I->isFast())
500c1a86f58STyler Nowicki     UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
501c1a86f58STyler Nowicki 
50276aa662cSKarthik Bhat   switch (I->getOpcode()) {
50376aa662cSKarthik Bhat   default:
50427b2c39eSTyler Nowicki     return InstDesc(false, I);
50576aa662cSKarthik Bhat   case Instruction::PHI:
50610a1e8b1STim Northover     return InstDesc(I, Prev.getMinMaxKind(), Prev.getUnsafeAlgebraInst());
50776aa662cSKarthik Bhat   case Instruction::Sub:
50876aa662cSKarthik Bhat   case Instruction::Add:
50927b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerAdd, I);
51076aa662cSKarthik Bhat   case Instruction::Mul:
51127b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerMult, I);
51276aa662cSKarthik Bhat   case Instruction::And:
51327b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerAnd, I);
51476aa662cSKarthik Bhat   case Instruction::Or:
51527b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerOr, I);
51676aa662cSKarthik Bhat   case Instruction::Xor:
51727b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerXor, I);
51876aa662cSKarthik Bhat   case Instruction::FMul:
519c1a86f58STyler Nowicki     return InstDesc(Kind == RK_FloatMult, I, UAI);
52076aa662cSKarthik Bhat   case Instruction::FSub:
52176aa662cSKarthik Bhat   case Instruction::FAdd:
522c1a86f58STyler Nowicki     return InstDesc(Kind == RK_FloatAdd, I, UAI);
52376aa662cSKarthik Bhat   case Instruction::FCmp:
52476aa662cSKarthik Bhat   case Instruction::ICmp:
52576aa662cSKarthik Bhat   case Instruction::Select:
52676aa662cSKarthik Bhat     if (Kind != RK_IntegerMinMax &&
52776aa662cSKarthik Bhat         (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
52827b2c39eSTyler Nowicki       return InstDesc(false, I);
52976aa662cSKarthik Bhat     return isMinMaxSelectCmpPattern(I, Prev);
53076aa662cSKarthik Bhat   }
53176aa662cSKarthik Bhat }
53276aa662cSKarthik Bhat 
5330a91310cSTyler Nowicki bool RecurrenceDescriptor::hasMultipleUsesOf(
53476aa662cSKarthik Bhat     Instruction *I, SmallPtrSetImpl<Instruction *> &Insts) {
53576aa662cSKarthik Bhat   unsigned NumUses = 0;
53676aa662cSKarthik Bhat   for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
53776aa662cSKarthik Bhat        ++Use) {
53876aa662cSKarthik Bhat     if (Insts.count(dyn_cast<Instruction>(*Use)))
53976aa662cSKarthik Bhat       ++NumUses;
54076aa662cSKarthik Bhat     if (NumUses > 1)
54176aa662cSKarthik Bhat       return true;
54276aa662cSKarthik Bhat   }
54376aa662cSKarthik Bhat 
54476aa662cSKarthik Bhat   return false;
54576aa662cSKarthik Bhat }
5460a91310cSTyler Nowicki bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
547a097bc69SChad Rosier                                           RecurrenceDescriptor &RedDes,
548a097bc69SChad Rosier                                           DemandedBits *DB, AssumptionCache *AC,
549a097bc69SChad Rosier                                           DominatorTree *DT) {
55076aa662cSKarthik Bhat 
55176aa662cSKarthik Bhat   BasicBlock *Header = TheLoop->getHeader();
55276aa662cSKarthik Bhat   Function &F = *Header->getParent();
5538dd66e57SNirav Dave   bool HasFunNoNaNAttr =
55476aa662cSKarthik Bhat       F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
55576aa662cSKarthik Bhat 
556a097bc69SChad Rosier   if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
557a097bc69SChad Rosier                       AC, DT)) {
55876aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
55976aa662cSKarthik Bhat     return true;
56076aa662cSKarthik Bhat   }
561a097bc69SChad Rosier   if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes, DB,
562a097bc69SChad Rosier                       AC, DT)) {
56376aa662cSKarthik Bhat     DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
56476aa662cSKarthik Bhat     return true;
56576aa662cSKarthik Bhat   }
566a097bc69SChad Rosier   if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes, DB,
567a097bc69SChad Rosier                       AC, DT)) {
56876aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
56976aa662cSKarthik Bhat     return true;
57076aa662cSKarthik Bhat   }
571a097bc69SChad Rosier   if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
572a097bc69SChad Rosier                       AC, DT)) {
57376aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
57476aa662cSKarthik Bhat     return true;
57576aa662cSKarthik Bhat   }
576a097bc69SChad Rosier   if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes, DB,
577a097bc69SChad Rosier                       AC, DT)) {
57876aa662cSKarthik Bhat     DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
57976aa662cSKarthik Bhat     return true;
58076aa662cSKarthik Bhat   }
581a097bc69SChad Rosier   if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr, RedDes,
582a097bc69SChad Rosier                       DB, AC, DT)) {
58376aa662cSKarthik Bhat     DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
58476aa662cSKarthik Bhat     return true;
58576aa662cSKarthik Bhat   }
586a097bc69SChad Rosier   if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes, DB,
587a097bc69SChad Rosier                       AC, DT)) {
58876aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
58976aa662cSKarthik Bhat     return true;
59076aa662cSKarthik Bhat   }
591a097bc69SChad Rosier   if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
592a097bc69SChad Rosier                       AC, DT)) {
59376aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
59476aa662cSKarthik Bhat     return true;
59576aa662cSKarthik Bhat   }
596a097bc69SChad Rosier   if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes, DB,
597a097bc69SChad Rosier                       AC, DT)) {
59876aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi << "\n");
59976aa662cSKarthik Bhat     return true;
60076aa662cSKarthik Bhat   }
60176aa662cSKarthik Bhat   // Not a reduction of known type.
60276aa662cSKarthik Bhat   return false;
60376aa662cSKarthik Bhat }
60476aa662cSKarthik Bhat 
6052ff59d43SAyal Zaks bool RecurrenceDescriptor::isFirstOrderRecurrence(
6062ff59d43SAyal Zaks     PHINode *Phi, Loop *TheLoop,
6072ff59d43SAyal Zaks     DenseMap<Instruction *, Instruction *> &SinkAfter, DominatorTree *DT) {
60829c997c1SMatthew Simpson 
60929c997c1SMatthew Simpson   // Ensure the phi node is in the loop header and has two incoming values.
61029c997c1SMatthew Simpson   if (Phi->getParent() != TheLoop->getHeader() ||
61129c997c1SMatthew Simpson       Phi->getNumIncomingValues() != 2)
61229c997c1SMatthew Simpson     return false;
61329c997c1SMatthew Simpson 
61429c997c1SMatthew Simpson   // Ensure the loop has a preheader and a single latch block. The loop
61529c997c1SMatthew Simpson   // vectorizer will need the latch to set up the next iteration of the loop.
61629c997c1SMatthew Simpson   auto *Preheader = TheLoop->getLoopPreheader();
61729c997c1SMatthew Simpson   auto *Latch = TheLoop->getLoopLatch();
61829c997c1SMatthew Simpson   if (!Preheader || !Latch)
61929c997c1SMatthew Simpson     return false;
62029c997c1SMatthew Simpson 
62129c997c1SMatthew Simpson   // Ensure the phi node's incoming blocks are the loop preheader and latch.
62229c997c1SMatthew Simpson   if (Phi->getBasicBlockIndex(Preheader) < 0 ||
62329c997c1SMatthew Simpson       Phi->getBasicBlockIndex(Latch) < 0)
62429c997c1SMatthew Simpson     return false;
62529c997c1SMatthew Simpson 
62629c997c1SMatthew Simpson   // Get the previous value. The previous value comes from the latch edge while
62729c997c1SMatthew Simpson   // the initial value comes form the preheader edge.
62829c997c1SMatthew Simpson   auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
6292ff59d43SAyal Zaks   if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous) ||
6302ff59d43SAyal Zaks       SinkAfter.count(Previous)) // Cannot rely on dominance due to motion.
63129c997c1SMatthew Simpson     return false;
63229c997c1SMatthew Simpson 
63300dc1b74SAnna Thomas   // Ensure every user of the phi node is dominated by the previous value.
63400dc1b74SAnna Thomas   // The dominance requirement ensures the loop vectorizer will not need to
63500dc1b74SAnna Thomas   // vectorize the initial value prior to the first iteration of the loop.
6362ff59d43SAyal Zaks   // TODO: Consider extending this sinking to handle other kinds of instructions
6372ff59d43SAyal Zaks   // and expressions, beyond sinking a single cast past Previous.
6382ff59d43SAyal Zaks   if (Phi->hasOneUse()) {
6392ff59d43SAyal Zaks     auto *I = Phi->user_back();
6402ff59d43SAyal Zaks     if (I->isCast() && (I->getParent() == Phi->getParent()) && I->hasOneUse() &&
6412ff59d43SAyal Zaks         DT->dominates(Previous, I->user_back())) {
64225e2800eSAyal Zaks       if (!DT->dominates(Previous, I)) // Otherwise we're good w/o sinking.
6432ff59d43SAyal Zaks         SinkAfter[I] = Previous;
6442ff59d43SAyal Zaks       return true;
6452ff59d43SAyal Zaks     }
6462ff59d43SAyal Zaks   }
6472ff59d43SAyal Zaks 
648dcdb325fSAnna Thomas   for (User *U : Phi->users())
649dcdb325fSAnna Thomas     if (auto *I = dyn_cast<Instruction>(U)) {
65029c997c1SMatthew Simpson       if (!DT->dominates(Previous, I))
65129c997c1SMatthew Simpson         return false;
65200dc1b74SAnna Thomas     }
65329c997c1SMatthew Simpson 
65429c997c1SMatthew Simpson   return true;
65529c997c1SMatthew Simpson }
65629c997c1SMatthew Simpson 
65776aa662cSKarthik Bhat /// This function returns the identity element (or neutral element) for
65876aa662cSKarthik Bhat /// the operation K.
6590a91310cSTyler Nowicki Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K,
6600a91310cSTyler Nowicki                                                       Type *Tp) {
66176aa662cSKarthik Bhat   switch (K) {
66276aa662cSKarthik Bhat   case RK_IntegerXor:
66376aa662cSKarthik Bhat   case RK_IntegerAdd:
66476aa662cSKarthik Bhat   case RK_IntegerOr:
66576aa662cSKarthik Bhat     // Adding, Xoring, Oring zero to a number does not change it.
66676aa662cSKarthik Bhat     return ConstantInt::get(Tp, 0);
66776aa662cSKarthik Bhat   case RK_IntegerMult:
66876aa662cSKarthik Bhat     // Multiplying a number by 1 does not change it.
66976aa662cSKarthik Bhat     return ConstantInt::get(Tp, 1);
67076aa662cSKarthik Bhat   case RK_IntegerAnd:
67176aa662cSKarthik Bhat     // AND-ing a number with an all-1 value does not change it.
67276aa662cSKarthik Bhat     return ConstantInt::get(Tp, -1, true);
67376aa662cSKarthik Bhat   case RK_FloatMult:
67476aa662cSKarthik Bhat     // Multiplying a number by 1 does not change it.
67576aa662cSKarthik Bhat     return ConstantFP::get(Tp, 1.0L);
67676aa662cSKarthik Bhat   case RK_FloatAdd:
67776aa662cSKarthik Bhat     // Adding zero to a number does not change it.
67876aa662cSKarthik Bhat     return ConstantFP::get(Tp, 0.0L);
67976aa662cSKarthik Bhat   default:
6800a91310cSTyler Nowicki     llvm_unreachable("Unknown recurrence kind");
68176aa662cSKarthik Bhat   }
68276aa662cSKarthik Bhat }
68376aa662cSKarthik Bhat 
6840a91310cSTyler Nowicki /// This function translates the recurrence kind to an LLVM binary operator.
6850a91310cSTyler Nowicki unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) {
68676aa662cSKarthik Bhat   switch (Kind) {
68776aa662cSKarthik Bhat   case RK_IntegerAdd:
68876aa662cSKarthik Bhat     return Instruction::Add;
68976aa662cSKarthik Bhat   case RK_IntegerMult:
69076aa662cSKarthik Bhat     return Instruction::Mul;
69176aa662cSKarthik Bhat   case RK_IntegerOr:
69276aa662cSKarthik Bhat     return Instruction::Or;
69376aa662cSKarthik Bhat   case RK_IntegerAnd:
69476aa662cSKarthik Bhat     return Instruction::And;
69576aa662cSKarthik Bhat   case RK_IntegerXor:
69676aa662cSKarthik Bhat     return Instruction::Xor;
69776aa662cSKarthik Bhat   case RK_FloatMult:
69876aa662cSKarthik Bhat     return Instruction::FMul;
69976aa662cSKarthik Bhat   case RK_FloatAdd:
70076aa662cSKarthik Bhat     return Instruction::FAdd;
70176aa662cSKarthik Bhat   case RK_IntegerMinMax:
70276aa662cSKarthik Bhat     return Instruction::ICmp;
70376aa662cSKarthik Bhat   case RK_FloatMinMax:
70476aa662cSKarthik Bhat     return Instruction::FCmp;
70576aa662cSKarthik Bhat   default:
7060a91310cSTyler Nowicki     llvm_unreachable("Unknown recurrence operation");
70776aa662cSKarthik Bhat   }
70876aa662cSKarthik Bhat }
70976aa662cSKarthik Bhat 
71027b2c39eSTyler Nowicki Value *RecurrenceDescriptor::createMinMaxOp(IRBuilder<> &Builder,
71127b2c39eSTyler Nowicki                                             MinMaxRecurrenceKind RK,
71276aa662cSKarthik Bhat                                             Value *Left, Value *Right) {
71376aa662cSKarthik Bhat   CmpInst::Predicate P = CmpInst::ICMP_NE;
71476aa662cSKarthik Bhat   switch (RK) {
71576aa662cSKarthik Bhat   default:
7160a91310cSTyler Nowicki     llvm_unreachable("Unknown min/max recurrence kind");
71727b2c39eSTyler Nowicki   case MRK_UIntMin:
71876aa662cSKarthik Bhat     P = CmpInst::ICMP_ULT;
71976aa662cSKarthik Bhat     break;
72027b2c39eSTyler Nowicki   case MRK_UIntMax:
72176aa662cSKarthik Bhat     P = CmpInst::ICMP_UGT;
72276aa662cSKarthik Bhat     break;
72327b2c39eSTyler Nowicki   case MRK_SIntMin:
72476aa662cSKarthik Bhat     P = CmpInst::ICMP_SLT;
72576aa662cSKarthik Bhat     break;
72627b2c39eSTyler Nowicki   case MRK_SIntMax:
72776aa662cSKarthik Bhat     P = CmpInst::ICMP_SGT;
72876aa662cSKarthik Bhat     break;
72927b2c39eSTyler Nowicki   case MRK_FloatMin:
73076aa662cSKarthik Bhat     P = CmpInst::FCMP_OLT;
73176aa662cSKarthik Bhat     break;
73227b2c39eSTyler Nowicki   case MRK_FloatMax:
73376aa662cSKarthik Bhat     P = CmpInst::FCMP_OGT;
73476aa662cSKarthik Bhat     break;
73576aa662cSKarthik Bhat   }
73676aa662cSKarthik Bhat 
737629c4115SSanjay Patel   // We only match FP sequences that are 'fast', so we can unconditionally
73850a4c27fSJames Molloy   // set it on any generated instructions.
73950a4c27fSJames Molloy   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
74050a4c27fSJames Molloy   FastMathFlags FMF;
741629c4115SSanjay Patel   FMF.setFast();
742a252815bSSanjay Patel   Builder.setFastMathFlags(FMF);
74350a4c27fSJames Molloy 
74476aa662cSKarthik Bhat   Value *Cmp;
74527b2c39eSTyler Nowicki   if (RK == MRK_FloatMin || RK == MRK_FloatMax)
74676aa662cSKarthik Bhat     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
74776aa662cSKarthik Bhat   else
74876aa662cSKarthik Bhat     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
74976aa662cSKarthik Bhat 
75076aa662cSKarthik Bhat   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
75176aa662cSKarthik Bhat   return Select;
75276aa662cSKarthik Bhat }
75324e6cc2dSKarthik Bhat 
7541bbf15c5SJames Molloy InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
7554750c785SDorit Nuzman                                          const SCEV *Step, BinaryOperator *BOp,
7564750c785SDorit Nuzman                                          SmallVectorImpl<Instruction *> *Casts)
757376a18bdSElena Demikhovsky   : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
7581bbf15c5SJames Molloy   assert(IK != IK_NoInduction && "Not an induction");
759c434d091SElena Demikhovsky 
760c434d091SElena Demikhovsky   // Start value type should match the induction kind and the value
761c434d091SElena Demikhovsky   // itself should not be null.
7621bbf15c5SJames Molloy   assert(StartValue && "StartValue is null");
7631bbf15c5SJames Molloy   assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
7641bbf15c5SJames Molloy          "StartValue is not a pointer for pointer induction");
7651bbf15c5SJames Molloy   assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
7661bbf15c5SJames Molloy          "StartValue is not an integer for integer induction");
767c434d091SElena Demikhovsky 
768c434d091SElena Demikhovsky   // Check the Step Value. It should be non-zero integer value.
769c434d091SElena Demikhovsky   assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
770c434d091SElena Demikhovsky          "Step value is zero");
771c434d091SElena Demikhovsky 
772c434d091SElena Demikhovsky   assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
773c434d091SElena Demikhovsky          "Step value should be constant for pointer induction");
774376a18bdSElena Demikhovsky   assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
775376a18bdSElena Demikhovsky          "StepValue is not an integer");
776376a18bdSElena Demikhovsky 
777376a18bdSElena Demikhovsky   assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
778376a18bdSElena Demikhovsky          "StepValue is not FP for FpInduction");
779376a18bdSElena Demikhovsky   assert((IK != IK_FpInduction || (InductionBinOp &&
780376a18bdSElena Demikhovsky           (InductionBinOp->getOpcode() == Instruction::FAdd ||
781376a18bdSElena Demikhovsky            InductionBinOp->getOpcode() == Instruction::FSub))) &&
782376a18bdSElena Demikhovsky          "Binary opcode should be specified for FP induction");
7834750c785SDorit Nuzman 
7844750c785SDorit Nuzman   if (Casts) {
7854750c785SDorit Nuzman     for (auto &Inst : *Casts) {
7864750c785SDorit Nuzman       RedundantCasts.push_back(Inst);
7874750c785SDorit Nuzman     }
7884750c785SDorit Nuzman   }
7891bbf15c5SJames Molloy }
7901bbf15c5SJames Molloy 
7911bbf15c5SJames Molloy int InductionDescriptor::getConsecutiveDirection() const {
792c434d091SElena Demikhovsky   ConstantInt *ConstStep = getConstIntStepValue();
793c434d091SElena Demikhovsky   if (ConstStep && (ConstStep->isOne() || ConstStep->isMinusOne()))
794c434d091SElena Demikhovsky     return ConstStep->getSExtValue();
7951bbf15c5SJames Molloy   return 0;
7961bbf15c5SJames Molloy }
7971bbf15c5SJames Molloy 
798c434d091SElena Demikhovsky ConstantInt *InductionDescriptor::getConstIntStepValue() const {
799c434d091SElena Demikhovsky   if (isa<SCEVConstant>(Step))
800c434d091SElena Demikhovsky     return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
801c434d091SElena Demikhovsky   return nullptr;
802c434d091SElena Demikhovsky }
803c434d091SElena Demikhovsky 
804c434d091SElena Demikhovsky Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index,
805c434d091SElena Demikhovsky                                       ScalarEvolution *SE,
806c434d091SElena Demikhovsky                                       const DataLayout& DL) const {
807c434d091SElena Demikhovsky 
808c434d091SElena Demikhovsky   SCEVExpander Exp(*SE, DL, "induction");
809376a18bdSElena Demikhovsky   assert(Index->getType() == Step->getType() &&
810376a18bdSElena Demikhovsky          "Index type does not match StepValue type");
8111bbf15c5SJames Molloy   switch (IK) {
812c434d091SElena Demikhovsky   case IK_IntInduction: {
8131bbf15c5SJames Molloy     assert(Index->getType() == StartValue->getType() &&
8141bbf15c5SJames Molloy            "Index type does not match StartValue type");
815c434d091SElena Demikhovsky 
816c434d091SElena Demikhovsky     // FIXME: Theoretically, we can call getAddExpr() of ScalarEvolution
817c434d091SElena Demikhovsky     // and calculate (Start + Index * Step) for all cases, without
818c434d091SElena Demikhovsky     // special handling for "isOne" and "isMinusOne".
819c434d091SElena Demikhovsky     // But in the real life the result code getting worse. We mix SCEV
820c434d091SElena Demikhovsky     // expressions and ADD/SUB operations and receive redundant
821c434d091SElena Demikhovsky     // intermediate values being calculated in different ways and
822c434d091SElena Demikhovsky     // Instcombine is unable to reduce them all.
823c434d091SElena Demikhovsky 
824c434d091SElena Demikhovsky     if (getConstIntStepValue() &&
825c434d091SElena Demikhovsky         getConstIntStepValue()->isMinusOne())
8261bbf15c5SJames Molloy       return B.CreateSub(StartValue, Index);
827c434d091SElena Demikhovsky     if (getConstIntStepValue() &&
828c434d091SElena Demikhovsky         getConstIntStepValue()->isOne())
8291bbf15c5SJames Molloy       return B.CreateAdd(StartValue, Index);
830c434d091SElena Demikhovsky     const SCEV *S = SE->getAddExpr(SE->getSCEV(StartValue),
831c434d091SElena Demikhovsky                                    SE->getMulExpr(Step, SE->getSCEV(Index)));
832c434d091SElena Demikhovsky     return Exp.expandCodeFor(S, StartValue->getType(), &*B.GetInsertPoint());
833c434d091SElena Demikhovsky   }
834c434d091SElena Demikhovsky   case IK_PtrInduction: {
835c434d091SElena Demikhovsky     assert(isa<SCEVConstant>(Step) &&
836c434d091SElena Demikhovsky            "Expected constant step for pointer induction");
837c434d091SElena Demikhovsky     const SCEV *S = SE->getMulExpr(SE->getSCEV(Index), Step);
838c434d091SElena Demikhovsky     Index = Exp.expandCodeFor(S, Index->getType(), &*B.GetInsertPoint());
8391bbf15c5SJames Molloy     return B.CreateGEP(nullptr, StartValue, Index);
840c434d091SElena Demikhovsky   }
841376a18bdSElena Demikhovsky   case IK_FpInduction: {
842376a18bdSElena Demikhovsky     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
843376a18bdSElena Demikhovsky     assert(InductionBinOp &&
844376a18bdSElena Demikhovsky            (InductionBinOp->getOpcode() == Instruction::FAdd ||
845376a18bdSElena Demikhovsky             InductionBinOp->getOpcode() == Instruction::FSub) &&
846376a18bdSElena Demikhovsky            "Original bin op should be defined for FP induction");
847376a18bdSElena Demikhovsky 
848376a18bdSElena Demikhovsky     Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
849376a18bdSElena Demikhovsky 
850376a18bdSElena Demikhovsky     // Floating point operations had to be 'fast' to enable the induction.
851376a18bdSElena Demikhovsky     FastMathFlags Flags;
852629c4115SSanjay Patel     Flags.setFast();
853376a18bdSElena Demikhovsky 
854376a18bdSElena Demikhovsky     Value *MulExp = B.CreateFMul(StepValue, Index);
855376a18bdSElena Demikhovsky     if (isa<Instruction>(MulExp))
856376a18bdSElena Demikhovsky       // We have to check, the MulExp may be a constant.
857376a18bdSElena Demikhovsky       cast<Instruction>(MulExp)->setFastMathFlags(Flags);
858376a18bdSElena Demikhovsky 
859376a18bdSElena Demikhovsky     Value *BOp = B.CreateBinOp(InductionBinOp->getOpcode() , StartValue,
860376a18bdSElena Demikhovsky                                MulExp, "induction");
861376a18bdSElena Demikhovsky     if (isa<Instruction>(BOp))
862376a18bdSElena Demikhovsky       cast<Instruction>(BOp)->setFastMathFlags(Flags);
863376a18bdSElena Demikhovsky 
864376a18bdSElena Demikhovsky     return BOp;
865376a18bdSElena Demikhovsky   }
8661bbf15c5SJames Molloy   case IK_NoInduction:
8671bbf15c5SJames Molloy     return nullptr;
8681bbf15c5SJames Molloy   }
8691bbf15c5SJames Molloy   llvm_unreachable("invalid enum");
8701bbf15c5SJames Molloy }
8711bbf15c5SJames Molloy 
872376a18bdSElena Demikhovsky bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop,
873376a18bdSElena Demikhovsky                                            ScalarEvolution *SE,
874376a18bdSElena Demikhovsky                                            InductionDescriptor &D) {
875376a18bdSElena Demikhovsky 
876376a18bdSElena Demikhovsky   // Here we only handle FP induction variables.
877376a18bdSElena Demikhovsky   assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
878376a18bdSElena Demikhovsky 
879376a18bdSElena Demikhovsky   if (TheLoop->getHeader() != Phi->getParent())
880376a18bdSElena Demikhovsky     return false;
881376a18bdSElena Demikhovsky 
882376a18bdSElena Demikhovsky   // The loop may have multiple entrances or multiple exits; we can analyze
883376a18bdSElena Demikhovsky   // this phi if it has a unique entry value and a unique backedge value.
884376a18bdSElena Demikhovsky   if (Phi->getNumIncomingValues() != 2)
885376a18bdSElena Demikhovsky     return false;
886376a18bdSElena Demikhovsky   Value *BEValue = nullptr, *StartValue = nullptr;
887376a18bdSElena Demikhovsky   if (TheLoop->contains(Phi->getIncomingBlock(0))) {
888376a18bdSElena Demikhovsky     BEValue = Phi->getIncomingValue(0);
889376a18bdSElena Demikhovsky     StartValue = Phi->getIncomingValue(1);
890376a18bdSElena Demikhovsky   } else {
891376a18bdSElena Demikhovsky     assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
892376a18bdSElena Demikhovsky            "Unexpected Phi node in the loop");
893376a18bdSElena Demikhovsky     BEValue = Phi->getIncomingValue(1);
894376a18bdSElena Demikhovsky     StartValue = Phi->getIncomingValue(0);
895376a18bdSElena Demikhovsky   }
896376a18bdSElena Demikhovsky 
897376a18bdSElena Demikhovsky   BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue);
898376a18bdSElena Demikhovsky   if (!BOp)
899376a18bdSElena Demikhovsky     return false;
900376a18bdSElena Demikhovsky 
901376a18bdSElena Demikhovsky   Value *Addend = nullptr;
902376a18bdSElena Demikhovsky   if (BOp->getOpcode() == Instruction::FAdd) {
903376a18bdSElena Demikhovsky     if (BOp->getOperand(0) == Phi)
904376a18bdSElena Demikhovsky       Addend = BOp->getOperand(1);
905376a18bdSElena Demikhovsky     else if (BOp->getOperand(1) == Phi)
906376a18bdSElena Demikhovsky       Addend = BOp->getOperand(0);
907376a18bdSElena Demikhovsky   } else if (BOp->getOpcode() == Instruction::FSub)
908376a18bdSElena Demikhovsky     if (BOp->getOperand(0) == Phi)
909376a18bdSElena Demikhovsky       Addend = BOp->getOperand(1);
910376a18bdSElena Demikhovsky 
911376a18bdSElena Demikhovsky   if (!Addend)
912376a18bdSElena Demikhovsky     return false;
913376a18bdSElena Demikhovsky 
914376a18bdSElena Demikhovsky   // The addend should be loop invariant
915376a18bdSElena Demikhovsky   if (auto *I = dyn_cast<Instruction>(Addend))
916376a18bdSElena Demikhovsky     if (TheLoop->contains(I))
917376a18bdSElena Demikhovsky       return false;
918376a18bdSElena Demikhovsky 
919376a18bdSElena Demikhovsky   // FP Step has unknown SCEV
920376a18bdSElena Demikhovsky   const SCEV *Step = SE->getUnknown(Addend);
921376a18bdSElena Demikhovsky   D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
922376a18bdSElena Demikhovsky   return true;
923376a18bdSElena Demikhovsky }
924376a18bdSElena Demikhovsky 
9254750c785SDorit Nuzman /// This function is called when we suspect that the update-chain of a phi node
9264750c785SDorit Nuzman /// (whose symbolic SCEV expression sin \p PhiScev) contains redundant casts,
9274750c785SDorit Nuzman /// that can be ignored. (This can happen when the PSCEV rewriter adds a runtime
9284750c785SDorit Nuzman /// predicate P under which the SCEV expression for the phi can be the
9294750c785SDorit Nuzman /// AddRecurrence \p AR; See createAddRecFromPHIWithCast). We want to find the
9304750c785SDorit Nuzman /// cast instructions that are involved in the update-chain of this induction.
9314750c785SDorit Nuzman /// A caller that adds the required runtime predicate can be free to drop these
9324750c785SDorit Nuzman /// cast instructions, and compute the phi using \p AR (instead of some scev
9334750c785SDorit Nuzman /// expression with casts).
9344750c785SDorit Nuzman ///
9354750c785SDorit Nuzman /// For example, without a predicate the scev expression can take the following
9364750c785SDorit Nuzman /// form:
9374750c785SDorit Nuzman ///      (Ext ix (Trunc iy ( Start + i*Step ) to ix) to iy)
9384750c785SDorit Nuzman ///
9394750c785SDorit Nuzman /// It corresponds to the following IR sequence:
9404750c785SDorit Nuzman /// %for.body:
9414750c785SDorit Nuzman ///   %x = phi i64 [ 0, %ph ], [ %add, %for.body ]
9424750c785SDorit Nuzman ///   %casted_phi = "ExtTrunc i64 %x"
9434750c785SDorit Nuzman ///   %add = add i64 %casted_phi, %step
9444750c785SDorit Nuzman ///
9454750c785SDorit Nuzman /// where %x is given in \p PN,
9464750c785SDorit Nuzman /// PSE.getSCEV(%x) is equal to PSE.getSCEV(%casted_phi) under a predicate,
9474750c785SDorit Nuzman /// and the IR sequence that "ExtTrunc i64 %x" represents can take one of
9484750c785SDorit Nuzman /// several forms, for example, such as:
9494750c785SDorit Nuzman ///   ExtTrunc1:    %casted_phi = and  %x, 2^n-1
9504750c785SDorit Nuzman /// or:
9514750c785SDorit Nuzman ///   ExtTrunc2:    %t = shl %x, m
9524750c785SDorit Nuzman ///                 %casted_phi = ashr %t, m
9534750c785SDorit Nuzman ///
9544750c785SDorit Nuzman /// If we are able to find such sequence, we return the instructions
9554750c785SDorit Nuzman /// we found, namely %casted_phi and the instructions on its use-def chain up
9564750c785SDorit Nuzman /// to the phi (not including the phi).
957802e6255SBenjamin Kramer static bool getCastsForInductionPHI(PredicatedScalarEvolution &PSE,
958802e6255SBenjamin Kramer                                     const SCEVUnknown *PhiScev,
959802e6255SBenjamin Kramer                                     const SCEVAddRecExpr *AR,
960802e6255SBenjamin Kramer                                     SmallVectorImpl<Instruction *> &CastInsts) {
9614750c785SDorit Nuzman 
9624750c785SDorit Nuzman   assert(CastInsts.empty() && "CastInsts is expected to be empty.");
9634750c785SDorit Nuzman   auto *PN = cast<PHINode>(PhiScev->getValue());
9644750c785SDorit Nuzman   assert(PSE.getSCEV(PN) == AR && "Unexpected phi node SCEV expression");
9654750c785SDorit Nuzman   const Loop *L = AR->getLoop();
9664750c785SDorit Nuzman 
9674750c785SDorit Nuzman   // Find any cast instructions that participate in the def-use chain of
9684750c785SDorit Nuzman   // PhiScev in the loop.
9694750c785SDorit Nuzman   // FORNOW/TODO: We currently expect the def-use chain to include only
9704750c785SDorit Nuzman   // two-operand instructions, where one of the operands is an invariant.
9714750c785SDorit Nuzman   // createAddRecFromPHIWithCasts() currently does not support anything more
9724750c785SDorit Nuzman   // involved than that, so we keep the search simple. This can be
9734750c785SDorit Nuzman   // extended/generalized as needed.
9744750c785SDorit Nuzman 
9754750c785SDorit Nuzman   auto getDef = [&](const Value *Val) -> Value * {
9764750c785SDorit Nuzman     const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val);
9774750c785SDorit Nuzman     if (!BinOp)
9784750c785SDorit Nuzman       return nullptr;
9794750c785SDorit Nuzman     Value *Op0 = BinOp->getOperand(0);
9804750c785SDorit Nuzman     Value *Op1 = BinOp->getOperand(1);
9814750c785SDorit Nuzman     Value *Def = nullptr;
9824750c785SDorit Nuzman     if (L->isLoopInvariant(Op0))
9834750c785SDorit Nuzman       Def = Op1;
9844750c785SDorit Nuzman     else if (L->isLoopInvariant(Op1))
9854750c785SDorit Nuzman       Def = Op0;
9864750c785SDorit Nuzman     return Def;
9874750c785SDorit Nuzman   };
9884750c785SDorit Nuzman 
9894750c785SDorit Nuzman   // Look for the instruction that defines the induction via the
9904750c785SDorit Nuzman   // loop backedge.
9914750c785SDorit Nuzman   BasicBlock *Latch = L->getLoopLatch();
9924750c785SDorit Nuzman   if (!Latch)
9934750c785SDorit Nuzman     return false;
9944750c785SDorit Nuzman   Value *Val = PN->getIncomingValueForBlock(Latch);
9954750c785SDorit Nuzman   if (!Val)
9964750c785SDorit Nuzman     return false;
9974750c785SDorit Nuzman 
9984750c785SDorit Nuzman   // Follow the def-use chain until the induction phi is reached.
9994750c785SDorit Nuzman   // If on the way we encounter a Value that has the same SCEV Expr as the
10004750c785SDorit Nuzman   // phi node, we can consider the instructions we visit from that point
10014750c785SDorit Nuzman   // as part of the cast-sequence that can be ignored.
10024750c785SDorit Nuzman   bool InCastSequence = false;
10034750c785SDorit Nuzman   auto *Inst = dyn_cast<Instruction>(Val);
10044750c785SDorit Nuzman   while (Val != PN) {
10054750c785SDorit Nuzman     // If we encountered a phi node other than PN, or if we left the loop,
10064750c785SDorit Nuzman     // we bail out.
10074750c785SDorit Nuzman     if (!Inst || !L->contains(Inst)) {
10084750c785SDorit Nuzman       return false;
10094750c785SDorit Nuzman     }
10104750c785SDorit Nuzman     auto *AddRec = dyn_cast<SCEVAddRecExpr>(PSE.getSCEV(Val));
10114750c785SDorit Nuzman     if (AddRec && PSE.areAddRecsEqualWithPreds(AddRec, AR))
10124750c785SDorit Nuzman       InCastSequence = true;
10134750c785SDorit Nuzman     if (InCastSequence) {
10144750c785SDorit Nuzman       // Only the last instruction in the cast sequence is expected to have
10154750c785SDorit Nuzman       // uses outside the induction def-use chain.
10164750c785SDorit Nuzman       if (!CastInsts.empty())
10174750c785SDorit Nuzman         if (!Inst->hasOneUse())
10184750c785SDorit Nuzman           return false;
10194750c785SDorit Nuzman       CastInsts.push_back(Inst);
10204750c785SDorit Nuzman     }
10214750c785SDorit Nuzman     Val = getDef(Val);
10224750c785SDorit Nuzman     if (!Val)
10234750c785SDorit Nuzman       return false;
10244750c785SDorit Nuzman     Inst = dyn_cast<Instruction>(Val);
10254750c785SDorit Nuzman   }
10264750c785SDorit Nuzman 
10274750c785SDorit Nuzman   return InCastSequence;
10284750c785SDorit Nuzman }
10294750c785SDorit Nuzman 
1030376a18bdSElena Demikhovsky bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
1031c05bab8aSSilviu Baranga                                          PredicatedScalarEvolution &PSE,
1032c05bab8aSSilviu Baranga                                          InductionDescriptor &D,
1033c05bab8aSSilviu Baranga                                          bool Assume) {
1034c05bab8aSSilviu Baranga   Type *PhiTy = Phi->getType();
1035376a18bdSElena Demikhovsky 
1036376a18bdSElena Demikhovsky   // Handle integer and pointer inductions variables.
1037376a18bdSElena Demikhovsky   // Now we handle also FP induction but not trying to make a
1038376a18bdSElena Demikhovsky   // recurrent expression from the PHI node in-place.
1039376a18bdSElena Demikhovsky 
1040376a18bdSElena Demikhovsky   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() &&
1041376a18bdSElena Demikhovsky       !PhiTy->isFloatTy() && !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
1042c05bab8aSSilviu Baranga     return false;
1043c05bab8aSSilviu Baranga 
1044376a18bdSElena Demikhovsky   if (PhiTy->isFloatingPointTy())
1045376a18bdSElena Demikhovsky     return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
1046376a18bdSElena Demikhovsky 
1047c05bab8aSSilviu Baranga   const SCEV *PhiScev = PSE.getSCEV(Phi);
1048c05bab8aSSilviu Baranga   const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1049c05bab8aSSilviu Baranga 
1050c05bab8aSSilviu Baranga   // We need this expression to be an AddRecExpr.
1051c05bab8aSSilviu Baranga   if (Assume && !AR)
1052c05bab8aSSilviu Baranga     AR = PSE.getAsAddRec(Phi);
1053c05bab8aSSilviu Baranga 
1054c05bab8aSSilviu Baranga   if (!AR) {
1055c05bab8aSSilviu Baranga     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1056c05bab8aSSilviu Baranga     return false;
1057c05bab8aSSilviu Baranga   }
1058c05bab8aSSilviu Baranga 
10594750c785SDorit Nuzman   // Record any Cast instructions that participate in the induction update
10604750c785SDorit Nuzman   const auto *SymbolicPhi = dyn_cast<SCEVUnknown>(PhiScev);
10614750c785SDorit Nuzman   // If we started from an UnknownSCEV, and managed to build an addRecurrence
10624750c785SDorit Nuzman   // only after enabling Assume with PSCEV, this means we may have encountered
10634750c785SDorit Nuzman   // cast instructions that required adding a runtime check in order to
10644750c785SDorit Nuzman   // guarantee the correctness of the AddRecurence respresentation of the
10654750c785SDorit Nuzman   // induction.
10664750c785SDorit Nuzman   if (PhiScev != AR && SymbolicPhi) {
10674750c785SDorit Nuzman     SmallVector<Instruction *, 2> Casts;
10684750c785SDorit Nuzman     if (getCastsForInductionPHI(PSE, SymbolicPhi, AR, Casts))
10694750c785SDorit Nuzman       return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR, &Casts);
10704750c785SDorit Nuzman   }
10714750c785SDorit Nuzman 
1072376a18bdSElena Demikhovsky   return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
1073c05bab8aSSilviu Baranga }
1074c05bab8aSSilviu Baranga 
10754750c785SDorit Nuzman bool InductionDescriptor::isInductionPHI(
10764750c785SDorit Nuzman     PHINode *Phi, const Loop *TheLoop, ScalarEvolution *SE,
10774750c785SDorit Nuzman     InductionDescriptor &D, const SCEV *Expr,
10784750c785SDorit Nuzman     SmallVectorImpl<Instruction *> *CastsToIgnore) {
107924e6cc2dSKarthik Bhat   Type *PhiTy = Phi->getType();
108024e6cc2dSKarthik Bhat   // We only handle integer and pointer inductions variables.
108124e6cc2dSKarthik Bhat   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
108224e6cc2dSKarthik Bhat     return false;
108324e6cc2dSKarthik Bhat 
108424e6cc2dSKarthik Bhat   // Check that the PHI is consecutive.
1085c05bab8aSSilviu Baranga   const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
108624e6cc2dSKarthik Bhat   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1087c05bab8aSSilviu Baranga 
108824e6cc2dSKarthik Bhat   if (!AR) {
108924e6cc2dSKarthik Bhat     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
109024e6cc2dSKarthik Bhat     return false;
109124e6cc2dSKarthik Bhat   }
109224e6cc2dSKarthik Bhat 
1093ee31cbe3SMichael Kuperstein   if (AR->getLoop() != TheLoop) {
1094ee31cbe3SMichael Kuperstein     // FIXME: We should treat this as a uniform. Unfortunately, we
1095ee31cbe3SMichael Kuperstein     // don't currently know how to handled uniform PHIs.
1096ee31cbe3SMichael Kuperstein     DEBUG(dbgs() << "LV: PHI is a recurrence with respect to an outer loop.\n");
1097ee31cbe3SMichael Kuperstein     return false;
1098ee31cbe3SMichael Kuperstein   }
1099ee31cbe3SMichael Kuperstein 
11001bbf15c5SJames Molloy   Value *StartValue =
11011bbf15c5SJames Molloy     Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
110224e6cc2dSKarthik Bhat   const SCEV *Step = AR->getStepRecurrence(*SE);
110324e6cc2dSKarthik Bhat   // Calculate the pointer stride and check if it is consecutive.
1104c434d091SElena Demikhovsky   // The stride may be a constant or a loop invariant integer value.
1105c434d091SElena Demikhovsky   const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
1106376a18bdSElena Demikhovsky   if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop))
110724e6cc2dSKarthik Bhat     return false;
110824e6cc2dSKarthik Bhat 
110924e6cc2dSKarthik Bhat   if (PhiTy->isIntegerTy()) {
11104750c785SDorit Nuzman     D = InductionDescriptor(StartValue, IK_IntInduction, Step, /*BOp=*/ nullptr,
11114750c785SDorit Nuzman                             CastsToIgnore);
111224e6cc2dSKarthik Bhat     return true;
111324e6cc2dSKarthik Bhat   }
111424e6cc2dSKarthik Bhat 
111524e6cc2dSKarthik Bhat   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1116c434d091SElena Demikhovsky   // Pointer induction should be a constant.
1117c434d091SElena Demikhovsky   if (!ConstStep)
1118c434d091SElena Demikhovsky     return false;
1119c434d091SElena Demikhovsky 
1120c434d091SElena Demikhovsky   ConstantInt *CV = ConstStep->getValue();
112124e6cc2dSKarthik Bhat   Type *PointerElementType = PhiTy->getPointerElementType();
112224e6cc2dSKarthik Bhat   // The pointer stride cannot be determined if the pointer element type is not
112324e6cc2dSKarthik Bhat   // sized.
112424e6cc2dSKarthik Bhat   if (!PointerElementType->isSized())
112524e6cc2dSKarthik Bhat     return false;
112624e6cc2dSKarthik Bhat 
112724e6cc2dSKarthik Bhat   const DataLayout &DL = Phi->getModule()->getDataLayout();
112824e6cc2dSKarthik Bhat   int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
1129b58f32f7SDavid Majnemer   if (!Size)
1130b58f32f7SDavid Majnemer     return false;
1131b58f32f7SDavid Majnemer 
113224e6cc2dSKarthik Bhat   int64_t CVSize = CV->getSExtValue();
113324e6cc2dSKarthik Bhat   if (CVSize % Size)
113424e6cc2dSKarthik Bhat     return false;
1135c434d091SElena Demikhovsky   auto *StepValue = SE->getConstant(CV->getType(), CVSize / Size,
1136c434d091SElena Demikhovsky                                     true /* signed */);
11371bbf15c5SJames Molloy   D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue);
113824e6cc2dSKarthik Bhat   return true;
113924e6cc2dSKarthik Bhat }
1140c5b7b555SAshutosh Nema 
11414a000883SChandler Carruth bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
11424a000883SChandler Carruth                                    bool PreserveLCSSA) {
11434a000883SChandler Carruth   bool Changed = false;
11444a000883SChandler Carruth 
11454a000883SChandler Carruth   // We re-use a vector for the in-loop predecesosrs.
11464a000883SChandler Carruth   SmallVector<BasicBlock *, 4> InLoopPredecessors;
11474a000883SChandler Carruth 
11484a000883SChandler Carruth   auto RewriteExit = [&](BasicBlock *BB) {
11494a000883SChandler Carruth     assert(InLoopPredecessors.empty() &&
11504a000883SChandler Carruth            "Must start with an empty predecessors list!");
11514a000883SChandler Carruth     auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
11524a000883SChandler Carruth 
11534a000883SChandler Carruth     // See if there are any non-loop predecessors of this exit block and
11544a000883SChandler Carruth     // keep track of the in-loop predecessors.
11554a000883SChandler Carruth     bool IsDedicatedExit = true;
11564a000883SChandler Carruth     for (auto *PredBB : predecessors(BB))
11574a000883SChandler Carruth       if (L->contains(PredBB)) {
11584a000883SChandler Carruth         if (isa<IndirectBrInst>(PredBB->getTerminator()))
11594a000883SChandler Carruth           // We cannot rewrite exiting edges from an indirectbr.
11604a000883SChandler Carruth           return false;
11614a000883SChandler Carruth 
11624a000883SChandler Carruth         InLoopPredecessors.push_back(PredBB);
11634a000883SChandler Carruth       } else {
11644a000883SChandler Carruth         IsDedicatedExit = false;
11654a000883SChandler Carruth       }
11664a000883SChandler Carruth 
11674a000883SChandler Carruth     assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
11684a000883SChandler Carruth 
11694a000883SChandler Carruth     // Nothing to do if this is already a dedicated exit.
11704a000883SChandler Carruth     if (IsDedicatedExit)
11714a000883SChandler Carruth       return false;
11724a000883SChandler Carruth 
11734a000883SChandler Carruth     auto *NewExitBB = SplitBlockPredecessors(
11744a000883SChandler Carruth         BB, InLoopPredecessors, ".loopexit", DT, LI, PreserveLCSSA);
11754a000883SChandler Carruth 
11764a000883SChandler Carruth     if (!NewExitBB)
11774a000883SChandler Carruth       DEBUG(dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
11784a000883SChandler Carruth                    << *L << "\n");
11794a000883SChandler Carruth     else
11804a000883SChandler Carruth       DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
11814a000883SChandler Carruth                    << NewExitBB->getName() << "\n");
11824a000883SChandler Carruth     return true;
11834a000883SChandler Carruth   };
11844a000883SChandler Carruth 
11854a000883SChandler Carruth   // Walk the exit blocks directly rather than building up a data structure for
11864a000883SChandler Carruth   // them, but only visit each one once.
11874a000883SChandler Carruth   SmallPtrSet<BasicBlock *, 4> Visited;
11884a000883SChandler Carruth   for (auto *BB : L->blocks())
11894a000883SChandler Carruth     for (auto *SuccBB : successors(BB)) {
11904a000883SChandler Carruth       // We're looking for exit blocks so skip in-loop successors.
11914a000883SChandler Carruth       if (L->contains(SuccBB))
11924a000883SChandler Carruth         continue;
11934a000883SChandler Carruth 
11944a000883SChandler Carruth       // Visit each exit block exactly once.
11954a000883SChandler Carruth       if (!Visited.insert(SuccBB).second)
11964a000883SChandler Carruth         continue;
11974a000883SChandler Carruth 
11984a000883SChandler Carruth       Changed |= RewriteExit(SuccBB);
11994a000883SChandler Carruth     }
12004a000883SChandler Carruth 
12014a000883SChandler Carruth   return Changed;
12024a000883SChandler Carruth }
12034a000883SChandler Carruth 
1204c5b7b555SAshutosh Nema /// \brief Returns the instructions that use values defined in the loop.
1205c5b7b555SAshutosh Nema SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
1206c5b7b555SAshutosh Nema   SmallVector<Instruction *, 8> UsedOutside;
1207c5b7b555SAshutosh Nema 
1208c5b7b555SAshutosh Nema   for (auto *Block : L->getBlocks())
1209c5b7b555SAshutosh Nema     // FIXME: I believe that this could use copy_if if the Inst reference could
1210c5b7b555SAshutosh Nema     // be adapted into a pointer.
1211c5b7b555SAshutosh Nema     for (auto &Inst : *Block) {
1212c5b7b555SAshutosh Nema       auto Users = Inst.users();
12130a16c228SDavid Majnemer       if (any_of(Users, [&](User *U) {
1214c5b7b555SAshutosh Nema             auto *Use = cast<Instruction>(U);
1215c5b7b555SAshutosh Nema             return !L->contains(Use->getParent());
1216c5b7b555SAshutosh Nema           }))
1217c5b7b555SAshutosh Nema         UsedOutside.push_back(&Inst);
1218c5b7b555SAshutosh Nema     }
1219c5b7b555SAshutosh Nema 
1220c5b7b555SAshutosh Nema   return UsedOutside;
1221c5b7b555SAshutosh Nema }
122231088a9dSChandler Carruth 
122331088a9dSChandler Carruth void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
122431088a9dSChandler Carruth   // By definition, all loop passes need the LoopInfo analysis and the
122531088a9dSChandler Carruth   // Dominator tree it depends on. Because they all participate in the loop
122631088a9dSChandler Carruth   // pass manager, they must also preserve these.
122731088a9dSChandler Carruth   AU.addRequired<DominatorTreeWrapperPass>();
122831088a9dSChandler Carruth   AU.addPreserved<DominatorTreeWrapperPass>();
122931088a9dSChandler Carruth   AU.addRequired<LoopInfoWrapperPass>();
123031088a9dSChandler Carruth   AU.addPreserved<LoopInfoWrapperPass>();
123131088a9dSChandler Carruth 
123231088a9dSChandler Carruth   // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
123331088a9dSChandler Carruth   // here because users shouldn't directly get them from this header.
123431088a9dSChandler Carruth   extern char &LoopSimplifyID;
123531088a9dSChandler Carruth   extern char &LCSSAID;
123631088a9dSChandler Carruth   AU.addRequiredID(LoopSimplifyID);
123731088a9dSChandler Carruth   AU.addPreservedID(LoopSimplifyID);
123831088a9dSChandler Carruth   AU.addRequiredID(LCSSAID);
123931088a9dSChandler Carruth   AU.addPreservedID(LCSSAID);
1240c3ccf5d7SIgor Laevsky   // This is used in the LPPassManager to perform LCSSA verification on passes
1241c3ccf5d7SIgor Laevsky   // which preserve lcssa form
1242c3ccf5d7SIgor Laevsky   AU.addRequired<LCSSAVerificationPass>();
1243c3ccf5d7SIgor Laevsky   AU.addPreserved<LCSSAVerificationPass>();
124431088a9dSChandler Carruth 
124531088a9dSChandler Carruth   // Loop passes are designed to run inside of a loop pass manager which means
124631088a9dSChandler Carruth   // that any function analyses they require must be required by the first loop
124731088a9dSChandler Carruth   // pass in the manager (so that it is computed before the loop pass manager
124831088a9dSChandler Carruth   // runs) and preserved by all loop pasess in the manager. To make this
124931088a9dSChandler Carruth   // reasonably robust, the set needed for most loop passes is maintained here.
125031088a9dSChandler Carruth   // If your loop pass requires an analysis not listed here, you will need to
125131088a9dSChandler Carruth   // carefully audit the loop pass manager nesting structure that results.
125231088a9dSChandler Carruth   AU.addRequired<AAResultsWrapperPass>();
125331088a9dSChandler Carruth   AU.addPreserved<AAResultsWrapperPass>();
125431088a9dSChandler Carruth   AU.addPreserved<BasicAAWrapperPass>();
125531088a9dSChandler Carruth   AU.addPreserved<GlobalsAAWrapperPass>();
125631088a9dSChandler Carruth   AU.addPreserved<SCEVAAWrapperPass>();
125731088a9dSChandler Carruth   AU.addRequired<ScalarEvolutionWrapperPass>();
125831088a9dSChandler Carruth   AU.addPreserved<ScalarEvolutionWrapperPass>();
125931088a9dSChandler Carruth }
126031088a9dSChandler Carruth 
126131088a9dSChandler Carruth /// Manually defined generic "LoopPass" dependency initialization. This is used
126231088a9dSChandler Carruth /// to initialize the exact set of passes from above in \c
126331088a9dSChandler Carruth /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
126431088a9dSChandler Carruth /// with:
126531088a9dSChandler Carruth ///
126631088a9dSChandler Carruth ///   INITIALIZE_PASS_DEPENDENCY(LoopPass)
126731088a9dSChandler Carruth ///
126831088a9dSChandler Carruth /// As-if "LoopPass" were a pass.
126931088a9dSChandler Carruth void llvm::initializeLoopPassPass(PassRegistry &Registry) {
127031088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
127131088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
127231088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1273e12c487bSEaswaran Raman   INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
127431088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
127531088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
127631088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
127731088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
127831088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
127931088a9dSChandler Carruth }
1280963341c8SAdam Nemet 
1281fe3def7cSAdam Nemet /// \brief Find string metadata for loop
1282fe3def7cSAdam Nemet ///
1283fe3def7cSAdam Nemet /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
1284fe3def7cSAdam Nemet /// operand or null otherwise.  If the string metadata is not found return
1285fe3def7cSAdam Nemet /// Optional's not-a-value.
1286fe3def7cSAdam Nemet Optional<const MDOperand *> llvm::findStringMetadataForLoop(Loop *TheLoop,
1287fe3def7cSAdam Nemet                                                             StringRef Name) {
1288963341c8SAdam Nemet   MDNode *LoopID = TheLoop->getLoopID();
1289fe3def7cSAdam Nemet   // Return none if LoopID is false.
1290963341c8SAdam Nemet   if (!LoopID)
1291fe3def7cSAdam Nemet     return None;
1292293be666SAdam Nemet 
1293293be666SAdam Nemet   // First operand should refer to the loop id itself.
1294293be666SAdam Nemet   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1295293be666SAdam Nemet   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1296293be666SAdam Nemet 
1297963341c8SAdam Nemet   // Iterate over LoopID operands and look for MDString Metadata
1298963341c8SAdam Nemet   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
1299963341c8SAdam Nemet     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1300963341c8SAdam Nemet     if (!MD)
1301963341c8SAdam Nemet       continue;
1302963341c8SAdam Nemet     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1303963341c8SAdam Nemet     if (!S)
1304963341c8SAdam Nemet       continue;
1305963341c8SAdam Nemet     // Return true if MDString holds expected MetaData.
1306963341c8SAdam Nemet     if (Name.equals(S->getString()))
1307fe3def7cSAdam Nemet       switch (MD->getNumOperands()) {
1308fe3def7cSAdam Nemet       case 1:
1309fe3def7cSAdam Nemet         return nullptr;
1310fe3def7cSAdam Nemet       case 2:
1311fe3def7cSAdam Nemet         return &MD->getOperand(1);
1312fe3def7cSAdam Nemet       default:
1313fe3def7cSAdam Nemet         llvm_unreachable("loop metadata has 0 or 1 operand");
1314963341c8SAdam Nemet       }
1315fe3def7cSAdam Nemet   }
1316fe3def7cSAdam Nemet   return None;
1317963341c8SAdam Nemet }
1318122f984aSEvgeniy Stepanov 
13197ed5856aSAlina Sbirlea /// Does a BFS from a given node to all of its children inside a given loop.
13207ed5856aSAlina Sbirlea /// The returned vector of nodes includes the starting point.
13217ed5856aSAlina Sbirlea SmallVector<DomTreeNode *, 16>
13227ed5856aSAlina Sbirlea llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
13237ed5856aSAlina Sbirlea   SmallVector<DomTreeNode *, 16> Worklist;
13247ed5856aSAlina Sbirlea   auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
13257ed5856aSAlina Sbirlea     // Only include subregions in the top level loop.
13267ed5856aSAlina Sbirlea     BasicBlock *BB = DTN->getBlock();
13277ed5856aSAlina Sbirlea     if (CurLoop->contains(BB))
13287ed5856aSAlina Sbirlea       Worklist.push_back(DTN);
13297ed5856aSAlina Sbirlea   };
13307ed5856aSAlina Sbirlea 
13317ed5856aSAlina Sbirlea   AddRegionToWorklist(N);
13327ed5856aSAlina Sbirlea 
13337ed5856aSAlina Sbirlea   for (size_t I = 0; I < Worklist.size(); I++)
13347ed5856aSAlina Sbirlea     for (DomTreeNode *Child : Worklist[I]->getChildren())
13357ed5856aSAlina Sbirlea       AddRegionToWorklist(Child);
13367ed5856aSAlina Sbirlea 
13377ed5856aSAlina Sbirlea   return Worklist;
13387ed5856aSAlina Sbirlea }
13397ed5856aSAlina Sbirlea 
1340df3e71e0SMarcello Maggioni void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT = nullptr,
1341df3e71e0SMarcello Maggioni                           ScalarEvolution *SE = nullptr,
1342df3e71e0SMarcello Maggioni                           LoopInfo *LI = nullptr) {
1343899809d5SHans Wennborg   assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
1344df3e71e0SMarcello Maggioni   auto *Preheader = L->getLoopPreheader();
1345df3e71e0SMarcello Maggioni   assert(Preheader && "Preheader should exist!");
1346df3e71e0SMarcello Maggioni 
1347df3e71e0SMarcello Maggioni   // Now that we know the removal is safe, remove the loop by changing the
1348df3e71e0SMarcello Maggioni   // branch from the preheader to go to the single exit block.
1349df3e71e0SMarcello Maggioni   //
1350df3e71e0SMarcello Maggioni   // Because we're deleting a large chunk of code at once, the sequence in which
1351df3e71e0SMarcello Maggioni   // we remove things is very important to avoid invalidation issues.
1352df3e71e0SMarcello Maggioni 
1353df3e71e0SMarcello Maggioni   // Tell ScalarEvolution that the loop is deleted. Do this before
1354df3e71e0SMarcello Maggioni   // deleting the loop so that ScalarEvolution can look at the loop
1355df3e71e0SMarcello Maggioni   // to determine what it needs to clean up.
1356df3e71e0SMarcello Maggioni   if (SE)
1357df3e71e0SMarcello Maggioni     SE->forgetLoop(L);
1358df3e71e0SMarcello Maggioni 
1359df3e71e0SMarcello Maggioni   auto *ExitBlock = L->getUniqueExitBlock();
1360df3e71e0SMarcello Maggioni   assert(ExitBlock && "Should have a unique exit block!");
1361df3e71e0SMarcello Maggioni   assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
1362df3e71e0SMarcello Maggioni 
1363df3e71e0SMarcello Maggioni   auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
1364df3e71e0SMarcello Maggioni   assert(OldBr && "Preheader must end with a branch");
1365df3e71e0SMarcello Maggioni   assert(OldBr->isUnconditional() && "Preheader must have a single successor");
1366df3e71e0SMarcello Maggioni   // Connect the preheader to the exit block. Keep the old edge to the header
1367df3e71e0SMarcello Maggioni   // around to perform the dominator tree update in two separate steps
1368df3e71e0SMarcello Maggioni   // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
1369df3e71e0SMarcello Maggioni   // preheader -> header.
1370df3e71e0SMarcello Maggioni   //
1371df3e71e0SMarcello Maggioni   //
1372df3e71e0SMarcello Maggioni   // 0.  Preheader          1.  Preheader           2.  Preheader
1373df3e71e0SMarcello Maggioni   //        |                    |   |                   |
1374df3e71e0SMarcello Maggioni   //        V                    |   V                   |
1375df3e71e0SMarcello Maggioni   //      Header <--\            | Header <--\           | Header <--\
1376df3e71e0SMarcello Maggioni   //       |  |     |            |  |  |     |           |  |  |     |
1377df3e71e0SMarcello Maggioni   //       |  V     |            |  |  V     |           |  |  V     |
1378df3e71e0SMarcello Maggioni   //       | Body --/            |  | Body --/           |  | Body --/
1379df3e71e0SMarcello Maggioni   //       V                     V  V                    V  V
1380df3e71e0SMarcello Maggioni   //      Exit                   Exit                    Exit
1381df3e71e0SMarcello Maggioni   //
1382df3e71e0SMarcello Maggioni   // By doing this is two separate steps we can perform the dominator tree
1383df3e71e0SMarcello Maggioni   // update without using the batch update API.
1384df3e71e0SMarcello Maggioni   //
1385df3e71e0SMarcello Maggioni   // Even when the loop is never executed, we cannot remove the edge from the
1386df3e71e0SMarcello Maggioni   // source block to the exit block. Consider the case where the unexecuted loop
1387df3e71e0SMarcello Maggioni   // branches back to an outer loop. If we deleted the loop and removed the edge
1388df3e71e0SMarcello Maggioni   // coming to this inner loop, this will break the outer loop structure (by
1389df3e71e0SMarcello Maggioni   // deleting the backedge of the outer loop). If the outer loop is indeed a
1390df3e71e0SMarcello Maggioni   // non-loop, it will be deleted in a future iteration of loop deletion pass.
1391df3e71e0SMarcello Maggioni   IRBuilder<> Builder(OldBr);
1392df3e71e0SMarcello Maggioni   Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
1393df3e71e0SMarcello Maggioni   // Remove the old branch. The conditional branch becomes a new terminator.
1394df3e71e0SMarcello Maggioni   OldBr->eraseFromParent();
1395df3e71e0SMarcello Maggioni 
1396df3e71e0SMarcello Maggioni   // Rewrite phis in the exit block to get their inputs from the Preheader
1397df3e71e0SMarcello Maggioni   // instead of the exiting block.
1398c7fc81e6SBenjamin Kramer   for (PHINode &P : ExitBlock->phis()) {
1399df3e71e0SMarcello Maggioni     // Set the zero'th element of Phi to be from the preheader and remove all
1400df3e71e0SMarcello Maggioni     // other incoming values. Given the loop has dedicated exits, all other
1401df3e71e0SMarcello Maggioni     // incoming values must be from the exiting blocks.
1402df3e71e0SMarcello Maggioni     int PredIndex = 0;
1403c7fc81e6SBenjamin Kramer     P.setIncomingBlock(PredIndex, Preheader);
1404df3e71e0SMarcello Maggioni     // Removes all incoming values from all other exiting blocks (including
1405df3e71e0SMarcello Maggioni     // duplicate values from an exiting block).
1406df3e71e0SMarcello Maggioni     // Nuke all entries except the zero'th entry which is the preheader entry.
1407df3e71e0SMarcello Maggioni     // NOTE! We need to remove Incoming Values in the reverse order as done
1408df3e71e0SMarcello Maggioni     // below, to keep the indices valid for deletion (removeIncomingValues
1409df3e71e0SMarcello Maggioni     // updates getNumIncomingValues and shifts all values down into the operand
1410df3e71e0SMarcello Maggioni     // being deleted).
1411c7fc81e6SBenjamin Kramer     for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
1412c7fc81e6SBenjamin Kramer       P.removeIncomingValue(e - i, false);
1413df3e71e0SMarcello Maggioni 
1414c7fc81e6SBenjamin Kramer     assert((P.getNumIncomingValues() == 1 &&
1415c7fc81e6SBenjamin Kramer             P.getIncomingBlock(PredIndex) == Preheader) &&
1416df3e71e0SMarcello Maggioni            "Should have exactly one value and that's from the preheader!");
1417df3e71e0SMarcello Maggioni   }
1418df3e71e0SMarcello Maggioni 
1419df3e71e0SMarcello Maggioni   // Disconnect the loop body by branching directly to its exit.
1420df3e71e0SMarcello Maggioni   Builder.SetInsertPoint(Preheader->getTerminator());
1421df3e71e0SMarcello Maggioni   Builder.CreateBr(ExitBlock);
1422df3e71e0SMarcello Maggioni   // Remove the old branch.
1423df3e71e0SMarcello Maggioni   Preheader->getTerminator()->eraseFromParent();
1424df3e71e0SMarcello Maggioni 
1425df3e71e0SMarcello Maggioni   if (DT) {
1426df3e71e0SMarcello Maggioni     // Update the dominator tree by informing it about the new edge from the
1427df3e71e0SMarcello Maggioni     // preheader to the exit.
1428df3e71e0SMarcello Maggioni     DT->insertEdge(Preheader, ExitBlock);
1429df3e71e0SMarcello Maggioni     // Inform the dominator tree about the removed edge.
1430df3e71e0SMarcello Maggioni     DT->deleteEdge(Preheader, L->getHeader());
1431df3e71e0SMarcello Maggioni   }
1432df3e71e0SMarcello Maggioni 
1433a757d65cSSerguei Katkov   // Given LCSSA form is satisfied, we should not have users of instructions
1434a757d65cSSerguei Katkov   // within the dead loop outside of the loop. However, LCSSA doesn't take
1435a757d65cSSerguei Katkov   // unreachable uses into account. We handle them here.
1436a757d65cSSerguei Katkov   // We could do it after drop all references (in this case all users in the
1437a757d65cSSerguei Katkov   // loop will be already eliminated and we have less work to do but according
1438a757d65cSSerguei Katkov   // to API doc of User::dropAllReferences only valid operation after dropping
1439a757d65cSSerguei Katkov   // references, is deletion. So let's substitute all usages of
1440a757d65cSSerguei Katkov   // instruction from the loop with undef value of corresponding type first.
1441a757d65cSSerguei Katkov   for (auto *Block : L->blocks())
1442a757d65cSSerguei Katkov     for (Instruction &I : *Block) {
1443a757d65cSSerguei Katkov       auto *Undef = UndefValue::get(I.getType());
1444a757d65cSSerguei Katkov       for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) {
1445a757d65cSSerguei Katkov         Use &U = *UI;
1446a757d65cSSerguei Katkov         ++UI;
1447a757d65cSSerguei Katkov         if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
1448a757d65cSSerguei Katkov           if (L->contains(Usr->getParent()))
1449a757d65cSSerguei Katkov             continue;
1450a757d65cSSerguei Katkov         // If we have a DT then we can check that uses outside a loop only in
1451a757d65cSSerguei Katkov         // unreachable block.
1452a757d65cSSerguei Katkov         if (DT)
1453a757d65cSSerguei Katkov           assert(!DT->isReachableFromEntry(U) &&
1454a757d65cSSerguei Katkov                  "Unexpected user in reachable block");
1455a757d65cSSerguei Katkov         U.set(Undef);
1456a757d65cSSerguei Katkov       }
1457a757d65cSSerguei Katkov     }
1458a757d65cSSerguei Katkov 
1459df3e71e0SMarcello Maggioni   // Remove the block from the reference counting scheme, so that we can
1460df3e71e0SMarcello Maggioni   // delete it freely later.
1461df3e71e0SMarcello Maggioni   for (auto *Block : L->blocks())
1462df3e71e0SMarcello Maggioni     Block->dropAllReferences();
1463df3e71e0SMarcello Maggioni 
1464df3e71e0SMarcello Maggioni   if (LI) {
1465df3e71e0SMarcello Maggioni     // Erase the instructions and the blocks without having to worry
1466df3e71e0SMarcello Maggioni     // about ordering because we already dropped the references.
1467df3e71e0SMarcello Maggioni     // NOTE: This iteration is safe because erasing the block does not remove
1468df3e71e0SMarcello Maggioni     // its entry from the loop's block list.  We do that in the next section.
1469df3e71e0SMarcello Maggioni     for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end();
1470df3e71e0SMarcello Maggioni          LpI != LpE; ++LpI)
1471df3e71e0SMarcello Maggioni       (*LpI)->eraseFromParent();
1472df3e71e0SMarcello Maggioni 
1473df3e71e0SMarcello Maggioni     // Finally, the blocks from loopinfo.  This has to happen late because
1474df3e71e0SMarcello Maggioni     // otherwise our loop iterators won't work.
1475df3e71e0SMarcello Maggioni 
1476df3e71e0SMarcello Maggioni     SmallPtrSet<BasicBlock *, 8> blocks;
1477df3e71e0SMarcello Maggioni     blocks.insert(L->block_begin(), L->block_end());
1478df3e71e0SMarcello Maggioni     for (BasicBlock *BB : blocks)
1479df3e71e0SMarcello Maggioni       LI->removeBlock(BB);
1480df3e71e0SMarcello Maggioni 
1481df3e71e0SMarcello Maggioni     // The last step is to update LoopInfo now that we've eliminated this loop.
1482df3e71e0SMarcello Maggioni     LI->erase(L);
1483df3e71e0SMarcello Maggioni   }
1484df3e71e0SMarcello Maggioni }
1485df3e71e0SMarcello Maggioni 
148641d72a86SDehao Chen Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) {
148741d72a86SDehao Chen   // Only support loops with a unique exiting block, and a latch.
148841d72a86SDehao Chen   if (!L->getExitingBlock())
148941d72a86SDehao Chen     return None;
149041d72a86SDehao Chen 
1491d24ddcd6SHiroshi Inoue   // Get the branch weights for the loop's backedge.
149241d72a86SDehao Chen   BranchInst *LatchBR =
149341d72a86SDehao Chen       dyn_cast<BranchInst>(L->getLoopLatch()->getTerminator());
149441d72a86SDehao Chen   if (!LatchBR || LatchBR->getNumSuccessors() != 2)
149541d72a86SDehao Chen     return None;
149641d72a86SDehao Chen 
149741d72a86SDehao Chen   assert((LatchBR->getSuccessor(0) == L->getHeader() ||
149841d72a86SDehao Chen           LatchBR->getSuccessor(1) == L->getHeader()) &&
149941d72a86SDehao Chen          "At least one edge out of the latch must go to the header");
150041d72a86SDehao Chen 
150141d72a86SDehao Chen   // To estimate the number of times the loop body was executed, we want to
150241d72a86SDehao Chen   // know the number of times the backedge was taken, vs. the number of times
150341d72a86SDehao Chen   // we exited the loop.
150441d72a86SDehao Chen   uint64_t TrueVal, FalseVal;
1505b151a641SMichael Kuperstein   if (!LatchBR->extractProfMetadata(TrueVal, FalseVal))
150641d72a86SDehao Chen     return None;
150741d72a86SDehao Chen 
1508b151a641SMichael Kuperstein   if (!TrueVal || !FalseVal)
1509b151a641SMichael Kuperstein     return 0;
151041d72a86SDehao Chen 
1511b151a641SMichael Kuperstein   // Divide the count of the backedge by the count of the edge exiting the loop,
1512b151a641SMichael Kuperstein   // rounding to nearest.
151341d72a86SDehao Chen   if (LatchBR->getSuccessor(0) == L->getHeader())
1514b151a641SMichael Kuperstein     return (TrueVal + (FalseVal / 2)) / FalseVal;
151541d72a86SDehao Chen   else
1516b151a641SMichael Kuperstein     return (FalseVal + (TrueVal / 2)) / TrueVal;
151741d72a86SDehao Chen }
1518cf9daa33SAmara Emerson 
1519cf9daa33SAmara Emerson /// \brief Adds a 'fast' flag to floating point operations.
1520cf9daa33SAmara Emerson static Value *addFastMathFlag(Value *V) {
1521cf9daa33SAmara Emerson   if (isa<FPMathOperator>(V)) {
1522cf9daa33SAmara Emerson     FastMathFlags Flags;
1523629c4115SSanjay Patel     Flags.setFast();
1524cf9daa33SAmara Emerson     cast<Instruction>(V)->setFastMathFlags(Flags);
1525cf9daa33SAmara Emerson   }
1526cf9daa33SAmara Emerson   return V;
1527cf9daa33SAmara Emerson }
1528cf9daa33SAmara Emerson 
1529cf9daa33SAmara Emerson // Helper to generate a log2 shuffle reduction.
1530836b0f48SAmara Emerson Value *
1531836b0f48SAmara Emerson llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op,
1532836b0f48SAmara Emerson                           RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
1533836b0f48SAmara Emerson                           ArrayRef<Value *> RedOps) {
1534cf9daa33SAmara Emerson   unsigned VF = Src->getType()->getVectorNumElements();
1535cf9daa33SAmara Emerson   // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1536cf9daa33SAmara Emerson   // and vector ops, reducing the set of values being computed by half each
1537cf9daa33SAmara Emerson   // round.
1538cf9daa33SAmara Emerson   assert(isPowerOf2_32(VF) &&
1539cf9daa33SAmara Emerson          "Reduction emission only supported for pow2 vectors!");
1540cf9daa33SAmara Emerson   Value *TmpVec = Src;
1541cf9daa33SAmara Emerson   SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
1542cf9daa33SAmara Emerson   for (unsigned i = VF; i != 1; i >>= 1) {
1543cf9daa33SAmara Emerson     // Move the upper half of the vector to the lower half.
1544cf9daa33SAmara Emerson     for (unsigned j = 0; j != i / 2; ++j)
1545cf9daa33SAmara Emerson       ShuffleMask[j] = Builder.getInt32(i / 2 + j);
1546cf9daa33SAmara Emerson 
1547cf9daa33SAmara Emerson     // Fill the rest of the mask with undef.
1548cf9daa33SAmara Emerson     std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
1549cf9daa33SAmara Emerson               UndefValue::get(Builder.getInt32Ty()));
1550cf9daa33SAmara Emerson 
1551cf9daa33SAmara Emerson     Value *Shuf = Builder.CreateShuffleVector(
1552cf9daa33SAmara Emerson         TmpVec, UndefValue::get(TmpVec->getType()),
1553cf9daa33SAmara Emerson         ConstantVector::get(ShuffleMask), "rdx.shuf");
1554cf9daa33SAmara Emerson 
1555cf9daa33SAmara Emerson     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
1556cf9daa33SAmara Emerson       // Floating point operations had to be 'fast' to enable the reduction.
1557cf9daa33SAmara Emerson       TmpVec = addFastMathFlag(Builder.CreateBinOp((Instruction::BinaryOps)Op,
1558cf9daa33SAmara Emerson                                                    TmpVec, Shuf, "bin.rdx"));
1559cf9daa33SAmara Emerson     } else {
1560cf9daa33SAmara Emerson       assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
1561cf9daa33SAmara Emerson              "Invalid min/max");
1562cf9daa33SAmara Emerson       TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind, TmpVec,
1563cf9daa33SAmara Emerson                                                     Shuf);
1564cf9daa33SAmara Emerson     }
1565cf9daa33SAmara Emerson     if (!RedOps.empty())
1566cf9daa33SAmara Emerson       propagateIRFlags(TmpVec, RedOps);
1567cf9daa33SAmara Emerson   }
1568cf9daa33SAmara Emerson   // The result is in the first element of the vector.
1569cf9daa33SAmara Emerson   return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1570cf9daa33SAmara Emerson }
1571cf9daa33SAmara Emerson 
1572cf9daa33SAmara Emerson /// Create a simple vector reduction specified by an opcode and some
1573cf9daa33SAmara Emerson /// flags (if generating min/max reductions).
1574cf9daa33SAmara Emerson Value *llvm::createSimpleTargetReduction(
1575cf9daa33SAmara Emerson     IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode,
1576cf9daa33SAmara Emerson     Value *Src, TargetTransformInfo::ReductionFlags Flags,
1577cf9daa33SAmara Emerson     ArrayRef<Value *> RedOps) {
1578cf9daa33SAmara Emerson   assert(isa<VectorType>(Src->getType()) && "Type must be a vector");
1579cf9daa33SAmara Emerson 
1580cf9daa33SAmara Emerson   Value *ScalarUdf = UndefValue::get(Src->getType()->getVectorElementType());
1581cf9daa33SAmara Emerson   std::function<Value*()> BuildFunc;
1582cf9daa33SAmara Emerson   using RD = RecurrenceDescriptor;
1583cf9daa33SAmara Emerson   RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
1584cf9daa33SAmara Emerson   // TODO: Support creating ordered reductions.
15851ea7b6f7SSanjay Patel   FastMathFlags FMFFast;
15861ea7b6f7SSanjay Patel   FMFFast.setFast();
1587cf9daa33SAmara Emerson 
1588cf9daa33SAmara Emerson   switch (Opcode) {
1589cf9daa33SAmara Emerson   case Instruction::Add:
1590cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateAddReduce(Src); };
1591cf9daa33SAmara Emerson     break;
1592cf9daa33SAmara Emerson   case Instruction::Mul:
1593cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateMulReduce(Src); };
1594cf9daa33SAmara Emerson     break;
1595cf9daa33SAmara Emerson   case Instruction::And:
1596cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateAndReduce(Src); };
1597cf9daa33SAmara Emerson     break;
1598cf9daa33SAmara Emerson   case Instruction::Or:
1599cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateOrReduce(Src); };
1600cf9daa33SAmara Emerson     break;
1601cf9daa33SAmara Emerson   case Instruction::Xor:
1602cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateXorReduce(Src); };
1603cf9daa33SAmara Emerson     break;
1604cf9daa33SAmara Emerson   case Instruction::FAdd:
1605cf9daa33SAmara Emerson     BuildFunc = [&]() {
1606cf9daa33SAmara Emerson       auto Rdx = Builder.CreateFAddReduce(ScalarUdf, Src);
16071ea7b6f7SSanjay Patel       cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
1608cf9daa33SAmara Emerson       return Rdx;
1609cf9daa33SAmara Emerson     };
1610cf9daa33SAmara Emerson     break;
1611cf9daa33SAmara Emerson   case Instruction::FMul:
1612cf9daa33SAmara Emerson     BuildFunc = [&]() {
1613cf9daa33SAmara Emerson       auto Rdx = Builder.CreateFMulReduce(ScalarUdf, Src);
16141ea7b6f7SSanjay Patel       cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
1615cf9daa33SAmara Emerson       return Rdx;
1616cf9daa33SAmara Emerson     };
1617cf9daa33SAmara Emerson     break;
1618cf9daa33SAmara Emerson   case Instruction::ICmp:
1619cf9daa33SAmara Emerson     if (Flags.IsMaxOp) {
1620cf9daa33SAmara Emerson       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
1621cf9daa33SAmara Emerson       BuildFunc = [&]() {
1622cf9daa33SAmara Emerson         return Builder.CreateIntMaxReduce(Src, Flags.IsSigned);
1623cf9daa33SAmara Emerson       };
1624cf9daa33SAmara Emerson     } else {
1625cf9daa33SAmara Emerson       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
1626cf9daa33SAmara Emerson       BuildFunc = [&]() {
1627cf9daa33SAmara Emerson         return Builder.CreateIntMinReduce(Src, Flags.IsSigned);
1628cf9daa33SAmara Emerson       };
1629cf9daa33SAmara Emerson     }
1630cf9daa33SAmara Emerson     break;
1631cf9daa33SAmara Emerson   case Instruction::FCmp:
1632cf9daa33SAmara Emerson     if (Flags.IsMaxOp) {
1633cf9daa33SAmara Emerson       MinMaxKind = RD::MRK_FloatMax;
1634cf9daa33SAmara Emerson       BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); };
1635cf9daa33SAmara Emerson     } else {
1636cf9daa33SAmara Emerson       MinMaxKind = RD::MRK_FloatMin;
1637cf9daa33SAmara Emerson       BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); };
1638cf9daa33SAmara Emerson     }
1639cf9daa33SAmara Emerson     break;
1640cf9daa33SAmara Emerson   default:
1641cf9daa33SAmara Emerson     llvm_unreachable("Unhandled opcode");
1642cf9daa33SAmara Emerson     break;
1643cf9daa33SAmara Emerson   }
1644cf9daa33SAmara Emerson   if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags))
1645cf9daa33SAmara Emerson     return BuildFunc();
1646cf9daa33SAmara Emerson   return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps);
1647cf9daa33SAmara Emerson }
1648cf9daa33SAmara Emerson 
1649cf9daa33SAmara Emerson /// Create a vector reduction using a given recurrence descriptor.
16503e069f57SSanjay Patel Value *llvm::createTargetReduction(IRBuilder<> &B,
1651cf9daa33SAmara Emerson                                    const TargetTransformInfo *TTI,
1652cf9daa33SAmara Emerson                                    RecurrenceDescriptor &Desc, Value *Src,
1653cf9daa33SAmara Emerson                                    bool NoNaN) {
1654cf9daa33SAmara Emerson   // TODO: Support in-order reductions based on the recurrence descriptor.
16553e069f57SSanjay Patel   using RD = RecurrenceDescriptor;
16563e069f57SSanjay Patel   RD::RecurrenceKind RecKind = Desc.getRecurrenceKind();
1657cf9daa33SAmara Emerson   TargetTransformInfo::ReductionFlags Flags;
1658cf9daa33SAmara Emerson   Flags.NoNaN = NoNaN;
1659cf9daa33SAmara Emerson   switch (RecKind) {
16603e069f57SSanjay Patel   case RD::RK_FloatAdd:
16613e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags);
16623e069f57SSanjay Patel   case RD::RK_FloatMult:
16633e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags);
16643e069f57SSanjay Patel   case RD::RK_IntegerAdd:
16653e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags);
16663e069f57SSanjay Patel   case RD::RK_IntegerMult:
16673e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags);
16683e069f57SSanjay Patel   case RD::RK_IntegerAnd:
16693e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags);
16703e069f57SSanjay Patel   case RD::RK_IntegerOr:
16713e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags);
16723e069f57SSanjay Patel   case RD::RK_IntegerXor:
16733e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags);
16743e069f57SSanjay Patel   case RD::RK_IntegerMinMax: {
16753e069f57SSanjay Patel     RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind();
16763e069f57SSanjay Patel     Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax);
16773e069f57SSanjay Patel     Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin);
16783e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags);
1679cf9daa33SAmara Emerson   }
16803e069f57SSanjay Patel   case RD::RK_FloatMinMax: {
16813e069f57SSanjay Patel     Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax;
16823e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags);
1683cf9daa33SAmara Emerson   }
1684cf9daa33SAmara Emerson   default:
1685cf9daa33SAmara Emerson     llvm_unreachable("Unhandled RecKind");
1686cf9daa33SAmara Emerson   }
1687cf9daa33SAmara Emerson }
1688cf9daa33SAmara Emerson 
1689a61f4b89SDinar Temirbulatov void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
1690a61f4b89SDinar Temirbulatov   auto *VecOp = dyn_cast<Instruction>(I);
1691a61f4b89SDinar Temirbulatov   if (!VecOp)
1692a61f4b89SDinar Temirbulatov     return;
1693a61f4b89SDinar Temirbulatov   auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
1694a61f4b89SDinar Temirbulatov                                             : dyn_cast<Instruction>(OpValue);
1695a61f4b89SDinar Temirbulatov   if (!Intersection)
1696a61f4b89SDinar Temirbulatov     return;
1697a61f4b89SDinar Temirbulatov   const unsigned Opcode = Intersection->getOpcode();
1698a61f4b89SDinar Temirbulatov   VecOp->copyIRFlags(Intersection);
1699a61f4b89SDinar Temirbulatov   for (auto *V : VL) {
1700a61f4b89SDinar Temirbulatov     auto *Instr = dyn_cast<Instruction>(V);
1701a61f4b89SDinar Temirbulatov     if (!Instr)
1702a61f4b89SDinar Temirbulatov       continue;
1703a61f4b89SDinar Temirbulatov     if (OpValue == nullptr || Opcode == Instr->getOpcode())
1704a61f4b89SDinar Temirbulatov       VecOp->andIRFlags(V);
1705cf9daa33SAmara Emerson   }
1706cf9daa33SAmara Emerson }
1707