An sinkable instruction may exist with uses, if those uses are in dead blocks.
[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 was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/DerivedTypes.h"
37 #include "llvm/Instructions.h"
38 #include "llvm/Target/TargetData.h"
39 #include "llvm/Analysis/LoopInfo.h"
40 #include "llvm/Analysis/AliasAnalysis.h"
41 #include "llvm/Analysis/AliasSetTracker.h"
42 #include "llvm/Analysis/Dominators.h"
43 #include "llvm/Support/CFG.h"
44 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/ADT/Statistic.h"
49 #include <algorithm>
50 #include <iostream>
51 using namespace llvm;
52
53 namespace {
54   cl::opt<bool>
55   DisablePromotion("disable-licm-promotion", cl::Hidden,
56                    cl::desc("Disable memory promotion in LICM pass"));
57
58   Statistic<> NumSunk("licm", "Number of instructions sunk out of loop");
59   Statistic<> NumHoisted("licm", "Number of instructions hoisted out of loop");
60   Statistic<> NumMovedLoads("licm", "Number of load insts hoisted or sunk");
61   Statistic<> NumMovedCalls("licm", "Number of call insts hoisted or sunk");
62   Statistic<> NumPromoted("licm",
63                           "Number of memory locations promoted to registers");
64
65   struct LICM : public FunctionPass {
66     virtual bool runOnFunction(Function &F);
67
68     /// This transformation requires natural loop information & requires that
69     /// loop preheaders be inserted into the CFG...
70     ///
71     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
72       AU.setPreservesCFG();
73       AU.addRequiredID(LoopSimplifyID);
74       AU.addRequired<LoopInfo>();
75       AU.addRequired<DominatorTree>();
76       AU.addRequired<DominanceFrontier>();  // For scalar promotion (mem2reg)
77       AU.addRequired<AliasAnalysis>();
78     }
79
80   private:
81     // Various analyses that we use...
82     AliasAnalysis *AA;       // Current AliasAnalysis information
83     LoopInfo      *LI;       // Current LoopInfo
84     DominatorTree *DT;       // Dominator Tree for the current Loop...
85     DominanceFrontier *DF;   // Current Dominance Frontier
86
87     // State that is updated as we process loops
88     bool Changed;            // Set to true when we change anything.
89     BasicBlock *Preheader;   // The preheader block of the current loop...
90     Loop *CurLoop;           // The current loop we are working on...
91     AliasSetTracker *CurAST; // AliasSet information for the current loop...
92
93     /// visitLoop - Hoist expressions out of the specified loop...
94     ///
95     void visitLoop(Loop *L, AliasSetTracker &AST);
96
97     /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
98     /// dominated by the specified block, and that are in the current loop) in
99     /// reverse depth first order w.r.t the DominatorTree.  This allows us to
100     /// visit uses before definitions, allowing us to sink a loop body in one
101     /// pass without iteration.
102     ///
103     void SinkRegion(DominatorTree::Node *N);
104
105     /// HoistRegion - Walk the specified region of the CFG (defined by all
106     /// blocks dominated by the specified block, and that are in the current
107     /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
108     /// visit definitions before uses, allowing us to hoist a loop body in one
109     /// pass without iteration.
110     ///
111     void HoistRegion(DominatorTree::Node *N);
112
113     /// inSubLoop - Little predicate that returns true if the specified basic
114     /// block is in a subloop of the current one, not the current one itself.
115     ///
116     bool inSubLoop(BasicBlock *BB) {
117       assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
118       for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
119         if ((*I)->contains(BB))
120           return true;  // A subloop actually contains this block!
121       return false;
122     }
123
124     /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
125     /// specified exit block of the loop is dominated by the specified block
126     /// that is in the body of the loop.  We use these constraints to
127     /// dramatically limit the amount of the dominator tree that needs to be
128     /// searched.
129     bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
130                                            BasicBlock *BlockInLoop) const {
131       // If the block in the loop is the loop header, it must be dominated!
132       BasicBlock *LoopHeader = CurLoop->getHeader();
133       if (BlockInLoop == LoopHeader)
134         return true;
135
136       DominatorTree::Node *BlockInLoopNode = DT->getNode(BlockInLoop);
137       DominatorTree::Node *IDom            = DT->getNode(ExitBlock);
138
139       // Because the exit block is not in the loop, we know we have to get _at
140       // least_ its immediate dominator.
141       do {
142         // Get next Immediate Dominator.
143         IDom = IDom->getIDom();
144
145         // If we have got to the header of the loop, then the instructions block
146         // did not dominate the exit node, so we can't hoist it.
147         if (IDom->getBlock() == LoopHeader)
148           return false;
149
150       } while (IDom != BlockInLoopNode);
151
152       return true;
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     /// pointerInvalidatedByLoop - Return true if the body of this loop may
173     /// store into the memory location pointed to by V.
174     ///
175     bool pointerInvalidatedByLoop(Value *V, unsigned Size) {
176       // Check to see if any of the basic blocks in CurLoop invalidate *V.
177       return CurAST->getAliasSetForPointer(V, Size).isMod();
178     }
179
180     bool canSinkOrHoistInst(Instruction &I);
181     bool isLoopInvariantInst(Instruction &I);
182     bool isNotUsedInLoop(Instruction &I);
183
184     /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
185     /// to scalars as we can.
186     ///
187     void PromoteValuesInLoop();
188
189     /// FindPromotableValuesInLoop - Check the current loop for stores to
190     /// definite pointers, which are not loaded and stored through may aliases.
191     /// If these are found, create an alloca for the value, add it to the
192     /// PromotedValues list, and keep track of the mapping from value to
193     /// alloca...
194     ///
195     void FindPromotableValuesInLoop(
196                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
197                                     std::map<Value*, AllocaInst*> &Val2AlMap);
198   };
199
200   RegisterPass<LICM> X("licm", "Loop Invariant Code Motion");
201 }
202
203 FunctionPass *llvm::createLICMPass() { return new LICM(); }
204
205 /// runOnFunction - For LICM, this simply traverses the loop structure of the
206 /// function, hoisting expressions out of loops if possible.
207 ///
208 bool LICM::runOnFunction(Function &) {
209   Changed = false;
210
211   // Get our Loop and Alias Analysis information...
212   LI = &getAnalysis<LoopInfo>();
213   AA = &getAnalysis<AliasAnalysis>();
214   DF = &getAnalysis<DominanceFrontier>();
215   DT = &getAnalysis<DominatorTree>();
216
217   // Hoist expressions out of all of the top-level loops.
218   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
219     AliasSetTracker AST(*AA);
220     visitLoop(*I, AST);
221   }
222   return Changed;
223 }
224
225
226 /// visitLoop - Hoist expressions out of the specified loop...
227 ///
228 void LICM::visitLoop(Loop *L, AliasSetTracker &AST) {
229   // Recurse through all subloops before we process this loop...
230   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
231     AliasSetTracker SubAST(*AA);
232     visitLoop(*I, SubAST);
233
234     // Incorporate information about the subloops into this loop...
235     AST.add(SubAST);
236   }
237   CurLoop = L;
238   CurAST = &AST;
239
240   // Get the preheader block to move instructions into...
241   Preheader = L->getLoopPreheader();
242   assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
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 (std::vector<BasicBlock*>::const_iterator I = L->getBlocks().begin(),
249          E = L->getBlocks().end(); I != E; ++I)
250     if (LI->getLoopFor(*I) == L)        // Ignore blocks in subloops...
251       AST.add(**I);                     // Incorporate the specified basic block
252
253   // We want to visit all of the instructions in this loop... that are not parts
254   // of our subloops (they have already had their invariants hoisted out of
255   // their loop, into this loop, so there is no need to process the BODIES of
256   // the subloops).
257   //
258   // Traverse the body of the loop in depth first order on the dominator tree so
259   // that we are guaranteed to see definitions before we see uses.  This allows
260   // us to sink instructions in one pass, without iteration.  AFter sinking
261   // instructions, we perform another pass to hoist them out of the loop.
262   //
263   SinkRegion(DT->getNode(L->getHeader()));
264   HoistRegion(DT->getNode(L->getHeader()));
265
266   // Now that all loop invariants have been removed from the loop, promote any
267   // memory references to scalars that we can...
268   if (!DisablePromotion)
269     PromoteValuesInLoop();
270
271   // Clear out loops state information for the next iteration
272   CurLoop = 0;
273   Preheader = 0;
274 }
275
276 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
277 /// dominated by the specified block, and that are in the current loop) in
278 /// reverse depth first order w.r.t the DominatorTree.  This allows us to visit
279 /// uses before definitions, allowing us to sink a loop body in one pass without
280 /// iteration.
281 ///
282 void LICM::SinkRegion(DominatorTree::Node *N) {
283   assert(N != 0 && "Null dominator tree node?");
284   BasicBlock *BB = N->getBlock();
285
286   // If this subregion is not in the top level loop at all, exit.
287   if (!CurLoop->contains(BB)) return;
288
289   // We are processing blocks in reverse dfo, so process children first...
290   const std::vector<DominatorTree::Node*> &Children = N->getChildren();
291   for (unsigned i = 0, e = Children.size(); i != e; ++i)
292     SinkRegion(Children[i]);
293
294   // Only need to process the contents of this block if it is not part of a
295   // subloop (which would already have been processed).
296   if (inSubLoop(BB)) return;
297
298   for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
299     Instruction &I = *--II;
300
301     // Check to see if we can sink this instruction to the exit blocks
302     // of the loop.  We can do this if the all users of the instruction are
303     // outside of the loop.  In this case, it doesn't even matter if the
304     // operands of the instruction are loop invariant.
305     //
306     if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
307       ++II;
308       sink(I);
309     }
310   }
311 }
312
313
314 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
315 /// dominated by the specified block, and that are in the current loop) in depth
316 /// first order w.r.t the DominatorTree.  This allows us to visit definitions
317 /// before uses, allowing us to hoist a loop body in one pass without iteration.
318 ///
319 void LICM::HoistRegion(DominatorTree::Node *N) {
320   assert(N != 0 && "Null dominator tree node?");
321   BasicBlock *BB = N->getBlock();
322
323   // If this subregion is not in the top level loop at all, exit.
324   if (!CurLoop->contains(BB)) return;
325
326   // Only need to process the contents of this block if it is not part of a
327   // subloop (which would already have been processed).
328   if (!inSubLoop(BB))
329     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
330       Instruction &I = *II++;
331
332       // Try hoisting the instruction out to the preheader.  We can only do this
333       // if all of the operands of the instruction are loop invariant and if it
334       // is safe to hoist the instruction.
335       //
336       if (isLoopInvariantInst(I) && canSinkOrHoistInst(I) &&
337           isSafeToExecuteUnconditionally(I))
338         hoist(I);
339       }
340
341   const std::vector<DominatorTree::Node*> &Children = N->getChildren();
342   for (unsigned i = 0, e = Children.size(); i != e; ++i)
343     HoistRegion(Children[i]);
344 }
345
346 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
347 /// instruction.
348 ///
349 bool LICM::canSinkOrHoistInst(Instruction &I) {
350   // Loads have extra constraints we have to verify before we can hoist them.
351   if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
352     if (LI->isVolatile())
353       return false;        // Don't hoist volatile loads!
354
355     // Don't hoist loads which have may-aliased stores in loop.
356     unsigned Size = 0;
357     if (LI->getType()->isSized())
358       Size = AA->getTargetData().getTypeSize(LI->getType());
359     return !pointerInvalidatedByLoop(LI->getOperand(0), Size);
360   } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
361     // Handle obvious cases efficiently.
362     if (Function *Callee = CI->getCalledFunction()) {
363       AliasAnalysis::ModRefBehavior Behavior =AA->getModRefBehavior(Callee, CI);
364       if (Behavior == AliasAnalysis::DoesNotAccessMemory)
365         return true;
366       else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
367         // If this call only reads from memory and there are no writes to memory
368         // in the loop, we can hoist or sink the call as appropriate.
369         bool FoundMod = false;
370         for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
371              I != E; ++I) {
372           AliasSet &AS = *I;
373           if (!AS.isForwardingAliasSet() && AS.isMod()) {
374             FoundMod = true;
375             break;
376           }
377         }
378         if (!FoundMod) return true;
379       }
380     }
381
382     // FIXME: This should use mod/ref information to see if we can hoist or sink
383     // the call.
384
385     return false;
386   }
387
388   return isa<BinaryOperator>(I) || isa<ShiftInst>(I) || isa<CastInst>(I) ||
389          isa<SelectInst>(I) || isa<GetElementPtrInst>(I);
390 }
391
392 /// isNotUsedInLoop - Return true if the only users of this instruction are
393 /// outside of the loop.  If this is true, we can sink the instruction to the
394 /// exit blocks of the loop.
395 ///
396 bool LICM::isNotUsedInLoop(Instruction &I) {
397   for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
398     Instruction *User = cast<Instruction>(*UI);
399     if (PHINode *PN = dyn_cast<PHINode>(User)) {
400       // PHI node uses occur in predecessor blocks!
401       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
402         if (PN->getIncomingValue(i) == &I)
403           if (CurLoop->contains(PN->getIncomingBlock(i)))
404             return false;
405     } else if (CurLoop->contains(User->getParent())) {
406       return false;
407     }
408   }
409   return true;
410 }
411
412
413 /// isLoopInvariantInst - Return true if all operands of this instruction are
414 /// loop invariant.  We also filter out non-hoistable instructions here just for
415 /// efficiency.
416 ///
417 bool LICM::isLoopInvariantInst(Instruction &I) {
418   // The instruction is loop invariant if all of its operands are loop-invariant
419   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
420     if (!CurLoop->isLoopInvariant(I.getOperand(i)))
421       return false;
422
423   // If we got this far, the instruction is loop invariant!
424   return true;
425 }
426
427 /// sink - When an instruction is found to only be used outside of the loop,
428 /// this function moves it to the exit blocks and patches up SSA form as needed.
429 /// This method is guaranteed to remove the original instruction from its
430 /// position, and may either delete it or move it to outside of the loop.
431 ///
432 void LICM::sink(Instruction &I) {
433   DEBUG(std::cerr << "LICM sinking instruction: " << I);
434
435   std::vector<BasicBlock*> ExitBlocks;
436   CurLoop->getExitBlocks(ExitBlocks);
437
438   if (isa<LoadInst>(I)) ++NumMovedLoads;
439   else if (isa<CallInst>(I)) ++NumMovedCalls;
440   ++NumSunk;
441   Changed = true;
442
443   // The case where there is only a single exit node of this loop is common
444   // enough that we handle it as a special (more efficient) case.  It is more
445   // efficient to handle because there are no PHI nodes that need to be placed.
446   if (ExitBlocks.size() == 1) {
447     if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
448       // Instruction is not used, just delete it.
449       CurAST->deleteValue(&I);
450       if (!I.use_empty())  // If I has users in unreachable blocks, eliminate.
451         I.replaceAllUsesWith(UndefValue::get(I.getType()));
452       I.eraseFromParent();
453     } else {
454       // Move the instruction to the start of the exit block, after any PHI
455       // nodes in it.
456       I.removeFromParent();
457
458       BasicBlock::iterator InsertPt = ExitBlocks[0]->begin();
459       while (isa<PHINode>(InsertPt)) ++InsertPt;
460       ExitBlocks[0]->getInstList().insert(InsertPt, &I);
461     }
462   } else if (ExitBlocks.size() == 0) {
463     // The instruction is actually dead if there ARE NO exit blocks.
464     CurAST->deleteValue(&I);
465     if (!I.use_empty())  // If I has users in unreachable blocks, eliminate.
466       I.replaceAllUsesWith(UndefValue::get(I.getType()));
467     I.eraseFromParent();
468   } else {
469     // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
470     // do all of the hard work of inserting PHI nodes as necessary.  We convert
471     // the value into a stack object to get it to do this.
472
473     // Firstly, we create a stack object to hold the value...
474     AllocaInst *AI = 0;
475
476     if (I.getType() != Type::VoidTy)
477       AI = new AllocaInst(I.getType(), 0, I.getName(),
478                           I.getParent()->getParent()->front().begin());
479
480     // Secondly, insert load instructions for each use of the instruction
481     // outside of the loop.
482     while (!I.use_empty()) {
483       Instruction *U = cast<Instruction>(I.use_back());
484
485       // If the user is a PHI Node, we actually have to insert load instructions
486       // in all predecessor blocks, not in the PHI block itself!
487       if (PHINode *UPN = dyn_cast<PHINode>(U)) {
488         // Only insert into each predecessor once, so that we don't have
489         // different incoming values from the same block!
490         std::map<BasicBlock*, Value*> InsertedBlocks;
491         for (unsigned i = 0, e = UPN->getNumIncomingValues(); i != e; ++i)
492           if (UPN->getIncomingValue(i) == &I) {
493             BasicBlock *Pred = UPN->getIncomingBlock(i);
494             Value *&PredVal = InsertedBlocks[Pred];
495             if (!PredVal) {
496               // Insert a new load instruction right before the terminator in
497               // the predecessor block.
498               PredVal = new LoadInst(AI, "", Pred->getTerminator());
499             }
500
501             UPN->setIncomingValue(i, PredVal);
502           }
503
504       } else {
505         LoadInst *L = new LoadInst(AI, "", U);
506         U->replaceUsesOfWith(&I, L);
507       }
508     }
509
510     // Thirdly, insert a copy of the instruction in each exit block of the loop
511     // that is dominated by the instruction, storing the result into the memory
512     // location.  Be careful not to insert the instruction into any particular
513     // basic block more than once.
514     std::set<BasicBlock*> InsertedBlocks;
515     BasicBlock *InstOrigBB = I.getParent();
516
517     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
518       BasicBlock *ExitBlock = ExitBlocks[i];
519
520       if (isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB)) {
521         // If we haven't already processed this exit block, do so now.
522         if (InsertedBlocks.insert(ExitBlock).second) {
523           // Insert the code after the last PHI node...
524           BasicBlock::iterator InsertPt = ExitBlock->begin();
525           while (isa<PHINode>(InsertPt)) ++InsertPt;
526
527           // If this is the first exit block processed, just move the original
528           // instruction, otherwise clone the original instruction and insert
529           // the copy.
530           Instruction *New;
531           if (InsertedBlocks.size() == 1) {
532             I.removeFromParent();
533             ExitBlock->getInstList().insert(InsertPt, &I);
534             New = &I;
535           } else {
536             New = I.clone();
537             CurAST->copyValue(&I, New);
538             if (!I.getName().empty())
539               New->setName(I.getName()+".le");
540             ExitBlock->getInstList().insert(InsertPt, New);
541           }
542
543           // Now that we have inserted the instruction, store it into the alloca
544           if (AI) new StoreInst(New, AI, InsertPt);
545         }
546       }
547     }
548
549     // If the instruction doesn't dominate any exit blocks, it must be dead.
550     if (InsertedBlocks.empty()) {
551       CurAST->deleteValue(&I);
552       I.eraseFromParent();
553     }
554
555     // Finally, promote the fine value to SSA form.
556     if (AI) {
557       std::vector<AllocaInst*> Allocas;
558       Allocas.push_back(AI);
559       PromoteMemToReg(Allocas, *DT, *DF, AA->getTargetData(), CurAST);
560     }
561   }
562 }
563
564 /// hoist - When an instruction is found to only use loop invariant operands
565 /// that is safe to hoist, this instruction is called to do the dirty work.
566 ///
567 void LICM::hoist(Instruction &I) {
568   DEBUG(std::cerr << "LICM hoisting to " << Preheader->getName()
569                   << ": " << I);
570
571   // Remove the instruction from its current basic block... but don't delete the
572   // instruction.
573   I.removeFromParent();
574
575   // Insert the new node in Preheader, before the terminator.
576   Preheader->getInstList().insert(Preheader->getTerminator(), &I);
577
578   if (isa<LoadInst>(I)) ++NumMovedLoads;
579   else if (isa<CallInst>(I)) ++NumMovedCalls;
580   ++NumHoisted;
581   Changed = true;
582 }
583
584 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
585 /// not a trapping instruction or if it is a trapping instruction and is
586 /// guaranteed to execute.
587 ///
588 bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
589   // If it is not a trapping instruction, it is always safe to hoist.
590   if (!Inst.isTrapping()) return true;
591
592   // Otherwise we have to check to make sure that the instruction dominates all
593   // of the exit blocks.  If it doesn't, then there is a path out of the loop
594   // which does not execute this instruction, so we can't hoist it.
595
596   // If the instruction is in the header block for the loop (which is very
597   // common), it is always guaranteed to dominate the exit blocks.  Since this
598   // is a common case, and can save some work, check it now.
599   if (Inst.getParent() == CurLoop->getHeader())
600     return true;
601
602   // It's always safe to load from a global or alloca.
603   if (isa<LoadInst>(Inst))
604     if (isa<AllocationInst>(Inst.getOperand(0)) ||
605         isa<GlobalVariable>(Inst.getOperand(0)))
606       return true;
607
608   // Get the exit blocks for the current loop.
609   std::vector<BasicBlock*> ExitBlocks;
610   CurLoop->getExitBlocks(ExitBlocks);
611
612   // For each exit block, get the DT node and walk up the DT until the
613   // instruction's basic block is found or we exit the loop.
614   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
615     if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
616       return false;
617
618   return true;
619 }
620
621
622 /// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
623 /// stores out of the loop and moving loads to before the loop.  We do this by
624 /// looping over the stores in the loop, looking for stores to Must pointers
625 /// which are loop invariant.  We promote these memory locations to use allocas
626 /// instead.  These allocas can easily be raised to register values by the
627 /// PromoteMem2Reg functionality.
628 ///
629 void LICM::PromoteValuesInLoop() {
630   // PromotedValues - List of values that are promoted out of the loop.  Each
631   // value has an alloca instruction for it, and a canonical version of the
632   // pointer.
633   std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
634   std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
635
636   FindPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
637   if (ValueToAllocaMap.empty()) return;   // If there are values to promote.
638
639   Changed = true;
640   NumPromoted += PromotedValues.size();
641
642   std::vector<Value*> PointerValueNumbers;
643
644   // Emit a copy from the value into the alloca'd value in the loop preheader
645   TerminatorInst *LoopPredInst = Preheader->getTerminator();
646   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
647     Value *Ptr = PromotedValues[i].second;
648
649     // If we are promoting a pointer value, update alias information for the
650     // inserted load.
651     Value *LoadValue = 0;
652     if (isa<PointerType>(cast<PointerType>(Ptr->getType())->getElementType())) {
653       // Locate a load or store through the pointer, and assign the same value
654       // to LI as we are loading or storing.  Since we know that the value is
655       // stored in this loop, this will always succeed.
656       for (Value::use_iterator UI = Ptr->use_begin(), E = Ptr->use_end();
657            UI != E; ++UI)
658         if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
659           LoadValue = LI;
660           break;
661         } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
662           if (SI->getOperand(1) == Ptr) {
663             LoadValue = SI->getOperand(0);
664             break;
665           }
666         }
667       assert(LoadValue && "No store through the pointer found!");
668       PointerValueNumbers.push_back(LoadValue);  // Remember this for later.
669     }
670
671     // Load from the memory we are promoting.
672     LoadInst *LI = new LoadInst(Ptr, Ptr->getName()+".promoted", LoopPredInst);
673
674     if (LoadValue) CurAST->copyValue(LoadValue, LI);
675
676     // Store into the temporary alloca.
677     new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
678   }
679
680   // Scan the basic blocks in the loop, replacing uses of our pointers with
681   // uses of the allocas in question.
682   //
683   const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
684   for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
685          E = LoopBBs.end(); I != E; ++I) {
686     // Rewrite all loads and stores in the block of the pointer...
687     for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
688          II != E; ++II) {
689       if (LoadInst *L = dyn_cast<LoadInst>(II)) {
690         std::map<Value*, AllocaInst*>::iterator
691           I = ValueToAllocaMap.find(L->getOperand(0));
692         if (I != ValueToAllocaMap.end())
693           L->setOperand(0, I->second);    // Rewrite load instruction...
694       } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
695         std::map<Value*, AllocaInst*>::iterator
696           I = ValueToAllocaMap.find(S->getOperand(1));
697         if (I != ValueToAllocaMap.end())
698           S->setOperand(1, I->second);    // Rewrite store instruction...
699       }
700     }
701   }
702
703   // Now that the body of the loop uses the allocas instead of the original
704   // memory locations, insert code to copy the alloca value back into the
705   // original memory location on all exits from the loop.  Note that we only
706   // want to insert one copy of the code in each exit block, though the loop may
707   // exit to the same block more than once.
708   //
709   std::set<BasicBlock*> ProcessedBlocks;
710
711   std::vector<BasicBlock*> ExitBlocks;
712   CurLoop->getExitBlocks(ExitBlocks);
713   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
714     if (ProcessedBlocks.insert(ExitBlocks[i]).second) {
715       // Copy all of the allocas into their memory locations.
716       BasicBlock::iterator BI = ExitBlocks[i]->begin();
717       while (isa<PHINode>(*BI))
718         ++BI;             // Skip over all of the phi nodes in the block.
719       Instruction *InsertPos = BI;
720       unsigned PVN = 0;
721       for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
722         // Load from the alloca.
723         LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
724
725         // If this is a pointer type, update alias info appropriately.
726         if (isa<PointerType>(LI->getType()))
727           CurAST->copyValue(PointerValueNumbers[PVN++], LI);
728
729         // Store into the memory we promoted.
730         new StoreInst(LI, PromotedValues[i].second, InsertPos);
731       }
732     }
733
734   // Now that we have done the deed, use the mem2reg functionality to promote
735   // all of the new allocas we just created into real SSA registers.
736   //
737   std::vector<AllocaInst*> PromotedAllocas;
738   PromotedAllocas.reserve(PromotedValues.size());
739   for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
740     PromotedAllocas.push_back(PromotedValues[i].first);
741   PromoteMemToReg(PromotedAllocas, *DT, *DF, AA->getTargetData(), CurAST);
742 }
743
744 /// FindPromotableValuesInLoop - Check the current loop for stores to definite
745 /// pointers, which are not loaded and stored through may aliases.  If these are
746 /// found, create an alloca for the value, add it to the PromotedValues list,
747 /// and keep track of the mapping from value to alloca.
748 ///
749 void LICM::FindPromotableValuesInLoop(
750                    std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
751                              std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
752   Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
753
754   // Loop over all of the alias sets in the tracker object.
755   for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
756        I != E; ++I) {
757     AliasSet &AS = *I;
758     // We can promote this alias set if it has a store, if it is a "Must" alias
759     // set, if the pointer is loop invariant, and if we are not eliminating any
760     // volatile loads or stores.
761     if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias() &&
762         !AS.isVolatile() && CurLoop->isLoopInvariant(AS.begin()->first)) {
763       assert(AS.begin() != AS.end() &&
764              "Must alias set should have at least one pointer element in it!");
765       Value *V = AS.begin()->first;
766
767       // Check that all of the pointers in the alias set have the same type.  We
768       // cannot (yet) promote a memory location that is loaded and stored in
769       // different sizes.
770       bool PointerOk = true;
771       for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
772         if (V->getType() != I->first->getType()) {
773           PointerOk = false;
774           break;
775         }
776
777       if (PointerOk) {
778         const Type *Ty = cast<PointerType>(V->getType())->getElementType();
779         AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
780         PromotedValues.push_back(std::make_pair(AI, V));
781
782         // Update the AST and alias analysis.
783         CurAST->copyValue(V, AI);
784
785         for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
786           ValueToAllocaMap.insert(std::make_pair(I->first, AI));
787
788         DEBUG(std::cerr << "LICM: Promoting value: " << *V << "\n");
789       }
790     }
791   }
792 }