LLVM  mainline
LoopUnrollRuntime.cpp
Go to the documentation of this file.
00001 //===-- UnrollLoopRuntime.cpp - Runtime Loop unrolling utilities ----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements some loop unrolling utilities for loops with run-time
00011 // trip counts.  See LoopUnroll.cpp for unrolling loops with compile-time
00012 // trip counts.
00013 //
00014 // The functions in this file are used to generate extra code when the
00015 // run-time trip count modulo the unroll factor is not 0.  When this is the
00016 // case, we need to generate code to execute these 'left over' iterations.
00017 //
00018 // The current strategy generates an if-then-else sequence prior to the
00019 // unrolled loop to execute the 'left over' iterations.  Other strategies
00020 // include generate a loop before or after the unrolled loop.
00021 //
00022 //===----------------------------------------------------------------------===//
00023 
00024 #include "llvm/Transforms/Utils/UnrollLoop.h"
00025 #include "llvm/ADT/Statistic.h"
00026 #include "llvm/Analysis/AliasAnalysis.h"
00027 #include "llvm/Analysis/LoopIterator.h"
00028 #include "llvm/Analysis/LoopPass.h"
00029 #include "llvm/Analysis/ScalarEvolution.h"
00030 #include "llvm/Analysis/ScalarEvolutionExpander.h"
00031 #include "llvm/IR/BasicBlock.h"
00032 #include "llvm/IR/Dominators.h"
00033 #include "llvm/IR/Metadata.h"
00034 #include "llvm/IR/Module.h"
00035 #include "llvm/Support/Debug.h"
00036 #include "llvm/Support/raw_ostream.h"
00037 #include "llvm/Transforms/Scalar.h"
00038 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00039 #include "llvm/Transforms/Utils/Cloning.h"
00040 #include <algorithm>
00041 
00042 using namespace llvm;
00043 
00044 #define DEBUG_TYPE "loop-unroll"
00045 
00046 STATISTIC(NumRuntimeUnrolled,
00047           "Number of loops unrolled with run-time trip counts");
00048 
00049 /// Connect the unrolling prolog code to the original loop.
00050 /// The unrolling prolog code contains code to execute the
00051 /// 'extra' iterations if the run-time trip count modulo the
00052 /// unroll count is non-zero.
00053 ///
00054 /// This function performs the following:
00055 /// - Create PHI nodes at prolog end block to combine values
00056 ///   that exit the prolog code and jump around the prolog.
00057 /// - Add a PHI operand to a PHI node at the loop exit block
00058 ///   for values that exit the prolog and go around the loop.
00059 /// - Branch around the original loop if the trip count is less
00060 ///   than the unroll factor.
00061 ///
00062 static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
00063                           BasicBlock *LastPrologBB, BasicBlock *PrologEnd,
00064                           BasicBlock *OrigPH, BasicBlock *NewPH,
00065                           ValueToValueMapTy &VMap, AliasAnalysis *AA,
00066                           DominatorTree *DT, LoopInfo *LI, Pass *P) {
00067   BasicBlock *Latch = L->getLoopLatch();
00068   assert(Latch && "Loop must have a latch");
00069 
00070   // Create a PHI node for each outgoing value from the original loop
00071   // (which means it is an outgoing value from the prolog code too).
00072   // The new PHI node is inserted in the prolog end basic block.
00073   // The new PHI name is added as an operand of a PHI node in either
00074   // the loop header or the loop exit block.
00075   for (succ_iterator SBI = succ_begin(Latch), SBE = succ_end(Latch);
00076        SBI != SBE; ++SBI) {
00077     for (BasicBlock::iterator BBI = (*SBI)->begin();
00078          PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) {
00079 
00080       // Add a new PHI node to the prolog end block and add the
00081       // appropriate incoming values.
00082       PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName()+".unr",
00083                                        PrologEnd->getTerminator());
00084       // Adding a value to the new PHI node from the original loop preheader.
00085       // This is the value that skips all the prolog code.
00086       if (L->contains(PN)) {
00087         NewPN->addIncoming(PN->getIncomingValueForBlock(NewPH), OrigPH);
00088       } else {
00089         NewPN->addIncoming(Constant::getNullValue(PN->getType()), OrigPH);
00090       }
00091 
00092       Value *V = PN->getIncomingValueForBlock(Latch);
00093       if (Instruction *I = dyn_cast<Instruction>(V)) {
00094         if (L->contains(I)) {
00095           V = VMap[I];
00096         }
00097       }
00098       // Adding a value to the new PHI node from the last prolog block
00099       // that was created.
00100       NewPN->addIncoming(V, LastPrologBB);
00101 
00102       // Update the existing PHI node operand with the value from the
00103       // new PHI node.  How this is done depends on if the existing
00104       // PHI node is in the original loop block, or the exit block.
00105       if (L->contains(PN)) {
00106         PN->setIncomingValue(PN->getBasicBlockIndex(NewPH), NewPN);
00107       } else {
00108         PN->addIncoming(NewPN, PrologEnd);
00109       }
00110     }
00111   }
00112 
00113   // Create a branch around the orignal loop, which is taken if there are no
00114   // iterations remaining to be executed after running the prologue.
00115   Instruction *InsertPt = PrologEnd->getTerminator();
00116   IRBuilder<> B(InsertPt);
00117 
00118   assert(Count != 0 && "nonsensical Count!");
00119 
00120   // If BECount <u (Count - 1) then (BECount + 1) & (Count - 1) == (BECount + 1)
00121   // (since Count is a power of 2).  This means %xtraiter is (BECount + 1) and
00122   // and all of the iterations of this loop were executed by the prologue.  Note
00123   // that if BECount <u (Count - 1) then (BECount + 1) cannot unsigned-overflow.
00124   Value *BrLoopExit =
00125       B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1));
00126   BasicBlock *Exit = L->getUniqueExitBlock();
00127   assert(Exit && "Loop must have a single exit block only");
00128   // Split the exit to maintain loop canonicalization guarantees
00129   SmallVector<BasicBlock*, 4> Preds(pred_begin(Exit), pred_end(Exit));
00130   SplitBlockPredecessors(Exit, Preds, ".unr-lcssa", AA, DT, LI,
00131                          P->mustPreserveAnalysisID(LCSSAID));
00132   // Add the branch to the exit block (around the unrolled loop)
00133   B.CreateCondBr(BrLoopExit, Exit, NewPH);
00134   InsertPt->eraseFromParent();
00135 }
00136 
00137 /// Create a clone of the blocks in a loop and connect them together.
00138 /// If UnrollProlog is true, loop structure will not be cloned, otherwise a new
00139 /// loop will be created including all cloned blocks, and the iterator of it
00140 /// switches to count NewIter down to 0.
00141 ///
00142 static void CloneLoopBlocks(Loop *L, Value *NewIter, const bool UnrollProlog,
00143                             BasicBlock *InsertTop, BasicBlock *InsertBot,
00144                             std::vector<BasicBlock *> &NewBlocks,
00145                             LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap,
00146                             LoopInfo *LI) {
00147   BasicBlock *Preheader = L->getLoopPreheader();
00148   BasicBlock *Header = L->getHeader();
00149   BasicBlock *Latch = L->getLoopLatch();
00150   Function *F = Header->getParent();
00151   LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
00152   LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
00153   Loop *NewLoop = 0;
00154   Loop *ParentLoop = L->getParentLoop();
00155   if (!UnrollProlog) {
00156     NewLoop = new Loop();
00157     if (ParentLoop)
00158       ParentLoop->addChildLoop(NewLoop);
00159     else
00160       LI->addTopLevelLoop(NewLoop);
00161   }
00162 
00163   // For each block in the original loop, create a new copy,
00164   // and update the value map with the newly created values.
00165   for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
00166     BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".prol", F);
00167     NewBlocks.push_back(NewBB);
00168 
00169     if (NewLoop)
00170       NewLoop->addBasicBlockToLoop(NewBB, *LI);
00171     else if (ParentLoop)
00172       ParentLoop->addBasicBlockToLoop(NewBB, *LI);
00173 
00174     VMap[*BB] = NewBB;
00175     if (Header == *BB) {
00176       // For the first block, add a CFG connection to this newly
00177       // created block.
00178       InsertTop->getTerminator()->setSuccessor(0, NewBB);
00179 
00180     }
00181     if (Latch == *BB) {
00182       // For the last block, if UnrollProlog is true, create a direct jump to
00183       // InsertBot. If not, create a loop back to cloned head.
00184       VMap.erase((*BB)->getTerminator());
00185       BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
00186       BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
00187       IRBuilder<> Builder(LatchBR);
00188       if (UnrollProlog) {
00189         Builder.CreateBr(InsertBot);
00190       } else {
00191         PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2, "prol.iter",
00192                                           FirstLoopBB->getFirstNonPHI());
00193         Value *IdxSub =
00194             Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
00195                               NewIdx->getName() + ".sub");
00196         Value *IdxCmp =
00197             Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
00198         Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot);
00199         NewIdx->addIncoming(NewIter, InsertTop);
00200         NewIdx->addIncoming(IdxSub, NewBB);
00201       }
00202       LatchBR->eraseFromParent();
00203     }
00204   }
00205 
00206   // Change the incoming values to the ones defined in the preheader or
00207   // cloned loop.
00208   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
00209     PHINode *NewPHI = cast<PHINode>(VMap[I]);
00210     if (UnrollProlog) {
00211       VMap[I] = NewPHI->getIncomingValueForBlock(Preheader);
00212       cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
00213     } else {
00214       unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
00215       NewPHI->setIncomingBlock(idx, InsertTop);
00216       BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
00217       idx = NewPHI->getBasicBlockIndex(Latch);
00218       Value *InVal = NewPHI->getIncomingValue(idx);
00219       NewPHI->setIncomingBlock(idx, NewLatch);
00220       if (VMap[InVal])
00221         NewPHI->setIncomingValue(idx, VMap[InVal]);
00222     }
00223   }
00224   if (NewLoop) {
00225     // Add unroll disable metadata to disable future unrolling for this loop.
00226     SmallVector<Metadata *, 4> MDs;
00227     // Reserve first location for self reference to the LoopID metadata node.
00228     MDs.push_back(nullptr);
00229     MDNode *LoopID = NewLoop->getLoopID();
00230     if (LoopID) {
00231       // First remove any existing loop unrolling metadata.
00232       for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
00233         bool IsUnrollMetadata = false;
00234         MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
00235         if (MD) {
00236           const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
00237           IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
00238         }
00239         if (!IsUnrollMetadata)
00240           MDs.push_back(LoopID->getOperand(i));
00241       }
00242     }
00243 
00244     LLVMContext &Context = NewLoop->getHeader()->getContext();
00245     SmallVector<Metadata *, 1> DisableOperands;
00246     DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
00247     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
00248     MDs.push_back(DisableNode);
00249 
00250     MDNode *NewLoopID = MDNode::get(Context, MDs);
00251     // Set operand 0 to refer to the loop id itself.
00252     NewLoopID->replaceOperandWith(0, NewLoopID);
00253     NewLoop->setLoopID(NewLoopID);
00254   }
00255 }
00256 
00257 /// Insert code in the prolog code when unrolling a loop with a
00258 /// run-time trip-count.
00259 ///
00260 /// This method assumes that the loop unroll factor is total number
00261 /// of loop bodes in the loop after unrolling. (Some folks refer
00262 /// to the unroll factor as the number of *extra* copies added).
00263 /// We assume also that the loop unroll factor is a power-of-two. So, after
00264 /// unrolling the loop, the number of loop bodies executed is 2,
00265 /// 4, 8, etc.  Note - LLVM converts the if-then-sequence to a switch
00266 /// instruction in SimplifyCFG.cpp.  Then, the backend decides how code for
00267 /// the switch instruction is generated.
00268 ///
00269 ///        extraiters = tripcount % loopfactor
00270 ///        if (extraiters == 0) jump Loop:
00271 ///        else jump Prol
00272 /// Prol:  LoopBody;
00273 ///        extraiters -= 1                 // Omitted if unroll factor is 2.
00274 ///        if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
00275 ///        if (tripcount < loopfactor) jump End
00276 /// Loop:
00277 /// ...
00278 /// End:
00279 ///
00280 bool llvm::UnrollRuntimeLoopProlog(Loop *L, unsigned Count,
00281                                    bool AllowExpensiveTripCount, LoopInfo *LI,
00282                                    LPPassManager *LPM) {
00283   // for now, only unroll loops that contain a single exit
00284   if (!L->getExitingBlock())
00285     return false;
00286 
00287   // Make sure the loop is in canonical form, and there is a single
00288   // exit block only.
00289   if (!L->isLoopSimplifyForm() || !L->getUniqueExitBlock())
00290     return false;
00291 
00292   // Use Scalar Evolution to compute the trip count.  This allows more
00293   // loops to be unrolled than relying on induction var simplification
00294   if (!LPM)
00295     return false;
00296   ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>();
00297   if (!SE)
00298     return false;
00299 
00300   // Only unroll loops with a computable trip count and the trip count needs
00301   // to be an int value (allowing a pointer type is a TODO item)
00302   const SCEV *BECountSC = SE->getBackedgeTakenCount(L);
00303   if (isa<SCEVCouldNotCompute>(BECountSC) ||
00304       !BECountSC->getType()->isIntegerTy())
00305     return false;
00306 
00307   unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
00308 
00309   // Add 1 since the backedge count doesn't include the first loop iteration
00310   const SCEV *TripCountSC =
00311     SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
00312   if (isa<SCEVCouldNotCompute>(TripCountSC))
00313     return false;
00314 
00315   BasicBlock *Header = L->getHeader();
00316   const DataLayout &DL = Header->getModule()->getDataLayout();
00317   SCEVExpander Expander(*SE, DL, "loop-unroll");
00318   if (!AllowExpensiveTripCount && Expander.isHighCostExpansion(TripCountSC, L))
00319     return false;
00320 
00321   // We only handle cases when the unroll factor is a power of 2.
00322   // Count is the loop unroll factor, the number of extra copies added + 1.
00323   if (!isPowerOf2_32(Count))
00324     return false;
00325 
00326   // This constraint lets us deal with an overflowing trip count easily; see the
00327   // comment on ModVal below.
00328   if (Log2_32(Count) > BEWidth)
00329     return false;
00330 
00331   // If this loop is nested, then the loop unroller changes the code in
00332   // parent loop, so the Scalar Evolution pass needs to be run again
00333   if (Loop *ParentLoop = L->getParentLoop())
00334     SE->forgetLoop(ParentLoop);
00335 
00336   // Grab analyses that we preserve.
00337   auto *DTWP = LPM->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
00338   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
00339 
00340   BasicBlock *PH = L->getLoopPreheader();
00341   BasicBlock *Latch = L->getLoopLatch();
00342   // It helps to splits the original preheader twice, one for the end of the
00343   // prolog code and one for a new loop preheader
00344   BasicBlock *PEnd = SplitEdge(PH, Header, DT, LI);
00345   BasicBlock *NewPH = SplitBlock(PEnd, PEnd->getTerminator(), DT, LI);
00346   BranchInst *PreHeaderBR = cast<BranchInst>(PH->getTerminator());
00347 
00348   // Compute the number of extra iterations required, which is:
00349   //  extra iterations = run-time trip count % (loop unroll factor + 1)
00350   Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
00351                                             PreHeaderBR);
00352   Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(),
00353                                           PreHeaderBR);
00354 
00355   IRBuilder<> B(PreHeaderBR);
00356   Value *ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter");
00357 
00358   // If ModVal is zero, we know that either
00359   //  1. there are no iteration to be run in the prologue loop
00360   // OR
00361   //  2. the addition computing TripCount overflowed
00362   //
00363   // If (2) is true, we know that TripCount really is (1 << BEWidth) and so the
00364   // number of iterations that remain to be run in the original loop is a
00365   // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we
00366   // explicitly check this above).
00367 
00368   Value *BranchVal = B.CreateIsNotNull(ModVal, "lcmp.mod");
00369 
00370   // Branch to either the extra iterations or the cloned/unrolled loop
00371   // We will fix up the true branch label when adding loop body copies
00372   B.CreateCondBr(BranchVal, PEnd, PEnd);
00373   assert(PreHeaderBR->isUnconditional() &&
00374          PreHeaderBR->getSuccessor(0) == PEnd &&
00375          "CFG edges in Preheader are not correct");
00376   PreHeaderBR->eraseFromParent();
00377   Function *F = Header->getParent();
00378   // Get an ordered list of blocks in the loop to help with the ordering of the
00379   // cloned blocks in the prolog code
00380   LoopBlocksDFS LoopBlocks(L);
00381   LoopBlocks.perform(LI);
00382 
00383   //
00384   // For each extra loop iteration, create a copy of the loop's basic blocks
00385   // and generate a condition that branches to the copy depending on the
00386   // number of 'left over' iterations.
00387   //
00388   std::vector<BasicBlock *> NewBlocks;
00389   ValueToValueMapTy VMap;
00390 
00391   bool UnrollPrologue = Count == 2;
00392 
00393   // Clone all the basic blocks in the loop. If Count is 2, we don't clone
00394   // the loop, otherwise we create a cloned loop to execute the extra
00395   // iterations. This function adds the appropriate CFG connections.
00396   CloneLoopBlocks(L, ModVal, UnrollPrologue, PH, PEnd, NewBlocks, LoopBlocks,
00397                   VMap, LI);
00398 
00399   // Insert the cloned blocks into function just before the original loop
00400   F->getBasicBlockList().splice(PEnd, F->getBasicBlockList(), NewBlocks[0],
00401                                 F->end());
00402 
00403   // Rewrite the cloned instruction operands to use the values
00404   // created when the clone is created.
00405   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
00406     for (BasicBlock::iterator I = NewBlocks[i]->begin(),
00407                               E = NewBlocks[i]->end();
00408          I != E; ++I) {
00409       RemapInstruction(I, VMap,
00410                        RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
00411     }
00412   }
00413 
00414   // Connect the prolog code to the original loop and update the
00415   // PHI functions.
00416   BasicBlock *LastLoopBB = cast<BasicBlock>(VMap[Latch]);
00417   ConnectProlog(L, BECount, Count, LastLoopBB, PEnd, PH, NewPH, VMap,
00418                 /*AliasAnalysis*/ nullptr, DT, LI, LPM->getAsPass());
00419   NumRuntimeUnrolled++;
00420   return true;
00421 }