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, ScalarEvolution *SE,
510                           LoopInfo *LI, MemorySSA *MSSA) {
511   assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
512   auto *Preheader = L->getLoopPreheader();
513   assert(Preheader && "Preheader should exist!");
514 
515   std::unique_ptr<MemorySSAUpdater> MSSAU;
516   if (MSSA)
517     MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
518 
519   // Now that we know the removal is safe, remove the loop by changing the
520   // branch from the preheader to go to the single exit block.
521   //
522   // Because we're deleting a large chunk of code at once, the sequence in which
523   // we remove things is very important to avoid invalidation issues.
524 
525   // Tell ScalarEvolution that the loop is deleted. Do this before
526   // deleting the loop so that ScalarEvolution can look at the loop
527   // to determine what it needs to clean up.
528   if (SE)
529     SE->forgetLoop(L);
530 
531   auto *ExitBlock = L->getUniqueExitBlock();
532   assert(ExitBlock && "Should have a unique exit block!");
533   assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
534 
535   auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
536   assert(OldBr && "Preheader must end with a branch");
537   assert(OldBr->isUnconditional() && "Preheader must have a single successor");
538   // Connect the preheader to the exit block. Keep the old edge to the header
539   // around to perform the dominator tree update in two separate steps
540   // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
541   // preheader -> header.
542   //
543   //
544   // 0.  Preheader          1.  Preheader           2.  Preheader
545   //        |                    |   |                   |
546   //        V                    |   V                   |
547   //      Header <--\            | Header <--\           | Header <--\
548   //       |  |     |            |  |  |     |           |  |  |     |
549   //       |  V     |            |  |  V     |           |  |  V     |
550   //       | Body --/            |  | Body --/           |  | Body --/
551   //       V                     V  V                    V  V
552   //      Exit                   Exit                    Exit
553   //
554   // By doing this is two separate steps we can perform the dominator tree
555   // update without using the batch update API.
556   //
557   // Even when the loop is never executed, we cannot remove the edge from the
558   // source block to the exit block. Consider the case where the unexecuted loop
559   // branches back to an outer loop. If we deleted the loop and removed the edge
560   // coming to this inner loop, this will break the outer loop structure (by
561   // deleting the backedge of the outer loop). If the outer loop is indeed a
562   // non-loop, it will be deleted in a future iteration of loop deletion pass.
563   IRBuilder<> Builder(OldBr);
564   Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
565   // Remove the old branch. The conditional branch becomes a new terminator.
566   OldBr->eraseFromParent();
567 
568   // Rewrite phis in the exit block to get their inputs from the Preheader
569   // instead of the exiting block.
570   for (PHINode &P : ExitBlock->phis()) {
571     // Set the zero'th element of Phi to be from the preheader and remove all
572     // other incoming values. Given the loop has dedicated exits, all other
573     // incoming values must be from the exiting blocks.
574     int PredIndex = 0;
575     P.setIncomingBlock(PredIndex, Preheader);
576     // Removes all incoming values from all other exiting blocks (including
577     // duplicate values from an exiting block).
578     // Nuke all entries except the zero'th entry which is the preheader entry.
579     // NOTE! We need to remove Incoming Values in the reverse order as done
580     // below, to keep the indices valid for deletion (removeIncomingValues
581     // updates getNumIncomingValues and shifts all values down into the operand
582     // being deleted).
583     for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
584       P.removeIncomingValue(e - i, false);
585 
586     assert((P.getNumIncomingValues() == 1 &&
587             P.getIncomingBlock(PredIndex) == Preheader) &&
588            "Should have exactly one value and that's from the preheader!");
589   }
590 
591   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
592   if (DT) {
593     DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}});
594     if (MSSA) {
595       MSSAU->applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}}, *DT);
596       if (VerifyMemorySSA)
597         MSSA->verifyMemorySSA();
598     }
599   }
600 
601   // Disconnect the loop body by branching directly to its exit.
602   Builder.SetInsertPoint(Preheader->getTerminator());
603   Builder.CreateBr(ExitBlock);
604   // Remove the old branch.
605   Preheader->getTerminator()->eraseFromParent();
606 
607   if (DT) {
608     DTU.applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}});
609     if (MSSA) {
610       MSSAU->applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}},
611                           *DT);
612       if (VerifyMemorySSA)
613         MSSA->verifyMemorySSA();
614       SmallSetVector<BasicBlock *, 8> DeadBlockSet(L->block_begin(),
615                                                    L->block_end());
616       MSSAU->removeBlocks(DeadBlockSet);
617     }
618   }
619 
620   // Use a map to unique and a vector to guarantee deterministic ordering.
621   llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet;
622   llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst;
623 
624   // Given LCSSA form is satisfied, we should not have users of instructions
625   // within the dead loop outside of the loop. However, LCSSA doesn't take
626   // unreachable uses into account. We handle them here.
627   // We could do it after drop all references (in this case all users in the
628   // loop will be already eliminated and we have less work to do but according
629   // to API doc of User::dropAllReferences only valid operation after dropping
630   // references, is deletion. So let's substitute all usages of
631   // instruction from the loop with undef value of corresponding type first.
632   for (auto *Block : L->blocks())
633     for (Instruction &I : *Block) {
634       auto *Undef = UndefValue::get(I.getType());
635       for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) {
636         Use &U = *UI;
637         ++UI;
638         if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
639           if (L->contains(Usr->getParent()))
640             continue;
641         // If we have a DT then we can check that uses outside a loop only in
642         // unreachable block.
643         if (DT)
644           assert(!DT->isReachableFromEntry(U) &&
645                  "Unexpected user in reachable block");
646         U.set(Undef);
647       }
648       auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I);
649       if (!DVI)
650         continue;
651       auto Key = DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()});
652       if (Key != DeadDebugSet.end())
653         continue;
654       DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()});
655       DeadDebugInst.push_back(DVI);
656     }
657 
658   // After the loop has been deleted all the values defined and modified
659   // inside the loop are going to be unavailable.
660   // Since debug values in the loop have been deleted, inserting an undef
661   // dbg.value truncates the range of any dbg.value before the loop where the
662   // loop used to be. This is particularly important for constant values.
663   DIBuilder DIB(*ExitBlock->getModule());
664   Instruction *InsertDbgValueBefore = ExitBlock->getFirstNonPHI();
665   assert(InsertDbgValueBefore &&
666          "There should be a non-PHI instruction in exit block, else these "
667          "instructions will have no parent.");
668   for (auto *DVI : DeadDebugInst)
669     DIB.insertDbgValueIntrinsic(UndefValue::get(Builder.getInt32Ty()),
670                                 DVI->getVariable(), DVI->getExpression(),
671                                 DVI->getDebugLoc(), InsertDbgValueBefore);
672 
673   // Remove the block from the reference counting scheme, so that we can
674   // delete it freely later.
675   for (auto *Block : L->blocks())
676     Block->dropAllReferences();
677 
678   if (MSSA && VerifyMemorySSA)
679     MSSA->verifyMemorySSA();
680 
681   if (LI) {
682     // Erase the instructions and the blocks without having to worry
683     // about ordering because we already dropped the references.
684     // NOTE: This iteration is safe because erasing the block does not remove
685     // its entry from the loop's block list.  We do that in the next section.
686     for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end();
687          LpI != LpE; ++LpI)
688       (*LpI)->eraseFromParent();
689 
690     // Finally, the blocks from loopinfo.  This has to happen late because
691     // otherwise our loop iterators won't work.
692 
693     SmallPtrSet<BasicBlock *, 8> blocks;
694     blocks.insert(L->block_begin(), L->block_end());
695     for (BasicBlock *BB : blocks)
696       LI->removeBlock(BB);
697 
698     // The last step is to update LoopInfo now that we've eliminated this loop.
699     // Note: LoopInfo::erase remove the given loop and relink its subloops with
700     // its parent. While removeLoop/removeChildLoop remove the given loop but
701     // not relink its subloops, which is what we want.
702     if (Loop *ParentLoop = L->getParentLoop()) {
703       Loop::iterator I = find(ParentLoop->begin(), ParentLoop->end(), L);
704       assert(I != ParentLoop->end() && "Couldn't find loop");
705       ParentLoop->removeChildLoop(I);
706     } else {
707       Loop::iterator I = find(LI->begin(), LI->end(), L);
708       assert(I != LI->end() && "Couldn't find loop");
709       LI->removeLoop(I);
710     }
711     LI->destroy(L);
712   }
713 }
714 
715 /// Checks if \p L has single exit through latch block except possibly
716 /// "deoptimizing" exits. Returns branch instruction terminating the loop
717 /// latch if above check is successful, nullptr otherwise.
718 static BranchInst *getExpectedExitLoopLatchBranch(Loop *L) {
719   BasicBlock *Latch = L->getLoopLatch();
720   if (!Latch)
721     return nullptr;
722 
723   BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator());
724   if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch))
725     return nullptr;
726 
727   assert((LatchBR->getSuccessor(0) == L->getHeader() ||
728           LatchBR->getSuccessor(1) == L->getHeader()) &&
729          "At least one edge out of the latch must go to the header");
730 
731   SmallVector<BasicBlock *, 4> ExitBlocks;
732   L->getUniqueNonLatchExitBlocks(ExitBlocks);
733   if (any_of(ExitBlocks, [](const BasicBlock *EB) {
734         return !EB->getTerminatingDeoptimizeCall();
735       }))
736     return nullptr;
737 
738   return LatchBR;
739 }
740 
741 Optional<unsigned>
742 llvm::getLoopEstimatedTripCount(Loop *L,
743                                 unsigned *EstimatedLoopInvocationWeight) {
744   // Support loops with an exiting latch and other existing exists only
745   // deoptimize.
746   BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
747   if (!LatchBranch)
748     return None;
749 
750   // To estimate the number of times the loop body was executed, we want to
751   // know the number of times the backedge was taken, vs. the number of times
752   // we exited the loop.
753   uint64_t BackedgeTakenWeight, LatchExitWeight;
754   if (!LatchBranch->extractProfMetadata(BackedgeTakenWeight, LatchExitWeight))
755     return None;
756 
757   if (LatchBranch->getSuccessor(0) != L->getHeader())
758     std::swap(BackedgeTakenWeight, LatchExitWeight);
759 
760   if (!LatchExitWeight)
761     return None;
762 
763   if (EstimatedLoopInvocationWeight)
764     *EstimatedLoopInvocationWeight = LatchExitWeight;
765 
766   // Estimated backedge taken count is a ratio of the backedge taken weight by
767   // the weight of the edge exiting the loop, rounded to nearest.
768   uint64_t BackedgeTakenCount =
769       llvm::divideNearest(BackedgeTakenWeight, LatchExitWeight);
770   // Estimated trip count is one plus estimated backedge taken count.
771   return BackedgeTakenCount + 1;
772 }
773 
774 bool llvm::setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount,
775                                      unsigned EstimatedloopInvocationWeight) {
776   // Support loops with an exiting latch and other existing exists only
777   // deoptimize.
778   BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
779   if (!LatchBranch)
780     return false;
781 
782   // Calculate taken and exit weights.
783   unsigned LatchExitWeight = 0;
784   unsigned BackedgeTakenWeight = 0;
785 
786   if (EstimatedTripCount > 0) {
787     LatchExitWeight = EstimatedloopInvocationWeight;
788     BackedgeTakenWeight = (EstimatedTripCount - 1) * LatchExitWeight;
789   }
790 
791   // Make a swap if back edge is taken when condition is "false".
792   if (LatchBranch->getSuccessor(0) != L->getHeader())
793     std::swap(BackedgeTakenWeight, LatchExitWeight);
794 
795   MDBuilder MDB(LatchBranch->getContext());
796 
797   // Set/Update profile metadata.
798   LatchBranch->setMetadata(
799       LLVMContext::MD_prof,
800       MDB.createBranchWeights(BackedgeTakenWeight, LatchExitWeight));
801 
802   return true;
803 }
804 
805 bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
806                                               ScalarEvolution &SE) {
807   Loop *OuterL = InnerLoop->getParentLoop();
808   if (!OuterL)
809     return true;
810 
811   // Get the backedge taken count for the inner loop
812   BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
813   const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
814   if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
815       !InnerLoopBECountSC->getType()->isIntegerTy())
816     return false;
817 
818   // Get whether count is invariant to the outer loop
819   ScalarEvolution::LoopDisposition LD =
820       SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
821   if (LD != ScalarEvolution::LoopInvariant)
822     return false;
823 
824   return true;
825 }
826 
827 Value *llvm::createMinMaxOp(IRBuilder<> &Builder,
828                             RecurrenceDescriptor::MinMaxRecurrenceKind RK,
829                             Value *Left, Value *Right) {
830   CmpInst::Predicate P = CmpInst::ICMP_NE;
831   switch (RK) {
832   default:
833     llvm_unreachable("Unknown min/max recurrence kind");
834   case RecurrenceDescriptor::MRK_UIntMin:
835     P = CmpInst::ICMP_ULT;
836     break;
837   case RecurrenceDescriptor::MRK_UIntMax:
838     P = CmpInst::ICMP_UGT;
839     break;
840   case RecurrenceDescriptor::MRK_SIntMin:
841     P = CmpInst::ICMP_SLT;
842     break;
843   case RecurrenceDescriptor::MRK_SIntMax:
844     P = CmpInst::ICMP_SGT;
845     break;
846   case RecurrenceDescriptor::MRK_FloatMin:
847     P = CmpInst::FCMP_OLT;
848     break;
849   case RecurrenceDescriptor::MRK_FloatMax:
850     P = CmpInst::FCMP_OGT;
851     break;
852   }
853 
854   // We only match FP sequences that are 'fast', so we can unconditionally
855   // set it on any generated instructions.
856   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
857   FastMathFlags FMF;
858   FMF.setFast();
859   Builder.setFastMathFlags(FMF);
860 
861   Value *Cmp;
862   if (RK == RecurrenceDescriptor::MRK_FloatMin ||
863       RK == RecurrenceDescriptor::MRK_FloatMax)
864     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
865   else
866     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
867 
868   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
869   return Select;
870 }
871 
872 // Helper to generate an ordered reduction.
873 Value *
874 llvm::getOrderedReduction(IRBuilder<> &Builder, Value *Acc, Value *Src,
875                           unsigned Op,
876                           RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
877                           ArrayRef<Value *> RedOps) {
878   unsigned VF = Src->getType()->getVectorNumElements();
879 
880   // Extract and apply reduction ops in ascending order:
881   // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
882   Value *Result = Acc;
883   for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
884     Value *Ext =
885         Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
886 
887     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
888       Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
889                                    "bin.rdx");
890     } else {
891       assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
892              "Invalid min/max");
893       Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext);
894     }
895 
896     if (!RedOps.empty())
897       propagateIRFlags(Result, RedOps);
898   }
899 
900   return Result;
901 }
902 
903 // Helper to generate a log2 shuffle reduction.
904 Value *
905 llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op,
906                           RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
907                           ArrayRef<Value *> RedOps) {
908   unsigned VF = Src->getType()->getVectorNumElements();
909   // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
910   // and vector ops, reducing the set of values being computed by half each
911   // round.
912   assert(isPowerOf2_32(VF) &&
913          "Reduction emission only supported for pow2 vectors!");
914   Value *TmpVec = Src;
915   SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
916   for (unsigned i = VF; i != 1; i >>= 1) {
917     // Move the upper half of the vector to the lower half.
918     for (unsigned j = 0; j != i / 2; ++j)
919       ShuffleMask[j] = Builder.getInt32(i / 2 + j);
920 
921     // Fill the rest of the mask with undef.
922     std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
923               UndefValue::get(Builder.getInt32Ty()));
924 
925     Value *Shuf = Builder.CreateShuffleVector(
926         TmpVec, UndefValue::get(TmpVec->getType()),
927         ConstantVector::get(ShuffleMask), "rdx.shuf");
928 
929     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
930       // The builder propagates its fast-math-flags setting.
931       TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
932                                    "bin.rdx");
933     } else {
934       assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
935              "Invalid min/max");
936       TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf);
937     }
938     if (!RedOps.empty())
939       propagateIRFlags(TmpVec, RedOps);
940   }
941   // The result is in the first element of the vector.
942   return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
943 }
944 
945 /// Create a simple vector reduction specified by an opcode and some
946 /// flags (if generating min/max reductions).
947 Value *llvm::createSimpleTargetReduction(
948     IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode,
949     Value *Src, TargetTransformInfo::ReductionFlags Flags,
950     ArrayRef<Value *> RedOps) {
951   assert(isa<VectorType>(Src->getType()) && "Type must be a vector");
952 
953   std::function<Value *()> BuildFunc;
954   using RD = RecurrenceDescriptor;
955   RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
956 
957   switch (Opcode) {
958   case Instruction::Add:
959     BuildFunc = [&]() { return Builder.CreateAddReduce(Src); };
960     break;
961   case Instruction::Mul:
962     BuildFunc = [&]() { return Builder.CreateMulReduce(Src); };
963     break;
964   case Instruction::And:
965     BuildFunc = [&]() { return Builder.CreateAndReduce(Src); };
966     break;
967   case Instruction::Or:
968     BuildFunc = [&]() { return Builder.CreateOrReduce(Src); };
969     break;
970   case Instruction::Xor:
971     BuildFunc = [&]() { return Builder.CreateXorReduce(Src); };
972     break;
973   case Instruction::FAdd:
974     BuildFunc = [&]() {
975       auto Rdx = Builder.CreateFAddReduce(
976           Constant::getNullValue(Src->getType()->getVectorElementType()), Src);
977       return Rdx;
978     };
979     break;
980   case Instruction::FMul:
981     BuildFunc = [&]() {
982       Type *Ty = Src->getType()->getVectorElementType();
983       auto Rdx = Builder.CreateFMulReduce(ConstantFP::get(Ty, 1.0), Src);
984       return Rdx;
985     };
986     break;
987   case Instruction::ICmp:
988     if (Flags.IsMaxOp) {
989       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
990       BuildFunc = [&]() {
991         return Builder.CreateIntMaxReduce(Src, Flags.IsSigned);
992       };
993     } else {
994       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
995       BuildFunc = [&]() {
996         return Builder.CreateIntMinReduce(Src, Flags.IsSigned);
997       };
998     }
999     break;
1000   case Instruction::FCmp:
1001     if (Flags.IsMaxOp) {
1002       MinMaxKind = RD::MRK_FloatMax;
1003       BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); };
1004     } else {
1005       MinMaxKind = RD::MRK_FloatMin;
1006       BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); };
1007     }
1008     break;
1009   default:
1010     llvm_unreachable("Unhandled opcode");
1011     break;
1012   }
1013   if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags))
1014     return BuildFunc();
1015   return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps);
1016 }
1017 
1018 /// Create a vector reduction using a given recurrence descriptor.
1019 Value *llvm::createTargetReduction(IRBuilder<> &B,
1020                                    const TargetTransformInfo *TTI,
1021                                    RecurrenceDescriptor &Desc, Value *Src,
1022                                    bool NoNaN) {
1023   // TODO: Support in-order reductions based on the recurrence descriptor.
1024   using RD = RecurrenceDescriptor;
1025   RD::RecurrenceKind RecKind = Desc.getRecurrenceKind();
1026   TargetTransformInfo::ReductionFlags Flags;
1027   Flags.NoNaN = NoNaN;
1028 
1029   // All ops in the reduction inherit fast-math-flags from the recurrence
1030   // descriptor.
1031   IRBuilder<>::FastMathFlagGuard FMFGuard(B);
1032   B.setFastMathFlags(Desc.getFastMathFlags());
1033 
1034   switch (RecKind) {
1035   case RD::RK_FloatAdd:
1036     return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags);
1037   case RD::RK_FloatMult:
1038     return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags);
1039   case RD::RK_IntegerAdd:
1040     return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags);
1041   case RD::RK_IntegerMult:
1042     return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags);
1043   case RD::RK_IntegerAnd:
1044     return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags);
1045   case RD::RK_IntegerOr:
1046     return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags);
1047   case RD::RK_IntegerXor:
1048     return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags);
1049   case RD::RK_IntegerMinMax: {
1050     RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind();
1051     Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax);
1052     Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin);
1053     return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags);
1054   }
1055   case RD::RK_FloatMinMax: {
1056     Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax;
1057     return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags);
1058   }
1059   default:
1060     llvm_unreachable("Unhandled RecKind");
1061   }
1062 }
1063 
1064 void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
1065   auto *VecOp = dyn_cast<Instruction>(I);
1066   if (!VecOp)
1067     return;
1068   auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
1069                                             : dyn_cast<Instruction>(OpValue);
1070   if (!Intersection)
1071     return;
1072   const unsigned Opcode = Intersection->getOpcode();
1073   VecOp->copyIRFlags(Intersection);
1074   for (auto *V : VL) {
1075     auto *Instr = dyn_cast<Instruction>(V);
1076     if (!Instr)
1077       continue;
1078     if (OpValue == nullptr || Opcode == Instr->getOpcode())
1079       VecOp->andIRFlags(V);
1080   }
1081 }
1082 
1083 bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L,
1084                                  ScalarEvolution &SE) {
1085   const SCEV *Zero = SE.getZero(S->getType());
1086   return SE.isAvailableAtLoopEntry(S, L) &&
1087          SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero);
1088 }
1089 
1090 bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L,
1091                                     ScalarEvolution &SE) {
1092   const SCEV *Zero = SE.getZero(S->getType());
1093   return SE.isAvailableAtLoopEntry(S, L) &&
1094          SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero);
1095 }
1096 
1097 bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1098                              bool Signed) {
1099   unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1100   APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) :
1101     APInt::getMinValue(BitWidth);
1102   auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1103   return SE.isAvailableAtLoopEntry(S, L) &&
1104          SE.isLoopEntryGuardedByCond(L, Predicate, S,
1105                                      SE.getConstant(Min));
1106 }
1107 
1108 bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1109                              bool Signed) {
1110   unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1111   APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) :
1112     APInt::getMaxValue(BitWidth);
1113   auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1114   return SE.isAvailableAtLoopEntry(S, L) &&
1115          SE.isLoopEntryGuardedByCond(L, Predicate, S,
1116                                      SE.getConstant(Max));
1117 }
1118 
1119 //===----------------------------------------------------------------------===//
1120 // rewriteLoopExitValues - Optimize IV users outside the loop.
1121 // As a side effect, reduces the amount of IV processing within the loop.
1122 //===----------------------------------------------------------------------===//
1123 
1124 // Return true if the SCEV expansion generated by the rewriter can replace the
1125 // original value. SCEV guarantees that it produces the same value, but the way
1126 // it is produced may be illegal IR.  Ideally, this function will only be
1127 // called for verification.
1128 static bool isValidRewrite(ScalarEvolution *SE, Value *FromVal, Value *ToVal) {
1129   // If an SCEV expression subsumed multiple pointers, its expansion could
1130   // reassociate the GEP changing the base pointer. This is illegal because the
1131   // final address produced by a GEP chain must be inbounds relative to its
1132   // underlying object. Otherwise basic alias analysis, among other things,
1133   // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
1134   // producing an expression involving multiple pointers. Until then, we must
1135   // bail out here.
1136   //
1137   // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
1138   // because it understands lcssa phis while SCEV does not.
1139   Value *FromPtr = FromVal;
1140   Value *ToPtr = ToVal;
1141   if (auto *GEP = dyn_cast<GEPOperator>(FromVal))
1142     FromPtr = GEP->getPointerOperand();
1143 
1144   if (auto *GEP = dyn_cast<GEPOperator>(ToVal))
1145     ToPtr = GEP->getPointerOperand();
1146 
1147   if (FromPtr != FromVal || ToPtr != ToVal) {
1148     // Quickly check the common case
1149     if (FromPtr == ToPtr)
1150       return true;
1151 
1152     // SCEV may have rewritten an expression that produces the GEP's pointer
1153     // operand. That's ok as long as the pointer operand has the same base
1154     // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
1155     // base of a recurrence. This handles the case in which SCEV expansion
1156     // converts a pointer type recurrence into a nonrecurrent pointer base
1157     // indexed by an integer recurrence.
1158 
1159     // If the GEP base pointer is a vector of pointers, abort.
1160     if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy())
1161       return false;
1162 
1163     const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
1164     const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
1165     if (FromBase == ToBase)
1166       return true;
1167 
1168     LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: GEP rewrite bail out "
1169                       << *FromBase << " != " << *ToBase << "\n");
1170 
1171     return false;
1172   }
1173   return true;
1174 }
1175 
1176 static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) {
1177   SmallPtrSet<const Instruction *, 8> Visited;
1178   SmallVector<const Instruction *, 8> WorkList;
1179   Visited.insert(I);
1180   WorkList.push_back(I);
1181   while (!WorkList.empty()) {
1182     const Instruction *Curr = WorkList.pop_back_val();
1183     // This use is outside the loop, nothing to do.
1184     if (!L->contains(Curr))
1185       continue;
1186     // Do we assume it is a "hard" use which will not be eliminated easily?
1187     if (Curr->mayHaveSideEffects())
1188       return true;
1189     // Otherwise, add all its users to worklist.
1190     for (auto U : Curr->users()) {
1191       auto *UI = cast<Instruction>(U);
1192       if (Visited.insert(UI).second)
1193         WorkList.push_back(UI);
1194     }
1195   }
1196   return false;
1197 }
1198 
1199 // Collect information about PHI nodes which can be transformed in
1200 // rewriteLoopExitValues.
1201 struct RewritePhi {
1202   PHINode *PN;
1203   unsigned Ith;   // Ith incoming value.
1204   Value *Val;     // Exit value after expansion.
1205   bool HighCost;  // High Cost when expansion.
1206 
1207   RewritePhi(PHINode *P, unsigned I, Value *V, bool H)
1208       : PN(P), Ith(I), Val(V), HighCost(H) {}
1209 };
1210 
1211 // Check whether it is possible to delete the loop after rewriting exit
1212 // value. If it is possible, ignore ReplaceExitValue and do rewriting
1213 // aggressively.
1214 static bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
1215   BasicBlock *Preheader = L->getLoopPreheader();
1216   // If there is no preheader, the loop will not be deleted.
1217   if (!Preheader)
1218     return false;
1219 
1220   // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
1221   // We obviate multiple ExitingBlocks case for simplicity.
1222   // TODO: If we see testcase with multiple ExitingBlocks can be deleted
1223   // after exit value rewriting, we can enhance the logic here.
1224   SmallVector<BasicBlock *, 4> ExitingBlocks;
1225   L->getExitingBlocks(ExitingBlocks);
1226   SmallVector<BasicBlock *, 8> ExitBlocks;
1227   L->getUniqueExitBlocks(ExitBlocks);
1228   if (ExitBlocks.size() != 1 || ExitingBlocks.size() != 1)
1229     return false;
1230 
1231   BasicBlock *ExitBlock = ExitBlocks[0];
1232   BasicBlock::iterator BI = ExitBlock->begin();
1233   while (PHINode *P = dyn_cast<PHINode>(BI)) {
1234     Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
1235 
1236     // If the Incoming value of P is found in RewritePhiSet, we know it
1237     // could be rewritten to use a loop invariant value in transformation
1238     // phase later. Skip it in the loop invariant check below.
1239     bool found = false;
1240     for (const RewritePhi &Phi : RewritePhiSet) {
1241       unsigned i = Phi.Ith;
1242       if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
1243         found = true;
1244         break;
1245       }
1246     }
1247 
1248     Instruction *I;
1249     if (!found && (I = dyn_cast<Instruction>(Incoming)))
1250       if (!L->hasLoopInvariantOperands(I))
1251         return false;
1252 
1253     ++BI;
1254   }
1255 
1256   for (auto *BB : L->blocks())
1257     if (llvm::any_of(*BB, [](Instruction &I) {
1258           return I.mayHaveSideEffects();
1259         }))
1260       return false;
1261 
1262   return true;
1263 }
1264 
1265 int llvm::rewriteLoopExitValues(Loop *L, LoopInfo *LI,
1266     TargetLibraryInfo *TLI, ScalarEvolution *SE, SCEVExpander &Rewriter,
1267     DominatorTree *DT, ReplaceExitVal ReplaceExitValue,
1268     SmallVector<WeakTrackingVH, 16> &DeadInsts) {
1269   // Check a pre-condition.
1270   assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
1271          "Indvars did not preserve LCSSA!");
1272 
1273   SmallVector<BasicBlock*, 8> ExitBlocks;
1274   L->getUniqueExitBlocks(ExitBlocks);
1275 
1276   SmallVector<RewritePhi, 8> RewritePhiSet;
1277   // Find all values that are computed inside the loop, but used outside of it.
1278   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
1279   // the exit blocks of the loop to find them.
1280   for (BasicBlock *ExitBB : ExitBlocks) {
1281     // If there are no PHI nodes in this exit block, then no values defined
1282     // inside the loop are used on this path, skip it.
1283     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
1284     if (!PN) continue;
1285 
1286     unsigned NumPreds = PN->getNumIncomingValues();
1287 
1288     // Iterate over all of the PHI nodes.
1289     BasicBlock::iterator BBI = ExitBB->begin();
1290     while ((PN = dyn_cast<PHINode>(BBI++))) {
1291       if (PN->use_empty())
1292         continue; // dead use, don't replace it
1293 
1294       if (!SE->isSCEVable(PN->getType()))
1295         continue;
1296 
1297       // It's necessary to tell ScalarEvolution about this explicitly so that
1298       // it can walk the def-use list and forget all SCEVs, as it may not be
1299       // watching the PHI itself. Once the new exit value is in place, there
1300       // may not be a def-use connection between the loop and every instruction
1301       // which got a SCEVAddRecExpr for that loop.
1302       SE->forgetValue(PN);
1303 
1304       // Iterate over all of the values in all the PHI nodes.
1305       for (unsigned i = 0; i != NumPreds; ++i) {
1306         // If the value being merged in is not integer or is not defined
1307         // in the loop, skip it.
1308         Value *InVal = PN->getIncomingValue(i);
1309         if (!isa<Instruction>(InVal))
1310           continue;
1311 
1312         // If this pred is for a subloop, not L itself, skip it.
1313         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
1314           continue; // The Block is in a subloop, skip it.
1315 
1316         // Check that InVal is defined in the loop.
1317         Instruction *Inst = cast<Instruction>(InVal);
1318         if (!L->contains(Inst))
1319           continue;
1320 
1321         // Okay, this instruction has a user outside of the current loop
1322         // and varies predictably *inside* the loop.  Evaluate the value it
1323         // contains when the loop exits, if possible.  We prefer to start with
1324         // expressions which are true for all exits (so as to maximize
1325         // expression reuse by the SCEVExpander), but resort to per-exit
1326         // evaluation if that fails.
1327         const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
1328         if (isa<SCEVCouldNotCompute>(ExitValue) ||
1329             !SE->isLoopInvariant(ExitValue, L) ||
1330             !isSafeToExpand(ExitValue, *SE)) {
1331           // TODO: This should probably be sunk into SCEV in some way; maybe a
1332           // getSCEVForExit(SCEV*, L, ExitingBB)?  It can be generalized for
1333           // most SCEV expressions and other recurrence types (e.g. shift
1334           // recurrences).  Is there existing code we can reuse?
1335           const SCEV *ExitCount = SE->getExitCount(L, PN->getIncomingBlock(i));
1336           if (isa<SCEVCouldNotCompute>(ExitCount))
1337             continue;
1338           if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Inst)))
1339             if (AddRec->getLoop() == L)
1340               ExitValue = AddRec->evaluateAtIteration(ExitCount, *SE);
1341           if (isa<SCEVCouldNotCompute>(ExitValue) ||
1342               !SE->isLoopInvariant(ExitValue, L) ||
1343               !isSafeToExpand(ExitValue, *SE))
1344             continue;
1345         }
1346 
1347         // Computing the value outside of the loop brings no benefit if it is
1348         // definitely used inside the loop in a way which can not be optimized
1349         // away. Avoid doing so unless we know we have a value which computes
1350         // the ExitValue already. TODO: This should be merged into SCEV
1351         // expander to leverage its knowledge of existing expressions.
1352         if (ReplaceExitValue != AlwaysRepl &&
1353             !isa<SCEVConstant>(ExitValue) && !isa<SCEVUnknown>(ExitValue) &&
1354             hasHardUserWithinLoop(L, Inst))
1355           continue;
1356 
1357         bool HighCost = Rewriter.isHighCostExpansion(ExitValue, L, Inst);
1358         Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
1359 
1360         LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: AfterLoopVal = "
1361                           << *ExitVal << '\n' << "  LoopVal = " << *Inst
1362                           << "\n");
1363 
1364         if (!isValidRewrite(SE, Inst, ExitVal)) {
1365           DeadInsts.push_back(ExitVal);
1366           continue;
1367         }
1368 
1369 #ifndef NDEBUG
1370         // If we reuse an instruction from a loop which is neither L nor one of
1371         // its containing loops, we end up breaking LCSSA form for this loop by
1372         // creating a new use of its instruction.
1373         if (auto *ExitInsn = dyn_cast<Instruction>(ExitVal))
1374           if (auto *EVL = LI->getLoopFor(ExitInsn->getParent()))
1375             if (EVL != L)
1376               assert(EVL->contains(L) && "LCSSA breach detected!");
1377 #endif
1378 
1379         // Collect all the candidate PHINodes to be rewritten.
1380         RewritePhiSet.emplace_back(PN, i, ExitVal, HighCost);
1381       }
1382     }
1383   }
1384 
1385   bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
1386   int NumReplaced = 0;
1387 
1388   // Transformation.
1389   for (const RewritePhi &Phi : RewritePhiSet) {
1390     PHINode *PN = Phi.PN;
1391     Value *ExitVal = Phi.Val;
1392 
1393     // Only do the rewrite when the ExitValue can be expanded cheaply.
1394     // If LoopCanBeDel is true, rewrite exit value aggressively.
1395     if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) {
1396       DeadInsts.push_back(ExitVal);
1397       continue;
1398     }
1399 
1400     NumReplaced++;
1401     Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
1402     PN->setIncomingValue(Phi.Ith, ExitVal);
1403 
1404     // If this instruction is dead now, delete it. Don't do it now to avoid
1405     // invalidating iterators.
1406     if (isInstructionTriviallyDead(Inst, TLI))
1407       DeadInsts.push_back(Inst);
1408 
1409     // Replace PN with ExitVal if that is legal and does not break LCSSA.
1410     if (PN->getNumIncomingValues() == 1 &&
1411         LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
1412       PN->replaceAllUsesWith(ExitVal);
1413       PN->eraseFromParent();
1414     }
1415   }
1416 
1417   // The insertion point instruction may have been deleted; clear it out
1418   // so that the rewriter doesn't trip over it later.
1419   Rewriter.clearInsertPoint();
1420   return NumReplaced;
1421 }
1422 
1423 /// Set weights for \p UnrolledLoop and \p RemainderLoop based on weights for
1424 /// \p OrigLoop.
1425 void llvm::setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop,
1426                                         Loop *RemainderLoop, uint64_t UF) {
1427   assert(UF > 0 && "Zero unrolled factor is not supported");
1428   assert(UnrolledLoop != RemainderLoop &&
1429          "Unrolled and Remainder loops are expected to distinct");
1430 
1431   // Get number of iterations in the original scalar loop.
1432   unsigned OrigLoopInvocationWeight = 0;
1433   Optional<unsigned> OrigAverageTripCount =
1434       getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight);
1435   if (!OrigAverageTripCount)
1436     return;
1437 
1438   // Calculate number of iterations in unrolled loop.
1439   unsigned UnrolledAverageTripCount = *OrigAverageTripCount / UF;
1440   // Calculate number of iterations for remainder loop.
1441   unsigned RemainderAverageTripCount = *OrigAverageTripCount % UF;
1442 
1443   setLoopEstimatedTripCount(UnrolledLoop, UnrolledAverageTripCount,
1444                             OrigLoopInvocationWeight);
1445   setLoopEstimatedTripCount(RemainderLoop, RemainderAverageTripCount,
1446                             OrigLoopInvocationWeight);
1447 }
1448