1 //===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines common loop utility functions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/AliasAnalysis.h"
15 #include "llvm/Analysis/BasicAliasAnalysis.h"
16 #include "llvm/Analysis/LoopInfo.h"
17 #include "llvm/Analysis/GlobalsModRef.h"
18 #include "llvm/Analysis/ScalarEvolution.h"
19 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
20 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
21 #include "llvm/IR/Dominators.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/PatternMatch.h"
25 #include "llvm/IR/ValueHandle.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Transforms/Utils/LoopUtils.h"
29 
30 using namespace llvm;
31 using namespace llvm::PatternMatch;
32 
33 #define DEBUG_TYPE "loop-utils"
34 
35 bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
36                                         SmallPtrSetImpl<Instruction *> &Set) {
37   for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
38     if (!Set.count(dyn_cast<Instruction>(*Use)))
39       return false;
40   return true;
41 }
42 
43 bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) {
44   switch (Kind) {
45   default:
46     break;
47   case RK_IntegerAdd:
48   case RK_IntegerMult:
49   case RK_IntegerOr:
50   case RK_IntegerAnd:
51   case RK_IntegerXor:
52   case RK_IntegerMinMax:
53     return true;
54   }
55   return false;
56 }
57 
58 bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) {
59   return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
60 }
61 
62 bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) {
63   switch (Kind) {
64   default:
65     break;
66   case RK_IntegerAdd:
67   case RK_IntegerMult:
68   case RK_FloatAdd:
69   case RK_FloatMult:
70     return true;
71   }
72   return false;
73 }
74 
75 Instruction *
76 RecurrenceDescriptor::lookThroughAnd(PHINode *Phi, Type *&RT,
77                                      SmallPtrSetImpl<Instruction *> &Visited,
78                                      SmallPtrSetImpl<Instruction *> &CI) {
79   if (!Phi->hasOneUse())
80     return Phi;
81 
82   const APInt *M = nullptr;
83   Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
84 
85   // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
86   // with a new integer type of the corresponding bit width.
87   if (match(J, m_CombineOr(m_And(m_Instruction(I), m_APInt(M)),
88                            m_And(m_APInt(M), m_Instruction(I))))) {
89     int32_t Bits = (*M + 1).exactLogBase2();
90     if (Bits > 0) {
91       RT = IntegerType::get(Phi->getContext(), Bits);
92       Visited.insert(Phi);
93       CI.insert(J);
94       return J;
95     }
96   }
97   return Phi;
98 }
99 
100 bool RecurrenceDescriptor::getSourceExtensionKind(
101     Instruction *Start, Instruction *Exit, Type *RT, bool &IsSigned,
102     SmallPtrSetImpl<Instruction *> &Visited,
103     SmallPtrSetImpl<Instruction *> &CI) {
104 
105   SmallVector<Instruction *, 8> Worklist;
106   bool FoundOneOperand = false;
107   unsigned DstSize = RT->getPrimitiveSizeInBits();
108   Worklist.push_back(Exit);
109 
110   // Traverse the instructions in the reduction expression, beginning with the
111   // exit value.
112   while (!Worklist.empty()) {
113     Instruction *I = Worklist.pop_back_val();
114     for (Use &U : I->operands()) {
115 
116       // Terminate the traversal if the operand is not an instruction, or we
117       // reach the starting value.
118       Instruction *J = dyn_cast<Instruction>(U.get());
119       if (!J || J == Start)
120         continue;
121 
122       // Otherwise, investigate the operation if it is also in the expression.
123       if (Visited.count(J)) {
124         Worklist.push_back(J);
125         continue;
126       }
127 
128       // If the operand is not in Visited, it is not a reduction operation, but
129       // it does feed into one. Make sure it is either a single-use sign- or
130       // zero-extend instruction.
131       CastInst *Cast = dyn_cast<CastInst>(J);
132       bool IsSExtInst = isa<SExtInst>(J);
133       if (!Cast || !Cast->hasOneUse() || !(isa<ZExtInst>(J) || IsSExtInst))
134         return false;
135 
136       // Ensure the source type of the extend is no larger than the reduction
137       // type. It is not necessary for the types to be identical.
138       unsigned SrcSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
139       if (SrcSize > DstSize)
140         return false;
141 
142       // Furthermore, ensure that all such extends are of the same kind.
143       if (FoundOneOperand) {
144         if (IsSigned != IsSExtInst)
145           return false;
146       } else {
147         FoundOneOperand = true;
148         IsSigned = IsSExtInst;
149       }
150 
151       // Lastly, if the source type of the extend matches the reduction type,
152       // add the extend to CI so that we can avoid accounting for it in the
153       // cost model.
154       if (SrcSize == DstSize)
155         CI.insert(Cast);
156     }
157   }
158   return true;
159 }
160 
161 bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind,
162                                            Loop *TheLoop, bool HasFunNoNaNAttr,
163                                            RecurrenceDescriptor &RedDes) {
164   if (Phi->getNumIncomingValues() != 2)
165     return false;
166 
167   // Reduction variables are only found in the loop header block.
168   if (Phi->getParent() != TheLoop->getHeader())
169     return false;
170 
171   // Obtain the reduction start value from the value that comes from the loop
172   // preheader.
173   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
174 
175   // ExitInstruction is the single value which is used outside the loop.
176   // We only allow for a single reduction value to be used outside the loop.
177   // This includes users of the reduction, variables (which form a cycle
178   // which ends in the phi node).
179   Instruction *ExitInstruction = nullptr;
180   // Indicates that we found a reduction operation in our scan.
181   bool FoundReduxOp = false;
182 
183   // We start with the PHI node and scan for all of the users of this
184   // instruction. All users must be instructions that can be used as reduction
185   // variables (such as ADD). We must have a single out-of-block user. The cycle
186   // must include the original PHI.
187   bool FoundStartPHI = false;
188 
189   // To recognize min/max patterns formed by a icmp select sequence, we store
190   // the number of instruction we saw from the recognized min/max pattern,
191   //  to make sure we only see exactly the two instructions.
192   unsigned NumCmpSelectPatternInst = 0;
193   InstDesc ReduxDesc(false, nullptr);
194 
195   // Data used for determining if the recurrence has been type-promoted.
196   Type *RecurrenceType = Phi->getType();
197   SmallPtrSet<Instruction *, 4> CastInsts;
198   Instruction *Start = Phi;
199   bool IsSigned = false;
200 
201   SmallPtrSet<Instruction *, 8> VisitedInsts;
202   SmallVector<Instruction *, 8> Worklist;
203 
204   // Return early if the recurrence kind does not match the type of Phi. If the
205   // recurrence kind is arithmetic, we attempt to look through AND operations
206   // resulting from the type promotion performed by InstCombine.  Vector
207   // operations are not limited to the legal integer widths, so we may be able
208   // to evaluate the reduction in the narrower width.
209   if (RecurrenceType->isFloatingPointTy()) {
210     if (!isFloatingPointRecurrenceKind(Kind))
211       return false;
212   } else {
213     if (!isIntegerRecurrenceKind(Kind))
214       return false;
215     if (isArithmeticRecurrenceKind(Kind))
216       Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
217   }
218 
219   Worklist.push_back(Start);
220   VisitedInsts.insert(Start);
221 
222   // A value in the reduction can be used:
223   //  - By the reduction:
224   //      - Reduction operation:
225   //        - One use of reduction value (safe).
226   //        - Multiple use of reduction value (not safe).
227   //      - PHI:
228   //        - All uses of the PHI must be the reduction (safe).
229   //        - Otherwise, not safe.
230   //  - By one instruction outside of the loop (safe).
231   //  - By further instructions outside of the loop (not safe).
232   //  - By an instruction that is not part of the reduction (not safe).
233   //    This is either:
234   //      * An instruction type other than PHI or the reduction operation.
235   //      * A PHI in the header other than the initial PHI.
236   while (!Worklist.empty()) {
237     Instruction *Cur = Worklist.back();
238     Worklist.pop_back();
239 
240     // No Users.
241     // If the instruction has no users then this is a broken chain and can't be
242     // a reduction variable.
243     if (Cur->use_empty())
244       return false;
245 
246     bool IsAPhi = isa<PHINode>(Cur);
247 
248     // A header PHI use other than the original PHI.
249     if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
250       return false;
251 
252     // Reductions of instructions such as Div, and Sub is only possible if the
253     // LHS is the reduction variable.
254     if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
255         !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
256         !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
257       return false;
258 
259     // Any reduction instruction must be of one of the allowed kinds. We ignore
260     // the starting value (the Phi or an AND instruction if the Phi has been
261     // type-promoted).
262     if (Cur != Start) {
263       ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
264       if (!ReduxDesc.isRecurrence())
265         return false;
266     }
267 
268     // A reduction operation must only have one use of the reduction value.
269     if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
270         hasMultipleUsesOf(Cur, VisitedInsts))
271       return false;
272 
273     // All inputs to a PHI node must be a reduction value.
274     if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
275       return false;
276 
277     if (Kind == RK_IntegerMinMax &&
278         (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
279       ++NumCmpSelectPatternInst;
280     if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
281       ++NumCmpSelectPatternInst;
282 
283     // Check  whether we found a reduction operator.
284     FoundReduxOp |= !IsAPhi && Cur != Start;
285 
286     // Process users of current instruction. Push non-PHI nodes after PHI nodes
287     // onto the stack. This way we are going to have seen all inputs to PHI
288     // nodes once we get to them.
289     SmallVector<Instruction *, 8> NonPHIs;
290     SmallVector<Instruction *, 8> PHIs;
291     for (User *U : Cur->users()) {
292       Instruction *UI = cast<Instruction>(U);
293 
294       // Check if we found the exit user.
295       BasicBlock *Parent = UI->getParent();
296       if (!TheLoop->contains(Parent)) {
297         // Exit if you find multiple outside users or if the header phi node is
298         // being used. In this case the user uses the value of the previous
299         // iteration, in which case we would loose "VF-1" iterations of the
300         // reduction operation if we vectorize.
301         if (ExitInstruction != nullptr || Cur == Phi)
302           return false;
303 
304         // The instruction used by an outside user must be the last instruction
305         // before we feed back to the reduction phi. Otherwise, we loose VF-1
306         // operations on the value.
307         if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
308           return false;
309 
310         ExitInstruction = Cur;
311         continue;
312       }
313 
314       // Process instructions only once (termination). Each reduction cycle
315       // value must only be used once, except by phi nodes and min/max
316       // reductions which are represented as a cmp followed by a select.
317       InstDesc IgnoredVal(false, nullptr);
318       if (VisitedInsts.insert(UI).second) {
319         if (isa<PHINode>(UI))
320           PHIs.push_back(UI);
321         else
322           NonPHIs.push_back(UI);
323       } else if (!isa<PHINode>(UI) &&
324                  ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
325                    !isa<SelectInst>(UI)) ||
326                   !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence()))
327         return false;
328 
329       // Remember that we completed the cycle.
330       if (UI == Phi)
331         FoundStartPHI = true;
332     }
333     Worklist.append(PHIs.begin(), PHIs.end());
334     Worklist.append(NonPHIs.begin(), NonPHIs.end());
335   }
336 
337   // This means we have seen one but not the other instruction of the
338   // pattern or more than just a select and cmp.
339   if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
340       NumCmpSelectPatternInst != 2)
341     return false;
342 
343   if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
344     return false;
345 
346   // If we think Phi may have been type-promoted, we also need to ensure that
347   // all source operands of the reduction are either SExtInsts or ZEstInsts. If
348   // so, we will be able to evaluate the reduction in the narrower bit width.
349   if (Start != Phi)
350     if (!getSourceExtensionKind(Start, ExitInstruction, RecurrenceType,
351                                 IsSigned, VisitedInsts, CastInsts))
352       return false;
353 
354   // We found a reduction var if we have reached the original phi node and we
355   // only have a single instruction with out-of-loop users.
356 
357   // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
358   // is saved as part of the RecurrenceDescriptor.
359 
360   // Save the description of this reduction variable.
361   RecurrenceDescriptor RD(
362       RdxStart, ExitInstruction, Kind, ReduxDesc.getMinMaxKind(),
363       ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts);
364   RedDes = RD;
365 
366   return true;
367 }
368 
369 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
370 /// pattern corresponding to a min(X, Y) or max(X, Y).
371 RecurrenceDescriptor::InstDesc
372 RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) {
373 
374   assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
375          "Expect a select instruction");
376   Instruction *Cmp = nullptr;
377   SelectInst *Select = nullptr;
378 
379   // We must handle the select(cmp()) as a single instruction. Advance to the
380   // select.
381   if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
382     if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
383       return InstDesc(false, I);
384     return InstDesc(Select, Prev.getMinMaxKind());
385   }
386 
387   // Only handle single use cases for now.
388   if (!(Select = dyn_cast<SelectInst>(I)))
389     return InstDesc(false, I);
390   if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
391       !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
392     return InstDesc(false, I);
393   if (!Cmp->hasOneUse())
394     return InstDesc(false, I);
395 
396   Value *CmpLeft;
397   Value *CmpRight;
398 
399   // Look for a min/max pattern.
400   if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
401     return InstDesc(Select, MRK_UIntMin);
402   else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
403     return InstDesc(Select, MRK_UIntMax);
404   else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
405     return InstDesc(Select, MRK_SIntMax);
406   else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
407     return InstDesc(Select, MRK_SIntMin);
408   else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
409     return InstDesc(Select, MRK_FloatMin);
410   else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
411     return InstDesc(Select, MRK_FloatMax);
412   else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
413     return InstDesc(Select, MRK_FloatMin);
414   else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
415     return InstDesc(Select, MRK_FloatMax);
416 
417   return InstDesc(false, I);
418 }
419 
420 RecurrenceDescriptor::InstDesc
421 RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
422                                         InstDesc &Prev, bool HasFunNoNaNAttr) {
423   bool FP = I->getType()->isFloatingPointTy();
424   Instruction *UAI = Prev.getUnsafeAlgebraInst();
425   if (!UAI && FP && !I->hasUnsafeAlgebra())
426     UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
427 
428   switch (I->getOpcode()) {
429   default:
430     return InstDesc(false, I);
431   case Instruction::PHI:
432     return InstDesc(I, Prev.getMinMaxKind());
433   case Instruction::Sub:
434   case Instruction::Add:
435     return InstDesc(Kind == RK_IntegerAdd, I);
436   case Instruction::Mul:
437     return InstDesc(Kind == RK_IntegerMult, I);
438   case Instruction::And:
439     return InstDesc(Kind == RK_IntegerAnd, I);
440   case Instruction::Or:
441     return InstDesc(Kind == RK_IntegerOr, I);
442   case Instruction::Xor:
443     return InstDesc(Kind == RK_IntegerXor, I);
444   case Instruction::FMul:
445     return InstDesc(Kind == RK_FloatMult, I, UAI);
446   case Instruction::FSub:
447   case Instruction::FAdd:
448     return InstDesc(Kind == RK_FloatAdd, I, UAI);
449   case Instruction::FCmp:
450   case Instruction::ICmp:
451   case Instruction::Select:
452     if (Kind != RK_IntegerMinMax &&
453         (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
454       return InstDesc(false, I);
455     return isMinMaxSelectCmpPattern(I, Prev);
456   }
457 }
458 
459 bool RecurrenceDescriptor::hasMultipleUsesOf(
460     Instruction *I, SmallPtrSetImpl<Instruction *> &Insts) {
461   unsigned NumUses = 0;
462   for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
463        ++Use) {
464     if (Insts.count(dyn_cast<Instruction>(*Use)))
465       ++NumUses;
466     if (NumUses > 1)
467       return true;
468   }
469 
470   return false;
471 }
472 bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
473                                           RecurrenceDescriptor &RedDes) {
474 
475   bool HasFunNoNaNAttr = false;
476   BasicBlock *Header = TheLoop->getHeader();
477   Function &F = *Header->getParent();
478   if (F.hasFnAttribute("no-nans-fp-math"))
479     HasFunNoNaNAttr =
480         F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
481 
482   if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
483     DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
484     return true;
485   }
486   if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
487     DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
488     return true;
489   }
490   if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes)) {
491     DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
492     return true;
493   }
494   if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes)) {
495     DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
496     return true;
497   }
498   if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes)) {
499     DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
500     return true;
501   }
502   if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr,
503                       RedDes)) {
504     DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
505     return true;
506   }
507   if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
508     DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
509     return true;
510   }
511   if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
512     DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
513     return true;
514   }
515   if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes)) {
516     DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi << "\n");
517     return true;
518   }
519   // Not a reduction of known type.
520   return false;
521 }
522 
523 bool RecurrenceDescriptor::isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop,
524                                                   DominatorTree *DT) {
525 
526   // Ensure the phi node is in the loop header and has two incoming values.
527   if (Phi->getParent() != TheLoop->getHeader() ||
528       Phi->getNumIncomingValues() != 2)
529     return false;
530 
531   // Ensure the loop has a preheader and a single latch block. The loop
532   // vectorizer will need the latch to set up the next iteration of the loop.
533   auto *Preheader = TheLoop->getLoopPreheader();
534   auto *Latch = TheLoop->getLoopLatch();
535   if (!Preheader || !Latch)
536     return false;
537 
538   // Ensure the phi node's incoming blocks are the loop preheader and latch.
539   if (Phi->getBasicBlockIndex(Preheader) < 0 ||
540       Phi->getBasicBlockIndex(Latch) < 0)
541     return false;
542 
543   // Get the previous value. The previous value comes from the latch edge while
544   // the initial value comes form the preheader edge.
545   auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
546   if (!Previous || !TheLoop->contains(Previous))
547     return false;
548 
549   // Ensure every user of the phi node is dominated by the previous value. The
550   // dominance requirement ensures the loop vectorizer will not need to
551   // vectorize the initial value prior to the first iteration of the loop.
552   for (User *U : Phi->users())
553     if (auto *I = dyn_cast<Instruction>(U))
554       if (!DT->dominates(Previous, I))
555         return false;
556 
557   return true;
558 }
559 
560 /// This function returns the identity element (or neutral element) for
561 /// the operation K.
562 Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K,
563                                                       Type *Tp) {
564   switch (K) {
565   case RK_IntegerXor:
566   case RK_IntegerAdd:
567   case RK_IntegerOr:
568     // Adding, Xoring, Oring zero to a number does not change it.
569     return ConstantInt::get(Tp, 0);
570   case RK_IntegerMult:
571     // Multiplying a number by 1 does not change it.
572     return ConstantInt::get(Tp, 1);
573   case RK_IntegerAnd:
574     // AND-ing a number with an all-1 value does not change it.
575     return ConstantInt::get(Tp, -1, true);
576   case RK_FloatMult:
577     // Multiplying a number by 1 does not change it.
578     return ConstantFP::get(Tp, 1.0L);
579   case RK_FloatAdd:
580     // Adding zero to a number does not change it.
581     return ConstantFP::get(Tp, 0.0L);
582   default:
583     llvm_unreachable("Unknown recurrence kind");
584   }
585 }
586 
587 /// This function translates the recurrence kind to an LLVM binary operator.
588 unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) {
589   switch (Kind) {
590   case RK_IntegerAdd:
591     return Instruction::Add;
592   case RK_IntegerMult:
593     return Instruction::Mul;
594   case RK_IntegerOr:
595     return Instruction::Or;
596   case RK_IntegerAnd:
597     return Instruction::And;
598   case RK_IntegerXor:
599     return Instruction::Xor;
600   case RK_FloatMult:
601     return Instruction::FMul;
602   case RK_FloatAdd:
603     return Instruction::FAdd;
604   case RK_IntegerMinMax:
605     return Instruction::ICmp;
606   case RK_FloatMinMax:
607     return Instruction::FCmp;
608   default:
609     llvm_unreachable("Unknown recurrence operation");
610   }
611 }
612 
613 Value *RecurrenceDescriptor::createMinMaxOp(IRBuilder<> &Builder,
614                                             MinMaxRecurrenceKind RK,
615                                             Value *Left, Value *Right) {
616   CmpInst::Predicate P = CmpInst::ICMP_NE;
617   switch (RK) {
618   default:
619     llvm_unreachable("Unknown min/max recurrence kind");
620   case MRK_UIntMin:
621     P = CmpInst::ICMP_ULT;
622     break;
623   case MRK_UIntMax:
624     P = CmpInst::ICMP_UGT;
625     break;
626   case MRK_SIntMin:
627     P = CmpInst::ICMP_SLT;
628     break;
629   case MRK_SIntMax:
630     P = CmpInst::ICMP_SGT;
631     break;
632   case MRK_FloatMin:
633     P = CmpInst::FCMP_OLT;
634     break;
635   case MRK_FloatMax:
636     P = CmpInst::FCMP_OGT;
637     break;
638   }
639 
640   // We only match FP sequences with unsafe algebra, so we can unconditionally
641   // set it on any generated instructions.
642   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
643   FastMathFlags FMF;
644   FMF.setUnsafeAlgebra();
645   Builder.setFastMathFlags(FMF);
646 
647   Value *Cmp;
648   if (RK == MRK_FloatMin || RK == MRK_FloatMax)
649     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
650   else
651     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
652 
653   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
654   return Select;
655 }
656 
657 InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
658                                          ConstantInt *Step)
659   : StartValue(Start), IK(K), StepValue(Step) {
660   assert(IK != IK_NoInduction && "Not an induction");
661   assert(StartValue && "StartValue is null");
662   assert(StepValue && !StepValue->isZero() && "StepValue is zero");
663   assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
664          "StartValue is not a pointer for pointer induction");
665   assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
666          "StartValue is not an integer for integer induction");
667   assert(StepValue->getType()->isIntegerTy() &&
668          "StepValue is not an integer");
669 }
670 
671 int InductionDescriptor::getConsecutiveDirection() const {
672   if (StepValue && (StepValue->isOne() || StepValue->isMinusOne()))
673     return StepValue->getSExtValue();
674   return 0;
675 }
676 
677 Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index) const {
678   switch (IK) {
679   case IK_IntInduction:
680     assert(Index->getType() == StartValue->getType() &&
681            "Index type does not match StartValue type");
682     if (StepValue->isMinusOne())
683       return B.CreateSub(StartValue, Index);
684     if (!StepValue->isOne())
685       Index = B.CreateMul(Index, StepValue);
686     return B.CreateAdd(StartValue, Index);
687 
688   case IK_PtrInduction:
689     assert(Index->getType() == StepValue->getType() &&
690            "Index type does not match StepValue type");
691     if (StepValue->isMinusOne())
692       Index = B.CreateNeg(Index);
693     else if (!StepValue->isOne())
694       Index = B.CreateMul(Index, StepValue);
695     return B.CreateGEP(nullptr, StartValue, Index);
696 
697   case IK_NoInduction:
698     return nullptr;
699   }
700   llvm_unreachable("invalid enum");
701 }
702 
703 bool InductionDescriptor::isInductionPHI(PHINode *Phi, ScalarEvolution *SE,
704                                          InductionDescriptor &D) {
705   Type *PhiTy = Phi->getType();
706   // We only handle integer and pointer inductions variables.
707   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
708     return false;
709 
710   // Check that the PHI is consecutive.
711   const SCEV *PhiScev = SE->getSCEV(Phi);
712   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
713   if (!AR) {
714     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
715     return false;
716   }
717 
718   assert(AR->getLoop()->getHeader() == Phi->getParent() &&
719          "PHI is an AddRec for a different loop?!");
720   Value *StartValue =
721     Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
722   const SCEV *Step = AR->getStepRecurrence(*SE);
723   // Calculate the pointer stride and check if it is consecutive.
724   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
725   if (!C)
726     return false;
727 
728   ConstantInt *CV = C->getValue();
729   if (PhiTy->isIntegerTy()) {
730     D = InductionDescriptor(StartValue, IK_IntInduction, CV);
731     return true;
732   }
733 
734   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
735   Type *PointerElementType = PhiTy->getPointerElementType();
736   // The pointer stride cannot be determined if the pointer element type is not
737   // sized.
738   if (!PointerElementType->isSized())
739     return false;
740 
741   const DataLayout &DL = Phi->getModule()->getDataLayout();
742   int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
743   if (!Size)
744     return false;
745 
746   int64_t CVSize = CV->getSExtValue();
747   if (CVSize % Size)
748     return false;
749   auto *StepValue = ConstantInt::getSigned(CV->getType(), CVSize / Size);
750 
751   D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue);
752   return true;
753 }
754 
755 /// \brief Returns the instructions that use values defined in the loop.
756 SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
757   SmallVector<Instruction *, 8> UsedOutside;
758 
759   for (auto *Block : L->getBlocks())
760     // FIXME: I believe that this could use copy_if if the Inst reference could
761     // be adapted into a pointer.
762     for (auto &Inst : *Block) {
763       auto Users = Inst.users();
764       if (std::any_of(Users.begin(), Users.end(), [&](User *U) {
765             auto *Use = cast<Instruction>(U);
766             return !L->contains(Use->getParent());
767           }))
768         UsedOutside.push_back(&Inst);
769     }
770 
771   return UsedOutside;
772 }
773 
774 void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
775   // By definition, all loop passes need the LoopInfo analysis and the
776   // Dominator tree it depends on. Because they all participate in the loop
777   // pass manager, they must also preserve these.
778   AU.addRequired<DominatorTreeWrapperPass>();
779   AU.addPreserved<DominatorTreeWrapperPass>();
780   AU.addRequired<LoopInfoWrapperPass>();
781   AU.addPreserved<LoopInfoWrapperPass>();
782 
783   // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
784   // here because users shouldn't directly get them from this header.
785   extern char &LoopSimplifyID;
786   extern char &LCSSAID;
787   AU.addRequiredID(LoopSimplifyID);
788   AU.addPreservedID(LoopSimplifyID);
789   AU.addRequiredID(LCSSAID);
790   AU.addPreservedID(LCSSAID);
791 
792   // Loop passes are designed to run inside of a loop pass manager which means
793   // that any function analyses they require must be required by the first loop
794   // pass in the manager (so that it is computed before the loop pass manager
795   // runs) and preserved by all loop pasess in the manager. To make this
796   // reasonably robust, the set needed for most loop passes is maintained here.
797   // If your loop pass requires an analysis not listed here, you will need to
798   // carefully audit the loop pass manager nesting structure that results.
799   AU.addRequired<AAResultsWrapperPass>();
800   AU.addPreserved<AAResultsWrapperPass>();
801   AU.addPreserved<BasicAAWrapperPass>();
802   AU.addPreserved<GlobalsAAWrapperPass>();
803   AU.addPreserved<SCEVAAWrapperPass>();
804   AU.addRequired<ScalarEvolutionWrapperPass>();
805   AU.addPreserved<ScalarEvolutionWrapperPass>();
806 }
807 
808 /// Manually defined generic "LoopPass" dependency initialization. This is used
809 /// to initialize the exact set of passes from above in \c
810 /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
811 /// with:
812 ///
813 ///   INITIALIZE_PASS_DEPENDENCY(LoopPass)
814 ///
815 /// As-if "LoopPass" were a pass.
816 void llvm::initializeLoopPassPass(PassRegistry &Registry) {
817   INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
818   INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
819   INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
820   INITIALIZE_PASS_DEPENDENCY(LCSSA)
821   INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
822   INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
823   INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
824   INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
825   INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
826 }
827