1 //===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines common loop utility functions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Transforms/Utils/LoopUtils.h"
14 #include "llvm/ADT/DenseSet.h"
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/ADT/PriorityWorklist.h"
17 #include "llvm/ADT/ScopeExit.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/BasicAliasAnalysis.h"
23 #include "llvm/Analysis/DomTreeUpdater.h"
24 #include "llvm/Analysis/GlobalsModRef.h"
25 #include "llvm/Analysis/InstructionSimplify.h"
26 #include "llvm/Analysis/LoopInfo.h"
27 #include "llvm/Analysis/LoopPass.h"
28 #include "llvm/Analysis/MemorySSA.h"
29 #include "llvm/Analysis/MemorySSAUpdater.h"
30 #include "llvm/Analysis/MustExecute.h"
31 #include "llvm/Analysis/ScalarEvolution.h"
32 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
33 #include "llvm/Analysis/ScalarEvolutionExpander.h"
34 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
35 #include "llvm/Analysis/TargetTransformInfo.h"
36 #include "llvm/Analysis/ValueTracking.h"
37 #include "llvm/IR/DIBuilder.h"
38 #include "llvm/IR/Dominators.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/IntrinsicInst.h"
41 #include "llvm/IR/MDBuilder.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/IR/Operator.h"
44 #include "llvm/IR/PatternMatch.h"
45 #include "llvm/IR/ValueHandle.h"
46 #include "llvm/InitializePasses.h"
47 #include "llvm/Pass.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/KnownBits.h"
50 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
51 #include "llvm/Transforms/Utils/Local.h"
52 
53 using namespace llvm;
54 using namespace llvm::PatternMatch;
55 
56 static cl::opt<bool> ForceReductionIntrinsic(
57     "force-reduction-intrinsics", cl::Hidden,
58     cl::desc("Force creating reduction intrinsics for testing."),
59     cl::init(false));
60 
61 #define DEBUG_TYPE "loop-utils"
62 
63 static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced";
64 static const char *LLVMLoopDisableLICM = "llvm.licm.disable";
65 
66 bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
67                                    MemorySSAUpdater *MSSAU,
68                                    bool PreserveLCSSA) {
69   bool Changed = false;
70 
71   // We re-use a vector for the in-loop predecesosrs.
72   SmallVector<BasicBlock *, 4> InLoopPredecessors;
73 
74   auto RewriteExit = [&](BasicBlock *BB) {
75     assert(InLoopPredecessors.empty() &&
76            "Must start with an empty predecessors list!");
77     auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
78 
79     // See if there are any non-loop predecessors of this exit block and
80     // keep track of the in-loop predecessors.
81     bool IsDedicatedExit = true;
82     for (auto *PredBB : predecessors(BB))
83       if (L->contains(PredBB)) {
84         if (isa<IndirectBrInst>(PredBB->getTerminator()))
85           // We cannot rewrite exiting edges from an indirectbr.
86           return false;
87         if (isa<CallBrInst>(PredBB->getTerminator()))
88           // We cannot rewrite exiting edges from a callbr.
89           return false;
90 
91         InLoopPredecessors.push_back(PredBB);
92       } else {
93         IsDedicatedExit = false;
94       }
95 
96     assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
97 
98     // Nothing to do if this is already a dedicated exit.
99     if (IsDedicatedExit)
100       return false;
101 
102     auto *NewExitBB = SplitBlockPredecessors(
103         BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA);
104 
105     if (!NewExitBB)
106       LLVM_DEBUG(
107           dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
108                  << *L << "\n");
109     else
110       LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
111                         << NewExitBB->getName() << "\n");
112     return true;
113   };
114 
115   // Walk the exit blocks directly rather than building up a data structure for
116   // them, but only visit each one once.
117   SmallPtrSet<BasicBlock *, 4> Visited;
118   for (auto *BB : L->blocks())
119     for (auto *SuccBB : successors(BB)) {
120       // We're looking for exit blocks so skip in-loop successors.
121       if (L->contains(SuccBB))
122         continue;
123 
124       // Visit each exit block exactly once.
125       if (!Visited.insert(SuccBB).second)
126         continue;
127 
128       Changed |= RewriteExit(SuccBB);
129     }
130 
131   return Changed;
132 }
133 
134 /// Returns the instructions that use values defined in the loop.
135 SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
136   SmallVector<Instruction *, 8> UsedOutside;
137 
138   for (auto *Block : L->getBlocks())
139     // FIXME: I believe that this could use copy_if if the Inst reference could
140     // be adapted into a pointer.
141     for (auto &Inst : *Block) {
142       auto Users = Inst.users();
143       if (any_of(Users, [&](User *U) {
144             auto *Use = cast<Instruction>(U);
145             return !L->contains(Use->getParent());
146           }))
147         UsedOutside.push_back(&Inst);
148     }
149 
150   return UsedOutside;
151 }
152 
153 void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
154   // By definition, all loop passes need the LoopInfo analysis and the
155   // Dominator tree it depends on. Because they all participate in the loop
156   // pass manager, they must also preserve these.
157   AU.addRequired<DominatorTreeWrapperPass>();
158   AU.addPreserved<DominatorTreeWrapperPass>();
159   AU.addRequired<LoopInfoWrapperPass>();
160   AU.addPreserved<LoopInfoWrapperPass>();
161 
162   // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
163   // here because users shouldn't directly get them from this header.
164   extern char &LoopSimplifyID;
165   extern char &LCSSAID;
166   AU.addRequiredID(LoopSimplifyID);
167   AU.addPreservedID(LoopSimplifyID);
168   AU.addRequiredID(LCSSAID);
169   AU.addPreservedID(LCSSAID);
170   // This is used in the LPPassManager to perform LCSSA verification on passes
171   // which preserve lcssa form
172   AU.addRequired<LCSSAVerificationPass>();
173   AU.addPreserved<LCSSAVerificationPass>();
174 
175   // Loop passes are designed to run inside of a loop pass manager which means
176   // that any function analyses they require must be required by the first loop
177   // pass in the manager (so that it is computed before the loop pass manager
178   // runs) and preserved by all loop pasess in the manager. To make this
179   // reasonably robust, the set needed for most loop passes is maintained here.
180   // If your loop pass requires an analysis not listed here, you will need to
181   // carefully audit the loop pass manager nesting structure that results.
182   AU.addRequired<AAResultsWrapperPass>();
183   AU.addPreserved<AAResultsWrapperPass>();
184   AU.addPreserved<BasicAAWrapperPass>();
185   AU.addPreserved<GlobalsAAWrapperPass>();
186   AU.addPreserved<SCEVAAWrapperPass>();
187   AU.addRequired<ScalarEvolutionWrapperPass>();
188   AU.addPreserved<ScalarEvolutionWrapperPass>();
189   // FIXME: When all loop passes preserve MemorySSA, it can be required and
190   // preserved here instead of the individual handling in each pass.
191 }
192 
193 /// Manually defined generic "LoopPass" dependency initialization. This is used
194 /// to initialize the exact set of passes from above in \c
195 /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
196 /// with:
197 ///
198 ///   INITIALIZE_PASS_DEPENDENCY(LoopPass)
199 ///
200 /// As-if "LoopPass" were a pass.
201 void llvm::initializeLoopPassPass(PassRegistry &Registry) {
202   INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
203   INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
204   INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
205   INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
206   INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
207   INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
208   INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
209   INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
210   INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
211   INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
212 }
213 
214 /// Create MDNode for input string.
215 static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) {
216   LLVMContext &Context = TheLoop->getHeader()->getContext();
217   Metadata *MDs[] = {
218       MDString::get(Context, Name),
219       ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))};
220   return MDNode::get(Context, MDs);
221 }
222 
223 /// Set input string into loop metadata by keeping other values intact.
224 /// If the string is already in loop metadata update value if it is
225 /// different.
226 void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *StringMD,
227                                    unsigned V) {
228   SmallVector<Metadata *, 4> MDs(1);
229   // If the loop already has metadata, retain it.
230   MDNode *LoopID = TheLoop->getLoopID();
231   if (LoopID) {
232     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
233       MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
234       // If it is of form key = value, try to parse it.
235       if (Node->getNumOperands() == 2) {
236         MDString *S = dyn_cast<MDString>(Node->getOperand(0));
237         if (S && S->getString().equals(StringMD)) {
238           ConstantInt *IntMD =
239               mdconst::extract_or_null<ConstantInt>(Node->getOperand(1));
240           if (IntMD && IntMD->getSExtValue() == V)
241             // It is already in place. Do nothing.
242             return;
243           // We need to update the value, so just skip it here and it will
244           // be added after copying other existed nodes.
245           continue;
246         }
247       }
248       MDs.push_back(Node);
249     }
250   }
251   // Add new metadata.
252   MDs.push_back(createStringMetadata(TheLoop, StringMD, V));
253   // Replace current metadata node with new one.
254   LLVMContext &Context = TheLoop->getHeader()->getContext();
255   MDNode *NewLoopID = MDNode::get(Context, MDs);
256   // Set operand 0 to refer to the loop id itself.
257   NewLoopID->replaceOperandWith(0, NewLoopID);
258   TheLoop->setLoopID(NewLoopID);
259 }
260 
261 /// Find string metadata for loop
262 ///
263 /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
264 /// operand or null otherwise.  If the string metadata is not found return
265 /// Optional's not-a-value.
266 Optional<const MDOperand *> llvm::findStringMetadataForLoop(const Loop *TheLoop,
267                                                             StringRef Name) {
268   MDNode *MD = findOptionMDForLoop(TheLoop, Name);
269   if (!MD)
270     return None;
271   switch (MD->getNumOperands()) {
272   case 1:
273     return nullptr;
274   case 2:
275     return &MD->getOperand(1);
276   default:
277     llvm_unreachable("loop metadata has 0 or 1 operand");
278   }
279 }
280 
281 static Optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop,
282                                                    StringRef Name) {
283   MDNode *MD = findOptionMDForLoop(TheLoop, Name);
284   if (!MD)
285     return None;
286   switch (MD->getNumOperands()) {
287   case 1:
288     // When the value is absent it is interpreted as 'attribute set'.
289     return true;
290   case 2:
291     if (ConstantInt *IntMD =
292             mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get()))
293       return IntMD->getZExtValue();
294     return true;
295   }
296   llvm_unreachable("unexpected number of options");
297 }
298 
299 static bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) {
300   return getOptionalBoolLoopAttribute(TheLoop, Name).getValueOr(false);
301 }
302 
303 llvm::Optional<int> llvm::getOptionalIntLoopAttribute(Loop *TheLoop,
304                                                       StringRef Name) {
305   const MDOperand *AttrMD =
306       findStringMetadataForLoop(TheLoop, Name).getValueOr(nullptr);
307   if (!AttrMD)
308     return None;
309 
310   ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
311   if (!IntMD)
312     return None;
313 
314   return IntMD->getSExtValue();
315 }
316 
317 Optional<MDNode *> llvm::makeFollowupLoopID(
318     MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
319     const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
320   if (!OrigLoopID) {
321     if (AlwaysNew)
322       return nullptr;
323     return None;
324   }
325 
326   assert(OrigLoopID->getOperand(0) == OrigLoopID);
327 
328   bool InheritAllAttrs = !InheritOptionsExceptPrefix;
329   bool InheritSomeAttrs =
330       InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
331   SmallVector<Metadata *, 8> MDs;
332   MDs.push_back(nullptr);
333 
334   bool Changed = false;
335   if (InheritAllAttrs || InheritSomeAttrs) {
336     for (const MDOperand &Existing : drop_begin(OrigLoopID->operands(), 1)) {
337       MDNode *Op = cast<MDNode>(Existing.get());
338 
339       auto InheritThisAttribute = [InheritSomeAttrs,
340                                    InheritOptionsExceptPrefix](MDNode *Op) {
341         if (!InheritSomeAttrs)
342           return false;
343 
344         // Skip malformatted attribute metadata nodes.
345         if (Op->getNumOperands() == 0)
346           return true;
347         Metadata *NameMD = Op->getOperand(0).get();
348         if (!isa<MDString>(NameMD))
349           return true;
350         StringRef AttrName = cast<MDString>(NameMD)->getString();
351 
352         // Do not inherit excluded attributes.
353         return !AttrName.startswith(InheritOptionsExceptPrefix);
354       };
355 
356       if (InheritThisAttribute(Op))
357         MDs.push_back(Op);
358       else
359         Changed = true;
360     }
361   } else {
362     // Modified if we dropped at least one attribute.
363     Changed = OrigLoopID->getNumOperands() > 1;
364   }
365 
366   bool HasAnyFollowup = false;
367   for (StringRef OptionName : FollowupOptions) {
368     MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName);
369     if (!FollowupNode)
370       continue;
371 
372     HasAnyFollowup = true;
373     for (const MDOperand &Option : drop_begin(FollowupNode->operands(), 1)) {
374       MDs.push_back(Option.get());
375       Changed = true;
376     }
377   }
378 
379   // Attributes of the followup loop not specified explicity, so signal to the
380   // transformation pass to add suitable attributes.
381   if (!AlwaysNew && !HasAnyFollowup)
382     return None;
383 
384   // If no attributes were added or remove, the previous loop Id can be reused.
385   if (!AlwaysNew && !Changed)
386     return OrigLoopID;
387 
388   // No attributes is equivalent to having no !llvm.loop metadata at all.
389   if (MDs.size() == 1)
390     return nullptr;
391 
392   // Build the new loop ID.
393   MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs);
394   FollowupLoopID->replaceOperandWith(0, FollowupLoopID);
395   return FollowupLoopID;
396 }
397 
398 bool llvm::hasDisableAllTransformsHint(const Loop *L) {
399   return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced);
400 }
401 
402 bool llvm::hasDisableLICMTransformsHint(const Loop *L) {
403   return getBooleanLoopAttribute(L, LLVMLoopDisableLICM);
404 }
405 
406 TransformationMode llvm::hasUnrollTransformation(Loop *L) {
407   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable"))
408     return TM_SuppressedByUser;
409 
410   Optional<int> Count =
411       getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
412   if (Count.hasValue())
413     return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
414 
415   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
416     return TM_ForcedByUser;
417 
418   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full"))
419     return TM_ForcedByUser;
420 
421   if (hasDisableAllTransformsHint(L))
422     return TM_Disable;
423 
424   return TM_Unspecified;
425 }
426 
427 TransformationMode llvm::hasUnrollAndJamTransformation(Loop *L) {
428   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable"))
429     return TM_SuppressedByUser;
430 
431   Optional<int> Count =
432       getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
433   if (Count.hasValue())
434     return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
435 
436   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
437     return TM_ForcedByUser;
438 
439   if (hasDisableAllTransformsHint(L))
440     return TM_Disable;
441 
442   return TM_Unspecified;
443 }
444 
445 TransformationMode llvm::hasVectorizeTransformation(Loop *L) {
446   Optional<bool> Enable =
447       getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable");
448 
449   if (Enable == false)
450     return TM_SuppressedByUser;
451 
452   Optional<int> VectorizeWidth =
453       getOptionalIntLoopAttribute(L, "llvm.loop.vectorize.width");
454   Optional<int> InterleaveCount =
455       getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count");
456 
457   // 'Forcing' vector width and interleave count to one effectively disables
458   // this tranformation.
459   if (Enable == true && VectorizeWidth == 1 && InterleaveCount == 1)
460     return TM_SuppressedByUser;
461 
462   if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
463     return TM_Disable;
464 
465   if (Enable == true)
466     return TM_ForcedByUser;
467 
468   if (VectorizeWidth == 1 && InterleaveCount == 1)
469     return TM_Disable;
470 
471   if (VectorizeWidth > 1 || InterleaveCount > 1)
472     return TM_Enable;
473 
474   if (hasDisableAllTransformsHint(L))
475     return TM_Disable;
476 
477   return TM_Unspecified;
478 }
479 
480 TransformationMode llvm::hasDistributeTransformation(Loop *L) {
481   if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable"))
482     return TM_ForcedByUser;
483 
484   if (hasDisableAllTransformsHint(L))
485     return TM_Disable;
486 
487   return TM_Unspecified;
488 }
489 
490 TransformationMode llvm::hasLICMVersioningTransformation(Loop *L) {
491   if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable"))
492     return TM_SuppressedByUser;
493 
494   if (hasDisableAllTransformsHint(L))
495     return TM_Disable;
496 
497   return TM_Unspecified;
498 }
499 
500 /// Does a BFS from a given node to all of its children inside a given loop.
501 /// The returned vector of nodes includes the starting point.
502 SmallVector<DomTreeNode *, 16>
503 llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
504   SmallVector<DomTreeNode *, 16> Worklist;
505   auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
506     // Only include subregions in the top level loop.
507     BasicBlock *BB = DTN->getBlock();
508     if (CurLoop->contains(BB))
509       Worklist.push_back(DTN);
510   };
511 
512   AddRegionToWorklist(N);
513 
514   for (size_t I = 0; I < Worklist.size(); I++)
515     for (DomTreeNode *Child : Worklist[I]->getChildren())
516       AddRegionToWorklist(Child);
517 
518   return Worklist;
519 }
520 
521 void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE,
522                           LoopInfo *LI, MemorySSA *MSSA) {
523   assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
524   auto *Preheader = L->getLoopPreheader();
525   assert(Preheader && "Preheader should exist!");
526 
527   std::unique_ptr<MemorySSAUpdater> MSSAU;
528   if (MSSA)
529     MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
530 
531   // Now that we know the removal is safe, remove the loop by changing the
532   // branch from the preheader to go to the single exit block.
533   //
534   // Because we're deleting a large chunk of code at once, the sequence in which
535   // we remove things is very important to avoid invalidation issues.
536 
537   // Tell ScalarEvolution that the loop is deleted. Do this before
538   // deleting the loop so that ScalarEvolution can look at the loop
539   // to determine what it needs to clean up.
540   if (SE)
541     SE->forgetLoop(L);
542 
543   auto *ExitBlock = L->getUniqueExitBlock();
544   assert(ExitBlock && "Should have a unique exit block!");
545   assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
546 
547   auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
548   assert(OldBr && "Preheader must end with a branch");
549   assert(OldBr->isUnconditional() && "Preheader must have a single successor");
550   // Connect the preheader to the exit block. Keep the old edge to the header
551   // around to perform the dominator tree update in two separate steps
552   // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
553   // preheader -> header.
554   //
555   //
556   // 0.  Preheader          1.  Preheader           2.  Preheader
557   //        |                    |   |                   |
558   //        V                    |   V                   |
559   //      Header <--\            | Header <--\           | Header <--\
560   //       |  |     |            |  |  |     |           |  |  |     |
561   //       |  V     |            |  |  V     |           |  |  V     |
562   //       | Body --/            |  | Body --/           |  | Body --/
563   //       V                     V  V                    V  V
564   //      Exit                   Exit                    Exit
565   //
566   // By doing this is two separate steps we can perform the dominator tree
567   // update without using the batch update API.
568   //
569   // Even when the loop is never executed, we cannot remove the edge from the
570   // source block to the exit block. Consider the case where the unexecuted loop
571   // branches back to an outer loop. If we deleted the loop and removed the edge
572   // coming to this inner loop, this will break the outer loop structure (by
573   // deleting the backedge of the outer loop). If the outer loop is indeed a
574   // non-loop, it will be deleted in a future iteration of loop deletion pass.
575   IRBuilder<> Builder(OldBr);
576   Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
577   // Remove the old branch. The conditional branch becomes a new terminator.
578   OldBr->eraseFromParent();
579 
580   // Rewrite phis in the exit block to get their inputs from the Preheader
581   // instead of the exiting block.
582   for (PHINode &P : ExitBlock->phis()) {
583     // Set the zero'th element of Phi to be from the preheader and remove all
584     // other incoming values. Given the loop has dedicated exits, all other
585     // incoming values must be from the exiting blocks.
586     int PredIndex = 0;
587     P.setIncomingBlock(PredIndex, Preheader);
588     // Removes all incoming values from all other exiting blocks (including
589     // duplicate values from an exiting block).
590     // Nuke all entries except the zero'th entry which is the preheader entry.
591     // NOTE! We need to remove Incoming Values in the reverse order as done
592     // below, to keep the indices valid for deletion (removeIncomingValues
593     // updates getNumIncomingValues and shifts all values down into the operand
594     // being deleted).
595     for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
596       P.removeIncomingValue(e - i, false);
597 
598     assert((P.getNumIncomingValues() == 1 &&
599             P.getIncomingBlock(PredIndex) == Preheader) &&
600            "Should have exactly one value and that's from the preheader!");
601   }
602 
603   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
604   if (DT) {
605     DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}});
606     if (MSSA) {
607       MSSAU->applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}}, *DT);
608       if (VerifyMemorySSA)
609         MSSA->verifyMemorySSA();
610     }
611   }
612 
613   // Disconnect the loop body by branching directly to its exit.
614   Builder.SetInsertPoint(Preheader->getTerminator());
615   Builder.CreateBr(ExitBlock);
616   // Remove the old branch.
617   Preheader->getTerminator()->eraseFromParent();
618 
619   if (DT) {
620     DTU.applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}});
621     if (MSSA) {
622       MSSAU->applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}},
623                           *DT);
624       if (VerifyMemorySSA)
625         MSSA->verifyMemorySSA();
626       SmallSetVector<BasicBlock *, 8> DeadBlockSet(L->block_begin(),
627                                                    L->block_end());
628       MSSAU->removeBlocks(DeadBlockSet);
629     }
630   }
631 
632   // Use a map to unique and a vector to guarantee deterministic ordering.
633   llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet;
634   llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst;
635 
636   // Given LCSSA form is satisfied, we should not have users of instructions
637   // within the dead loop outside of the loop. However, LCSSA doesn't take
638   // unreachable uses into account. We handle them here.
639   // We could do it after drop all references (in this case all users in the
640   // loop will be already eliminated and we have less work to do but according
641   // to API doc of User::dropAllReferences only valid operation after dropping
642   // references, is deletion. So let's substitute all usages of
643   // instruction from the loop with undef value of corresponding type first.
644   for (auto *Block : L->blocks())
645     for (Instruction &I : *Block) {
646       auto *Undef = UndefValue::get(I.getType());
647       for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) {
648         Use &U = *UI;
649         ++UI;
650         if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
651           if (L->contains(Usr->getParent()))
652             continue;
653         // If we have a DT then we can check that uses outside a loop only in
654         // unreachable block.
655         if (DT)
656           assert(!DT->isReachableFromEntry(U) &&
657                  "Unexpected user in reachable block");
658         U.set(Undef);
659       }
660       auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I);
661       if (!DVI)
662         continue;
663       auto Key = DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()});
664       if (Key != DeadDebugSet.end())
665         continue;
666       DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()});
667       DeadDebugInst.push_back(DVI);
668     }
669 
670   // After the loop has been deleted all the values defined and modified
671   // inside the loop are going to be unavailable.
672   // Since debug values in the loop have been deleted, inserting an undef
673   // dbg.value truncates the range of any dbg.value before the loop where the
674   // loop used to be. This is particularly important for constant values.
675   DIBuilder DIB(*ExitBlock->getModule());
676   Instruction *InsertDbgValueBefore = ExitBlock->getFirstNonPHI();
677   assert(InsertDbgValueBefore &&
678          "There should be a non-PHI instruction in exit block, else these "
679          "instructions will have no parent.");
680   for (auto *DVI : DeadDebugInst)
681     DIB.insertDbgValueIntrinsic(UndefValue::get(Builder.getInt32Ty()),
682                                 DVI->getVariable(), DVI->getExpression(),
683                                 DVI->getDebugLoc(), InsertDbgValueBefore);
684 
685   // Remove the block from the reference counting scheme, so that we can
686   // delete it freely later.
687   for (auto *Block : L->blocks())
688     Block->dropAllReferences();
689 
690   if (MSSA && VerifyMemorySSA)
691     MSSA->verifyMemorySSA();
692 
693   if (LI) {
694     // Erase the instructions and the blocks without having to worry
695     // about ordering because we already dropped the references.
696     // NOTE: This iteration is safe because erasing the block does not remove
697     // its entry from the loop's block list.  We do that in the next section.
698     for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end();
699          LpI != LpE; ++LpI)
700       (*LpI)->eraseFromParent();
701 
702     // Finally, the blocks from loopinfo.  This has to happen late because
703     // otherwise our loop iterators won't work.
704 
705     SmallPtrSet<BasicBlock *, 8> blocks;
706     blocks.insert(L->block_begin(), L->block_end());
707     for (BasicBlock *BB : blocks)
708       LI->removeBlock(BB);
709 
710     // The last step is to update LoopInfo now that we've eliminated this loop.
711     // Note: LoopInfo::erase remove the given loop and relink its subloops with
712     // its parent. While removeLoop/removeChildLoop remove the given loop but
713     // not relink its subloops, which is what we want.
714     if (Loop *ParentLoop = L->getParentLoop()) {
715       Loop::iterator I = find(ParentLoop->begin(), ParentLoop->end(), L);
716       assert(I != ParentLoop->end() && "Couldn't find loop");
717       ParentLoop->removeChildLoop(I);
718     } else {
719       Loop::iterator I = find(LI->begin(), LI->end(), L);
720       assert(I != LI->end() && "Couldn't find loop");
721       LI->removeLoop(I);
722     }
723     LI->destroy(L);
724   }
725 }
726 
727 /// Checks if \p L has single exit through latch block except possibly
728 /// "deoptimizing" exits. Returns branch instruction terminating the loop
729 /// latch if above check is successful, nullptr otherwise.
730 static BranchInst *getExpectedExitLoopLatchBranch(Loop *L) {
731   BasicBlock *Latch = L->getLoopLatch();
732   if (!Latch)
733     return nullptr;
734 
735   BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator());
736   if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch))
737     return nullptr;
738 
739   assert((LatchBR->getSuccessor(0) == L->getHeader() ||
740           LatchBR->getSuccessor(1) == L->getHeader()) &&
741          "At least one edge out of the latch must go to the header");
742 
743   SmallVector<BasicBlock *, 4> ExitBlocks;
744   L->getUniqueNonLatchExitBlocks(ExitBlocks);
745   if (any_of(ExitBlocks, [](const BasicBlock *EB) {
746         return !EB->getTerminatingDeoptimizeCall();
747       }))
748     return nullptr;
749 
750   return LatchBR;
751 }
752 
753 Optional<unsigned>
754 llvm::getLoopEstimatedTripCount(Loop *L,
755                                 unsigned *EstimatedLoopInvocationWeight) {
756   // Support loops with an exiting latch and other existing exists only
757   // deoptimize.
758   BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
759   if (!LatchBranch)
760     return None;
761 
762   // To estimate the number of times the loop body was executed, we want to
763   // know the number of times the backedge was taken, vs. the number of times
764   // we exited the loop.
765   uint64_t BackedgeTakenWeight, LatchExitWeight;
766   if (!LatchBranch->extractProfMetadata(BackedgeTakenWeight, LatchExitWeight))
767     return None;
768 
769   if (LatchBranch->getSuccessor(0) != L->getHeader())
770     std::swap(BackedgeTakenWeight, LatchExitWeight);
771 
772   if (!LatchExitWeight)
773     return None;
774 
775   if (EstimatedLoopInvocationWeight)
776     *EstimatedLoopInvocationWeight = LatchExitWeight;
777 
778   // Estimated backedge taken count is a ratio of the backedge taken weight by
779   // the weight of the edge exiting the loop, rounded to nearest.
780   uint64_t BackedgeTakenCount =
781       llvm::divideNearest(BackedgeTakenWeight, LatchExitWeight);
782   // Estimated trip count is one plus estimated backedge taken count.
783   return BackedgeTakenCount + 1;
784 }
785 
786 bool llvm::setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount,
787                                      unsigned EstimatedloopInvocationWeight) {
788   // Support loops with an exiting latch and other existing exists only
789   // deoptimize.
790   BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
791   if (!LatchBranch)
792     return false;
793 
794   // Calculate taken and exit weights.
795   unsigned LatchExitWeight = 0;
796   unsigned BackedgeTakenWeight = 0;
797 
798   if (EstimatedTripCount > 0) {
799     LatchExitWeight = EstimatedloopInvocationWeight;
800     BackedgeTakenWeight = (EstimatedTripCount - 1) * LatchExitWeight;
801   }
802 
803   // Make a swap if back edge is taken when condition is "false".
804   if (LatchBranch->getSuccessor(0) != L->getHeader())
805     std::swap(BackedgeTakenWeight, LatchExitWeight);
806 
807   MDBuilder MDB(LatchBranch->getContext());
808 
809   // Set/Update profile metadata.
810   LatchBranch->setMetadata(
811       LLVMContext::MD_prof,
812       MDB.createBranchWeights(BackedgeTakenWeight, LatchExitWeight));
813 
814   return true;
815 }
816 
817 bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
818                                               ScalarEvolution &SE) {
819   Loop *OuterL = InnerLoop->getParentLoop();
820   if (!OuterL)
821     return true;
822 
823   // Get the backedge taken count for the inner loop
824   BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
825   const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
826   if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
827       !InnerLoopBECountSC->getType()->isIntegerTy())
828     return false;
829 
830   // Get whether count is invariant to the outer loop
831   ScalarEvolution::LoopDisposition LD =
832       SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
833   if (LD != ScalarEvolution::LoopInvariant)
834     return false;
835 
836   return true;
837 }
838 
839 Value *llvm::createMinMaxOp(IRBuilderBase &Builder,
840                             RecurrenceDescriptor::MinMaxRecurrenceKind RK,
841                             Value *Left, Value *Right) {
842   CmpInst::Predicate P = CmpInst::ICMP_NE;
843   switch (RK) {
844   default:
845     llvm_unreachable("Unknown min/max recurrence kind");
846   case RecurrenceDescriptor::MRK_UIntMin:
847     P = CmpInst::ICMP_ULT;
848     break;
849   case RecurrenceDescriptor::MRK_UIntMax:
850     P = CmpInst::ICMP_UGT;
851     break;
852   case RecurrenceDescriptor::MRK_SIntMin:
853     P = CmpInst::ICMP_SLT;
854     break;
855   case RecurrenceDescriptor::MRK_SIntMax:
856     P = CmpInst::ICMP_SGT;
857     break;
858   case RecurrenceDescriptor::MRK_FloatMin:
859     P = CmpInst::FCMP_OLT;
860     break;
861   case RecurrenceDescriptor::MRK_FloatMax:
862     P = CmpInst::FCMP_OGT;
863     break;
864   }
865 
866   // We only match FP sequences that are 'fast', so we can unconditionally
867   // set it on any generated instructions.
868   IRBuilderBase::FastMathFlagGuard FMFG(Builder);
869   FastMathFlags FMF;
870   FMF.setFast();
871   Builder.setFastMathFlags(FMF);
872 
873   Value *Cmp;
874   if (RK == RecurrenceDescriptor::MRK_FloatMin ||
875       RK == RecurrenceDescriptor::MRK_FloatMax)
876     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
877   else
878     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
879 
880   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
881   return Select;
882 }
883 
884 // Helper to generate an ordered reduction.
885 Value *
886 llvm::getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src,
887                           unsigned Op,
888                           RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
889                           ArrayRef<Value *> RedOps) {
890   unsigned VF = cast<VectorType>(Src->getType())->getNumElements();
891 
892   // Extract and apply reduction ops in ascending order:
893   // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
894   Value *Result = Acc;
895   for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
896     Value *Ext =
897         Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
898 
899     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
900       Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
901                                    "bin.rdx");
902     } else {
903       assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
904              "Invalid min/max");
905       Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext);
906     }
907 
908     if (!RedOps.empty())
909       propagateIRFlags(Result, RedOps);
910   }
911 
912   return Result;
913 }
914 
915 // Helper to generate a log2 shuffle reduction.
916 Value *
917 llvm::getShuffleReduction(IRBuilderBase &Builder, Value *Src, unsigned Op,
918                           RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
919                           ArrayRef<Value *> RedOps) {
920   unsigned VF = cast<VectorType>(Src->getType())->getNumElements();
921   // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
922   // and vector ops, reducing the set of values being computed by half each
923   // round.
924   assert(isPowerOf2_32(VF) &&
925          "Reduction emission only supported for pow2 vectors!");
926   Value *TmpVec = Src;
927   SmallVector<int, 32> ShuffleMask(VF);
928   for (unsigned i = VF; i != 1; i >>= 1) {
929     // Move the upper half of the vector to the lower half.
930     for (unsigned j = 0; j != i / 2; ++j)
931       ShuffleMask[j] = i / 2 + j;
932 
933     // Fill the rest of the mask with undef.
934     std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), -1);
935 
936     Value *Shuf = Builder.CreateShuffleVector(
937         TmpVec, UndefValue::get(TmpVec->getType()), ShuffleMask, "rdx.shuf");
938 
939     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
940       // The builder propagates its fast-math-flags setting.
941       TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
942                                    "bin.rdx");
943     } else {
944       assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
945              "Invalid min/max");
946       TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf);
947     }
948     if (!RedOps.empty())
949       propagateIRFlags(TmpVec, RedOps);
950 
951     // We may compute the reassociated scalar ops in a way that does not
952     // preserve nsw/nuw etc. Conservatively, drop those flags.
953     if (auto *ReductionInst = dyn_cast<Instruction>(TmpVec))
954       ReductionInst->dropPoisonGeneratingFlags();
955   }
956   // The result is in the first element of the vector.
957   return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
958 }
959 
960 /// Create a simple vector reduction specified by an opcode and some
961 /// flags (if generating min/max reductions).
962 Value *llvm::createSimpleTargetReduction(
963     IRBuilderBase &Builder, const TargetTransformInfo *TTI, unsigned Opcode,
964     Value *Src, TargetTransformInfo::ReductionFlags Flags,
965     ArrayRef<Value *> RedOps) {
966   auto *SrcVTy = cast<VectorType>(Src->getType());
967 
968   std::function<Value *()> BuildFunc;
969   using RD = RecurrenceDescriptor;
970   RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
971 
972   switch (Opcode) {
973   case Instruction::Add:
974     BuildFunc = [&]() { return Builder.CreateAddReduce(Src); };
975     break;
976   case Instruction::Mul:
977     BuildFunc = [&]() { return Builder.CreateMulReduce(Src); };
978     break;
979   case Instruction::And:
980     BuildFunc = [&]() { return Builder.CreateAndReduce(Src); };
981     break;
982   case Instruction::Or:
983     BuildFunc = [&]() { return Builder.CreateOrReduce(Src); };
984     break;
985   case Instruction::Xor:
986     BuildFunc = [&]() { return Builder.CreateXorReduce(Src); };
987     break;
988   case Instruction::FAdd:
989     BuildFunc = [&]() {
990       auto Rdx = Builder.CreateFAddReduce(
991           Constant::getNullValue(SrcVTy->getElementType()), Src);
992       return Rdx;
993     };
994     break;
995   case Instruction::FMul:
996     BuildFunc = [&]() {
997       Type *Ty = SrcVTy->getElementType();
998       auto Rdx = Builder.CreateFMulReduce(ConstantFP::get(Ty, 1.0), Src);
999       return Rdx;
1000     };
1001     break;
1002   case Instruction::ICmp:
1003     if (Flags.IsMaxOp) {
1004       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
1005       BuildFunc = [&]() {
1006         return Builder.CreateIntMaxReduce(Src, Flags.IsSigned);
1007       };
1008     } else {
1009       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
1010       BuildFunc = [&]() {
1011         return Builder.CreateIntMinReduce(Src, Flags.IsSigned);
1012       };
1013     }
1014     break;
1015   case Instruction::FCmp:
1016     if (Flags.IsMaxOp) {
1017       MinMaxKind = RD::MRK_FloatMax;
1018       BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); };
1019     } else {
1020       MinMaxKind = RD::MRK_FloatMin;
1021       BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); };
1022     }
1023     break;
1024   default:
1025     llvm_unreachable("Unhandled opcode");
1026     break;
1027   }
1028   if (ForceReductionIntrinsic ||
1029       TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags))
1030     return BuildFunc();
1031   return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps);
1032 }
1033 
1034 /// Create a vector reduction using a given recurrence descriptor.
1035 Value *llvm::createTargetReduction(IRBuilderBase &B,
1036                                    const TargetTransformInfo *TTI,
1037                                    RecurrenceDescriptor &Desc, Value *Src,
1038                                    bool NoNaN) {
1039   // TODO: Support in-order reductions based on the recurrence descriptor.
1040   using RD = RecurrenceDescriptor;
1041   RD::RecurrenceKind RecKind = Desc.getRecurrenceKind();
1042   TargetTransformInfo::ReductionFlags Flags;
1043   Flags.NoNaN = NoNaN;
1044 
1045   // All ops in the reduction inherit fast-math-flags from the recurrence
1046   // descriptor.
1047   IRBuilderBase::FastMathFlagGuard FMFGuard(B);
1048   B.setFastMathFlags(Desc.getFastMathFlags());
1049 
1050   switch (RecKind) {
1051   case RD::RK_FloatAdd:
1052     return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags);
1053   case RD::RK_FloatMult:
1054     return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags);
1055   case RD::RK_IntegerAdd:
1056     return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags);
1057   case RD::RK_IntegerMult:
1058     return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags);
1059   case RD::RK_IntegerAnd:
1060     return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags);
1061   case RD::RK_IntegerOr:
1062     return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags);
1063   case RD::RK_IntegerXor:
1064     return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags);
1065   case RD::RK_IntegerMinMax: {
1066     RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind();
1067     Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax);
1068     Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin);
1069     return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags);
1070   }
1071   case RD::RK_FloatMinMax: {
1072     Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax;
1073     return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags);
1074   }
1075   default:
1076     llvm_unreachable("Unhandled RecKind");
1077   }
1078 }
1079 
1080 void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
1081   auto *VecOp = dyn_cast<Instruction>(I);
1082   if (!VecOp)
1083     return;
1084   auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
1085                                             : dyn_cast<Instruction>(OpValue);
1086   if (!Intersection)
1087     return;
1088   const unsigned Opcode = Intersection->getOpcode();
1089   VecOp->copyIRFlags(Intersection);
1090   for (auto *V : VL) {
1091     auto *Instr = dyn_cast<Instruction>(V);
1092     if (!Instr)
1093       continue;
1094     if (OpValue == nullptr || Opcode == Instr->getOpcode())
1095       VecOp->andIRFlags(V);
1096   }
1097 }
1098 
1099 bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L,
1100                                  ScalarEvolution &SE) {
1101   const SCEV *Zero = SE.getZero(S->getType());
1102   return SE.isAvailableAtLoopEntry(S, L) &&
1103          SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero);
1104 }
1105 
1106 bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L,
1107                                     ScalarEvolution &SE) {
1108   const SCEV *Zero = SE.getZero(S->getType());
1109   return SE.isAvailableAtLoopEntry(S, L) &&
1110          SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero);
1111 }
1112 
1113 bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1114                              bool Signed) {
1115   unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1116   APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) :
1117     APInt::getMinValue(BitWidth);
1118   auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1119   return SE.isAvailableAtLoopEntry(S, L) &&
1120          SE.isLoopEntryGuardedByCond(L, Predicate, S,
1121                                      SE.getConstant(Min));
1122 }
1123 
1124 bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1125                              bool Signed) {
1126   unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1127   APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) :
1128     APInt::getMaxValue(BitWidth);
1129   auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1130   return SE.isAvailableAtLoopEntry(S, L) &&
1131          SE.isLoopEntryGuardedByCond(L, Predicate, S,
1132                                      SE.getConstant(Max));
1133 }
1134 
1135 //===----------------------------------------------------------------------===//
1136 // rewriteLoopExitValues - Optimize IV users outside the loop.
1137 // As a side effect, reduces the amount of IV processing within the loop.
1138 //===----------------------------------------------------------------------===//
1139 
1140 // Return true if the SCEV expansion generated by the rewriter can replace the
1141 // original value. SCEV guarantees that it produces the same value, but the way
1142 // it is produced may be illegal IR.  Ideally, this function will only be
1143 // called for verification.
1144 static bool isValidRewrite(ScalarEvolution *SE, Value *FromVal, Value *ToVal) {
1145   // If an SCEV expression subsumed multiple pointers, its expansion could
1146   // reassociate the GEP changing the base pointer. This is illegal because the
1147   // final address produced by a GEP chain must be inbounds relative to its
1148   // underlying object. Otherwise basic alias analysis, among other things,
1149   // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
1150   // producing an expression involving multiple pointers. Until then, we must
1151   // bail out here.
1152   //
1153   // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
1154   // because it understands lcssa phis while SCEV does not.
1155   Value *FromPtr = FromVal;
1156   Value *ToPtr = ToVal;
1157   if (auto *GEP = dyn_cast<GEPOperator>(FromVal))
1158     FromPtr = GEP->getPointerOperand();
1159 
1160   if (auto *GEP = dyn_cast<GEPOperator>(ToVal))
1161     ToPtr = GEP->getPointerOperand();
1162 
1163   if (FromPtr != FromVal || ToPtr != ToVal) {
1164     // Quickly check the common case
1165     if (FromPtr == ToPtr)
1166       return true;
1167 
1168     // SCEV may have rewritten an expression that produces the GEP's pointer
1169     // operand. That's ok as long as the pointer operand has the same base
1170     // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
1171     // base of a recurrence. This handles the case in which SCEV expansion
1172     // converts a pointer type recurrence into a nonrecurrent pointer base
1173     // indexed by an integer recurrence.
1174 
1175     // If the GEP base pointer is a vector of pointers, abort.
1176     if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy())
1177       return false;
1178 
1179     const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
1180     const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
1181     if (FromBase == ToBase)
1182       return true;
1183 
1184     LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: GEP rewrite bail out "
1185                       << *FromBase << " != " << *ToBase << "\n");
1186 
1187     return false;
1188   }
1189   return true;
1190 }
1191 
1192 static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) {
1193   SmallPtrSet<const Instruction *, 8> Visited;
1194   SmallVector<const Instruction *, 8> WorkList;
1195   Visited.insert(I);
1196   WorkList.push_back(I);
1197   while (!WorkList.empty()) {
1198     const Instruction *Curr = WorkList.pop_back_val();
1199     // This use is outside the loop, nothing to do.
1200     if (!L->contains(Curr))
1201       continue;
1202     // Do we assume it is a "hard" use which will not be eliminated easily?
1203     if (Curr->mayHaveSideEffects())
1204       return true;
1205     // Otherwise, add all its users to worklist.
1206     for (auto U : Curr->users()) {
1207       auto *UI = cast<Instruction>(U);
1208       if (Visited.insert(UI).second)
1209         WorkList.push_back(UI);
1210     }
1211   }
1212   return false;
1213 }
1214 
1215 // Collect information about PHI nodes which can be transformed in
1216 // rewriteLoopExitValues.
1217 struct RewritePhi {
1218   PHINode *PN;
1219   unsigned Ith;   // Ith incoming value.
1220   Value *Val;     // Exit value after expansion.
1221   bool HighCost;  // High Cost when expansion.
1222 
1223   RewritePhi(PHINode *P, unsigned I, Value *V, bool H)
1224       : PN(P), Ith(I), Val(V), HighCost(H) {}
1225 };
1226 
1227 // Check whether it is possible to delete the loop after rewriting exit
1228 // value. If it is possible, ignore ReplaceExitValue and do rewriting
1229 // aggressively.
1230 static bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
1231   BasicBlock *Preheader = L->getLoopPreheader();
1232   // If there is no preheader, the loop will not be deleted.
1233   if (!Preheader)
1234     return false;
1235 
1236   // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
1237   // We obviate multiple ExitingBlocks case for simplicity.
1238   // TODO: If we see testcase with multiple ExitingBlocks can be deleted
1239   // after exit value rewriting, we can enhance the logic here.
1240   SmallVector<BasicBlock *, 4> ExitingBlocks;
1241   L->getExitingBlocks(ExitingBlocks);
1242   SmallVector<BasicBlock *, 8> ExitBlocks;
1243   L->getUniqueExitBlocks(ExitBlocks);
1244   if (ExitBlocks.size() != 1 || ExitingBlocks.size() != 1)
1245     return false;
1246 
1247   BasicBlock *ExitBlock = ExitBlocks[0];
1248   BasicBlock::iterator BI = ExitBlock->begin();
1249   while (PHINode *P = dyn_cast<PHINode>(BI)) {
1250     Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
1251 
1252     // If the Incoming value of P is found in RewritePhiSet, we know it
1253     // could be rewritten to use a loop invariant value in transformation
1254     // phase later. Skip it in the loop invariant check below.
1255     bool found = false;
1256     for (const RewritePhi &Phi : RewritePhiSet) {
1257       unsigned i = Phi.Ith;
1258       if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
1259         found = true;
1260         break;
1261       }
1262     }
1263 
1264     Instruction *I;
1265     if (!found && (I = dyn_cast<Instruction>(Incoming)))
1266       if (!L->hasLoopInvariantOperands(I))
1267         return false;
1268 
1269     ++BI;
1270   }
1271 
1272   for (auto *BB : L->blocks())
1273     if (llvm::any_of(*BB, [](Instruction &I) {
1274           return I.mayHaveSideEffects();
1275         }))
1276       return false;
1277 
1278   return true;
1279 }
1280 
1281 int llvm::rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI,
1282                                 ScalarEvolution *SE,
1283                                 const TargetTransformInfo *TTI,
1284                                 SCEVExpander &Rewriter, DominatorTree *DT,
1285                                 ReplaceExitVal ReplaceExitValue,
1286                                 SmallVector<WeakTrackingVH, 16> &DeadInsts) {
1287   // Check a pre-condition.
1288   assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
1289          "Indvars did not preserve LCSSA!");
1290 
1291   SmallVector<BasicBlock*, 8> ExitBlocks;
1292   L->getUniqueExitBlocks(ExitBlocks);
1293 
1294   SmallVector<RewritePhi, 8> RewritePhiSet;
1295   // Find all values that are computed inside the loop, but used outside of it.
1296   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
1297   // the exit blocks of the loop to find them.
1298   for (BasicBlock *ExitBB : ExitBlocks) {
1299     // If there are no PHI nodes in this exit block, then no values defined
1300     // inside the loop are used on this path, skip it.
1301     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
1302     if (!PN) continue;
1303 
1304     unsigned NumPreds = PN->getNumIncomingValues();
1305 
1306     // Iterate over all of the PHI nodes.
1307     BasicBlock::iterator BBI = ExitBB->begin();
1308     while ((PN = dyn_cast<PHINode>(BBI++))) {
1309       if (PN->use_empty())
1310         continue; // dead use, don't replace it
1311 
1312       if (!SE->isSCEVable(PN->getType()))
1313         continue;
1314 
1315       // It's necessary to tell ScalarEvolution about this explicitly so that
1316       // it can walk the def-use list and forget all SCEVs, as it may not be
1317       // watching the PHI itself. Once the new exit value is in place, there
1318       // may not be a def-use connection between the loop and every instruction
1319       // which got a SCEVAddRecExpr for that loop.
1320       SE->forgetValue(PN);
1321 
1322       // Iterate over all of the values in all the PHI nodes.
1323       for (unsigned i = 0; i != NumPreds; ++i) {
1324         // If the value being merged in is not integer or is not defined
1325         // in the loop, skip it.
1326         Value *InVal = PN->getIncomingValue(i);
1327         if (!isa<Instruction>(InVal))
1328           continue;
1329 
1330         // If this pred is for a subloop, not L itself, skip it.
1331         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
1332           continue; // The Block is in a subloop, skip it.
1333 
1334         // Check that InVal is defined in the loop.
1335         Instruction *Inst = cast<Instruction>(InVal);
1336         if (!L->contains(Inst))
1337           continue;
1338 
1339         // Okay, this instruction has a user outside of the current loop
1340         // and varies predictably *inside* the loop.  Evaluate the value it
1341         // contains when the loop exits, if possible.  We prefer to start with
1342         // expressions which are true for all exits (so as to maximize
1343         // expression reuse by the SCEVExpander), but resort to per-exit
1344         // evaluation if that fails.
1345         const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
1346         if (isa<SCEVCouldNotCompute>(ExitValue) ||
1347             !SE->isLoopInvariant(ExitValue, L) ||
1348             !isSafeToExpand(ExitValue, *SE)) {
1349           // TODO: This should probably be sunk into SCEV in some way; maybe a
1350           // getSCEVForExit(SCEV*, L, ExitingBB)?  It can be generalized for
1351           // most SCEV expressions and other recurrence types (e.g. shift
1352           // recurrences).  Is there existing code we can reuse?
1353           const SCEV *ExitCount = SE->getExitCount(L, PN->getIncomingBlock(i));
1354           if (isa<SCEVCouldNotCompute>(ExitCount))
1355             continue;
1356           if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Inst)))
1357             if (AddRec->getLoop() == L)
1358               ExitValue = AddRec->evaluateAtIteration(ExitCount, *SE);
1359           if (isa<SCEVCouldNotCompute>(ExitValue) ||
1360               !SE->isLoopInvariant(ExitValue, L) ||
1361               !isSafeToExpand(ExitValue, *SE))
1362             continue;
1363         }
1364 
1365         // Computing the value outside of the loop brings no benefit if it is
1366         // definitely used inside the loop in a way which can not be optimized
1367         // away. Avoid doing so unless we know we have a value which computes
1368         // the ExitValue already. TODO: This should be merged into SCEV
1369         // expander to leverage its knowledge of existing expressions.
1370         if (ReplaceExitValue != AlwaysRepl && !isa<SCEVConstant>(ExitValue) &&
1371             !isa<SCEVUnknown>(ExitValue) && hasHardUserWithinLoop(L, Inst))
1372           continue;
1373 
1374         bool HighCost = Rewriter.isHighCostExpansion(
1375             ExitValue, L, SCEVCheapExpansionBudget, TTI, Inst);
1376         Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
1377 
1378         LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: AfterLoopVal = "
1379                           << *ExitVal << '\n' << "  LoopVal = " << *Inst
1380                           << "\n");
1381 
1382         if (!isValidRewrite(SE, Inst, ExitVal)) {
1383           DeadInsts.push_back(ExitVal);
1384           continue;
1385         }
1386 
1387 #ifndef NDEBUG
1388         // If we reuse an instruction from a loop which is neither L nor one of
1389         // its containing loops, we end up breaking LCSSA form for this loop by
1390         // creating a new use of its instruction.
1391         if (auto *ExitInsn = dyn_cast<Instruction>(ExitVal))
1392           if (auto *EVL = LI->getLoopFor(ExitInsn->getParent()))
1393             if (EVL != L)
1394               assert(EVL->contains(L) && "LCSSA breach detected!");
1395 #endif
1396 
1397         // Collect all the candidate PHINodes to be rewritten.
1398         RewritePhiSet.emplace_back(PN, i, ExitVal, HighCost);
1399       }
1400     }
1401   }
1402 
1403   bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
1404   int NumReplaced = 0;
1405 
1406   // Transformation.
1407   for (const RewritePhi &Phi : RewritePhiSet) {
1408     PHINode *PN = Phi.PN;
1409     Value *ExitVal = Phi.Val;
1410 
1411     // Only do the rewrite when the ExitValue can be expanded cheaply.
1412     // If LoopCanBeDel is true, rewrite exit value aggressively.
1413     if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) {
1414       DeadInsts.push_back(ExitVal);
1415       continue;
1416     }
1417 
1418     NumReplaced++;
1419     Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
1420     PN->setIncomingValue(Phi.Ith, ExitVal);
1421 
1422     // If this instruction is dead now, delete it. Don't do it now to avoid
1423     // invalidating iterators.
1424     if (isInstructionTriviallyDead(Inst, TLI))
1425       DeadInsts.push_back(Inst);
1426 
1427     // Replace PN with ExitVal if that is legal and does not break LCSSA.
1428     if (PN->getNumIncomingValues() == 1 &&
1429         LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
1430       PN->replaceAllUsesWith(ExitVal);
1431       PN->eraseFromParent();
1432     }
1433   }
1434 
1435   // The insertion point instruction may have been deleted; clear it out
1436   // so that the rewriter doesn't trip over it later.
1437   Rewriter.clearInsertPoint();
1438   return NumReplaced;
1439 }
1440 
1441 /// Set weights for \p UnrolledLoop and \p RemainderLoop based on weights for
1442 /// \p OrigLoop.
1443 void llvm::setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop,
1444                                         Loop *RemainderLoop, uint64_t UF) {
1445   assert(UF > 0 && "Zero unrolled factor is not supported");
1446   assert(UnrolledLoop != RemainderLoop &&
1447          "Unrolled and Remainder loops are expected to distinct");
1448 
1449   // Get number of iterations in the original scalar loop.
1450   unsigned OrigLoopInvocationWeight = 0;
1451   Optional<unsigned> OrigAverageTripCount =
1452       getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight);
1453   if (!OrigAverageTripCount)
1454     return;
1455 
1456   // Calculate number of iterations in unrolled loop.
1457   unsigned UnrolledAverageTripCount = *OrigAverageTripCount / UF;
1458   // Calculate number of iterations for remainder loop.
1459   unsigned RemainderAverageTripCount = *OrigAverageTripCount % UF;
1460 
1461   setLoopEstimatedTripCount(UnrolledLoop, UnrolledAverageTripCount,
1462                             OrigLoopInvocationWeight);
1463   setLoopEstimatedTripCount(RemainderLoop, RemainderAverageTripCount,
1464                             OrigLoopInvocationWeight);
1465 }
1466 
1467 /// Utility that implements appending of loops onto a worklist.
1468 /// Loops are added in preorder (analogous for reverse postorder for trees),
1469 /// and the worklist is processed LIFO.
1470 template <typename RangeT>
1471 void llvm::appendReversedLoopsToWorklist(
1472     RangeT &&Loops, SmallPriorityWorklist<Loop *, 4> &Worklist) {
1473   // We use an internal worklist to build up the preorder traversal without
1474   // recursion.
1475   SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist;
1476 
1477   // We walk the initial sequence of loops in reverse because we generally want
1478   // to visit defs before uses and the worklist is LIFO.
1479   for (Loop *RootL : Loops) {
1480     assert(PreOrderLoops.empty() && "Must start with an empty preorder walk.");
1481     assert(PreOrderWorklist.empty() &&
1482            "Must start with an empty preorder walk worklist.");
1483     PreOrderWorklist.push_back(RootL);
1484     do {
1485       Loop *L = PreOrderWorklist.pop_back_val();
1486       PreOrderWorklist.append(L->begin(), L->end());
1487       PreOrderLoops.push_back(L);
1488     } while (!PreOrderWorklist.empty());
1489 
1490     Worklist.insert(std::move(PreOrderLoops));
1491     PreOrderLoops.clear();
1492   }
1493 }
1494 
1495 template <typename RangeT>
1496 void llvm::appendLoopsToWorklist(RangeT &&Loops,
1497                                  SmallPriorityWorklist<Loop *, 4> &Worklist) {
1498   appendReversedLoopsToWorklist(reverse(Loops), Worklist);
1499 }
1500 
1501 template void llvm::appendLoopsToWorklist<ArrayRef<Loop *> &>(
1502     ArrayRef<Loop *> &Loops, SmallPriorityWorklist<Loop *, 4> &Worklist);
1503 
1504 template void
1505 llvm::appendLoopsToWorklist<Loop &>(Loop &L,
1506                                     SmallPriorityWorklist<Loop *, 4> &Worklist);
1507 
1508 void llvm::appendLoopsToWorklist(LoopInfo &LI,
1509                                  SmallPriorityWorklist<Loop *, 4> &Worklist) {
1510   appendReversedLoopsToWorklist(LI, Worklist);
1511 }
1512 
1513 Loop *llvm::cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
1514                       LoopInfo *LI, LPPassManager *LPM) {
1515   Loop &New = *LI->AllocateLoop();
1516   if (PL)
1517     PL->addChildLoop(&New);
1518   else
1519     LI->addTopLevelLoop(&New);
1520 
1521   if (LPM)
1522     LPM->addLoop(New);
1523 
1524   // Add all of the blocks in L to the new loop.
1525   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
1526        I != E; ++I)
1527     if (LI->getLoopFor(*I) == L)
1528       New.addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
1529 
1530   // Add all of the subloops to the new loop.
1531   for (Loop *I : *L)
1532     cloneLoop(I, &New, VM, LI, LPM);
1533 
1534   return &New;
1535 }
1536