blob: 785e2d4917ffac70d412cb1e511bcc9deffaa514 [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
14#include "llvm/Analysis/LoopInfo.h"
15#include "llvm/IR/Instructions.h"
16#include "llvm/IR/PatternMatch.h"
17#include "llvm/IR/ValueHandle.h"
18#include "llvm/Support/Debug.h"
Karthik Bhat24e6cc22015-04-23 08:29:20 +000019#include "llvm/Analysis/ScalarEvolution.h"
20#include "llvm/Analysis/ScalarEvolutionExpressions.h"
21#include "llvm/IR/Module.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000022#include "llvm/Transforms/Utils/LoopUtils.h"
23
24using namespace llvm;
25using namespace llvm::PatternMatch;
26
27#define DEBUG_TYPE "loop-utils"
28
Tyler Nowicki0a913102015-06-16 18:07:34 +000029bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
30 SmallPtrSetImpl<Instruction *> &Set) {
Karthik Bhat76aa6622015-04-20 04:38:33 +000031 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
32 if (!Set.count(dyn_cast<Instruction>(*Use)))
33 return false;
34 return true;
35}
36
Chad Rosierc94f8e22015-08-27 14:12:17 +000037bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) {
38 switch (Kind) {
39 default:
40 break;
41 case RK_IntegerAdd:
42 case RK_IntegerMult:
43 case RK_IntegerOr:
44 case RK_IntegerAnd:
45 case RK_IntegerXor:
46 case RK_IntegerMinMax:
47 return true;
48 }
49 return false;
50}
51
52bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) {
53 return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
54}
55
56bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) {
57 switch (Kind) {
58 default:
59 break;
60 case RK_IntegerAdd:
61 case RK_IntegerMult:
62 case RK_FloatAdd:
63 case RK_FloatMult:
64 return true;
65 }
66 return false;
67}
68
69Instruction *
70RecurrenceDescriptor::lookThroughAnd(PHINode *Phi, Type *&RT,
71 SmallPtrSetImpl<Instruction *> &Visited,
72 SmallPtrSetImpl<Instruction *> &CI) {
73 if (!Phi->hasOneUse())
74 return Phi;
75
76 const APInt *M = nullptr;
77 Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
78
79 // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
80 // with a new integer type of the corresponding bit width.
81 if (match(J, m_CombineOr(m_And(m_Instruction(I), m_APInt(M)),
82 m_And(m_APInt(M), m_Instruction(I))))) {
83 int32_t Bits = (*M + 1).exactLogBase2();
84 if (Bits > 0) {
85 RT = IntegerType::get(Phi->getContext(), Bits);
86 Visited.insert(Phi);
87 CI.insert(J);
88 return J;
89 }
90 }
91 return Phi;
92}
93
94bool RecurrenceDescriptor::getSourceExtensionKind(
95 Instruction *Start, Instruction *Exit, Type *RT, bool &IsSigned,
96 SmallPtrSetImpl<Instruction *> &Visited,
97 SmallPtrSetImpl<Instruction *> &CI) {
98
99 SmallVector<Instruction *, 8> Worklist;
100 bool FoundOneOperand = false;
101 Worklist.push_back(Exit);
102
103 // Traverse the instructions in the reduction expression, beginning with the
104 // exit value.
105 while (!Worklist.empty()) {
106 Instruction *I = Worklist.pop_back_val();
107 for (Use &U : I->operands()) {
108
109 // Terminate the traversal if the operand is not an instruction, or we
110 // reach the starting value.
111 Instruction *J = dyn_cast<Instruction>(U.get());
112 if (!J || J == Start)
113 continue;
114
115 // Otherwise, investigate the operation if it is also in the expression.
116 if (Visited.count(J)) {
117 Worklist.push_back(J);
118 continue;
119 }
120
121 // If the operand is not in Visited, it is not a reduction operation, but
122 // it does feed into one. Make sure it is either a single-use sign- or
123 // zero-extend of the recurrence type.
124 CastInst *Cast = dyn_cast<CastInst>(J);
125 bool IsSExtInst = isa<SExtInst>(J);
126 if (!Cast || !Cast->hasOneUse() || Cast->getSrcTy() != RT ||
127 !(isa<ZExtInst>(J) || IsSExtInst))
128 return false;
129
130 // Furthermore, ensure that all such extends are of the same kind.
131 if (FoundOneOperand) {
132 if (IsSigned != IsSExtInst)
133 return false;
134 } else {
135 FoundOneOperand = true;
136 IsSigned = IsSExtInst;
137 }
138
139 // Lastly, add the sign- or zero-extend to CI so that we can avoid
140 // accounting for it in the cost model.
141 CI.insert(Cast);
142 }
143 }
144 return true;
145}
146
Tyler Nowicki0a913102015-06-16 18:07:34 +0000147bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind,
148 Loop *TheLoop, bool HasFunNoNaNAttr,
149 RecurrenceDescriptor &RedDes) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000150 if (Phi->getNumIncomingValues() != 2)
151 return false;
152
153 // Reduction variables are only found in the loop header block.
154 if (Phi->getParent() != TheLoop->getHeader())
155 return false;
156
157 // Obtain the reduction start value from the value that comes from the loop
158 // preheader.
159 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
160
161 // ExitInstruction is the single value which is used outside the loop.
162 // We only allow for a single reduction value to be used outside the loop.
163 // This includes users of the reduction, variables (which form a cycle
164 // which ends in the phi node).
165 Instruction *ExitInstruction = nullptr;
166 // Indicates that we found a reduction operation in our scan.
167 bool FoundReduxOp = false;
168
169 // We start with the PHI node and scan for all of the users of this
170 // instruction. All users must be instructions that can be used as reduction
171 // variables (such as ADD). We must have a single out-of-block user. The cycle
172 // must include the original PHI.
173 bool FoundStartPHI = false;
174
175 // To recognize min/max patterns formed by a icmp select sequence, we store
176 // the number of instruction we saw from the recognized min/max pattern,
177 // to make sure we only see exactly the two instructions.
178 unsigned NumCmpSelectPatternInst = 0;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000179 InstDesc ReduxDesc(false, nullptr);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000180
Chad Rosierc94f8e22015-08-27 14:12:17 +0000181 // Data used for determining if the recurrence has been type-promoted.
182 Type *RecurrenceType = Phi->getType();
183 SmallPtrSet<Instruction *, 4> CastInsts;
184 Instruction *Start = Phi;
185 bool IsSigned = false;
186
Karthik Bhat76aa6622015-04-20 04:38:33 +0000187 SmallPtrSet<Instruction *, 8> VisitedInsts;
188 SmallVector<Instruction *, 8> Worklist;
Chad Rosierc94f8e22015-08-27 14:12:17 +0000189
190 // Return early if the recurrence kind does not match the type of Phi. If the
191 // recurrence kind is arithmetic, we attempt to look through AND operations
192 // resulting from the type promotion performed by InstCombine. Vector
193 // operations are not limited to the legal integer widths, so we may be able
194 // to evaluate the reduction in the narrower width.
195 if (RecurrenceType->isFloatingPointTy()) {
196 if (!isFloatingPointRecurrenceKind(Kind))
197 return false;
198 } else {
199 if (!isIntegerRecurrenceKind(Kind))
200 return false;
201 if (isArithmeticRecurrenceKind(Kind))
202 Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
203 }
204
205 Worklist.push_back(Start);
206 VisitedInsts.insert(Start);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000207
208 // A value in the reduction can be used:
209 // - By the reduction:
210 // - Reduction operation:
211 // - One use of reduction value (safe).
212 // - Multiple use of reduction value (not safe).
213 // - PHI:
214 // - All uses of the PHI must be the reduction (safe).
215 // - Otherwise, not safe.
216 // - By one instruction outside of the loop (safe).
217 // - By further instructions outside of the loop (not safe).
218 // - By an instruction that is not part of the reduction (not safe).
219 // This is either:
220 // * An instruction type other than PHI or the reduction operation.
221 // * A PHI in the header other than the initial PHI.
222 while (!Worklist.empty()) {
223 Instruction *Cur = Worklist.back();
224 Worklist.pop_back();
225
226 // No Users.
227 // If the instruction has no users then this is a broken chain and can't be
228 // a reduction variable.
229 if (Cur->use_empty())
230 return false;
231
232 bool IsAPhi = isa<PHINode>(Cur);
233
234 // A header PHI use other than the original PHI.
235 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
236 return false;
237
238 // Reductions of instructions such as Div, and Sub is only possible if the
239 // LHS is the reduction variable.
240 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
241 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
242 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
243 return false;
244
Chad Rosierc94f8e22015-08-27 14:12:17 +0000245 // Any reduction instruction must be of one of the allowed kinds. We ignore
246 // the starting value (the Phi or an AND instruction if the Phi has been
247 // type-promoted).
248 if (Cur != Start) {
249 ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
250 if (!ReduxDesc.isRecurrence())
251 return false;
252 }
Karthik Bhat76aa6622015-04-20 04:38:33 +0000253
254 // A reduction operation must only have one use of the reduction value.
255 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
256 hasMultipleUsesOf(Cur, VisitedInsts))
257 return false;
258
259 // All inputs to a PHI node must be a reduction value.
260 if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
261 return false;
262
263 if (Kind == RK_IntegerMinMax &&
264 (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
265 ++NumCmpSelectPatternInst;
266 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
267 ++NumCmpSelectPatternInst;
268
269 // Check whether we found a reduction operator.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000270 FoundReduxOp |= !IsAPhi && Cur != Start;
Karthik Bhat76aa6622015-04-20 04:38:33 +0000271
272 // Process users of current instruction. Push non-PHI nodes after PHI nodes
273 // onto the stack. This way we are going to have seen all inputs to PHI
274 // nodes once we get to them.
275 SmallVector<Instruction *, 8> NonPHIs;
276 SmallVector<Instruction *, 8> PHIs;
277 for (User *U : Cur->users()) {
278 Instruction *UI = cast<Instruction>(U);
279
280 // Check if we found the exit user.
281 BasicBlock *Parent = UI->getParent();
282 if (!TheLoop->contains(Parent)) {
283 // Exit if you find multiple outside users or if the header phi node is
284 // being used. In this case the user uses the value of the previous
285 // iteration, in which case we would loose "VF-1" iterations of the
286 // reduction operation if we vectorize.
287 if (ExitInstruction != nullptr || Cur == Phi)
288 return false;
289
290 // The instruction used by an outside user must be the last instruction
291 // before we feed back to the reduction phi. Otherwise, we loose VF-1
292 // operations on the value.
293 if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
294 return false;
295
296 ExitInstruction = Cur;
297 continue;
298 }
299
300 // Process instructions only once (termination). Each reduction cycle
301 // value must only be used once, except by phi nodes and min/max
302 // reductions which are represented as a cmp followed by a select.
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000303 InstDesc IgnoredVal(false, nullptr);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000304 if (VisitedInsts.insert(UI).second) {
305 if (isa<PHINode>(UI))
306 PHIs.push_back(UI);
307 else
308 NonPHIs.push_back(UI);
309 } else if (!isa<PHINode>(UI) &&
310 ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
311 !isa<SelectInst>(UI)) ||
Tyler Nowicki0a913102015-06-16 18:07:34 +0000312 !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence()))
Karthik Bhat76aa6622015-04-20 04:38:33 +0000313 return false;
314
315 // Remember that we completed the cycle.
316 if (UI == Phi)
317 FoundStartPHI = true;
318 }
319 Worklist.append(PHIs.begin(), PHIs.end());
320 Worklist.append(NonPHIs.begin(), NonPHIs.end());
321 }
322
323 // This means we have seen one but not the other instruction of the
324 // pattern or more than just a select and cmp.
325 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
326 NumCmpSelectPatternInst != 2)
327 return false;
328
329 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
330 return false;
331
Chad Rosierc94f8e22015-08-27 14:12:17 +0000332 // If we think Phi may have been type-promoted, we also need to ensure that
333 // all source operands of the reduction are either SExtInsts or ZEstInsts. If
334 // so, we will be able to evaluate the reduction in the narrower bit width.
335 if (Start != Phi)
336 if (!getSourceExtensionKind(Start, ExitInstruction, RecurrenceType,
337 IsSigned, VisitedInsts, CastInsts))
338 return false;
339
Karthik Bhat76aa6622015-04-20 04:38:33 +0000340 // We found a reduction var if we have reached the original phi node and we
341 // only have a single instruction with out-of-loop users.
342
343 // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
Tyler Nowicki0a913102015-06-16 18:07:34 +0000344 // is saved as part of the RecurrenceDescriptor.
Karthik Bhat76aa6622015-04-20 04:38:33 +0000345
346 // Save the description of this reduction variable.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000347 RecurrenceDescriptor RD(
348 RdxStart, ExitInstruction, Kind, ReduxDesc.getMinMaxKind(),
349 ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000350 RedDes = RD;
351
352 return true;
353}
354
355/// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
356/// pattern corresponding to a min(X, Y) or max(X, Y).
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000357RecurrenceDescriptor::InstDesc
358RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000359
360 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
361 "Expect a select instruction");
362 Instruction *Cmp = nullptr;
363 SelectInst *Select = nullptr;
364
365 // We must handle the select(cmp()) as a single instruction. Advance to the
366 // select.
367 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
368 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000369 return InstDesc(false, I);
370 return InstDesc(Select, Prev.getMinMaxKind());
Karthik Bhat76aa6622015-04-20 04:38:33 +0000371 }
372
373 // Only handle single use cases for now.
374 if (!(Select = dyn_cast<SelectInst>(I)))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000375 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000376 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
377 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000378 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000379 if (!Cmp->hasOneUse())
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000380 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000381
382 Value *CmpLeft;
383 Value *CmpRight;
384
385 // Look for a min/max pattern.
386 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000387 return InstDesc(Select, MRK_UIntMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000388 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000389 return InstDesc(Select, MRK_UIntMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000390 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000391 return InstDesc(Select, MRK_SIntMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000392 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000393 return InstDesc(Select, MRK_SIntMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000394 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000395 return InstDesc(Select, MRK_FloatMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000396 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000397 return InstDesc(Select, MRK_FloatMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000398 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000399 return InstDesc(Select, MRK_FloatMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000400 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000401 return InstDesc(Select, MRK_FloatMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000402
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000403 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000404}
405
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000406RecurrenceDescriptor::InstDesc
Tyler Nowicki0a913102015-06-16 18:07:34 +0000407RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000408 InstDesc &Prev, bool HasFunNoNaNAttr) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000409 bool FP = I->getType()->isFloatingPointTy();
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000410 Instruction *UAI = Prev.getUnsafeAlgebraInst();
411 if (!UAI && FP && !I->hasUnsafeAlgebra())
412 UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
413
Karthik Bhat76aa6622015-04-20 04:38:33 +0000414 switch (I->getOpcode()) {
415 default:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000416 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000417 case Instruction::PHI:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000418 return InstDesc(I, Prev.getMinMaxKind());
Karthik Bhat76aa6622015-04-20 04:38:33 +0000419 case Instruction::Sub:
420 case Instruction::Add:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000421 return InstDesc(Kind == RK_IntegerAdd, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000422 case Instruction::Mul:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000423 return InstDesc(Kind == RK_IntegerMult, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000424 case Instruction::And:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000425 return InstDesc(Kind == RK_IntegerAnd, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000426 case Instruction::Or:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000427 return InstDesc(Kind == RK_IntegerOr, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000428 case Instruction::Xor:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000429 return InstDesc(Kind == RK_IntegerXor, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000430 case Instruction::FMul:
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000431 return InstDesc(Kind == RK_FloatMult, I, UAI);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000432 case Instruction::FSub:
433 case Instruction::FAdd:
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000434 return InstDesc(Kind == RK_FloatAdd, I, UAI);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000435 case Instruction::FCmp:
436 case Instruction::ICmp:
437 case Instruction::Select:
438 if (Kind != RK_IntegerMinMax &&
439 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000440 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000441 return isMinMaxSelectCmpPattern(I, Prev);
442 }
443}
444
Tyler Nowicki0a913102015-06-16 18:07:34 +0000445bool RecurrenceDescriptor::hasMultipleUsesOf(
Karthik Bhat76aa6622015-04-20 04:38:33 +0000446 Instruction *I, SmallPtrSetImpl<Instruction *> &Insts) {
447 unsigned NumUses = 0;
448 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
449 ++Use) {
450 if (Insts.count(dyn_cast<Instruction>(*Use)))
451 ++NumUses;
452 if (NumUses > 1)
453 return true;
454 }
455
456 return false;
457}
Tyler Nowicki0a913102015-06-16 18:07:34 +0000458bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
459 RecurrenceDescriptor &RedDes) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000460
461 bool HasFunNoNaNAttr = false;
462 BasicBlock *Header = TheLoop->getHeader();
463 Function &F = *Header->getParent();
464 if (F.hasFnAttribute("no-nans-fp-math"))
465 HasFunNoNaNAttr =
466 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
467
468 if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
469 DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
470 return true;
471 }
472 if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
473 DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
474 return true;
475 }
476 if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes)) {
477 DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
478 return true;
479 }
480 if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes)) {
481 DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
482 return true;
483 }
484 if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes)) {
485 DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
486 return true;
487 }
488 if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr,
489 RedDes)) {
490 DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
491 return true;
492 }
493 if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
494 DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
495 return true;
496 }
497 if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
498 DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
499 return true;
500 }
501 if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes)) {
502 DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi << "\n");
503 return true;
504 }
505 // Not a reduction of known type.
506 return false;
507}
508
509/// This function returns the identity element (or neutral element) for
510/// the operation K.
Tyler Nowicki0a913102015-06-16 18:07:34 +0000511Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K,
512 Type *Tp) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000513 switch (K) {
514 case RK_IntegerXor:
515 case RK_IntegerAdd:
516 case RK_IntegerOr:
517 // Adding, Xoring, Oring zero to a number does not change it.
518 return ConstantInt::get(Tp, 0);
519 case RK_IntegerMult:
520 // Multiplying a number by 1 does not change it.
521 return ConstantInt::get(Tp, 1);
522 case RK_IntegerAnd:
523 // AND-ing a number with an all-1 value does not change it.
524 return ConstantInt::get(Tp, -1, true);
525 case RK_FloatMult:
526 // Multiplying a number by 1 does not change it.
527 return ConstantFP::get(Tp, 1.0L);
528 case RK_FloatAdd:
529 // Adding zero to a number does not change it.
530 return ConstantFP::get(Tp, 0.0L);
531 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000532 llvm_unreachable("Unknown recurrence kind");
Karthik Bhat76aa6622015-04-20 04:38:33 +0000533 }
534}
535
Tyler Nowicki0a913102015-06-16 18:07:34 +0000536/// This function translates the recurrence kind to an LLVM binary operator.
537unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000538 switch (Kind) {
539 case RK_IntegerAdd:
540 return Instruction::Add;
541 case RK_IntegerMult:
542 return Instruction::Mul;
543 case RK_IntegerOr:
544 return Instruction::Or;
545 case RK_IntegerAnd:
546 return Instruction::And;
547 case RK_IntegerXor:
548 return Instruction::Xor;
549 case RK_FloatMult:
550 return Instruction::FMul;
551 case RK_FloatAdd:
552 return Instruction::FAdd;
553 case RK_IntegerMinMax:
554 return Instruction::ICmp;
555 case RK_FloatMinMax:
556 return Instruction::FCmp;
557 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000558 llvm_unreachable("Unknown recurrence operation");
Karthik Bhat76aa6622015-04-20 04:38:33 +0000559 }
560}
561
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000562Value *RecurrenceDescriptor::createMinMaxOp(IRBuilder<> &Builder,
563 MinMaxRecurrenceKind RK,
564 Value *Left, Value *Right) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000565 CmpInst::Predicate P = CmpInst::ICMP_NE;
566 switch (RK) {
567 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000568 llvm_unreachable("Unknown min/max recurrence kind");
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000569 case MRK_UIntMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000570 P = CmpInst::ICMP_ULT;
571 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000572 case MRK_UIntMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000573 P = CmpInst::ICMP_UGT;
574 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000575 case MRK_SIntMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000576 P = CmpInst::ICMP_SLT;
577 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000578 case MRK_SIntMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000579 P = CmpInst::ICMP_SGT;
580 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000581 case MRK_FloatMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000582 P = CmpInst::FCMP_OLT;
583 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000584 case MRK_FloatMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000585 P = CmpInst::FCMP_OGT;
586 break;
587 }
588
589 Value *Cmp;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000590 if (RK == MRK_FloatMin || RK == MRK_FloatMax)
Karthik Bhat76aa6622015-04-20 04:38:33 +0000591 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
592 else
593 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
594
595 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
596 return Select;
597}
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000598
James Molloy1bbf15c2015-08-27 09:53:00 +0000599InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
600 ConstantInt *Step)
601 : StartValue(Start), IK(K), StepValue(Step) {
602 assert(IK != IK_NoInduction && "Not an induction");
603 assert(StartValue && "StartValue is null");
604 assert(StepValue && !StepValue->isZero() && "StepValue is zero");
605 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
606 "StartValue is not a pointer for pointer induction");
607 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
608 "StartValue is not an integer for integer induction");
609 assert(StepValue->getType()->isIntegerTy() &&
610 "StepValue is not an integer");
611}
612
613int InductionDescriptor::getConsecutiveDirection() const {
614 if (StepValue && (StepValue->isOne() || StepValue->isMinusOne()))
615 return StepValue->getSExtValue();
616 return 0;
617}
618
619Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index) const {
620 switch (IK) {
621 case IK_IntInduction:
622 assert(Index->getType() == StartValue->getType() &&
623 "Index type does not match StartValue type");
624 if (StepValue->isMinusOne())
625 return B.CreateSub(StartValue, Index);
626 if (!StepValue->isOne())
627 Index = B.CreateMul(Index, StepValue);
628 return B.CreateAdd(StartValue, Index);
629
630 case IK_PtrInduction:
631 assert(Index->getType() == StepValue->getType() &&
632 "Index type does not match StepValue type");
633 if (StepValue->isMinusOne())
634 Index = B.CreateNeg(Index);
635 else if (!StepValue->isOne())
636 Index = B.CreateMul(Index, StepValue);
637 return B.CreateGEP(nullptr, StartValue, Index);
638
639 case IK_NoInduction:
640 return nullptr;
641 }
642 llvm_unreachable("invalid enum");
643}
644
645bool InductionDescriptor::isInductionPHI(PHINode *Phi, ScalarEvolution *SE,
646 InductionDescriptor &D) {
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000647 Type *PhiTy = Phi->getType();
648 // We only handle integer and pointer inductions variables.
649 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
650 return false;
651
652 // Check that the PHI is consecutive.
653 const SCEV *PhiScev = SE->getSCEV(Phi);
654 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
655 if (!AR) {
656 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
657 return false;
658 }
659
James Molloy1bbf15c2015-08-27 09:53:00 +0000660 assert(AR->getLoop()->getHeader() == Phi->getParent() &&
661 "PHI is an AddRec for a different loop?!");
662 Value *StartValue =
663 Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000664 const SCEV *Step = AR->getStepRecurrence(*SE);
665 // Calculate the pointer stride and check if it is consecutive.
666 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
667 if (!C)
668 return false;
669
670 ConstantInt *CV = C->getValue();
671 if (PhiTy->isIntegerTy()) {
James Molloy1bbf15c2015-08-27 09:53:00 +0000672 D = InductionDescriptor(StartValue, IK_IntInduction, CV);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000673 return true;
674 }
675
676 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
677 Type *PointerElementType = PhiTy->getPointerElementType();
678 // The pointer stride cannot be determined if the pointer element type is not
679 // sized.
680 if (!PointerElementType->isSized())
681 return false;
682
683 const DataLayout &DL = Phi->getModule()->getDataLayout();
684 int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
David Majnemerb58f32f2015-06-05 10:52:40 +0000685 if (!Size)
686 return false;
687
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000688 int64_t CVSize = CV->getSExtValue();
689 if (CVSize % Size)
690 return false;
James Molloy1bbf15c2015-08-27 09:53:00 +0000691 auto *StepValue = ConstantInt::getSigned(CV->getType(), CVSize / Size);
692
693 D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000694 return true;
695}
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000696
697/// \brief Returns the instructions that use values defined in the loop.
698SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
699 SmallVector<Instruction *, 8> UsedOutside;
700
701 for (auto *Block : L->getBlocks())
702 // FIXME: I believe that this could use copy_if if the Inst reference could
703 // be adapted into a pointer.
704 for (auto &Inst : *Block) {
705 auto Users = Inst.users();
706 if (std::any_of(Users.begin(), Users.end(), [&](User *U) {
707 auto *Use = cast<Instruction>(U);
708 return !L->contains(Use->getParent());
709 }))
710 UsedOutside.push_back(&Inst);
711 }
712
713 return UsedOutside;
714}