Update various Loop optimization passes to cope with the possibility that
[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 mem2reg functionality to construct the appropriate SSA form for the
30 //     variable.
31 //
32 //===----------------------------------------------------------------------===//
33
34 #define DEBUG_TYPE "licm"
35 #include "llvm/Transforms/Scalar.h"
36 #include "llvm/Constants.h"
37 #include "llvm/DerivedTypes.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Instructions.h"
40 #include "llvm/Target/TargetData.h"
41 #include "llvm/Analysis/LoopInfo.h"
42 #include "llvm/Analysis/LoopPass.h"
43 #include "llvm/Analysis/AliasAnalysis.h"
44 #include "llvm/Analysis/AliasSetTracker.h"
45 #include "llvm/Analysis/Dominators.h"
46 #include "llvm/Analysis/ScalarEvolution.h"
47 #include "llvm/Transforms/Utils/PromoteMemToReg.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 // This feature is currently disabled by default because CodeGen is not yet
67 // capable of rematerializing these constants in PIC mode, so it can lead to
68 // degraded performance. Compile test/CodeGen/X86/remat-constant.ll with
69 // -relocation-model=pic to see an example of this.
70 static cl::opt<bool>
71 EnableLICMConstantMotion("enable-licm-constant-variables", cl::Hidden,
72                          cl::desc("Enable hoisting/sinking of constant "
73                                   "global variables"));
74
75 namespace {
76   struct LICM : public LoopPass {
77     static char ID; // Pass identification, replacement for typeid
78     LICM() : LoopPass(&ID) {}
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.addRequiredID(LoopSimplifyID);
88       AU.addRequired<LoopInfo>();
89       AU.addRequired<DominatorTree>();
90       AU.addRequired<DominanceFrontier>();  // For scalar promotion (mem2reg)
91       AU.addRequired<AliasAnalysis>();
92       AU.addPreserved<ScalarEvolution>();
93       AU.addPreserved<DominanceFrontier>();
94       AU.addPreservedID(LoopSimplifyID);
95     }
96
97     bool doFinalization() {
98       // Free the values stored in the map
99       for (std::map<Loop *, AliasSetTracker *>::iterator
100              I = LoopToAliasMap.begin(), E = LoopToAliasMap.end(); I != E; ++I)
101         delete I->second;
102
103       LoopToAliasMap.clear();
104       return false;
105     }
106
107   private:
108     // Various analyses that we use...
109     AliasAnalysis *AA;       // Current AliasAnalysis information
110     LoopInfo      *LI;       // Current LoopInfo
111     DominatorTree *DT;       // Dominator Tree for the current Loop...
112     DominanceFrontier *DF;   // Current Dominance Frontier
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     std::map<Loop *, AliasSetTracker *> LoopToAliasMap;
120
121     /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
122     void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L);
123
124     /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
125     /// set.
126     void deleteAnalysisValue(Value *V, Loop *L);
127
128     /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
129     /// dominated by the specified block, and that are in the current loop) in
130     /// reverse depth first order w.r.t the DominatorTree.  This allows us to
131     /// visit uses before definitions, allowing us to sink a loop body in one
132     /// pass without iteration.
133     ///
134     void SinkRegion(DomTreeNode *N);
135
136     /// HoistRegion - Walk the specified region of the CFG (defined by all
137     /// blocks dominated by the specified block, and that are in the current
138     /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
139     /// visit definitions before uses, allowing us to hoist a loop body in one
140     /// pass without iteration.
141     ///
142     void HoistRegion(DomTreeNode *N);
143
144     /// inSubLoop - Little predicate that returns true if the specified basic
145     /// block is in a subloop of the current one, not the current one itself.
146     ///
147     bool inSubLoop(BasicBlock *BB) {
148       assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
149       for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
150         if ((*I)->contains(BB))
151           return true;  // A subloop actually contains this block!
152       return false;
153     }
154
155     /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
156     /// specified exit block of the loop is dominated by the specified block
157     /// that is in the body of the loop.  We use these constraints to
158     /// dramatically limit the amount of the dominator tree that needs to be
159     /// searched.
160     bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
161                                            BasicBlock *BlockInLoop) const {
162       // If the block in the loop is the loop header, it must be dominated!
163       BasicBlock *LoopHeader = CurLoop->getHeader();
164       if (BlockInLoop == LoopHeader)
165         return true;
166
167       DomTreeNode *BlockInLoopNode = DT->getNode(BlockInLoop);
168       DomTreeNode *IDom            = DT->getNode(ExitBlock);
169
170       // Because the exit block is not in the loop, we know we have to get _at
171       // least_ its immediate dominator.
172       do {
173         // Get next Immediate Dominator.
174         IDom = IDom->getIDom();
175
176         // If we have got to the header of the loop, then the instructions block
177         // did not dominate the exit node, so we can't hoist it.
178         if (IDom->getBlock() == LoopHeader)
179           return false;
180
181       } while (IDom != BlockInLoopNode);
182
183       return true;
184     }
185
186     /// sink - When an instruction is found to only be used outside of the loop,
187     /// this function moves it to the exit blocks and patches up SSA form as
188     /// needed.
189     ///
190     void sink(Instruction &I);
191
192     /// hoist - When an instruction is found to only use loop invariant operands
193     /// that is safe to hoist, this instruction is called to do the dirty work.
194     ///
195     void hoist(Instruction &I);
196
197     /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
198     /// is not a trapping instruction or if it is a trapping instruction and is
199     /// guaranteed to execute.
200     ///
201     bool isSafeToExecuteUnconditionally(Instruction &I);
202
203     /// pointerInvalidatedByLoop - Return true if the body of this loop may
204     /// store into the memory location pointed to by V.
205     ///
206     bool pointerInvalidatedByLoop(Value *V, unsigned Size) {
207       // Check to see if any of the basic blocks in CurLoop invalidate *V.
208       return CurAST->getAliasSetForPointer(V, Size).isMod();
209     }
210
211     bool canSinkOrHoistInst(Instruction &I);
212     bool isLoopInvariantInst(Instruction &I);
213     bool isNotUsedInLoop(Instruction &I);
214
215     /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
216     /// to scalars as we can.
217     ///
218     void PromoteValuesInLoop();
219
220     /// FindPromotableValuesInLoop - Check the current loop for stores to
221     /// definite pointers, which are not loaded and stored through may aliases.
222     /// If these are found, create an alloca for the value, add it to the
223     /// PromotedValues list, and keep track of the mapping from value to
224     /// alloca...
225     ///
226     void FindPromotableValuesInLoop(
227                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
228                                     std::map<Value*, AllocaInst*> &Val2AlMap);
229   };
230 }
231
232 char LICM::ID = 0;
233 static RegisterPass<LICM> X("licm", "Loop Invariant Code Motion");
234
235 Pass *llvm::createLICMPass() { return new LICM(); }
236
237 /// Hoist expressions out of the specified loop. Note, alias info for inner
238 /// loop is not preserved so it is not a good idea to run LICM multiple 
239 /// times on one loop.
240 ///
241 bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
242   Changed = false;
243
244   // Get our Loop and Alias Analysis information...
245   LI = &getAnalysis<LoopInfo>();
246   AA = &getAnalysis<AliasAnalysis>();
247   DF = &getAnalysis<DominanceFrontier>();
248   DT = &getAnalysis<DominatorTree>();
249
250   CurAST = new AliasSetTracker(*AA);
251   // Collect Alias info from subloops
252   for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
253        LoopItr != LoopItrE; ++LoopItr) {
254     Loop *InnerL = *LoopItr;
255     AliasSetTracker *InnerAST = LoopToAliasMap[InnerL];
256     assert (InnerAST && "Where is my AST?");
257
258     // What if InnerLoop was modified by other passes ?
259     CurAST->add(*InnerAST);
260   }
261   
262   CurLoop = L;
263
264   // Get the preheader block to move instructions into...
265   Preheader = L->getLoopPreheader();
266
267   // Loop over the body of this loop, looking for calls, invokes, and stores.
268   // Because subloops have already been incorporated into AST, we skip blocks in
269   // subloops.
270   //
271   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
272        I != E; ++I) {
273     BasicBlock *BB = *I;
274     if (LI->getLoopFor(BB) == L)        // Ignore blocks in subloops...
275       CurAST->add(*BB);                 // Incorporate the specified basic block
276   }
277
278   // We want to visit all of the instructions in this loop... that are not parts
279   // of our subloops (they have already had their invariants hoisted out of
280   // their loop, into this loop, so there is no need to process the BODIES of
281   // the subloops).
282   //
283   // Traverse the body of the loop in depth first order on the dominator tree so
284   // that we are guaranteed to see definitions before we see uses.  This allows
285   // us to sink instructions in one pass, without iteration.  After sinking
286   // instructions, we perform another pass to hoist them out of the loop.
287   //
288   if (L->hasDedicatedExits())
289     SinkRegion(DT->getNode(L->getHeader()));
290   if (Preheader)
291     HoistRegion(DT->getNode(L->getHeader()));
292
293   // Now that all loop invariants have been removed from the loop, promote any
294   // memory references to scalars that we can...
295   if (!DisablePromotion && Preheader && L->hasDedicatedExits())
296     PromoteValuesInLoop();
297
298   // Clear out loops state information for the next iteration
299   CurLoop = 0;
300   Preheader = 0;
301
302   LoopToAliasMap[L] = CurAST;
303   return Changed;
304 }
305
306 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
307 /// dominated by the specified block, and that are in the current loop) in
308 /// reverse depth first order w.r.t the DominatorTree.  This allows us to visit
309 /// uses before definitions, allowing us to sink a loop body in one pass without
310 /// iteration.
311 ///
312 void LICM::SinkRegion(DomTreeNode *N) {
313   assert(N != 0 && "Null dominator tree node?");
314   BasicBlock *BB = N->getBlock();
315
316   // If this subregion is not in the top level loop at all, exit.
317   if (!CurLoop->contains(BB)) return;
318
319   // We are processing blocks in reverse dfo, so process children first...
320   const std::vector<DomTreeNode*> &Children = N->getChildren();
321   for (unsigned i = 0, e = Children.size(); i != e; ++i)
322     SinkRegion(Children[i]);
323
324   // Only need to process the contents of this block if it is not part of a
325   // subloop (which would already have been processed).
326   if (inSubLoop(BB)) return;
327
328   for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
329     Instruction &I = *--II;
330
331     // Check to see if we can sink this instruction to the exit blocks
332     // of the loop.  We can do this if the all users of the instruction are
333     // outside of the loop.  In this case, it doesn't even matter if the
334     // operands of the instruction are loop invariant.
335     //
336     if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
337       ++II;
338       sink(I);
339     }
340   }
341 }
342
343 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
344 /// dominated by the specified block, and that are in the current loop) in depth
345 /// first order w.r.t the DominatorTree.  This allows us to visit definitions
346 /// before uses, allowing us to hoist a loop body in one pass without iteration.
347 ///
348 void LICM::HoistRegion(DomTreeNode *N) {
349   assert(N != 0 && "Null dominator tree node?");
350   BasicBlock *BB = N->getBlock();
351
352   // If this subregion is not in the top level loop at all, exit.
353   if (!CurLoop->contains(BB)) return;
354
355   // Only need to process the contents of this block if it is not part of a
356   // subloop (which would already have been processed).
357   if (!inSubLoop(BB))
358     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
359       Instruction &I = *II++;
360
361       // Try hoisting the instruction out to the preheader.  We can only do this
362       // if all of the operands of the instruction are loop invariant and if it
363       // is safe to hoist the instruction.
364       //
365       if (isLoopInvariantInst(I) && canSinkOrHoistInst(I) &&
366           isSafeToExecuteUnconditionally(I))
367         hoist(I);
368       }
369
370   const std::vector<DomTreeNode*> &Children = N->getChildren();
371   for (unsigned i = 0, e = Children.size(); i != e; ++i)
372     HoistRegion(Children[i]);
373 }
374
375 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
376 /// instruction.
377 ///
378 bool LICM::canSinkOrHoistInst(Instruction &I) {
379   // Loads have extra constraints we have to verify before we can hoist them.
380   if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
381     if (LI->isVolatile())
382       return false;        // Don't hoist volatile loads!
383
384     // Loads from constant memory are always safe to move, even if they end up
385     // in the same alias set as something that ends up being modified.
386     if (EnableLICMConstantMotion &&
387         AA->pointsToConstantMemory(LI->getOperand(0)))
388       return true;
389     
390     // Don't hoist loads which have may-aliased stores in loop.
391     unsigned Size = 0;
392     if (LI->getType()->isSized())
393       Size = AA->getTypeStoreSize(LI->getType());
394     return !pointerInvalidatedByLoop(LI->getOperand(0), Size);
395   } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
396     if (isa<DbgStopPointInst>(CI)) {
397       // Don't hoist/sink dbgstoppoints, we handle them separately
398       return false;
399     }
400     // Handle obvious cases efficiently.
401     AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
402     if (Behavior == AliasAnalysis::DoesNotAccessMemory)
403       return true;
404     else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
405       // If this call only reads from memory and there are no writes to memory
406       // in the loop, we can hoist or sink the call as appropriate.
407       bool FoundMod = false;
408       for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
409            I != E; ++I) {
410         AliasSet &AS = *I;
411         if (!AS.isForwardingAliasSet() && AS.isMod()) {
412           FoundMod = true;
413           break;
414         }
415       }
416       if (!FoundMod) return true;
417     }
418
419     // FIXME: This should use mod/ref information to see if we can hoist or sink
420     // the call.
421
422     return false;
423   }
424
425   // Otherwise these instructions are hoistable/sinkable
426   return isa<BinaryOperator>(I) || isa<CastInst>(I) ||
427          isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||
428          isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
429          isa<ShuffleVectorInst>(I);
430 }
431
432 /// isNotUsedInLoop - Return true if the only users of this instruction are
433 /// outside of the loop.  If this is true, we can sink the instruction to the
434 /// exit blocks of the loop.
435 ///
436 bool LICM::isNotUsedInLoop(Instruction &I) {
437   for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
438     Instruction *User = cast<Instruction>(*UI);
439     if (PHINode *PN = dyn_cast<PHINode>(User)) {
440       // PHI node uses occur in predecessor blocks!
441       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
442         if (PN->getIncomingValue(i) == &I)
443           if (CurLoop->contains(PN->getIncomingBlock(i)))
444             return false;
445     } else if (CurLoop->contains(User->getParent())) {
446       return false;
447     }
448   }
449   return true;
450 }
451
452
453 /// isLoopInvariantInst - Return true if all operands of this instruction are
454 /// loop invariant.  We also filter out non-hoistable instructions here just for
455 /// efficiency.
456 ///
457 bool LICM::isLoopInvariantInst(Instruction &I) {
458   // The instruction is loop invariant if all of its operands are loop-invariant
459   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
460     if (!CurLoop->isLoopInvariant(I.getOperand(i)))
461       return false;
462
463   // If we got this far, the instruction is loop invariant!
464   return true;
465 }
466
467 /// sink - When an instruction is found to only be used outside of the loop,
468 /// this function moves it to the exit blocks and patches up SSA form as needed.
469 /// This method is guaranteed to remove the original instruction from its
470 /// position, and may either delete it or move it to outside of the loop.
471 ///
472 void LICM::sink(Instruction &I) {
473   DEBUG(errs() << "LICM sinking instruction: " << I);
474
475   SmallVector<BasicBlock*, 8> ExitBlocks;
476   CurLoop->getExitBlocks(ExitBlocks);
477
478   if (isa<LoadInst>(I)) ++NumMovedLoads;
479   else if (isa<CallInst>(I)) ++NumMovedCalls;
480   ++NumSunk;
481   Changed = true;
482
483   // The case where there is only a single exit node of this loop is common
484   // enough that we handle it as a special (more efficient) case.  It is more
485   // efficient to handle because there are no PHI nodes that need to be placed.
486   if (ExitBlocks.size() == 1) {
487     if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
488       // Instruction is not used, just delete it.
489       CurAST->deleteValue(&I);
490       // If I has users in unreachable blocks, eliminate.
491       // If I is not void type then replaceAllUsesWith undef.
492       // This allows ValueHandlers and custom metadata to adjust itself.
493       if (!I.getType()->isVoidTy())
494         I.replaceAllUsesWith(UndefValue::get(I.getType()));
495       I.eraseFromParent();
496     } else {
497       // Move the instruction to the start of the exit block, after any PHI
498       // nodes in it.
499       I.removeFromParent();
500       BasicBlock::iterator InsertPt = ExitBlocks[0]->getFirstNonPHI();
501       ExitBlocks[0]->getInstList().insert(InsertPt, &I);
502     }
503   } else if (ExitBlocks.empty()) {
504     // The instruction is actually dead if there ARE NO exit blocks.
505     CurAST->deleteValue(&I);
506     // If I has users in unreachable blocks, eliminate.
507     // If I is not void type then replaceAllUsesWith undef.
508     // This allows ValueHandlers and custom metadata to adjust itself.
509     if (!I.getType()->isVoidTy())
510       I.replaceAllUsesWith(UndefValue::get(I.getType()));
511     I.eraseFromParent();
512   } else {
513     // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
514     // do all of the hard work of inserting PHI nodes as necessary.  We convert
515     // the value into a stack object to get it to do this.
516
517     // Firstly, we create a stack object to hold the value...
518     AllocaInst *AI = 0;
519
520     if (!I.getType()->isVoidTy()) {
521       AI = new AllocaInst(I.getType(), 0, I.getName(),
522                           I.getParent()->getParent()->getEntryBlock().begin());
523       CurAST->add(AI);
524     }
525
526     // Secondly, insert load instructions for each use of the instruction
527     // outside of the loop.
528     while (!I.use_empty()) {
529       Instruction *U = cast<Instruction>(I.use_back());
530
531       // If the user is a PHI Node, we actually have to insert load instructions
532       // in all predecessor blocks, not in the PHI block itself!
533       if (PHINode *UPN = dyn_cast<PHINode>(U)) {
534         // Only insert into each predecessor once, so that we don't have
535         // different incoming values from the same block!
536         std::map<BasicBlock*, Value*> InsertedBlocks;
537         for (unsigned i = 0, e = UPN->getNumIncomingValues(); i != e; ++i)
538           if (UPN->getIncomingValue(i) == &I) {
539             BasicBlock *Pred = UPN->getIncomingBlock(i);
540             Value *&PredVal = InsertedBlocks[Pred];
541             if (!PredVal) {
542               // Insert a new load instruction right before the terminator in
543               // the predecessor block.
544               PredVal = new LoadInst(AI, "", Pred->getTerminator());
545               CurAST->add(cast<LoadInst>(PredVal));
546             }
547
548             UPN->setIncomingValue(i, PredVal);
549           }
550
551       } else {
552         LoadInst *L = new LoadInst(AI, "", U);
553         U->replaceUsesOfWith(&I, L);
554         CurAST->add(L);
555       }
556     }
557
558     // Thirdly, insert a copy of the instruction in each exit block of the loop
559     // that is dominated by the instruction, storing the result into the memory
560     // location.  Be careful not to insert the instruction into any particular
561     // basic block more than once.
562     std::set<BasicBlock*> InsertedBlocks;
563     BasicBlock *InstOrigBB = I.getParent();
564
565     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
566       BasicBlock *ExitBlock = ExitBlocks[i];
567
568       if (isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB)) {
569         // If we haven't already processed this exit block, do so now.
570         if (InsertedBlocks.insert(ExitBlock).second) {
571           // Insert the code after the last PHI node...
572           BasicBlock::iterator InsertPt = ExitBlock->getFirstNonPHI();
573
574           // If this is the first exit block processed, just move the original
575           // instruction, otherwise clone the original instruction and insert
576           // the copy.
577           Instruction *New;
578           if (InsertedBlocks.size() == 1) {
579             I.removeFromParent();
580             ExitBlock->getInstList().insert(InsertPt, &I);
581             New = &I;
582           } else {
583             New = I.clone();
584             CurAST->copyValue(&I, New);
585             if (!I.getName().empty())
586               New->setName(I.getName()+".le");
587             ExitBlock->getInstList().insert(InsertPt, New);
588           }
589
590           // Now that we have inserted the instruction, store it into the alloca
591           if (AI) new StoreInst(New, AI, InsertPt);
592         }
593       }
594     }
595
596     // If the instruction doesn't dominate any exit blocks, it must be dead.
597     if (InsertedBlocks.empty()) {
598       CurAST->deleteValue(&I);
599       I.eraseFromParent();
600     }
601
602     // Finally, promote the fine value to SSA form.
603     if (AI) {
604       std::vector<AllocaInst*> Allocas;
605       Allocas.push_back(AI);
606       PromoteMemToReg(Allocas, *DT, *DF, AI->getContext(), CurAST);
607     }
608   }
609 }
610
611 /// hoist - When an instruction is found to only use loop invariant operands
612 /// that is safe to hoist, this instruction is called to do the dirty work.
613 ///
614 void LICM::hoist(Instruction &I) {
615   DEBUG(errs() << "LICM hoisting to " << Preheader->getName() << ": "
616         << I << "\n");
617
618   // Remove the instruction from its current basic block... but don't delete the
619   // instruction.
620   I.removeFromParent();
621
622   // Insert the new node in Preheader, before the terminator.
623   Preheader->getInstList().insert(Preheader->getTerminator(), &I);
624
625   if (isa<LoadInst>(I)) ++NumMovedLoads;
626   else if (isa<CallInst>(I)) ++NumMovedCalls;
627   ++NumHoisted;
628   Changed = true;
629 }
630
631 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
632 /// not a trapping instruction or if it is a trapping instruction and is
633 /// guaranteed to execute.
634 ///
635 bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
636   // If it is not a trapping instruction, it is always safe to hoist.
637   if (Inst.isSafeToSpeculativelyExecute())
638     return true;
639
640   // Otherwise we have to check to make sure that the instruction dominates all
641   // of the exit blocks.  If it doesn't, then there is a path out of the loop
642   // which does not execute this instruction, so we can't hoist it.
643
644   // If the instruction is in the header block for the loop (which is very
645   // common), it is always guaranteed to dominate the exit blocks.  Since this
646   // is a common case, and can save some work, check it now.
647   if (Inst.getParent() == CurLoop->getHeader())
648     return true;
649
650   // Get the exit blocks for the current loop.
651   SmallVector<BasicBlock*, 8> ExitBlocks;
652   CurLoop->getExitBlocks(ExitBlocks);
653
654   // For each exit block, get the DT node and walk up the DT until the
655   // instruction's basic block is found or we exit the loop.
656   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
657     if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
658       return false;
659
660   return true;
661 }
662
663
664 /// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
665 /// stores out of the loop and moving loads to before the loop.  We do this by
666 /// looping over the stores in the loop, looking for stores to Must pointers
667 /// which are loop invariant.  We promote these memory locations to use allocas
668 /// instead.  These allocas can easily be raised to register values by the
669 /// PromoteMem2Reg functionality.
670 ///
671 void LICM::PromoteValuesInLoop() {
672   // PromotedValues - List of values that are promoted out of the loop.  Each
673   // value has an alloca instruction for it, and a canonical version of the
674   // pointer.
675   std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
676   std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
677
678   FindPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
679   if (ValueToAllocaMap.empty()) return;   // If there are values to promote.
680
681   Changed = true;
682   NumPromoted += PromotedValues.size();
683
684   std::vector<Value*> PointerValueNumbers;
685
686   // Emit a copy from the value into the alloca'd value in the loop preheader
687   TerminatorInst *LoopPredInst = Preheader->getTerminator();
688   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
689     Value *Ptr = PromotedValues[i].second;
690
691     // If we are promoting a pointer value, update alias information for the
692     // inserted load.
693     Value *LoadValue = 0;
694     if (isa<PointerType>(cast<PointerType>(Ptr->getType())->getElementType())) {
695       // Locate a load or store through the pointer, and assign the same value
696       // to LI as we are loading or storing.  Since we know that the value is
697       // stored in this loop, this will always succeed.
698       for (Value::use_iterator UI = Ptr->use_begin(), E = Ptr->use_end();
699            UI != E; ++UI)
700         if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
701           LoadValue = LI;
702           break;
703         } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
704           if (SI->getOperand(1) == Ptr) {
705             LoadValue = SI->getOperand(0);
706             break;
707           }
708         }
709       assert(LoadValue && "No store through the pointer found!");
710       PointerValueNumbers.push_back(LoadValue);  // Remember this for later.
711     }
712
713     // Load from the memory we are promoting.
714     LoadInst *LI = new LoadInst(Ptr, Ptr->getName()+".promoted", LoopPredInst);
715
716     if (LoadValue) CurAST->copyValue(LoadValue, LI);
717
718     // Store into the temporary alloca.
719     new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
720   }
721
722   // Scan the basic blocks in the loop, replacing uses of our pointers with
723   // uses of the allocas in question.
724   //
725   for (Loop::block_iterator I = CurLoop->block_begin(),
726          E = CurLoop->block_end(); I != E; ++I) {
727     BasicBlock *BB = *I;
728     // Rewrite all loads and stores in the block of the pointer...
729     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
730       if (LoadInst *L = dyn_cast<LoadInst>(II)) {
731         std::map<Value*, AllocaInst*>::iterator
732           I = ValueToAllocaMap.find(L->getOperand(0));
733         if (I != ValueToAllocaMap.end())
734           L->setOperand(0, I->second);    // Rewrite load instruction...
735       } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
736         std::map<Value*, AllocaInst*>::iterator
737           I = ValueToAllocaMap.find(S->getOperand(1));
738         if (I != ValueToAllocaMap.end())
739           S->setOperand(1, I->second);    // Rewrite store instruction...
740       }
741     }
742   }
743
744   // Now that the body of the loop uses the allocas instead of the original
745   // memory locations, insert code to copy the alloca value back into the
746   // original memory location on all exits from the loop.  Note that we only
747   // want to insert one copy of the code in each exit block, though the loop may
748   // exit to the same block more than once.
749   //
750   SmallPtrSet<BasicBlock*, 16> ProcessedBlocks;
751
752   SmallVector<BasicBlock*, 8> ExitBlocks;
753   CurLoop->getExitBlocks(ExitBlocks);
754   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
755     if (!ProcessedBlocks.insert(ExitBlocks[i]))
756       continue;
757   
758     // Copy all of the allocas into their memory locations.
759     BasicBlock::iterator BI = ExitBlocks[i]->getFirstNonPHI();
760     Instruction *InsertPos = BI;
761     unsigned PVN = 0;
762     for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
763       // Load from the alloca.
764       LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
765
766       // If this is a pointer type, update alias info appropriately.
767       if (isa<PointerType>(LI->getType()))
768         CurAST->copyValue(PointerValueNumbers[PVN++], LI);
769
770       // Store into the memory we promoted.
771       new StoreInst(LI, PromotedValues[i].second, InsertPos);
772     }
773   }
774
775   // Now that we have done the deed, use the mem2reg functionality to promote
776   // all of the new allocas we just created into real SSA registers.
777   //
778   std::vector<AllocaInst*> PromotedAllocas;
779   PromotedAllocas.reserve(PromotedValues.size());
780   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
781     PromotedAllocas.push_back(PromotedValues[i].first);
782   PromoteMemToReg(PromotedAllocas, *DT, *DF, Preheader->getContext(), CurAST);
783 }
784
785 /// FindPromotableValuesInLoop - Check the current loop for stores to definite
786 /// pointers, which are not loaded and stored through may aliases and are safe
787 /// for promotion.  If these are found, create an alloca for the value, add it 
788 /// to the PromotedValues list, and keep track of the mapping from value to 
789 /// alloca. 
790 void LICM::FindPromotableValuesInLoop(
791                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
792                              std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
793   Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
794
795   // Loop over all of the alias sets in the tracker object.
796   for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
797        I != E; ++I) {
798     AliasSet &AS = *I;
799     // We can promote this alias set if it has a store, if it is a "Must" alias
800     // set, if the pointer is loop invariant, and if we are not eliminating any
801     // volatile loads or stores.
802     if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
803         AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
804       continue;
805     
806     assert(!AS.empty() &&
807            "Must alias set should have at least one pointer element in it!");
808     Value *V = AS.begin()->getValue();
809
810     // Check that all of the pointers in the alias set have the same type.  We
811     // cannot (yet) promote a memory location that is loaded and stored in
812     // different sizes.
813     {
814       bool PointerOk = true;
815       for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
816         if (V->getType() != I->getValue()->getType()) {
817           PointerOk = false;
818           break;
819         }
820       if (!PointerOk)
821         continue;
822     }
823
824     // It isn't safe to promote a load/store from the loop if the load/store is
825     // conditional.  For example, turning:
826     //
827     //    for () { if (c) *P += 1; }
828     //
829     // into:
830     //
831     //    tmp = *P;  for () { if (c) tmp +=1; } *P = tmp;
832     //
833     // is not safe, because *P may only be valid to access if 'c' is true.
834     // 
835     // It is safe to promote P if all uses are direct load/stores and if at
836     // least one is guaranteed to be executed.
837     bool GuaranteedToExecute = false;
838     bool InvalidInst = false;
839     for (Value::use_iterator UI = V->use_begin(), UE = V->use_end();
840          UI != UE; ++UI) {
841       // Ignore instructions not in this loop.
842       Instruction *Use = dyn_cast<Instruction>(*UI);
843       if (!Use || !CurLoop->contains(Use->getParent()))
844         continue;
845
846       if (!isa<LoadInst>(Use) && !isa<StoreInst>(Use)) {
847         InvalidInst = true;
848         break;
849       }
850       
851       if (!GuaranteedToExecute)
852         GuaranteedToExecute = isSafeToExecuteUnconditionally(*Use);
853     }
854
855     // If there is an non-load/store instruction in the loop, we can't promote
856     // it.  If there isn't a guaranteed-to-execute instruction, we can't
857     // promote.
858     if (InvalidInst || !GuaranteedToExecute)
859       continue;
860     
861     const Type *Ty = cast<PointerType>(V->getType())->getElementType();
862     AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
863     PromotedValues.push_back(std::make_pair(AI, V));
864
865     // Update the AST and alias analysis.
866     CurAST->copyValue(V, AI);
867
868     for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
869       ValueToAllocaMap.insert(std::make_pair(I->getValue(), AI));
870
871     DEBUG(errs() << "LICM: Promoting value: " << *V << "\n");
872   }
873 }
874
875 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
876 void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
877   AliasSetTracker *AST = LoopToAliasMap[L];
878   if (!AST)
879     return;
880
881   AST->copyValue(From, To);
882 }
883
884 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
885 /// set.
886 void LICM::deleteAnalysisValue(Value *V, Loop *L) {
887   AliasSetTracker *AST = LoopToAliasMap[L];
888   if (!AST)
889     return;
890
891   AST->deleteValue(V);
892 }