rip out isExitBlockDominatedByBlockInLoop, calling DomTree::dominates instead.
[oota-llvm.git] / lib / Transforms / Scalar / LICM.cpp
1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs loop invariant code motion, attempting to remove as much
11 // code from the body of a loop as possible.  It does this by either hoisting
12 // code into the preheader block, or by sinking code to the exit blocks if it is
13 // safe.  This pass also promotes must-aliased memory locations in the loop to
14 // live in registers, thus hoisting and sinking "invariant" loads and stores.
15 //
16 // This pass uses alias analysis for two purposes:
17 //
18 //  1. Moving loop invariant loads and calls out of loops.  If we can determine
19 //     that a load or call inside of a loop never aliases anything stored to,
20 //     we can hoist it or sink it like any other instruction.
21 //  2. Scalar Promotion of Memory - If there is a store instruction inside of
22 //     the loop, we try to move the store to happen AFTER the loop instead of
23 //     inside of the loop.  This can only happen if a few conditions are true:
24 //       A. The pointer stored through is loop invariant
25 //       B. There are no stores or loads in the loop which _may_ alias the
26 //          pointer.  There are no calls in the loop which mod/ref the pointer.
27 //     If these conditions are true, we can promote the loads and stores in the
28 //     loop of the pointer to use a temporary alloca'd variable.  We then use
29 //     the SSAUpdater to construct the appropriate SSA form for the value.
30 //
31 //===----------------------------------------------------------------------===//
32
33 #define DEBUG_TYPE "licm"
34 #include "llvm/Transforms/Scalar.h"
35 #include "llvm/Constants.h"
36 #include "llvm/DerivedTypes.h"
37 #include "llvm/IntrinsicInst.h"
38 #include "llvm/Instructions.h"
39 #include "llvm/LLVMContext.h"
40 #include "llvm/Analysis/AliasAnalysis.h"
41 #include "llvm/Analysis/AliasSetTracker.h"
42 #include "llvm/Analysis/ConstantFolding.h"
43 #include "llvm/Analysis/LoopInfo.h"
44 #include "llvm/Analysis/LoopPass.h"
45 #include "llvm/Analysis/Dominators.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Transforms/Utils/SSAUpdater.h"
48 #include "llvm/Support/CFG.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/ADT/Statistic.h"
53 #include <algorithm>
54 using namespace llvm;
55
56 STATISTIC(NumSunk      , "Number of instructions sunk out of loop");
57 STATISTIC(NumHoisted   , "Number of instructions hoisted out of loop");
58 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
59 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
60 STATISTIC(NumPromoted  , "Number of memory locations promoted to registers");
61
62 static cl::opt<bool>
63 DisablePromotion("disable-licm-promotion", cl::Hidden,
64                  cl::desc("Disable memory promotion in LICM pass"));
65
66 namespace {
67   struct LICM : public LoopPass {
68     static char ID; // Pass identification, replacement for typeid
69     LICM() : LoopPass(ID) {
70       initializeLICMPass(*PassRegistry::getPassRegistry());
71     }
72
73     virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
74
75     /// This transformation requires natural loop information & requires that
76     /// loop preheaders be inserted into the CFG...
77     ///
78     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
79       AU.setPreservesCFG();
80       AU.addRequired<DominatorTree>();
81       AU.addRequired<LoopInfo>();
82       AU.addRequiredID(LoopSimplifyID);
83       AU.addRequired<AliasAnalysis>();
84       AU.addPreserved<AliasAnalysis>();
85       AU.addPreserved("scalar-evolution");
86       AU.addPreservedID(LoopSimplifyID);
87     }
88
89     bool doFinalization() {
90       assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets");
91       return false;
92     }
93
94   private:
95     AliasAnalysis *AA;       // Current AliasAnalysis information
96     LoopInfo      *LI;       // Current LoopInfo
97     DominatorTree *DT;       // Dominator Tree for the current Loop.
98
99     // State that is updated as we process loops.
100     bool Changed;            // Set to true when we change anything.
101     BasicBlock *Preheader;   // The preheader block of the current loop...
102     Loop *CurLoop;           // The current loop we are working on...
103     AliasSetTracker *CurAST; // AliasSet information for the current loop...
104     DenseMap<Loop*, AliasSetTracker*> LoopToAliasSetMap;
105
106     /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
107     void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L);
108
109     /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
110     /// set.
111     void deleteAnalysisValue(Value *V, Loop *L);
112
113     /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
114     /// dominated by the specified block, and that are in the current loop) in
115     /// reverse depth first order w.r.t the DominatorTree.  This allows us to
116     /// visit uses before definitions, allowing us to sink a loop body in one
117     /// pass without iteration.
118     ///
119     void SinkRegion(DomTreeNode *N);
120
121     /// HoistRegion - Walk the specified region of the CFG (defined by all
122     /// blocks dominated by the specified block, and that are in the current
123     /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
124     /// visit definitions before uses, allowing us to hoist a loop body in one
125     /// pass without iteration.
126     ///
127     void HoistRegion(DomTreeNode *N);
128
129     /// inSubLoop - Little predicate that returns true if the specified basic
130     /// block is in a subloop of the current one, not the current one itself.
131     ///
132     bool inSubLoop(BasicBlock *BB) {
133       assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
134       for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
135         if ((*I)->contains(BB))
136           return true;  // A subloop actually contains this block!
137       return false;
138     }
139
140     /// sink - When an instruction is found to only be used outside of the loop,
141     /// this function moves it to the exit blocks and patches up SSA form as
142     /// needed.
143     ///
144     void sink(Instruction &I);
145
146     /// hoist - When an instruction is found to only use loop invariant operands
147     /// that is safe to hoist, this instruction is called to do the dirty work.
148     ///
149     void hoist(Instruction &I);
150
151     /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
152     /// is not a trapping instruction or if it is a trapping instruction and is
153     /// guaranteed to execute.
154     ///
155     bool isSafeToExecuteUnconditionally(Instruction &I);
156
157     /// pointerInvalidatedByLoop - Return true if the body of this loop may
158     /// store into the memory location pointed to by V.
159     ///
160     bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
161                                   const MDNode *TBAAInfo) {
162       // Check to see if any of the basic blocks in CurLoop invalidate *V.
163       return CurAST->getAliasSetForPointer(V, Size, TBAAInfo).isMod();
164     }
165
166     bool canSinkOrHoistInst(Instruction &I);
167     bool isNotUsedInLoop(Instruction &I);
168
169     void PromoteAliasSet(AliasSet &AS);
170   };
171 }
172
173 char LICM::ID = 0;
174 INITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false)
175 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
176 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
177 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
178 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
179 INITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false)
180
181 Pass *llvm::createLICMPass() { return new LICM(); }
182
183 /// Hoist expressions out of the specified loop. Note, alias info for inner
184 /// loop is not preserved so it is not a good idea to run LICM multiple 
185 /// times on one loop.
186 ///
187 bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
188   Changed = false;
189
190   // Get our Loop and Alias Analysis information...
191   LI = &getAnalysis<LoopInfo>();
192   AA = &getAnalysis<AliasAnalysis>();
193   DT = &getAnalysis<DominatorTree>();
194
195   CurAST = new AliasSetTracker(*AA);
196   // Collect Alias info from subloops.
197   for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
198        LoopItr != LoopItrE; ++LoopItr) {
199     Loop *InnerL = *LoopItr;
200     AliasSetTracker *InnerAST = LoopToAliasSetMap[InnerL];
201     assert(InnerAST && "Where is my AST?");
202
203     // What if InnerLoop was modified by other passes ?
204     CurAST->add(*InnerAST);
205     
206     // Once we've incorporated the inner loop's AST into ours, we don't need the
207     // subloop's anymore.
208     delete InnerAST;
209     LoopToAliasSetMap.erase(InnerL);
210   }
211   
212   CurLoop = L;
213
214   // Get the preheader block to move instructions into...
215   Preheader = L->getLoopPreheader();
216
217   // Loop over the body of this loop, looking for calls, invokes, and stores.
218   // Because subloops have already been incorporated into AST, we skip blocks in
219   // subloops.
220   //
221   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
222        I != E; ++I) {
223     BasicBlock *BB = *I;
224     if (LI->getLoopFor(BB) == L)        // Ignore blocks in subloops.
225       CurAST->add(*BB);                 // Incorporate the specified basic block
226   }
227
228   // We want to visit all of the instructions in this loop... that are not parts
229   // of our subloops (they have already had their invariants hoisted out of
230   // their loop, into this loop, so there is no need to process the BODIES of
231   // the subloops).
232   //
233   // Traverse the body of the loop in depth first order on the dominator tree so
234   // that we are guaranteed to see definitions before we see uses.  This allows
235   // us to sink instructions in one pass, without iteration.  After sinking
236   // instructions, we perform another pass to hoist them out of the loop.
237   //
238   if (L->hasDedicatedExits())
239     SinkRegion(DT->getNode(L->getHeader()));
240   if (Preheader)
241     HoistRegion(DT->getNode(L->getHeader()));
242
243   // Now that all loop invariants have been removed from the loop, promote any
244   // memory references to scalars that we can.
245   if (!DisablePromotion && Preheader && L->hasDedicatedExits()) {
246     // Loop over all of the alias sets in the tracker object.
247     for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
248          I != E; ++I)
249       PromoteAliasSet(*I);
250   }
251   
252   // Clear out loops state information for the next iteration
253   CurLoop = 0;
254   Preheader = 0;
255
256   // If this loop is nested inside of another one, save the alias information
257   // for when we process the outer loop.
258   if (L->getParentLoop())
259     LoopToAliasSetMap[L] = CurAST;
260   else
261     delete CurAST;
262   return Changed;
263 }
264
265 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
266 /// dominated by the specified block, and that are in the current loop) in
267 /// reverse depth first order w.r.t the DominatorTree.  This allows us to visit
268 /// uses before definitions, allowing us to sink a loop body in one pass without
269 /// iteration.
270 ///
271 void LICM::SinkRegion(DomTreeNode *N) {
272   assert(N != 0 && "Null dominator tree node?");
273   BasicBlock *BB = N->getBlock();
274
275   // If this subregion is not in the top level loop at all, exit.
276   if (!CurLoop->contains(BB)) return;
277
278   // We are processing blocks in reverse dfo, so process children first.
279   const std::vector<DomTreeNode*> &Children = N->getChildren();
280   for (unsigned i = 0, e = Children.size(); i != e; ++i)
281     SinkRegion(Children[i]);
282
283   // Only need to process the contents of this block if it is not part of a
284   // subloop (which would already have been processed).
285   if (inSubLoop(BB)) return;
286
287   for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
288     Instruction &I = *--II;
289     
290     // If the instruction is dead, we would try to sink it because it isn't used
291     // in the loop, instead, just delete it.
292     if (isInstructionTriviallyDead(&I)) {
293       DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
294       ++II;
295       CurAST->deleteValue(&I);
296       I.eraseFromParent();
297       Changed = true;
298       continue;
299     }
300
301     // Check to see if we can sink this instruction to the exit blocks
302     // of the loop.  We can do this if the all users of the instruction are
303     // outside of the loop.  In this case, it doesn't even matter if the
304     // operands of the instruction are loop invariant.
305     //
306     if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
307       ++II;
308       sink(I);
309     }
310   }
311 }
312
313 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
314 /// dominated by the specified block, and that are in the current loop) in depth
315 /// first order w.r.t the DominatorTree.  This allows us to visit definitions
316 /// before uses, allowing us to hoist a loop body in one pass without iteration.
317 ///
318 void LICM::HoistRegion(DomTreeNode *N) {
319   assert(N != 0 && "Null dominator tree node?");
320   BasicBlock *BB = N->getBlock();
321
322   // If this subregion is not in the top level loop at all, exit.
323   if (!CurLoop->contains(BB)) return;
324
325   // Only need to process the contents of this block if it is not part of a
326   // subloop (which would already have been processed).
327   if (!inSubLoop(BB))
328     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
329       Instruction &I = *II++;
330
331       // Try constant folding this instruction.  If all the operands are
332       // constants, it is technically hoistable, but it would be better to just
333       // fold it.
334       if (Constant *C = ConstantFoldInstruction(&I)) {
335         DEBUG(dbgs() << "LICM folding inst: " << I << "  --> " << *C << '\n');
336         CurAST->copyValue(&I, C);
337         CurAST->deleteValue(&I);
338         I.replaceAllUsesWith(C);
339         I.eraseFromParent();
340         continue;
341       }
342       
343       // Try hoisting the instruction out to the preheader.  We can only do this
344       // if all of the operands of the instruction are loop invariant and if it
345       // is safe to hoist the instruction.
346       //
347       if (CurLoop->hasLoopInvariantOperands(&I) && canSinkOrHoistInst(I) &&
348           isSafeToExecuteUnconditionally(I))
349         hoist(I);
350     }
351
352   const std::vector<DomTreeNode*> &Children = N->getChildren();
353   for (unsigned i = 0, e = Children.size(); i != e; ++i)
354     HoistRegion(Children[i]);
355 }
356
357 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
358 /// instruction.
359 ///
360 bool LICM::canSinkOrHoistInst(Instruction &I) {
361   // Loads have extra constraints we have to verify before we can hoist them.
362   if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
363     if (LI->isVolatile())
364       return false;        // Don't hoist volatile loads!
365
366     // Loads from constant memory are always safe to move, even if they end up
367     // in the same alias set as something that ends up being modified.
368     if (AA->pointsToConstantMemory(LI->getOperand(0)))
369       return true;
370     
371     // Don't hoist loads which have may-aliased stores in loop.
372     uint64_t Size = 0;
373     if (LI->getType()->isSized())
374       Size = AA->getTypeStoreSize(LI->getType());
375     return !pointerInvalidatedByLoop(LI->getOperand(0), Size,
376                                      LI->getMetadata(LLVMContext::MD_tbaa));
377   } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
378     // Handle obvious cases efficiently.
379     AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
380     if (Behavior == AliasAnalysis::DoesNotAccessMemory)
381       return true;
382     if (AliasAnalysis::onlyReadsMemory(Behavior)) {
383       // If this call only reads from memory and there are no writes to memory
384       // in the loop, we can hoist or sink the call as appropriate.
385       bool FoundMod = false;
386       for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
387            I != E; ++I) {
388         AliasSet &AS = *I;
389         if (!AS.isForwardingAliasSet() && AS.isMod()) {
390           FoundMod = true;
391           break;
392         }
393       }
394       if (!FoundMod) return true;
395     }
396
397     // FIXME: This should use mod/ref information to see if we can hoist or sink
398     // the call.
399
400     return false;
401   }
402
403   // Otherwise these instructions are hoistable/sinkable
404   return isa<BinaryOperator>(I) || isa<CastInst>(I) ||
405          isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||
406          isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
407          isa<ShuffleVectorInst>(I);
408 }
409
410 /// isNotUsedInLoop - Return true if the only users of this instruction are
411 /// outside of the loop.  If this is true, we can sink the instruction to the
412 /// exit blocks of the loop.
413 ///
414 bool LICM::isNotUsedInLoop(Instruction &I) {
415   for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
416     Instruction *User = cast<Instruction>(*UI);
417     if (PHINode *PN = dyn_cast<PHINode>(User)) {
418       // PHI node uses occur in predecessor blocks!
419       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
420         if (PN->getIncomingValue(i) == &I)
421           if (CurLoop->contains(PN->getIncomingBlock(i)))
422             return false;
423     } else if (CurLoop->contains(User)) {
424       return false;
425     }
426   }
427   return true;
428 }
429
430
431 /// sink - When an instruction is found to only be used outside of the loop,
432 /// this function moves it to the exit blocks and patches up SSA form as needed.
433 /// This method is guaranteed to remove the original instruction from its
434 /// position, and may either delete it or move it to outside of the loop.
435 ///
436 void LICM::sink(Instruction &I) {
437   DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
438
439   SmallVector<BasicBlock*, 8> ExitBlocks;
440   CurLoop->getUniqueExitBlocks(ExitBlocks);
441
442   if (isa<LoadInst>(I)) ++NumMovedLoads;
443   else if (isa<CallInst>(I)) ++NumMovedCalls;
444   ++NumSunk;
445   Changed = true;
446
447   // The case where there is only a single exit node of this loop is common
448   // enough that we handle it as a special (more efficient) case.  It is more
449   // efficient to handle because there are no PHI nodes that need to be placed.
450   if (ExitBlocks.size() == 1) {
451     if (!DT->dominates(I.getParent(), ExitBlocks[0])) {
452       // Instruction is not used, just delete it.
453       CurAST->deleteValue(&I);
454       // If I has users in unreachable blocks, eliminate.
455       // If I is not void type then replaceAllUsesWith undef.
456       // This allows ValueHandlers and custom metadata to adjust itself.
457       if (!I.use_empty())
458         I.replaceAllUsesWith(UndefValue::get(I.getType()));
459       I.eraseFromParent();
460     } else {
461       // Move the instruction to the start of the exit block, after any PHI
462       // nodes in it.
463       I.moveBefore(ExitBlocks[0]->getFirstNonPHI());
464
465       // This instruction is no longer in the AST for the current loop, because
466       // we just sunk it out of the loop.  If we just sunk it into an outer
467       // loop, we will rediscover the operation when we process it.
468       CurAST->deleteValue(&I);
469     }
470     return;
471   }
472   
473   if (ExitBlocks.empty()) {
474     // The instruction is actually dead if there ARE NO exit blocks.
475     CurAST->deleteValue(&I);
476     // If I has users in unreachable blocks, eliminate.
477     // If I is not void type then replaceAllUsesWith undef.
478     // This allows ValueHandlers and custom metadata to adjust itself.
479     if (!I.use_empty())
480       I.replaceAllUsesWith(UndefValue::get(I.getType()));
481     I.eraseFromParent();
482     return;
483   }
484   
485   // Otherwise, if we have multiple exits, use the SSAUpdater to do all of the
486   // hard work of inserting PHI nodes as necessary.
487   SmallVector<PHINode*, 8> NewPHIs;
488   SSAUpdater SSA(&NewPHIs);
489   
490   if (!I.use_empty())
491     SSA.Initialize(I.getType(), I.getName());
492   
493   // Insert a copy of the instruction in each exit block of the loop that is
494   // dominated by the instruction.  Each exit block is known to only be in the
495   // ExitBlocks list once.
496   BasicBlock *InstOrigBB = I.getParent();
497   unsigned NumInserted = 0;
498   
499   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
500     BasicBlock *ExitBlock = ExitBlocks[i];
501     
502     if (!DT->dominates(InstOrigBB, ExitBlock))
503       continue;
504     
505     // Insert the code after the last PHI node.
506     BasicBlock::iterator InsertPt = ExitBlock->getFirstNonPHI();
507     
508     // If this is the first exit block processed, just move the original
509     // instruction, otherwise clone the original instruction and insert
510     // the copy.
511     Instruction *New;
512     if (NumInserted++ == 0) {
513       I.moveBefore(InsertPt);
514       New = &I;
515     } else {
516       New = I.clone();
517       if (!I.getName().empty())
518         New->setName(I.getName()+".le");
519       ExitBlock->getInstList().insert(InsertPt, New);
520     }
521     
522     // Now that we have inserted the instruction, inform SSAUpdater.
523     if (!I.use_empty())
524       SSA.AddAvailableValue(ExitBlock, New);
525   }
526   
527   // If the instruction doesn't dominate any exit blocks, it must be dead.
528   if (NumInserted == 0) {
529     CurAST->deleteValue(&I);
530     if (!I.use_empty())
531       I.replaceAllUsesWith(UndefValue::get(I.getType()));
532     I.eraseFromParent();
533     return;
534   }
535   
536   // Next, rewrite uses of the instruction, inserting PHI nodes as needed.
537   for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE; ) {
538     // Grab the use before incrementing the iterator.
539     Use &U = UI.getUse();
540     // Increment the iterator before removing the use from the list.
541     ++UI;
542     SSA.RewriteUseAfterInsertions(U);
543   }
544   
545   // Update CurAST for NewPHIs if I had pointer type.
546   if (I.getType()->isPointerTy())
547     for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
548       CurAST->copyValue(&I, NewPHIs[i]);
549   
550   // Finally, remove the instruction from CurAST.  It is no longer in the loop.
551   CurAST->deleteValue(&I);
552 }
553
554 /// hoist - When an instruction is found to only use loop invariant operands
555 /// that is safe to hoist, this instruction is called to do the dirty work.
556 ///
557 void LICM::hoist(Instruction &I) {
558   DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": "
559         << I << "\n");
560
561   // Move the new node to the Preheader, before its terminator.
562   I.moveBefore(Preheader->getTerminator());
563
564   if (isa<LoadInst>(I)) ++NumMovedLoads;
565   else if (isa<CallInst>(I)) ++NumMovedCalls;
566   ++NumHoisted;
567   Changed = true;
568 }
569
570 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
571 /// not a trapping instruction or if it is a trapping instruction and is
572 /// guaranteed to execute.
573 ///
574 bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
575   // If it is not a trapping instruction, it is always safe to hoist.
576   if (Inst.isSafeToSpeculativelyExecute())
577     return true;
578
579   // Otherwise we have to check to make sure that the instruction dominates all
580   // of the exit blocks.  If it doesn't, then there is a path out of the loop
581   // which does not execute this instruction, so we can't hoist it.
582
583   // If the instruction is in the header block for the loop (which is very
584   // common), it is always guaranteed to dominate the exit blocks.  Since this
585   // is a common case, and can save some work, check it now.
586   if (Inst.getParent() == CurLoop->getHeader())
587     return true;
588
589   // Get the exit blocks for the current loop.
590   SmallVector<BasicBlock*, 8> ExitBlocks;
591   CurLoop->getExitBlocks(ExitBlocks);
592
593   // Verify that the block dominates each of the exit blocks of the loop.
594   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
595     if (!DT->dominates(Inst.getParent(), ExitBlocks[i]))
596       return false;
597
598   return true;
599 }
600
601 /// PromoteAliasSet - Try to promote memory values to scalars by sinking
602 /// stores out of the loop and moving loads to before the loop.  We do this by
603 /// looping over the stores in the loop, looking for stores to Must pointers
604 /// which are loop invariant.
605 ///
606 void LICM::PromoteAliasSet(AliasSet &AS) {
607   // We can promote this alias set if it has a store, if it is a "Must" alias
608   // set, if the pointer is loop invariant, and if we are not eliminating any
609   // volatile loads or stores.
610   if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
611       AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
612     return;
613   
614   assert(!AS.empty() &&
615          "Must alias set should have at least one pointer element in it!");
616   Value *SomePtr = AS.begin()->getValue();
617
618   // It isn't safe to promote a load/store from the loop if the load/store is
619   // conditional.  For example, turning:
620   //
621   //    for () { if (c) *P += 1; }
622   //
623   // into:
624   //
625   //    tmp = *P;  for () { if (c) tmp +=1; } *P = tmp;
626   //
627   // is not safe, because *P may only be valid to access if 'c' is true.
628   // 
629   // It is safe to promote P if all uses are direct load/stores and if at
630   // least one is guaranteed to be executed.
631   bool GuaranteedToExecute = false;
632   
633   SmallVector<Instruction*, 64> LoopUses;
634   SmallPtrSet<Value*, 4> PointerMustAliases;
635
636   // Check that all of the pointers in the alias set have the same type.  We
637   // cannot (yet) promote a memory location that is loaded and stored in
638   // different sizes.
639   for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
640     Value *ASIV = ASI->getValue();
641     PointerMustAliases.insert(ASIV);
642     
643     // Check that all of the pointers in the alias set have the same type.  We
644     // cannot (yet) promote a memory location that is loaded and stored in
645     // different sizes.
646     if (SomePtr->getType() != ASIV->getType())
647       return;
648     
649     for (Value::use_iterator UI = ASIV->use_begin(), UE = ASIV->use_end();
650          UI != UE; ++UI) {
651       // Ignore instructions that are outside the loop.
652       Instruction *Use = dyn_cast<Instruction>(*UI);
653       if (!Use || !CurLoop->contains(Use))
654         continue;
655       
656       // If there is an non-load/store instruction in the loop, we can't promote
657       // it.
658       if (isa<LoadInst>(Use))
659         assert(!cast<LoadInst>(Use)->isVolatile() && "AST broken");
660       else if (isa<StoreInst>(Use)) {
661         // Stores *of* the pointer are not interesting, only stores *to* the
662         // pointer.
663         if (Use->getOperand(1) != ASIV)
664           continue;
665         assert(!cast<StoreInst>(Use)->isVolatile() && "AST broken");
666       } else
667         return; // Not a load or store.
668       
669       if (!GuaranteedToExecute)
670         GuaranteedToExecute = isSafeToExecuteUnconditionally(*Use);
671       
672       LoopUses.push_back(Use);
673     }
674   }
675   
676   // If there isn't a guaranteed-to-execute instruction, we can't promote.
677   if (!GuaranteedToExecute)
678     return;
679   
680   // Otherwise, this is safe to promote, lets do it!
681   DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n');  
682   Changed = true;
683   ++NumPromoted;
684
685   // We use the SSAUpdater interface to insert phi nodes as required.
686   SmallVector<PHINode*, 16> NewPHIs;
687   SSAUpdater SSA(&NewPHIs);
688   
689   // It wants to know some value of the same type as what we'll be inserting.
690   Value *SomeValue;
691   if (isa<LoadInst>(LoopUses[0]))
692     SomeValue = LoopUses[0];
693   else
694     SomeValue = cast<StoreInst>(LoopUses[0])->getOperand(0);
695   SSA.Initialize(SomeValue->getType(), SomeValue->getName());
696
697   // First step: bucket up uses of the pointers by the block they occur in.
698   // This is important because we have to handle multiple defs/uses in a block
699   // ourselves: SSAUpdater is purely for cross-block references.
700   // FIXME: Want a TinyVector<Instruction*> since there is usually 0/1 element.
701   DenseMap<BasicBlock*, std::vector<Instruction*> > UsesByBlock;
702   for (unsigned i = 0, e = LoopUses.size(); i != e; ++i) {
703     Instruction *User = LoopUses[i];
704     UsesByBlock[User->getParent()].push_back(User);
705   }
706   
707   // Okay, now we can iterate over all the blocks in the loop with uses,
708   // processing them.  Keep track of which loads are loading a live-in value.
709   SmallVector<LoadInst*, 32> LiveInLoads;
710   DenseMap<Value*, Value*> ReplacedLoads;
711   
712   for (unsigned LoopUse = 0, e = LoopUses.size(); LoopUse != e; ++LoopUse) {
713     Instruction *User = LoopUses[LoopUse];
714     std::vector<Instruction*> &BlockUses = UsesByBlock[User->getParent()];
715     
716     // If this block has already been processed, ignore this repeat use.
717     if (BlockUses.empty()) continue;
718     
719     // Okay, this is the first use in the block.  If this block just has a
720     // single user in it, we can rewrite it trivially.
721     if (BlockUses.size() == 1) {
722       // If it is a store, it is a trivial def of the value in the block.
723       if (isa<StoreInst>(User)) {
724         SSA.AddAvailableValue(User->getParent(),
725                               cast<StoreInst>(User)->getOperand(0));
726       } else {
727         // Otherwise it is a load, queue it to rewrite as a live-in load.
728         LiveInLoads.push_back(cast<LoadInst>(User));
729       }
730       BlockUses.clear();
731       continue;
732     }
733     
734     // Otherwise, check to see if this block is all loads.  If so, we can queue
735     // them all as live in loads.
736     bool HasStore = false;
737     for (unsigned i = 0, e = BlockUses.size(); i != e; ++i) {
738       if (isa<StoreInst>(BlockUses[i])) {
739         HasStore = true;
740         break;
741       }
742     }
743     
744     if (!HasStore) {
745       for (unsigned i = 0, e = BlockUses.size(); i != e; ++i)
746         LiveInLoads.push_back(cast<LoadInst>(BlockUses[i]));
747       BlockUses.clear();
748       continue;
749     }
750
751     // Otherwise, we have mixed loads and stores (or just a bunch of stores).
752     // Since SSAUpdater is purely for cross-block values, we need to determine
753     // the order of these instructions in the block.  If the first use in the
754     // block is a load, then it uses the live in value.  The last store defines
755     // the live out value.  We handle this by doing a linear scan of the block.
756     BasicBlock *BB = User->getParent();
757     Value *StoredValue = 0;
758     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
759       if (LoadInst *L = dyn_cast<LoadInst>(II)) {
760         // If this is a load from an unrelated pointer, ignore it.
761         if (!PointerMustAliases.count(L->getOperand(0))) continue;
762
763         // If we haven't seen a store yet, this is a live in use, otherwise
764         // use the stored value.
765         if (StoredValue) {
766           L->replaceAllUsesWith(StoredValue);
767           ReplacedLoads[L] = StoredValue;
768         } else {
769           LiveInLoads.push_back(L);
770         }
771         continue;
772       }
773       
774       if (StoreInst *S = dyn_cast<StoreInst>(II)) {
775         // If this is a store to an unrelated pointer, ignore it.
776         if (!PointerMustAliases.count(S->getOperand(1))) continue;
777
778         // Remember that this is the active value in the block.
779         StoredValue = S->getOperand(0);
780       }
781     }
782     
783     // The last stored value that happened is the live-out for the block.
784     assert(StoredValue && "Already checked that there is a store in block");
785     SSA.AddAvailableValue(BB, StoredValue);
786     BlockUses.clear();
787   }
788   
789   // Now that all the intra-loop values are classified, set up the preheader.
790   // It gets a load of the pointer we're promoting, and it is the live-out value
791   // from the preheader.
792   LoadInst *PreheaderLoad = new LoadInst(SomePtr,SomePtr->getName()+".promoted",
793                                          Preheader->getTerminator());
794   SSA.AddAvailableValue(Preheader, PreheaderLoad);
795
796   // Now that the preheader is good to go, set up the exit blocks.  Each exit
797   // block gets a store of the live-out values that feed them.  Since we've
798   // already told the SSA updater about the defs in the loop and the preheader
799   // definition, it is all set and we can start using it.
800   SmallVector<BasicBlock*, 8> ExitBlocks;
801   CurLoop->getUniqueExitBlocks(ExitBlocks);
802   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
803     BasicBlock *ExitBlock = ExitBlocks[i];
804     Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
805     Instruction *InsertPos = ExitBlock->getFirstNonPHI();
806     new StoreInst(LiveInValue, SomePtr, InsertPos);
807   }
808
809   // Okay, now we rewrite all loads that use live-in values in the loop,
810   // inserting PHI nodes as necessary.
811   for (unsigned i = 0, e = LiveInLoads.size(); i != e; ++i) {
812     LoadInst *ALoad = LiveInLoads[i];
813     Value *NewVal = SSA.GetValueInMiddleOfBlock(ALoad->getParent());
814     ALoad->replaceAllUsesWith(NewVal);
815     CurAST->copyValue(ALoad, NewVal);
816     ReplacedLoads[ALoad] = NewVal;
817   }
818   
819   // If the preheader load is itself a pointer, we need to tell alias analysis
820   // about the new pointer we created in the preheader block and about any PHI
821   // nodes that just got inserted.
822   if (PreheaderLoad->getType()->isPointerTy()) {
823     // Copy any value stored to or loaded from a must-alias of the pointer.
824     CurAST->copyValue(SomeValue, PreheaderLoad);
825     
826     for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
827       CurAST->copyValue(SomeValue, NewPHIs[i]);
828   }
829   
830   // Now that everything is rewritten, delete the old instructions from the body
831   // of the loop.  They should all be dead now.
832   for (unsigned i = 0, e = LoopUses.size(); i != e; ++i) {
833     Instruction *User = LoopUses[i];
834     
835     // If this is a load that still has uses, then the load must have been added
836     // as a live value in the SSAUpdate data structure for a block (e.g. because
837     // the loaded value was stored later).  In this case, we need to recursively
838     // propagate the updates until we get to the real value.
839     if (!User->use_empty()) {
840       Value *NewVal = ReplacedLoads[User];
841       assert(NewVal && "not a replaced load?");
842       
843       // Propagate down to the ultimate replacee.  The intermediately loads
844       // could theoretically already have been deleted, so we don't want to
845       // dereference the Value*'s.
846       DenseMap<Value*, Value*>::iterator RLI = ReplacedLoads.find(NewVal);
847       while (RLI != ReplacedLoads.end()) {
848         NewVal = RLI->second;
849         RLI = ReplacedLoads.find(NewVal);
850       }
851       
852       User->replaceAllUsesWith(NewVal);
853       CurAST->copyValue(User, NewVal);
854     }
855     
856     CurAST->deleteValue(User);
857     User->eraseFromParent();
858   }
859   
860   // fwew, we're done!
861 }
862
863
864 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
865 void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
866   AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
867   if (!AST)
868     return;
869
870   AST->copyValue(From, To);
871 }
872
873 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
874 /// set.
875 void LICM::deleteAnalysisValue(Value *V, Loop *L) {
876   AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
877   if (!AST)
878     return;
879
880   AST->deleteValue(V);
881 }