blob: c3a02685244591984e57c9ad420ca46ec35114de [file] [log] [blame]
Karthik Bhat76aa6622015-04-20 04:38:33 +00001//===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Karthik Bhat76aa6622015-04-20 04:38:33 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file defines common loop utility functions.
10//
11//===----------------------------------------------------------------------===//
12
Adam Nemet2f2bd8c2016-07-26 17:52:02 +000013#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruth4a000882017-06-25 22:45:31 +000014#include "llvm/ADT/ScopeExit.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000015#include "llvm/Analysis/AliasAnalysis.h"
16#include "llvm/Analysis/BasicAliasAnalysis.h"
Richard Trieu5f436fc2019-02-06 02:52:52 +000017#include "llvm/Analysis/DomTreeUpdater.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000018#include "llvm/Analysis/GlobalsModRef.h"
Philip Reamesa21d5f12018-03-15 21:04:28 +000019#include "llvm/Analysis/InstructionSimplify.h"
Adam Nemet2f2bd8c2016-07-26 17:52:02 +000020#include "llvm/Analysis/LoopInfo.h"
Igor Laevskyc3ccf5d2016-10-28 12:57:20 +000021#include "llvm/Analysis/LoopPass.h"
Alina Sbirlea97468e92019-02-21 21:13:34 +000022#include "llvm/Analysis/MemorySSAUpdater.h"
Philip Reames23aed5e2018-03-20 22:45:23 +000023#include "llvm/Analysis/MustExecute.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000024#include "llvm/Analysis/ScalarEvolution.h"
Adam Nemet2f2bd8c2016-07-26 17:52:02 +000025#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Elena Demikhovskyc434d092016-05-10 07:33:35 +000026#include "llvm/Analysis/ScalarEvolutionExpander.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000027#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000028#include "llvm/Analysis/TargetTransformInfo.h"
Chad Rosiera097bc62018-02-04 15:42:24 +000029#include "llvm/Analysis/ValueTracking.h"
Davide Italiano744c3c32018-12-12 23:32:35 +000030#include "llvm/IR/DIBuilder.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000031#include "llvm/IR/Dominators.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000032#include "llvm/IR/Instructions.h"
Davide Italiano744c3c32018-12-12 23:32:35 +000033#include "llvm/IR/IntrinsicInst.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000034#include "llvm/IR/Module.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000035#include "llvm/IR/PatternMatch.h"
36#include "llvm/IR/ValueHandle.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000037#include "llvm/Pass.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000038#include "llvm/Support/Debug.h"
Chad Rosiera097bc62018-02-04 15:42:24 +000039#include "llvm/Support/KnownBits.h"
Chandler Carruth4a000882017-06-25 22:45:31 +000040#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000041
42using namespace llvm;
43using namespace llvm::PatternMatch;
44
45#define DEBUG_TYPE "loop-utils"
46
Michael Kruse72448522018-12-12 17:32:52 +000047static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced";
48
Chandler Carruth4a000882017-06-25 22:45:31 +000049bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
Alina Sbirlea97468e92019-02-21 21:13:34 +000050 MemorySSAUpdater *MSSAU,
Chandler Carruth4a000882017-06-25 22:45:31 +000051 bool PreserveLCSSA) {
52 bool Changed = false;
53
54 // We re-use a vector for the in-loop predecesosrs.
55 SmallVector<BasicBlock *, 4> InLoopPredecessors;
56
57 auto RewriteExit = [&](BasicBlock *BB) {
58 assert(InLoopPredecessors.empty() &&
59 "Must start with an empty predecessors list!");
60 auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
61
62 // See if there are any non-loop predecessors of this exit block and
63 // keep track of the in-loop predecessors.
64 bool IsDedicatedExit = true;
65 for (auto *PredBB : predecessors(BB))
66 if (L->contains(PredBB)) {
67 if (isa<IndirectBrInst>(PredBB->getTerminator()))
68 // We cannot rewrite exiting edges from an indirectbr.
69 return false;
Craig Topper784929d2019-02-08 20:48:56 +000070 if (isa<CallBrInst>(PredBB->getTerminator()))
71 // We cannot rewrite exiting edges from a callbr.
72 return false;
Chandler Carruth4a000882017-06-25 22:45:31 +000073
74 InLoopPredecessors.push_back(PredBB);
75 } else {
76 IsDedicatedExit = false;
77 }
78
79 assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
80
81 // Nothing to do if this is already a dedicated exit.
82 if (IsDedicatedExit)
83 return false;
84
85 auto *NewExitBB = SplitBlockPredecessors(
Alina Sbirlea97468e92019-02-21 21:13:34 +000086 BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA);
Chandler Carruth4a000882017-06-25 22:45:31 +000087
88 if (!NewExitBB)
Nicola Zaghend34e60c2018-05-14 12:53:11 +000089 LLVM_DEBUG(
90 dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
91 << *L << "\n");
Chandler Carruth4a000882017-06-25 22:45:31 +000092 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +000093 LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
94 << NewExitBB->getName() << "\n");
Chandler Carruth4a000882017-06-25 22:45:31 +000095 return true;
96 };
97
98 // Walk the exit blocks directly rather than building up a data structure for
99 // them, but only visit each one once.
100 SmallPtrSet<BasicBlock *, 4> Visited;
101 for (auto *BB : L->blocks())
102 for (auto *SuccBB : successors(BB)) {
103 // We're looking for exit blocks so skip in-loop successors.
104 if (L->contains(SuccBB))
105 continue;
106
107 // Visit each exit block exactly once.
108 if (!Visited.insert(SuccBB).second)
109 continue;
110
111 Changed |= RewriteExit(SuccBB);
112 }
113
114 return Changed;
115}
116
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000117/// Returns the instructions that use values defined in the loop.
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000118SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
119 SmallVector<Instruction *, 8> UsedOutside;
120
121 for (auto *Block : L->getBlocks())
122 // FIXME: I believe that this could use copy_if if the Inst reference could
123 // be adapted into a pointer.
124 for (auto &Inst : *Block) {
125 auto Users = Inst.users();
David Majnemer0a16c222016-08-11 21:15:00 +0000126 if (any_of(Users, [&](User *U) {
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000127 auto *Use = cast<Instruction>(U);
128 return !L->contains(Use->getParent());
129 }))
130 UsedOutside.push_back(&Inst);
131 }
132
133 return UsedOutside;
134}
Chandler Carruth31088a92016-02-19 10:45:18 +0000135
136void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
137 // By definition, all loop passes need the LoopInfo analysis and the
138 // Dominator tree it depends on. Because they all participate in the loop
139 // pass manager, they must also preserve these.
140 AU.addRequired<DominatorTreeWrapperPass>();
141 AU.addPreserved<DominatorTreeWrapperPass>();
142 AU.addRequired<LoopInfoWrapperPass>();
143 AU.addPreserved<LoopInfoWrapperPass>();
144
145 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
146 // here because users shouldn't directly get them from this header.
147 extern char &LoopSimplifyID;
148 extern char &LCSSAID;
149 AU.addRequiredID(LoopSimplifyID);
150 AU.addPreservedID(LoopSimplifyID);
151 AU.addRequiredID(LCSSAID);
152 AU.addPreservedID(LCSSAID);
Igor Laevskyc3ccf5d2016-10-28 12:57:20 +0000153 // This is used in the LPPassManager to perform LCSSA verification on passes
154 // which preserve lcssa form
155 AU.addRequired<LCSSAVerificationPass>();
156 AU.addPreserved<LCSSAVerificationPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000157
158 // Loop passes are designed to run inside of a loop pass manager which means
159 // that any function analyses they require must be required by the first loop
160 // pass in the manager (so that it is computed before the loop pass manager
161 // runs) and preserved by all loop pasess in the manager. To make this
162 // reasonably robust, the set needed for most loop passes is maintained here.
163 // If your loop pass requires an analysis not listed here, you will need to
164 // carefully audit the loop pass manager nesting structure that results.
165 AU.addRequired<AAResultsWrapperPass>();
166 AU.addPreserved<AAResultsWrapperPass>();
167 AU.addPreserved<BasicAAWrapperPass>();
168 AU.addPreserved<GlobalsAAWrapperPass>();
169 AU.addPreserved<SCEVAAWrapperPass>();
170 AU.addRequired<ScalarEvolutionWrapperPass>();
171 AU.addPreserved<ScalarEvolutionWrapperPass>();
172}
173
174/// Manually defined generic "LoopPass" dependency initialization. This is used
175/// to initialize the exact set of passes from above in \c
176/// getLoopAnalysisUsage. It can be used within a loop pass's initialization
177/// with:
178///
179/// INITIALIZE_PASS_DEPENDENCY(LoopPass)
180///
181/// As-if "LoopPass" were a pass.
182void llvm::initializeLoopPassPass(PassRegistry &Registry) {
183 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
184 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
185 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Easwaran Ramane12c4872016-06-09 19:44:46 +0000186 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000187 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
188 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
189 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
190 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
191 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
192}
Adam Nemet963341c2016-04-21 17:33:17 +0000193
Michael Kruse72448522018-12-12 17:32:52 +0000194/// Find string metadata for loop
195///
196/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
197/// operand or null otherwise. If the string metadata is not found return
198/// Optional's not-a-value.
Michael Kruse978ba612018-12-20 04:58:07 +0000199Optional<const MDOperand *> llvm::findStringMetadataForLoop(const Loop *TheLoop,
Michael Kruse72448522018-12-12 17:32:52 +0000200 StringRef Name) {
Michael Kruse978ba612018-12-20 04:58:07 +0000201 MDNode *MD = findOptionMDForLoop(TheLoop, Name);
Michael Kruse72448522018-12-12 17:32:52 +0000202 if (!MD)
203 return None;
204 switch (MD->getNumOperands()) {
205 case 1:
206 return nullptr;
207 case 2:
208 return &MD->getOperand(1);
209 default:
210 llvm_unreachable("loop metadata has 0 or 1 operand");
211 }
212}
213
214static Optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop,
215 StringRef Name) {
Michael Kruse978ba612018-12-20 04:58:07 +0000216 MDNode *MD = findOptionMDForLoop(TheLoop, Name);
217 if (!MD)
Michael Kruse72448522018-12-12 17:32:52 +0000218 return None;
Michael Kruse978ba612018-12-20 04:58:07 +0000219 switch (MD->getNumOperands()) {
Michael Kruse72448522018-12-12 17:32:52 +0000220 case 1:
221 // When the value is absent it is interpreted as 'attribute set'.
222 return true;
223 case 2:
Alina Sbirleaf9027e52019-01-29 22:33:20 +0000224 if (ConstantInt *IntMD =
225 mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get()))
226 return IntMD->getZExtValue();
227 return true;
Michael Kruse72448522018-12-12 17:32:52 +0000228 }
229 llvm_unreachable("unexpected number of options");
230}
231
232static bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) {
233 return getOptionalBoolLoopAttribute(TheLoop, Name).getValueOr(false);
234}
235
236llvm::Optional<int> llvm::getOptionalIntLoopAttribute(Loop *TheLoop,
237 StringRef Name) {
238 const MDOperand *AttrMD =
239 findStringMetadataForLoop(TheLoop, Name).getValueOr(nullptr);
240 if (!AttrMD)
241 return None;
242
243 ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
244 if (!IntMD)
245 return None;
246
247 return IntMD->getSExtValue();
248}
249
250Optional<MDNode *> llvm::makeFollowupLoopID(
251 MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
252 const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
253 if (!OrigLoopID) {
254 if (AlwaysNew)
255 return nullptr;
256 return None;
257 }
258
259 assert(OrigLoopID->getOperand(0) == OrigLoopID);
260
261 bool InheritAllAttrs = !InheritOptionsExceptPrefix;
262 bool InheritSomeAttrs =
263 InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
264 SmallVector<Metadata *, 8> MDs;
265 MDs.push_back(nullptr);
266
267 bool Changed = false;
268 if (InheritAllAttrs || InheritSomeAttrs) {
269 for (const MDOperand &Existing : drop_begin(OrigLoopID->operands(), 1)) {
270 MDNode *Op = cast<MDNode>(Existing.get());
271
272 auto InheritThisAttribute = [InheritSomeAttrs,
273 InheritOptionsExceptPrefix](MDNode *Op) {
274 if (!InheritSomeAttrs)
275 return false;
276
277 // Skip malformatted attribute metadata nodes.
278 if (Op->getNumOperands() == 0)
279 return true;
280 Metadata *NameMD = Op->getOperand(0).get();
281 if (!isa<MDString>(NameMD))
282 return true;
283 StringRef AttrName = cast<MDString>(NameMD)->getString();
284
285 // Do not inherit excluded attributes.
286 return !AttrName.startswith(InheritOptionsExceptPrefix);
287 };
288
289 if (InheritThisAttribute(Op))
290 MDs.push_back(Op);
291 else
292 Changed = true;
293 }
294 } else {
295 // Modified if we dropped at least one attribute.
296 Changed = OrigLoopID->getNumOperands() > 1;
297 }
298
299 bool HasAnyFollowup = false;
300 for (StringRef OptionName : FollowupOptions) {
Michael Kruse978ba612018-12-20 04:58:07 +0000301 MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName);
Michael Kruse72448522018-12-12 17:32:52 +0000302 if (!FollowupNode)
303 continue;
304
305 HasAnyFollowup = true;
306 for (const MDOperand &Option : drop_begin(FollowupNode->operands(), 1)) {
307 MDs.push_back(Option.get());
308 Changed = true;
309 }
310 }
311
312 // Attributes of the followup loop not specified explicity, so signal to the
313 // transformation pass to add suitable attributes.
314 if (!AlwaysNew && !HasAnyFollowup)
315 return None;
316
317 // If no attributes were added or remove, the previous loop Id can be reused.
318 if (!AlwaysNew && !Changed)
319 return OrigLoopID;
320
321 // No attributes is equivalent to having no !llvm.loop metadata at all.
322 if (MDs.size() == 1)
323 return nullptr;
324
325 // Build the new loop ID.
326 MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs);
327 FollowupLoopID->replaceOperandWith(0, FollowupLoopID);
328 return FollowupLoopID;
329}
330
331bool llvm::hasDisableAllTransformsHint(const Loop *L) {
332 return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced);
333}
334
335TransformationMode llvm::hasUnrollTransformation(Loop *L) {
336 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable"))
337 return TM_SuppressedByUser;
338
339 Optional<int> Count =
340 getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
341 if (Count.hasValue())
342 return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
343
344 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
345 return TM_ForcedByUser;
346
347 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full"))
348 return TM_ForcedByUser;
349
350 if (hasDisableAllTransformsHint(L))
351 return TM_Disable;
352
353 return TM_Unspecified;
354}
355
356TransformationMode llvm::hasUnrollAndJamTransformation(Loop *L) {
357 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable"))
358 return TM_SuppressedByUser;
359
360 Optional<int> Count =
361 getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
362 if (Count.hasValue())
363 return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
364
365 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
366 return TM_ForcedByUser;
367
368 if (hasDisableAllTransformsHint(L))
369 return TM_Disable;
370
371 return TM_Unspecified;
372}
373
374TransformationMode llvm::hasVectorizeTransformation(Loop *L) {
375 Optional<bool> Enable =
376 getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable");
377
378 if (Enable == false)
379 return TM_SuppressedByUser;
380
381 Optional<int> VectorizeWidth =
382 getOptionalIntLoopAttribute(L, "llvm.loop.vectorize.width");
383 Optional<int> InterleaveCount =
384 getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count");
385
Michael Kruse70560a02019-02-04 19:55:59 +0000386 // 'Forcing' vector width and interleave count to one effectively disables
387 // this tranformation.
388 if (Enable == true && VectorizeWidth == 1 && InterleaveCount == 1)
389 return TM_SuppressedByUser;
Michael Kruse72448522018-12-12 17:32:52 +0000390
391 if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
392 return TM_Disable;
393
Michael Kruse70560a02019-02-04 19:55:59 +0000394 if (Enable == true)
395 return TM_ForcedByUser;
396
Michael Kruse72448522018-12-12 17:32:52 +0000397 if (VectorizeWidth == 1 && InterleaveCount == 1)
398 return TM_Disable;
399
400 if (VectorizeWidth > 1 || InterleaveCount > 1)
401 return TM_Enable;
402
403 if (hasDisableAllTransformsHint(L))
404 return TM_Disable;
405
406 return TM_Unspecified;
407}
408
409TransformationMode llvm::hasDistributeTransformation(Loop *L) {
410 if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable"))
411 return TM_ForcedByUser;
412
413 if (hasDisableAllTransformsHint(L))
414 return TM_Disable;
415
416 return TM_Unspecified;
417}
418
419TransformationMode llvm::hasLICMVersioningTransformation(Loop *L) {
420 if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable"))
421 return TM_SuppressedByUser;
422
423 if (hasDisableAllTransformsHint(L))
424 return TM_Disable;
425
426 return TM_Unspecified;
427}
428
Alina Sbirlea7ed58562017-09-15 00:04:16 +0000429/// Does a BFS from a given node to all of its children inside a given loop.
430/// The returned vector of nodes includes the starting point.
431SmallVector<DomTreeNode *, 16>
432llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
433 SmallVector<DomTreeNode *, 16> Worklist;
434 auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
435 // Only include subregions in the top level loop.
436 BasicBlock *BB = DTN->getBlock();
437 if (CurLoop->contains(BB))
438 Worklist.push_back(DTN);
439 };
440
441 AddRegionToWorklist(N);
442
443 for (size_t I = 0; I < Worklist.size(); I++)
444 for (DomTreeNode *Child : Worklist[I]->getChildren())
445 AddRegionToWorklist(Child);
446
447 return Worklist;
448}
449
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000450void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT = nullptr,
451 ScalarEvolution *SE = nullptr,
452 LoopInfo *LI = nullptr) {
Hans Wennborg899809d2017-10-04 21:14:07 +0000453 assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000454 auto *Preheader = L->getLoopPreheader();
455 assert(Preheader && "Preheader should exist!");
456
457 // Now that we know the removal is safe, remove the loop by changing the
458 // branch from the preheader to go to the single exit block.
459 //
460 // Because we're deleting a large chunk of code at once, the sequence in which
461 // we remove things is very important to avoid invalidation issues.
462
463 // Tell ScalarEvolution that the loop is deleted. Do this before
464 // deleting the loop so that ScalarEvolution can look at the loop
465 // to determine what it needs to clean up.
466 if (SE)
467 SE->forgetLoop(L);
468
469 auto *ExitBlock = L->getUniqueExitBlock();
470 assert(ExitBlock && "Should have a unique exit block!");
471 assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
472
473 auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
474 assert(OldBr && "Preheader must end with a branch");
475 assert(OldBr->isUnconditional() && "Preheader must have a single successor");
476 // Connect the preheader to the exit block. Keep the old edge to the header
477 // around to perform the dominator tree update in two separate steps
478 // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
479 // preheader -> header.
480 //
481 //
482 // 0. Preheader 1. Preheader 2. Preheader
483 // | | | |
484 // V | V |
485 // Header <--\ | Header <--\ | Header <--\
486 // | | | | | | | | | | |
487 // | V | | | V | | | V |
488 // | Body --/ | | Body --/ | | Body --/
489 // V V V V V
490 // Exit Exit Exit
491 //
492 // By doing this is two separate steps we can perform the dominator tree
493 // update without using the batch update API.
494 //
495 // Even when the loop is never executed, we cannot remove the edge from the
496 // source block to the exit block. Consider the case where the unexecuted loop
497 // branches back to an outer loop. If we deleted the loop and removed the edge
498 // coming to this inner loop, this will break the outer loop structure (by
499 // deleting the backedge of the outer loop). If the outer loop is indeed a
500 // non-loop, it will be deleted in a future iteration of loop deletion pass.
501 IRBuilder<> Builder(OldBr);
502 Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
503 // Remove the old branch. The conditional branch becomes a new terminator.
504 OldBr->eraseFromParent();
505
506 // Rewrite phis in the exit block to get their inputs from the Preheader
507 // instead of the exiting block.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000508 for (PHINode &P : ExitBlock->phis()) {
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000509 // Set the zero'th element of Phi to be from the preheader and remove all
510 // other incoming values. Given the loop has dedicated exits, all other
511 // incoming values must be from the exiting blocks.
512 int PredIndex = 0;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000513 P.setIncomingBlock(PredIndex, Preheader);
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000514 // Removes all incoming values from all other exiting blocks (including
515 // duplicate values from an exiting block).
516 // Nuke all entries except the zero'th entry which is the preheader entry.
517 // NOTE! We need to remove Incoming Values in the reverse order as done
518 // below, to keep the indices valid for deletion (removeIncomingValues
519 // updates getNumIncomingValues and shifts all values down into the operand
520 // being deleted).
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000521 for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
522 P.removeIncomingValue(e - i, false);
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000523
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000524 assert((P.getNumIncomingValues() == 1 &&
525 P.getIncomingBlock(PredIndex) == Preheader) &&
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000526 "Should have exactly one value and that's from the preheader!");
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000527 }
528
529 // Disconnect the loop body by branching directly to its exit.
530 Builder.SetInsertPoint(Preheader->getTerminator());
531 Builder.CreateBr(ExitBlock);
532 // Remove the old branch.
533 Preheader->getTerminator()->eraseFromParent();
534
Chijun Sima21a8b602018-08-03 05:08:17 +0000535 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000536 if (DT) {
537 // Update the dominator tree by informing it about the new edge from the
Chijun Simaf131d612019-02-22 05:41:43 +0000538 // preheader to the exit and the removed edge.
539 DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock},
540 {DominatorTree::Delete, Preheader, L->getHeader()}});
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000541 }
542
Davide Italiano744c3c32018-12-12 23:32:35 +0000543 // Use a map to unique and a vector to guarantee deterministic ordering.
Davide Italiano8ee59ca2018-12-13 01:11:52 +0000544 llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet;
Davide Italiano744c3c32018-12-12 23:32:35 +0000545 llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst;
546
Serguei Katkova757d652018-01-12 07:24:43 +0000547 // Given LCSSA form is satisfied, we should not have users of instructions
548 // within the dead loop outside of the loop. However, LCSSA doesn't take
549 // unreachable uses into account. We handle them here.
550 // We could do it after drop all references (in this case all users in the
551 // loop will be already eliminated and we have less work to do but according
552 // to API doc of User::dropAllReferences only valid operation after dropping
553 // references, is deletion. So let's substitute all usages of
554 // instruction from the loop with undef value of corresponding type first.
555 for (auto *Block : L->blocks())
556 for (Instruction &I : *Block) {
557 auto *Undef = UndefValue::get(I.getType());
558 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) {
559 Use &U = *UI;
560 ++UI;
561 if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
562 if (L->contains(Usr->getParent()))
563 continue;
564 // If we have a DT then we can check that uses outside a loop only in
565 // unreachable block.
566 if (DT)
567 assert(!DT->isReachableFromEntry(U) &&
568 "Unexpected user in reachable block");
569 U.set(Undef);
570 }
Davide Italiano744c3c32018-12-12 23:32:35 +0000571 auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I);
572 if (!DVI)
573 continue;
Davide Italiano8ee59ca2018-12-13 01:11:52 +0000574 auto Key = DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()});
575 if (Key != DeadDebugSet.end())
Davide Italiano744c3c32018-12-12 23:32:35 +0000576 continue;
Davide Italiano8ee59ca2018-12-13 01:11:52 +0000577 DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()});
Davide Italiano744c3c32018-12-12 23:32:35 +0000578 DeadDebugInst.push_back(DVI);
Serguei Katkova757d652018-01-12 07:24:43 +0000579 }
580
Davide Italiano744c3c32018-12-12 23:32:35 +0000581 // After the loop has been deleted all the values defined and modified
582 // inside the loop are going to be unavailable.
583 // Since debug values in the loop have been deleted, inserting an undef
584 // dbg.value truncates the range of any dbg.value before the loop where the
585 // loop used to be. This is particularly important for constant values.
586 DIBuilder DIB(*ExitBlock->getModule());
587 for (auto *DVI : DeadDebugInst)
588 DIB.insertDbgValueIntrinsic(
Davide Italiano97370962018-12-13 18:37:23 +0000589 UndefValue::get(Builder.getInt32Ty()), DVI->getVariable(),
Davide Italiano744c3c32018-12-12 23:32:35 +0000590 DVI->getExpression(), DVI->getDebugLoc(), ExitBlock->getFirstNonPHI());
591
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000592 // Remove the block from the reference counting scheme, so that we can
593 // delete it freely later.
594 for (auto *Block : L->blocks())
595 Block->dropAllReferences();
596
597 if (LI) {
598 // Erase the instructions and the blocks without having to worry
599 // about ordering because we already dropped the references.
600 // NOTE: This iteration is safe because erasing the block does not remove
601 // its entry from the loop's block list. We do that in the next section.
602 for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end();
603 LpI != LpE; ++LpI)
604 (*LpI)->eraseFromParent();
605
606 // Finally, the blocks from loopinfo. This has to happen late because
607 // otherwise our loop iterators won't work.
608
609 SmallPtrSet<BasicBlock *, 8> blocks;
610 blocks.insert(L->block_begin(), L->block_end());
611 for (BasicBlock *BB : blocks)
612 LI->removeBlock(BB);
613
614 // The last step is to update LoopInfo now that we've eliminated this loop.
615 LI->erase(L);
616 }
617}
618
Dehao Chen41d72a82016-11-17 01:17:02 +0000619Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) {
620 // Only support loops with a unique exiting block, and a latch.
621 if (!L->getExitingBlock())
622 return None;
623
Hiroshi Inoued24ddcd2018-01-19 10:55:29 +0000624 // Get the branch weights for the loop's backedge.
Dehao Chen41d72a82016-11-17 01:17:02 +0000625 BranchInst *LatchBR =
626 dyn_cast<BranchInst>(L->getLoopLatch()->getTerminator());
627 if (!LatchBR || LatchBR->getNumSuccessors() != 2)
628 return None;
629
630 assert((LatchBR->getSuccessor(0) == L->getHeader() ||
631 LatchBR->getSuccessor(1) == L->getHeader()) &&
632 "At least one edge out of the latch must go to the header");
633
634 // To estimate the number of times the loop body was executed, we want to
635 // know the number of times the backedge was taken, vs. the number of times
636 // we exited the loop.
Dehao Chen41d72a82016-11-17 01:17:02 +0000637 uint64_t TrueVal, FalseVal;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000638 if (!LatchBR->extractProfMetadata(TrueVal, FalseVal))
Dehao Chen41d72a82016-11-17 01:17:02 +0000639 return None;
640
Michael Kupersteinb151a642016-11-30 21:13:57 +0000641 if (!TrueVal || !FalseVal)
642 return 0;
Dehao Chen41d72a82016-11-17 01:17:02 +0000643
Michael Kupersteinb151a642016-11-30 21:13:57 +0000644 // Divide the count of the backedge by the count of the edge exiting the loop,
645 // rounding to nearest.
Dehao Chen41d72a82016-11-17 01:17:02 +0000646 if (LatchBR->getSuccessor(0) == L->getHeader())
Michael Kupersteinb151a642016-11-30 21:13:57 +0000647 return (TrueVal + (FalseVal / 2)) / FalseVal;
Dehao Chen41d72a82016-11-17 01:17:02 +0000648 else
Michael Kupersteinb151a642016-11-30 21:13:57 +0000649 return (FalseVal + (TrueVal / 2)) / TrueVal;
Dehao Chen41d72a82016-11-17 01:17:02 +0000650}
Amara Emersoncf9daa32017-05-09 10:43:25 +0000651
David Green6cb64782018-08-15 10:59:41 +0000652bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
653 ScalarEvolution &SE) {
David Green395b80c2018-08-11 06:57:28 +0000654 Loop *OuterL = InnerLoop->getParentLoop();
655 if (!OuterL)
656 return true;
657
658 // Get the backedge taken count for the inner loop
659 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
660 const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
661 if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
662 !InnerLoopBECountSC->getType()->isIntegerTy())
663 return false;
664
665 // Get whether count is invariant to the outer loop
666 ScalarEvolution::LoopDisposition LD =
667 SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
668 if (LD != ScalarEvolution::LoopInvariant)
669 return false;
670
671 return true;
672}
673
Sanjoy Das2136a5bc2019-03-11 22:37:31 +0000674/// Adds a 'fast' flag to floating point operations.
675static Value *addFastMathFlag(Value *V) {
676 if (isa<FPMathOperator>(V)) {
677 FastMathFlags Flags;
678 Flags.setFast();
679 cast<Instruction>(V)->setFastMathFlags(Flags);
680 }
Amara Emersoncf9daa32017-05-09 10:43:25 +0000681 return V;
682}
683
Vikram TV6594dc32018-09-10 05:05:08 +0000684Value *llvm::createMinMaxOp(IRBuilder<> &Builder,
685 RecurrenceDescriptor::MinMaxRecurrenceKind RK,
686 Value *Left, Value *Right) {
687 CmpInst::Predicate P = CmpInst::ICMP_NE;
688 switch (RK) {
689 default:
690 llvm_unreachable("Unknown min/max recurrence kind");
691 case RecurrenceDescriptor::MRK_UIntMin:
692 P = CmpInst::ICMP_ULT;
693 break;
694 case RecurrenceDescriptor::MRK_UIntMax:
695 P = CmpInst::ICMP_UGT;
696 break;
697 case RecurrenceDescriptor::MRK_SIntMin:
698 P = CmpInst::ICMP_SLT;
699 break;
700 case RecurrenceDescriptor::MRK_SIntMax:
701 P = CmpInst::ICMP_SGT;
702 break;
703 case RecurrenceDescriptor::MRK_FloatMin:
704 P = CmpInst::FCMP_OLT;
705 break;
706 case RecurrenceDescriptor::MRK_FloatMax:
707 P = CmpInst::FCMP_OGT;
708 break;
709 }
710
711 // We only match FP sequences that are 'fast', so we can unconditionally
712 // set it on any generated instructions.
713 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
714 FastMathFlags FMF;
715 FMF.setFast();
716 Builder.setFastMathFlags(FMF);
717
718 Value *Cmp;
719 if (RK == RecurrenceDescriptor::MRK_FloatMin ||
720 RK == RecurrenceDescriptor::MRK_FloatMax)
721 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
722 else
723 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
724
725 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
726 return Select;
727}
728
Simon Pilgrim23c21822018-04-09 15:44:20 +0000729// Helper to generate an ordered reduction.
730Value *
731llvm::getOrderedReduction(IRBuilder<> &Builder, Value *Acc, Value *Src,
732 unsigned Op,
733 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
734 ArrayRef<Value *> RedOps) {
735 unsigned VF = Src->getType()->getVectorNumElements();
736
737 // Extract and apply reduction ops in ascending order:
738 // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
739 Value *Result = Acc;
740 for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
741 Value *Ext =
742 Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
743
744 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
745 Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
746 "bin.rdx");
747 } else {
748 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
749 "Invalid min/max");
Vikram TV6594dc32018-09-10 05:05:08 +0000750 Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext);
Simon Pilgrim23c21822018-04-09 15:44:20 +0000751 }
752
753 if (!RedOps.empty())
754 propagateIRFlags(Result, RedOps);
755 }
756
757 return Result;
758}
759
Amara Emersoncf9daa32017-05-09 10:43:25 +0000760// Helper to generate a log2 shuffle reduction.
Amara Emerson836b0f42017-05-10 09:42:49 +0000761Value *
762llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op,
763 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
Sanjoy Das2136a5bc2019-03-11 22:37:31 +0000764 ArrayRef<Value *> RedOps) {
Amara Emersoncf9daa32017-05-09 10:43:25 +0000765 unsigned VF = Src->getType()->getVectorNumElements();
766 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
767 // and vector ops, reducing the set of values being computed by half each
768 // round.
769 assert(isPowerOf2_32(VF) &&
770 "Reduction emission only supported for pow2 vectors!");
771 Value *TmpVec = Src;
772 SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
773 for (unsigned i = VF; i != 1; i >>= 1) {
774 // Move the upper half of the vector to the lower half.
775 for (unsigned j = 0; j != i / 2; ++j)
776 ShuffleMask[j] = Builder.getInt32(i / 2 + j);
777
778 // Fill the rest of the mask with undef.
779 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
780 UndefValue::get(Builder.getInt32Ty()));
781
782 Value *Shuf = Builder.CreateShuffleVector(
783 TmpVec, UndefValue::get(TmpVec->getType()),
784 ConstantVector::get(ShuffleMask), "rdx.shuf");
785
786 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
787 // Floating point operations had to be 'fast' to enable the reduction.
788 TmpVec = addFastMathFlag(Builder.CreateBinOp((Instruction::BinaryOps)Op,
Sanjoy Das2136a5bc2019-03-11 22:37:31 +0000789 TmpVec, Shuf, "bin.rdx"));
Amara Emersoncf9daa32017-05-09 10:43:25 +0000790 } else {
791 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
792 "Invalid min/max");
Vikram TV6594dc32018-09-10 05:05:08 +0000793 TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000794 }
795 if (!RedOps.empty())
796 propagateIRFlags(TmpVec, RedOps);
797 }
798 // The result is in the first element of the vector.
799 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
800}
801
802/// Create a simple vector reduction specified by an opcode and some
803/// flags (if generating min/max reductions).
804Value *llvm::createSimpleTargetReduction(
805 IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode,
Sanjoy Das2136a5bc2019-03-11 22:37:31 +0000806 Value *Src, TargetTransformInfo::ReductionFlags Flags,
Amara Emersoncf9daa32017-05-09 10:43:25 +0000807 ArrayRef<Value *> RedOps) {
808 assert(isa<VectorType>(Src->getType()) && "Type must be a vector");
809
810 Value *ScalarUdf = UndefValue::get(Src->getType()->getVectorElementType());
Vikram TV7e98d692018-09-12 01:59:43 +0000811 std::function<Value *()> BuildFunc;
Amara Emersoncf9daa32017-05-09 10:43:25 +0000812 using RD = RecurrenceDescriptor;
813 RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
814 // TODO: Support creating ordered reductions.
Sanjay Patel1ea7b6f2017-12-06 19:11:23 +0000815 FastMathFlags FMFFast;
816 FMFFast.setFast();
Amara Emersoncf9daa32017-05-09 10:43:25 +0000817
818 switch (Opcode) {
819 case Instruction::Add:
820 BuildFunc = [&]() { return Builder.CreateAddReduce(Src); };
821 break;
822 case Instruction::Mul:
823 BuildFunc = [&]() { return Builder.CreateMulReduce(Src); };
824 break;
825 case Instruction::And:
826 BuildFunc = [&]() { return Builder.CreateAndReduce(Src); };
827 break;
828 case Instruction::Or:
829 BuildFunc = [&]() { return Builder.CreateOrReduce(Src); };
830 break;
831 case Instruction::Xor:
832 BuildFunc = [&]() { return Builder.CreateXorReduce(Src); };
833 break;
834 case Instruction::FAdd:
835 BuildFunc = [&]() {
836 auto Rdx = Builder.CreateFAddReduce(ScalarUdf, Src);
Sanjay Patel1ea7b6f2017-12-06 19:11:23 +0000837 cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000838 return Rdx;
839 };
840 break;
841 case Instruction::FMul:
842 BuildFunc = [&]() {
843 auto Rdx = Builder.CreateFMulReduce(ScalarUdf, Src);
Sanjay Patel1ea7b6f2017-12-06 19:11:23 +0000844 cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000845 return Rdx;
846 };
847 break;
848 case Instruction::ICmp:
849 if (Flags.IsMaxOp) {
850 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
851 BuildFunc = [&]() {
852 return Builder.CreateIntMaxReduce(Src, Flags.IsSigned);
853 };
854 } else {
855 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
856 BuildFunc = [&]() {
857 return Builder.CreateIntMinReduce(Src, Flags.IsSigned);
858 };
859 }
860 break;
861 case Instruction::FCmp:
862 if (Flags.IsMaxOp) {
863 MinMaxKind = RD::MRK_FloatMax;
864 BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); };
865 } else {
866 MinMaxKind = RD::MRK_FloatMin;
867 BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); };
868 }
869 break;
870 default:
871 llvm_unreachable("Unhandled opcode");
872 break;
873 }
874 if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags))
875 return BuildFunc();
Sanjoy Das2136a5bc2019-03-11 22:37:31 +0000876 return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000877}
878
879/// Create a vector reduction using a given recurrence descriptor.
Sanjay Patel3e069f52017-12-06 19:37:00 +0000880Value *llvm::createTargetReduction(IRBuilder<> &B,
Amara Emersoncf9daa32017-05-09 10:43:25 +0000881 const TargetTransformInfo *TTI,
882 RecurrenceDescriptor &Desc, Value *Src,
883 bool NoNaN) {
884 // TODO: Support in-order reductions based on the recurrence descriptor.
Sanjay Patel3e069f52017-12-06 19:37:00 +0000885 using RD = RecurrenceDescriptor;
886 RD::RecurrenceKind RecKind = Desc.getRecurrenceKind();
Amara Emersoncf9daa32017-05-09 10:43:25 +0000887 TargetTransformInfo::ReductionFlags Flags;
888 Flags.NoNaN = NoNaN;
Amara Emersoncf9daa32017-05-09 10:43:25 +0000889 switch (RecKind) {
Sanjay Patel3e069f52017-12-06 19:37:00 +0000890 case RD::RK_FloatAdd:
Sanjoy Das2136a5bc2019-03-11 22:37:31 +0000891 return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags);
Sanjay Patel3e069f52017-12-06 19:37:00 +0000892 case RD::RK_FloatMult:
Sanjoy Das2136a5bc2019-03-11 22:37:31 +0000893 return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags);
Sanjay Patel3e069f52017-12-06 19:37:00 +0000894 case RD::RK_IntegerAdd:
Sanjoy Das2136a5bc2019-03-11 22:37:31 +0000895 return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags);
Sanjay Patel3e069f52017-12-06 19:37:00 +0000896 case RD::RK_IntegerMult:
Sanjoy Das2136a5bc2019-03-11 22:37:31 +0000897 return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags);
Sanjay Patel3e069f52017-12-06 19:37:00 +0000898 case RD::RK_IntegerAnd:
Sanjoy Das2136a5bc2019-03-11 22:37:31 +0000899 return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags);
Sanjay Patel3e069f52017-12-06 19:37:00 +0000900 case RD::RK_IntegerOr:
Sanjoy Das2136a5bc2019-03-11 22:37:31 +0000901 return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags);
Sanjay Patel3e069f52017-12-06 19:37:00 +0000902 case RD::RK_IntegerXor:
Sanjoy Das2136a5bc2019-03-11 22:37:31 +0000903 return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags);
Sanjay Patel3e069f52017-12-06 19:37:00 +0000904 case RD::RK_IntegerMinMax: {
905 RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind();
906 Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax);
907 Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin);
Sanjoy Das2136a5bc2019-03-11 22:37:31 +0000908 return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000909 }
Sanjay Patel3e069f52017-12-06 19:37:00 +0000910 case RD::RK_FloatMinMax: {
911 Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax;
Sanjoy Das2136a5bc2019-03-11 22:37:31 +0000912 return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000913 }
914 default:
915 llvm_unreachable("Unhandled RecKind");
916 }
917}
918
Dinar Temirbulatova61f4b82017-07-19 10:02:07 +0000919void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
920 auto *VecOp = dyn_cast<Instruction>(I);
921 if (!VecOp)
922 return;
923 auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
924 : dyn_cast<Instruction>(OpValue);
925 if (!Intersection)
926 return;
927 const unsigned Opcode = Intersection->getOpcode();
928 VecOp->copyIRFlags(Intersection);
929 for (auto *V : VL) {
930 auto *Instr = dyn_cast<Instruction>(V);
931 if (!Instr)
932 continue;
933 if (OpValue == nullptr || Opcode == Instr->getOpcode())
934 VecOp->andIRFlags(V);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000935 }
936}
Max Kazantseva78dc4d2019-01-15 09:51:34 +0000937
938bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L,
939 ScalarEvolution &SE) {
940 const SCEV *Zero = SE.getZero(S->getType());
941 return SE.isAvailableAtLoopEntry(S, L) &&
942 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero);
943}
944
945bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L,
946 ScalarEvolution &SE) {
947 const SCEV *Zero = SE.getZero(S->getType());
948 return SE.isAvailableAtLoopEntry(S, L) &&
949 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero);
950}
951
952bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
953 bool Signed) {
954 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
955 APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) :
956 APInt::getMinValue(BitWidth);
957 auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
958 return SE.isAvailableAtLoopEntry(S, L) &&
959 SE.isLoopEntryGuardedByCond(L, Predicate, S,
960 SE.getConstant(Min));
961}
962
963bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
964 bool Signed) {
965 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
966 APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) :
967 APInt::getMaxValue(BitWidth);
968 auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
969 return SE.isAvailableAtLoopEntry(S, L) &&
970 SE.isLoopEntryGuardedByCond(L, Predicate, S,
971 SE.getConstant(Max));
972}