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