blob: a5d88d8269f03c1999a552b84df517776c943e80 [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 Carruth4a000882017-06-25 22:45:31 +000015#include "llvm/ADT/ScopeExit.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000016#include "llvm/Analysis/AliasAnalysis.h"
17#include "llvm/Analysis/BasicAliasAnalysis.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"
Philip Reames23aed5e2018-03-20 22:45:23 +000022#include "llvm/Analysis/MustExecute.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000023#include "llvm/Analysis/ScalarEvolution.h"
Adam Nemet2f2bd8c2016-07-26 17:52:02 +000024#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Elena Demikhovskyc434d092016-05-10 07:33:35 +000025#include "llvm/Analysis/ScalarEvolutionExpander.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000026#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000027#include "llvm/Analysis/TargetTransformInfo.h"
Chad Rosiera097bc62018-02-04 15:42:24 +000028#include "llvm/Analysis/ValueTracking.h"
Davide Italiano744c3c32018-12-12 23:32:35 +000029#include "llvm/IR/DIBuilder.h"
Chijun Sima21a8b602018-08-03 05:08:17 +000030#include "llvm/IR/DomTreeUpdater.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,
50 bool PreserveLCSSA) {
51 bool Changed = false;
52
53 // We re-use a vector for the in-loop predecesosrs.
54 SmallVector<BasicBlock *, 4> InLoopPredecessors;
55
56 auto RewriteExit = [&](BasicBlock *BB) {
57 assert(InLoopPredecessors.empty() &&
58 "Must start with an empty predecessors list!");
59 auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
60
61 // See if there are any non-loop predecessors of this exit block and
62 // keep track of the in-loop predecessors.
63 bool IsDedicatedExit = true;
64 for (auto *PredBB : predecessors(BB))
65 if (L->contains(PredBB)) {
66 if (isa<IndirectBrInst>(PredBB->getTerminator()))
67 // We cannot rewrite exiting edges from an indirectbr.
68 return false;
69
70 InLoopPredecessors.push_back(PredBB);
71 } else {
72 IsDedicatedExit = false;
73 }
74
75 assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
76
77 // Nothing to do if this is already a dedicated exit.
78 if (IsDedicatedExit)
79 return false;
80
81 auto *NewExitBB = SplitBlockPredecessors(
Alina Sbirleaab6f84f72018-08-21 23:32:03 +000082 BB, InLoopPredecessors, ".loopexit", DT, LI, nullptr, PreserveLCSSA);
Chandler Carruth4a000882017-06-25 22:45:31 +000083
84 if (!NewExitBB)
Nicola Zaghend34e60c2018-05-14 12:53:11 +000085 LLVM_DEBUG(
86 dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
87 << *L << "\n");
Chandler Carruth4a000882017-06-25 22:45:31 +000088 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +000089 LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
90 << NewExitBB->getName() << "\n");
Chandler Carruth4a000882017-06-25 22:45:31 +000091 return true;
92 };
93
94 // Walk the exit blocks directly rather than building up a data structure for
95 // them, but only visit each one once.
96 SmallPtrSet<BasicBlock *, 4> Visited;
97 for (auto *BB : L->blocks())
98 for (auto *SuccBB : successors(BB)) {
99 // We're looking for exit blocks so skip in-loop successors.
100 if (L->contains(SuccBB))
101 continue;
102
103 // Visit each exit block exactly once.
104 if (!Visited.insert(SuccBB).second)
105 continue;
106
107 Changed |= RewriteExit(SuccBB);
108 }
109
110 return Changed;
111}
112
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000113/// Returns the instructions that use values defined in the loop.
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000114SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
115 SmallVector<Instruction *, 8> UsedOutside;
116
117 for (auto *Block : L->getBlocks())
118 // FIXME: I believe that this could use copy_if if the Inst reference could
119 // be adapted into a pointer.
120 for (auto &Inst : *Block) {
121 auto Users = Inst.users();
David Majnemer0a16c222016-08-11 21:15:00 +0000122 if (any_of(Users, [&](User *U) {
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000123 auto *Use = cast<Instruction>(U);
124 return !L->contains(Use->getParent());
125 }))
126 UsedOutside.push_back(&Inst);
127 }
128
129 return UsedOutside;
130}
Chandler Carruth31088a92016-02-19 10:45:18 +0000131
132void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
133 // By definition, all loop passes need the LoopInfo analysis and the
134 // Dominator tree it depends on. Because they all participate in the loop
135 // pass manager, they must also preserve these.
136 AU.addRequired<DominatorTreeWrapperPass>();
137 AU.addPreserved<DominatorTreeWrapperPass>();
138 AU.addRequired<LoopInfoWrapperPass>();
139 AU.addPreserved<LoopInfoWrapperPass>();
140
141 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
142 // here because users shouldn't directly get them from this header.
143 extern char &LoopSimplifyID;
144 extern char &LCSSAID;
145 AU.addRequiredID(LoopSimplifyID);
146 AU.addPreservedID(LoopSimplifyID);
147 AU.addRequiredID(LCSSAID);
148 AU.addPreservedID(LCSSAID);
Igor Laevskyc3ccf5d2016-10-28 12:57:20 +0000149 // This is used in the LPPassManager to perform LCSSA verification on passes
150 // which preserve lcssa form
151 AU.addRequired<LCSSAVerificationPass>();
152 AU.addPreserved<LCSSAVerificationPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000153
154 // Loop passes are designed to run inside of a loop pass manager which means
155 // that any function analyses they require must be required by the first loop
156 // pass in the manager (so that it is computed before the loop pass manager
157 // runs) and preserved by all loop pasess in the manager. To make this
158 // reasonably robust, the set needed for most loop passes is maintained here.
159 // If your loop pass requires an analysis not listed here, you will need to
160 // carefully audit the loop pass manager nesting structure that results.
161 AU.addRequired<AAResultsWrapperPass>();
162 AU.addPreserved<AAResultsWrapperPass>();
163 AU.addPreserved<BasicAAWrapperPass>();
164 AU.addPreserved<GlobalsAAWrapperPass>();
165 AU.addPreserved<SCEVAAWrapperPass>();
166 AU.addRequired<ScalarEvolutionWrapperPass>();
167 AU.addPreserved<ScalarEvolutionWrapperPass>();
168}
169
170/// Manually defined generic "LoopPass" dependency initialization. This is used
171/// to initialize the exact set of passes from above in \c
172/// getLoopAnalysisUsage. It can be used within a loop pass's initialization
173/// with:
174///
175/// INITIALIZE_PASS_DEPENDENCY(LoopPass)
176///
177/// As-if "LoopPass" were a pass.
178void llvm::initializeLoopPassPass(PassRegistry &Registry) {
179 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
180 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
181 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Easwaran Ramane12c4872016-06-09 19:44:46 +0000182 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000183 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
184 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
185 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
186 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
187 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
188}
Adam Nemet963341c2016-04-21 17:33:17 +0000189
Michael Kruse72448522018-12-12 17:32:52 +0000190static Optional<MDNode *> findOptionMDForLoopID(MDNode *LoopID,
191 StringRef Name) {
Adam Nemetfe3def72016-04-22 19:10:05 +0000192 // Return none if LoopID is false.
Adam Nemet963341c2016-04-21 17:33:17 +0000193 if (!LoopID)
Adam Nemetfe3def72016-04-22 19:10:05 +0000194 return None;
Adam Nemet293be662016-04-21 17:33:20 +0000195
196 // First operand should refer to the loop id itself.
197 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
198 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
199
Adam Nemet963341c2016-04-21 17:33:17 +0000200 // Iterate over LoopID operands and look for MDString Metadata
201 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
202 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
203 if (!MD)
204 continue;
205 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
206 if (!S)
207 continue;
208 // Return true if MDString holds expected MetaData.
209 if (Name.equals(S->getString()))
Michael Kruse72448522018-12-12 17:32:52 +0000210 return MD;
Adam Nemet963341c2016-04-21 17:33:17 +0000211 }
Adam Nemetfe3def72016-04-22 19:10:05 +0000212 return None;
Adam Nemet963341c2016-04-21 17:33:17 +0000213}
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000214
Michael Kruse72448522018-12-12 17:32:52 +0000215static Optional<MDNode *> findOptionMDForLoop(const Loop *TheLoop,
216 StringRef Name) {
217 return findOptionMDForLoopID(TheLoop->getLoopID(), Name);
218}
219
220/// Find string metadata for loop
221///
222/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
223/// operand or null otherwise. If the string metadata is not found return
224/// Optional's not-a-value.
225Optional<const MDOperand *> llvm::findStringMetadataForLoop(Loop *TheLoop,
226 StringRef Name) {
227 auto MD = findOptionMDForLoop(TheLoop, Name).getValueOr(nullptr);
228 if (!MD)
229 return None;
230 switch (MD->getNumOperands()) {
231 case 1:
232 return nullptr;
233 case 2:
234 return &MD->getOperand(1);
235 default:
236 llvm_unreachable("loop metadata has 0 or 1 operand");
237 }
238}
239
240static Optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop,
241 StringRef Name) {
242 Optional<MDNode *> MD = findOptionMDForLoop(TheLoop, Name);
243 if (!MD.hasValue())
244 return None;
245 MDNode *OptionNode = MD.getValue();
246 if (OptionNode == nullptr)
247 return None;
248 switch (OptionNode->getNumOperands()) {
249 case 1:
250 // When the value is absent it is interpreted as 'attribute set'.
251 return true;
252 case 2:
253 return mdconst::extract_or_null<ConstantInt>(
254 OptionNode->getOperand(1).get());
255 }
256 llvm_unreachable("unexpected number of options");
257}
258
259static bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) {
260 return getOptionalBoolLoopAttribute(TheLoop, Name).getValueOr(false);
261}
262
263llvm::Optional<int> llvm::getOptionalIntLoopAttribute(Loop *TheLoop,
264 StringRef Name) {
265 const MDOperand *AttrMD =
266 findStringMetadataForLoop(TheLoop, Name).getValueOr(nullptr);
267 if (!AttrMD)
268 return None;
269
270 ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
271 if (!IntMD)
272 return None;
273
274 return IntMD->getSExtValue();
275}
276
277Optional<MDNode *> llvm::makeFollowupLoopID(
278 MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
279 const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
280 if (!OrigLoopID) {
281 if (AlwaysNew)
282 return nullptr;
283 return None;
284 }
285
286 assert(OrigLoopID->getOperand(0) == OrigLoopID);
287
288 bool InheritAllAttrs = !InheritOptionsExceptPrefix;
289 bool InheritSomeAttrs =
290 InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
291 SmallVector<Metadata *, 8> MDs;
292 MDs.push_back(nullptr);
293
294 bool Changed = false;
295 if (InheritAllAttrs || InheritSomeAttrs) {
296 for (const MDOperand &Existing : drop_begin(OrigLoopID->operands(), 1)) {
297 MDNode *Op = cast<MDNode>(Existing.get());
298
299 auto InheritThisAttribute = [InheritSomeAttrs,
300 InheritOptionsExceptPrefix](MDNode *Op) {
301 if (!InheritSomeAttrs)
302 return false;
303
304 // Skip malformatted attribute metadata nodes.
305 if (Op->getNumOperands() == 0)
306 return true;
307 Metadata *NameMD = Op->getOperand(0).get();
308 if (!isa<MDString>(NameMD))
309 return true;
310 StringRef AttrName = cast<MDString>(NameMD)->getString();
311
312 // Do not inherit excluded attributes.
313 return !AttrName.startswith(InheritOptionsExceptPrefix);
314 };
315
316 if (InheritThisAttribute(Op))
317 MDs.push_back(Op);
318 else
319 Changed = true;
320 }
321 } else {
322 // Modified if we dropped at least one attribute.
323 Changed = OrigLoopID->getNumOperands() > 1;
324 }
325
326 bool HasAnyFollowup = false;
327 for (StringRef OptionName : FollowupOptions) {
328 MDNode *FollowupNode =
329 findOptionMDForLoopID(OrigLoopID, OptionName).getValueOr(nullptr);
330 if (!FollowupNode)
331 continue;
332
333 HasAnyFollowup = true;
334 for (const MDOperand &Option : drop_begin(FollowupNode->operands(), 1)) {
335 MDs.push_back(Option.get());
336 Changed = true;
337 }
338 }
339
340 // Attributes of the followup loop not specified explicity, so signal to the
341 // transformation pass to add suitable attributes.
342 if (!AlwaysNew && !HasAnyFollowup)
343 return None;
344
345 // If no attributes were added or remove, the previous loop Id can be reused.
346 if (!AlwaysNew && !Changed)
347 return OrigLoopID;
348
349 // No attributes is equivalent to having no !llvm.loop metadata at all.
350 if (MDs.size() == 1)
351 return nullptr;
352
353 // Build the new loop ID.
354 MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs);
355 FollowupLoopID->replaceOperandWith(0, FollowupLoopID);
356 return FollowupLoopID;
357}
358
359bool llvm::hasDisableAllTransformsHint(const Loop *L) {
360 return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced);
361}
362
363TransformationMode llvm::hasUnrollTransformation(Loop *L) {
364 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable"))
365 return TM_SuppressedByUser;
366
367 Optional<int> Count =
368 getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
369 if (Count.hasValue())
370 return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
371
372 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
373 return TM_ForcedByUser;
374
375 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full"))
376 return TM_ForcedByUser;
377
378 if (hasDisableAllTransformsHint(L))
379 return TM_Disable;
380
381 return TM_Unspecified;
382}
383
384TransformationMode llvm::hasUnrollAndJamTransformation(Loop *L) {
385 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable"))
386 return TM_SuppressedByUser;
387
388 Optional<int> Count =
389 getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
390 if (Count.hasValue())
391 return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
392
393 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
394 return TM_ForcedByUser;
395
396 if (hasDisableAllTransformsHint(L))
397 return TM_Disable;
398
399 return TM_Unspecified;
400}
401
402TransformationMode llvm::hasVectorizeTransformation(Loop *L) {
403 Optional<bool> Enable =
404 getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable");
405
406 if (Enable == false)
407 return TM_SuppressedByUser;
408
409 Optional<int> VectorizeWidth =
410 getOptionalIntLoopAttribute(L, "llvm.loop.vectorize.width");
411 Optional<int> InterleaveCount =
412 getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count");
413
414 if (Enable == true) {
415 // 'Forcing' vector width and interleave count to one effectively disables
416 // this tranformation.
417 if (VectorizeWidth == 1 && InterleaveCount == 1)
418 return TM_SuppressedByUser;
419 return TM_ForcedByUser;
420 }
421
422 if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
423 return TM_Disable;
424
425 if (VectorizeWidth == 1 && InterleaveCount == 1)
426 return TM_Disable;
427
428 if (VectorizeWidth > 1 || InterleaveCount > 1)
429 return TM_Enable;
430
431 if (hasDisableAllTransformsHint(L))
432 return TM_Disable;
433
434 return TM_Unspecified;
435}
436
437TransformationMode llvm::hasDistributeTransformation(Loop *L) {
438 if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable"))
439 return TM_ForcedByUser;
440
441 if (hasDisableAllTransformsHint(L))
442 return TM_Disable;
443
444 return TM_Unspecified;
445}
446
447TransformationMode llvm::hasLICMVersioningTransformation(Loop *L) {
448 if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable"))
449 return TM_SuppressedByUser;
450
451 if (hasDisableAllTransformsHint(L))
452 return TM_Disable;
453
454 return TM_Unspecified;
455}
456
Alina Sbirlea7ed58562017-09-15 00:04:16 +0000457/// Does a BFS from a given node to all of its children inside a given loop.
458/// The returned vector of nodes includes the starting point.
459SmallVector<DomTreeNode *, 16>
460llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
461 SmallVector<DomTreeNode *, 16> Worklist;
462 auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
463 // Only include subregions in the top level loop.
464 BasicBlock *BB = DTN->getBlock();
465 if (CurLoop->contains(BB))
466 Worklist.push_back(DTN);
467 };
468
469 AddRegionToWorklist(N);
470
471 for (size_t I = 0; I < Worklist.size(); I++)
472 for (DomTreeNode *Child : Worklist[I]->getChildren())
473 AddRegionToWorklist(Child);
474
475 return Worklist;
476}
477
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000478void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT = nullptr,
479 ScalarEvolution *SE = nullptr,
480 LoopInfo *LI = nullptr) {
Hans Wennborg899809d2017-10-04 21:14:07 +0000481 assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000482 auto *Preheader = L->getLoopPreheader();
483 assert(Preheader && "Preheader should exist!");
484
485 // Now that we know the removal is safe, remove the loop by changing the
486 // branch from the preheader to go to the single exit block.
487 //
488 // Because we're deleting a large chunk of code at once, the sequence in which
489 // we remove things is very important to avoid invalidation issues.
490
491 // Tell ScalarEvolution that the loop is deleted. Do this before
492 // deleting the loop so that ScalarEvolution can look at the loop
493 // to determine what it needs to clean up.
494 if (SE)
495 SE->forgetLoop(L);
496
497 auto *ExitBlock = L->getUniqueExitBlock();
498 assert(ExitBlock && "Should have a unique exit block!");
499 assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
500
501 auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
502 assert(OldBr && "Preheader must end with a branch");
503 assert(OldBr->isUnconditional() && "Preheader must have a single successor");
504 // Connect the preheader to the exit block. Keep the old edge to the header
505 // around to perform the dominator tree update in two separate steps
506 // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
507 // preheader -> header.
508 //
509 //
510 // 0. Preheader 1. Preheader 2. Preheader
511 // | | | |
512 // V | V |
513 // Header <--\ | Header <--\ | Header <--\
514 // | | | | | | | | | | |
515 // | V | | | V | | | V |
516 // | Body --/ | | Body --/ | | Body --/
517 // V V V V V
518 // Exit Exit Exit
519 //
520 // By doing this is two separate steps we can perform the dominator tree
521 // update without using the batch update API.
522 //
523 // Even when the loop is never executed, we cannot remove the edge from the
524 // source block to the exit block. Consider the case where the unexecuted loop
525 // branches back to an outer loop. If we deleted the loop and removed the edge
526 // coming to this inner loop, this will break the outer loop structure (by
527 // deleting the backedge of the outer loop). If the outer loop is indeed a
528 // non-loop, it will be deleted in a future iteration of loop deletion pass.
529 IRBuilder<> Builder(OldBr);
530 Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
531 // Remove the old branch. The conditional branch becomes a new terminator.
532 OldBr->eraseFromParent();
533
534 // Rewrite phis in the exit block to get their inputs from the Preheader
535 // instead of the exiting block.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000536 for (PHINode &P : ExitBlock->phis()) {
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000537 // Set the zero'th element of Phi to be from the preheader and remove all
538 // other incoming values. Given the loop has dedicated exits, all other
539 // incoming values must be from the exiting blocks.
540 int PredIndex = 0;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000541 P.setIncomingBlock(PredIndex, Preheader);
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000542 // Removes all incoming values from all other exiting blocks (including
543 // duplicate values from an exiting block).
544 // Nuke all entries except the zero'th entry which is the preheader entry.
545 // NOTE! We need to remove Incoming Values in the reverse order as done
546 // below, to keep the indices valid for deletion (removeIncomingValues
547 // updates getNumIncomingValues and shifts all values down into the operand
548 // being deleted).
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000549 for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
550 P.removeIncomingValue(e - i, false);
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000551
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000552 assert((P.getNumIncomingValues() == 1 &&
553 P.getIncomingBlock(PredIndex) == Preheader) &&
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000554 "Should have exactly one value and that's from the preheader!");
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000555 }
556
557 // Disconnect the loop body by branching directly to its exit.
558 Builder.SetInsertPoint(Preheader->getTerminator());
559 Builder.CreateBr(ExitBlock);
560 // Remove the old branch.
561 Preheader->getTerminator()->eraseFromParent();
562
Chijun Sima21a8b602018-08-03 05:08:17 +0000563 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000564 if (DT) {
565 // Update the dominator tree by informing it about the new edge from the
566 // preheader to the exit.
Chijun Sima21a8b602018-08-03 05:08:17 +0000567 DTU.insertEdge(Preheader, ExitBlock);
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000568 // Inform the dominator tree about the removed edge.
Chijun Sima21a8b602018-08-03 05:08:17 +0000569 DTU.deleteEdge(Preheader, L->getHeader());
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000570 }
571
Davide Italiano744c3c32018-12-12 23:32:35 +0000572 // Use a map to unique and a vector to guarantee deterministic ordering.
573 llvm::SmallDenseMap<std::pair<DIVariable *, DIExpression *>,
574 DbgVariableIntrinsic *, 4>
575 DeadDebugMap;
576 llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst;
577
Serguei Katkova757d652018-01-12 07:24:43 +0000578 // Given LCSSA form is satisfied, we should not have users of instructions
579 // within the dead loop outside of the loop. However, LCSSA doesn't take
580 // unreachable uses into account. We handle them here.
581 // We could do it after drop all references (in this case all users in the
582 // loop will be already eliminated and we have less work to do but according
583 // to API doc of User::dropAllReferences only valid operation after dropping
584 // references, is deletion. So let's substitute all usages of
585 // instruction from the loop with undef value of corresponding type first.
586 for (auto *Block : L->blocks())
587 for (Instruction &I : *Block) {
588 auto *Undef = UndefValue::get(I.getType());
589 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) {
590 Use &U = *UI;
591 ++UI;
592 if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
593 if (L->contains(Usr->getParent()))
594 continue;
595 // If we have a DT then we can check that uses outside a loop only in
596 // unreachable block.
597 if (DT)
598 assert(!DT->isReachableFromEntry(U) &&
599 "Unexpected user in reachable block");
600 U.set(Undef);
601 }
Davide Italiano744c3c32018-12-12 23:32:35 +0000602 auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I);
603 if (!DVI)
604 continue;
605 auto Key = DeadDebugMap.find({DVI->getVariable(), DVI->getExpression()});
606 if (Key != DeadDebugMap.end())
607 continue;
608 DeadDebugMap[{DVI->getVariable(), DVI->getExpression()}] = DVI;
609 DeadDebugInst.push_back(DVI);
Serguei Katkova757d652018-01-12 07:24:43 +0000610 }
611
Davide Italiano744c3c32018-12-12 23:32:35 +0000612 // After the loop has been deleted all the values defined and modified
613 // inside the loop are going to be unavailable.
614 // Since debug values in the loop have been deleted, inserting an undef
615 // dbg.value truncates the range of any dbg.value before the loop where the
616 // loop used to be. This is particularly important for constant values.
617 DIBuilder DIB(*ExitBlock->getModule());
618 for (auto *DVI : DeadDebugInst)
619 DIB.insertDbgValueIntrinsic(
620 UndefValue::get(DVI->getType()), DVI->getVariable(),
621 DVI->getExpression(), DVI->getDebugLoc(), ExitBlock->getFirstNonPHI());
622
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000623 // Remove the block from the reference counting scheme, so that we can
624 // delete it freely later.
625 for (auto *Block : L->blocks())
626 Block->dropAllReferences();
627
628 if (LI) {
629 // Erase the instructions and the blocks without having to worry
630 // about ordering because we already dropped the references.
631 // NOTE: This iteration is safe because erasing the block does not remove
632 // its entry from the loop's block list. We do that in the next section.
633 for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end();
634 LpI != LpE; ++LpI)
635 (*LpI)->eraseFromParent();
636
637 // Finally, the blocks from loopinfo. This has to happen late because
638 // otherwise our loop iterators won't work.
639
640 SmallPtrSet<BasicBlock *, 8> blocks;
641 blocks.insert(L->block_begin(), L->block_end());
642 for (BasicBlock *BB : blocks)
643 LI->removeBlock(BB);
644
645 // The last step is to update LoopInfo now that we've eliminated this loop.
646 LI->erase(L);
647 }
648}
649
Dehao Chen41d72a82016-11-17 01:17:02 +0000650Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) {
651 // Only support loops with a unique exiting block, and a latch.
652 if (!L->getExitingBlock())
653 return None;
654
Hiroshi Inoued24ddcd2018-01-19 10:55:29 +0000655 // Get the branch weights for the loop's backedge.
Dehao Chen41d72a82016-11-17 01:17:02 +0000656 BranchInst *LatchBR =
657 dyn_cast<BranchInst>(L->getLoopLatch()->getTerminator());
658 if (!LatchBR || LatchBR->getNumSuccessors() != 2)
659 return None;
660
661 assert((LatchBR->getSuccessor(0) == L->getHeader() ||
662 LatchBR->getSuccessor(1) == L->getHeader()) &&
663 "At least one edge out of the latch must go to the header");
664
665 // To estimate the number of times the loop body was executed, we want to
666 // know the number of times the backedge was taken, vs. the number of times
667 // we exited the loop.
Dehao Chen41d72a82016-11-17 01:17:02 +0000668 uint64_t TrueVal, FalseVal;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000669 if (!LatchBR->extractProfMetadata(TrueVal, FalseVal))
Dehao Chen41d72a82016-11-17 01:17:02 +0000670 return None;
671
Michael Kupersteinb151a642016-11-30 21:13:57 +0000672 if (!TrueVal || !FalseVal)
673 return 0;
Dehao Chen41d72a82016-11-17 01:17:02 +0000674
Michael Kupersteinb151a642016-11-30 21:13:57 +0000675 // Divide the count of the backedge by the count of the edge exiting the loop,
676 // rounding to nearest.
Dehao Chen41d72a82016-11-17 01:17:02 +0000677 if (LatchBR->getSuccessor(0) == L->getHeader())
Michael Kupersteinb151a642016-11-30 21:13:57 +0000678 return (TrueVal + (FalseVal / 2)) / FalseVal;
Dehao Chen41d72a82016-11-17 01:17:02 +0000679 else
Michael Kupersteinb151a642016-11-30 21:13:57 +0000680 return (FalseVal + (TrueVal / 2)) / TrueVal;
Dehao Chen41d72a82016-11-17 01:17:02 +0000681}
Amara Emersoncf9daa32017-05-09 10:43:25 +0000682
David Green6cb64782018-08-15 10:59:41 +0000683bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
684 ScalarEvolution &SE) {
David Green395b80c2018-08-11 06:57:28 +0000685 Loop *OuterL = InnerLoop->getParentLoop();
686 if (!OuterL)
687 return true;
688
689 // Get the backedge taken count for the inner loop
690 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
691 const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
692 if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
693 !InnerLoopBECountSC->getType()->isIntegerTy())
694 return false;
695
696 // Get whether count is invariant to the outer loop
697 ScalarEvolution::LoopDisposition LD =
698 SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
699 if (LD != ScalarEvolution::LoopInvariant)
700 return false;
701
702 return true;
703}
704
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000705/// Adds a 'fast' flag to floating point operations.
Amara Emersoncf9daa32017-05-09 10:43:25 +0000706static Value *addFastMathFlag(Value *V) {
707 if (isa<FPMathOperator>(V)) {
708 FastMathFlags Flags;
Sanjay Patel629c4112017-11-06 16:27:15 +0000709 Flags.setFast();
Amara Emersoncf9daa32017-05-09 10:43:25 +0000710 cast<Instruction>(V)->setFastMathFlags(Flags);
711 }
712 return V;
713}
714
Vikram TV6594dc32018-09-10 05:05:08 +0000715Value *llvm::createMinMaxOp(IRBuilder<> &Builder,
716 RecurrenceDescriptor::MinMaxRecurrenceKind RK,
717 Value *Left, Value *Right) {
718 CmpInst::Predicate P = CmpInst::ICMP_NE;
719 switch (RK) {
720 default:
721 llvm_unreachable("Unknown min/max recurrence kind");
722 case RecurrenceDescriptor::MRK_UIntMin:
723 P = CmpInst::ICMP_ULT;
724 break;
725 case RecurrenceDescriptor::MRK_UIntMax:
726 P = CmpInst::ICMP_UGT;
727 break;
728 case RecurrenceDescriptor::MRK_SIntMin:
729 P = CmpInst::ICMP_SLT;
730 break;
731 case RecurrenceDescriptor::MRK_SIntMax:
732 P = CmpInst::ICMP_SGT;
733 break;
734 case RecurrenceDescriptor::MRK_FloatMin:
735 P = CmpInst::FCMP_OLT;
736 break;
737 case RecurrenceDescriptor::MRK_FloatMax:
738 P = CmpInst::FCMP_OGT;
739 break;
740 }
741
742 // We only match FP sequences that are 'fast', so we can unconditionally
743 // set it on any generated instructions.
744 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
745 FastMathFlags FMF;
746 FMF.setFast();
747 Builder.setFastMathFlags(FMF);
748
749 Value *Cmp;
750 if (RK == RecurrenceDescriptor::MRK_FloatMin ||
751 RK == RecurrenceDescriptor::MRK_FloatMax)
752 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
753 else
754 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
755
756 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
757 return Select;
758}
759
Simon Pilgrim23c21822018-04-09 15:44:20 +0000760// Helper to generate an ordered reduction.
761Value *
762llvm::getOrderedReduction(IRBuilder<> &Builder, Value *Acc, Value *Src,
763 unsigned Op,
764 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
765 ArrayRef<Value *> RedOps) {
766 unsigned VF = Src->getType()->getVectorNumElements();
767
768 // Extract and apply reduction ops in ascending order:
769 // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
770 Value *Result = Acc;
771 for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
772 Value *Ext =
773 Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
774
775 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
776 Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
777 "bin.rdx");
778 } else {
779 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
780 "Invalid min/max");
Vikram TV6594dc32018-09-10 05:05:08 +0000781 Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext);
Simon Pilgrim23c21822018-04-09 15:44:20 +0000782 }
783
784 if (!RedOps.empty())
785 propagateIRFlags(Result, RedOps);
786 }
787
788 return Result;
789}
790
Amara Emersoncf9daa32017-05-09 10:43:25 +0000791// Helper to generate a log2 shuffle reduction.
Amara Emerson836b0f42017-05-10 09:42:49 +0000792Value *
793llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op,
794 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
795 ArrayRef<Value *> RedOps) {
Amara Emersoncf9daa32017-05-09 10:43:25 +0000796 unsigned VF = Src->getType()->getVectorNumElements();
797 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
798 // and vector ops, reducing the set of values being computed by half each
799 // round.
800 assert(isPowerOf2_32(VF) &&
801 "Reduction emission only supported for pow2 vectors!");
802 Value *TmpVec = Src;
803 SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
804 for (unsigned i = VF; i != 1; i >>= 1) {
805 // Move the upper half of the vector to the lower half.
806 for (unsigned j = 0; j != i / 2; ++j)
807 ShuffleMask[j] = Builder.getInt32(i / 2 + j);
808
809 // Fill the rest of the mask with undef.
810 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
811 UndefValue::get(Builder.getInt32Ty()));
812
813 Value *Shuf = Builder.CreateShuffleVector(
814 TmpVec, UndefValue::get(TmpVec->getType()),
815 ConstantVector::get(ShuffleMask), "rdx.shuf");
816
817 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
818 // Floating point operations had to be 'fast' to enable the reduction.
819 TmpVec = addFastMathFlag(Builder.CreateBinOp((Instruction::BinaryOps)Op,
820 TmpVec, Shuf, "bin.rdx"));
821 } else {
822 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
823 "Invalid min/max");
Vikram TV6594dc32018-09-10 05:05:08 +0000824 TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000825 }
826 if (!RedOps.empty())
827 propagateIRFlags(TmpVec, RedOps);
828 }
829 // The result is in the first element of the vector.
830 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
831}
832
833/// Create a simple vector reduction specified by an opcode and some
834/// flags (if generating min/max reductions).
835Value *llvm::createSimpleTargetReduction(
836 IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode,
837 Value *Src, TargetTransformInfo::ReductionFlags Flags,
838 ArrayRef<Value *> RedOps) {
839 assert(isa<VectorType>(Src->getType()) && "Type must be a vector");
840
841 Value *ScalarUdf = UndefValue::get(Src->getType()->getVectorElementType());
Vikram TV7e98d692018-09-12 01:59:43 +0000842 std::function<Value *()> BuildFunc;
Amara Emersoncf9daa32017-05-09 10:43:25 +0000843 using RD = RecurrenceDescriptor;
844 RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
845 // TODO: Support creating ordered reductions.
Sanjay Patel1ea7b6f2017-12-06 19:11:23 +0000846 FastMathFlags FMFFast;
847 FMFFast.setFast();
Amara Emersoncf9daa32017-05-09 10:43:25 +0000848
849 switch (Opcode) {
850 case Instruction::Add:
851 BuildFunc = [&]() { return Builder.CreateAddReduce(Src); };
852 break;
853 case Instruction::Mul:
854 BuildFunc = [&]() { return Builder.CreateMulReduce(Src); };
855 break;
856 case Instruction::And:
857 BuildFunc = [&]() { return Builder.CreateAndReduce(Src); };
858 break;
859 case Instruction::Or:
860 BuildFunc = [&]() { return Builder.CreateOrReduce(Src); };
861 break;
862 case Instruction::Xor:
863 BuildFunc = [&]() { return Builder.CreateXorReduce(Src); };
864 break;
865 case Instruction::FAdd:
866 BuildFunc = [&]() {
867 auto Rdx = Builder.CreateFAddReduce(ScalarUdf, Src);
Sanjay Patel1ea7b6f2017-12-06 19:11:23 +0000868 cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000869 return Rdx;
870 };
871 break;
872 case Instruction::FMul:
873 BuildFunc = [&]() {
874 auto Rdx = Builder.CreateFMulReduce(ScalarUdf, Src);
Sanjay Patel1ea7b6f2017-12-06 19:11:23 +0000875 cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000876 return Rdx;
877 };
878 break;
879 case Instruction::ICmp:
880 if (Flags.IsMaxOp) {
881 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
882 BuildFunc = [&]() {
883 return Builder.CreateIntMaxReduce(Src, Flags.IsSigned);
884 };
885 } else {
886 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
887 BuildFunc = [&]() {
888 return Builder.CreateIntMinReduce(Src, Flags.IsSigned);
889 };
890 }
891 break;
892 case Instruction::FCmp:
893 if (Flags.IsMaxOp) {
894 MinMaxKind = RD::MRK_FloatMax;
895 BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); };
896 } else {
897 MinMaxKind = RD::MRK_FloatMin;
898 BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); };
899 }
900 break;
901 default:
902 llvm_unreachable("Unhandled opcode");
903 break;
904 }
905 if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags))
906 return BuildFunc();
907 return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps);
908}
909
910/// Create a vector reduction using a given recurrence descriptor.
Sanjay Patel3e069f52017-12-06 19:37:00 +0000911Value *llvm::createTargetReduction(IRBuilder<> &B,
Amara Emersoncf9daa32017-05-09 10:43:25 +0000912 const TargetTransformInfo *TTI,
913 RecurrenceDescriptor &Desc, Value *Src,
914 bool NoNaN) {
915 // TODO: Support in-order reductions based on the recurrence descriptor.
Sanjay Patel3e069f52017-12-06 19:37:00 +0000916 using RD = RecurrenceDescriptor;
917 RD::RecurrenceKind RecKind = Desc.getRecurrenceKind();
Amara Emersoncf9daa32017-05-09 10:43:25 +0000918 TargetTransformInfo::ReductionFlags Flags;
919 Flags.NoNaN = NoNaN;
Amara Emersoncf9daa32017-05-09 10:43:25 +0000920 switch (RecKind) {
Sanjay Patel3e069f52017-12-06 19:37:00 +0000921 case RD::RK_FloatAdd:
922 return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags);
923 case RD::RK_FloatMult:
924 return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags);
925 case RD::RK_IntegerAdd:
926 return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags);
927 case RD::RK_IntegerMult:
928 return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags);
929 case RD::RK_IntegerAnd:
930 return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags);
931 case RD::RK_IntegerOr:
932 return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags);
933 case RD::RK_IntegerXor:
934 return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags);
935 case RD::RK_IntegerMinMax: {
936 RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind();
937 Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax);
938 Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin);
939 return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000940 }
Sanjay Patel3e069f52017-12-06 19:37:00 +0000941 case RD::RK_FloatMinMax: {
942 Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax;
943 return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000944 }
945 default:
946 llvm_unreachable("Unhandled RecKind");
947 }
948}
949
Dinar Temirbulatova61f4b82017-07-19 10:02:07 +0000950void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
951 auto *VecOp = dyn_cast<Instruction>(I);
952 if (!VecOp)
953 return;
954 auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
955 : dyn_cast<Instruction>(OpValue);
956 if (!Intersection)
957 return;
958 const unsigned Opcode = Intersection->getOpcode();
959 VecOp->copyIRFlags(Intersection);
960 for (auto *V : VL) {
961 auto *Instr = dyn_cast<Instruction>(V);
962 if (!Instr)
963 continue;
964 if (OpValue == nullptr || Opcode == Instr->getOpcode())
965 VecOp->andIRFlags(V);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000966 }
967}