LLVM API Documentation

Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members | Related Pages

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