LLVM API Documentation

LICM.cpp

Go to the documentation of this file.
00001 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass performs loop invariant code motion, attempting to remove as much
00011 // code from the body of a loop as possible.  It does this by either hoisting
00012 // code into the preheader block, or by sinking code to the exit blocks if it is
00013 // safe.  This pass also promotes must-aliased memory locations in the loop to
00014 // live in registers, thus hoisting and sinking "invariant" loads and stores.
00015 //
00016 // This pass uses alias analysis for two purposes:
00017 //
00018 //  1. Moving loop invariant loads and calls out of loops.  If we can determine
00019 //     that a load or call inside of a loop never aliases anything stored to,
00020 //     we can hoist it or sink it like any other instruction.
00021 //  2. Scalar Promotion of Memory - If there is a store instruction inside of
00022 //     the loop, we try to move the store to happen AFTER the loop instead of
00023 //     inside of the loop.  This can only happen if a few conditions are true:
00024 //       A. The pointer stored through is loop invariant
00025 //       B. There are no stores or loads in the loop which _may_ alias the
00026 //          pointer.  There are no calls in the loop which mod/ref the pointer.
00027 //     If these conditions are true, we can promote the loads and stores in the
00028 //     loop of the pointer to use a temporary alloca'd variable.  We then use
00029 //     the mem2reg functionality to construct the appropriate SSA form for the
00030 //     variable.
00031 //
00032 //===----------------------------------------------------------------------===//
00033 
00034 #define DEBUG_TYPE "licm"
00035 #include "llvm/Transforms/Scalar.h"
00036 #include "llvm/DerivedTypes.h"
00037 #include "llvm/Instructions.h"
00038 #include "llvm/Target/TargetData.h"
00039 #include "llvm/Analysis/LoopInfo.h"
00040 #include "llvm/Analysis/AliasAnalysis.h"
00041 #include "llvm/Analysis/AliasSetTracker.h"
00042 #include "llvm/Analysis/Dominators.h"
00043 #include "llvm/Support/CFG.h"
00044 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
00045 #include "llvm/Transforms/Utils/Local.h"
00046 #include "llvm/Support/CommandLine.h"
00047 #include "llvm/Support/Debug.h"
00048 #include "llvm/ADT/Statistic.h"
00049 #include <algorithm>
00050 #include <iostream>
00051 using namespace llvm;
00052 
00053 namespace {
00054   cl::opt<bool>
00055   DisablePromotion("disable-licm-promotion", cl::Hidden,
00056                    cl::desc("Disable memory promotion in LICM pass"));
00057 
00058   Statistic<> NumSunk("licm", "Number of instructions sunk out of loop");
00059   Statistic<> NumHoisted("licm", "Number of instructions hoisted out of loop");
00060   Statistic<> NumMovedLoads("licm", "Number of load insts hoisted or sunk");
00061   Statistic<> NumMovedCalls("licm", "Number of call insts hoisted or sunk");
00062   Statistic<> NumPromoted("licm",
00063                           "Number of memory locations promoted to registers");
00064 
00065   struct LICM : public FunctionPass {
00066     virtual bool runOnFunction(Function &F);
00067 
00068     /// This transformation requires natural loop information & requires that
00069     /// loop preheaders be inserted into the CFG...
00070     ///
00071     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00072       AU.setPreservesCFG();
00073       AU.addRequiredID(LoopSimplifyID);
00074       AU.addRequired<LoopInfo>();
00075       AU.addRequired<DominatorTree>();
00076       AU.addRequired<DominanceFrontier>();  // For scalar promotion (mem2reg)
00077       AU.addRequired<AliasAnalysis>();
00078     }
00079 
00080   private:
00081     // Various analyses that we use...
00082     AliasAnalysis *AA;       // Current AliasAnalysis information
00083     LoopInfo      *LI;       // Current LoopInfo
00084     DominatorTree *DT;       // Dominator Tree for the current Loop...
00085     DominanceFrontier *DF;   // Current Dominance Frontier
00086 
00087     // State that is updated as we process loops
00088     bool Changed;            // Set to true when we change anything.
00089     BasicBlock *Preheader;   // The preheader block of the current loop...
00090     Loop *CurLoop;           // The current loop we are working on...
00091     AliasSetTracker *CurAST; // AliasSet information for the current loop...
00092 
00093     /// visitLoop - Hoist expressions out of the specified loop...
00094     ///
00095     void visitLoop(Loop *L, AliasSetTracker &AST);
00096 
00097     /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
00098     /// dominated by the specified block, and that are in the current loop) in
00099     /// reverse depth first order w.r.t the DominatorTree.  This allows us to
00100     /// visit uses before definitions, allowing us to sink a loop body in one
00101     /// pass without iteration.
00102     ///
00103     void SinkRegion(DominatorTree::Node *N);
00104 
00105     /// HoistRegion - Walk the specified region of the CFG (defined by all
00106     /// blocks dominated by the specified block, and that are in the current
00107     /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
00108     /// visit definitions before uses, allowing us to hoist a loop body in one
00109     /// pass without iteration.
00110     ///
00111     void HoistRegion(DominatorTree::Node *N);
00112 
00113     /// inSubLoop - Little predicate that returns true if the specified basic
00114     /// block is in a subloop of the current one, not the current one itself.
00115     ///
00116     bool inSubLoop(BasicBlock *BB) {
00117       assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
00118       for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
00119         if ((*I)->contains(BB))
00120           return true;  // A subloop actually contains this block!
00121       return false;
00122     }
00123 
00124     /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
00125     /// specified exit block of the loop is dominated by the specified block
00126     /// that is in the body of the loop.  We use these constraints to
00127     /// dramatically limit the amount of the dominator tree that needs to be
00128     /// searched.
00129     bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
00130                                            BasicBlock *BlockInLoop) const {
00131       // If the block in the loop is the loop header, it must be dominated!
00132       BasicBlock *LoopHeader = CurLoop->getHeader();
00133       if (BlockInLoop == LoopHeader)
00134         return true;
00135 
00136       DominatorTree::Node *BlockInLoopNode = DT->getNode(BlockInLoop);
00137       DominatorTree::Node *IDom            = DT->getNode(ExitBlock);
00138 
00139       // Because the exit block is not in the loop, we know we have to get _at
00140       // least_ its immediate dominator.
00141       do {
00142         // Get next Immediate Dominator.
00143         IDom = IDom->getIDom();
00144 
00145         // If we have got to the header of the loop, then the instructions block
00146         // did not dominate the exit node, so we can't hoist it.
00147         if (IDom->getBlock() == LoopHeader)
00148           return false;
00149 
00150       } while (IDom != BlockInLoopNode);
00151 
00152       return true;
00153     }
00154 
00155     /// sink - When an instruction is found to only be used outside of the loop,
00156     /// this function moves it to the exit blocks and patches up SSA form as
00157     /// needed.
00158     ///
00159     void sink(Instruction &I);
00160 
00161     /// hoist - When an instruction is found to only use loop invariant operands
00162     /// that is safe to hoist, this instruction is called to do the dirty work.
00163     ///
00164     void hoist(Instruction &I);
00165 
00166     /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
00167     /// is not a trapping instruction or if it is a trapping instruction and is
00168     /// guaranteed to execute.
00169     ///
00170     bool isSafeToExecuteUnconditionally(Instruction &I);
00171 
00172     /// pointerInvalidatedByLoop - Return true if the body of this loop may
00173     /// store into the memory location pointed to by V.
00174     ///
00175     bool pointerInvalidatedByLoop(Value *V, unsigned Size) {
00176       // Check to see if any of the basic blocks in CurLoop invalidate *V.
00177       return CurAST->getAliasSetForPointer(V, Size).isMod();
00178     }
00179 
00180     bool canSinkOrHoistInst(Instruction &I);
00181     bool isLoopInvariantInst(Instruction &I);
00182     bool isNotUsedInLoop(Instruction &I);
00183 
00184     /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
00185     /// to scalars as we can.
00186     ///
00187     void PromoteValuesInLoop();
00188 
00189     /// FindPromotableValuesInLoop - Check the current loop for stores to
00190     /// definite pointers, which are not loaded and stored through may aliases.
00191     /// If these are found, create an alloca for the value, add it to the
00192     /// PromotedValues list, and keep track of the mapping from value to
00193     /// alloca...
00194     ///
00195     void FindPromotableValuesInLoop(
00196                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
00197                                     std::map<Value*, AllocaInst*> &Val2AlMap);
00198   };
00199 
00200   RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
00201 }
00202 
00203 FunctionPass *llvm::createLICMPass() { return new LICM(); }
00204 
00205 /// runOnFunction - For LICM, this simply traverses the loop structure of the
00206 /// function, hoisting expressions out of loops if possible.
00207 ///
00208 bool LICM::runOnFunction(Function &) {
00209   Changed = false;
00210 
00211   // Get our Loop and Alias Analysis information...
00212   LI = &getAnalysis<LoopInfo>();
00213   AA = &getAnalysis<AliasAnalysis>();
00214   DF = &getAnalysis<DominanceFrontier>();
00215   DT = &getAnalysis<DominatorTree>();
00216 
00217   // Hoist expressions out of all of the top-level loops.
00218   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
00219     AliasSetTracker AST(*AA);
00220     visitLoop(*I, AST);
00221   }
00222   return Changed;
00223 }
00224 
00225 
00226 /// visitLoop - Hoist expressions out of the specified loop...
00227 ///
00228 void LICM::visitLoop(Loop *L, AliasSetTracker &AST) {
00229   // Recurse through all subloops before we process this loop...
00230   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
00231     AliasSetTracker SubAST(*AA);
00232     visitLoop(*I, SubAST);
00233 
00234     // Incorporate information about the subloops into this loop...
00235     AST.add(SubAST);
00236   }
00237   CurLoop = L;
00238   CurAST = &AST;
00239 
00240   // Get the preheader block to move instructions into...
00241   Preheader = L->getLoopPreheader();
00242   assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
00243 
00244   // Loop over the body of this loop, looking for calls, invokes, and stores.
00245   // Because subloops have already been incorporated into AST, we skip blocks in
00246   // subloops.
00247   //
00248   for (std::vector<BasicBlock*>::const_iterator I = L->getBlocks().begin(),
00249          E = L->getBlocks().end(); I != E; ++I)
00250     if (LI->getLoopFor(*I) == L)        // Ignore blocks in subloops...
00251       AST.add(**I);                     // Incorporate the specified basic block
00252 
00253   // We want to visit all of the instructions in this loop... that are not parts
00254   // of our subloops (they have already had their invariants hoisted out of
00255   // their loop, into this loop, so there is no need to process the BODIES of
00256   // the subloops).
00257   //
00258   // Traverse the body of the loop in depth first order on the dominator tree so
00259   // that we are guaranteed to see definitions before we see uses.  This allows
00260   // us to sink instructions in one pass, without iteration.  AFter sinking
00261   // instructions, we perform another pass to hoist them out of the loop.
00262   //
00263   SinkRegion(DT->getNode(L->getHeader()));
00264   HoistRegion(DT->getNode(L->getHeader()));
00265 
00266   // Now that all loop invariants have been removed from the loop, promote any
00267   // memory references to scalars that we can...
00268   if (!DisablePromotion)
00269     PromoteValuesInLoop();
00270 
00271   // Clear out loops state information for the next iteration
00272   CurLoop = 0;
00273   Preheader = 0;
00274 }
00275 
00276 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
00277 /// dominated by the specified block, and that are in the current loop) in
00278 /// reverse depth first order w.r.t the DominatorTree.  This allows us to visit
00279 /// uses before definitions, allowing us to sink a loop body in one pass without
00280 /// iteration.
00281 ///
00282 void LICM::SinkRegion(DominatorTree::Node *N) {
00283   assert(N != 0 && "Null dominator tree node?");
00284   BasicBlock *BB = N->getBlock();
00285 
00286   // If this subregion is not in the top level loop at all, exit.
00287   if (!CurLoop->contains(BB)) return;
00288 
00289   // We are processing blocks in reverse dfo, so process children first...
00290   const std::vector<DominatorTree::Node*> &Children = N->getChildren();
00291   for (unsigned i = 0, e = Children.size(); i != e; ++i)
00292     SinkRegion(Children[i]);
00293 
00294   // Only need to process the contents of this block if it is not part of a
00295   // subloop (which would already have been processed).
00296   if (inSubLoop(BB)) return;
00297 
00298   for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
00299     Instruction &I = *--II;
00300 
00301     // Check to see if we can sink this instruction to the exit blocks
00302     // of the loop.  We can do this if the all users of the instruction are
00303     // outside of the loop.  In this case, it doesn't even matter if the
00304     // operands of the instruction are loop invariant.
00305     //
00306     if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
00307       ++II;
00308       sink(I);
00309     }
00310   }
00311 }
00312 
00313 
00314 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
00315 /// dominated by the specified block, and that are in the current loop) in depth
00316 /// first order w.r.t the DominatorTree.  This allows us to visit definitions
00317 /// before uses, allowing us to hoist a loop body in one pass without iteration.
00318 ///
00319 void LICM::HoistRegion(DominatorTree::Node *N) {
00320   assert(N != 0 && "Null dominator tree node?");
00321   BasicBlock *BB = N->getBlock();
00322 
00323   // If this subregion is not in the top level loop at all, exit.
00324   if (!CurLoop->contains(BB)) return;
00325 
00326   // Only need to process the contents of this block if it is not part of a
00327   // subloop (which would already have been processed).
00328   if (!inSubLoop(BB))
00329     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
00330       Instruction &I = *II++;
00331 
00332       // Try hoisting the instruction out to the preheader.  We can only do this
00333       // if all of the operands of the instruction are loop invariant and if it
00334       // is safe to hoist the instruction.
00335       //
00336       if (isLoopInvariantInst(I) && canSinkOrHoistInst(I) &&
00337           isSafeToExecuteUnconditionally(I))
00338           hoist(I);
00339       }
00340 
00341   const std::vector<DominatorTree::Node*> &Children = N->getChildren();
00342   for (unsigned i = 0, e = Children.size(); i != e; ++i)
00343     HoistRegion(Children[i]);
00344 }
00345 
00346 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
00347 /// instruction.
00348 ///
00349 bool LICM::canSinkOrHoistInst(Instruction &I) {
00350   // Loads have extra constraints we have to verify before we can hoist them.
00351   if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
00352     if (LI->isVolatile())
00353       return false;        // Don't hoist volatile loads!
00354 
00355     // Don't hoist loads which have may-aliased stores in loop.
00356     unsigned Size = 0;
00357     if (LI->getType()->isSized())
00358       Size = AA->getTargetData().getTypeSize(LI->getType());
00359     return !pointerInvalidatedByLoop(LI->getOperand(0), Size);
00360   } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
00361     // Handle obvious cases efficiently.
00362     if (Function *Callee = CI->getCalledFunction()) {
00363       AliasAnalysis::ModRefBehavior Behavior =AA->getModRefBehavior(Callee, CI);
00364       if (Behavior == AliasAnalysis::DoesNotAccessMemory)
00365         return true;
00366       else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
00367         // If this call only reads from memory and there are no writes to memory
00368         // in the loop, we can hoist or sink the call as appropriate.
00369         bool FoundMod = false;
00370         for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
00371              I != E; ++I) {
00372           AliasSet &AS = *I;
00373           if (!AS.isForwardingAliasSet() && AS.isMod()) {
00374             FoundMod = true;
00375             break;
00376           }
00377         }
00378         if (!FoundMod) return true;
00379       }
00380     }
00381 
00382     // FIXME: This should use mod/ref information to see if we can hoist or sink
00383     // the call.
00384 
00385     return false;
00386   }
00387 
00388   return isa<BinaryOperator>(I) || isa<ShiftInst>(I) || isa<CastInst>(I) ||
00389          isa<SelectInst>(I) ||
00390          isa<GetElementPtrInst>(I);
00391 }
00392 
00393 /// isNotUsedInLoop - Return true if the only users of this instruction are
00394 /// outside of the loop.  If this is true, we can sink the instruction to the
00395 /// exit blocks of the loop.
00396 ///
00397 bool LICM::isNotUsedInLoop(Instruction &I) {
00398   for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
00399     Instruction *User = cast<Instruction>(*UI);
00400     if (PHINode *PN = dyn_cast<PHINode>(User)) {
00401       // PHI node uses occur in predecessor blocks!
00402       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00403         if (PN->getIncomingValue(i) == &I)
00404           if (CurLoop->contains(PN->getIncomingBlock(i)))
00405             return false;
00406     } else if (CurLoop->contains(User->getParent())) {
00407       return false;
00408     }
00409   }
00410   return true;
00411 }
00412 
00413 
00414 /// isLoopInvariantInst - Return true if all operands of this instruction are
00415 /// loop invariant.  We also filter out non-hoistable instructions here just for
00416 /// efficiency.
00417 ///
00418 bool LICM::isLoopInvariantInst(Instruction &I) {
00419   // The instruction is loop invariant if all of its operands are loop-invariant
00420   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
00421     if (!CurLoop->isLoopInvariant(I.getOperand(i)))
00422       return false;
00423 
00424   // If we got this far, the instruction is loop invariant!
00425   return true;
00426 }
00427 
00428 /// sink - When an instruction is found to only be used outside of the loop,
00429 /// this function moves it to the exit blocks and patches up SSA form as needed.
00430 /// This method is guaranteed to remove the original instruction from its
00431 /// position, and may either delete it or move it to outside of the loop.
00432 ///
00433 void LICM::sink(Instruction &I) {
00434   DEBUG(std::cerr << "LICM sinking instruction: " << I);
00435 
00436   std::vector<BasicBlock*> ExitBlocks;
00437   CurLoop->getExitBlocks(ExitBlocks);
00438 
00439   if (isa<LoadInst>(I)) ++NumMovedLoads;
00440   else if (isa<CallInst>(I)) ++NumMovedCalls;
00441   ++NumSunk;
00442   Changed = true;
00443 
00444   // The case where there is only a single exit node of this loop is common
00445   // enough that we handle it as a special (more efficient) case.  It is more
00446   // efficient to handle because there are no PHI nodes that need to be placed.
00447   if (ExitBlocks.size() == 1) {
00448     if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
00449       // Instruction is not used, just delete it.
00450       CurAST->deleteValue(&I);
00451       I.getParent()->getInstList().erase(&I);
00452     } else {
00453       // Move the instruction to the start of the exit block, after any PHI
00454       // nodes in it.
00455       I.getParent()->getInstList().remove(&I);
00456 
00457       BasicBlock::iterator InsertPt = ExitBlocks[0]->begin();
00458       while (isa<PHINode>(InsertPt)) ++InsertPt;
00459       ExitBlocks[0]->getInstList().insert(InsertPt, &I);
00460     }
00461   } else if (ExitBlocks.size() == 0) {
00462     // The instruction is actually dead if there ARE NO exit blocks.
00463     CurAST->deleteValue(&I);
00464     I.getParent()->getInstList().erase(&I);
00465   } else {
00466     // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
00467     // do all of the hard work of inserting PHI nodes as necessary.  We convert
00468     // the value into a stack object to get it to do this.
00469 
00470     // Firstly, we create a stack object to hold the value...
00471     AllocaInst *AI = 0;
00472 
00473     if (I.getType() != Type::VoidTy)
00474       AI = new AllocaInst(I.getType(), 0, I.getName(),
00475                           I.getParent()->getParent()->front().begin());
00476 
00477     // Secondly, insert load instructions for each use of the instruction
00478     // outside of the loop.
00479     while (!I.use_empty()) {
00480       Instruction *U = cast<Instruction>(I.use_back());
00481 
00482       // If the user is a PHI Node, we actually have to insert load instructions
00483       // in all predecessor blocks, not in the PHI block itself!
00484       if (PHINode *UPN = dyn_cast<PHINode>(U)) {
00485         // Only insert into each predecessor once, so that we don't have
00486         // different incoming values from the same block!
00487         std::map<BasicBlock*, Value*> InsertedBlocks;
00488         for (unsigned i = 0, e = UPN->getNumIncomingValues(); i != e; ++i)
00489           if (UPN->getIncomingValue(i) == &I) {
00490             BasicBlock *Pred = UPN->getIncomingBlock(i);
00491             Value *&PredVal = InsertedBlocks[Pred];
00492             if (!PredVal) {
00493               // Insert a new load instruction right before the terminator in
00494               // the predecessor block.
00495               PredVal = new LoadInst(AI, "", Pred->getTerminator());
00496             }
00497 
00498             UPN->setIncomingValue(i, PredVal);
00499           }
00500 
00501       } else {
00502         LoadInst *L = new LoadInst(AI, "", U);
00503         U->replaceUsesOfWith(&I, L);
00504       }
00505     }
00506 
00507     // Thirdly, insert a copy of the instruction in each exit block of the loop
00508     // that is dominated by the instruction, storing the result into the memory
00509     // location.  Be careful not to insert the instruction into any particular
00510     // basic block more than once.
00511     std::set<BasicBlock*> InsertedBlocks;
00512     BasicBlock *InstOrigBB = I.getParent();
00513 
00514     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
00515       BasicBlock *ExitBlock = ExitBlocks[i];
00516 
00517       if (isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB)) {
00518         // If we haven't already processed this exit block, do so now.
00519         if (InsertedBlocks.insert(ExitBlock).second) {
00520           // Insert the code after the last PHI node...
00521           BasicBlock::iterator InsertPt = ExitBlock->begin();
00522           while (isa<PHINode>(InsertPt)) ++InsertPt;
00523 
00524           // If this is the first exit block processed, just move the original
00525           // instruction, otherwise clone the original instruction and insert
00526           // the copy.
00527           Instruction *New;
00528           if (InsertedBlocks.size() == 1) {
00529             I.getParent()->getInstList().remove(&I);
00530             ExitBlock->getInstList().insert(InsertPt, &I);
00531             New = &I;
00532           } else {
00533             New = I.clone();
00534             CurAST->copyValue(&I, New);
00535             if (!I.getName().empty())
00536               New->setName(I.getName()+".le");
00537             ExitBlock->getInstList().insert(InsertPt, New);
00538           }
00539 
00540           // Now that we have inserted the instruction, store it into the alloca
00541           if (AI) new StoreInst(New, AI, InsertPt);
00542         }
00543       }
00544     }
00545 
00546     // If the instruction doesn't dominate any exit blocks, it must be dead.
00547     if (InsertedBlocks.empty()) {
00548       CurAST->deleteValue(&I);
00549       I.getParent()->getInstList().erase(&I);
00550     }
00551 
00552     // Finally, promote the fine value to SSA form.
00553     if (AI) {
00554       std::vector<AllocaInst*> Allocas;
00555       Allocas.push_back(AI);
00556       PromoteMemToReg(Allocas, *DT, *DF, AA->getTargetData(), CurAST);
00557     }
00558   }
00559 }
00560 
00561 /// hoist - When an instruction is found to only use loop invariant operands
00562 /// that is safe to hoist, this instruction is called to do the dirty work.
00563 ///
00564 void LICM::hoist(Instruction &I) {
00565   DEBUG(std::cerr << "LICM hoisting to " << Preheader->getName()
00566                   << ": " << I);
00567 
00568   // Remove the instruction from its current basic block... but don't delete the
00569   // instruction.
00570   I.getParent()->getInstList().remove(&I);
00571 
00572   // Insert the new node in Preheader, before the terminator.
00573   Preheader->getInstList().insert(Preheader->getTerminator(), &I);
00574 
00575   if (isa<LoadInst>(I)) ++NumMovedLoads;
00576   else if (isa<CallInst>(I)) ++NumMovedCalls;
00577   ++NumHoisted;
00578   Changed = true;
00579 }
00580 
00581 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
00582 /// not a trapping instruction or if it is a trapping instruction and is
00583 /// guaranteed to execute.
00584 ///
00585 bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
00586   // If it is not a trapping instruction, it is always safe to hoist.
00587   if (!Inst.isTrapping()) return true;
00588 
00589   // Otherwise we have to check to make sure that the instruction dominates all
00590   // of the exit blocks.  If it doesn't, then there is a path out of the loop
00591   // which does not execute this instruction, so we can't hoist it.
00592 
00593   // If the instruction is in the header block for the loop (which is very
00594   // common), it is always guaranteed to dominate the exit blocks.  Since this
00595   // is a common case, and can save some work, check it now.
00596   if (Inst.getParent() == CurLoop->getHeader())
00597     return true;
00598 
00599   // It's always safe to load from a global or alloca.
00600   if (isa<LoadInst>(Inst))
00601     if (isa<AllocationInst>(Inst.getOperand(0)) ||
00602         isa<GlobalVariable>(Inst.getOperand(0)))
00603       return true;
00604 
00605   // Get the exit blocks for the current loop.
00606   std::vector<BasicBlock*> ExitBlocks;
00607   CurLoop->getExitBlocks(ExitBlocks);
00608 
00609   // For each exit block, get the DT node and walk up the DT until the
00610   // instruction's basic block is found or we exit the loop.
00611   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
00612     if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
00613       return false;
00614 
00615   return true;
00616 }
00617 
00618 
00619 /// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
00620 /// stores out of the loop and moving loads to before the loop.  We do this by
00621 /// looping over the stores in the loop, looking for stores to Must pointers
00622 /// which are loop invariant.  We promote these memory locations to use allocas
00623 /// instead.  These allocas can easily be raised to register values by the
00624 /// PromoteMem2Reg functionality.
00625 ///
00626 void LICM::PromoteValuesInLoop() {
00627   // PromotedValues - List of values that are promoted out of the loop.  Each
00628   // value has an alloca instruction for it, and a canonical version of the
00629   // pointer.
00630   std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
00631   std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
00632 
00633   FindPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
00634   if (ValueToAllocaMap.empty()) return;   // If there are values to promote.
00635 
00636   Changed = true;
00637   NumPromoted += PromotedValues.size();
00638 
00639   std::vector<Value*> PointerValueNumbers;
00640 
00641   // Emit a copy from the value into the alloca'd value in the loop preheader
00642   TerminatorInst *LoopPredInst = Preheader->getTerminator();
00643   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
00644     Value *Ptr = PromotedValues[i].second;
00645 
00646     // If we are promoting a pointer value, update alias information for the
00647     // inserted load.
00648     Value *LoadValue = 0;
00649     if (isa<PointerType>(cast<PointerType>(Ptr->getType())->getElementType())) {
00650       // Locate a load or store through the pointer, and assign the same value
00651       // to LI as we are loading or storing.  Since we know that the value is
00652       // stored in this loop, this will always succeed.
00653       for (Value::use_iterator UI = Ptr->use_begin(), E = Ptr->use_end();
00654            UI != E; ++UI)
00655         if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
00656           LoadValue = LI;
00657           break;
00658         } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
00659           if (SI->getOperand(1) == Ptr) {
00660             LoadValue = SI->getOperand(0);
00661             break;
00662           }
00663         }
00664       assert(LoadValue && "No store through the pointer found!");
00665       PointerValueNumbers.push_back(LoadValue);  // Remember this for later.
00666     }
00667 
00668     // Load from the memory we are promoting.
00669     LoadInst *LI = new LoadInst(Ptr, Ptr->getName()+".promoted", LoopPredInst);
00670 
00671     if (LoadValue) CurAST->copyValue(LoadValue, LI);
00672 
00673     // Store into the temporary alloca.
00674     new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
00675   }
00676 
00677   // Scan the basic blocks in the loop, replacing uses of our pointers with
00678   // uses of the allocas in question.
00679   //
00680   const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
00681   for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
00682          E = LoopBBs.end(); I != E; ++I) {
00683     // Rewrite all loads and stores in the block of the pointer...
00684     for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
00685          II != E; ++II) {
00686       if (LoadInst *L = dyn_cast<LoadInst>(II)) {
00687         std::map<Value*, AllocaInst*>::iterator
00688           I = ValueToAllocaMap.find(L->getOperand(0));
00689         if (I != ValueToAllocaMap.end())
00690           L->setOperand(0, I->second);    // Rewrite load instruction...
00691       } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
00692         std::map<Value*, AllocaInst*>::iterator
00693           I = ValueToAllocaMap.find(S->getOperand(1));
00694         if (I != ValueToAllocaMap.end())
00695           S->setOperand(1, I->second);    // Rewrite store instruction...
00696       }
00697     }
00698   }
00699 
00700   // Now that the body of the loop uses the allocas instead of the original
00701   // memory locations, insert code to copy the alloca value back into the
00702   // original memory location on all exits from the loop.  Note that we only
00703   // want to insert one copy of the code in each exit block, though the loop may
00704   // exit to the same block more than once.
00705   //
00706   std::set<BasicBlock*> ProcessedBlocks;
00707 
00708   std::vector<BasicBlock*> ExitBlocks;
00709   CurLoop->getExitBlocks(ExitBlocks);
00710   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
00711     if (ProcessedBlocks.insert(ExitBlocks[i]).second) {
00712       // Copy all of the allocas into their memory locations.
00713       BasicBlock::iterator BI = ExitBlocks[i]->begin();
00714       while (isa<PHINode>(*BI))
00715         ++BI;             // Skip over all of the phi nodes in the block.
00716       Instruction *InsertPos = BI;
00717       unsigned PVN = 0;
00718       for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
00719         // Load from the alloca.
00720         LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
00721 
00722         // If this is a pointer type, update alias info appropriately.
00723         if (isa<PointerType>(LI->getType()))
00724           CurAST->copyValue(PointerValueNumbers[PVN++], LI);
00725 
00726         // Store into the memory we promoted.
00727         new StoreInst(LI, PromotedValues[i].second, InsertPos);
00728       }
00729     }
00730 
00731   // Now that we have done the deed, use the mem2reg functionality to promote
00732   // all of the new allocas we just created into real SSA registers.
00733   //
00734   std::vector<AllocaInst*> PromotedAllocas;
00735   PromotedAllocas.reserve(PromotedValues.size());
00736   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
00737     PromotedAllocas.push_back(PromotedValues[i].first);
00738   PromoteMemToReg(PromotedAllocas, *DT, *DF, AA->getTargetData(), CurAST);
00739 }
00740 
00741 /// FindPromotableValuesInLoop - Check the current loop for stores to definite
00742 /// pointers, which are not loaded and stored through may aliases.  If these are
00743 /// found, create an alloca for the value, add it to the PromotedValues list,
00744 /// and keep track of the mapping from value to alloca.
00745 ///
00746 void LICM::FindPromotableValuesInLoop(
00747                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
00748                              std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
00749   Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
00750 
00751   // Loop over all of the alias sets in the tracker object.
00752   for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
00753        I != E; ++I) {
00754     AliasSet &AS = *I;
00755     // We can promote this alias set if it has a store, if it is a "Must" alias
00756     // set, if the pointer is loop invariant, and if we are not eliminating any
00757     // volatile loads or stores.
00758     if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias() &&
00759         !AS.isVolatile() && CurLoop->isLoopInvariant(AS.begin()->first)) {
00760       assert(AS.begin() != AS.end() &&
00761              "Must alias set should have at least one pointer element in it!");
00762       Value *V = AS.begin()->first;
00763 
00764       // Check that all of the pointers in the alias set have the same type.  We
00765       // cannot (yet) promote a memory location that is loaded and stored in
00766       // different sizes.
00767       bool PointerOk = true;
00768       for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
00769         if (V->getType() != I->first->getType()) {
00770           PointerOk = false;
00771           break;
00772         }
00773 
00774       if (PointerOk) {
00775         const Type *Ty = cast<PointerType>(V->getType())->getElementType();
00776         AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
00777         PromotedValues.push_back(std::make_pair(AI, V));
00778 
00779         // Update the AST and alias analysis.
00780         CurAST->copyValue(V, AI);
00781 
00782         for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
00783           ValueToAllocaMap.insert(std::make_pair(I->first, AI));
00784 
00785         DEBUG(std::cerr << "LICM: Promoting value: " << *V << "\n");
00786       }
00787     }
00788   }
00789 }