blob: c8efa9efc7f34ed18c647c42a09359807e3d515e [file] [log] [blame]
Karthik Bhat76aa6622015-04-20 04:38:33 +00001//===-- 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
Adam Nemet2f2bd8c2016-07-26 17:52:02 +000014#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000015#include "llvm/Analysis/AliasAnalysis.h"
16#include "llvm/Analysis/BasicAliasAnalysis.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000017#include "llvm/Analysis/GlobalsModRef.h"
Adam Nemet2f2bd8c2016-07-26 17:52:02 +000018#include "llvm/Analysis/GlobalsModRef.h"
19#include "llvm/Analysis/LoopInfo.h"
Igor Laevskyc3ccf5d2016-10-28 12:57:20 +000020#include "llvm/Analysis/LoopPass.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000021#include "llvm/Analysis/ScalarEvolution.h"
Adam Nemet2f2bd8c2016-07-26 17:52:02 +000022#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Elena Demikhovskyc434d092016-05-10 07:33:35 +000023#include "llvm/Analysis/ScalarEvolutionExpander.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000024#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000025#include "llvm/IR/Dominators.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000026#include "llvm/IR/Instructions.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000027#include "llvm/IR/Module.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000028#include "llvm/IR/PatternMatch.h"
29#include "llvm/IR/ValueHandle.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000030#include "llvm/Pass.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000031#include "llvm/Support/Debug.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000032
33using namespace llvm;
34using namespace llvm::PatternMatch;
35
36#define DEBUG_TYPE "loop-utils"
37
Tyler Nowicki0a913102015-06-16 18:07:34 +000038bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
39 SmallPtrSetImpl<Instruction *> &Set) {
Karthik Bhat76aa6622015-04-20 04:38:33 +000040 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
41 if (!Set.count(dyn_cast<Instruction>(*Use)))
42 return false;
43 return true;
44}
45
Chad Rosierc94f8e22015-08-27 14:12:17 +000046bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) {
47 switch (Kind) {
48 default:
49 break;
50 case RK_IntegerAdd:
51 case RK_IntegerMult:
52 case RK_IntegerOr:
53 case RK_IntegerAnd:
54 case RK_IntegerXor:
55 case RK_IntegerMinMax:
56 return true;
57 }
58 return false;
59}
60
61bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) {
62 return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
63}
64
65bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) {
66 switch (Kind) {
67 default:
68 break;
69 case RK_IntegerAdd:
70 case RK_IntegerMult:
71 case RK_FloatAdd:
72 case RK_FloatMult:
73 return true;
74 }
75 return false;
76}
77
78Instruction *
79RecurrenceDescriptor::lookThroughAnd(PHINode *Phi, Type *&RT,
80 SmallPtrSetImpl<Instruction *> &Visited,
81 SmallPtrSetImpl<Instruction *> &CI) {
82 if (!Phi->hasOneUse())
83 return Phi;
84
85 const APInt *M = nullptr;
86 Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
87
88 // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
89 // with a new integer type of the corresponding bit width.
90 if (match(J, m_CombineOr(m_And(m_Instruction(I), m_APInt(M)),
91 m_And(m_APInt(M), m_Instruction(I))))) {
92 int32_t Bits = (*M + 1).exactLogBase2();
93 if (Bits > 0) {
94 RT = IntegerType::get(Phi->getContext(), Bits);
95 Visited.insert(Phi);
96 CI.insert(J);
97 return J;
98 }
99 }
100 return Phi;
101}
102
103bool RecurrenceDescriptor::getSourceExtensionKind(
104 Instruction *Start, Instruction *Exit, Type *RT, bool &IsSigned,
105 SmallPtrSetImpl<Instruction *> &Visited,
106 SmallPtrSetImpl<Instruction *> &CI) {
107
108 SmallVector<Instruction *, 8> Worklist;
109 bool FoundOneOperand = false;
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000110 unsigned DstSize = RT->getPrimitiveSizeInBits();
Chad Rosierc94f8e22015-08-27 14:12:17 +0000111 Worklist.push_back(Exit);
112
113 // Traverse the instructions in the reduction expression, beginning with the
114 // exit value.
115 while (!Worklist.empty()) {
116 Instruction *I = Worklist.pop_back_val();
117 for (Use &U : I->operands()) {
118
119 // Terminate the traversal if the operand is not an instruction, or we
120 // reach the starting value.
121 Instruction *J = dyn_cast<Instruction>(U.get());
122 if (!J || J == Start)
123 continue;
124
125 // Otherwise, investigate the operation if it is also in the expression.
126 if (Visited.count(J)) {
127 Worklist.push_back(J);
128 continue;
129 }
130
131 // If the operand is not in Visited, it is not a reduction operation, but
132 // it does feed into one. Make sure it is either a single-use sign- or
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000133 // zero-extend instruction.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000134 CastInst *Cast = dyn_cast<CastInst>(J);
135 bool IsSExtInst = isa<SExtInst>(J);
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000136 if (!Cast || !Cast->hasOneUse() || !(isa<ZExtInst>(J) || IsSExtInst))
137 return false;
138
139 // Ensure the source type of the extend is no larger than the reduction
140 // type. It is not necessary for the types to be identical.
141 unsigned SrcSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
142 if (SrcSize > DstSize)
Chad Rosierc94f8e22015-08-27 14:12:17 +0000143 return false;
144
145 // Furthermore, ensure that all such extends are of the same kind.
146 if (FoundOneOperand) {
147 if (IsSigned != IsSExtInst)
148 return false;
149 } else {
150 FoundOneOperand = true;
151 IsSigned = IsSExtInst;
152 }
153
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000154 // Lastly, if the source type of the extend matches the reduction type,
155 // add the extend to CI so that we can avoid accounting for it in the
156 // cost model.
157 if (SrcSize == DstSize)
158 CI.insert(Cast);
Chad Rosierc94f8e22015-08-27 14:12:17 +0000159 }
160 }
161 return true;
162}
163
Tyler Nowicki0a913102015-06-16 18:07:34 +0000164bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind,
165 Loop *TheLoop, bool HasFunNoNaNAttr,
166 RecurrenceDescriptor &RedDes) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000167 if (Phi->getNumIncomingValues() != 2)
168 return false;
169
170 // Reduction variables are only found in the loop header block.
171 if (Phi->getParent() != TheLoop->getHeader())
172 return false;
173
174 // Obtain the reduction start value from the value that comes from the loop
175 // preheader.
176 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
177
178 // ExitInstruction is the single value which is used outside the loop.
179 // We only allow for a single reduction value to be used outside the loop.
180 // This includes users of the reduction, variables (which form a cycle
181 // which ends in the phi node).
182 Instruction *ExitInstruction = nullptr;
183 // Indicates that we found a reduction operation in our scan.
184 bool FoundReduxOp = false;
185
186 // We start with the PHI node and scan for all of the users of this
187 // instruction. All users must be instructions that can be used as reduction
188 // variables (such as ADD). We must have a single out-of-block user. The cycle
189 // must include the original PHI.
190 bool FoundStartPHI = false;
191
192 // To recognize min/max patterns formed by a icmp select sequence, we store
193 // the number of instruction we saw from the recognized min/max pattern,
194 // to make sure we only see exactly the two instructions.
195 unsigned NumCmpSelectPatternInst = 0;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000196 InstDesc ReduxDesc(false, nullptr);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000197
Chad Rosierc94f8e22015-08-27 14:12:17 +0000198 // Data used for determining if the recurrence has been type-promoted.
199 Type *RecurrenceType = Phi->getType();
200 SmallPtrSet<Instruction *, 4> CastInsts;
201 Instruction *Start = Phi;
202 bool IsSigned = false;
203
Karthik Bhat76aa6622015-04-20 04:38:33 +0000204 SmallPtrSet<Instruction *, 8> VisitedInsts;
205 SmallVector<Instruction *, 8> Worklist;
Chad Rosierc94f8e22015-08-27 14:12:17 +0000206
207 // Return early if the recurrence kind does not match the type of Phi. If the
208 // recurrence kind is arithmetic, we attempt to look through AND operations
209 // resulting from the type promotion performed by InstCombine. Vector
210 // operations are not limited to the legal integer widths, so we may be able
211 // to evaluate the reduction in the narrower width.
212 if (RecurrenceType->isFloatingPointTy()) {
213 if (!isFloatingPointRecurrenceKind(Kind))
214 return false;
215 } else {
216 if (!isIntegerRecurrenceKind(Kind))
217 return false;
218 if (isArithmeticRecurrenceKind(Kind))
219 Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
220 }
221
222 Worklist.push_back(Start);
223 VisitedInsts.insert(Start);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000224
225 // A value in the reduction can be used:
226 // - By the reduction:
227 // - Reduction operation:
228 // - One use of reduction value (safe).
229 // - Multiple use of reduction value (not safe).
230 // - PHI:
231 // - All uses of the PHI must be the reduction (safe).
232 // - Otherwise, not safe.
233 // - By one instruction outside of the loop (safe).
234 // - By further instructions outside of the loop (not safe).
235 // - By an instruction that is not part of the reduction (not safe).
236 // This is either:
237 // * An instruction type other than PHI or the reduction operation.
238 // * A PHI in the header other than the initial PHI.
239 while (!Worklist.empty()) {
240 Instruction *Cur = Worklist.back();
241 Worklist.pop_back();
242
243 // No Users.
244 // If the instruction has no users then this is a broken chain and can't be
245 // a reduction variable.
246 if (Cur->use_empty())
247 return false;
248
249 bool IsAPhi = isa<PHINode>(Cur);
250
251 // A header PHI use other than the original PHI.
252 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
253 return false;
254
255 // Reductions of instructions such as Div, and Sub is only possible if the
256 // LHS is the reduction variable.
257 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
258 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
259 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
260 return false;
261
Chad Rosierc94f8e22015-08-27 14:12:17 +0000262 // Any reduction instruction must be of one of the allowed kinds. We ignore
263 // the starting value (the Phi or an AND instruction if the Phi has been
264 // type-promoted).
265 if (Cur != Start) {
266 ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
267 if (!ReduxDesc.isRecurrence())
268 return false;
269 }
Karthik Bhat76aa6622015-04-20 04:38:33 +0000270
271 // A reduction operation must only have one use of the reduction value.
272 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
273 hasMultipleUsesOf(Cur, VisitedInsts))
274 return false;
275
276 // All inputs to a PHI node must be a reduction value.
277 if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
278 return false;
279
280 if (Kind == RK_IntegerMinMax &&
281 (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
282 ++NumCmpSelectPatternInst;
283 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
284 ++NumCmpSelectPatternInst;
285
286 // Check whether we found a reduction operator.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000287 FoundReduxOp |= !IsAPhi && Cur != Start;
Karthik Bhat76aa6622015-04-20 04:38:33 +0000288
289 // Process users of current instruction. Push non-PHI nodes after PHI nodes
290 // onto the stack. This way we are going to have seen all inputs to PHI
291 // nodes once we get to them.
292 SmallVector<Instruction *, 8> NonPHIs;
293 SmallVector<Instruction *, 8> PHIs;
294 for (User *U : Cur->users()) {
295 Instruction *UI = cast<Instruction>(U);
296
297 // Check if we found the exit user.
298 BasicBlock *Parent = UI->getParent();
299 if (!TheLoop->contains(Parent)) {
300 // Exit if you find multiple outside users or if the header phi node is
301 // being used. In this case the user uses the value of the previous
302 // iteration, in which case we would loose "VF-1" iterations of the
303 // reduction operation if we vectorize.
304 if (ExitInstruction != nullptr || Cur == Phi)
305 return false;
306
307 // The instruction used by an outside user must be the last instruction
308 // before we feed back to the reduction phi. Otherwise, we loose VF-1
309 // operations on the value.
David Majnemer42531262016-08-12 03:55:06 +0000310 if (!is_contained(Phi->operands(), Cur))
Karthik Bhat76aa6622015-04-20 04:38:33 +0000311 return false;
312
313 ExitInstruction = Cur;
314 continue;
315 }
316
317 // Process instructions only once (termination). Each reduction cycle
318 // value must only be used once, except by phi nodes and min/max
319 // reductions which are represented as a cmp followed by a select.
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000320 InstDesc IgnoredVal(false, nullptr);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000321 if (VisitedInsts.insert(UI).second) {
322 if (isa<PHINode>(UI))
323 PHIs.push_back(UI);
324 else
325 NonPHIs.push_back(UI);
326 } else if (!isa<PHINode>(UI) &&
327 ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
328 !isa<SelectInst>(UI)) ||
Tyler Nowicki0a913102015-06-16 18:07:34 +0000329 !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence()))
Karthik Bhat76aa6622015-04-20 04:38:33 +0000330 return false;
331
332 // Remember that we completed the cycle.
333 if (UI == Phi)
334 FoundStartPHI = true;
335 }
336 Worklist.append(PHIs.begin(), PHIs.end());
337 Worklist.append(NonPHIs.begin(), NonPHIs.end());
338 }
339
340 // This means we have seen one but not the other instruction of the
341 // pattern or more than just a select and cmp.
342 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
343 NumCmpSelectPatternInst != 2)
344 return false;
345
346 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
347 return false;
348
Chad Rosierc94f8e22015-08-27 14:12:17 +0000349 // If we think Phi may have been type-promoted, we also need to ensure that
350 // all source operands of the reduction are either SExtInsts or ZEstInsts. If
351 // so, we will be able to evaluate the reduction in the narrower bit width.
352 if (Start != Phi)
353 if (!getSourceExtensionKind(Start, ExitInstruction, RecurrenceType,
354 IsSigned, VisitedInsts, CastInsts))
355 return false;
356
Karthik Bhat76aa6622015-04-20 04:38:33 +0000357 // We found a reduction var if we have reached the original phi node and we
358 // only have a single instruction with out-of-loop users.
359
360 // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
Tyler Nowicki0a913102015-06-16 18:07:34 +0000361 // is saved as part of the RecurrenceDescriptor.
Karthik Bhat76aa6622015-04-20 04:38:33 +0000362
363 // Save the description of this reduction variable.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000364 RecurrenceDescriptor RD(
365 RdxStart, ExitInstruction, Kind, ReduxDesc.getMinMaxKind(),
366 ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000367 RedDes = RD;
368
369 return true;
370}
371
372/// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
373/// pattern corresponding to a min(X, Y) or max(X, Y).
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000374RecurrenceDescriptor::InstDesc
375RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000376
377 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
378 "Expect a select instruction");
379 Instruction *Cmp = nullptr;
380 SelectInst *Select = nullptr;
381
382 // We must handle the select(cmp()) as a single instruction. Advance to the
383 // select.
384 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
385 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000386 return InstDesc(false, I);
387 return InstDesc(Select, Prev.getMinMaxKind());
Karthik Bhat76aa6622015-04-20 04:38:33 +0000388 }
389
390 // Only handle single use cases for now.
391 if (!(Select = dyn_cast<SelectInst>(I)))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000392 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000393 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
394 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000395 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000396 if (!Cmp->hasOneUse())
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000397 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000398
399 Value *CmpLeft;
400 Value *CmpRight;
401
402 // Look for a min/max pattern.
403 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000404 return InstDesc(Select, MRK_UIntMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000405 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000406 return InstDesc(Select, MRK_UIntMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000407 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000408 return InstDesc(Select, MRK_SIntMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000409 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000410 return InstDesc(Select, MRK_SIntMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000411 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000412 return InstDesc(Select, MRK_FloatMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000413 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000414 return InstDesc(Select, MRK_FloatMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000415 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000416 return InstDesc(Select, MRK_FloatMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000417 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000418 return InstDesc(Select, MRK_FloatMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000419
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000420 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000421}
422
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000423RecurrenceDescriptor::InstDesc
Tyler Nowicki0a913102015-06-16 18:07:34 +0000424RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000425 InstDesc &Prev, bool HasFunNoNaNAttr) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000426 bool FP = I->getType()->isFloatingPointTy();
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000427 Instruction *UAI = Prev.getUnsafeAlgebraInst();
428 if (!UAI && FP && !I->hasUnsafeAlgebra())
429 UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
430
Karthik Bhat76aa6622015-04-20 04:38:33 +0000431 switch (I->getOpcode()) {
432 default:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000433 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000434 case Instruction::PHI:
Tim Northover10a1e8b2016-05-27 16:40:27 +0000435 return InstDesc(I, Prev.getMinMaxKind(), Prev.getUnsafeAlgebraInst());
Karthik Bhat76aa6622015-04-20 04:38:33 +0000436 case Instruction::Sub:
437 case Instruction::Add:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000438 return InstDesc(Kind == RK_IntegerAdd, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000439 case Instruction::Mul:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000440 return InstDesc(Kind == RK_IntegerMult, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000441 case Instruction::And:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000442 return InstDesc(Kind == RK_IntegerAnd, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000443 case Instruction::Or:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000444 return InstDesc(Kind == RK_IntegerOr, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000445 case Instruction::Xor:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000446 return InstDesc(Kind == RK_IntegerXor, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000447 case Instruction::FMul:
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000448 return InstDesc(Kind == RK_FloatMult, I, UAI);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000449 case Instruction::FSub:
450 case Instruction::FAdd:
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000451 return InstDesc(Kind == RK_FloatAdd, I, UAI);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000452 case Instruction::FCmp:
453 case Instruction::ICmp:
454 case Instruction::Select:
455 if (Kind != RK_IntegerMinMax &&
456 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000457 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000458 return isMinMaxSelectCmpPattern(I, Prev);
459 }
460}
461
Tyler Nowicki0a913102015-06-16 18:07:34 +0000462bool RecurrenceDescriptor::hasMultipleUsesOf(
Karthik Bhat76aa6622015-04-20 04:38:33 +0000463 Instruction *I, SmallPtrSetImpl<Instruction *> &Insts) {
464 unsigned NumUses = 0;
465 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
466 ++Use) {
467 if (Insts.count(dyn_cast<Instruction>(*Use)))
468 ++NumUses;
469 if (NumUses > 1)
470 return true;
471 }
472
473 return false;
474}
Tyler Nowicki0a913102015-06-16 18:07:34 +0000475bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
476 RecurrenceDescriptor &RedDes) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000477
Karthik Bhat76aa6622015-04-20 04:38:33 +0000478 BasicBlock *Header = TheLoop->getHeader();
479 Function &F = *Header->getParent();
Nirav Dave8dd66e52016-03-30 15:41:12 +0000480 bool HasFunNoNaNAttr =
481 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
Karthik Bhat76aa6622015-04-20 04:38:33 +0000482
483 if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
484 DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
485 return true;
486 }
487 if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
488 DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
489 return true;
490 }
491 if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes)) {
492 DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
493 return true;
494 }
495 if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes)) {
496 DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
497 return true;
498 }
499 if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes)) {
500 DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
501 return true;
502 }
503 if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr,
504 RedDes)) {
505 DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
506 return true;
507 }
508 if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
509 DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
510 return true;
511 }
512 if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
513 DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
514 return true;
515 }
516 if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes)) {
517 DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi << "\n");
518 return true;
519 }
520 // Not a reduction of known type.
521 return false;
522}
523
Matthew Simpson29c997c2016-02-19 17:56:08 +0000524bool RecurrenceDescriptor::isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop,
525 DominatorTree *DT) {
526
527 // Ensure the phi node is in the loop header and has two incoming values.
528 if (Phi->getParent() != TheLoop->getHeader() ||
529 Phi->getNumIncomingValues() != 2)
530 return false;
531
532 // Ensure the loop has a preheader and a single latch block. The loop
533 // vectorizer will need the latch to set up the next iteration of the loop.
534 auto *Preheader = TheLoop->getLoopPreheader();
535 auto *Latch = TheLoop->getLoopLatch();
536 if (!Preheader || !Latch)
537 return false;
538
539 // Ensure the phi node's incoming blocks are the loop preheader and latch.
540 if (Phi->getBasicBlockIndex(Preheader) < 0 ||
541 Phi->getBasicBlockIndex(Latch) < 0)
542 return false;
543
544 // Get the previous value. The previous value comes from the latch edge while
545 // the initial value comes form the preheader edge.
546 auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
Matthew Simpson53207a92016-04-11 19:48:18 +0000547 if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous))
Matthew Simpson29c997c2016-02-19 17:56:08 +0000548 return false;
549
550 // Ensure every user of the phi node is dominated by the previous value. The
551 // dominance requirement ensures the loop vectorizer will not need to
552 // vectorize the initial value prior to the first iteration of the loop.
553 for (User *U : Phi->users())
554 if (auto *I = dyn_cast<Instruction>(U))
555 if (!DT->dominates(Previous, I))
556 return false;
557
558 return true;
559}
560
Karthik Bhat76aa6622015-04-20 04:38:33 +0000561/// This function returns the identity element (or neutral element) for
562/// the operation K.
Tyler Nowicki0a913102015-06-16 18:07:34 +0000563Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K,
564 Type *Tp) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000565 switch (K) {
566 case RK_IntegerXor:
567 case RK_IntegerAdd:
568 case RK_IntegerOr:
569 // Adding, Xoring, Oring zero to a number does not change it.
570 return ConstantInt::get(Tp, 0);
571 case RK_IntegerMult:
572 // Multiplying a number by 1 does not change it.
573 return ConstantInt::get(Tp, 1);
574 case RK_IntegerAnd:
575 // AND-ing a number with an all-1 value does not change it.
576 return ConstantInt::get(Tp, -1, true);
577 case RK_FloatMult:
578 // Multiplying a number by 1 does not change it.
579 return ConstantFP::get(Tp, 1.0L);
580 case RK_FloatAdd:
581 // Adding zero to a number does not change it.
582 return ConstantFP::get(Tp, 0.0L);
583 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000584 llvm_unreachable("Unknown recurrence kind");
Karthik Bhat76aa6622015-04-20 04:38:33 +0000585 }
586}
587
Tyler Nowicki0a913102015-06-16 18:07:34 +0000588/// This function translates the recurrence kind to an LLVM binary operator.
589unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000590 switch (Kind) {
591 case RK_IntegerAdd:
592 return Instruction::Add;
593 case RK_IntegerMult:
594 return Instruction::Mul;
595 case RK_IntegerOr:
596 return Instruction::Or;
597 case RK_IntegerAnd:
598 return Instruction::And;
599 case RK_IntegerXor:
600 return Instruction::Xor;
601 case RK_FloatMult:
602 return Instruction::FMul;
603 case RK_FloatAdd:
604 return Instruction::FAdd;
605 case RK_IntegerMinMax:
606 return Instruction::ICmp;
607 case RK_FloatMinMax:
608 return Instruction::FCmp;
609 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000610 llvm_unreachable("Unknown recurrence operation");
Karthik Bhat76aa6622015-04-20 04:38:33 +0000611 }
612}
613
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000614Value *RecurrenceDescriptor::createMinMaxOp(IRBuilder<> &Builder,
615 MinMaxRecurrenceKind RK,
616 Value *Left, Value *Right) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000617 CmpInst::Predicate P = CmpInst::ICMP_NE;
618 switch (RK) {
619 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000620 llvm_unreachable("Unknown min/max recurrence kind");
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000621 case MRK_UIntMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000622 P = CmpInst::ICMP_ULT;
623 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000624 case MRK_UIntMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000625 P = CmpInst::ICMP_UGT;
626 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000627 case MRK_SIntMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000628 P = CmpInst::ICMP_SLT;
629 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000630 case MRK_SIntMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000631 P = CmpInst::ICMP_SGT;
632 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000633 case MRK_FloatMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000634 P = CmpInst::FCMP_OLT;
635 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000636 case MRK_FloatMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000637 P = CmpInst::FCMP_OGT;
638 break;
639 }
640
James Molloy50a4c272015-09-21 19:41:19 +0000641 // We only match FP sequences with unsafe algebra, so we can unconditionally
642 // set it on any generated instructions.
643 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
644 FastMathFlags FMF;
645 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +0000646 Builder.setFastMathFlags(FMF);
James Molloy50a4c272015-09-21 19:41:19 +0000647
Karthik Bhat76aa6622015-04-20 04:38:33 +0000648 Value *Cmp;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000649 if (RK == MRK_FloatMin || RK == MRK_FloatMax)
Karthik Bhat76aa6622015-04-20 04:38:33 +0000650 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
651 else
652 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
653
654 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
655 return Select;
656}
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000657
James Molloy1bbf15c2015-08-27 09:53:00 +0000658InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000659 const SCEV *Step, BinaryOperator *BOp)
660 : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
James Molloy1bbf15c2015-08-27 09:53:00 +0000661 assert(IK != IK_NoInduction && "Not an induction");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000662
663 // Start value type should match the induction kind and the value
664 // itself should not be null.
James Molloy1bbf15c2015-08-27 09:53:00 +0000665 assert(StartValue && "StartValue is null");
James Molloy1bbf15c2015-08-27 09:53:00 +0000666 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
667 "StartValue is not a pointer for pointer induction");
668 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
669 "StartValue is not an integer for integer induction");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000670
671 // Check the Step Value. It should be non-zero integer value.
672 assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
673 "Step value is zero");
674
675 assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
676 "Step value should be constant for pointer induction");
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000677 assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
678 "StepValue is not an integer");
679
680 assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
681 "StepValue is not FP for FpInduction");
682 assert((IK != IK_FpInduction || (InductionBinOp &&
683 (InductionBinOp->getOpcode() == Instruction::FAdd ||
684 InductionBinOp->getOpcode() == Instruction::FSub))) &&
685 "Binary opcode should be specified for FP induction");
James Molloy1bbf15c2015-08-27 09:53:00 +0000686}
687
688int InductionDescriptor::getConsecutiveDirection() const {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000689 ConstantInt *ConstStep = getConstIntStepValue();
690 if (ConstStep && (ConstStep->isOne() || ConstStep->isMinusOne()))
691 return ConstStep->getSExtValue();
James Molloy1bbf15c2015-08-27 09:53:00 +0000692 return 0;
693}
694
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000695ConstantInt *InductionDescriptor::getConstIntStepValue() const {
696 if (isa<SCEVConstant>(Step))
697 return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
698 return nullptr;
699}
700
701Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index,
702 ScalarEvolution *SE,
703 const DataLayout& DL) const {
704
705 SCEVExpander Exp(*SE, DL, "induction");
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000706 assert(Index->getType() == Step->getType() &&
707 "Index type does not match StepValue type");
James Molloy1bbf15c2015-08-27 09:53:00 +0000708 switch (IK) {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000709 case IK_IntInduction: {
James Molloy1bbf15c2015-08-27 09:53:00 +0000710 assert(Index->getType() == StartValue->getType() &&
711 "Index type does not match StartValue type");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000712
713 // FIXME: Theoretically, we can call getAddExpr() of ScalarEvolution
714 // and calculate (Start + Index * Step) for all cases, without
715 // special handling for "isOne" and "isMinusOne".
716 // But in the real life the result code getting worse. We mix SCEV
717 // expressions and ADD/SUB operations and receive redundant
718 // intermediate values being calculated in different ways and
719 // Instcombine is unable to reduce them all.
720
721 if (getConstIntStepValue() &&
722 getConstIntStepValue()->isMinusOne())
James Molloy1bbf15c2015-08-27 09:53:00 +0000723 return B.CreateSub(StartValue, Index);
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000724 if (getConstIntStepValue() &&
725 getConstIntStepValue()->isOne())
726 return B.CreateAdd(StartValue, Index);
727 const SCEV *S = SE->getAddExpr(SE->getSCEV(StartValue),
728 SE->getMulExpr(Step, SE->getSCEV(Index)));
729 return Exp.expandCodeFor(S, StartValue->getType(), &*B.GetInsertPoint());
730 }
731 case IK_PtrInduction: {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000732 assert(isa<SCEVConstant>(Step) &&
733 "Expected constant step for pointer induction");
734 const SCEV *S = SE->getMulExpr(SE->getSCEV(Index), Step);
735 Index = Exp.expandCodeFor(S, Index->getType(), &*B.GetInsertPoint());
James Molloy1bbf15c2015-08-27 09:53:00 +0000736 return B.CreateGEP(nullptr, StartValue, Index);
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000737 }
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000738 case IK_FpInduction: {
739 assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
740 assert(InductionBinOp &&
741 (InductionBinOp->getOpcode() == Instruction::FAdd ||
742 InductionBinOp->getOpcode() == Instruction::FSub) &&
743 "Original bin op should be defined for FP induction");
744
745 Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
746
747 // Floating point operations had to be 'fast' to enable the induction.
748 FastMathFlags Flags;
749 Flags.setUnsafeAlgebra();
750
751 Value *MulExp = B.CreateFMul(StepValue, Index);
752 if (isa<Instruction>(MulExp))
753 // We have to check, the MulExp may be a constant.
754 cast<Instruction>(MulExp)->setFastMathFlags(Flags);
755
756 Value *BOp = B.CreateBinOp(InductionBinOp->getOpcode() , StartValue,
757 MulExp, "induction");
758 if (isa<Instruction>(BOp))
759 cast<Instruction>(BOp)->setFastMathFlags(Flags);
760
761 return BOp;
762 }
James Molloy1bbf15c2015-08-27 09:53:00 +0000763 case IK_NoInduction:
764 return nullptr;
765 }
766 llvm_unreachable("invalid enum");
767}
768
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000769bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop,
770 ScalarEvolution *SE,
771 InductionDescriptor &D) {
772
773 // Here we only handle FP induction variables.
774 assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
775
776 if (TheLoop->getHeader() != Phi->getParent())
777 return false;
778
779 // The loop may have multiple entrances or multiple exits; we can analyze
780 // this phi if it has a unique entry value and a unique backedge value.
781 if (Phi->getNumIncomingValues() != 2)
782 return false;
783 Value *BEValue = nullptr, *StartValue = nullptr;
784 if (TheLoop->contains(Phi->getIncomingBlock(0))) {
785 BEValue = Phi->getIncomingValue(0);
786 StartValue = Phi->getIncomingValue(1);
787 } else {
788 assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
789 "Unexpected Phi node in the loop");
790 BEValue = Phi->getIncomingValue(1);
791 StartValue = Phi->getIncomingValue(0);
792 }
793
794 BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue);
795 if (!BOp)
796 return false;
797
798 Value *Addend = nullptr;
799 if (BOp->getOpcode() == Instruction::FAdd) {
800 if (BOp->getOperand(0) == Phi)
801 Addend = BOp->getOperand(1);
802 else if (BOp->getOperand(1) == Phi)
803 Addend = BOp->getOperand(0);
804 } else if (BOp->getOpcode() == Instruction::FSub)
805 if (BOp->getOperand(0) == Phi)
806 Addend = BOp->getOperand(1);
807
808 if (!Addend)
809 return false;
810
811 // The addend should be loop invariant
812 if (auto *I = dyn_cast<Instruction>(Addend))
813 if (TheLoop->contains(I))
814 return false;
815
816 // FP Step has unknown SCEV
817 const SCEV *Step = SE->getUnknown(Addend);
818 D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
819 return true;
820}
821
822bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
Silviu Barangac05bab82016-05-05 15:20:39 +0000823 PredicatedScalarEvolution &PSE,
824 InductionDescriptor &D,
825 bool Assume) {
826 Type *PhiTy = Phi->getType();
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000827
828 // Handle integer and pointer inductions variables.
829 // Now we handle also FP induction but not trying to make a
830 // recurrent expression from the PHI node in-place.
831
832 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() &&
833 !PhiTy->isFloatTy() && !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
Silviu Barangac05bab82016-05-05 15:20:39 +0000834 return false;
835
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000836 if (PhiTy->isFloatingPointTy())
837 return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
838
Silviu Barangac05bab82016-05-05 15:20:39 +0000839 const SCEV *PhiScev = PSE.getSCEV(Phi);
840 const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
841
842 // We need this expression to be an AddRecExpr.
843 if (Assume && !AR)
844 AR = PSE.getAsAddRec(Phi);
845
846 if (!AR) {
847 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
848 return false;
849 }
850
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000851 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
Silviu Barangac05bab82016-05-05 15:20:39 +0000852}
853
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000854bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
Silviu Barangac05bab82016-05-05 15:20:39 +0000855 ScalarEvolution *SE,
856 InductionDescriptor &D,
857 const SCEV *Expr) {
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000858 Type *PhiTy = Phi->getType();
859 // We only handle integer and pointer inductions variables.
860 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
861 return false;
862
863 // Check that the PHI is consecutive.
Silviu Barangac05bab82016-05-05 15:20:39 +0000864 const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000865 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
Silviu Barangac05bab82016-05-05 15:20:39 +0000866
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000867 if (!AR) {
868 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
869 return false;
870 }
871
Michael Kupersteinee31cbe2017-01-10 19:32:30 +0000872 if (AR->getLoop() != TheLoop) {
873 // FIXME: We should treat this as a uniform. Unfortunately, we
874 // don't currently know how to handled uniform PHIs.
875 DEBUG(dbgs() << "LV: PHI is a recurrence with respect to an outer loop.\n");
876 return false;
877 }
878
James Molloy1bbf15c2015-08-27 09:53:00 +0000879 Value *StartValue =
880 Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000881 const SCEV *Step = AR->getStepRecurrence(*SE);
882 // Calculate the pointer stride and check if it is consecutive.
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000883 // The stride may be a constant or a loop invariant integer value.
884 const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000885 if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop))
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000886 return false;
887
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000888 if (PhiTy->isIntegerTy()) {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000889 D = InductionDescriptor(StartValue, IK_IntInduction, Step);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000890 return true;
891 }
892
893 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000894 // Pointer induction should be a constant.
895 if (!ConstStep)
896 return false;
897
898 ConstantInt *CV = ConstStep->getValue();
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000899 Type *PointerElementType = PhiTy->getPointerElementType();
900 // The pointer stride cannot be determined if the pointer element type is not
901 // sized.
902 if (!PointerElementType->isSized())
903 return false;
904
905 const DataLayout &DL = Phi->getModule()->getDataLayout();
906 int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
David Majnemerb58f32f2015-06-05 10:52:40 +0000907 if (!Size)
908 return false;
909
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000910 int64_t CVSize = CV->getSExtValue();
911 if (CVSize % Size)
912 return false;
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000913 auto *StepValue = SE->getConstant(CV->getType(), CVSize / Size,
914 true /* signed */);
James Molloy1bbf15c2015-08-27 09:53:00 +0000915 D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000916 return true;
917}
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000918
919/// \brief Returns the instructions that use values defined in the loop.
920SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
921 SmallVector<Instruction *, 8> UsedOutside;
922
923 for (auto *Block : L->getBlocks())
924 // FIXME: I believe that this could use copy_if if the Inst reference could
925 // be adapted into a pointer.
926 for (auto &Inst : *Block) {
927 auto Users = Inst.users();
David Majnemer0a16c222016-08-11 21:15:00 +0000928 if (any_of(Users, [&](User *U) {
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000929 auto *Use = cast<Instruction>(U);
930 return !L->contains(Use->getParent());
931 }))
932 UsedOutside.push_back(&Inst);
933 }
934
935 return UsedOutside;
936}
Chandler Carruth31088a92016-02-19 10:45:18 +0000937
938void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
939 // By definition, all loop passes need the LoopInfo analysis and the
940 // Dominator tree it depends on. Because they all participate in the loop
941 // pass manager, they must also preserve these.
942 AU.addRequired<DominatorTreeWrapperPass>();
943 AU.addPreserved<DominatorTreeWrapperPass>();
944 AU.addRequired<LoopInfoWrapperPass>();
945 AU.addPreserved<LoopInfoWrapperPass>();
946
947 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
948 // here because users shouldn't directly get them from this header.
949 extern char &LoopSimplifyID;
950 extern char &LCSSAID;
951 AU.addRequiredID(LoopSimplifyID);
952 AU.addPreservedID(LoopSimplifyID);
953 AU.addRequiredID(LCSSAID);
954 AU.addPreservedID(LCSSAID);
Igor Laevskyc3ccf5d2016-10-28 12:57:20 +0000955 // This is used in the LPPassManager to perform LCSSA verification on passes
956 // which preserve lcssa form
957 AU.addRequired<LCSSAVerificationPass>();
958 AU.addPreserved<LCSSAVerificationPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000959
960 // Loop passes are designed to run inside of a loop pass manager which means
961 // that any function analyses they require must be required by the first loop
962 // pass in the manager (so that it is computed before the loop pass manager
963 // runs) and preserved by all loop pasess in the manager. To make this
964 // reasonably robust, the set needed for most loop passes is maintained here.
965 // If your loop pass requires an analysis not listed here, you will need to
966 // carefully audit the loop pass manager nesting structure that results.
967 AU.addRequired<AAResultsWrapperPass>();
968 AU.addPreserved<AAResultsWrapperPass>();
969 AU.addPreserved<BasicAAWrapperPass>();
970 AU.addPreserved<GlobalsAAWrapperPass>();
971 AU.addPreserved<SCEVAAWrapperPass>();
972 AU.addRequired<ScalarEvolutionWrapperPass>();
973 AU.addPreserved<ScalarEvolutionWrapperPass>();
974}
975
976/// Manually defined generic "LoopPass" dependency initialization. This is used
977/// to initialize the exact set of passes from above in \c
978/// getLoopAnalysisUsage. It can be used within a loop pass's initialization
979/// with:
980///
981/// INITIALIZE_PASS_DEPENDENCY(LoopPass)
982///
983/// As-if "LoopPass" were a pass.
984void llvm::initializeLoopPassPass(PassRegistry &Registry) {
985 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
986 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
987 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Easwaran Ramane12c4872016-06-09 19:44:46 +0000988 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000989 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
990 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
991 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
992 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
993 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
994}
Adam Nemet963341c2016-04-21 17:33:17 +0000995
Adam Nemetfe3def72016-04-22 19:10:05 +0000996/// \brief Find string metadata for loop
997///
998/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
999/// operand or null otherwise. If the string metadata is not found return
1000/// Optional's not-a-value.
1001Optional<const MDOperand *> llvm::findStringMetadataForLoop(Loop *TheLoop,
1002 StringRef Name) {
Adam Nemet963341c2016-04-21 17:33:17 +00001003 MDNode *LoopID = TheLoop->getLoopID();
Adam Nemetfe3def72016-04-22 19:10:05 +00001004 // Return none if LoopID is false.
Adam Nemet963341c2016-04-21 17:33:17 +00001005 if (!LoopID)
Adam Nemetfe3def72016-04-22 19:10:05 +00001006 return None;
Adam Nemet293be662016-04-21 17:33:20 +00001007
1008 // First operand should refer to the loop id itself.
1009 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1010 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1011
Adam Nemet963341c2016-04-21 17:33:17 +00001012 // Iterate over LoopID operands and look for MDString Metadata
1013 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
1014 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1015 if (!MD)
1016 continue;
1017 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1018 if (!S)
1019 continue;
1020 // Return true if MDString holds expected MetaData.
1021 if (Name.equals(S->getString()))
Adam Nemetfe3def72016-04-22 19:10:05 +00001022 switch (MD->getNumOperands()) {
1023 case 1:
1024 return nullptr;
1025 case 2:
1026 return &MD->getOperand(1);
1027 default:
1028 llvm_unreachable("loop metadata has 0 or 1 operand");
1029 }
Adam Nemet963341c2016-04-21 17:33:17 +00001030 }
Adam Nemetfe3def72016-04-22 19:10:05 +00001031 return None;
Adam Nemet963341c2016-04-21 17:33:17 +00001032}
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001033
1034/// Returns true if the instruction in a loop is guaranteed to execute at least
1035/// once.
1036bool llvm::isGuaranteedToExecute(const Instruction &Inst,
1037 const DominatorTree *DT, const Loop *CurLoop,
1038 const LoopSafetyInfo *SafetyInfo) {
1039 // We have to check to make sure that the instruction dominates all
1040 // of the exit blocks. If it doesn't, then there is a path out of the loop
1041 // which does not execute this instruction, so we can't hoist it.
1042
1043 // If the instruction is in the header block for the loop (which is very
1044 // common), it is always guaranteed to dominate the exit blocks. Since this
1045 // is a common case, and can save some work, check it now.
1046 if (Inst.getParent() == CurLoop->getHeader())
1047 // If there's a throw in the header block, we can't guarantee we'll reach
1048 // Inst.
1049 return !SafetyInfo->HeaderMayThrow;
1050
1051 // Somewhere in this loop there is an instruction which may throw and make us
1052 // exit the loop.
1053 if (SafetyInfo->MayThrow)
1054 return false;
1055
1056 // Get the exit blocks for the current loop.
1057 SmallVector<BasicBlock *, 8> ExitBlocks;
1058 CurLoop->getExitBlocks(ExitBlocks);
1059
1060 // Verify that the block dominates each of the exit blocks of the loop.
1061 for (BasicBlock *ExitBlock : ExitBlocks)
1062 if (!DT->dominates(Inst.getParent(), ExitBlock))
1063 return false;
1064
1065 // As a degenerate case, if the loop is statically infinite then we haven't
1066 // proven anything since there are no exit blocks.
1067 if (ExitBlocks.empty())
1068 return false;
1069
Eli Friedmanf1da33e2016-06-11 21:48:25 +00001070 // FIXME: In general, we have to prove that the loop isn't an infinite loop.
1071 // See http::llvm.org/PR24078 . (The "ExitBlocks.empty()" check above is
1072 // just a special case of this.)
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001073 return true;
1074}
Dehao Chen41d72a82016-11-17 01:17:02 +00001075
1076Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) {
1077 // Only support loops with a unique exiting block, and a latch.
1078 if (!L->getExitingBlock())
1079 return None;
1080
1081 // Get the branch weights for the the loop's backedge.
1082 BranchInst *LatchBR =
1083 dyn_cast<BranchInst>(L->getLoopLatch()->getTerminator());
1084 if (!LatchBR || LatchBR->getNumSuccessors() != 2)
1085 return None;
1086
1087 assert((LatchBR->getSuccessor(0) == L->getHeader() ||
1088 LatchBR->getSuccessor(1) == L->getHeader()) &&
1089 "At least one edge out of the latch must go to the header");
1090
1091 // To estimate the number of times the loop body was executed, we want to
1092 // know the number of times the backedge was taken, vs. the number of times
1093 // we exited the loop.
Dehao Chen41d72a82016-11-17 01:17:02 +00001094 uint64_t TrueVal, FalseVal;
Michael Kupersteinb151a642016-11-30 21:13:57 +00001095 if (!LatchBR->extractProfMetadata(TrueVal, FalseVal))
Dehao Chen41d72a82016-11-17 01:17:02 +00001096 return None;
1097
Michael Kupersteinb151a642016-11-30 21:13:57 +00001098 if (!TrueVal || !FalseVal)
1099 return 0;
Dehao Chen41d72a82016-11-17 01:17:02 +00001100
Michael Kupersteinb151a642016-11-30 21:13:57 +00001101 // Divide the count of the backedge by the count of the edge exiting the loop,
1102 // rounding to nearest.
Dehao Chen41d72a82016-11-17 01:17:02 +00001103 if (LatchBR->getSuccessor(0) == L->getHeader())
Michael Kupersteinb151a642016-11-30 21:13:57 +00001104 return (TrueVal + (FalseVal / 2)) / FalseVal;
Dehao Chen41d72a82016-11-17 01:17:02 +00001105 else
Michael Kupersteinb151a642016-11-30 21:13:57 +00001106 return (FalseVal + (TrueVal / 2)) / TrueVal;
Dehao Chen41d72a82016-11-17 01:17:02 +00001107}