Home | History | Annotate | Download | only in Utils
      1 //===-- UnrollLoopRuntime.cpp - Runtime 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 for loops with run-time
     11 // trip counts.  See LoopUnroll.cpp for unrolling loops with compile-time
     12 // trip counts.
     13 //
     14 // The functions in this file are used to generate extra code when the
     15 // run-time trip count modulo the unroll factor is not 0.  When this is the
     16 // case, we need to generate code to execute these 'left over' iterations.
     17 //
     18 // The current strategy generates an if-then-else sequence prior to the
     19 // unrolled loop to execute the 'left over' iterations before or after the
     20 // unrolled loop.
     21 //
     22 //===----------------------------------------------------------------------===//
     23 
     24 #include "llvm/Transforms/Utils/UnrollLoop.h"
     25 #include "llvm/ADT/Statistic.h"
     26 #include "llvm/Analysis/AliasAnalysis.h"
     27 #include "llvm/Analysis/LoopIterator.h"
     28 #include "llvm/Analysis/LoopPass.h"
     29 #include "llvm/Analysis/ScalarEvolution.h"
     30 #include "llvm/Analysis/ScalarEvolutionExpander.h"
     31 #include "llvm/IR/BasicBlock.h"
     32 #include "llvm/IR/Dominators.h"
     33 #include "llvm/IR/Metadata.h"
     34 #include "llvm/IR/Module.h"
     35 #include "llvm/Support/Debug.h"
     36 #include "llvm/Support/raw_ostream.h"
     37 #include "llvm/Transforms/Scalar.h"
     38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
     39 #include "llvm/Transforms/Utils/Cloning.h"
     40 #include <algorithm>
     41 
     42 using namespace llvm;
     43 
     44 #define DEBUG_TYPE "loop-unroll"
     45 
     46 STATISTIC(NumRuntimeUnrolled,
     47           "Number of loops unrolled with run-time trip counts");
     48 
     49 /// Connect the unrolling prolog code to the original loop.
     50 /// The unrolling prolog code contains code to execute the
     51 /// 'extra' iterations if the run-time trip count modulo the
     52 /// unroll count is non-zero.
     53 ///
     54 /// This function performs the following:
     55 /// - Create PHI nodes at prolog end block to combine values
     56 ///   that exit the prolog code and jump around the prolog.
     57 /// - Add a PHI operand to a PHI node at the loop exit block
     58 ///   for values that exit the prolog and go around the loop.
     59 /// - Branch around the original loop if the trip count is less
     60 ///   than the unroll factor.
     61 ///
     62 static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
     63                           BasicBlock *PrologExit, BasicBlock *PreHeader,
     64                           BasicBlock *NewPreHeader, ValueToValueMapTy &VMap,
     65                           DominatorTree *DT, LoopInfo *LI, bool PreserveLCSSA) {
     66   BasicBlock *Latch = L->getLoopLatch();
     67   assert(Latch && "Loop must have a latch");
     68   BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]);
     69 
     70   // Create a PHI node for each outgoing value from the original loop
     71   // (which means it is an outgoing value from the prolog code too).
     72   // The new PHI node is inserted in the prolog end basic block.
     73   // The new PHI node value is added as an operand of a PHI node in either
     74   // the loop header or the loop exit block.
     75   for (BasicBlock *Succ : successors(Latch)) {
     76     for (Instruction &BBI : *Succ) {
     77       PHINode *PN = dyn_cast<PHINode>(&BBI);
     78       // Exit when we passed all PHI nodes.
     79       if (!PN)
     80         break;
     81       // Add a new PHI node to the prolog end block and add the
     82       // appropriate incoming values.
     83       PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName() + ".unr",
     84                                        PrologExit->getFirstNonPHI());
     85       // Adding a value to the new PHI node from the original loop preheader.
     86       // This is the value that skips all the prolog code.
     87       if (L->contains(PN)) {
     88         NewPN->addIncoming(PN->getIncomingValueForBlock(NewPreHeader),
     89                            PreHeader);
     90       } else {
     91         NewPN->addIncoming(UndefValue::get(PN->getType()), PreHeader);
     92       }
     93 
     94       Value *V = PN->getIncomingValueForBlock(Latch);
     95       if (Instruction *I = dyn_cast<Instruction>(V)) {
     96         if (L->contains(I)) {
     97           V = VMap.lookup(I);
     98         }
     99       }
    100       // Adding a value to the new PHI node from the last prolog block
    101       // that was created.
    102       NewPN->addIncoming(V, PrologLatch);
    103 
    104       // Update the existing PHI node operand with the value from the
    105       // new PHI node.  How this is done depends on if the existing
    106       // PHI node is in the original loop block, or the exit block.
    107       if (L->contains(PN)) {
    108         PN->setIncomingValue(PN->getBasicBlockIndex(NewPreHeader), NewPN);
    109       } else {
    110         PN->addIncoming(NewPN, PrologExit);
    111       }
    112     }
    113   }
    114 
    115   // Create a branch around the original loop, which is taken if there are no
    116   // iterations remaining to be executed after running the prologue.
    117   Instruction *InsertPt = PrologExit->getTerminator();
    118   IRBuilder<> B(InsertPt);
    119 
    120   assert(Count != 0 && "nonsensical Count!");
    121 
    122   // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1)
    123   // This means %xtraiter is (BECount + 1) and all of the iterations of this
    124   // loop were executed by the prologue.  Note that if BECount <u (Count - 1)
    125   // then (BECount + 1) cannot unsigned-overflow.
    126   Value *BrLoopExit =
    127       B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1));
    128   BasicBlock *Exit = L->getUniqueExitBlock();
    129   assert(Exit && "Loop must have a single exit block only");
    130   // Split the exit to maintain loop canonicalization guarantees
    131   SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
    132   SplitBlockPredecessors(Exit, Preds, ".unr-lcssa", DT, LI,
    133                          PreserveLCSSA);
    134   // Add the branch to the exit block (around the unrolled loop)
    135   B.CreateCondBr(BrLoopExit, Exit, NewPreHeader);
    136   InsertPt->eraseFromParent();
    137 }
    138 
    139 /// Connect the unrolling epilog code to the original loop.
    140 /// The unrolling epilog code contains code to execute the
    141 /// 'extra' iterations if the run-time trip count modulo the
    142 /// unroll count is non-zero.
    143 ///
    144 /// This function performs the following:
    145 /// - Update PHI nodes at the unrolling loop exit and epilog loop exit
    146 /// - Create PHI nodes at the unrolling loop exit to combine
    147 ///   values that exit the unrolling loop code and jump around it.
    148 /// - Update PHI operands in the epilog loop by the new PHI nodes
    149 /// - Branch around the epilog loop if extra iters (ModVal) is zero.
    150 ///
    151 static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit,
    152                           BasicBlock *Exit, BasicBlock *PreHeader,
    153                           BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader,
    154                           ValueToValueMapTy &VMap, DominatorTree *DT,
    155                           LoopInfo *LI, bool PreserveLCSSA)  {
    156   BasicBlock *Latch = L->getLoopLatch();
    157   assert(Latch && "Loop must have a latch");
    158   BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]);
    159 
    160   // Loop structure should be the following:
    161   //
    162   // PreHeader
    163   // NewPreHeader
    164   //   Header
    165   //   ...
    166   //   Latch
    167   // NewExit (PN)
    168   // EpilogPreHeader
    169   //   EpilogHeader
    170   //   ...
    171   //   EpilogLatch
    172   // Exit (EpilogPN)
    173 
    174   // Update PHI nodes at NewExit and Exit.
    175   for (Instruction &BBI : *NewExit) {
    176     PHINode *PN = dyn_cast<PHINode>(&BBI);
    177     // Exit when we passed all PHI nodes.
    178     if (!PN)
    179       break;
    180     // PN should be used in another PHI located in Exit block as
    181     // Exit was split by SplitBlockPredecessors into Exit and NewExit
    182     // Basicaly it should look like:
    183     // NewExit:
    184     //   PN = PHI [I, Latch]
    185     // ...
    186     // Exit:
    187     //   EpilogPN = PHI [PN, EpilogPreHeader]
    188     //
    189     // There is EpilogPreHeader incoming block instead of NewExit as
    190     // NewExit was spilt 1 more time to get EpilogPreHeader.
    191     assert(PN->hasOneUse() && "The phi should have 1 use");
    192     PHINode *EpilogPN = cast<PHINode> (PN->use_begin()->getUser());
    193     assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block");
    194 
    195     // Add incoming PreHeader from branch around the Loop
    196     PN->addIncoming(UndefValue::get(PN->getType()), PreHeader);
    197 
    198     Value *V = PN->getIncomingValueForBlock(Latch);
    199     Instruction *I = dyn_cast<Instruction>(V);
    200     if (I && L->contains(I))
    201       // If value comes from an instruction in the loop add VMap value.
    202       V = VMap.lookup(I);
    203     // For the instruction out of the loop, constant or undefined value
    204     // insert value itself.
    205     EpilogPN->addIncoming(V, EpilogLatch);
    206 
    207     assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 &&
    208           "EpilogPN should have EpilogPreHeader incoming block");
    209     // Change EpilogPreHeader incoming block to NewExit.
    210     EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader),
    211                                NewExit);
    212     // Now PHIs should look like:
    213     // NewExit:
    214     //   PN = PHI [I, Latch], [undef, PreHeader]
    215     // ...
    216     // Exit:
    217     //   EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch]
    218   }
    219 
    220   // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader).
    221   // Update corresponding PHI nodes in epilog loop.
    222   for (BasicBlock *Succ : successors(Latch)) {
    223     // Skip this as we already updated phis in exit blocks.
    224     if (!L->contains(Succ))
    225       continue;
    226     for (Instruction &BBI : *Succ) {
    227       PHINode *PN = dyn_cast<PHINode>(&BBI);
    228       // Exit when we passed all PHI nodes.
    229       if (!PN)
    230         break;
    231       // Add new PHI nodes to the loop exit block and update epilog
    232       // PHIs with the new PHI values.
    233       PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName() + ".unr",
    234                                        NewExit->getFirstNonPHI());
    235       // Adding a value to the new PHI node from the unrolling loop preheader.
    236       NewPN->addIncoming(PN->getIncomingValueForBlock(NewPreHeader), PreHeader);
    237       // Adding a value to the new PHI node from the unrolling loop latch.
    238       NewPN->addIncoming(PN->getIncomingValueForBlock(Latch), Latch);
    239 
    240       // Update the existing PHI node operand with the value from the new PHI
    241       // node.  Corresponding instruction in epilog loop should be PHI.
    242       PHINode *VPN = cast<PHINode>(VMap[&BBI]);
    243       VPN->setIncomingValue(VPN->getBasicBlockIndex(EpilogPreHeader), NewPN);
    244     }
    245   }
    246 
    247   Instruction *InsertPt = NewExit->getTerminator();
    248   IRBuilder<> B(InsertPt);
    249   Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod");
    250   assert(Exit && "Loop must have a single exit block only");
    251   // Split the exit to maintain loop canonicalization guarantees
    252   SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
    253   SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI,
    254                          PreserveLCSSA);
    255   // Add the branch to the exit block (around the unrolling loop)
    256   B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit);
    257   InsertPt->eraseFromParent();
    258 }
    259 
    260 /// Create a clone of the blocks in a loop and connect them together.
    261 /// If CreateRemainderLoop is false, loop structure will not be cloned,
    262 /// otherwise a new loop will be created including all cloned blocks, and the
    263 /// iterator of it switches to count NewIter down to 0.
    264 /// The cloned blocks should be inserted between InsertTop and InsertBot.
    265 /// If loop structure is cloned InsertTop should be new preheader, InsertBot
    266 /// new loop exit.
    267 ///
    268 static void CloneLoopBlocks(Loop *L, Value *NewIter,
    269                             const bool CreateRemainderLoop,
    270                             const bool UseEpilogRemainder,
    271                             BasicBlock *InsertTop, BasicBlock *InsertBot,
    272                             BasicBlock *Preheader,
    273                             std::vector<BasicBlock *> &NewBlocks,
    274                             LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap,
    275                             LoopInfo *LI) {
    276   StringRef suffix = UseEpilogRemainder ? "epil" : "prol";
    277   BasicBlock *Header = L->getHeader();
    278   BasicBlock *Latch = L->getLoopLatch();
    279   Function *F = Header->getParent();
    280   LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
    281   LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
    282   Loop *NewLoop = nullptr;
    283   Loop *ParentLoop = L->getParentLoop();
    284   if (CreateRemainderLoop) {
    285     NewLoop = new Loop();
    286     if (ParentLoop)
    287       ParentLoop->addChildLoop(NewLoop);
    288     else
    289       LI->addTopLevelLoop(NewLoop);
    290   }
    291 
    292   // For each block in the original loop, create a new copy,
    293   // and update the value map with the newly created values.
    294   for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
    295     BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F);
    296     NewBlocks.push_back(NewBB);
    297 
    298     if (NewLoop)
    299       NewLoop->addBasicBlockToLoop(NewBB, *LI);
    300     else if (ParentLoop)
    301       ParentLoop->addBasicBlockToLoop(NewBB, *LI);
    302 
    303     VMap[*BB] = NewBB;
    304     if (Header == *BB) {
    305       // For the first block, add a CFG connection to this newly
    306       // created block.
    307       InsertTop->getTerminator()->setSuccessor(0, NewBB);
    308     }
    309 
    310     if (Latch == *BB) {
    311       // For the last block, if CreateRemainderLoop is false, create a direct
    312       // jump to InsertBot. If not, create a loop back to cloned head.
    313       VMap.erase((*BB)->getTerminator());
    314       BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
    315       BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
    316       IRBuilder<> Builder(LatchBR);
    317       if (!CreateRemainderLoop) {
    318         Builder.CreateBr(InsertBot);
    319       } else {
    320         PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2,
    321                                           suffix + ".iter",
    322                                           FirstLoopBB->getFirstNonPHI());
    323         Value *IdxSub =
    324             Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
    325                               NewIdx->getName() + ".sub");
    326         Value *IdxCmp =
    327             Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
    328         Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot);
    329         NewIdx->addIncoming(NewIter, InsertTop);
    330         NewIdx->addIncoming(IdxSub, NewBB);
    331       }
    332       LatchBR->eraseFromParent();
    333     }
    334   }
    335 
    336   // Change the incoming values to the ones defined in the preheader or
    337   // cloned loop.
    338   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
    339     PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
    340     if (!CreateRemainderLoop) {
    341       if (UseEpilogRemainder) {
    342         unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
    343         NewPHI->setIncomingBlock(idx, InsertTop);
    344         NewPHI->removeIncomingValue(Latch, false);
    345       } else {
    346         VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader);
    347         cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
    348       }
    349     } else {
    350       unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
    351       NewPHI->setIncomingBlock(idx, InsertTop);
    352       BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
    353       idx = NewPHI->getBasicBlockIndex(Latch);
    354       Value *InVal = NewPHI->getIncomingValue(idx);
    355       NewPHI->setIncomingBlock(idx, NewLatch);
    356       if (Value *V = VMap.lookup(InVal))
    357         NewPHI->setIncomingValue(idx, V);
    358     }
    359   }
    360   if (NewLoop) {
    361     // Add unroll disable metadata to disable future unrolling for this loop.
    362     SmallVector<Metadata *, 4> MDs;
    363     // Reserve first location for self reference to the LoopID metadata node.
    364     MDs.push_back(nullptr);
    365     MDNode *LoopID = NewLoop->getLoopID();
    366     if (LoopID) {
    367       // First remove any existing loop unrolling metadata.
    368       for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
    369         bool IsUnrollMetadata = false;
    370         MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
    371         if (MD) {
    372           const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
    373           IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
    374         }
    375         if (!IsUnrollMetadata)
    376           MDs.push_back(LoopID->getOperand(i));
    377       }
    378     }
    379 
    380     LLVMContext &Context = NewLoop->getHeader()->getContext();
    381     SmallVector<Metadata *, 1> DisableOperands;
    382     DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
    383     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
    384     MDs.push_back(DisableNode);
    385 
    386     MDNode *NewLoopID = MDNode::get(Context, MDs);
    387     // Set operand 0 to refer to the loop id itself.
    388     NewLoopID->replaceOperandWith(0, NewLoopID);
    389     NewLoop->setLoopID(NewLoopID);
    390   }
    391 }
    392 
    393 /// Insert code in the prolog/epilog code when unrolling a loop with a
    394 /// run-time trip-count.
    395 ///
    396 /// This method assumes that the loop unroll factor is total number
    397 /// of loop bodies in the loop after unrolling. (Some folks refer
    398 /// to the unroll factor as the number of *extra* copies added).
    399 /// We assume also that the loop unroll factor is a power-of-two. So, after
    400 /// unrolling the loop, the number of loop bodies executed is 2,
    401 /// 4, 8, etc.  Note - LLVM converts the if-then-sequence to a switch
    402 /// instruction in SimplifyCFG.cpp.  Then, the backend decides how code for
    403 /// the switch instruction is generated.
    404 ///
    405 /// ***Prolog case***
    406 ///        extraiters = tripcount % loopfactor
    407 ///        if (extraiters == 0) jump Loop:
    408 ///        else jump Prol:
    409 /// Prol:  LoopBody;
    410 ///        extraiters -= 1                 // Omitted if unroll factor is 2.
    411 ///        if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
    412 ///        if (tripcount < loopfactor) jump End:
    413 /// Loop:
    414 /// ...
    415 /// End:
    416 ///
    417 /// ***Epilog case***
    418 ///        extraiters = tripcount % loopfactor
    419 ///        if (tripcount < loopfactor) jump LoopExit:
    420 ///        unroll_iters = tripcount - extraiters
    421 /// Loop:  LoopBody; (executes unroll_iter times);
    422 ///        unroll_iter -= 1
    423 ///        if (unroll_iter != 0) jump Loop:
    424 /// LoopExit:
    425 ///        if (extraiters == 0) jump EpilExit:
    426 /// Epil:  LoopBody; (executes extraiters times)
    427 ///        extraiters -= 1                 // Omitted if unroll factor is 2.
    428 ///        if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
    429 /// EpilExit:
    430 
    431 bool llvm::UnrollRuntimeLoopRemainder(Loop *L, unsigned Count,
    432                                       bool AllowExpensiveTripCount,
    433                                       bool UseEpilogRemainder,
    434                                       LoopInfo *LI, ScalarEvolution *SE,
    435                                       DominatorTree *DT, bool PreserveLCSSA) {
    436   // for now, only unroll loops that contain a single exit
    437   if (!L->getExitingBlock())
    438     return false;
    439 
    440   // Make sure the loop is in canonical form, and there is a single
    441   // exit block only.
    442   if (!L->isLoopSimplifyForm())
    443     return false;
    444   BasicBlock *Exit = L->getUniqueExitBlock(); // successor out of loop
    445   if (!Exit)
    446     return false;
    447 
    448   // Use Scalar Evolution to compute the trip count. This allows more loops to
    449   // be unrolled than relying on induction var simplification.
    450   if (!SE)
    451     return false;
    452 
    453   // Only unroll loops with a computable trip count, and the trip count needs
    454   // to be an int value (allowing a pointer type is a TODO item).
    455   const SCEV *BECountSC = SE->getBackedgeTakenCount(L);
    456   if (isa<SCEVCouldNotCompute>(BECountSC) ||
    457       !BECountSC->getType()->isIntegerTy())
    458     return false;
    459 
    460   unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
    461 
    462   // Add 1 since the backedge count doesn't include the first loop iteration.
    463   const SCEV *TripCountSC =
    464       SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
    465   if (isa<SCEVCouldNotCompute>(TripCountSC))
    466     return false;
    467 
    468   BasicBlock *Header = L->getHeader();
    469   BasicBlock *PreHeader = L->getLoopPreheader();
    470   BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
    471   const DataLayout &DL = Header->getModule()->getDataLayout();
    472   SCEVExpander Expander(*SE, DL, "loop-unroll");
    473   if (!AllowExpensiveTripCount &&
    474       Expander.isHighCostExpansion(TripCountSC, L, PreHeaderBR))
    475     return false;
    476 
    477   // This constraint lets us deal with an overflowing trip count easily; see the
    478   // comment on ModVal below.
    479   if (Log2_32(Count) > BEWidth)
    480     return false;
    481 
    482   // If this loop is nested, then the loop unroller changes the code in the
    483   // parent loop, so the Scalar Evolution pass needs to be run again.
    484   if (Loop *ParentLoop = L->getParentLoop())
    485     SE->forgetLoop(ParentLoop);
    486 
    487   BasicBlock *Latch = L->getLoopLatch();
    488 
    489   // Loop structure is the following:
    490   //
    491   // PreHeader
    492   //   Header
    493   //   ...
    494   //   Latch
    495   // Exit
    496 
    497   BasicBlock *NewPreHeader;
    498   BasicBlock *NewExit = nullptr;
    499   BasicBlock *PrologExit = nullptr;
    500   BasicBlock *EpilogPreHeader = nullptr;
    501   BasicBlock *PrologPreHeader = nullptr;
    502 
    503   if (UseEpilogRemainder) {
    504     // If epilog remainder
    505     // Split PreHeader to insert a branch around loop for unrolling.
    506     NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI);
    507     NewPreHeader->setName(PreHeader->getName() + ".new");
    508     // Split Exit to create phi nodes from branch above.
    509     SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
    510     NewExit = SplitBlockPredecessors(Exit, Preds, ".unr-lcssa",
    511                                      DT, LI, PreserveLCSSA);
    512     // Split NewExit to insert epilog remainder loop.
    513     EpilogPreHeader = SplitBlock(NewExit, NewExit->getTerminator(), DT, LI);
    514     EpilogPreHeader->setName(Header->getName() + ".epil.preheader");
    515   } else {
    516     // If prolog remainder
    517     // Split the original preheader twice to insert prolog remainder loop
    518     PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI);
    519     PrologPreHeader->setName(Header->getName() + ".prol.preheader");
    520     PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(),
    521                             DT, LI);
    522     PrologExit->setName(Header->getName() + ".prol.loopexit");
    523     // Split PrologExit to get NewPreHeader.
    524     NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI);
    525     NewPreHeader->setName(PreHeader->getName() + ".new");
    526   }
    527   // Loop structure should be the following:
    528   //  Epilog             Prolog
    529   //
    530   // PreHeader         PreHeader
    531   // *NewPreHeader     *PrologPreHeader
    532   //   Header          *PrologExit
    533   //   ...             *NewPreHeader
    534   //   Latch             Header
    535   // *NewExit            ...
    536   // *EpilogPreHeader    Latch
    537   // Exit              Exit
    538 
    539   // Calculate conditions for branch around loop for unrolling
    540   // in epilog case and around prolog remainder loop in prolog case.
    541   // Compute the number of extra iterations required, which is:
    542   //  extra iterations = run-time trip count % loop unroll factor
    543   PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
    544   Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
    545                                             PreHeaderBR);
    546   Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(),
    547                                           PreHeaderBR);
    548   IRBuilder<> B(PreHeaderBR);
    549   Value *ModVal;
    550   // Calculate ModVal = (BECount + 1) % Count.
    551   // Note that TripCount is BECount + 1.
    552   if (isPowerOf2_32(Count)) {
    553     // When Count is power of 2 we don't BECount for epilog case, however we'll
    554     // need it for a branch around unrolling loop for prolog case.
    555     ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter");
    556     //  1. There are no iterations to be run in the prolog/epilog loop.
    557     // OR
    558     //  2. The addition computing TripCount overflowed.
    559     //
    560     // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
    561     // the number of iterations that remain to be run in the original loop is a
    562     // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we
    563     // explicitly check this above).
    564   } else {
    565     // As (BECount + 1) can potentially unsigned overflow we count
    566     // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
    567     Value *ModValTmp = B.CreateURem(BECount,
    568                                     ConstantInt::get(BECount->getType(),
    569                                                      Count));
    570     Value *ModValAdd = B.CreateAdd(ModValTmp,
    571                                    ConstantInt::get(ModValTmp->getType(), 1));
    572     // At that point (BECount % Count) + 1 could be equal to Count.
    573     // To handle this case we need to take mod by Count one more time.
    574     ModVal = B.CreateURem(ModValAdd,
    575                           ConstantInt::get(BECount->getType(), Count),
    576                           "xtraiter");
    577   }
    578   Value *BranchVal =
    579       UseEpilogRemainder ? B.CreateICmpULT(BECount,
    580                                            ConstantInt::get(BECount->getType(),
    581                                                             Count - 1)) :
    582                            B.CreateIsNotNull(ModVal, "lcmp.mod");
    583   BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader;
    584   BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit;
    585   // Branch to either remainder (extra iterations) loop or unrolling loop.
    586   B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop);
    587   PreHeaderBR->eraseFromParent();
    588   Function *F = Header->getParent();
    589   // Get an ordered list of blocks in the loop to help with the ordering of the
    590   // cloned blocks in the prolog/epilog code
    591   LoopBlocksDFS LoopBlocks(L);
    592   LoopBlocks.perform(LI);
    593 
    594   //
    595   // For each extra loop iteration, create a copy of the loop's basic blocks
    596   // and generate a condition that branches to the copy depending on the
    597   // number of 'left over' iterations.
    598   //
    599   std::vector<BasicBlock *> NewBlocks;
    600   ValueToValueMapTy VMap;
    601 
    602   // For unroll factor 2 remainder loop will have 1 iterations.
    603   // Do not create 1 iteration loop.
    604   bool CreateRemainderLoop = (Count != 2);
    605 
    606   // Clone all the basic blocks in the loop. If Count is 2, we don't clone
    607   // the loop, otherwise we create a cloned loop to execute the extra
    608   // iterations. This function adds the appropriate CFG connections.
    609   BasicBlock *InsertBot = UseEpilogRemainder ? Exit : PrologExit;
    610   BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
    611   CloneLoopBlocks(L, ModVal, CreateRemainderLoop, UseEpilogRemainder, InsertTop,
    612                   InsertBot, NewPreHeader, NewBlocks, LoopBlocks, VMap, LI);
    613 
    614   // Insert the cloned blocks into the function.
    615   F->getBasicBlockList().splice(InsertBot->getIterator(),
    616                                 F->getBasicBlockList(),
    617                                 NewBlocks[0]->getIterator(),
    618                                 F->end());
    619 
    620   // Loop structure should be the following:
    621   //  Epilog             Prolog
    622   //
    623   // PreHeader         PreHeader
    624   // NewPreHeader      PrologPreHeader
    625   //   Header            PrologHeader
    626   //   ...               ...
    627   //   Latch             PrologLatch
    628   // NewExit           PrologExit
    629   // EpilogPreHeader   NewPreHeader
    630   //   EpilogHeader      Header
    631   //   ...               ...
    632   //   EpilogLatch       Latch
    633   // Exit              Exit
    634 
    635   // Rewrite the cloned instruction operands to use the values created when the
    636   // clone is created.
    637   for (BasicBlock *BB : NewBlocks) {
    638     for (Instruction &I : *BB) {
    639       RemapInstruction(&I, VMap,
    640                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
    641     }
    642   }
    643 
    644   if (UseEpilogRemainder) {
    645     // Connect the epilog code to the original loop and update the
    646     // PHI functions.
    647     ConnectEpilog(L, ModVal, NewExit, Exit, PreHeader,
    648                   EpilogPreHeader, NewPreHeader, VMap, DT, LI,
    649                   PreserveLCSSA);
    650 
    651     // Update counter in loop for unrolling.
    652     // I should be multiply of Count.
    653     IRBuilder<> B2(NewPreHeader->getTerminator());
    654     Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter");
    655     BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
    656     B2.SetInsertPoint(LatchBR);
    657     PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter",
    658                                       Header->getFirstNonPHI());
    659     Value *IdxSub =
    660         B2.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
    661                      NewIdx->getName() + ".nsub");
    662     Value *IdxCmp;
    663     if (LatchBR->getSuccessor(0) == Header)
    664       IdxCmp = B2.CreateIsNotNull(IdxSub, NewIdx->getName() + ".ncmp");
    665     else
    666       IdxCmp = B2.CreateIsNull(IdxSub, NewIdx->getName() + ".ncmp");
    667     NewIdx->addIncoming(TestVal, NewPreHeader);
    668     NewIdx->addIncoming(IdxSub, Latch);
    669     LatchBR->setCondition(IdxCmp);
    670   } else {
    671     // Connect the prolog code to the original loop and update the
    672     // PHI functions.
    673     ConnectProlog(L, BECount, Count, PrologExit, PreHeader, NewPreHeader,
    674                   VMap, DT, LI, PreserveLCSSA);
    675   }
    676   NumRuntimeUnrolled++;
    677   return true;
    678 }
    679