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 
00117   assert(Count != 0 && "nonsensical Count!");
00118 
00119   // If BECount <u (Count - 1) then (BECount + 1) & (Count - 1) == (BECount + 1)
00120   // (since Count is a power of 2).  This means %xtraiter is (BECount + 1) and
00121   // and all of the iterations of this loop were executed by the prologue.  Note
00122   // that if BECount <u (Count - 1) then (BECount + 1) cannot unsigned-overflow.
00123   Instruction *BrLoopExit =
00124     new ICmpInst(InsertPt, ICmpInst::ICMP_ULT, BECount,
00125                  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   BranchInst::Create(Exit, NewPH, BrLoopExit, InsertPt);
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       if (UnrollProlog) {
00188         LatchBR->eraseFromParent();
00189         BranchInst::Create(InsertBot, NewBB);
00190       } else {
00191         PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2, "prol.iter",
00192                                           FirstLoopBB->getFirstNonPHI());
00193         IRBuilder<> Builder(LatchBR);
00194         Value *IdxSub =
00195             Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
00196                               NewIdx->getName() + ".sub");
00197         Value *IdxCmp =
00198             Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
00199         BranchInst::Create(FirstLoopBB, InsertBot, IdxCmp, NewBB);
00200         NewIdx->addIncoming(NewIter, InsertTop);
00201         NewIdx->addIncoming(IdxSub, NewBB);
00202         LatchBR->eraseFromParent();
00203       }
00204     }
00205   }
00206 
00207   // Change the incoming values to the ones defined in the preheader or
00208   // cloned loop.
00209   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
00210     PHINode *NewPHI = cast<PHINode>(VMap[I]);
00211     if (UnrollProlog) {
00212       VMap[I] = NewPHI->getIncomingValueForBlock(Preheader);
00213       cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
00214     } else {
00215       unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
00216       NewPHI->setIncomingBlock(idx, InsertTop);
00217       BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
00218       idx = NewPHI->getBasicBlockIndex(Latch);
00219       Value *InVal = NewPHI->getIncomingValue(idx);
00220       NewPHI->setIncomingBlock(idx, NewLatch);
00221       if (VMap[InVal])
00222         NewPHI->setIncomingValue(idx, VMap[InVal]);
00223     }
00224   }
00225   if (NewLoop) {
00226     // Add unroll disable metadata to disable future unrolling for this loop.
00227     SmallVector<Metadata *, 4> MDs;
00228     // Reserve first location for self reference to the LoopID metadata node.
00229     MDs.push_back(nullptr);
00230     MDNode *LoopID = NewLoop->getLoopID();
00231     if (LoopID) {
00232       // First remove any existing loop unrolling metadata.
00233       for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
00234         bool IsUnrollMetadata = false;
00235         MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
00236         if (MD) {
00237           const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
00238           IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
00239         }
00240         if (!IsUnrollMetadata)
00241           MDs.push_back(LoopID->getOperand(i));
00242       }
00243     }
00244 
00245     LLVMContext &Context = NewLoop->getHeader()->getContext();
00246     SmallVector<Metadata *, 1> DisableOperands;
00247     DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
00248     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
00249     MDs.push_back(DisableNode);
00250 
00251     MDNode *NewLoopID = MDNode::get(Context, MDs);
00252     // Set operand 0 to refer to the loop id itself.
00253     NewLoopID->replaceOperandWith(0, NewLoopID);
00254     NewLoop->setLoopID(NewLoopID);
00255   }
00256 }
00257 
00258 /// Insert code in the prolog code when unrolling a loop with a
00259 /// run-time trip-count.
00260 ///
00261 /// This method assumes that the loop unroll factor is total number
00262 /// of loop bodes in the loop after unrolling. (Some folks refer
00263 /// to the unroll factor as the number of *extra* copies added).
00264 /// We assume also that the loop unroll factor is a power-of-two. So, after
00265 /// unrolling the loop, the number of loop bodies executed is 2,
00266 /// 4, 8, etc.  Note - LLVM converts the if-then-sequence to a switch
00267 /// instruction in SimplifyCFG.cpp.  Then, the backend decides how code for
00268 /// the switch instruction is generated.
00269 ///
00270 ///        extraiters = tripcount % loopfactor
00271 ///        if (extraiters == 0) jump Loop:
00272 ///        else jump Prol
00273 /// Prol:  LoopBody;
00274 ///        extraiters -= 1                 // Omitted if unroll factor is 2.
00275 ///        if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
00276 ///        if (tripcount < loopfactor) jump End
00277 /// Loop:
00278 /// ...
00279 /// End:
00280 ///
00281 bool llvm::UnrollRuntimeLoopProlog(Loop *L, unsigned Count,
00282                                    bool AllowExpensiveTripCount, LoopInfo *LI,
00283                                    LPPassManager *LPM) {
00284   // for now, only unroll loops that contain a single exit
00285   if (!L->getExitingBlock())
00286     return false;
00287 
00288   // Make sure the loop is in canonical form, and there is a single
00289   // exit block only.
00290   if (!L->isLoopSimplifyForm() || !L->getUniqueExitBlock())
00291     return false;
00292 
00293   // Use Scalar Evolution to compute the trip count.  This allows more
00294   // loops to be unrolled than relying on induction var simplification
00295   if (!LPM)
00296     return false;
00297   ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>();
00298   if (!SE)
00299     return false;
00300 
00301   // Only unroll loops with a computable trip count and the trip count needs
00302   // to be an int value (allowing a pointer type is a TODO item)
00303   const SCEV *BECountSC = SE->getBackedgeTakenCount(L);
00304   if (isa<SCEVCouldNotCompute>(BECountSC) ||
00305       !BECountSC->getType()->isIntegerTy())
00306     return false;
00307 
00308   unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
00309 
00310   // Add 1 since the backedge count doesn't include the first loop iteration
00311   const SCEV *TripCountSC =
00312     SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
00313   if (isa<SCEVCouldNotCompute>(TripCountSC))
00314     return false;
00315 
00316   BasicBlock *Header = L->getHeader();
00317   const DataLayout &DL = Header->getModule()->getDataLayout();
00318   SCEVExpander Expander(*SE, DL, "loop-unroll");
00319   if (!AllowExpensiveTripCount && Expander.isHighCostExpansion(TripCountSC, L))
00320     return false;
00321 
00322   // We only handle cases when the unroll factor is a power of 2.
00323   // Count is the loop unroll factor, the number of extra copies added + 1.
00324   if (!isPowerOf2_32(Count))
00325     return false;
00326 
00327   // This constraint lets us deal with an overflowing trip count easily; see the
00328   // comment on ModVal below.
00329   if (Log2_32(Count) > BEWidth)
00330     return false;
00331 
00332   // If this loop is nested, then the loop unroller changes the code in
00333   // parent loop, so the Scalar Evolution pass needs to be run again
00334   if (Loop *ParentLoop = L->getParentLoop())
00335     SE->forgetLoop(ParentLoop);
00336 
00337   // Grab analyses that we preserve.
00338   auto *DTWP = LPM->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
00339   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
00340 
00341   BasicBlock *PH = L->getLoopPreheader();
00342   BasicBlock *Latch = L->getLoopLatch();
00343   // It helps to splits the original preheader twice, one for the end of the
00344   // prolog code and one for a new loop preheader
00345   BasicBlock *PEnd = SplitEdge(PH, Header, DT, LI);
00346   BasicBlock *NewPH = SplitBlock(PEnd, PEnd->getTerminator(), DT, LI);
00347   BranchInst *PreHeaderBR = cast<BranchInst>(PH->getTerminator());
00348 
00349   // Compute the number of extra iterations required, which is:
00350   //  extra iterations = run-time trip count % (loop unroll factor + 1)
00351   Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
00352                                             PreHeaderBR);
00353   Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(),
00354                                           PreHeaderBR);
00355 
00356   IRBuilder<> B(PreHeaderBR);
00357   Value *ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter");
00358 
00359   // If ModVal is zero, we know that either
00360   //  1. there are no iteration to be run in the prologue loop
00361   // OR
00362   //  2. the addition computing TripCount overflowed
00363   //
00364   // If (2) is true, we know that TripCount really is (1 << BEWidth) and so the
00365   // number of iterations that remain to be run in the original loop is a
00366   // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we
00367   // explicitly check this above).
00368 
00369   Value *BranchVal = B.CreateIsNotNull(ModVal, "lcmp.mod");
00370 
00371   // Branch to either the extra iterations or the cloned/unrolled loop
00372   // We will fix up the true branch label when adding loop body copies
00373   BranchInst::Create(PEnd, PEnd, BranchVal, PreHeaderBR);
00374   assert(PreHeaderBR->isUnconditional() &&
00375          PreHeaderBR->getSuccessor(0) == PEnd &&
00376          "CFG edges in Preheader are not correct");
00377   PreHeaderBR->eraseFromParent();
00378   Function *F = Header->getParent();
00379   // Get an ordered list of blocks in the loop to help with the ordering of the
00380   // cloned blocks in the prolog code
00381   LoopBlocksDFS LoopBlocks(L);
00382   LoopBlocks.perform(LI);
00383 
00384   //
00385   // For each extra loop iteration, create a copy of the loop's basic blocks
00386   // and generate a condition that branches to the copy depending on the
00387   // number of 'left over' iterations.
00388   //
00389   std::vector<BasicBlock *> NewBlocks;
00390   ValueToValueMapTy VMap;
00391 
00392   bool UnrollPrologue = Count == 2;
00393 
00394   // Clone all the basic blocks in the loop. If Count is 2, we don't clone
00395   // the loop, otherwise we create a cloned loop to execute the extra
00396   // iterations. This function adds the appropriate CFG connections.
00397   CloneLoopBlocks(L, ModVal, UnrollPrologue, PH, PEnd, NewBlocks, LoopBlocks,
00398                   VMap, LI);
00399 
00400   // Insert the cloned blocks into function just before the original loop
00401   F->getBasicBlockList().splice(PEnd, F->getBasicBlockList(), NewBlocks[0],
00402                                 F->end());
00403 
00404   // Rewrite the cloned instruction operands to use the values
00405   // created when the clone is created.
00406   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
00407     for (BasicBlock::iterator I = NewBlocks[i]->begin(),
00408                               E = NewBlocks[i]->end();
00409          I != E; ++I) {
00410       RemapInstruction(I, VMap,
00411                        RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
00412     }
00413   }
00414 
00415   // Connect the prolog code to the original loop and update the
00416   // PHI functions.
00417   BasicBlock *LastLoopBB = cast<BasicBlock>(VMap[Latch]);
00418   ConnectProlog(L, BECount, Count, LastLoopBB, PEnd, PH, NewPH, VMap,
00419                 /*AliasAnalysis*/ nullptr, DT, LI, LPM->getAsPass());
00420   NumRuntimeUnrolled++;
00421   return true;
00422 }