blob: 88fa9812da40aa2335ceac187a5bc90f87c782c2 [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/LoopInfo.h"
Igor Laevskyc3ccf5d2016-10-28 12:57:20 +000019#include "llvm/Analysis/LoopPass.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000020#include "llvm/Analysis/ScalarEvolution.h"
Adam Nemet2f2bd8c2016-07-26 17:52:02 +000021#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Elena Demikhovskyc434d092016-05-10 07:33:35 +000022#include "llvm/Analysis/ScalarEvolutionExpander.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000023#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000024#include "llvm/Analysis/TargetTransformInfo.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"
Chandler Carruth4ab0f492017-06-23 04:03:04 +000032#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000033
34using namespace llvm;
35using namespace llvm::PatternMatch;
36
37#define DEBUG_TYPE "loop-utils"
38
Tyler Nowicki0a913102015-06-16 18:07:34 +000039bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
40 SmallPtrSetImpl<Instruction *> &Set) {
Karthik Bhat76aa6622015-04-20 04:38:33 +000041 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
42 if (!Set.count(dyn_cast<Instruction>(*Use)))
43 return false;
44 return true;
45}
46
Chad Rosierc94f8e22015-08-27 14:12:17 +000047bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) {
48 switch (Kind) {
49 default:
50 break;
51 case RK_IntegerAdd:
52 case RK_IntegerMult:
53 case RK_IntegerOr:
54 case RK_IntegerAnd:
55 case RK_IntegerXor:
56 case RK_IntegerMinMax:
57 return true;
58 }
59 return false;
60}
61
62bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) {
63 return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
64}
65
66bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) {
67 switch (Kind) {
68 default:
69 break;
70 case RK_IntegerAdd:
71 case RK_IntegerMult:
72 case RK_FloatAdd:
73 case RK_FloatMult:
74 return true;
75 }
76 return false;
77}
78
79Instruction *
80RecurrenceDescriptor::lookThroughAnd(PHINode *Phi, Type *&RT,
81 SmallPtrSetImpl<Instruction *> &Visited,
82 SmallPtrSetImpl<Instruction *> &CI) {
83 if (!Phi->hasOneUse())
84 return Phi;
85
86 const APInt *M = nullptr;
87 Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
88
89 // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
90 // with a new integer type of the corresponding bit width.
Craig Topper72ee6942017-06-24 06:24:01 +000091 if (match(J, m_c_And(m_Instruction(I), m_APInt(M)))) {
Chad Rosierc94f8e22015-08-27 14:12:17 +000092 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.
Michael Kuperstein7cefb402017-01-18 19:02:52 +0000233 // - By instructions outside of the loop (safe).
234 // * One value may have several outside users, but all outside
235 // uses must be of the same value.
Karthik Bhat76aa6622015-04-20 04:38:33 +0000236 // - By an instruction that is not part of the reduction (not safe).
237 // This is either:
238 // * An instruction type other than PHI or the reduction operation.
239 // * A PHI in the header other than the initial PHI.
240 while (!Worklist.empty()) {
241 Instruction *Cur = Worklist.back();
242 Worklist.pop_back();
243
244 // No Users.
245 // If the instruction has no users then this is a broken chain and can't be
246 // a reduction variable.
247 if (Cur->use_empty())
248 return false;
249
250 bool IsAPhi = isa<PHINode>(Cur);
251
252 // A header PHI use other than the original PHI.
253 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
254 return false;
255
256 // Reductions of instructions such as Div, and Sub is only possible if the
257 // LHS is the reduction variable.
258 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
259 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
260 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
261 return false;
262
Chad Rosierc94f8e22015-08-27 14:12:17 +0000263 // Any reduction instruction must be of one of the allowed kinds. We ignore
264 // the starting value (the Phi or an AND instruction if the Phi has been
265 // type-promoted).
266 if (Cur != Start) {
267 ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
268 if (!ReduxDesc.isRecurrence())
269 return false;
270 }
Karthik Bhat76aa6622015-04-20 04:38:33 +0000271
272 // A reduction operation must only have one use of the reduction value.
273 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
274 hasMultipleUsesOf(Cur, VisitedInsts))
275 return false;
276
277 // All inputs to a PHI node must be a reduction value.
278 if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
279 return false;
280
281 if (Kind == RK_IntegerMinMax &&
282 (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
283 ++NumCmpSelectPatternInst;
284 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
285 ++NumCmpSelectPatternInst;
286
287 // Check whether we found a reduction operator.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000288 FoundReduxOp |= !IsAPhi && Cur != Start;
Karthik Bhat76aa6622015-04-20 04:38:33 +0000289
290 // Process users of current instruction. Push non-PHI nodes after PHI nodes
291 // onto the stack. This way we are going to have seen all inputs to PHI
292 // nodes once we get to them.
293 SmallVector<Instruction *, 8> NonPHIs;
294 SmallVector<Instruction *, 8> PHIs;
295 for (User *U : Cur->users()) {
296 Instruction *UI = cast<Instruction>(U);
297
298 // Check if we found the exit user.
299 BasicBlock *Parent = UI->getParent();
300 if (!TheLoop->contains(Parent)) {
Michael Kuperstein7cefb402017-01-18 19:02:52 +0000301 // If we already know this instruction is used externally, move on to
302 // the next user.
303 if (ExitInstruction == Cur)
304 continue;
305
306 // Exit if you find multiple values used outside or if the header phi
307 // node is being used. In this case the user uses the value of the
308 // previous iteration, in which case we would loose "VF-1" iterations of
309 // the reduction operation if we vectorize.
Karthik Bhat76aa6622015-04-20 04:38:33 +0000310 if (ExitInstruction != nullptr || Cur == Phi)
311 return false;
312
313 // The instruction used by an outside user must be the last instruction
314 // before we feed back to the reduction phi. Otherwise, we loose VF-1
315 // operations on the value.
David Majnemer42531262016-08-12 03:55:06 +0000316 if (!is_contained(Phi->operands(), Cur))
Karthik Bhat76aa6622015-04-20 04:38:33 +0000317 return false;
318
319 ExitInstruction = Cur;
320 continue;
321 }
322
323 // Process instructions only once (termination). Each reduction cycle
324 // value must only be used once, except by phi nodes and min/max
325 // reductions which are represented as a cmp followed by a select.
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000326 InstDesc IgnoredVal(false, nullptr);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000327 if (VisitedInsts.insert(UI).second) {
328 if (isa<PHINode>(UI))
329 PHIs.push_back(UI);
330 else
331 NonPHIs.push_back(UI);
332 } else if (!isa<PHINode>(UI) &&
333 ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
334 !isa<SelectInst>(UI)) ||
Tyler Nowicki0a913102015-06-16 18:07:34 +0000335 !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence()))
Karthik Bhat76aa6622015-04-20 04:38:33 +0000336 return false;
337
338 // Remember that we completed the cycle.
339 if (UI == Phi)
340 FoundStartPHI = true;
341 }
342 Worklist.append(PHIs.begin(), PHIs.end());
343 Worklist.append(NonPHIs.begin(), NonPHIs.end());
344 }
345
346 // This means we have seen one but not the other instruction of the
347 // pattern or more than just a select and cmp.
348 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
349 NumCmpSelectPatternInst != 2)
350 return false;
351
352 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
353 return false;
354
Chad Rosierc94f8e22015-08-27 14:12:17 +0000355 // If we think Phi may have been type-promoted, we also need to ensure that
356 // all source operands of the reduction are either SExtInsts or ZEstInsts. If
357 // so, we will be able to evaluate the reduction in the narrower bit width.
358 if (Start != Phi)
359 if (!getSourceExtensionKind(Start, ExitInstruction, RecurrenceType,
360 IsSigned, VisitedInsts, CastInsts))
361 return false;
362
Karthik Bhat76aa6622015-04-20 04:38:33 +0000363 // We found a reduction var if we have reached the original phi node and we
364 // only have a single instruction with out-of-loop users.
365
366 // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
Tyler Nowicki0a913102015-06-16 18:07:34 +0000367 // is saved as part of the RecurrenceDescriptor.
Karthik Bhat76aa6622015-04-20 04:38:33 +0000368
369 // Save the description of this reduction variable.
Chad Rosierc94f8e22015-08-27 14:12:17 +0000370 RecurrenceDescriptor RD(
371 RdxStart, ExitInstruction, Kind, ReduxDesc.getMinMaxKind(),
372 ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000373 RedDes = RD;
374
375 return true;
376}
377
378/// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
379/// pattern corresponding to a min(X, Y) or max(X, Y).
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000380RecurrenceDescriptor::InstDesc
381RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000382
383 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
384 "Expect a select instruction");
385 Instruction *Cmp = nullptr;
386 SelectInst *Select = nullptr;
387
388 // We must handle the select(cmp()) as a single instruction. Advance to the
389 // select.
390 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
391 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000392 return InstDesc(false, I);
393 return InstDesc(Select, Prev.getMinMaxKind());
Karthik Bhat76aa6622015-04-20 04:38:33 +0000394 }
395
396 // Only handle single use cases for now.
397 if (!(Select = dyn_cast<SelectInst>(I)))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000398 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000399 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
400 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000401 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000402 if (!Cmp->hasOneUse())
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000403 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000404
405 Value *CmpLeft;
406 Value *CmpRight;
407
408 // Look for a min/max pattern.
409 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000410 return InstDesc(Select, MRK_UIntMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000411 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000412 return InstDesc(Select, MRK_UIntMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000413 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000414 return InstDesc(Select, MRK_SIntMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000415 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000416 return InstDesc(Select, MRK_SIntMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000417 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000418 return InstDesc(Select, MRK_FloatMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000419 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000420 return InstDesc(Select, MRK_FloatMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000421 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000422 return InstDesc(Select, MRK_FloatMin);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000423 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000424 return InstDesc(Select, MRK_FloatMax);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000425
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000426 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000427}
428
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000429RecurrenceDescriptor::InstDesc
Tyler Nowicki0a913102015-06-16 18:07:34 +0000430RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000431 InstDesc &Prev, bool HasFunNoNaNAttr) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000432 bool FP = I->getType()->isFloatingPointTy();
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000433 Instruction *UAI = Prev.getUnsafeAlgebraInst();
434 if (!UAI && FP && !I->hasUnsafeAlgebra())
435 UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
436
Karthik Bhat76aa6622015-04-20 04:38:33 +0000437 switch (I->getOpcode()) {
438 default:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000439 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000440 case Instruction::PHI:
Tim Northover10a1e8b2016-05-27 16:40:27 +0000441 return InstDesc(I, Prev.getMinMaxKind(), Prev.getUnsafeAlgebraInst());
Karthik Bhat76aa6622015-04-20 04:38:33 +0000442 case Instruction::Sub:
443 case Instruction::Add:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000444 return InstDesc(Kind == RK_IntegerAdd, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000445 case Instruction::Mul:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000446 return InstDesc(Kind == RK_IntegerMult, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000447 case Instruction::And:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000448 return InstDesc(Kind == RK_IntegerAnd, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000449 case Instruction::Or:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000450 return InstDesc(Kind == RK_IntegerOr, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000451 case Instruction::Xor:
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000452 return InstDesc(Kind == RK_IntegerXor, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000453 case Instruction::FMul:
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000454 return InstDesc(Kind == RK_FloatMult, I, UAI);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000455 case Instruction::FSub:
456 case Instruction::FAdd:
Tyler Nowickic1a86f52015-08-10 19:51:46 +0000457 return InstDesc(Kind == RK_FloatAdd, I, UAI);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000458 case Instruction::FCmp:
459 case Instruction::ICmp:
460 case Instruction::Select:
461 if (Kind != RK_IntegerMinMax &&
462 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000463 return InstDesc(false, I);
Karthik Bhat76aa6622015-04-20 04:38:33 +0000464 return isMinMaxSelectCmpPattern(I, Prev);
465 }
466}
467
Tyler Nowicki0a913102015-06-16 18:07:34 +0000468bool RecurrenceDescriptor::hasMultipleUsesOf(
Karthik Bhat76aa6622015-04-20 04:38:33 +0000469 Instruction *I, SmallPtrSetImpl<Instruction *> &Insts) {
470 unsigned NumUses = 0;
471 for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
472 ++Use) {
473 if (Insts.count(dyn_cast<Instruction>(*Use)))
474 ++NumUses;
475 if (NumUses > 1)
476 return true;
477 }
478
479 return false;
480}
Tyler Nowicki0a913102015-06-16 18:07:34 +0000481bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
482 RecurrenceDescriptor &RedDes) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000483
Karthik Bhat76aa6622015-04-20 04:38:33 +0000484 BasicBlock *Header = TheLoop->getHeader();
485 Function &F = *Header->getParent();
Nirav Dave8dd66e52016-03-30 15:41:12 +0000486 bool HasFunNoNaNAttr =
487 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
Karthik Bhat76aa6622015-04-20 04:38:33 +0000488
489 if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
490 DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
491 return true;
492 }
493 if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
494 DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
495 return true;
496 }
497 if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes)) {
498 DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
499 return true;
500 }
501 if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes)) {
502 DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
503 return true;
504 }
505 if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes)) {
506 DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
507 return true;
508 }
509 if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr,
510 RedDes)) {
511 DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
512 return true;
513 }
514 if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
515 DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
516 return true;
517 }
518 if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
519 DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
520 return true;
521 }
522 if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes)) {
523 DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi << "\n");
524 return true;
525 }
526 // Not a reduction of known type.
527 return false;
528}
529
Matthew Simpson29c997c2016-02-19 17:56:08 +0000530bool RecurrenceDescriptor::isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop,
531 DominatorTree *DT) {
532
533 // Ensure the phi node is in the loop header and has two incoming values.
534 if (Phi->getParent() != TheLoop->getHeader() ||
535 Phi->getNumIncomingValues() != 2)
536 return false;
537
538 // Ensure the loop has a preheader and a single latch block. The loop
539 // vectorizer will need the latch to set up the next iteration of the loop.
540 auto *Preheader = TheLoop->getLoopPreheader();
541 auto *Latch = TheLoop->getLoopLatch();
542 if (!Preheader || !Latch)
543 return false;
544
545 // Ensure the phi node's incoming blocks are the loop preheader and latch.
546 if (Phi->getBasicBlockIndex(Preheader) < 0 ||
547 Phi->getBasicBlockIndex(Latch) < 0)
548 return false;
549
550 // Get the previous value. The previous value comes from the latch edge while
551 // the initial value comes form the preheader edge.
552 auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
Matthew Simpson53207a92016-04-11 19:48:18 +0000553 if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous))
Matthew Simpson29c997c2016-02-19 17:56:08 +0000554 return false;
555
Anna Thomasdcdb3252017-04-13 18:59:25 +0000556 // Ensure every user of the phi node is dominated by the previous value.
557 // The dominance requirement ensures the loop vectorizer will not need to
558 // vectorize the initial value prior to the first iteration of the loop.
Matthew Simpson29c997c2016-02-19 17:56:08 +0000559 for (User *U : Phi->users())
Anna Thomas00dc1b72017-04-11 21:02:00 +0000560 if (auto *I = dyn_cast<Instruction>(U)) {
Matthew Simpson29c997c2016-02-19 17:56:08 +0000561 if (!DT->dominates(Previous, I))
562 return false;
Anna Thomas00dc1b72017-04-11 21:02:00 +0000563 }
Matthew Simpson29c997c2016-02-19 17:56:08 +0000564
565 return true;
566}
567
Karthik Bhat76aa6622015-04-20 04:38:33 +0000568/// This function returns the identity element (or neutral element) for
569/// the operation K.
Tyler Nowicki0a913102015-06-16 18:07:34 +0000570Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K,
571 Type *Tp) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000572 switch (K) {
573 case RK_IntegerXor:
574 case RK_IntegerAdd:
575 case RK_IntegerOr:
576 // Adding, Xoring, Oring zero to a number does not change it.
577 return ConstantInt::get(Tp, 0);
578 case RK_IntegerMult:
579 // Multiplying a number by 1 does not change it.
580 return ConstantInt::get(Tp, 1);
581 case RK_IntegerAnd:
582 // AND-ing a number with an all-1 value does not change it.
583 return ConstantInt::get(Tp, -1, true);
584 case RK_FloatMult:
585 // Multiplying a number by 1 does not change it.
586 return ConstantFP::get(Tp, 1.0L);
587 case RK_FloatAdd:
588 // Adding zero to a number does not change it.
589 return ConstantFP::get(Tp, 0.0L);
590 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000591 llvm_unreachable("Unknown recurrence kind");
Karthik Bhat76aa6622015-04-20 04:38:33 +0000592 }
593}
594
Tyler Nowicki0a913102015-06-16 18:07:34 +0000595/// This function translates the recurrence kind to an LLVM binary operator.
596unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000597 switch (Kind) {
598 case RK_IntegerAdd:
599 return Instruction::Add;
600 case RK_IntegerMult:
601 return Instruction::Mul;
602 case RK_IntegerOr:
603 return Instruction::Or;
604 case RK_IntegerAnd:
605 return Instruction::And;
606 case RK_IntegerXor:
607 return Instruction::Xor;
608 case RK_FloatMult:
609 return Instruction::FMul;
610 case RK_FloatAdd:
611 return Instruction::FAdd;
612 case RK_IntegerMinMax:
613 return Instruction::ICmp;
614 case RK_FloatMinMax:
615 return Instruction::FCmp;
616 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000617 llvm_unreachable("Unknown recurrence operation");
Karthik Bhat76aa6622015-04-20 04:38:33 +0000618 }
619}
620
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000621Value *RecurrenceDescriptor::createMinMaxOp(IRBuilder<> &Builder,
622 MinMaxRecurrenceKind RK,
623 Value *Left, Value *Right) {
Karthik Bhat76aa6622015-04-20 04:38:33 +0000624 CmpInst::Predicate P = CmpInst::ICMP_NE;
625 switch (RK) {
626 default:
Tyler Nowicki0a913102015-06-16 18:07:34 +0000627 llvm_unreachable("Unknown min/max recurrence kind");
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000628 case MRK_UIntMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000629 P = CmpInst::ICMP_ULT;
630 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000631 case MRK_UIntMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000632 P = CmpInst::ICMP_UGT;
633 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000634 case MRK_SIntMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000635 P = CmpInst::ICMP_SLT;
636 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000637 case MRK_SIntMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000638 P = CmpInst::ICMP_SGT;
639 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000640 case MRK_FloatMin:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000641 P = CmpInst::FCMP_OLT;
642 break;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000643 case MRK_FloatMax:
Karthik Bhat76aa6622015-04-20 04:38:33 +0000644 P = CmpInst::FCMP_OGT;
645 break;
646 }
647
James Molloy50a4c272015-09-21 19:41:19 +0000648 // We only match FP sequences with unsafe algebra, so we can unconditionally
649 // set it on any generated instructions.
650 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
651 FastMathFlags FMF;
652 FMF.setUnsafeAlgebra();
Sanjay Patela2528152016-01-12 18:03:37 +0000653 Builder.setFastMathFlags(FMF);
James Molloy50a4c272015-09-21 19:41:19 +0000654
Karthik Bhat76aa6622015-04-20 04:38:33 +0000655 Value *Cmp;
Tyler Nowicki27b2c392015-06-16 22:59:45 +0000656 if (RK == MRK_FloatMin || RK == MRK_FloatMax)
Karthik Bhat76aa6622015-04-20 04:38:33 +0000657 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
658 else
659 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
660
661 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
662 return Select;
663}
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000664
James Molloy1bbf15c2015-08-27 09:53:00 +0000665InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000666 const SCEV *Step, BinaryOperator *BOp)
667 : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
James Molloy1bbf15c2015-08-27 09:53:00 +0000668 assert(IK != IK_NoInduction && "Not an induction");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000669
670 // Start value type should match the induction kind and the value
671 // itself should not be null.
James Molloy1bbf15c2015-08-27 09:53:00 +0000672 assert(StartValue && "StartValue is null");
James Molloy1bbf15c2015-08-27 09:53:00 +0000673 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
674 "StartValue is not a pointer for pointer induction");
675 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
676 "StartValue is not an integer for integer induction");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000677
678 // Check the Step Value. It should be non-zero integer value.
679 assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
680 "Step value is zero");
681
682 assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
683 "Step value should be constant for pointer induction");
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000684 assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
685 "StepValue is not an integer");
686
687 assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
688 "StepValue is not FP for FpInduction");
689 assert((IK != IK_FpInduction || (InductionBinOp &&
690 (InductionBinOp->getOpcode() == Instruction::FAdd ||
691 InductionBinOp->getOpcode() == Instruction::FSub))) &&
692 "Binary opcode should be specified for FP induction");
James Molloy1bbf15c2015-08-27 09:53:00 +0000693}
694
695int InductionDescriptor::getConsecutiveDirection() const {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000696 ConstantInt *ConstStep = getConstIntStepValue();
697 if (ConstStep && (ConstStep->isOne() || ConstStep->isMinusOne()))
698 return ConstStep->getSExtValue();
James Molloy1bbf15c2015-08-27 09:53:00 +0000699 return 0;
700}
701
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000702ConstantInt *InductionDescriptor::getConstIntStepValue() const {
703 if (isa<SCEVConstant>(Step))
704 return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
705 return nullptr;
706}
707
708Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index,
709 ScalarEvolution *SE,
710 const DataLayout& DL) const {
711
712 SCEVExpander Exp(*SE, DL, "induction");
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000713 assert(Index->getType() == Step->getType() &&
714 "Index type does not match StepValue type");
James Molloy1bbf15c2015-08-27 09:53:00 +0000715 switch (IK) {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000716 case IK_IntInduction: {
James Molloy1bbf15c2015-08-27 09:53:00 +0000717 assert(Index->getType() == StartValue->getType() &&
718 "Index type does not match StartValue type");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000719
720 // FIXME: Theoretically, we can call getAddExpr() of ScalarEvolution
721 // and calculate (Start + Index * Step) for all cases, without
722 // special handling for "isOne" and "isMinusOne".
723 // But in the real life the result code getting worse. We mix SCEV
724 // expressions and ADD/SUB operations and receive redundant
725 // intermediate values being calculated in different ways and
726 // Instcombine is unable to reduce them all.
727
728 if (getConstIntStepValue() &&
729 getConstIntStepValue()->isMinusOne())
James Molloy1bbf15c2015-08-27 09:53:00 +0000730 return B.CreateSub(StartValue, Index);
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000731 if (getConstIntStepValue() &&
732 getConstIntStepValue()->isOne())
733 return B.CreateAdd(StartValue, Index);
734 const SCEV *S = SE->getAddExpr(SE->getSCEV(StartValue),
735 SE->getMulExpr(Step, SE->getSCEV(Index)));
736 return Exp.expandCodeFor(S, StartValue->getType(), &*B.GetInsertPoint());
737 }
738 case IK_PtrInduction: {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000739 assert(isa<SCEVConstant>(Step) &&
740 "Expected constant step for pointer induction");
741 const SCEV *S = SE->getMulExpr(SE->getSCEV(Index), Step);
742 Index = Exp.expandCodeFor(S, Index->getType(), &*B.GetInsertPoint());
James Molloy1bbf15c2015-08-27 09:53:00 +0000743 return B.CreateGEP(nullptr, StartValue, Index);
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000744 }
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000745 case IK_FpInduction: {
746 assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
747 assert(InductionBinOp &&
748 (InductionBinOp->getOpcode() == Instruction::FAdd ||
749 InductionBinOp->getOpcode() == Instruction::FSub) &&
750 "Original bin op should be defined for FP induction");
751
752 Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
753
754 // Floating point operations had to be 'fast' to enable the induction.
755 FastMathFlags Flags;
756 Flags.setUnsafeAlgebra();
757
758 Value *MulExp = B.CreateFMul(StepValue, Index);
759 if (isa<Instruction>(MulExp))
760 // We have to check, the MulExp may be a constant.
761 cast<Instruction>(MulExp)->setFastMathFlags(Flags);
762
763 Value *BOp = B.CreateBinOp(InductionBinOp->getOpcode() , StartValue,
764 MulExp, "induction");
765 if (isa<Instruction>(BOp))
766 cast<Instruction>(BOp)->setFastMathFlags(Flags);
767
768 return BOp;
769 }
James Molloy1bbf15c2015-08-27 09:53:00 +0000770 case IK_NoInduction:
771 return nullptr;
772 }
773 llvm_unreachable("invalid enum");
774}
775
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000776bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop,
777 ScalarEvolution *SE,
778 InductionDescriptor &D) {
779
780 // Here we only handle FP induction variables.
781 assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
782
783 if (TheLoop->getHeader() != Phi->getParent())
784 return false;
785
786 // The loop may have multiple entrances or multiple exits; we can analyze
787 // this phi if it has a unique entry value and a unique backedge value.
788 if (Phi->getNumIncomingValues() != 2)
789 return false;
790 Value *BEValue = nullptr, *StartValue = nullptr;
791 if (TheLoop->contains(Phi->getIncomingBlock(0))) {
792 BEValue = Phi->getIncomingValue(0);
793 StartValue = Phi->getIncomingValue(1);
794 } else {
795 assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
796 "Unexpected Phi node in the loop");
797 BEValue = Phi->getIncomingValue(1);
798 StartValue = Phi->getIncomingValue(0);
799 }
800
801 BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue);
802 if (!BOp)
803 return false;
804
805 Value *Addend = nullptr;
806 if (BOp->getOpcode() == Instruction::FAdd) {
807 if (BOp->getOperand(0) == Phi)
808 Addend = BOp->getOperand(1);
809 else if (BOp->getOperand(1) == Phi)
810 Addend = BOp->getOperand(0);
811 } else if (BOp->getOpcode() == Instruction::FSub)
812 if (BOp->getOperand(0) == Phi)
813 Addend = BOp->getOperand(1);
814
815 if (!Addend)
816 return false;
817
818 // The addend should be loop invariant
819 if (auto *I = dyn_cast<Instruction>(Addend))
820 if (TheLoop->contains(I))
821 return false;
822
823 // FP Step has unknown SCEV
824 const SCEV *Step = SE->getUnknown(Addend);
825 D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
826 return true;
827}
828
829bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
Silviu Barangac05bab82016-05-05 15:20:39 +0000830 PredicatedScalarEvolution &PSE,
831 InductionDescriptor &D,
832 bool Assume) {
833 Type *PhiTy = Phi->getType();
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000834
835 // Handle integer and pointer inductions variables.
836 // Now we handle also FP induction but not trying to make a
837 // recurrent expression from the PHI node in-place.
838
839 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() &&
840 !PhiTy->isFloatTy() && !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
Silviu Barangac05bab82016-05-05 15:20:39 +0000841 return false;
842
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000843 if (PhiTy->isFloatingPointTy())
844 return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
845
Silviu Barangac05bab82016-05-05 15:20:39 +0000846 const SCEV *PhiScev = PSE.getSCEV(Phi);
847 const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
848
849 // We need this expression to be an AddRecExpr.
850 if (Assume && !AR)
851 AR = PSE.getAsAddRec(Phi);
852
853 if (!AR) {
854 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
855 return false;
856 }
857
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000858 return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
Silviu Barangac05bab82016-05-05 15:20:39 +0000859}
860
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000861bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
Silviu Barangac05bab82016-05-05 15:20:39 +0000862 ScalarEvolution *SE,
863 InductionDescriptor &D,
864 const SCEV *Expr) {
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000865 Type *PhiTy = Phi->getType();
866 // We only handle integer and pointer inductions variables.
867 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
868 return false;
869
870 // Check that the PHI is consecutive.
Silviu Barangac05bab82016-05-05 15:20:39 +0000871 const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000872 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
Silviu Barangac05bab82016-05-05 15:20:39 +0000873
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000874 if (!AR) {
875 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
876 return false;
877 }
878
Michael Kupersteinee31cbe2017-01-10 19:32:30 +0000879 if (AR->getLoop() != TheLoop) {
880 // FIXME: We should treat this as a uniform. Unfortunately, we
881 // don't currently know how to handled uniform PHIs.
882 DEBUG(dbgs() << "LV: PHI is a recurrence with respect to an outer loop.\n");
883 return false;
884 }
885
James Molloy1bbf15c2015-08-27 09:53:00 +0000886 Value *StartValue =
887 Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000888 const SCEV *Step = AR->getStepRecurrence(*SE);
889 // Calculate the pointer stride and check if it is consecutive.
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000890 // The stride may be a constant or a loop invariant integer value.
891 const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
Elena Demikhovsky376a18b2016-07-24 07:24:54 +0000892 if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop))
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000893 return false;
894
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000895 if (PhiTy->isIntegerTy()) {
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000896 D = InductionDescriptor(StartValue, IK_IntInduction, Step);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000897 return true;
898 }
899
900 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000901 // Pointer induction should be a constant.
902 if (!ConstStep)
903 return false;
904
905 ConstantInt *CV = ConstStep->getValue();
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000906 Type *PointerElementType = PhiTy->getPointerElementType();
907 // The pointer stride cannot be determined if the pointer element type is not
908 // sized.
909 if (!PointerElementType->isSized())
910 return false;
911
912 const DataLayout &DL = Phi->getModule()->getDataLayout();
913 int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
David Majnemerb58f32f2015-06-05 10:52:40 +0000914 if (!Size)
915 return false;
916
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000917 int64_t CVSize = CV->getSExtValue();
918 if (CVSize % Size)
919 return false;
Elena Demikhovskyc434d092016-05-10 07:33:35 +0000920 auto *StepValue = SE->getConstant(CV->getType(), CVSize / Size,
921 true /* signed */);
James Molloy1bbf15c2015-08-27 09:53:00 +0000922 D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue);
Karthik Bhat24e6cc22015-04-23 08:29:20 +0000923 return true;
924}
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000925
Chandler Carruth4ab0f492017-06-23 04:03:04 +0000926bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
927 bool PreserveLCSSA) {
928 bool Changed = false;
929
930 // We re-use a vector for the in-loop predecesosrs.
931 SmallVector<BasicBlock *, 4> InLoopPredecessors;
932
933 auto RewriteExit = [&](BasicBlock *BB) {
934 // See if there are any non-loop predecessors of this exit block and
935 // keep track of the in-loop predecessors.
936 bool IsDedicatedExit = true;
937 for (auto *PredBB : predecessors(BB))
938 if (L->contains(PredBB)) {
939 if (isa<IndirectBrInst>(PredBB->getTerminator()))
940 // We cannot rewrite exiting edges from an indirectbr.
941 return false;
942
943 InLoopPredecessors.push_back(PredBB);
944 } else {
945 IsDedicatedExit = false;
946 }
947
948 // Nothing to do if this is already a dedicated exit.
949 if (IsDedicatedExit) {
950 InLoopPredecessors.clear();
951 return false;
952 }
953
954 assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
955 auto *NewExitBB = SplitBlockPredecessors(
956 BB, InLoopPredecessors, ".loopexit", DT, LI, PreserveLCSSA);
957
958 if (!NewExitBB)
959 DEBUG(dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
960 << *L << "\n");
961 else
962 DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
963 << NewExitBB->getName() << "\n");
964 InLoopPredecessors.clear();
965 return true;
966 };
967
968 // Walk the exit blocks directly rather than building up a data structure for
969 // them, but only visit each one once.
970 SmallPtrSet<BasicBlock *, 4> Visited;
971 for (auto *BB : L->blocks())
972 for (auto *SuccBB : successors(BB)) {
973 // We're looking for exit blocks so skip in-loop successors.
974 if (L->contains(SuccBB))
975 continue;
976
977 // Visit each exit block exactly once.
978 if (!Visited.insert(SuccBB).second)
979 continue;
980
981 Changed |= RewriteExit(SuccBB);
982 }
983
984 return Changed;
985}
986
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000987/// \brief Returns the instructions that use values defined in the loop.
988SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
989 SmallVector<Instruction *, 8> UsedOutside;
990
991 for (auto *Block : L->getBlocks())
992 // FIXME: I believe that this could use copy_if if the Inst reference could
993 // be adapted into a pointer.
994 for (auto &Inst : *Block) {
995 auto Users = Inst.users();
David Majnemer0a16c222016-08-11 21:15:00 +0000996 if (any_of(Users, [&](User *U) {
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000997 auto *Use = cast<Instruction>(U);
998 return !L->contains(Use->getParent());
999 }))
1000 UsedOutside.push_back(&Inst);
1001 }
1002
1003 return UsedOutside;
1004}
Chandler Carruth31088a92016-02-19 10:45:18 +00001005
1006void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
1007 // By definition, all loop passes need the LoopInfo analysis and the
1008 // Dominator tree it depends on. Because they all participate in the loop
1009 // pass manager, they must also preserve these.
1010 AU.addRequired<DominatorTreeWrapperPass>();
1011 AU.addPreserved<DominatorTreeWrapperPass>();
1012 AU.addRequired<LoopInfoWrapperPass>();
1013 AU.addPreserved<LoopInfoWrapperPass>();
1014
1015 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
1016 // here because users shouldn't directly get them from this header.
1017 extern char &LoopSimplifyID;
1018 extern char &LCSSAID;
1019 AU.addRequiredID(LoopSimplifyID);
1020 AU.addPreservedID(LoopSimplifyID);
1021 AU.addRequiredID(LCSSAID);
1022 AU.addPreservedID(LCSSAID);
Igor Laevskyc3ccf5d2016-10-28 12:57:20 +00001023 // This is used in the LPPassManager to perform LCSSA verification on passes
1024 // which preserve lcssa form
1025 AU.addRequired<LCSSAVerificationPass>();
1026 AU.addPreserved<LCSSAVerificationPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +00001027
1028 // Loop passes are designed to run inside of a loop pass manager which means
1029 // that any function analyses they require must be required by the first loop
1030 // pass in the manager (so that it is computed before the loop pass manager
1031 // runs) and preserved by all loop pasess in the manager. To make this
1032 // reasonably robust, the set needed for most loop passes is maintained here.
1033 // If your loop pass requires an analysis not listed here, you will need to
1034 // carefully audit the loop pass manager nesting structure that results.
1035 AU.addRequired<AAResultsWrapperPass>();
1036 AU.addPreserved<AAResultsWrapperPass>();
1037 AU.addPreserved<BasicAAWrapperPass>();
1038 AU.addPreserved<GlobalsAAWrapperPass>();
1039 AU.addPreserved<SCEVAAWrapperPass>();
1040 AU.addRequired<ScalarEvolutionWrapperPass>();
1041 AU.addPreserved<ScalarEvolutionWrapperPass>();
1042}
1043
1044/// Manually defined generic "LoopPass" dependency initialization. This is used
1045/// to initialize the exact set of passes from above in \c
1046/// getLoopAnalysisUsage. It can be used within a loop pass's initialization
1047/// with:
1048///
1049/// INITIALIZE_PASS_DEPENDENCY(LoopPass)
1050///
1051/// As-if "LoopPass" were a pass.
1052void llvm::initializeLoopPassPass(PassRegistry &Registry) {
1053 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1054 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1055 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Easwaran Ramane12c4872016-06-09 19:44:46 +00001056 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +00001057 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1058 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
1059 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
1060 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
1061 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
1062}
Adam Nemet963341c2016-04-21 17:33:17 +00001063
Adam Nemetfe3def72016-04-22 19:10:05 +00001064/// \brief Find string metadata for loop
1065///
1066/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
1067/// operand or null otherwise. If the string metadata is not found return
1068/// Optional's not-a-value.
1069Optional<const MDOperand *> llvm::findStringMetadataForLoop(Loop *TheLoop,
1070 StringRef Name) {
Adam Nemet963341c2016-04-21 17:33:17 +00001071 MDNode *LoopID = TheLoop->getLoopID();
Adam Nemetfe3def72016-04-22 19:10:05 +00001072 // Return none if LoopID is false.
Adam Nemet963341c2016-04-21 17:33:17 +00001073 if (!LoopID)
Adam Nemetfe3def72016-04-22 19:10:05 +00001074 return None;
Adam Nemet293be662016-04-21 17:33:20 +00001075
1076 // First operand should refer to the loop id itself.
1077 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1078 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1079
Adam Nemet963341c2016-04-21 17:33:17 +00001080 // Iterate over LoopID operands and look for MDString Metadata
1081 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
1082 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1083 if (!MD)
1084 continue;
1085 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1086 if (!S)
1087 continue;
1088 // Return true if MDString holds expected MetaData.
1089 if (Name.equals(S->getString()))
Adam Nemetfe3def72016-04-22 19:10:05 +00001090 switch (MD->getNumOperands()) {
1091 case 1:
1092 return nullptr;
1093 case 2:
1094 return &MD->getOperand(1);
1095 default:
1096 llvm_unreachable("loop metadata has 0 or 1 operand");
1097 }
Adam Nemet963341c2016-04-21 17:33:17 +00001098 }
Adam Nemetfe3def72016-04-22 19:10:05 +00001099 return None;
Adam Nemet963341c2016-04-21 17:33:17 +00001100}
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001101
1102/// Returns true if the instruction in a loop is guaranteed to execute at least
1103/// once.
1104bool llvm::isGuaranteedToExecute(const Instruction &Inst,
1105 const DominatorTree *DT, const Loop *CurLoop,
1106 const LoopSafetyInfo *SafetyInfo) {
1107 // We have to check to make sure that the instruction dominates all
Evgeniy Stepanov58ccc092017-04-24 18:25:07 +00001108 // of the exit blocks. If it doesn't, then there is a path out of the loop
1109 // which does not execute this instruction, so we can't hoist it.
1110
1111 // If the instruction is in the header block for the loop (which is very
1112 // common), it is always guaranteed to dominate the exit blocks. Since this
1113 // is a common case, and can save some work, check it now.
1114 if (Inst.getParent() == CurLoop->getHeader())
1115 // If there's a throw in the header block, we can't guarantee we'll reach
1116 // Inst.
1117 return !SafetyInfo->HeaderMayThrow;
1118
1119 // Somewhere in this loop there is an instruction which may throw and make us
1120 // exit the loop.
1121 if (SafetyInfo->MayThrow)
1122 return false;
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001123
1124 // Get the exit blocks for the current loop.
1125 SmallVector<BasicBlock *, 8> ExitBlocks;
1126 CurLoop->getExitBlocks(ExitBlocks);
1127
1128 // Verify that the block dominates each of the exit blocks of the loop.
1129 for (BasicBlock *ExitBlock : ExitBlocks)
1130 if (!DT->dominates(Inst.getParent(), ExitBlock))
1131 return false;
1132
1133 // As a degenerate case, if the loop is statically infinite then we haven't
1134 // proven anything since there are no exit blocks.
Evgeniy Stepanov58ccc092017-04-24 18:25:07 +00001135 if (ExitBlocks.empty())
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001136 return false;
1137
Eli Friedmanf1da33e2016-06-11 21:48:25 +00001138 // FIXME: In general, we have to prove that the loop isn't an infinite loop.
1139 // See http::llvm.org/PR24078 . (The "ExitBlocks.empty()" check above is
1140 // just a special case of this.)
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001141 return true;
1142}
Dehao Chen41d72a82016-11-17 01:17:02 +00001143
1144Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) {
1145 // Only support loops with a unique exiting block, and a latch.
1146 if (!L->getExitingBlock())
1147 return None;
1148
1149 // Get the branch weights for the the loop's backedge.
1150 BranchInst *LatchBR =
1151 dyn_cast<BranchInst>(L->getLoopLatch()->getTerminator());
1152 if (!LatchBR || LatchBR->getNumSuccessors() != 2)
1153 return None;
1154
1155 assert((LatchBR->getSuccessor(0) == L->getHeader() ||
1156 LatchBR->getSuccessor(1) == L->getHeader()) &&
1157 "At least one edge out of the latch must go to the header");
1158
1159 // To estimate the number of times the loop body was executed, we want to
1160 // know the number of times the backedge was taken, vs. the number of times
1161 // we exited the loop.
Dehao Chen41d72a82016-11-17 01:17:02 +00001162 uint64_t TrueVal, FalseVal;
Michael Kupersteinb151a642016-11-30 21:13:57 +00001163 if (!LatchBR->extractProfMetadata(TrueVal, FalseVal))
Dehao Chen41d72a82016-11-17 01:17:02 +00001164 return None;
1165
Michael Kupersteinb151a642016-11-30 21:13:57 +00001166 if (!TrueVal || !FalseVal)
1167 return 0;
Dehao Chen41d72a82016-11-17 01:17:02 +00001168
Michael Kupersteinb151a642016-11-30 21:13:57 +00001169 // Divide the count of the backedge by the count of the edge exiting the loop,
1170 // rounding to nearest.
Dehao Chen41d72a82016-11-17 01:17:02 +00001171 if (LatchBR->getSuccessor(0) == L->getHeader())
Michael Kupersteinb151a642016-11-30 21:13:57 +00001172 return (TrueVal + (FalseVal / 2)) / FalseVal;
Dehao Chen41d72a82016-11-17 01:17:02 +00001173 else
Michael Kupersteinb151a642016-11-30 21:13:57 +00001174 return (FalseVal + (TrueVal / 2)) / TrueVal;
Dehao Chen41d72a82016-11-17 01:17:02 +00001175}
Amara Emersoncf9daa32017-05-09 10:43:25 +00001176
1177/// \brief Adds a 'fast' flag to floating point operations.
1178static Value *addFastMathFlag(Value *V) {
1179 if (isa<FPMathOperator>(V)) {
1180 FastMathFlags Flags;
1181 Flags.setUnsafeAlgebra();
1182 cast<Instruction>(V)->setFastMathFlags(Flags);
1183 }
1184 return V;
1185}
1186
1187// Helper to generate a log2 shuffle reduction.
Amara Emerson836b0f42017-05-10 09:42:49 +00001188Value *
1189llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op,
1190 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
1191 ArrayRef<Value *> RedOps) {
Amara Emersoncf9daa32017-05-09 10:43:25 +00001192 unsigned VF = Src->getType()->getVectorNumElements();
1193 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1194 // and vector ops, reducing the set of values being computed by half each
1195 // round.
1196 assert(isPowerOf2_32(VF) &&
1197 "Reduction emission only supported for pow2 vectors!");
1198 Value *TmpVec = Src;
1199 SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
1200 for (unsigned i = VF; i != 1; i >>= 1) {
1201 // Move the upper half of the vector to the lower half.
1202 for (unsigned j = 0; j != i / 2; ++j)
1203 ShuffleMask[j] = Builder.getInt32(i / 2 + j);
1204
1205 // Fill the rest of the mask with undef.
1206 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
1207 UndefValue::get(Builder.getInt32Ty()));
1208
1209 Value *Shuf = Builder.CreateShuffleVector(
1210 TmpVec, UndefValue::get(TmpVec->getType()),
1211 ConstantVector::get(ShuffleMask), "rdx.shuf");
1212
1213 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
1214 // Floating point operations had to be 'fast' to enable the reduction.
1215 TmpVec = addFastMathFlag(Builder.CreateBinOp((Instruction::BinaryOps)Op,
1216 TmpVec, Shuf, "bin.rdx"));
1217 } else {
1218 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
1219 "Invalid min/max");
1220 TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind, TmpVec,
1221 Shuf);
1222 }
1223 if (!RedOps.empty())
1224 propagateIRFlags(TmpVec, RedOps);
1225 }
1226 // The result is in the first element of the vector.
1227 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1228}
1229
1230/// Create a simple vector reduction specified by an opcode and some
1231/// flags (if generating min/max reductions).
1232Value *llvm::createSimpleTargetReduction(
1233 IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode,
1234 Value *Src, TargetTransformInfo::ReductionFlags Flags,
1235 ArrayRef<Value *> RedOps) {
1236 assert(isa<VectorType>(Src->getType()) && "Type must be a vector");
1237
1238 Value *ScalarUdf = UndefValue::get(Src->getType()->getVectorElementType());
1239 std::function<Value*()> BuildFunc;
1240 using RD = RecurrenceDescriptor;
1241 RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
1242 // TODO: Support creating ordered reductions.
1243 FastMathFlags FMFUnsafe;
1244 FMFUnsafe.setUnsafeAlgebra();
1245
1246 switch (Opcode) {
1247 case Instruction::Add:
1248 BuildFunc = [&]() { return Builder.CreateAddReduce(Src); };
1249 break;
1250 case Instruction::Mul:
1251 BuildFunc = [&]() { return Builder.CreateMulReduce(Src); };
1252 break;
1253 case Instruction::And:
1254 BuildFunc = [&]() { return Builder.CreateAndReduce(Src); };
1255 break;
1256 case Instruction::Or:
1257 BuildFunc = [&]() { return Builder.CreateOrReduce(Src); };
1258 break;
1259 case Instruction::Xor:
1260 BuildFunc = [&]() { return Builder.CreateXorReduce(Src); };
1261 break;
1262 case Instruction::FAdd:
1263 BuildFunc = [&]() {
1264 auto Rdx = Builder.CreateFAddReduce(ScalarUdf, Src);
1265 cast<CallInst>(Rdx)->setFastMathFlags(FMFUnsafe);
1266 return Rdx;
1267 };
1268 break;
1269 case Instruction::FMul:
1270 BuildFunc = [&]() {
1271 auto Rdx = Builder.CreateFMulReduce(ScalarUdf, Src);
1272 cast<CallInst>(Rdx)->setFastMathFlags(FMFUnsafe);
1273 return Rdx;
1274 };
1275 break;
1276 case Instruction::ICmp:
1277 if (Flags.IsMaxOp) {
1278 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
1279 BuildFunc = [&]() {
1280 return Builder.CreateIntMaxReduce(Src, Flags.IsSigned);
1281 };
1282 } else {
1283 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
1284 BuildFunc = [&]() {
1285 return Builder.CreateIntMinReduce(Src, Flags.IsSigned);
1286 };
1287 }
1288 break;
1289 case Instruction::FCmp:
1290 if (Flags.IsMaxOp) {
1291 MinMaxKind = RD::MRK_FloatMax;
1292 BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); };
1293 } else {
1294 MinMaxKind = RD::MRK_FloatMin;
1295 BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); };
1296 }
1297 break;
1298 default:
1299 llvm_unreachable("Unhandled opcode");
1300 break;
1301 }
1302 if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags))
1303 return BuildFunc();
1304 return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps);
1305}
1306
1307/// Create a vector reduction using a given recurrence descriptor.
1308Value *llvm::createTargetReduction(IRBuilder<> &Builder,
1309 const TargetTransformInfo *TTI,
1310 RecurrenceDescriptor &Desc, Value *Src,
1311 bool NoNaN) {
1312 // TODO: Support in-order reductions based on the recurrence descriptor.
1313 RecurrenceDescriptor::RecurrenceKind RecKind = Desc.getRecurrenceKind();
1314 TargetTransformInfo::ReductionFlags Flags;
1315 Flags.NoNaN = NoNaN;
1316 auto getSimpleRdx = [&](unsigned Opc) {
1317 return createSimpleTargetReduction(Builder, TTI, Opc, Src, Flags);
1318 };
1319 switch (RecKind) {
1320 case RecurrenceDescriptor::RK_FloatAdd:
1321 return getSimpleRdx(Instruction::FAdd);
1322 case RecurrenceDescriptor::RK_FloatMult:
1323 return getSimpleRdx(Instruction::FMul);
1324 case RecurrenceDescriptor::RK_IntegerAdd:
1325 return getSimpleRdx(Instruction::Add);
1326 case RecurrenceDescriptor::RK_IntegerMult:
1327 return getSimpleRdx(Instruction::Mul);
1328 case RecurrenceDescriptor::RK_IntegerAnd:
1329 return getSimpleRdx(Instruction::And);
1330 case RecurrenceDescriptor::RK_IntegerOr:
1331 return getSimpleRdx(Instruction::Or);
1332 case RecurrenceDescriptor::RK_IntegerXor:
1333 return getSimpleRdx(Instruction::Xor);
1334 case RecurrenceDescriptor::RK_IntegerMinMax: {
1335 switch (Desc.getMinMaxRecurrenceKind()) {
1336 case RecurrenceDescriptor::MRK_SIntMax:
1337 Flags.IsSigned = true;
1338 Flags.IsMaxOp = true;
1339 break;
1340 case RecurrenceDescriptor::MRK_UIntMax:
1341 Flags.IsMaxOp = true;
1342 break;
1343 case RecurrenceDescriptor::MRK_SIntMin:
1344 Flags.IsSigned = true;
1345 break;
1346 case RecurrenceDescriptor::MRK_UIntMin:
1347 break;
1348 default:
1349 llvm_unreachable("Unhandled MRK");
1350 }
1351 return getSimpleRdx(Instruction::ICmp);
1352 }
1353 case RecurrenceDescriptor::RK_FloatMinMax: {
1354 Flags.IsMaxOp =
1355 Desc.getMinMaxRecurrenceKind() == RecurrenceDescriptor::MRK_FloatMax;
1356 return getSimpleRdx(Instruction::FCmp);
1357 }
1358 default:
1359 llvm_unreachable("Unhandled RecKind");
1360 }
1361}
1362
1363void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL) {
1364 if (auto *VecOp = dyn_cast<Instruction>(I)) {
1365 if (auto *I0 = dyn_cast<Instruction>(VL[0])) {
1366 // VecOVp is initialized to the 0th scalar, so start counting from index
1367 // '1'.
1368 VecOp->copyIRFlags(I0);
1369 for (int i = 1, e = VL.size(); i < e; ++i) {
1370 if (auto *Scalar = dyn_cast<Instruction>(VL[i]))
1371 VecOp->andIRFlags(Scalar);
1372 }
1373 }
1374 }
1375}