]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Transforms/Utils/LoopUnroll.cpp
Merge llvm, clang, lld and lldb release_40 branch r292009. Also update
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Transforms / Utils / LoopUnroll.cpp
1 //===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===//
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 implements some loop unrolling utilities. It does not define any
11 // actual pass or policy, but provides a single function to perform loop
12 // unrolling.
13 //
14 // The process of unrolling can produce extraneous basic blocks linked with
15 // unconditional branches.  This will be corrected in the future.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Transforms/Utils/UnrollLoop.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AssumptionCache.h"
23 #include "llvm/Analysis/InstructionSimplify.h"
24 #include "llvm/Analysis/LoopIterator.h"
25 #include "llvm/Analysis/LoopPass.h"
26 #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
27 #include "llvm/Analysis/ScalarEvolution.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36 #include "llvm/Transforms/Utils/Cloning.h"
37 #include "llvm/Transforms/Utils/Local.h"
38 #include "llvm/Transforms/Utils/LoopSimplify.h"
39 #include "llvm/Transforms/Utils/LoopUtils.h"
40 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
41 using namespace llvm;
42
43 #define DEBUG_TYPE "loop-unroll"
44
45 // TODO: Should these be here or in LoopUnroll?
46 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
47 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
48
49 static cl::opt<bool>
50 UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden,
51                     cl::desc("Allow runtime unrolled loops to be unrolled "
52                              "with epilog instead of prolog."));
53
54 /// Convert the instruction operands from referencing the current values into
55 /// those specified by VMap.
56 static inline void remapInstruction(Instruction *I,
57                                     ValueToValueMapTy &VMap) {
58   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
59     Value *Op = I->getOperand(op);
60     ValueToValueMapTy::iterator It = VMap.find(Op);
61     if (It != VMap.end())
62       I->setOperand(op, It->second);
63   }
64
65   if (PHINode *PN = dyn_cast<PHINode>(I)) {
66     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
67       ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i));
68       if (It != VMap.end())
69         PN->setIncomingBlock(i, cast<BasicBlock>(It->second));
70     }
71   }
72 }
73
74 /// Folds a basic block into its predecessor if it only has one predecessor, and
75 /// that predecessor only has one successor.
76 /// The LoopInfo Analysis that is passed will be kept consistent.  If folding is
77 /// successful references to the containing loop must be removed from
78 /// ScalarEvolution by calling ScalarEvolution::forgetLoop because SE may have
79 /// references to the eliminated BB.  The argument ForgottenLoops contains a set
80 /// of loops that have already been forgotten to prevent redundant, expensive
81 /// calls to ScalarEvolution::forgetLoop.  Returns the new combined block.
82 static BasicBlock *
83 foldBlockIntoPredecessor(BasicBlock *BB, LoopInfo *LI, ScalarEvolution *SE,
84                          SmallPtrSetImpl<Loop *> &ForgottenLoops,
85                          DominatorTree *DT) {
86   // Merge basic blocks into their predecessor if there is only one distinct
87   // pred, and if there is only one distinct successor of the predecessor, and
88   // if there are no PHI nodes.
89   BasicBlock *OnlyPred = BB->getSinglePredecessor();
90   if (!OnlyPred) return nullptr;
91
92   if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
93     return nullptr;
94
95   DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred);
96
97   // Resolve any PHI nodes at the start of the block.  They are all
98   // guaranteed to have exactly one entry if they exist, unless there are
99   // multiple duplicate (but guaranteed to be equal) entries for the
100   // incoming edges.  This occurs when there are multiple edges from
101   // OnlyPred to OnlySucc.
102   FoldSingleEntryPHINodes(BB);
103
104   // Delete the unconditional branch from the predecessor...
105   OnlyPred->getInstList().pop_back();
106
107   // Make all PHI nodes that referred to BB now refer to Pred as their
108   // source...
109   BB->replaceAllUsesWith(OnlyPred);
110
111   // Move all definitions in the successor to the predecessor...
112   OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
113
114   // OldName will be valid until erased.
115   StringRef OldName = BB->getName();
116
117   // Erase the old block and update dominator info.
118   if (DT)
119     if (DomTreeNode *DTN = DT->getNode(BB)) {
120       DomTreeNode *PredDTN = DT->getNode(OnlyPred);
121       SmallVector<DomTreeNode *, 8> Children(DTN->begin(), DTN->end());
122       for (auto *DI : Children)
123         DT->changeImmediateDominator(DI, PredDTN);
124
125       DT->eraseNode(BB);
126     }
127
128   // ScalarEvolution holds references to loop exit blocks.
129   if (SE) {
130     if (Loop *L = LI->getLoopFor(BB)) {
131       if (ForgottenLoops.insert(L).second)
132         SE->forgetLoop(L);
133     }
134   }
135   LI->removeBlock(BB);
136
137   // Inherit predecessor's name if it exists...
138   if (!OldName.empty() && !OnlyPred->hasName())
139     OnlyPred->setName(OldName);
140
141   BB->eraseFromParent();
142
143   return OnlyPred;
144 }
145
146 /// Check if unrolling created a situation where we need to insert phi nodes to
147 /// preserve LCSSA form.
148 /// \param Blocks is a vector of basic blocks representing unrolled loop.
149 /// \param L is the outer loop.
150 /// It's possible that some of the blocks are in L, and some are not. In this
151 /// case, if there is a use is outside L, and definition is inside L, we need to
152 /// insert a phi-node, otherwise LCSSA will be broken.
153 /// The function is just a helper function for llvm::UnrollLoop that returns
154 /// true if this situation occurs, indicating that LCSSA needs to be fixed.
155 static bool needToInsertPhisForLCSSA(Loop *L, std::vector<BasicBlock *> Blocks,
156                                      LoopInfo *LI) {
157   for (BasicBlock *BB : Blocks) {
158     if (LI->getLoopFor(BB) == L)
159       continue;
160     for (Instruction &I : *BB) {
161       for (Use &U : I.operands()) {
162         if (auto Def = dyn_cast<Instruction>(U)) {
163           Loop *DefLoop = LI->getLoopFor(Def->getParent());
164           if (!DefLoop)
165             continue;
166           if (DefLoop->contains(L))
167             return true;
168         }
169       }
170     }
171   }
172   return false;
173 }
174
175 /// Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary
176 /// and adds a mapping from the original loop to the new loop to NewLoops.
177 /// Returns nullptr if no new loop was created and a pointer to the
178 /// original loop OriginalBB was part of otherwise.
179 const Loop* llvm::addClonedBlockToLoopInfo(BasicBlock *OriginalBB,
180                                            BasicBlock *ClonedBB, LoopInfo *LI,
181                                            NewLoopsMap &NewLoops) {
182   // Figure out which loop New is in.
183   const Loop *OldLoop = LI->getLoopFor(OriginalBB);
184   assert(OldLoop && "Should (at least) be in the loop being unrolled!");
185
186   Loop *&NewLoop = NewLoops[OldLoop];
187   if (!NewLoop) {
188     // Found a new sub-loop.
189     assert(OriginalBB == OldLoop->getHeader() &&
190            "Header should be first in RPO");
191
192     Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
193     assert(NewLoopParent &&
194            "Expected parent loop before sub-loop in RPO");
195     NewLoop = new Loop;
196     NewLoopParent->addChildLoop(NewLoop);
197     NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
198     return OldLoop;
199   } else {
200     NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
201     return nullptr;
202   }
203 }
204
205 /// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
206 /// if unrolling was successful, or false if the loop was unmodified. Unrolling
207 /// can only fail when the loop's latch block is not terminated by a conditional
208 /// branch instruction. However, if the trip count (and multiple) are not known,
209 /// loop unrolling will mostly produce more code that is no faster.
210 ///
211 /// TripCount is the upper bound of the iteration on which control exits
212 /// LatchBlock. Control may exit the loop prior to TripCount iterations either
213 /// via an early branch in other loop block or via LatchBlock terminator. This
214 /// is relaxed from the general definition of trip count which is the number of
215 /// times the loop header executes. Note that UnrollLoop assumes that the loop
216 /// counter test is in LatchBlock in order to remove unnecesssary instances of
217 /// the test.  If control can exit the loop from the LatchBlock's terminator
218 /// prior to TripCount iterations, flag PreserveCondBr needs to be set.
219 ///
220 /// PreserveCondBr indicates whether the conditional branch of the LatchBlock
221 /// needs to be preserved.  It is needed when we use trip count upper bound to
222 /// fully unroll the loop. If PreserveOnlyFirst is also set then only the first
223 /// conditional branch needs to be preserved.
224 ///
225 /// Similarly, TripMultiple divides the number of times that the LatchBlock may
226 /// execute without exiting the loop.
227 ///
228 /// If AllowRuntime is true then UnrollLoop will consider unrolling loops that
229 /// have a runtime (i.e. not compile time constant) trip count.  Unrolling these
230 /// loops require a unroll "prologue" that runs "RuntimeTripCount % Count"
231 /// iterations before branching into the unrolled loop.  UnrollLoop will not
232 /// runtime-unroll the loop if computing RuntimeTripCount will be expensive and
233 /// AllowExpensiveTripCount is false.
234 ///
235 /// If we want to perform PGO-based loop peeling, PeelCount is set to the 
236 /// number of iterations we want to peel off.
237 ///
238 /// The LoopInfo Analysis that is passed will be kept consistent.
239 ///
240 /// This utility preserves LoopInfo. It will also preserve ScalarEvolution and
241 /// DominatorTree if they are non-null.
242 bool llvm::UnrollLoop(Loop *L, unsigned Count, unsigned TripCount, bool Force,
243                       bool AllowRuntime, bool AllowExpensiveTripCount,
244                       bool PreserveCondBr, bool PreserveOnlyFirst,
245                       unsigned TripMultiple, unsigned PeelCount, LoopInfo *LI,
246                       ScalarEvolution *SE, DominatorTree *DT,
247                       AssumptionCache *AC, OptimizationRemarkEmitter *ORE,
248                       bool PreserveLCSSA) {
249
250   BasicBlock *Preheader = L->getLoopPreheader();
251   if (!Preheader) {
252     DEBUG(dbgs() << "  Can't unroll; loop preheader-insertion failed.\n");
253     return false;
254   }
255
256   BasicBlock *LatchBlock = L->getLoopLatch();
257   if (!LatchBlock) {
258     DEBUG(dbgs() << "  Can't unroll; loop exit-block-insertion failed.\n");
259     return false;
260   }
261
262   // Loops with indirectbr cannot be cloned.
263   if (!L->isSafeToClone()) {
264     DEBUG(dbgs() << "  Can't unroll; Loop body cannot be cloned.\n");
265     return false;
266   }
267
268   BasicBlock *Header = L->getHeader();
269   BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
270
271   if (!BI || BI->isUnconditional()) {
272     // The loop-rotate pass can be helpful to avoid this in many cases.
273     DEBUG(dbgs() <<
274              "  Can't unroll; loop not terminated by a conditional branch.\n");
275     return false;
276   }
277
278   if (Header->hasAddressTaken()) {
279     // The loop-rotate pass can be helpful to avoid this in many cases.
280     DEBUG(dbgs() <<
281           "  Won't unroll loop: address of header block is taken.\n");
282     return false;
283   }
284
285   if (TripCount != 0)
286     DEBUG(dbgs() << "  Trip Count = " << TripCount << "\n");
287   if (TripMultiple != 1)
288     DEBUG(dbgs() << "  Trip Multiple = " << TripMultiple << "\n");
289
290   // Effectively "DCE" unrolled iterations that are beyond the tripcount
291   // and will never be executed.
292   if (TripCount != 0 && Count > TripCount)
293     Count = TripCount;
294
295   // Don't enter the unroll code if there is nothing to do.
296   if (TripCount == 0 && Count < 2 && PeelCount == 0)
297     return false;
298
299   assert(Count > 0);
300   assert(TripMultiple > 0);
301   assert(TripCount == 0 || TripCount % TripMultiple == 0);
302
303   // Are we eliminating the loop control altogether?
304   bool CompletelyUnroll = Count == TripCount;
305   SmallVector<BasicBlock *, 4> ExitBlocks;
306   L->getExitBlocks(ExitBlocks);
307   std::vector<BasicBlock*> OriginalLoopBlocks = L->getBlocks();
308
309   // Go through all exits of L and see if there are any phi-nodes there. We just
310   // conservatively assume that they're inserted to preserve LCSSA form, which
311   // means that complete unrolling might break this form. We need to either fix
312   // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
313   // now we just recompute LCSSA for the outer loop, but it should be possible
314   // to fix it in-place.
315   bool NeedToFixLCSSA = PreserveLCSSA && CompletelyUnroll &&
316                         any_of(ExitBlocks, [](const BasicBlock *BB) {
317                           return isa<PHINode>(BB->begin());
318                         });
319
320   // We assume a run-time trip count if the compiler cannot
321   // figure out the loop trip count and the unroll-runtime
322   // flag is specified.
323   bool RuntimeTripCount = (TripCount == 0 && Count > 0 && AllowRuntime);
324
325   assert((!RuntimeTripCount || !PeelCount) &&
326          "Did not expect runtime trip-count unrolling "
327          "and peeling for the same loop");
328
329   if (PeelCount)
330     peelLoop(L, PeelCount, LI, SE, DT, PreserveLCSSA);
331
332   // Loops containing convergent instructions must have a count that divides
333   // their TripMultiple.
334   DEBUG(
335       {
336         bool HasConvergent = false;
337         for (auto &BB : L->blocks())
338           for (auto &I : *BB)
339             if (auto CS = CallSite(&I))
340               HasConvergent |= CS.isConvergent();
341         assert((!HasConvergent || TripMultiple % Count == 0) &&
342                "Unroll count must divide trip multiple if loop contains a "
343                "convergent operation.");
344       });
345
346   if (RuntimeTripCount && TripMultiple % Count != 0 &&
347       !UnrollRuntimeLoopRemainder(L, Count, AllowExpensiveTripCount,
348                                   UnrollRuntimeEpilog, LI, SE, DT, 
349                                   PreserveLCSSA)) {
350     if (Force)
351       RuntimeTripCount = false;
352     else
353       return false;
354   }
355
356   // Notify ScalarEvolution that the loop will be substantially changed,
357   // if not outright eliminated.
358   if (SE)
359     SE->forgetLoop(L);
360
361   // If we know the trip count, we know the multiple...
362   unsigned BreakoutTrip = 0;
363   if (TripCount != 0) {
364     BreakoutTrip = TripCount % Count;
365     TripMultiple = 0;
366   } else {
367     // Figure out what multiple to use.
368     BreakoutTrip = TripMultiple =
369       (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
370   }
371
372   using namespace ore;
373   // Report the unrolling decision.
374   if (CompletelyUnroll) {
375     DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
376           << " with trip count " << TripCount << "!\n");
377     ORE->emit(OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(),
378                                  L->getHeader())
379               << "completely unrolled loop with "
380               << NV("UnrollCount", TripCount) << " iterations");
381   } else if (PeelCount) {
382     DEBUG(dbgs() << "PEELING loop %" << Header->getName()
383                  << " with iteration count " << PeelCount << "!\n");
384     ORE->emit(OptimizationRemark(DEBUG_TYPE, "Peeled", L->getStartLoc(),
385                                  L->getHeader())
386               << " peeled loop by " << NV("PeelCount", PeelCount)
387               << " iterations");
388   } else {
389     OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(),
390                             L->getHeader());
391     Diag << "unrolled loop by a factor of " << NV("UnrollCount", Count);
392
393     DEBUG(dbgs() << "UNROLLING loop %" << Header->getName()
394           << " by " << Count);
395     if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
396       DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
397       ORE->emit(Diag << " with a breakout at trip "
398                      << NV("BreakoutTrip", BreakoutTrip));
399     } else if (TripMultiple != 1) {
400       DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
401       ORE->emit(Diag << " with " << NV("TripMultiple", TripMultiple)
402                      << " trips per branch");
403     } else if (RuntimeTripCount) {
404       DEBUG(dbgs() << " with run-time trip count");
405       ORE->emit(Diag << " with run-time trip count");
406     }
407     DEBUG(dbgs() << "!\n");
408   }
409
410   bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
411   BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
412
413   // For the first iteration of the loop, we should use the precloned values for
414   // PHI nodes.  Insert associations now.
415   ValueToValueMapTy LastValueMap;
416   std::vector<PHINode*> OrigPHINode;
417   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
418     OrigPHINode.push_back(cast<PHINode>(I));
419   }
420
421   std::vector<BasicBlock*> Headers;
422   std::vector<BasicBlock*> Latches;
423   Headers.push_back(Header);
424   Latches.push_back(LatchBlock);
425
426   // The current on-the-fly SSA update requires blocks to be processed in
427   // reverse postorder so that LastValueMap contains the correct value at each
428   // exit.
429   LoopBlocksDFS DFS(L);
430   DFS.perform(LI);
431
432   // Stash the DFS iterators before adding blocks to the loop.
433   LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
434   LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
435
436   std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
437
438   // Loop Unrolling might create new loops. While we do preserve LoopInfo, we
439   // might break loop-simplified form for these loops (as they, e.g., would
440   // share the same exit blocks). We'll keep track of loops for which we can
441   // break this so that later we can re-simplify them.
442   SmallSetVector<Loop *, 4> LoopsToSimplify;
443   for (Loop *SubLoop : *L)
444     LoopsToSimplify.insert(SubLoop);
445
446   for (unsigned It = 1; It != Count; ++It) {
447     std::vector<BasicBlock*> NewBlocks;
448     SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
449     NewLoops[L] = L;
450
451     for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
452       ValueToValueMapTy VMap;
453       BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
454       Header->getParent()->getBasicBlockList().push_back(New);
455
456       // Tell LI about New.
457       if (*BB == Header) {
458         assert(LI->getLoopFor(*BB) == L && "Header should not be in a sub-loop");
459         L->addBasicBlockToLoop(New, *LI);
460       } else {
461         const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
462         if (OldLoop) {
463           LoopsToSimplify.insert(NewLoops[OldLoop]);
464
465           // Forget the old loop, since its inputs may have changed.
466           if (SE)
467             SE->forgetLoop(OldLoop);
468         }
469       }
470
471       if (*BB == Header)
472         // Loop over all of the PHI nodes in the block, changing them to use
473         // the incoming values from the previous block.
474         for (PHINode *OrigPHI : OrigPHINode) {
475           PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
476           Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
477           if (Instruction *InValI = dyn_cast<Instruction>(InVal))
478             if (It > 1 && L->contains(InValI))
479               InVal = LastValueMap[InValI];
480           VMap[OrigPHI] = InVal;
481           New->getInstList().erase(NewPHI);
482         }
483
484       // Update our running map of newest clones
485       LastValueMap[*BB] = New;
486       for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
487            VI != VE; ++VI)
488         LastValueMap[VI->first] = VI->second;
489
490       // Add phi entries for newly created values to all exit blocks.
491       for (BasicBlock *Succ : successors(*BB)) {
492         if (L->contains(Succ))
493           continue;
494         for (BasicBlock::iterator BBI = Succ->begin();
495              PHINode *phi = dyn_cast<PHINode>(BBI); ++BBI) {
496           Value *Incoming = phi->getIncomingValueForBlock(*BB);
497           ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
498           if (It != LastValueMap.end())
499             Incoming = It->second;
500           phi->addIncoming(Incoming, New);
501         }
502       }
503       // Keep track of new headers and latches as we create them, so that
504       // we can insert the proper branches later.
505       if (*BB == Header)
506         Headers.push_back(New);
507       if (*BB == LatchBlock)
508         Latches.push_back(New);
509
510       NewBlocks.push_back(New);
511       UnrolledLoopBlocks.push_back(New);
512
513       // Update DomTree: since we just copy the loop body, and each copy has a
514       // dedicated entry block (copy of the header block), this header's copy
515       // dominates all copied blocks. That means, dominance relations in the
516       // copied body are the same as in the original body.
517       if (DT) {
518         if (*BB == Header)
519           DT->addNewBlock(New, Latches[It - 1]);
520         else {
521           auto BBDomNode = DT->getNode(*BB);
522           auto BBIDom = BBDomNode->getIDom();
523           BasicBlock *OriginalBBIDom = BBIDom->getBlock();
524           DT->addNewBlock(
525               New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
526         }
527       }
528     }
529
530     // Remap all instructions in the most recent iteration
531     for (BasicBlock *NewBlock : NewBlocks) {
532       for (Instruction &I : *NewBlock) {
533         ::remapInstruction(&I, LastValueMap);
534         if (auto *II = dyn_cast<IntrinsicInst>(&I))
535           if (II->getIntrinsicID() == Intrinsic::assume)
536             AC->registerAssumption(II);
537       }
538     }
539   }
540
541   // Loop over the PHI nodes in the original block, setting incoming values.
542   for (PHINode *PN : OrigPHINode) {
543     if (CompletelyUnroll) {
544       PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
545       Header->getInstList().erase(PN);
546     }
547     else if (Count > 1) {
548       Value *InVal = PN->removeIncomingValue(LatchBlock, false);
549       // If this value was defined in the loop, take the value defined by the
550       // last iteration of the loop.
551       if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
552         if (L->contains(InValI))
553           InVal = LastValueMap[InVal];
554       }
555       assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
556       PN->addIncoming(InVal, Latches.back());
557     }
558   }
559
560   // Now that all the basic blocks for the unrolled iterations are in place,
561   // set up the branches to connect them.
562   for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
563     // The original branch was replicated in each unrolled iteration.
564     BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
565
566     // The branch destination.
567     unsigned j = (i + 1) % e;
568     BasicBlock *Dest = Headers[j];
569     bool NeedConditional = true;
570
571     if (RuntimeTripCount && j != 0) {
572       NeedConditional = false;
573     }
574
575     // For a complete unroll, make the last iteration end with a branch
576     // to the exit block.
577     if (CompletelyUnroll) {
578       if (j == 0)
579         Dest = LoopExit;
580       // If using trip count upper bound to completely unroll, we need to keep
581       // the conditional branch except the last one because the loop may exit
582       // after any iteration.
583       assert(NeedConditional &&
584              "NeedCondition cannot be modified by both complete "
585              "unrolling and runtime unrolling");
586       NeedConditional = (PreserveCondBr && j && !(PreserveOnlyFirst && i != 0));
587     } else if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
588       // If we know the trip count or a multiple of it, we can safely use an
589       // unconditional branch for some iterations.
590       NeedConditional = false;
591     }
592
593     if (NeedConditional) {
594       // Update the conditional branch's successor for the following
595       // iteration.
596       Term->setSuccessor(!ContinueOnTrue, Dest);
597     } else {
598       // Remove phi operands at this loop exit
599       if (Dest != LoopExit) {
600         BasicBlock *BB = Latches[i];
601         for (BasicBlock *Succ: successors(BB)) {
602           if (Succ == Headers[i])
603             continue;
604           for (BasicBlock::iterator BBI = Succ->begin();
605                PHINode *Phi = dyn_cast<PHINode>(BBI); ++BBI) {
606             Phi->removeIncomingValue(BB, false);
607           }
608         }
609       }
610       // Replace the conditional branch with an unconditional one.
611       BranchInst::Create(Dest, Term);
612       Term->eraseFromParent();
613     }
614   }
615   // Update dominators of blocks we might reach through exits.
616   // Immediate dominator of such block might change, because we add more
617   // routes which can lead to the exit: we can now reach it from the copied
618   // iterations too. Thus, the new idom of the block will be the nearest
619   // common dominator of the previous idom and common dominator of all copies of
620   // the previous idom. This is equivalent to the nearest common dominator of
621   // the previous idom and the first latch, which dominates all copies of the
622   // previous idom.
623   if (DT && Count > 1) {
624     for (auto *BB : OriginalLoopBlocks) {
625       auto *BBDomNode = DT->getNode(BB);
626       SmallVector<BasicBlock *, 16> ChildrenToUpdate;
627       for (auto *ChildDomNode : BBDomNode->getChildren()) {
628         auto *ChildBB = ChildDomNode->getBlock();
629         if (!L->contains(ChildBB))
630           ChildrenToUpdate.push_back(ChildBB);
631       }
632       BasicBlock *NewIDom = DT->findNearestCommonDominator(BB, Latches[0]);
633       for (auto *ChildBB : ChildrenToUpdate)
634         DT->changeImmediateDominator(ChildBB, NewIDom);
635     }
636   }
637
638   // Merge adjacent basic blocks, if possible.
639   SmallPtrSet<Loop *, 4> ForgottenLoops;
640   for (BasicBlock *Latch : Latches) {
641     BranchInst *Term = cast<BranchInst>(Latch->getTerminator());
642     if (Term->isUnconditional()) {
643       BasicBlock *Dest = Term->getSuccessor(0);
644       if (BasicBlock *Fold =
645               foldBlockIntoPredecessor(Dest, LI, SE, ForgottenLoops, DT)) {
646         // Dest has been folded into Fold. Update our worklists accordingly.
647         std::replace(Latches.begin(), Latches.end(), Dest, Fold);
648         UnrolledLoopBlocks.erase(std::remove(UnrolledLoopBlocks.begin(),
649                                              UnrolledLoopBlocks.end(), Dest),
650                                  UnrolledLoopBlocks.end());
651       }
652     }
653   }
654
655   // FIXME: We only preserve DT info for complete unrolling now. Incrementally
656   // updating domtree after partial loop unrolling should also be easy.
657   if (DT && !CompletelyUnroll)
658     DT->recalculate(*L->getHeader()->getParent());
659   else if (DT)
660     DEBUG(DT->verifyDomTree());
661
662   // Simplify any new induction variables in the partially unrolled loop.
663   if (SE && !CompletelyUnroll && Count > 1) {
664     SmallVector<WeakVH, 16> DeadInsts;
665     simplifyLoopIVs(L, SE, DT, LI, DeadInsts);
666
667     // Aggressively clean up dead instructions that simplifyLoopIVs already
668     // identified. Any remaining should be cleaned up below.
669     while (!DeadInsts.empty())
670       if (Instruction *Inst =
671               dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
672         RecursivelyDeleteTriviallyDeadInstructions(Inst);
673   }
674
675   // At this point, the code is well formed.  We now do a quick sweep over the
676   // inserted code, doing constant propagation and dead code elimination as we
677   // go.
678   const DataLayout &DL = Header->getModule()->getDataLayout();
679   const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
680   for (BasicBlock *BB : NewLoopBlocks) {
681     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
682       Instruction *Inst = &*I++;
683
684       if (Value *V = SimplifyInstruction(Inst, DL))
685         if (LI->replacementPreservesLCSSAForm(Inst, V))
686           Inst->replaceAllUsesWith(V);
687       if (isInstructionTriviallyDead(Inst))
688         BB->getInstList().erase(Inst);
689     }
690   }
691
692   // TODO: after peeling or unrolling, previously loop variant conditions are
693   // likely to fold to constants, eagerly propagating those here will require
694   // fewer cleanup passes to be run.  Alternatively, a LoopEarlyCSE might be
695   // appropriate.
696
697   NumCompletelyUnrolled += CompletelyUnroll;
698   ++NumUnrolled;
699
700   Loop *OuterL = L->getParentLoop();
701   // Update LoopInfo if the loop is completely removed.
702   if (CompletelyUnroll)
703     LI->markAsRemoved(L);
704
705   // After complete unrolling most of the blocks should be contained in OuterL.
706   // However, some of them might happen to be out of OuterL (e.g. if they
707   // precede a loop exit). In this case we might need to insert PHI nodes in
708   // order to preserve LCSSA form.
709   // We don't need to check this if we already know that we need to fix LCSSA
710   // form.
711   // TODO: For now we just recompute LCSSA for the outer loop in this case, but
712   // it should be possible to fix it in-place.
713   if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
714     NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
715
716   // If we have a pass and a DominatorTree we should re-simplify impacted loops
717   // to ensure subsequent analyses can rely on this form. We want to simplify
718   // at least one layer outside of the loop that was unrolled so that any
719   // changes to the parent loop exposed by the unrolling are considered.
720   if (DT) {
721     if (!OuterL && !CompletelyUnroll)
722       OuterL = L;
723     if (OuterL) {
724       // OuterL includes all loops for which we can break loop-simplify, so
725       // it's sufficient to simplify only it (it'll recursively simplify inner
726       // loops too).
727       // TODO: That potentially might be compile-time expensive. We should try
728       // to fix the loop-simplified form incrementally.
729       simplifyLoop(OuterL, DT, LI, SE, AC, PreserveLCSSA);
730
731       // LCSSA must be performed on the outermost affected loop. The unrolled
732       // loop's last loop latch is guaranteed to be in the outermost loop after
733       // LoopInfo's been updated by markAsRemoved.
734       Loop *LatchLoop = LI->getLoopFor(Latches.back());
735       if (!OuterL->contains(LatchLoop))
736         while (OuterL->getParentLoop() != LatchLoop)
737           OuterL = OuterL->getParentLoop();
738
739       if (NeedToFixLCSSA)
740         formLCSSARecursively(*OuterL, *DT, LI, SE);
741       else
742         assert(OuterL->isLCSSAForm(*DT) &&
743                "Loops should be in LCSSA form after loop-unroll.");
744     } else {
745       // Simplify loops for which we might've broken loop-simplify form.
746       for (Loop *SubLoop : LoopsToSimplify)
747         simplifyLoop(SubLoop, DT, LI, SE, AC, PreserveLCSSA);
748     }
749   }
750
751   return true;
752 }
753
754 /// Given an llvm.loop loop id metadata node, returns the loop hint metadata
755 /// node with the given name (for example, "llvm.loop.unroll.count"). If no
756 /// such metadata node exists, then nullptr is returned.
757 MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
758   // First operand should refer to the loop id itself.
759   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
760   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
761
762   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
763     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
764     if (!MD)
765       continue;
766
767     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
768     if (!S)
769       continue;
770
771     if (Name.equals(S->getString()))
772       return MD;
773   }
774   return nullptr;
775 }