[LPM] Make LCSSA a utility with a FunctionPass that applies it to all
[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/ADT/Statistic.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/Analysis/AliasSetTracker.h"
38 #include "llvm/Analysis/ConstantFolding.h"
39 #include "llvm/Analysis/LoopInfo.h"
40 #include "llvm/Analysis/LoopPass.h"
41 #include "llvm/Analysis/ScalarEvolution.h"
42 #include "llvm/Analysis/ValueTracking.h"
43 #include "llvm/IR/Constants.h"
44 #include "llvm/IR/DataLayout.h"
45 #include "llvm/IR/DerivedTypes.h"
46 #include "llvm/IR/Dominators.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/IntrinsicInst.h"
49 #include "llvm/IR/LLVMContext.h"
50 #include "llvm/IR/Metadata.h"
51 #include "llvm/Support/CFG.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Target/TargetLibraryInfo.h"
56 #include "llvm/Transforms/Utils/Local.h"
57 #include "llvm/Transforms/Utils/LoopUtils.h"
58 #include "llvm/Transforms/Utils/SSAUpdater.h"
59 #include <algorithm>
60 using namespace llvm;
61
62 STATISTIC(NumSunk      , "Number of instructions sunk out of loop");
63 STATISTIC(NumHoisted   , "Number of instructions hoisted out of loop");
64 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
65 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
66 STATISTIC(NumPromoted  , "Number of memory locations promoted to registers");
67
68 static cl::opt<bool>
69 DisablePromotion("disable-licm-promotion", cl::Hidden,
70                  cl::desc("Disable memory promotion in LICM pass"));
71
72 namespace {
73   struct LICM : public LoopPass {
74     static char ID; // Pass identification, replacement for typeid
75     LICM() : LoopPass(ID) {
76       initializeLICMPass(*PassRegistry::getPassRegistry());
77     }
78
79     virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
80
81     /// This transformation requires natural loop information & requires that
82     /// loop preheaders be inserted into the CFG...
83     ///
84     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
85       AU.setPreservesCFG();
86       AU.addRequired<DominatorTreeWrapperPass>();
87       AU.addRequired<LoopInfo>();
88       AU.addRequiredID(LoopSimplifyID);
89       AU.addPreservedID(LoopSimplifyID);
90       AU.addRequiredID(LCSSAID);
91       AU.addPreservedID(LCSSAID);
92       AU.addRequired<AliasAnalysis>();
93       AU.addPreserved<AliasAnalysis>();
94       AU.addPreserved<ScalarEvolution>();
95       AU.addRequired<TargetLibraryInfo>();
96     }
97
98     using llvm::Pass::doFinalization;
99
100     bool doFinalization() {
101       assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets");
102       return false;
103     }
104
105   private:
106     AliasAnalysis *AA;       // Current AliasAnalysis information
107     LoopInfo      *LI;       // Current LoopInfo
108     DominatorTree *DT;       // Dominator Tree for the current Loop.
109
110     DataLayout *TD;          // DataLayout for constant folding.
111     TargetLibraryInfo *TLI;  // TargetLibraryInfo for constant folding.
112
113     // State that is updated as we process loops.
114     bool Changed;            // Set to true when we change anything.
115     BasicBlock *Preheader;   // The preheader block of the current loop...
116     Loop *CurLoop;           // The current loop we are working on...
117     AliasSetTracker *CurAST; // AliasSet information for the current loop...
118     bool MayThrow;           // The current loop contains an instruction which
119                              // may throw, thus preventing code motion of
120                              // instructions with side effects.
121     DenseMap<Loop*, AliasSetTracker*> LoopToAliasSetMap;
122
123     /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
124     void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L);
125
126     /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
127     /// set.
128     void deleteAnalysisValue(Value *V, Loop *L);
129
130     /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
131     /// dominated by the specified block, and that are in the current loop) in
132     /// reverse depth first order w.r.t the DominatorTree.  This allows us to
133     /// visit uses before definitions, allowing us to sink a loop body in one
134     /// pass without iteration.
135     ///
136     void SinkRegion(DomTreeNode *N);
137
138     /// HoistRegion - Walk the specified region of the CFG (defined by all
139     /// blocks dominated by the specified block, and that are in the current
140     /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
141     /// visit definitions before uses, allowing us to hoist a loop body in one
142     /// pass without iteration.
143     ///
144     void HoistRegion(DomTreeNode *N);
145
146     /// inSubLoop - Little predicate that returns true if the specified basic
147     /// block is in a subloop of the current one, not the current one itself.
148     ///
149     bool inSubLoop(BasicBlock *BB) {
150       assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
151       return LI->getLoopFor(BB) != CurLoop;
152     }
153
154     /// sink - When an instruction is found to only be used outside of the loop,
155     /// this function moves it to the exit blocks and patches up SSA form as
156     /// needed.
157     ///
158     void sink(Instruction &I);
159
160     /// hoist - When an instruction is found to only use loop invariant operands
161     /// that is safe to hoist, this instruction is called to do the dirty work.
162     ///
163     void hoist(Instruction &I);
164
165     /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
166     /// is not a trapping instruction or if it is a trapping instruction and is
167     /// guaranteed to execute.
168     ///
169     bool isSafeToExecuteUnconditionally(Instruction &I);
170
171     /// isGuaranteedToExecute - Check that the instruction is guaranteed to
172     /// execute.
173     ///
174     bool isGuaranteedToExecute(Instruction &I);
175
176     /// pointerInvalidatedByLoop - Return true if the body of this loop may
177     /// store into the memory location pointed to by V.
178     ///
179     bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
180                                   const MDNode *TBAAInfo) {
181       // Check to see if any of the basic blocks in CurLoop invalidate *V.
182       return CurAST->getAliasSetForPointer(V, Size, TBAAInfo).isMod();
183     }
184
185     bool canSinkOrHoistInst(Instruction &I);
186     bool isNotUsedInLoop(Instruction &I);
187
188     void PromoteAliasSet(AliasSet &AS,
189                          SmallVectorImpl<BasicBlock*> &ExitBlocks,
190                          SmallVectorImpl<Instruction*> &InsertPts);
191   };
192 }
193
194 char LICM::ID = 0;
195 INITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false)
196 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
197 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
198 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
199 INITIALIZE_PASS_DEPENDENCY(LCSSA)
200 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
201 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
202 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
203 INITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false)
204
205 Pass *llvm::createLICMPass() { return new LICM(); }
206
207 /// Hoist expressions out of the specified loop. Note, alias info for inner
208 /// loop is not preserved so it is not a good idea to run LICM multiple
209 /// times on one loop.
210 ///
211 bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
212   Changed = false;
213
214   // Get our Loop and Alias Analysis information...
215   LI = &getAnalysis<LoopInfo>();
216   AA = &getAnalysis<AliasAnalysis>();
217   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
218
219   TD = getAnalysisIfAvailable<DataLayout>();
220   TLI = &getAnalysis<TargetLibraryInfo>();
221
222   CurAST = new AliasSetTracker(*AA);
223   // Collect Alias info from subloops.
224   for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
225        LoopItr != LoopItrE; ++LoopItr) {
226     Loop *InnerL = *LoopItr;
227     AliasSetTracker *InnerAST = LoopToAliasSetMap[InnerL];
228     assert(InnerAST && "Where is my AST?");
229
230     // What if InnerLoop was modified by other passes ?
231     CurAST->add(*InnerAST);
232
233     // Once we've incorporated the inner loop's AST into ours, we don't need the
234     // subloop's anymore.
235     delete InnerAST;
236     LoopToAliasSetMap.erase(InnerL);
237   }
238
239   CurLoop = L;
240
241   // Get the preheader block to move instructions into...
242   Preheader = L->getLoopPreheader();
243
244   // Loop over the body of this loop, looking for calls, invokes, and stores.
245   // Because subloops have already been incorporated into AST, we skip blocks in
246   // subloops.
247   //
248   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
249        I != E; ++I) {
250     BasicBlock *BB = *I;
251     if (LI->getLoopFor(BB) == L)        // Ignore blocks in subloops.
252       CurAST->add(*BB);                 // Incorporate the specified basic block
253   }
254
255   MayThrow = false;
256   // TODO: We've already searched for instructions which may throw in subloops.
257   // We may want to reuse this information.
258   for (Loop::block_iterator BB = L->block_begin(), BBE = L->block_end();
259        (BB != BBE) && !MayThrow ; ++BB)
260     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
261          (I != E) && !MayThrow; ++I)
262       MayThrow |= I->mayThrow();
263
264   // We want to visit all of the instructions in this loop... that are not parts
265   // of our subloops (they have already had their invariants hoisted out of
266   // their loop, into this loop, so there is no need to process the BODIES of
267   // the subloops).
268   //
269   // Traverse the body of the loop in depth first order on the dominator tree so
270   // that we are guaranteed to see definitions before we see uses.  This allows
271   // us to sink instructions in one pass, without iteration.  After sinking
272   // instructions, we perform another pass to hoist them out of the loop.
273   //
274   if (L->hasDedicatedExits())
275     SinkRegion(DT->getNode(L->getHeader()));
276   if (Preheader)
277     HoistRegion(DT->getNode(L->getHeader()));
278
279   // Now that all loop invariants have been removed from the loop, promote any
280   // memory references to scalars that we can.
281   if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) {
282     SmallVector<BasicBlock *, 8> ExitBlocks;
283     SmallVector<Instruction *, 8> InsertPts;
284
285     // Loop over all of the alias sets in the tracker object.
286     for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
287          I != E; ++I)
288       PromoteAliasSet(*I, ExitBlocks, InsertPts);
289   }
290
291   // If we have successfully changed the loop, re-form LCSSA and also re-form
292   // LCSSA in the parent loop as hoisting or sinking may have broken it.
293   if (Changed) {
294     formLCSSA(*L, *DT, getAnalysisIfAvailable<ScalarEvolution>());
295     if (Loop *ParentL = L->getParentLoop())
296       formLCSSA(*ParentL, *DT, getAnalysisIfAvailable<ScalarEvolution>());
297   }
298
299   // Clear out loops state information for the next iteration
300   CurLoop = 0;
301   Preheader = 0;
302
303   // If this loop is nested inside of another one, save the alias information
304   // for when we process the outer loop.
305   if (L->getParentLoop())
306     LoopToAliasSetMap[L] = CurAST;
307   else
308     delete CurAST;
309   return Changed;
310 }
311
312 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
313 /// dominated by the specified block, and that are in the current loop) in
314 /// reverse depth first order w.r.t the DominatorTree.  This allows us to visit
315 /// uses before definitions, allowing us to sink a loop body in one pass without
316 /// iteration.
317 ///
318 void LICM::SinkRegion(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   // We are processing blocks in reverse dfo, so process children first.
326   const std::vector<DomTreeNode*> &Children = N->getChildren();
327   for (unsigned i = 0, e = Children.size(); i != e; ++i)
328     SinkRegion(Children[i]);
329
330   // Only need to process the contents of this block if it is not part of a
331   // subloop (which would already have been processed).
332   if (inSubLoop(BB)) return;
333
334   for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
335     Instruction &I = *--II;
336
337     // If the instruction is dead, we would try to sink it because it isn't used
338     // in the loop, instead, just delete it.
339     if (isInstructionTriviallyDead(&I, TLI)) {
340       DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
341       ++II;
342       CurAST->deleteValue(&I);
343       I.eraseFromParent();
344       Changed = true;
345       continue;
346     }
347
348     // Check to see if we can sink this instruction to the exit blocks
349     // of the loop.  We can do this if the all users of the instruction are
350     // outside of the loop.  In this case, it doesn't even matter if the
351     // operands of the instruction are loop invariant.
352     //
353     if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
354       ++II;
355       sink(I);
356     }
357   }
358 }
359
360 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
361 /// dominated by the specified block, and that are in the current loop) in depth
362 /// first order w.r.t the DominatorTree.  This allows us to visit definitions
363 /// before uses, allowing us to hoist a loop body in one pass without iteration.
364 ///
365 void LICM::HoistRegion(DomTreeNode *N) {
366   assert(N != 0 && "Null dominator tree node?");
367   BasicBlock *BB = N->getBlock();
368
369   // If this subregion is not in the top level loop at all, exit.
370   if (!CurLoop->contains(BB)) return;
371
372   // Only need to process the contents of this block if it is not part of a
373   // subloop (which would already have been processed).
374   if (!inSubLoop(BB))
375     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
376       Instruction &I = *II++;
377
378       // Try constant folding this instruction.  If all the operands are
379       // constants, it is technically hoistable, but it would be better to just
380       // fold it.
381       if (Constant *C = ConstantFoldInstruction(&I, TD, TLI)) {
382         DEBUG(dbgs() << "LICM folding inst: " << I << "  --> " << *C << '\n');
383         CurAST->copyValue(&I, C);
384         CurAST->deleteValue(&I);
385         I.replaceAllUsesWith(C);
386         I.eraseFromParent();
387         continue;
388       }
389
390       // Try hoisting the instruction out to the preheader.  We can only do this
391       // if all of the operands of the instruction are loop invariant and if it
392       // is safe to hoist the instruction.
393       //
394       if (CurLoop->hasLoopInvariantOperands(&I) && canSinkOrHoistInst(I) &&
395           isSafeToExecuteUnconditionally(I))
396         hoist(I);
397     }
398
399   const std::vector<DomTreeNode*> &Children = N->getChildren();
400   for (unsigned i = 0, e = Children.size(); i != e; ++i)
401     HoistRegion(Children[i]);
402 }
403
404 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
405 /// instruction.
406 ///
407 bool LICM::canSinkOrHoistInst(Instruction &I) {
408   // Loads have extra constraints we have to verify before we can hoist them.
409   if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
410     if (!LI->isUnordered())
411       return false;        // Don't hoist volatile/atomic loads!
412
413     // Loads from constant memory are always safe to move, even if they end up
414     // in the same alias set as something that ends up being modified.
415     if (AA->pointsToConstantMemory(LI->getOperand(0)))
416       return true;
417     if (LI->getMetadata("invariant.load"))
418       return true;
419
420     // Don't hoist loads which have may-aliased stores in loop.
421     uint64_t Size = 0;
422     if (LI->getType()->isSized())
423       Size = AA->getTypeStoreSize(LI->getType());
424     return !pointerInvalidatedByLoop(LI->getOperand(0), Size,
425                                      LI->getMetadata(LLVMContext::MD_tbaa));
426   } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
427     // Don't sink or hoist dbg info; it's legal, but not useful.
428     if (isa<DbgInfoIntrinsic>(I))
429       return false;
430
431     // Handle simple cases by querying alias analysis.
432     AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
433     if (Behavior == AliasAnalysis::DoesNotAccessMemory)
434       return true;
435     if (AliasAnalysis::onlyReadsMemory(Behavior)) {
436       // If this call only reads from memory and there are no writes to memory
437       // in the loop, we can hoist or sink the call as appropriate.
438       bool FoundMod = false;
439       for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
440            I != E; ++I) {
441         AliasSet &AS = *I;
442         if (!AS.isForwardingAliasSet() && AS.isMod()) {
443           FoundMod = true;
444           break;
445         }
446       }
447       if (!FoundMod) return true;
448     }
449
450     // FIXME: This should use mod/ref information to see if we can hoist or
451     // sink the call.
452
453     return false;
454   }
455
456   // Only these instructions are hoistable/sinkable.
457   if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
458       !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
459       !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
460       !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
461       !isa<InsertValueInst>(I))
462     return false;
463
464   return isSafeToExecuteUnconditionally(I);
465 }
466
467 /// \brief Returns true if a PHINode is a trivially replaceable with an
468 /// Instruction.
469 ///
470 /// This is true when all incoming values are that instruction. This pattern
471 /// occurs most often with LCSSA PHI nodes.
472 static bool isTriviallyReplacablePHI(PHINode &PN, Instruction &I) {
473   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
474     if (PN.getIncomingValue(i) != &I)
475       return false;
476
477   return true;
478 }
479
480 /// isNotUsedInLoop - Return true if the only users of this instruction are
481 /// outside of the loop.  If this is true, we can sink the instruction to the
482 /// exit blocks of the loop.
483 ///
484 bool LICM::isNotUsedInLoop(Instruction &I) {
485   for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
486     Instruction *User = cast<Instruction>(*UI);
487     if (PHINode *PN = dyn_cast<PHINode>(User)) {
488       // A PHI node where all of the incoming values are this instruction are
489       // special -- they can just be RAUW'ed with the instruction and thus
490       // don't require a use in the predecessor. This is a particular important
491       // special case because it is the pattern found in LCSSA form.
492       if (isTriviallyReplacablePHI(*PN, I)) {
493         if (CurLoop->contains(PN))
494           return false;
495         else
496           continue;
497       }
498
499       // Otherwise, PHI node uses occur in predecessor blocks if the incoming
500       // values. Check for such a use being inside the loop.
501       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
502         if (PN->getIncomingValue(i) == &I)
503           if (CurLoop->contains(PN->getIncomingBlock(i)))
504             return false;
505
506       continue;
507     }
508
509     if (CurLoop->contains(User))
510       return false;
511   }
512   return true;
513 }
514
515 static BasicBlock::iterator
516 replaceTrivialPHIsAndGetInsertionPt(BasicBlock &BB, Instruction &I) {
517   BasicBlock::iterator II = BB.begin();
518   while (PHINode *PN = dyn_cast<PHINode>(II)) {
519     ++II;
520     if (isTriviallyReplacablePHI(*PN, I)) {
521       PN->replaceAllUsesWith(&I);
522       PN->eraseFromParent();
523     }
524   }
525   if (isa<LandingPadInst>(II))
526     ++II;
527
528   return II;
529 }
530
531 /// sink - When an instruction is found to only be used outside of the loop,
532 /// this function moves it to the exit blocks and patches up SSA form as needed.
533 /// This method is guaranteed to remove the original instruction from its
534 /// position, and may either delete it or move it to outside of the loop.
535 ///
536 void LICM::sink(Instruction &I) {
537   DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
538
539   SmallVector<BasicBlock*, 8> ExitBlocks;
540   CurLoop->getUniqueExitBlocks(ExitBlocks);
541
542   if (isa<LoadInst>(I)) ++NumMovedLoads;
543   else if (isa<CallInst>(I)) ++NumMovedCalls;
544   ++NumSunk;
545   Changed = true;
546
547   // The case where there is only a single exit node of this loop is common
548   // enough that we handle it as a special (more efficient) case.  It is more
549   // efficient to handle because there are no PHI nodes that need to be placed.
550   if (ExitBlocks.size() == 1) {
551     if (!DT->dominates(I.getParent(), ExitBlocks[0])) {
552       // Instruction is not used, just delete it.
553       CurAST->deleteValue(&I);
554       // If I has users in unreachable blocks, eliminate.
555       // If I is not void type then replaceAllUsesWith undef.
556       // This allows ValueHandlers and custom metadata to adjust itself.
557       if (!I.use_empty())
558         I.replaceAllUsesWith(UndefValue::get(I.getType()));
559       I.eraseFromParent();
560     } else {
561       // Look for any LCSSA PHI nodes for this instruction in the exit blocks
562       // and replace them.
563       BasicBlock::iterator II =
564           replaceTrivialPHIsAndGetInsertionPt(*ExitBlocks[0], I);
565
566       // Move the instruction to the start of the exit block, after any PHI
567       // nodes in it.
568       I.moveBefore(II);
569
570       // This instruction is no longer in the AST for the current loop, because
571       // we just sunk it out of the loop.  If we just sunk it into an outer
572       // loop, we will rediscover the operation when we process it.
573       CurAST->deleteValue(&I);
574     }
575     return;
576   }
577
578   if (ExitBlocks.empty()) {
579     // The instruction is actually dead if there ARE NO exit blocks.
580     CurAST->deleteValue(&I);
581     // If I has users in unreachable blocks, eliminate.
582     // If I is not void type then replaceAllUsesWith undef.
583     // This allows ValueHandlers and custom metadata to adjust itself.
584     if (!I.use_empty())
585       I.replaceAllUsesWith(UndefValue::get(I.getType()));
586     I.eraseFromParent();
587     return;
588   }
589
590   // Otherwise, if we have multiple exits, use the SSAUpdater to do all of the
591   // hard work of inserting PHI nodes as necessary.
592   SmallVector<PHINode*, 8> NewPHIs;
593   SSAUpdater SSA(&NewPHIs);
594
595   if (!I.use_empty())
596     SSA.Initialize(I.getType(), I.getName());
597
598   // Insert a copy of the instruction in each exit block of the loop that is
599   // dominated by the instruction.  Each exit block is known to only be in the
600   // ExitBlocks list once.
601   BasicBlock *InstOrigBB = I.getParent();
602   unsigned NumInserted = 0;
603
604   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
605     BasicBlock *ExitBlock = ExitBlocks[i];
606
607     if (!DT->dominates(InstOrigBB, ExitBlock))
608       continue;
609
610     // Look for any LCSSA PHI nodes for this instruction in the exit blocks
611     // and replace them. Then get the insertion point after the last PHI.
612     BasicBlock::iterator InsertPt =
613       replaceTrivialPHIsAndGetInsertionPt(*ExitBlock, I);
614
615     // If this is the first exit block processed, just move the original
616     // instruction, otherwise clone the original instruction and insert
617     // the copy.
618     Instruction *New;
619     if (NumInserted++ == 0) {
620       I.moveBefore(InsertPt);
621       New = &I;
622     } else {
623       New = I.clone();
624       if (!I.getName().empty())
625         New->setName(I.getName()+".le");
626       ExitBlock->getInstList().insert(InsertPt, New);
627     }
628
629     // Now that we have inserted the instruction, inform SSAUpdater.
630     if (!I.use_empty())
631       SSA.AddAvailableValue(ExitBlock, New);
632   }
633
634   // If the instruction doesn't dominate any exit blocks, it must be dead.
635   if (NumInserted == 0) {
636     CurAST->deleteValue(&I);
637     if (!I.use_empty())
638       I.replaceAllUsesWith(UndefValue::get(I.getType()));
639     I.eraseFromParent();
640     return;
641   }
642
643   // Next, rewrite uses of the instruction, inserting PHI nodes as needed.
644   for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE; ) {
645     // Grab the use before incrementing the iterator.
646     Use &U = UI.getUse();
647     // Increment the iterator before removing the use from the list.
648     ++UI;
649     SSA.RewriteUseAfterInsertions(U);
650   }
651
652   // Update CurAST for NewPHIs if I had pointer type.
653   if (I.getType()->isPointerTy())
654     for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
655       CurAST->copyValue(&I, NewPHIs[i]);
656
657   // Finally, remove the instruction from CurAST.  It is no longer in the loop.
658   CurAST->deleteValue(&I);
659 }
660
661 /// hoist - When an instruction is found to only use loop invariant operands
662 /// that is safe to hoist, this instruction is called to do the dirty work.
663 ///
664 void LICM::hoist(Instruction &I) {
665   DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": "
666         << I << "\n");
667
668   // Move the new node to the Preheader, before its terminator.
669   I.moveBefore(Preheader->getTerminator());
670
671   if (isa<LoadInst>(I)) ++NumMovedLoads;
672   else if (isa<CallInst>(I)) ++NumMovedCalls;
673   ++NumHoisted;
674   Changed = true;
675 }
676
677 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
678 /// not a trapping instruction or if it is a trapping instruction and is
679 /// guaranteed to execute.
680 ///
681 bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
682   // If it is not a trapping instruction, it is always safe to hoist.
683   if (isSafeToSpeculativelyExecute(&Inst))
684     return true;
685
686   return isGuaranteedToExecute(Inst);
687 }
688
689 bool LICM::isGuaranteedToExecute(Instruction &Inst) {
690
691   // Somewhere in this loop there is an instruction which may throw and make us
692   // exit the loop.
693   if (MayThrow)
694     return false;
695
696   // Otherwise we have to check to make sure that the instruction dominates all
697   // of the exit blocks.  If it doesn't, then there is a path out of the loop
698   // which does not execute this instruction, so we can't hoist it.
699
700   // If the instruction is in the header block for the loop (which is very
701   // common), it is always guaranteed to dominate the exit blocks.  Since this
702   // is a common case, and can save some work, check it now.
703   if (Inst.getParent() == CurLoop->getHeader())
704     return true;
705
706   // Get the exit blocks for the current loop.
707   SmallVector<BasicBlock*, 8> ExitBlocks;
708   CurLoop->getExitBlocks(ExitBlocks);
709
710   // Verify that the block dominates each of the exit blocks of the loop.
711   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
712     if (!DT->dominates(Inst.getParent(), ExitBlocks[i]))
713       return false;
714
715   // As a degenerate case, if the loop is statically infinite then we haven't
716   // proven anything since there are no exit blocks.
717   if (ExitBlocks.empty())
718     return false;
719
720   return true;
721 }
722
723 namespace {
724   class LoopPromoter : public LoadAndStorePromoter {
725     Value *SomePtr;  // Designated pointer to store to.
726     SmallPtrSet<Value*, 4> &PointerMustAliases;
727     SmallVectorImpl<BasicBlock*> &LoopExitBlocks;
728     SmallVectorImpl<Instruction*> &LoopInsertPts;
729     AliasSetTracker &AST;
730     DebugLoc DL;
731     int Alignment;
732     MDNode *TBAATag;
733   public:
734     LoopPromoter(Value *SP,
735                  const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
736                  SmallPtrSet<Value*, 4> &PMA,
737                  SmallVectorImpl<BasicBlock*> &LEB,
738                  SmallVectorImpl<Instruction*> &LIP,
739                  AliasSetTracker &ast, DebugLoc dl, int alignment,
740                  MDNode *TBAATag)
741       : LoadAndStorePromoter(Insts, S), SomePtr(SP),
742         PointerMustAliases(PMA), LoopExitBlocks(LEB), LoopInsertPts(LIP),
743         AST(ast), DL(dl), Alignment(alignment), TBAATag(TBAATag) {}
744
745     virtual bool isInstInList(Instruction *I,
746                               const SmallVectorImpl<Instruction*> &) const {
747       Value *Ptr;
748       if (LoadInst *LI = dyn_cast<LoadInst>(I))
749         Ptr = LI->getOperand(0);
750       else
751         Ptr = cast<StoreInst>(I)->getPointerOperand();
752       return PointerMustAliases.count(Ptr);
753     }
754
755     virtual void doExtraRewritesBeforeFinalDeletion() const {
756       // Insert stores after in the loop exit blocks.  Each exit block gets a
757       // store of the live-out values that feed them.  Since we've already told
758       // the SSA updater about the defs in the loop and the preheader
759       // definition, it is all set and we can start using it.
760       for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
761         BasicBlock *ExitBlock = LoopExitBlocks[i];
762         Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
763         Instruction *InsertPos = LoopInsertPts[i];
764         StoreInst *NewSI = new StoreInst(LiveInValue, SomePtr, InsertPos);
765         NewSI->setAlignment(Alignment);
766         NewSI->setDebugLoc(DL);
767         if (TBAATag) NewSI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
768       }
769     }
770
771     virtual void replaceLoadWithValue(LoadInst *LI, Value *V) const {
772       // Update alias analysis.
773       AST.copyValue(LI, V);
774     }
775     virtual void instructionDeleted(Instruction *I) const {
776       AST.deleteValue(I);
777     }
778   };
779 } // end anon namespace
780
781 /// PromoteAliasSet - Try to promote memory values to scalars by sinking
782 /// stores out of the loop and moving loads to before the loop.  We do this by
783 /// looping over the stores in the loop, looking for stores to Must pointers
784 /// which are loop invariant.
785 ///
786 void LICM::PromoteAliasSet(AliasSet &AS,
787                            SmallVectorImpl<BasicBlock*> &ExitBlocks,
788                            SmallVectorImpl<Instruction*> &InsertPts) {
789   // We can promote this alias set if it has a store, if it is a "Must" alias
790   // set, if the pointer is loop invariant, and if we are not eliminating any
791   // volatile loads or stores.
792   if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
793       AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
794     return;
795
796   assert(!AS.empty() &&
797          "Must alias set should have at least one pointer element in it!");
798   Value *SomePtr = AS.begin()->getValue();
799
800   // It isn't safe to promote a load/store from the loop if the load/store is
801   // conditional.  For example, turning:
802   //
803   //    for () { if (c) *P += 1; }
804   //
805   // into:
806   //
807   //    tmp = *P;  for () { if (c) tmp +=1; } *P = tmp;
808   //
809   // is not safe, because *P may only be valid to access if 'c' is true.
810   //
811   // It is safe to promote P if all uses are direct load/stores and if at
812   // least one is guaranteed to be executed.
813   bool GuaranteedToExecute = false;
814
815   SmallVector<Instruction*, 64> LoopUses;
816   SmallPtrSet<Value*, 4> PointerMustAliases;
817
818   // We start with an alignment of one and try to find instructions that allow
819   // us to prove better alignment.
820   unsigned Alignment = 1;
821   MDNode *TBAATag = 0;
822
823   // Check that all of the pointers in the alias set have the same type.  We
824   // cannot (yet) promote a memory location that is loaded and stored in
825   // different sizes.  While we are at it, collect alignment and TBAA info.
826   for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
827     Value *ASIV = ASI->getValue();
828     PointerMustAliases.insert(ASIV);
829
830     // Check that all of the pointers in the alias set have the same type.  We
831     // cannot (yet) promote a memory location that is loaded and stored in
832     // different sizes.
833     if (SomePtr->getType() != ASIV->getType())
834       return;
835
836     for (Value::use_iterator UI = ASIV->use_begin(), UE = ASIV->use_end();
837          UI != UE; ++UI) {
838       // Ignore instructions that are outside the loop.
839       Instruction *Use = dyn_cast<Instruction>(*UI);
840       if (!Use || !CurLoop->contains(Use))
841         continue;
842
843       // If there is an non-load/store instruction in the loop, we can't promote
844       // it.
845       if (LoadInst *load = dyn_cast<LoadInst>(Use)) {
846         assert(!load->isVolatile() && "AST broken");
847         if (!load->isSimple())
848           return;
849       } else if (StoreInst *store = dyn_cast<StoreInst>(Use)) {
850         // Stores *of* the pointer are not interesting, only stores *to* the
851         // pointer.
852         if (Use->getOperand(1) != ASIV)
853           continue;
854         assert(!store->isVolatile() && "AST broken");
855         if (!store->isSimple())
856           return;
857
858         // Note that we only check GuaranteedToExecute inside the store case
859         // so that we do not introduce stores where they did not exist before
860         // (which would break the LLVM concurrency model).
861
862         // If the alignment of this instruction allows us to specify a more
863         // restrictive (and performant) alignment and if we are sure this
864         // instruction will be executed, update the alignment.
865         // Larger is better, with the exception of 0 being the best alignment.
866         unsigned InstAlignment = store->getAlignment();
867         if ((InstAlignment > Alignment || InstAlignment == 0) && Alignment != 0)
868           if (isGuaranteedToExecute(*Use)) {
869             GuaranteedToExecute = true;
870             Alignment = InstAlignment;
871           }
872
873         if (!GuaranteedToExecute)
874           GuaranteedToExecute = isGuaranteedToExecute(*Use);
875
876       } else
877         return; // Not a load or store.
878
879       // Merge the TBAA tags.
880       if (LoopUses.empty()) {
881         // On the first load/store, just take its TBAA tag.
882         TBAATag = Use->getMetadata(LLVMContext::MD_tbaa);
883       } else if (TBAATag) {
884         TBAATag = MDNode::getMostGenericTBAA(TBAATag,
885                                        Use->getMetadata(LLVMContext::MD_tbaa));
886       }
887       
888       LoopUses.push_back(Use);
889     }
890   }
891
892   // If there isn't a guaranteed-to-execute instruction, we can't promote.
893   if (!GuaranteedToExecute)
894     return;
895
896   // Otherwise, this is safe to promote, lets do it!
897   DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n');
898   Changed = true;
899   ++NumPromoted;
900
901   // Grab a debug location for the inserted loads/stores; given that the
902   // inserted loads/stores have little relation to the original loads/stores,
903   // this code just arbitrarily picks a location from one, since any debug
904   // location is better than none.
905   DebugLoc DL = LoopUses[0]->getDebugLoc();
906
907   // Figure out the loop exits and their insertion points, if this is the
908   // first promotion.
909   if (ExitBlocks.empty()) {
910     CurLoop->getUniqueExitBlocks(ExitBlocks);
911     InsertPts.resize(ExitBlocks.size());
912     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
913       InsertPts[i] = ExitBlocks[i]->getFirstInsertionPt();
914   }
915
916   // We use the SSAUpdater interface to insert phi nodes as required.
917   SmallVector<PHINode*, 16> NewPHIs;
918   SSAUpdater SSA(&NewPHIs);
919   LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
920                         InsertPts, *CurAST, DL, Alignment, TBAATag);
921
922   // Set up the preheader to have a definition of the value.  It is the live-out
923   // value from the preheader that uses in the loop will use.
924   LoadInst *PreheaderLoad =
925     new LoadInst(SomePtr, SomePtr->getName()+".promoted",
926                  Preheader->getTerminator());
927   PreheaderLoad->setAlignment(Alignment);
928   PreheaderLoad->setDebugLoc(DL);
929   if (TBAATag) PreheaderLoad->setMetadata(LLVMContext::MD_tbaa, TBAATag);
930   SSA.AddAvailableValue(Preheader, PreheaderLoad);
931
932   // Rewrite all the loads in the loop and remember all the definitions from
933   // stores in the loop.
934   Promoter.run(LoopUses);
935
936   // If the SSAUpdater didn't use the load in the preheader, just zap it now.
937   if (PreheaderLoad->use_empty())
938     PreheaderLoad->eraseFromParent();
939 }
940
941
942 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
943 void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
944   AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
945   if (!AST)
946     return;
947
948   AST->copyValue(From, To);
949 }
950
951 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
952 /// set.
953 void LICM::deleteAnalysisValue(Value *V, Loop *L) {
954   AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
955   if (!AST)
956     return;
957
958   AST->deleteValue(V);
959 }