Home | History | Annotate | Download | only in Scalar
      1 //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
      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 pass implements a simple loop unroller.  It works best when loops have
     11 // been canonicalized by the -indvars pass, allowing it to determine the trip
     12 // counts of loops easily.
     13 //===----------------------------------------------------------------------===//
     14 
     15 #define DEBUG_TYPE "loop-unroll"
     16 #include "llvm/IntrinsicInst.h"
     17 #include "llvm/Transforms/Scalar.h"
     18 #include "llvm/Analysis/LoopPass.h"
     19 #include "llvm/Analysis/CodeMetrics.h"
     20 #include "llvm/Analysis/ScalarEvolution.h"
     21 #include "llvm/Support/CommandLine.h"
     22 #include "llvm/Support/Debug.h"
     23 #include "llvm/Support/raw_ostream.h"
     24 #include "llvm/Transforms/Utils/UnrollLoop.h"
     25 #include <climits>
     26 
     27 using namespace llvm;
     28 
     29 static cl::opt<unsigned>
     30 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden,
     31   cl::desc("The cut-off point for automatic loop unrolling"));
     32 
     33 static cl::opt<unsigned>
     34 UnrollCount("unroll-count", cl::init(0), cl::Hidden,
     35   cl::desc("Use this unroll count for all loops, for testing purposes"));
     36 
     37 static cl::opt<bool>
     38 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden,
     39   cl::desc("Allows loops to be partially unrolled until "
     40            "-unroll-threshold loop size is reached."));
     41 
     42 namespace {
     43   class LoopUnroll : public LoopPass {
     44   public:
     45     static char ID; // Pass ID, replacement for typeid
     46     LoopUnroll(int T = -1, int C = -1,  int P = -1) : LoopPass(ID) {
     47       CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T);
     48       CurrentCount = (C == -1) ? UnrollCount : unsigned(C);
     49       CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P;
     50 
     51       UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0);
     52 
     53       initializeLoopUnrollPass(*PassRegistry::getPassRegistry());
     54     }
     55 
     56     /// A magic value for use with the Threshold parameter to indicate
     57     /// that the loop unroll should be performed regardless of how much
     58     /// code expansion would result.
     59     static const unsigned NoThreshold = UINT_MAX;
     60 
     61     // Threshold to use when optsize is specified (and there is no
     62     // explicit -unroll-threshold).
     63     static const unsigned OptSizeUnrollThreshold = 50;
     64 
     65     unsigned CurrentCount;
     66     unsigned CurrentThreshold;
     67     bool     CurrentAllowPartial;
     68     bool     UserThreshold;        // CurrentThreshold is user-specified.
     69 
     70     bool runOnLoop(Loop *L, LPPassManager &LPM);
     71 
     72     /// This transformation requires natural loop information & requires that
     73     /// loop preheaders be inserted into the CFG...
     74     ///
     75     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
     76       AU.addRequired<LoopInfo>();
     77       AU.addPreserved<LoopInfo>();
     78       AU.addRequiredID(LoopSimplifyID);
     79       AU.addPreservedID(LoopSimplifyID);
     80       AU.addRequiredID(LCSSAID);
     81       AU.addPreservedID(LCSSAID);
     82       AU.addPreserved<ScalarEvolution>();
     83       // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.
     84       // If loop unroll does not preserve dom info then LCSSA pass on next
     85       // loop will receive invalid dom info.
     86       // For now, recreate dom info, if loop is unrolled.
     87       AU.addPreserved<DominatorTree>();
     88     }
     89   };
     90 }
     91 
     92 char LoopUnroll::ID = 0;
     93 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
     94 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
     95 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
     96 INITIALIZE_PASS_DEPENDENCY(LCSSA)
     97 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false)
     98 
     99 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial) {
    100   return new LoopUnroll(Threshold, Count, AllowPartial);
    101 }
    102 
    103 /// ApproximateLoopSize - Approximate the size of the loop.
    104 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls) {
    105   CodeMetrics Metrics;
    106   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
    107        I != E; ++I)
    108     Metrics.analyzeBasicBlock(*I);
    109   NumCalls = Metrics.NumInlineCandidates;
    110 
    111   unsigned LoopSize = Metrics.NumInsts;
    112 
    113   // Don't allow an estimate of size zero.  This would allows unrolling of loops
    114   // with huge iteration counts, which is a compile time problem even if it's
    115   // not a problem for code quality.
    116   if (LoopSize == 0) LoopSize = 1;
    117 
    118   return LoopSize;
    119 }
    120 
    121 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
    122   LoopInfo *LI = &getAnalysis<LoopInfo>();
    123 
    124   BasicBlock *Header = L->getHeader();
    125   DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName()
    126         << "] Loop %" << Header->getName() << "\n");
    127   (void)Header;
    128 
    129   // Determine the current unrolling threshold.  While this is normally set
    130   // from UnrollThreshold, it is overridden to a smaller value if the current
    131   // function is marked as optimize-for-size, and the unroll threshold was
    132   // not user specified.
    133   unsigned Threshold = CurrentThreshold;
    134   if (!UserThreshold &&
    135       Header->getParent()->hasFnAttr(Attribute::OptimizeForSize))
    136     Threshold = OptSizeUnrollThreshold;
    137 
    138   // Find trip count
    139   unsigned TripCount = L->getSmallConstantTripCount();
    140   unsigned Count = CurrentCount;
    141 
    142   // Automatically select an unroll count.
    143   if (Count == 0) {
    144     // Conservative heuristic: if we know the trip count, see if we can
    145     // completely unroll (subject to the threshold, checked below); otherwise
    146     // try to find greatest modulo of the trip count which is still under
    147     // threshold value.
    148     if (TripCount == 0)
    149       return false;
    150     Count = TripCount;
    151   }
    152 
    153   // Enforce the threshold.
    154   if (Threshold != NoThreshold) {
    155     unsigned NumInlineCandidates;
    156     unsigned LoopSize = ApproximateLoopSize(L, NumInlineCandidates);
    157     DEBUG(dbgs() << "  Loop Size = " << LoopSize << "\n");
    158     if (NumInlineCandidates != 0) {
    159       DEBUG(dbgs() << "  Not unrolling loop with inlinable calls.\n");
    160       return false;
    161     }
    162     uint64_t Size = (uint64_t)LoopSize*Count;
    163     if (TripCount != 1 && Size > Threshold) {
    164       DEBUG(dbgs() << "  Too large to fully unroll with count: " << Count
    165             << " because size: " << Size << ">" << Threshold << "\n");
    166       if (!CurrentAllowPartial) {
    167         DEBUG(dbgs() << "  will not try to unroll partially because "
    168               << "-unroll-allow-partial not given\n");
    169         return false;
    170       }
    171       // Reduce unroll count to be modulo of TripCount for partial unrolling
    172       Count = Threshold / LoopSize;
    173       while (Count != 0 && TripCount%Count != 0) {
    174         Count--;
    175       }
    176       if (Count < 2) {
    177         DEBUG(dbgs() << "  could not unroll partially\n");
    178         return false;
    179       }
    180       DEBUG(dbgs() << "  partially unrolling with count: " << Count << "\n");
    181     }
    182   }
    183 
    184   // Unroll the loop.
    185   Function *F = L->getHeader()->getParent();
    186   if (!UnrollLoop(L, Count, LI, &LPM))
    187     return false;
    188 
    189   // FIXME: Reconstruct dom info, because it is not preserved properly.
    190   if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>())
    191     DT->runOnFunction(*F);
    192   return true;
    193 }
    194