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