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