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/Module.h"
36 #include "llvm/IR/PatternMatch.h"
37 #include "llvm/IR/ValueHandle.h"
38 #include "llvm/InitializePasses.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/KnownBits.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 
44 using namespace llvm;
45 using namespace llvm::PatternMatch;
46 
47 #define DEBUG_TYPE "loop-utils"
48 
49 static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced";
50 static const char *LLVMLoopDisableLICM = "llvm.licm.disable";
51 
52 bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
53                                    MemorySSAUpdater *MSSAU,
54                                    bool PreserveLCSSA) {
55   bool Changed = false;
56 
57   // We re-use a vector for the in-loop predecesosrs.
58   SmallVector<BasicBlock *, 4> InLoopPredecessors;
59 
60   auto RewriteExit = [&](BasicBlock *BB) {
61     assert(InLoopPredecessors.empty() &&
62            "Must start with an empty predecessors list!");
63     auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
64 
65     // See if there are any non-loop predecessors of this exit block and
66     // keep track of the in-loop predecessors.
67     bool IsDedicatedExit = true;
68     for (auto *PredBB : predecessors(BB))
69       if (L->contains(PredBB)) {
70         if (isa<IndirectBrInst>(PredBB->getTerminator()))
71           // We cannot rewrite exiting edges from an indirectbr.
72           return false;
73         if (isa<CallBrInst>(PredBB->getTerminator()))
74           // We cannot rewrite exiting edges from a callbr.
75           return false;
76 
77         InLoopPredecessors.push_back(PredBB);
78       } else {
79         IsDedicatedExit = false;
80       }
81 
82     assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
83 
84     // Nothing to do if this is already a dedicated exit.
85     if (IsDedicatedExit)
86       return false;
87 
88     auto *NewExitBB = SplitBlockPredecessors(
89         BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA);
90 
91     if (!NewExitBB)
92       LLVM_DEBUG(
93           dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
94                  << *L << "\n");
95     else
96       LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
97                         << NewExitBB->getName() << "\n");
98     return true;
99   };
100 
101   // Walk the exit blocks directly rather than building up a data structure for
102   // them, but only visit each one once.
103   SmallPtrSet<BasicBlock *, 4> Visited;
104   for (auto *BB : L->blocks())
105     for (auto *SuccBB : successors(BB)) {
106       // We're looking for exit blocks so skip in-loop successors.
107       if (L->contains(SuccBB))
108         continue;
109 
110       // Visit each exit block exactly once.
111       if (!Visited.insert(SuccBB).second)
112         continue;
113 
114       Changed |= RewriteExit(SuccBB);
115     }
116 
117   return Changed;
118 }
119 
120 /// Returns the instructions that use values defined in the loop.
121 SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
122   SmallVector<Instruction *, 8> UsedOutside;
123 
124   for (auto *Block : L->getBlocks())
125     // FIXME: I believe that this could use copy_if if the Inst reference could
126     // be adapted into a pointer.
127     for (auto &Inst : *Block) {
128       auto Users = Inst.users();
129       if (any_of(Users, [&](User *U) {
130             auto *Use = cast<Instruction>(U);
131             return !L->contains(Use->getParent());
132           }))
133         UsedOutside.push_back(&Inst);
134     }
135 
136   return UsedOutside;
137 }
138 
139 void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
140   // By definition, all loop passes need the LoopInfo analysis and the
141   // Dominator tree it depends on. Because they all participate in the loop
142   // pass manager, they must also preserve these.
143   AU.addRequired<DominatorTreeWrapperPass>();
144   AU.addPreserved<DominatorTreeWrapperPass>();
145   AU.addRequired<LoopInfoWrapperPass>();
146   AU.addPreserved<LoopInfoWrapperPass>();
147 
148   // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
149   // here because users shouldn't directly get them from this header.
150   extern char &LoopSimplifyID;
151   extern char &LCSSAID;
152   AU.addRequiredID(LoopSimplifyID);
153   AU.addPreservedID(LoopSimplifyID);
154   AU.addRequiredID(LCSSAID);
155   AU.addPreservedID(LCSSAID);
156   // This is used in the LPPassManager to perform LCSSA verification on passes
157   // which preserve lcssa form
158   AU.addRequired<LCSSAVerificationPass>();
159   AU.addPreserved<LCSSAVerificationPass>();
160 
161   // Loop passes are designed to run inside of a loop pass manager which means
162   // that any function analyses they require must be required by the first loop
163   // pass in the manager (so that it is computed before the loop pass manager
164   // runs) and preserved by all loop pasess in the manager. To make this
165   // reasonably robust, the set needed for most loop passes is maintained here.
166   // If your loop pass requires an analysis not listed here, you will need to
167   // carefully audit the loop pass manager nesting structure that results.
168   AU.addRequired<AAResultsWrapperPass>();
169   AU.addPreserved<AAResultsWrapperPass>();
170   AU.addPreserved<BasicAAWrapperPass>();
171   AU.addPreserved<GlobalsAAWrapperPass>();
172   AU.addPreserved<SCEVAAWrapperPass>();
173   AU.addRequired<ScalarEvolutionWrapperPass>();
174   AU.addPreserved<ScalarEvolutionWrapperPass>();
175   // FIXME: When all loop passes preserve MemorySSA, it can be required and
176   // preserved here instead of the individual handling in each pass.
177 }
178 
179 /// Manually defined generic "LoopPass" dependency initialization. This is used
180 /// to initialize the exact set of passes from above in \c
181 /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
182 /// with:
183 ///
184 ///   INITIALIZE_PASS_DEPENDENCY(LoopPass)
185 ///
186 /// As-if "LoopPass" were a pass.
187 void llvm::initializeLoopPassPass(PassRegistry &Registry) {
188   INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
189   INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
190   INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
191   INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
192   INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
193   INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
194   INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
195   INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
196   INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
197   INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
198 }
199 
200 /// Create MDNode for input string.
201 static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) {
202   LLVMContext &Context = TheLoop->getHeader()->getContext();
203   Metadata *MDs[] = {
204       MDString::get(Context, Name),
205       ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))};
206   return MDNode::get(Context, MDs);
207 }
208 
209 /// Set input string into loop metadata by keeping other values intact.
210 /// If the string is already in loop metadata update value if it is
211 /// different.
212 void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *StringMD,
213                                    unsigned V) {
214   SmallVector<Metadata *, 4> MDs(1);
215   // If the loop already has metadata, retain it.
216   MDNode *LoopID = TheLoop->getLoopID();
217   if (LoopID) {
218     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
219       MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
220       // If it is of form key = value, try to parse it.
221       if (Node->getNumOperands() == 2) {
222         MDString *S = dyn_cast<MDString>(Node->getOperand(0));
223         if (S && S->getString().equals(StringMD)) {
224           ConstantInt *IntMD =
225               mdconst::extract_or_null<ConstantInt>(Node->getOperand(1));
226           if (IntMD && IntMD->getSExtValue() == V)
227             // It is already in place. Do nothing.
228             return;
229           // We need to update the value, so just skip it here and it will
230           // be added after copying other existed nodes.
231           continue;
232         }
233       }
234       MDs.push_back(Node);
235     }
236   }
237   // Add new metadata.
238   MDs.push_back(createStringMetadata(TheLoop, StringMD, V));
239   // Replace current metadata node with new one.
240   LLVMContext &Context = TheLoop->getHeader()->getContext();
241   MDNode *NewLoopID = MDNode::get(Context, MDs);
242   // Set operand 0 to refer to the loop id itself.
243   NewLoopID->replaceOperandWith(0, NewLoopID);
244   TheLoop->setLoopID(NewLoopID);
245 }
246 
247 /// Find string metadata for loop
248 ///
249 /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
250 /// operand or null otherwise.  If the string metadata is not found return
251 /// Optional's not-a-value.
252 Optional<const MDOperand *> llvm::findStringMetadataForLoop(const Loop *TheLoop,
253                                                             StringRef Name) {
254   MDNode *MD = findOptionMDForLoop(TheLoop, Name);
255   if (!MD)
256     return None;
257   switch (MD->getNumOperands()) {
258   case 1:
259     return nullptr;
260   case 2:
261     return &MD->getOperand(1);
262   default:
263     llvm_unreachable("loop metadata has 0 or 1 operand");
264   }
265 }
266 
267 static Optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop,
268                                                    StringRef Name) {
269   MDNode *MD = findOptionMDForLoop(TheLoop, Name);
270   if (!MD)
271     return None;
272   switch (MD->getNumOperands()) {
273   case 1:
274     // When the value is absent it is interpreted as 'attribute set'.
275     return true;
276   case 2:
277     if (ConstantInt *IntMD =
278             mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get()))
279       return IntMD->getZExtValue();
280     return true;
281   }
282   llvm_unreachable("unexpected number of options");
283 }
284 
285 static bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) {
286   return getOptionalBoolLoopAttribute(TheLoop, Name).getValueOr(false);
287 }
288 
289 llvm::Optional<int> llvm::getOptionalIntLoopAttribute(Loop *TheLoop,
290                                                       StringRef Name) {
291   const MDOperand *AttrMD =
292       findStringMetadataForLoop(TheLoop, Name).getValueOr(nullptr);
293   if (!AttrMD)
294     return None;
295 
296   ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
297   if (!IntMD)
298     return None;
299 
300   return IntMD->getSExtValue();
301 }
302 
303 Optional<MDNode *> llvm::makeFollowupLoopID(
304     MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
305     const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
306   if (!OrigLoopID) {
307     if (AlwaysNew)
308       return nullptr;
309     return None;
310   }
311 
312   assert(OrigLoopID->getOperand(0) == OrigLoopID);
313 
314   bool InheritAllAttrs = !InheritOptionsExceptPrefix;
315   bool InheritSomeAttrs =
316       InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
317   SmallVector<Metadata *, 8> MDs;
318   MDs.push_back(nullptr);
319 
320   bool Changed = false;
321   if (InheritAllAttrs || InheritSomeAttrs) {
322     for (const MDOperand &Existing : drop_begin(OrigLoopID->operands(), 1)) {
323       MDNode *Op = cast<MDNode>(Existing.get());
324 
325       auto InheritThisAttribute = [InheritSomeAttrs,
326                                    InheritOptionsExceptPrefix](MDNode *Op) {
327         if (!InheritSomeAttrs)
328           return false;
329 
330         // Skip malformatted attribute metadata nodes.
331         if (Op->getNumOperands() == 0)
332           return true;
333         Metadata *NameMD = Op->getOperand(0).get();
334         if (!isa<MDString>(NameMD))
335           return true;
336         StringRef AttrName = cast<MDString>(NameMD)->getString();
337 
338         // Do not inherit excluded attributes.
339         return !AttrName.startswith(InheritOptionsExceptPrefix);
340       };
341 
342       if (InheritThisAttribute(Op))
343         MDs.push_back(Op);
344       else
345         Changed = true;
346     }
347   } else {
348     // Modified if we dropped at least one attribute.
349     Changed = OrigLoopID->getNumOperands() > 1;
350   }
351 
352   bool HasAnyFollowup = false;
353   for (StringRef OptionName : FollowupOptions) {
354     MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName);
355     if (!FollowupNode)
356       continue;
357 
358     HasAnyFollowup = true;
359     for (const MDOperand &Option : drop_begin(FollowupNode->operands(), 1)) {
360       MDs.push_back(Option.get());
361       Changed = true;
362     }
363   }
364 
365   // Attributes of the followup loop not specified explicity, so signal to the
366   // transformation pass to add suitable attributes.
367   if (!AlwaysNew && !HasAnyFollowup)
368     return None;
369 
370   // If no attributes were added or remove, the previous loop Id can be reused.
371   if (!AlwaysNew && !Changed)
372     return OrigLoopID;
373 
374   // No attributes is equivalent to having no !llvm.loop metadata at all.
375   if (MDs.size() == 1)
376     return nullptr;
377 
378   // Build the new loop ID.
379   MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs);
380   FollowupLoopID->replaceOperandWith(0, FollowupLoopID);
381   return FollowupLoopID;
382 }
383 
384 bool llvm::hasDisableAllTransformsHint(const Loop *L) {
385   return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced);
386 }
387 
388 bool llvm::hasDisableLICMTransformsHint(const Loop *L) {
389   return getBooleanLoopAttribute(L, LLVMLoopDisableLICM);
390 }
391 
392 TransformationMode llvm::hasUnrollTransformation(Loop *L) {
393   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable"))
394     return TM_SuppressedByUser;
395 
396   Optional<int> Count =
397       getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
398   if (Count.hasValue())
399     return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
400 
401   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
402     return TM_ForcedByUser;
403 
404   if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full"))
405     return TM_ForcedByUser;
406 
407   if (hasDisableAllTransformsHint(L))
408     return TM_Disable;
409 
410   return TM_Unspecified;
411 }
412 
413 TransformationMode llvm::hasUnrollAndJamTransformation(Loop *L) {
414   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable"))
415     return TM_SuppressedByUser;
416 
417   Optional<int> Count =
418       getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
419   if (Count.hasValue())
420     return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
421 
422   if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
423     return TM_ForcedByUser;
424 
425   if (hasDisableAllTransformsHint(L))
426     return TM_Disable;
427 
428   return TM_Unspecified;
429 }
430 
431 TransformationMode llvm::hasVectorizeTransformation(Loop *L) {
432   Optional<bool> Enable =
433       getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable");
434 
435   if (Enable == false)
436     return TM_SuppressedByUser;
437 
438   Optional<int> VectorizeWidth =
439       getOptionalIntLoopAttribute(L, "llvm.loop.vectorize.width");
440   Optional<int> InterleaveCount =
441       getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count");
442 
443   // 'Forcing' vector width and interleave count to one effectively disables
444   // this tranformation.
445   if (Enable == true && VectorizeWidth == 1 && InterleaveCount == 1)
446     return TM_SuppressedByUser;
447 
448   if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
449     return TM_Disable;
450 
451   if (Enable == true)
452     return TM_ForcedByUser;
453 
454   if (VectorizeWidth == 1 && InterleaveCount == 1)
455     return TM_Disable;
456 
457   if (VectorizeWidth > 1 || InterleaveCount > 1)
458     return TM_Enable;
459 
460   if (hasDisableAllTransformsHint(L))
461     return TM_Disable;
462 
463   return TM_Unspecified;
464 }
465 
466 TransformationMode llvm::hasDistributeTransformation(Loop *L) {
467   if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable"))
468     return TM_ForcedByUser;
469 
470   if (hasDisableAllTransformsHint(L))
471     return TM_Disable;
472 
473   return TM_Unspecified;
474 }
475 
476 TransformationMode llvm::hasLICMVersioningTransformation(Loop *L) {
477   if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable"))
478     return TM_SuppressedByUser;
479 
480   if (hasDisableAllTransformsHint(L))
481     return TM_Disable;
482 
483   return TM_Unspecified;
484 }
485 
486 /// Does a BFS from a given node to all of its children inside a given loop.
487 /// The returned vector of nodes includes the starting point.
488 SmallVector<DomTreeNode *, 16>
489 llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
490   SmallVector<DomTreeNode *, 16> Worklist;
491   auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
492     // Only include subregions in the top level loop.
493     BasicBlock *BB = DTN->getBlock();
494     if (CurLoop->contains(BB))
495       Worklist.push_back(DTN);
496   };
497 
498   AddRegionToWorklist(N);
499 
500   for (size_t I = 0; I < Worklist.size(); I++)
501     for (DomTreeNode *Child : Worklist[I]->getChildren())
502       AddRegionToWorklist(Child);
503 
504   return Worklist;
505 }
506 
507 void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT = nullptr,
508                           ScalarEvolution *SE = nullptr,
509                           LoopInfo *LI = nullptr) {
510   assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
511   auto *Preheader = L->getLoopPreheader();
512   assert(Preheader && "Preheader should exist!");
513 
514   // Now that we know the removal is safe, remove the loop by changing the
515   // branch from the preheader to go to the single exit block.
516   //
517   // Because we're deleting a large chunk of code at once, the sequence in which
518   // we remove things is very important to avoid invalidation issues.
519 
520   // Tell ScalarEvolution that the loop is deleted. Do this before
521   // deleting the loop so that ScalarEvolution can look at the loop
522   // to determine what it needs to clean up.
523   if (SE)
524     SE->forgetLoop(L);
525 
526   auto *ExitBlock = L->getUniqueExitBlock();
527   assert(ExitBlock && "Should have a unique exit block!");
528   assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
529 
530   auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
531   assert(OldBr && "Preheader must end with a branch");
532   assert(OldBr->isUnconditional() && "Preheader must have a single successor");
533   // Connect the preheader to the exit block. Keep the old edge to the header
534   // around to perform the dominator tree update in two separate steps
535   // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
536   // preheader -> header.
537   //
538   //
539   // 0.  Preheader          1.  Preheader           2.  Preheader
540   //        |                    |   |                   |
541   //        V                    |   V                   |
542   //      Header <--\            | Header <--\           | Header <--\
543   //       |  |     |            |  |  |     |           |  |  |     |
544   //       |  V     |            |  |  V     |           |  |  V     |
545   //       | Body --/            |  | Body --/           |  | Body --/
546   //       V                     V  V                    V  V
547   //      Exit                   Exit                    Exit
548   //
549   // By doing this is two separate steps we can perform the dominator tree
550   // update without using the batch update API.
551   //
552   // Even when the loop is never executed, we cannot remove the edge from the
553   // source block to the exit block. Consider the case where the unexecuted loop
554   // branches back to an outer loop. If we deleted the loop and removed the edge
555   // coming to this inner loop, this will break the outer loop structure (by
556   // deleting the backedge of the outer loop). If the outer loop is indeed a
557   // non-loop, it will be deleted in a future iteration of loop deletion pass.
558   IRBuilder<> Builder(OldBr);
559   Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
560   // Remove the old branch. The conditional branch becomes a new terminator.
561   OldBr->eraseFromParent();
562 
563   // Rewrite phis in the exit block to get their inputs from the Preheader
564   // instead of the exiting block.
565   for (PHINode &P : ExitBlock->phis()) {
566     // Set the zero'th element of Phi to be from the preheader and remove all
567     // other incoming values. Given the loop has dedicated exits, all other
568     // incoming values must be from the exiting blocks.
569     int PredIndex = 0;
570     P.setIncomingBlock(PredIndex, Preheader);
571     // Removes all incoming values from all other exiting blocks (including
572     // duplicate values from an exiting block).
573     // Nuke all entries except the zero'th entry which is the preheader entry.
574     // NOTE! We need to remove Incoming Values in the reverse order as done
575     // below, to keep the indices valid for deletion (removeIncomingValues
576     // updates getNumIncomingValues and shifts all values down into the operand
577     // being deleted).
578     for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
579       P.removeIncomingValue(e - i, false);
580 
581     assert((P.getNumIncomingValues() == 1 &&
582             P.getIncomingBlock(PredIndex) == Preheader) &&
583            "Should have exactly one value and that's from the preheader!");
584   }
585 
586   // Disconnect the loop body by branching directly to its exit.
587   Builder.SetInsertPoint(Preheader->getTerminator());
588   Builder.CreateBr(ExitBlock);
589   // Remove the old branch.
590   Preheader->getTerminator()->eraseFromParent();
591 
592   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
593   if (DT) {
594     // Update the dominator tree by informing it about the new edge from the
595     // preheader to the exit and the removed edge.
596     DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock},
597                       {DominatorTree::Delete, Preheader, L->getHeader()}});
598   }
599 
600   // Use a map to unique and a vector to guarantee deterministic ordering.
601   llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet;
602   llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst;
603 
604   // Given LCSSA form is satisfied, we should not have users of instructions
605   // within the dead loop outside of the loop. However, LCSSA doesn't take
606   // unreachable uses into account. We handle them here.
607   // We could do it after drop all references (in this case all users in the
608   // loop will be already eliminated and we have less work to do but according
609   // to API doc of User::dropAllReferences only valid operation after dropping
610   // references, is deletion. So let's substitute all usages of
611   // instruction from the loop with undef value of corresponding type first.
612   for (auto *Block : L->blocks())
613     for (Instruction &I : *Block) {
614       auto *Undef = UndefValue::get(I.getType());
615       for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) {
616         Use &U = *UI;
617         ++UI;
618         if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
619           if (L->contains(Usr->getParent()))
620             continue;
621         // If we have a DT then we can check that uses outside a loop only in
622         // unreachable block.
623         if (DT)
624           assert(!DT->isReachableFromEntry(U) &&
625                  "Unexpected user in reachable block");
626         U.set(Undef);
627       }
628       auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I);
629       if (!DVI)
630         continue;
631       auto Key = DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()});
632       if (Key != DeadDebugSet.end())
633         continue;
634       DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()});
635       DeadDebugInst.push_back(DVI);
636     }
637 
638   // After the loop has been deleted all the values defined and modified
639   // inside the loop are going to be unavailable.
640   // Since debug values in the loop have been deleted, inserting an undef
641   // dbg.value truncates the range of any dbg.value before the loop where the
642   // loop used to be. This is particularly important for constant values.
643   DIBuilder DIB(*ExitBlock->getModule());
644   Instruction *InsertDbgValueBefore = ExitBlock->getFirstNonPHI();
645   assert(InsertDbgValueBefore &&
646          "There should be a non-PHI instruction in exit block, else these "
647          "instructions will have no parent.");
648   for (auto *DVI : DeadDebugInst)
649     DIB.insertDbgValueIntrinsic(UndefValue::get(Builder.getInt32Ty()),
650                                 DVI->getVariable(), DVI->getExpression(),
651                                 DVI->getDebugLoc(), InsertDbgValueBefore);
652 
653   // Remove the block from the reference counting scheme, so that we can
654   // delete it freely later.
655   for (auto *Block : L->blocks())
656     Block->dropAllReferences();
657 
658   if (LI) {
659     // Erase the instructions and the blocks without having to worry
660     // about ordering because we already dropped the references.
661     // NOTE: This iteration is safe because erasing the block does not remove
662     // its entry from the loop's block list.  We do that in the next section.
663     for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end();
664          LpI != LpE; ++LpI)
665       (*LpI)->eraseFromParent();
666 
667     // Finally, the blocks from loopinfo.  This has to happen late because
668     // otherwise our loop iterators won't work.
669 
670     SmallPtrSet<BasicBlock *, 8> blocks;
671     blocks.insert(L->block_begin(), L->block_end());
672     for (BasicBlock *BB : blocks)
673       LI->removeBlock(BB);
674 
675     // The last step is to update LoopInfo now that we've eliminated this loop.
676     LI->erase(L);
677   }
678 }
679 
680 Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) {
681   // Support loops with an exiting latch and other existing exists only
682   // deoptimize.
683 
684   // Get the branch weights for the loop's backedge.
685   BasicBlock *Latch = L->getLoopLatch();
686   if (!Latch)
687     return None;
688   BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator());
689   if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch))
690     return None;
691 
692   assert((LatchBR->getSuccessor(0) == L->getHeader() ||
693           LatchBR->getSuccessor(1) == L->getHeader()) &&
694          "At least one edge out of the latch must go to the header");
695 
696   SmallVector<BasicBlock *, 4> ExitBlocks;
697   L->getUniqueNonLatchExitBlocks(ExitBlocks);
698   if (any_of(ExitBlocks, [](const BasicBlock *EB) {
699         return !EB->getTerminatingDeoptimizeCall();
700       }))
701     return None;
702 
703   // To estimate the number of times the loop body was executed, we want to
704   // know the number of times the backedge was taken, vs. the number of times
705   // we exited the loop.
706   uint64_t TrueVal, FalseVal;
707   if (!LatchBR->extractProfMetadata(TrueVal, FalseVal))
708     return None;
709 
710   if (!TrueVal || !FalseVal)
711     return 0;
712 
713   // Divide the count of the backedge by the count of the edge exiting the loop,
714   // rounding to nearest.
715   if (LatchBR->getSuccessor(0) == L->getHeader())
716     return (TrueVal + (FalseVal / 2)) / FalseVal;
717   else
718     return (FalseVal + (TrueVal / 2)) / TrueVal;
719 }
720 
721 bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
722                                               ScalarEvolution &SE) {
723   Loop *OuterL = InnerLoop->getParentLoop();
724   if (!OuterL)
725     return true;
726 
727   // Get the backedge taken count for the inner loop
728   BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
729   const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
730   if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
731       !InnerLoopBECountSC->getType()->isIntegerTy())
732     return false;
733 
734   // Get whether count is invariant to the outer loop
735   ScalarEvolution::LoopDisposition LD =
736       SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
737   if (LD != ScalarEvolution::LoopInvariant)
738     return false;
739 
740   return true;
741 }
742 
743 Value *llvm::createMinMaxOp(IRBuilder<> &Builder,
744                             RecurrenceDescriptor::MinMaxRecurrenceKind RK,
745                             Value *Left, Value *Right) {
746   CmpInst::Predicate P = CmpInst::ICMP_NE;
747   switch (RK) {
748   default:
749     llvm_unreachable("Unknown min/max recurrence kind");
750   case RecurrenceDescriptor::MRK_UIntMin:
751     P = CmpInst::ICMP_ULT;
752     break;
753   case RecurrenceDescriptor::MRK_UIntMax:
754     P = CmpInst::ICMP_UGT;
755     break;
756   case RecurrenceDescriptor::MRK_SIntMin:
757     P = CmpInst::ICMP_SLT;
758     break;
759   case RecurrenceDescriptor::MRK_SIntMax:
760     P = CmpInst::ICMP_SGT;
761     break;
762   case RecurrenceDescriptor::MRK_FloatMin:
763     P = CmpInst::FCMP_OLT;
764     break;
765   case RecurrenceDescriptor::MRK_FloatMax:
766     P = CmpInst::FCMP_OGT;
767     break;
768   }
769 
770   // We only match FP sequences that are 'fast', so we can unconditionally
771   // set it on any generated instructions.
772   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
773   FastMathFlags FMF;
774   FMF.setFast();
775   Builder.setFastMathFlags(FMF);
776 
777   Value *Cmp;
778   if (RK == RecurrenceDescriptor::MRK_FloatMin ||
779       RK == RecurrenceDescriptor::MRK_FloatMax)
780     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
781   else
782     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
783 
784   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
785   return Select;
786 }
787 
788 // Helper to generate an ordered reduction.
789 Value *
790 llvm::getOrderedReduction(IRBuilder<> &Builder, Value *Acc, Value *Src,
791                           unsigned Op,
792                           RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
793                           ArrayRef<Value *> RedOps) {
794   unsigned VF = Src->getType()->getVectorNumElements();
795 
796   // Extract and apply reduction ops in ascending order:
797   // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
798   Value *Result = Acc;
799   for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
800     Value *Ext =
801         Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
802 
803     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
804       Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
805                                    "bin.rdx");
806     } else {
807       assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
808              "Invalid min/max");
809       Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext);
810     }
811 
812     if (!RedOps.empty())
813       propagateIRFlags(Result, RedOps);
814   }
815 
816   return Result;
817 }
818 
819 // Helper to generate a log2 shuffle reduction.
820 Value *
821 llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op,
822                           RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
823                           ArrayRef<Value *> RedOps) {
824   unsigned VF = Src->getType()->getVectorNumElements();
825   // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
826   // and vector ops, reducing the set of values being computed by half each
827   // round.
828   assert(isPowerOf2_32(VF) &&
829          "Reduction emission only supported for pow2 vectors!");
830   Value *TmpVec = Src;
831   SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
832   for (unsigned i = VF; i != 1; i >>= 1) {
833     // Move the upper half of the vector to the lower half.
834     for (unsigned j = 0; j != i / 2; ++j)
835       ShuffleMask[j] = Builder.getInt32(i / 2 + j);
836 
837     // Fill the rest of the mask with undef.
838     std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
839               UndefValue::get(Builder.getInt32Ty()));
840 
841     Value *Shuf = Builder.CreateShuffleVector(
842         TmpVec, UndefValue::get(TmpVec->getType()),
843         ConstantVector::get(ShuffleMask), "rdx.shuf");
844 
845     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
846       // The builder propagates its fast-math-flags setting.
847       TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
848                                    "bin.rdx");
849     } else {
850       assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
851              "Invalid min/max");
852       TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf);
853     }
854     if (!RedOps.empty())
855       propagateIRFlags(TmpVec, RedOps);
856   }
857   // The result is in the first element of the vector.
858   return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
859 }
860 
861 /// Create a simple vector reduction specified by an opcode and some
862 /// flags (if generating min/max reductions).
863 Value *llvm::createSimpleTargetReduction(
864     IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode,
865     Value *Src, TargetTransformInfo::ReductionFlags Flags,
866     ArrayRef<Value *> RedOps) {
867   assert(isa<VectorType>(Src->getType()) && "Type must be a vector");
868 
869   std::function<Value *()> BuildFunc;
870   using RD = RecurrenceDescriptor;
871   RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
872 
873   switch (Opcode) {
874   case Instruction::Add:
875     BuildFunc = [&]() { return Builder.CreateAddReduce(Src); };
876     break;
877   case Instruction::Mul:
878     BuildFunc = [&]() { return Builder.CreateMulReduce(Src); };
879     break;
880   case Instruction::And:
881     BuildFunc = [&]() { return Builder.CreateAndReduce(Src); };
882     break;
883   case Instruction::Or:
884     BuildFunc = [&]() { return Builder.CreateOrReduce(Src); };
885     break;
886   case Instruction::Xor:
887     BuildFunc = [&]() { return Builder.CreateXorReduce(Src); };
888     break;
889   case Instruction::FAdd:
890     BuildFunc = [&]() {
891       auto Rdx = Builder.CreateFAddReduce(
892           Constant::getNullValue(Src->getType()->getVectorElementType()), Src);
893       return Rdx;
894     };
895     break;
896   case Instruction::FMul:
897     BuildFunc = [&]() {
898       Type *Ty = Src->getType()->getVectorElementType();
899       auto Rdx = Builder.CreateFMulReduce(ConstantFP::get(Ty, 1.0), Src);
900       return Rdx;
901     };
902     break;
903   case Instruction::ICmp:
904     if (Flags.IsMaxOp) {
905       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
906       BuildFunc = [&]() {
907         return Builder.CreateIntMaxReduce(Src, Flags.IsSigned);
908       };
909     } else {
910       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
911       BuildFunc = [&]() {
912         return Builder.CreateIntMinReduce(Src, Flags.IsSigned);
913       };
914     }
915     break;
916   case Instruction::FCmp:
917     if (Flags.IsMaxOp) {
918       MinMaxKind = RD::MRK_FloatMax;
919       BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); };
920     } else {
921       MinMaxKind = RD::MRK_FloatMin;
922       BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); };
923     }
924     break;
925   default:
926     llvm_unreachable("Unhandled opcode");
927     break;
928   }
929   if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags))
930     return BuildFunc();
931   return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps);
932 }
933 
934 /// Create a vector reduction using a given recurrence descriptor.
935 Value *llvm::createTargetReduction(IRBuilder<> &B,
936                                    const TargetTransformInfo *TTI,
937                                    RecurrenceDescriptor &Desc, Value *Src,
938                                    bool NoNaN) {
939   // TODO: Support in-order reductions based on the recurrence descriptor.
940   using RD = RecurrenceDescriptor;
941   RD::RecurrenceKind RecKind = Desc.getRecurrenceKind();
942   TargetTransformInfo::ReductionFlags Flags;
943   Flags.NoNaN = NoNaN;
944 
945   // All ops in the reduction inherit fast-math-flags from the recurrence
946   // descriptor.
947   IRBuilder<>::FastMathFlagGuard FMFGuard(B);
948   B.setFastMathFlags(Desc.getFastMathFlags());
949 
950   switch (RecKind) {
951   case RD::RK_FloatAdd:
952     return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags);
953   case RD::RK_FloatMult:
954     return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags);
955   case RD::RK_IntegerAdd:
956     return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags);
957   case RD::RK_IntegerMult:
958     return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags);
959   case RD::RK_IntegerAnd:
960     return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags);
961   case RD::RK_IntegerOr:
962     return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags);
963   case RD::RK_IntegerXor:
964     return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags);
965   case RD::RK_IntegerMinMax: {
966     RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind();
967     Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax);
968     Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin);
969     return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags);
970   }
971   case RD::RK_FloatMinMax: {
972     Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax;
973     return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags);
974   }
975   default:
976     llvm_unreachable("Unhandled RecKind");
977   }
978 }
979 
980 void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
981   auto *VecOp = dyn_cast<Instruction>(I);
982   if (!VecOp)
983     return;
984   auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
985                                             : dyn_cast<Instruction>(OpValue);
986   if (!Intersection)
987     return;
988   const unsigned Opcode = Intersection->getOpcode();
989   VecOp->copyIRFlags(Intersection);
990   for (auto *V : VL) {
991     auto *Instr = dyn_cast<Instruction>(V);
992     if (!Instr)
993       continue;
994     if (OpValue == nullptr || Opcode == Instr->getOpcode())
995       VecOp->andIRFlags(V);
996   }
997 }
998 
999 bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L,
1000                                  ScalarEvolution &SE) {
1001   const SCEV *Zero = SE.getZero(S->getType());
1002   return SE.isAvailableAtLoopEntry(S, L) &&
1003          SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero);
1004 }
1005 
1006 bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L,
1007                                     ScalarEvolution &SE) {
1008   const SCEV *Zero = SE.getZero(S->getType());
1009   return SE.isAvailableAtLoopEntry(S, L) &&
1010          SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero);
1011 }
1012 
1013 bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1014                              bool Signed) {
1015   unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1016   APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) :
1017     APInt::getMinValue(BitWidth);
1018   auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1019   return SE.isAvailableAtLoopEntry(S, L) &&
1020          SE.isLoopEntryGuardedByCond(L, Predicate, S,
1021                                      SE.getConstant(Min));
1022 }
1023 
1024 bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
1025                              bool Signed) {
1026   unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1027   APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) :
1028     APInt::getMaxValue(BitWidth);
1029   auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1030   return SE.isAvailableAtLoopEntry(S, L) &&
1031          SE.isLoopEntryGuardedByCond(L, Predicate, S,
1032                                      SE.getConstant(Max));
1033 }
1034