blob: 240fff0d8222f21e15ae122f22593ba257fa54f1 [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
Chandler Carruth31088a92016-02-19 10:45:18 +000014#include "llvm/Analysis/AliasAnalysis.h"
15#include "llvm/Analysis/BasicAliasAnalysis.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000016#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000017#include "llvm/Analysis/GlobalsModRef.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000018#include "llvm/Analysis/ScalarEvolution.h"
19#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000020#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
21#include "llvm/IR/Dominators.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000022#include "llvm/IR/Instructions.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000023#include "llvm/IR/Module.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000024#include "llvm/IR/PatternMatch.h"
25#include "llvm/IR/ValueHandle.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000026#include "llvm/Pass.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000027#include "llvm/Support/Debug.h"
28#include "llvm/Transforms/Utils/LoopUtils.h"
29
30using namespace llvm;
31using namespace llvm::PatternMatch;
32
33#define DEBUG_TYPE "loop-utils"
34
Tyler Nowicki0a913102015-06-16 18:07:34 +000035bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
36 SmallPtrSetImpl<Instruction *> &Set) {
Karthik Bhat76aa6622015-04-20 04:38:33 +000037 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
Chad Rosierc94f8e22015-08-27 14:12:17 +000043bool 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
58bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) {
59 return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
60}
61
62bool 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
75Instruction *
76RecurrenceDescriptor::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
100bool 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;
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000107 unsigned DstSize = RT->getPrimitiveSizeInBits();
Chad Rosierc94f8e22015-08-27 14:12:17 +0000108 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
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000130 // zero-extend instruction.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000131 CastInst *Cast = dyn_cast<CastInst>(J);
132 bool IsSExtInst = isa<SExtInst>(J);
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000133 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)
Chad Rosierc94f8e22015-08-27 14:12:17 +0000140 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
Matthew Simpson29dc0f72015-09-10 21:12:57 +0000151 // 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);
Chad Rosierc94f8e22015-08-27 14:12:17 +0000156 }
157 }
158 return true;
159}
160
Tyler Nowicki0a913102015-06-16 18:07:34 +0000161bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind,
162 Loop *TheLoop, bool HasFunNoNaNAttr,
163 RecurrenceDescriptor &RedDes) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000164 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;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000193 InstDesc ReduxDesc(false, nullptr);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000194
Chad Rosierc94f8e22015-08-27 14:12:17 +0000195 // 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
Karthik Bhat76aa6622015-04-20 04:38:33 +0000201 SmallPtrSet<Instruction *, 8> VisitedInsts;
202 SmallVector<Instruction *, 8> Worklist;
Chad Rosierc94f8e22015-08-27 14:12:17 +0000203
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);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000221
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
Chad Rosierc94f8e22015-08-27 14:12:17 +0000259 // 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 }
Karthik Bhat76aa6622015-04-20 04:38:33 +0000267
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.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000284 FoundReduxOp |= !IsAPhi && Cur != Start;
Karthik Bhat76aa6622015-04-20 04:38:33 +0000285
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.
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000317 InstDesc IgnoredVal(false, nullptr);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000318 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)) ||
Tyler Nowicki0a913102015-06-16 18:07:34 +0000326 !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence()))
Karthik Bhat76aa6622015-04-20 04:38:33 +0000327 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
Chad Rosierc94f8e22015-08-27 14:12:17 +0000346 // 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
Karthik Bhat76aa6622015-04-20 04:38:33 +0000354 // 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)
Tyler Nowicki0a913102015-06-16 18:07:34 +0000358 // is saved as part of the RecurrenceDescriptor.
Karthik Bhat76aa6622015-04-20 04:38:33 +0000359
360 // Save the description of this reduction variable.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000361 RecurrenceDescriptor RD(
362 RdxStart, ExitInstruction, Kind, ReduxDesc.getMinMaxKind(),
363 ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000364 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).
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000371RecurrenceDescriptor::InstDesc
372RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000373
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())))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000383 return InstDesc(false, I);
384 return InstDesc(Select, Prev.getMinMaxKind());
Karthik Bhat76aa6622015-04-20 04:38:33 +0000385 }
386
387 // Only handle single use cases for now.
388 if (!(Select = dyn_cast<SelectInst>(I)))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000389 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000390 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
391 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000392 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000393 if (!Cmp->hasOneUse())
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000394 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000395
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))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000401 return InstDesc(Select, MRK_UIntMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000402 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000403 return InstDesc(Select, MRK_UIntMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000404 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000405 return InstDesc(Select, MRK_SIntMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000406 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000407 return InstDesc(Select, MRK_SIntMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000408 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000409 return InstDesc(Select, MRK_FloatMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000410 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000411 return InstDesc(Select, MRK_FloatMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000412 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000413 return InstDesc(Select, MRK_FloatMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000414 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000415 return InstDesc(Select, MRK_FloatMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000416
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000417 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000418}
419
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000420RecurrenceDescriptor::InstDesc
Tyler Nowicki0a913102015-06-16 18:07:34 +0000421RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000422 InstDesc &Prev, bool HasFunNoNaNAttr) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000423 bool FP = I->getType()->isFloatingPointTy();
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000424 Instruction *UAI = Prev.getUnsafeAlgebraInst();
425 if (!UAI && FP && !I->hasUnsafeAlgebra())
426 UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
427
Karthik Bhat76aa6622015-04-20 04:38:33 +0000428 switch (I->getOpcode()) {
429 default:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000430 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000431 case Instruction::PHI:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000432 return InstDesc(I, Prev.getMinMaxKind());
Karthik Bhat76aa6622015-04-20 04:38:33 +0000433 case Instruction::Sub:
434 case Instruction::Add:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000435 return InstDesc(Kind == RK_IntegerAdd, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000436 case Instruction::Mul:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000437 return InstDesc(Kind == RK_IntegerMult, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000438 case Instruction::And:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000439 return InstDesc(Kind == RK_IntegerAnd, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000440 case Instruction::Or:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000441 return InstDesc(Kind == RK_IntegerOr, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000442 case Instruction::Xor:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000443 return InstDesc(Kind == RK_IntegerXor, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000444 case Instruction::FMul:
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000445 return InstDesc(Kind == RK_FloatMult, I, UAI);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000446 case Instruction::FSub:
447 case Instruction::FAdd:
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000448 return InstDesc(Kind == RK_FloatAdd, I, UAI);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000449 case Instruction::FCmp:
450 case Instruction::ICmp:
451 case Instruction::Select:
452 if (Kind != RK_IntegerMinMax &&
453 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000454 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000455 return isMinMaxSelectCmpPattern(I, Prev);
456 }
457}
458
Tyler Nowicki0a913102015-06-16 18:07:34 +0000459bool RecurrenceDescriptor::hasMultipleUsesOf(
Karthik Bhat76aa6622015-04-20 04:38:33 +0000460 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}
Tyler Nowicki0a913102015-06-16 18:07:34 +0000472bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
473 RecurrenceDescriptor &RedDes) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000474
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/// This function returns the identity element (or neutral element) for
524/// the operation K.
Tyler Nowicki0a913102015-06-16 18:07:34 +0000525Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K,
526 Type *Tp) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000527 switch (K) {
528 case RK_IntegerXor:
529 case RK_IntegerAdd:
530 case RK_IntegerOr:
531 // Adding, Xoring, Oring zero to a number does not change it.
532 return ConstantInt::get(Tp, 0);
533 case RK_IntegerMult:
534 // Multiplying a number by 1 does not change it.
535 return ConstantInt::get(Tp, 1);
536 case RK_IntegerAnd:
537 // AND-ing a number with an all-1 value does not change it.
538 return ConstantInt::get(Tp, -1, true);
539 case RK_FloatMult:
540 // Multiplying a number by 1 does not change it.
541 return ConstantFP::get(Tp, 1.0L);
542 case RK_FloatAdd:
543 // Adding zero to a number does not change it.
544 return ConstantFP::get(Tp, 0.0L);
545 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000546 llvm_unreachable("Unknown recurrence kind");
Karthik Bhat76aa6622015-04-20 04:38:33 +0000547 }
548}
549
Tyler Nowicki0a913102015-06-16 18:07:34 +0000550/// This function translates the recurrence kind to an LLVM binary operator.
551unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000552 switch (Kind) {
553 case RK_IntegerAdd:
554 return Instruction::Add;
555 case RK_IntegerMult:
556 return Instruction::Mul;
557 case RK_IntegerOr:
558 return Instruction::Or;
559 case RK_IntegerAnd:
560 return Instruction::And;
561 case RK_IntegerXor:
562 return Instruction::Xor;
563 case RK_FloatMult:
564 return Instruction::FMul;
565 case RK_FloatAdd:
566 return Instruction::FAdd;
567 case RK_IntegerMinMax:
568 return Instruction::ICmp;
569 case RK_FloatMinMax:
570 return Instruction::FCmp;
571 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000572 llvm_unreachable("Unknown recurrence operation");
Karthik Bhat76aa6622015-04-20 04:38:33 +0000573 }
574}
575
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000576Value *RecurrenceDescriptor::createMinMaxOp(IRBuilder<> &Builder,
577 MinMaxRecurrenceKind RK,
578 Value *Left, Value *Right) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000579 CmpInst::Predicate P = CmpInst::ICMP_NE;
580 switch (RK) {
581 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000582 llvm_unreachable("Unknown min/max recurrence kind");
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000583 case MRK_UIntMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000584 P = CmpInst::ICMP_ULT;
585 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000586 case MRK_UIntMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000587 P = CmpInst::ICMP_UGT;
588 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000589 case MRK_SIntMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000590 P = CmpInst::ICMP_SLT;
591 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000592 case MRK_SIntMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000593 P = CmpInst::ICMP_SGT;
594 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000595 case MRK_FloatMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000596 P = CmpInst::FCMP_OLT;
597 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000598 case MRK_FloatMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000599 P = CmpInst::FCMP_OGT;
600 break;
601 }
602
James Molloy50a4c272015-09-21 19:41:19 +0000603 // We only match FP sequences with unsafe algebra, so we can unconditionally
604 // set it on any generated instructions.
605 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
606 FastMathFlags FMF;
607 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +0000608 Builder.setFastMathFlags(FMF);
James Molloy50a4c272015-09-21 19:41:19 +0000609
Karthik Bhat76aa6622015-04-20 04:38:33 +0000610 Value *Cmp;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000611 if (RK == MRK_FloatMin || RK == MRK_FloatMax)
Karthik Bhat76aa6622015-04-20 04:38:33 +0000612 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
613 else
614 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
615
616 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
617 return Select;
618}
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000619
James Molloy1bbf15c2015-08-27 09:53:00 +0000620InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
621 ConstantInt *Step)
622 : StartValue(Start), IK(K), StepValue(Step) {
623 assert(IK != IK_NoInduction && "Not an induction");
624 assert(StartValue && "StartValue is null");
625 assert(StepValue && !StepValue->isZero() && "StepValue is zero");
626 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
627 "StartValue is not a pointer for pointer induction");
628 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
629 "StartValue is not an integer for integer induction");
630 assert(StepValue->getType()->isIntegerTy() &&
631 "StepValue is not an integer");
632}
633
634int InductionDescriptor::getConsecutiveDirection() const {
635 if (StepValue && (StepValue->isOne() || StepValue->isMinusOne()))
636 return StepValue->getSExtValue();
637 return 0;
638}
639
640Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index) const {
641 switch (IK) {
642 case IK_IntInduction:
643 assert(Index->getType() == StartValue->getType() &&
644 "Index type does not match StartValue type");
645 if (StepValue->isMinusOne())
646 return B.CreateSub(StartValue, Index);
647 if (!StepValue->isOne())
648 Index = B.CreateMul(Index, StepValue);
649 return B.CreateAdd(StartValue, Index);
650
651 case IK_PtrInduction:
652 assert(Index->getType() == StepValue->getType() &&
653 "Index type does not match StepValue type");
654 if (StepValue->isMinusOne())
655 Index = B.CreateNeg(Index);
656 else if (!StepValue->isOne())
657 Index = B.CreateMul(Index, StepValue);
658 return B.CreateGEP(nullptr, StartValue, Index);
659
660 case IK_NoInduction:
661 return nullptr;
662 }
663 llvm_unreachable("invalid enum");
664}
665
666bool InductionDescriptor::isInductionPHI(PHINode *Phi, ScalarEvolution *SE,
667 InductionDescriptor &D) {
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000668 Type *PhiTy = Phi->getType();
669 // We only handle integer and pointer inductions variables.
670 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
671 return false;
672
673 // Check that the PHI is consecutive.
674 const SCEV *PhiScev = SE->getSCEV(Phi);
675 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
676 if (!AR) {
677 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
678 return false;
679 }
680
James Molloy1bbf15c2015-08-27 09:53:00 +0000681 assert(AR->getLoop()->getHeader() == Phi->getParent() &&
682 "PHI is an AddRec for a different loop?!");
683 Value *StartValue =
684 Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000685 const SCEV *Step = AR->getStepRecurrence(*SE);
686 // Calculate the pointer stride and check if it is consecutive.
687 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
688 if (!C)
689 return false;
690
691 ConstantInt *CV = C->getValue();
692 if (PhiTy->isIntegerTy()) {
James Molloy1bbf15c2015-08-27 09:53:00 +0000693 D = InductionDescriptor(StartValue, IK_IntInduction, CV);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000694 return true;
695 }
696
697 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
698 Type *PointerElementType = PhiTy->getPointerElementType();
699 // The pointer stride cannot be determined if the pointer element type is not
700 // sized.
701 if (!PointerElementType->isSized())
702 return false;
703
704 const DataLayout &DL = Phi->getModule()->getDataLayout();
705 int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
David Majnemerb58f32f2015-06-05 10:52:40 +0000706 if (!Size)
707 return false;
708
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000709 int64_t CVSize = CV->getSExtValue();
710 if (CVSize % Size)
711 return false;
James Molloy1bbf15c2015-08-27 09:53:00 +0000712 auto *StepValue = ConstantInt::getSigned(CV->getType(), CVSize / Size);
713
714 D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000715 return true;
716}
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000717
718/// \brief Returns the instructions that use values defined in the loop.
719SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
720 SmallVector<Instruction *, 8> UsedOutside;
721
722 for (auto *Block : L->getBlocks())
723 // FIXME: I believe that this could use copy_if if the Inst reference could
724 // be adapted into a pointer.
725 for (auto &Inst : *Block) {
726 auto Users = Inst.users();
727 if (std::any_of(Users.begin(), Users.end(), [&](User *U) {
728 auto *Use = cast<Instruction>(U);
729 return !L->contains(Use->getParent());
730 }))
731 UsedOutside.push_back(&Inst);
732 }
733
734 return UsedOutside;
735}
Chandler Carruth31088a92016-02-19 10:45:18 +0000736
737void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
738 // By definition, all loop passes need the LoopInfo analysis and the
739 // Dominator tree it depends on. Because they all participate in the loop
740 // pass manager, they must also preserve these.
741 AU.addRequired<DominatorTreeWrapperPass>();
742 AU.addPreserved<DominatorTreeWrapperPass>();
743 AU.addRequired<LoopInfoWrapperPass>();
744 AU.addPreserved<LoopInfoWrapperPass>();
745
746 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
747 // here because users shouldn't directly get them from this header.
748 extern char &LoopSimplifyID;
749 extern char &LCSSAID;
750 AU.addRequiredID(LoopSimplifyID);
751 AU.addPreservedID(LoopSimplifyID);
752 AU.addRequiredID(LCSSAID);
753 AU.addPreservedID(LCSSAID);
754
755 // Loop passes are designed to run inside of a loop pass manager which means
756 // that any function analyses they require must be required by the first loop
757 // pass in the manager (so that it is computed before the loop pass manager
758 // runs) and preserved by all loop pasess in the manager. To make this
759 // reasonably robust, the set needed for most loop passes is maintained here.
760 // If your loop pass requires an analysis not listed here, you will need to
761 // carefully audit the loop pass manager nesting structure that results.
762 AU.addRequired<AAResultsWrapperPass>();
763 AU.addPreserved<AAResultsWrapperPass>();
764 AU.addPreserved<BasicAAWrapperPass>();
765 AU.addPreserved<GlobalsAAWrapperPass>();
766 AU.addPreserved<SCEVAAWrapperPass>();
767 AU.addRequired<ScalarEvolutionWrapperPass>();
768 AU.addPreserved<ScalarEvolutionWrapperPass>();
769}
770
771/// Manually defined generic "LoopPass" dependency initialization. This is used
772/// to initialize the exact set of passes from above in \c
773/// getLoopAnalysisUsage. It can be used within a loop pass's initialization
774/// with:
775///
776/// INITIALIZE_PASS_DEPENDENCY(LoopPass)
777///
778/// As-if "LoopPass" were a pass.
779void llvm::initializeLoopPassPass(PassRegistry &Registry) {
780 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
781 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
782 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
783 INITIALIZE_PASS_DEPENDENCY(LCSSA)
784 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
785 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
786 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
787 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
788 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
789}