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