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