blob: 3eee4a27f7d6eda3bd1ebbd58563454c08b2df5f [file] [log] [blame]
Chris Lattner6ec05f52002-05-10 22:44:58 +00001//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner6ec05f52002-05-10 22:44:58 +00009//
Chris Lattnerc0517682003-12-09 17:18:00 +000010// 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
Chris Lattner547192d62003-12-19 07:22:45 +000014// live in registers, thus hoisting and sinking "invariant" loads and stores.
Chris Lattnerc0517682003-12-09 17:18:00 +000015//
16// This pass uses alias analysis for two purposes:
Chris Lattner45d67d62003-02-24 03:52:32 +000017//
Chris Lattner289ba2a2004-05-23 21:20:19 +000018// 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.
Chris Lattner45d67d62003-02-24 03:52:32 +000021// 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.
Chris Lattner6ec05f52002-05-10 22:44:58 +000031//
Chris Lattner6ec05f52002-05-10 22:44:58 +000032//===----------------------------------------------------------------------===//
33
Chris Lattner1c790bf2005-03-23 21:00:12 +000034#define DEBUG_TYPE "licm"
Chris Lattner6ec05f52002-05-10 22:44:58 +000035#include "llvm/Transforms/Scalar.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000036#include "llvm/Constants.h"
Chris Lattner289ba2a2004-05-23 21:20:19 +000037#include "llvm/DerivedTypes.h"
38#include "llvm/Instructions.h"
39#include "llvm/Target/TargetData.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000040#include "llvm/Analysis/LoopInfo.h"
Devang Patel69730c92007-03-07 04:41:30 +000041#include "llvm/Analysis/LoopPass.h"
Chris Lattnera51fa882002-08-22 21:39:55 +000042#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner0592bb72003-03-03 23:32:45 +000043#include "llvm/Analysis/AliasSetTracker.h"
Chris Lattner64437692002-09-29 21:46:09 +000044#include "llvm/Analysis/Dominators.h"
Devang Patelbb97ac42007-07-30 20:19:59 +000045#include "llvm/Analysis/ScalarEvolution.h"
Chris Lattner289ba2a2004-05-23 21:20:19 +000046#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Reid Spencer557ab152007-02-05 23:32:05 +000047#include "llvm/Support/CFG.h"
48#include "llvm/Support/Compiler.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000049#include "llvm/Support/CommandLine.h"
50#include "llvm/Support/Debug.h"
51#include "llvm/ADT/Statistic.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000052#include <algorithm>
Chris Lattnerc0517682003-12-09 17:18:00 +000053using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000054
Chris Lattner79a42ac2006-12-19 21:40:18 +000055STATISTIC(NumSunk , "Number of instructions sunk out of loop");
56STATISTIC(NumHoisted , "Number of instructions hoisted out of loop");
57STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
58STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
59STATISTIC(NumPromoted , "Number of memory locations promoted to registers");
60
Dan Gohmand78c4002008-05-13 00:00:25 +000061static cl::opt<bool>
62DisablePromotion("disable-licm-promotion", cl::Hidden,
63 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner45d67d62003-02-24 03:52:32 +000064
Dan Gohman5f36a322008-07-24 23:57:25 +000065// This feature is currently disabled by default because CodeGen is not yet capable
66// of rematerializing these constants in PIC mode, so it can lead to degraded
67// performance. Compile test/CodeGen/X86/remat-constant.ll with
68// -relocation-model=pic to see an example of this.
69static cl::opt<bool>
70EnableLICMConstantMotion("enable-licm-constant-variables", cl::Hidden,
71 cl::desc("Enable hoisting/sinking of constant "
72 "global variables"));
73
Dan Gohmand78c4002008-05-13 00:00:25 +000074namespace {
Devang Patel69730c92007-03-07 04:41:30 +000075 struct VISIBILITY_HIDDEN LICM : public LoopPass {
Nick Lewyckye7da2d62007-05-06 13:37:16 +000076 static char ID; // Pass identification, replacement for typeid
Dan Gohmana79db302008-09-04 17:05:41 +000077 LICM() : LoopPass(&ID) {}
Devang Patel09f162c2007-05-01 21:15:47 +000078
Devang Patel69730c92007-03-07 04:41:30 +000079 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattner6ec05f52002-05-10 22:44:58 +000080
Chris Lattnerf64f2d32002-09-26 16:52:07 +000081 /// This transformation requires natural loop information & requires that
82 /// loop preheaders be inserted into the CFG...
83 ///
Chris Lattner6ec05f52002-05-10 22:44:58 +000084 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +000085 AU.setPreservesCFG();
Chris Lattner72272a72003-10-12 21:52:28 +000086 AU.addRequiredID(LoopSimplifyID);
Chris Lattnerf0ed55d2002-08-08 19:01:30 +000087 AU.addRequired<LoopInfo>();
Owen Andersonc24701e2007-04-24 06:40:39 +000088 AU.addRequired<DominatorTree>();
Chris Lattner0592bb72003-03-03 23:32:45 +000089 AU.addRequired<DominanceFrontier>(); // For scalar promotion (mem2reg)
Chris Lattnera51fa882002-08-22 21:39:55 +000090 AU.addRequired<AliasAnalysis>();
Devang Patelbb97ac42007-07-30 20:19:59 +000091 AU.addPreserved<ScalarEvolution>();
92 AU.addPreserved<DominanceFrontier>();
Chris Lattner6ec05f52002-05-10 22:44:58 +000093 }
94
Dan Gohman2ce11162007-04-17 18:21:36 +000095 bool doFinalization() {
Anton Korobeynikov2f76e372007-11-25 23:52:02 +000096 // Free the values stored in the map
97 for (std::map<Loop *, AliasSetTracker *>::iterator
98 I = LoopToAliasMap.begin(), E = LoopToAliasMap.end(); I != E; ++I)
99 delete I->second;
100
Devang Patel69730c92007-03-07 04:41:30 +0000101 LoopToAliasMap.clear();
102 return false;
103 }
104
Chris Lattner6ec05f52002-05-10 22:44:58 +0000105 private:
Chris Lattnerc0517682003-12-09 17:18:00 +0000106 // Various analyses that we use...
Chris Lattner45d67d62003-02-24 03:52:32 +0000107 AliasAnalysis *AA; // Current AliasAnalysis information
Chris Lattnerc0517682003-12-09 17:18:00 +0000108 LoopInfo *LI; // Current LoopInfo
Owen Andersonc24701e2007-04-24 06:40:39 +0000109 DominatorTree *DT; // Dominator Tree for the current Loop...
Chris Lattnera906bac2003-10-05 21:20:13 +0000110 DominanceFrontier *DF; // Current Dominance Frontier
Chris Lattnerc0517682003-12-09 17:18:00 +0000111
112 // State that is updated as we process loops
Chris Lattner45d67d62003-02-24 03:52:32 +0000113 bool Changed; // Set to true when we change anything.
114 BasicBlock *Preheader; // The preheader block of the current loop...
115 Loop *CurLoop; // The current loop we are working on...
Chris Lattner0592bb72003-03-03 23:32:45 +0000116 AliasSetTracker *CurAST; // AliasSet information for the current loop...
Devang Patel69730c92007-03-07 04:41:30 +0000117 std::map<Loop *, AliasSetTracker *> LoopToAliasMap;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000118
Devang Patelb98a0972007-07-31 08:01:41 +0000119 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
120 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L);
121
122 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
123 /// set.
124 void deleteAnalysisValue(Value *V, Loop *L);
125
Chris Lattner547192d62003-12-19 07:22:45 +0000126 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
127 /// dominated by the specified block, and that are in the current loop) in
Owen Andersonc24701e2007-04-24 06:40:39 +0000128 /// reverse depth first order w.r.t the DominatorTree. This allows us to
Chris Lattner547192d62003-12-19 07:22:45 +0000129 /// visit uses before definitions, allowing us to sink a loop body in one
130 /// pass without iteration.
131 ///
Devang Patelbdd1aae2007-06-04 00:32:22 +0000132 void SinkRegion(DomTreeNode *N);
Chris Lattner547192d62003-12-19 07:22:45 +0000133
Chris Lattner64437692002-09-29 21:46:09 +0000134 /// HoistRegion - Walk the specified region of the CFG (defined by all
135 /// blocks dominated by the specified block, and that are in the current
Owen Andersonc24701e2007-04-24 06:40:39 +0000136 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000137 /// visit definitions before uses, allowing us to hoist a loop body in one
Chris Lattner64437692002-09-29 21:46:09 +0000138 /// pass without iteration.
139 ///
Devang Patelbdd1aae2007-06-04 00:32:22 +0000140 void HoistRegion(DomTreeNode *N);
Chris Lattner64437692002-09-29 21:46:09 +0000141
Chris Lattner05e86302002-09-29 22:26:07 +0000142 /// inSubLoop - Little predicate that returns true if the specified basic
143 /// block is in a subloop of the current one, not the current one itself.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000144 ///
Chris Lattner05e86302002-09-29 22:26:07 +0000145 bool inSubLoop(BasicBlock *BB) {
146 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000147 for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
148 if ((*I)->contains(BB))
Chris Lattner05e86302002-09-29 22:26:07 +0000149 return true; // A subloop actually contains this block!
150 return false;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000151 }
152
Chris Lattneraaaea512003-12-10 06:41:05 +0000153 /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
154 /// specified exit block of the loop is dominated by the specified block
155 /// that is in the body of the loop. We use these constraints to
156 /// dramatically limit the amount of the dominator tree that needs to be
157 /// searched.
158 bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
159 BasicBlock *BlockInLoop) const {
160 // If the block in the loop is the loop header, it must be dominated!
161 BasicBlock *LoopHeader = CurLoop->getHeader();
162 if (BlockInLoop == LoopHeader)
163 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000164
Devang Patelbdd1aae2007-06-04 00:32:22 +0000165 DomTreeNode *BlockInLoopNode = DT->getNode(BlockInLoop);
166 DomTreeNode *IDom = DT->getNode(ExitBlock);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000167
Chris Lattneraaaea512003-12-10 06:41:05 +0000168 // Because the exit block is not in the loop, we know we have to get _at
Chris Lattner289ba2a2004-05-23 21:20:19 +0000169 // least_ its immediate dominator.
Chris Lattneraaaea512003-12-10 06:41:05 +0000170 do {
171 // Get next Immediate Dominator.
Owen Andersonc24701e2007-04-24 06:40:39 +0000172 IDom = IDom->getIDom();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000173
Chris Lattneraaaea512003-12-10 06:41:05 +0000174 // If we have got to the header of the loop, then the instructions block
175 // did not dominate the exit node, so we can't hoist it.
Owen Andersonc24701e2007-04-24 06:40:39 +0000176 if (IDom->getBlock() == LoopHeader)
Chris Lattneraaaea512003-12-10 06:41:05 +0000177 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000178
Owen Andersonc24701e2007-04-24 06:40:39 +0000179 } while (IDom != BlockInLoopNode);
Chris Lattneraaaea512003-12-10 06:41:05 +0000180
181 return true;
182 }
183
184 /// sink - When an instruction is found to only be used outside of the loop,
185 /// this function moves it to the exit blocks and patches up SSA form as
186 /// needed.
187 ///
188 void sink(Instruction &I);
189
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000190 /// hoist - When an instruction is found to only use loop invariant operands
191 /// that is safe to hoist, this instruction is called to do the dirty work.
192 ///
Chris Lattner113f4f42002-06-25 16:13:24 +0000193 void hoist(Instruction &I);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000194
Chris Lattneraaaea512003-12-10 06:41:05 +0000195 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
196 /// is not a trapping instruction or if it is a trapping instruction and is
197 /// guaranteed to execute.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000198 ///
Chris Lattneraaaea512003-12-10 06:41:05 +0000199 bool isSafeToExecuteUnconditionally(Instruction &I);
Tanya Lattner57c03df2003-08-05 18:45:46 +0000200
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000201 /// pointerInvalidatedByLoop - Return true if the body of this loop may
202 /// store into the memory location pointed to by V.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000203 ///
Chris Lattnerb1374092004-11-26 21:20:09 +0000204 bool pointerInvalidatedByLoop(Value *V, unsigned Size) {
Chris Lattner0592bb72003-03-03 23:32:45 +0000205 // Check to see if any of the basic blocks in CurLoop invalidate *V.
Chris Lattnerb1374092004-11-26 21:20:09 +0000206 return CurAST->getAliasSetForPointer(V, Size).isMod();
Chris Lattner45d67d62003-02-24 03:52:32 +0000207 }
Chris Lattnera51fa882002-08-22 21:39:55 +0000208
Chris Lattneraaaea512003-12-10 06:41:05 +0000209 bool canSinkOrHoistInst(Instruction &I);
210 bool isLoopInvariantInst(Instruction &I);
211 bool isNotUsedInLoop(Instruction &I);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000212
Chris Lattner45d67d62003-02-24 03:52:32 +0000213 /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
214 /// to scalars as we can.
215 ///
216 void PromoteValuesInLoop();
217
Chris Lattnera3465782004-09-15 01:04:07 +0000218 /// FindPromotableValuesInLoop - Check the current loop for stores to
Misha Brukman9b8d3392003-09-11 15:32:37 +0000219 /// definite pointers, which are not loaded and stored through may aliases.
Chris Lattner45d67d62003-02-24 03:52:32 +0000220 /// If these are found, create an alloca for the value, add it to the
221 /// PromotedValues list, and keep track of the mapping from value to
222 /// alloca...
223 ///
Chris Lattnera3465782004-09-15 01:04:07 +0000224 void FindPromotableValuesInLoop(
Chris Lattner45d67d62003-02-24 03:52:32 +0000225 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
226 std::map<Value*, AllocaInst*> &Val2AlMap);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000227 };
228}
229
Dan Gohmand78c4002008-05-13 00:00:25 +0000230char LICM::ID = 0;
231static RegisterPass<LICM> X("licm", "Loop Invariant Code Motion");
232
Devang Patel69730c92007-03-07 04:41:30 +0000233LoopPass *llvm::createLICMPass() { return new LICM(); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000234
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000235/// Hoist expressions out of the specified loop. Note, alias info for inner
236/// loop is not preserved so it is not a good idea to run LICM multiple
237/// times on one loop.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000238///
Devang Patel69730c92007-03-07 04:41:30 +0000239bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner45d67d62003-02-24 03:52:32 +0000240 Changed = false;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000241
Chris Lattner45d67d62003-02-24 03:52:32 +0000242 // Get our Loop and Alias Analysis information...
243 LI = &getAnalysis<LoopInfo>();
Chris Lattnera51fa882002-08-22 21:39:55 +0000244 AA = &getAnalysis<AliasAnalysis>();
Chris Lattnera906bac2003-10-05 21:20:13 +0000245 DF = &getAnalysis<DominanceFrontier>();
Owen Andersonc24701e2007-04-24 06:40:39 +0000246 DT = &getAnalysis<DominatorTree>();
Chris Lattnera51fa882002-08-22 21:39:55 +0000247
Devang Patel69730c92007-03-07 04:41:30 +0000248 CurAST = new AliasSetTracker(*AA);
Devang Patel9b3b35d2007-05-30 15:29:37 +0000249 // Collect Alias info from subloops
Devang Patel69730c92007-03-07 04:41:30 +0000250 for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
251 LoopItr != LoopItrE; ++LoopItr) {
252 Loop *InnerL = *LoopItr;
253 AliasSetTracker *InnerAST = LoopToAliasMap[InnerL];
254 assert (InnerAST && "Where is my AST?");
255
256 // What if InnerLoop was modified by other passes ?
257 CurAST->add(*InnerAST);
Chris Lattner45d67d62003-02-24 03:52:32 +0000258 }
Devang Patel69730c92007-03-07 04:41:30 +0000259
Chris Lattner6ec05f52002-05-10 22:44:58 +0000260 CurLoop = L;
261
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000262 // Get the preheader block to move instructions into...
263 Preheader = L->getLoopPreheader();
264 assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
265
Chris Lattner45d67d62003-02-24 03:52:32 +0000266 // Loop over the body of this loop, looking for calls, invokes, and stores.
Chris Lattner0592bb72003-03-03 23:32:45 +0000267 // Because subloops have already been incorporated into AST, we skip blocks in
Chris Lattner45d67d62003-02-24 03:52:32 +0000268 // subloops.
269 //
Dan Gohman90071072008-06-22 20:18:58 +0000270 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
271 I != E; ++I) {
272 BasicBlock *BB = *I;
273 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops...
274 CurAST->add(*BB); // Incorporate the specified basic block
275 }
Chris Lattner45d67d62003-02-24 03:52:32 +0000276
Chris Lattner6ec05f52002-05-10 22:44:58 +0000277 // We want to visit all of the instructions in this loop... that are not parts
278 // of our subloops (they have already had their invariants hoisted out of
279 // their loop, into this loop, so there is no need to process the BODIES of
280 // the subloops).
281 //
Chris Lattner64437692002-09-29 21:46:09 +0000282 // Traverse the body of the loop in depth first order on the dominator tree so
283 // that we are guaranteed to see definitions before we see uses. This allows
Nick Lewyckya0d49da2007-08-18 15:08:56 +0000284 // us to sink instructions in one pass, without iteration. After sinking
Chris Lattner547192d62003-12-19 07:22:45 +0000285 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner64437692002-09-29 21:46:09 +0000286 //
Owen Andersonc24701e2007-04-24 06:40:39 +0000287 SinkRegion(DT->getNode(L->getHeader()));
288 HoistRegion(DT->getNode(L->getHeader()));
Chris Lattner6ec05f52002-05-10 22:44:58 +0000289
Chris Lattner45d67d62003-02-24 03:52:32 +0000290 // Now that all loop invariants have been removed from the loop, promote any
291 // memory references to scalars that we can...
292 if (!DisablePromotion)
293 PromoteValuesInLoop();
294
Chris Lattner6ec05f52002-05-10 22:44:58 +0000295 // Clear out loops state information for the next iteration
296 CurLoop = 0;
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000297 Preheader = 0;
Devang Patel69730c92007-03-07 04:41:30 +0000298
299 LoopToAliasMap[L] = CurAST;
300 return Changed;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000301}
302
Chris Lattner547192d62003-12-19 07:22:45 +0000303/// SinkRegion - Walk the specified region of the CFG (defined by all blocks
304/// dominated by the specified block, and that are in the current loop) in
Owen Andersonc24701e2007-04-24 06:40:39 +0000305/// reverse depth first order w.r.t the DominatorTree. This allows us to visit
Chris Lattner547192d62003-12-19 07:22:45 +0000306/// uses before definitions, allowing us to sink a loop body in one pass without
307/// iteration.
308///
Devang Patelbdd1aae2007-06-04 00:32:22 +0000309void LICM::SinkRegion(DomTreeNode *N) {
Owen Andersonc24701e2007-04-24 06:40:39 +0000310 assert(N != 0 && "Null dominator tree node?");
311 BasicBlock *BB = N->getBlock();
Chris Lattner547192d62003-12-19 07:22:45 +0000312
313 // If this subregion is not in the top level loop at all, exit.
314 if (!CurLoop->contains(BB)) return;
315
316 // We are processing blocks in reverse dfo, so process children first...
Devang Patelbdd1aae2007-06-04 00:32:22 +0000317 const std::vector<DomTreeNode*> &Children = N->getChildren();
Chris Lattner547192d62003-12-19 07:22:45 +0000318 for (unsigned i = 0, e = Children.size(); i != e; ++i)
319 SinkRegion(Children[i]);
320
321 // Only need to process the contents of this block if it is not part of a
322 // subloop (which would already have been processed).
323 if (inSubLoop(BB)) return;
324
Chris Lattner91846012003-12-19 08:18:16 +0000325 for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
326 Instruction &I = *--II;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000327
Chris Lattner547192d62003-12-19 07:22:45 +0000328 // Check to see if we can sink this instruction to the exit blocks
329 // of the loop. We can do this if the all users of the instruction are
330 // outside of the loop. In this case, it doesn't even matter if the
331 // operands of the instruction are loop invariant.
332 //
Chris Lattnerfaf77912005-03-25 00:22:36 +0000333 if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
Chris Lattner91846012003-12-19 08:18:16 +0000334 ++II;
Chris Lattner547192d62003-12-19 07:22:45 +0000335 sink(I);
Chris Lattner91846012003-12-19 08:18:16 +0000336 }
Chris Lattner547192d62003-12-19 07:22:45 +0000337 }
338}
339
340
Chris Lattner64437692002-09-29 21:46:09 +0000341/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
342/// dominated by the specified block, and that are in the current loop) in depth
Owen Andersonc24701e2007-04-24 06:40:39 +0000343/// first order w.r.t the DominatorTree. This allows us to visit definitions
Chris Lattner64437692002-09-29 21:46:09 +0000344/// before uses, allowing us to hoist a loop body in one pass without iteration.
345///
Devang Patelbdd1aae2007-06-04 00:32:22 +0000346void LICM::HoistRegion(DomTreeNode *N) {
Owen Andersonc24701e2007-04-24 06:40:39 +0000347 assert(N != 0 && "Null dominator tree node?");
348 BasicBlock *BB = N->getBlock();
Chris Lattner64437692002-09-29 21:46:09 +0000349
Chris Lattner05e86302002-09-29 22:26:07 +0000350 // If this subregion is not in the top level loop at all, exit.
Chris Lattner65c11932003-12-09 19:32:44 +0000351 if (!CurLoop->contains(BB)) return;
Chris Lattner64437692002-09-29 21:46:09 +0000352
Chris Lattneraaaea512003-12-10 06:41:05 +0000353 // Only need to process the contents of this block if it is not part of a
354 // subloop (which would already have been processed).
Chris Lattner65c11932003-12-09 19:32:44 +0000355 if (!inSubLoop(BB))
Chris Lattneraaaea512003-12-10 06:41:05 +0000356 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
357 Instruction &I = *II++;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000358
Chris Lattner547192d62003-12-19 07:22:45 +0000359 // Try hoisting the instruction out to the preheader. We can only do this
360 // if all of the operands of the instruction are loop invariant and if it
361 // is safe to hoist the instruction.
362 //
Misha Brukmanb1c93172005-04-21 23:48:37 +0000363 if (isLoopInvariantInst(I) && canSinkOrHoistInst(I) &&
Chris Lattner547192d62003-12-19 07:22:45 +0000364 isSafeToExecuteUnconditionally(I))
Chris Lattner49771a02006-06-26 19:10:05 +0000365 hoist(I);
Chris Lattneraaaea512003-12-10 06:41:05 +0000366 }
Chris Lattner64437692002-09-29 21:46:09 +0000367
Devang Patelbdd1aae2007-06-04 00:32:22 +0000368 const std::vector<DomTreeNode*> &Children = N->getChildren();
Chris Lattner64437692002-09-29 21:46:09 +0000369 for (unsigned i = 0, e = Children.size(); i != e; ++i)
Chris Lattner42ad6462004-06-19 20:23:35 +0000370 HoistRegion(Children[i]);
Chris Lattner64437692002-09-29 21:46:09 +0000371}
372
Chris Lattneraaaea512003-12-10 06:41:05 +0000373/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
374/// instruction.
375///
376bool LICM::canSinkOrHoistInst(Instruction &I) {
Chris Lattner65c11932003-12-09 19:32:44 +0000377 // Loads have extra constraints we have to verify before we can hoist them.
378 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
379 if (LI->isVolatile())
380 return false; // Don't hoist volatile loads!
381
Chris Lattner8a8fb902008-07-23 05:06:28 +0000382 // Loads from constant memory are always safe to move, even if they end up
383 // in the same alias set as something that ends up being modified.
Dan Gohman5f36a322008-07-24 23:57:25 +0000384 if (EnableLICMConstantMotion &&
385 AA->pointsToConstantMemory(LI->getOperand(0)))
Chris Lattner8a8fb902008-07-23 05:06:28 +0000386 return true;
387
Chris Lattner65c11932003-12-09 19:32:44 +0000388 // Don't hoist loads which have may-aliased stores in loop.
Chris Lattnerb1374092004-11-26 21:20:09 +0000389 unsigned Size = 0;
390 if (LI->getType()->isSized())
Duncan Sands44b87212007-11-01 20:53:16 +0000391 Size = AA->getTargetData().getTypeStoreSize(LI->getType());
Chris Lattnerb1374092004-11-26 21:20:09 +0000392 return !pointerInvalidatedByLoop(LI->getOperand(0), Size);
Chris Lattner20cda262004-03-15 04:11:30 +0000393 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
394 // Handle obvious cases efficiently.
Duncan Sands68b6f502007-12-01 07:51:45 +0000395 AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
396 if (Behavior == AliasAnalysis::DoesNotAccessMemory)
397 return true;
398 else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
399 // If this call only reads from memory and there are no writes to memory
400 // in the loop, we can hoist or sink the call as appropriate.
401 bool FoundMod = false;
402 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
403 I != E; ++I) {
404 AliasSet &AS = *I;
405 if (!AS.isForwardingAliasSet() && AS.isMod()) {
406 FoundMod = true;
407 break;
Chris Lattner20cda262004-03-15 04:11:30 +0000408 }
Chris Lattner20cda262004-03-15 04:11:30 +0000409 }
Duncan Sands68b6f502007-12-01 07:51:45 +0000410 if (!FoundMod) return true;
Chris Lattner20cda262004-03-15 04:11:30 +0000411 }
412
413 // FIXME: This should use mod/ref information to see if we can hoist or sink
414 // the call.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000415
Chris Lattner20cda262004-03-15 04:11:30 +0000416 return false;
Chris Lattner65c11932003-12-09 19:32:44 +0000417 }
418
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000419 // Otherwise these instructions are hoistable/sinkable
Reid Spencer2341c222007-02-02 02:16:23 +0000420 return isa<BinaryOperator>(I) || isa<CastInst>(I) ||
Dan Gohman151169d2007-06-05 16:05:55 +0000421 isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||
422 isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
423 isa<ShuffleVectorInst>(I);
Chris Lattneraaaea512003-12-10 06:41:05 +0000424}
425
426/// isNotUsedInLoop - Return true if the only users of this instruction are
427/// outside of the loop. If this is true, we can sink the instruction to the
428/// exit blocks of the loop.
429///
430bool LICM::isNotUsedInLoop(Instruction &I) {
Chris Lattner34399dd2003-12-11 22:23:32 +0000431 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
432 Instruction *User = cast<Instruction>(*UI);
433 if (PHINode *PN = dyn_cast<PHINode>(User)) {
434 // PHI node uses occur in predecessor blocks!
435 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
436 if (PN->getIncomingValue(i) == &I)
437 if (CurLoop->contains(PN->getIncomingBlock(i)))
438 return false;
439 } else if (CurLoop->contains(User->getParent())) {
Chris Lattneraaaea512003-12-10 06:41:05 +0000440 return false;
Chris Lattner34399dd2003-12-11 22:23:32 +0000441 }
442 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000443 return true;
444}
445
446
447/// isLoopInvariantInst - Return true if all operands of this instruction are
448/// loop invariant. We also filter out non-hoistable instructions here just for
449/// efficiency.
450///
451bool LICM::isLoopInvariantInst(Instruction &I) {
452 // The instruction is loop invariant if all of its operands are loop-invariant
453 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Chris Lattnerfc44a252004-04-18 22:46:08 +0000454 if (!CurLoop->isLoopInvariant(I.getOperand(i)))
Chris Lattneraaaea512003-12-10 06:41:05 +0000455 return false;
456
Chris Lattner65c11932003-12-09 19:32:44 +0000457 // If we got this far, the instruction is loop invariant!
458 return true;
459}
460
Chris Lattneraaaea512003-12-10 06:41:05 +0000461/// sink - When an instruction is found to only be used outside of the loop,
Chris Lattner91846012003-12-19 08:18:16 +0000462/// this function moves it to the exit blocks and patches up SSA form as needed.
463/// This method is guaranteed to remove the original instruction from its
464/// position, and may either delete it or move it to outside of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000465///
466void LICM::sink(Instruction &I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000467 DOUT << "LICM sinking instruction: " << I;
Chris Lattneraaaea512003-12-10 06:41:05 +0000468
Devang Patelb5933bb2007-08-21 00:31:24 +0000469 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner35eaa552004-04-18 22:15:13 +0000470 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattner55c21132003-12-10 20:43:29 +0000471
472 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner20cda262004-03-15 04:11:30 +0000473 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattner55c21132003-12-10 20:43:29 +0000474 ++NumSunk;
475 Changed = true;
476
Chris Lattneraaaea512003-12-10 06:41:05 +0000477 // The case where there is only a single exit node of this loop is common
478 // enough that we handle it as a special (more efficient) case. It is more
479 // efficient to handle because there are no PHI nodes that need to be placed.
480 if (ExitBlocks.size() == 1) {
481 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
482 // Instruction is not used, just delete it.
Chris Lattner289ba2a2004-05-23 21:20:19 +0000483 CurAST->deleteValue(&I);
Chris Lattner1d7ec202006-09-12 19:17:09 +0000484 if (!I.use_empty()) // If I has users in unreachable blocks, eliminate.
485 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner49771a02006-06-26 19:10:05 +0000486 I.eraseFromParent();
Chris Lattneraaaea512003-12-10 06:41:05 +0000487 } else {
488 // Move the instruction to the start of the exit block, after any PHI
489 // nodes in it.
Chris Lattner49771a02006-06-26 19:10:05 +0000490 I.removeFromParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000491
Dan Gohmanf96e1372008-05-23 21:05:58 +0000492 BasicBlock::iterator InsertPt = ExitBlocks[0]->getFirstNonPHI();
Chris Lattneraaaea512003-12-10 06:41:05 +0000493 ExitBlocks[0]->getInstList().insert(InsertPt, &I);
494 }
Dan Gohman70de4cb2008-01-29 13:02:09 +0000495 } else if (ExitBlocks.empty()) {
Chris Lattneraaaea512003-12-10 06:41:05 +0000496 // The instruction is actually dead if there ARE NO exit blocks.
Chris Lattner289ba2a2004-05-23 21:20:19 +0000497 CurAST->deleteValue(&I);
Chris Lattner1d7ec202006-09-12 19:17:09 +0000498 if (!I.use_empty()) // If I has users in unreachable blocks, eliminate.
499 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner49771a02006-06-26 19:10:05 +0000500 I.eraseFromParent();
Chris Lattneraaaea512003-12-10 06:41:05 +0000501 } else {
502 // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
503 // do all of the hard work of inserting PHI nodes as necessary. We convert
504 // the value into a stack object to get it to do this.
505
506 // Firstly, we create a stack object to hold the value...
Chris Lattner50eb7712004-07-27 07:38:32 +0000507 AllocaInst *AI = 0;
Chris Lattneraaaea512003-12-10 06:41:05 +0000508
Devang Patelac54a622007-06-01 22:15:31 +0000509 if (I.getType() != Type::VoidTy) {
Chris Lattner50eb7712004-07-27 07:38:32 +0000510 AI = new AllocaInst(I.getType(), 0, I.getName(),
Dan Gohmandcb291f2007-03-22 16:38:57 +0000511 I.getParent()->getParent()->getEntryBlock().begin());
Devang Patelac54a622007-06-01 22:15:31 +0000512 CurAST->add(AI);
513 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000514
Chris Lattneraaaea512003-12-10 06:41:05 +0000515 // Secondly, insert load instructions for each use of the instruction
516 // outside of the loop.
517 while (!I.use_empty()) {
518 Instruction *U = cast<Instruction>(I.use_back());
519
520 // If the user is a PHI Node, we actually have to insert load instructions
521 // in all predecessor blocks, not in the PHI block itself!
522 if (PHINode *UPN = dyn_cast<PHINode>(U)) {
523 // Only insert into each predecessor once, so that we don't have
524 // different incoming values from the same block!
525 std::map<BasicBlock*, Value*> InsertedBlocks;
526 for (unsigned i = 0, e = UPN->getNumIncomingValues(); i != e; ++i)
527 if (UPN->getIncomingValue(i) == &I) {
528 BasicBlock *Pred = UPN->getIncomingBlock(i);
529 Value *&PredVal = InsertedBlocks[Pred];
530 if (!PredVal) {
531 // Insert a new load instruction right before the terminator in
532 // the predecessor block.
533 PredVal = new LoadInst(AI, "", Pred->getTerminator());
Devang Patelac54a622007-06-01 22:15:31 +0000534 CurAST->add(cast<LoadInst>(PredVal));
Chris Lattneraaaea512003-12-10 06:41:05 +0000535 }
536
537 UPN->setIncomingValue(i, PredVal);
538 }
539
540 } else {
541 LoadInst *L = new LoadInst(AI, "", U);
542 U->replaceUsesOfWith(&I, L);
Devang Patelac54a622007-06-01 22:15:31 +0000543 CurAST->add(L);
Chris Lattneraaaea512003-12-10 06:41:05 +0000544 }
545 }
546
547 // Thirdly, insert a copy of the instruction in each exit block of the loop
548 // that is dominated by the instruction, storing the result into the memory
549 // location. Be careful not to insert the instruction into any particular
550 // basic block more than once.
551 std::set<BasicBlock*> InsertedBlocks;
552 BasicBlock *InstOrigBB = I.getParent();
553
554 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
555 BasicBlock *ExitBlock = ExitBlocks[i];
556
557 if (isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB)) {
Chris Lattneraaaea512003-12-10 06:41:05 +0000558 // If we haven't already processed this exit block, do so now.
Chris Lattner63643142003-12-10 16:58:24 +0000559 if (InsertedBlocks.insert(ExitBlock).second) {
Chris Lattneraaaea512003-12-10 06:41:05 +0000560 // Insert the code after the last PHI node...
Dan Gohmanf96e1372008-05-23 21:05:58 +0000561 BasicBlock::iterator InsertPt = ExitBlock->getFirstNonPHI();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000562
Chris Lattneraaaea512003-12-10 06:41:05 +0000563 // If this is the first exit block processed, just move the original
564 // instruction, otherwise clone the original instruction and insert
565 // the copy.
566 Instruction *New;
Chris Lattner6281fd32003-12-10 22:35:56 +0000567 if (InsertedBlocks.size() == 1) {
Chris Lattner49771a02006-06-26 19:10:05 +0000568 I.removeFromParent();
Chris Lattneraaaea512003-12-10 06:41:05 +0000569 ExitBlock->getInstList().insert(InsertPt, &I);
570 New = &I;
571 } else {
572 New = I.clone();
Chris Lattnerfaf77912005-03-25 00:22:36 +0000573 CurAST->copyValue(&I, New);
Chris Lattner50eb7712004-07-27 07:38:32 +0000574 if (!I.getName().empty())
575 New->setName(I.getName()+".le");
Chris Lattneraaaea512003-12-10 06:41:05 +0000576 ExitBlock->getInstList().insert(InsertPt, New);
577 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000578
Chris Lattneraaaea512003-12-10 06:41:05 +0000579 // Now that we have inserted the instruction, store it into the alloca
Chris Lattner50eb7712004-07-27 07:38:32 +0000580 if (AI) new StoreInst(New, AI, InsertPt);
Chris Lattneraaaea512003-12-10 06:41:05 +0000581 }
582 }
583 }
Chris Lattner91846012003-12-19 08:18:16 +0000584
585 // If the instruction doesn't dominate any exit blocks, it must be dead.
586 if (InsertedBlocks.empty()) {
Chris Lattner289ba2a2004-05-23 21:20:19 +0000587 CurAST->deleteValue(&I);
Chris Lattner49771a02006-06-26 19:10:05 +0000588 I.eraseFromParent();
Chris Lattner91846012003-12-19 08:18:16 +0000589 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000590
Chris Lattneraaaea512003-12-10 06:41:05 +0000591 // Finally, promote the fine value to SSA form.
Chris Lattner50eb7712004-07-27 07:38:32 +0000592 if (AI) {
593 std::vector<AllocaInst*> Allocas;
594 Allocas.push_back(AI);
Devang Patelfc7fdef2007-06-07 21:57:03 +0000595 PromoteMemToReg(Allocas, *DT, *DF, CurAST);
Chris Lattner50eb7712004-07-27 07:38:32 +0000596 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000597 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000598}
Chris Lattner64437692002-09-29 21:46:09 +0000599
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000600/// hoist - When an instruction is found to only use loop invariant operands
601/// that is safe to hoist, this instruction is called to do the dirty work.
602///
Chris Lattneraaaea512003-12-10 06:41:05 +0000603void LICM::hoist(Instruction &I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000604 DOUT << "LICM hoisting to " << Preheader->getName() << ": " << I;
Chris Lattner65c11932003-12-09 19:32:44 +0000605
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000606 // Remove the instruction from its current basic block... but don't delete the
607 // instruction.
Chris Lattner49771a02006-06-26 19:10:05 +0000608 I.removeFromParent();
Chris Lattner6ec05f52002-05-10 22:44:58 +0000609
Chris Lattner718b2212002-09-26 16:38:03 +0000610 // Insert the new node in Preheader, before the terminator.
Chris Lattneraaaea512003-12-10 06:41:05 +0000611 Preheader->getInstList().insert(Preheader->getTerminator(), &I);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000612
Chris Lattneraaaea512003-12-10 06:41:05 +0000613 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner20cda262004-03-15 04:11:30 +0000614 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattner718b2212002-09-26 16:38:03 +0000615 ++NumHoisted;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000616 Changed = true;
617}
618
Chris Lattneraaaea512003-12-10 06:41:05 +0000619/// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
620/// not a trapping instruction or if it is a trapping instruction and is
621/// guaranteed to execute.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000622///
Chris Lattneraaaea512003-12-10 06:41:05 +0000623bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
Chris Lattnerc0517682003-12-09 17:18:00 +0000624 // If it is not a trapping instruction, it is always safe to hoist.
625 if (!Inst.isTrapping()) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000626
Chris Lattnerc0517682003-12-09 17:18:00 +0000627 // Otherwise we have to check to make sure that the instruction dominates all
628 // of the exit blocks. If it doesn't, then there is a path out of the loop
629 // which does not execute this instruction, so we can't hoist it.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000630
Chris Lattnerc0517682003-12-09 17:18:00 +0000631 // If the instruction is in the header block for the loop (which is very
632 // common), it is always guaranteed to dominate the exit blocks. Since this
633 // is a common case, and can save some work, check it now.
Chris Lattneraaaea512003-12-10 06:41:05 +0000634 if (Inst.getParent() == CurLoop->getHeader())
Chris Lattnerc0517682003-12-09 17:18:00 +0000635 return true;
Tanya Lattner57c03df2003-08-05 18:45:46 +0000636
Chris Lattner6e455602004-11-29 21:26:12 +0000637 // It's always safe to load from a global or alloca.
638 if (isa<LoadInst>(Inst))
639 if (isa<AllocationInst>(Inst.getOperand(0)) ||
640 isa<GlobalVariable>(Inst.getOperand(0)))
641 return true;
642
Chris Lattnerc0517682003-12-09 17:18:00 +0000643 // Get the exit blocks for the current loop.
Devang Patelb5933bb2007-08-21 00:31:24 +0000644 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner35eaa552004-04-18 22:15:13 +0000645 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattnerc0517682003-12-09 17:18:00 +0000646
Owen Andersonc24701e2007-04-24 06:40:39 +0000647 // For each exit block, get the DT node and walk up the DT until the
Chris Lattnerc0517682003-12-09 17:18:00 +0000648 // instruction's basic block is found or we exit the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000649 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
650 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
651 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000652
Tanya Lattner57c03df2003-08-05 18:45:46 +0000653 return true;
654}
655
Chris Lattnerd771fdf2002-09-26 16:19:31 +0000656
Chris Lattner45d67d62003-02-24 03:52:32 +0000657/// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
658/// stores out of the loop and moving loads to before the loop. We do this by
659/// looping over the stores in the loop, looking for stores to Must pointers
660/// which are loop invariant. We promote these memory locations to use allocas
661/// instead. These allocas can easily be raised to register values by the
662/// PromoteMem2Reg functionality.
663///
664void LICM::PromoteValuesInLoop() {
665 // PromotedValues - List of values that are promoted out of the loop. Each
Chris Lattner216c7b82003-09-10 05:29:43 +0000666 // value has an alloca instruction for it, and a canonical version of the
Chris Lattner45d67d62003-02-24 03:52:32 +0000667 // pointer.
668 std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
669 std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
670
Chris Lattnera3465782004-09-15 01:04:07 +0000671 FindPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
672 if (ValueToAllocaMap.empty()) return; // If there are values to promote.
Chris Lattner45d67d62003-02-24 03:52:32 +0000673
674 Changed = true;
675 NumPromoted += PromotedValues.size();
676
Chris Lattnera3465782004-09-15 01:04:07 +0000677 std::vector<Value*> PointerValueNumbers;
678
Chris Lattner45d67d62003-02-24 03:52:32 +0000679 // Emit a copy from the value into the alloca'd value in the loop preheader
680 TerminatorInst *LoopPredInst = Preheader->getTerminator();
681 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
Chris Lattnera3465782004-09-15 01:04:07 +0000682 Value *Ptr = PromotedValues[i].second;
683
684 // If we are promoting a pointer value, update alias information for the
685 // inserted load.
686 Value *LoadValue = 0;
687 if (isa<PointerType>(cast<PointerType>(Ptr->getType())->getElementType())) {
688 // Locate a load or store through the pointer, and assign the same value
689 // to LI as we are loading or storing. Since we know that the value is
690 // stored in this loop, this will always succeed.
691 for (Value::use_iterator UI = Ptr->use_begin(), E = Ptr->use_end();
692 UI != E; ++UI)
693 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
694 LoadValue = LI;
695 break;
696 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattnerf11216d2004-09-15 02:34:40 +0000697 if (SI->getOperand(1) == Ptr) {
Chris Lattnera3465782004-09-15 01:04:07 +0000698 LoadValue = SI->getOperand(0);
699 break;
700 }
701 }
702 assert(LoadValue && "No store through the pointer found!");
703 PointerValueNumbers.push_back(LoadValue); // Remember this for later.
704 }
705
706 // Load from the memory we are promoting.
707 LoadInst *LI = new LoadInst(Ptr, Ptr->getName()+".promoted", LoopPredInst);
708
709 if (LoadValue) CurAST->copyValue(LoadValue, LI);
710
711 // Store into the temporary alloca.
Chris Lattner45d67d62003-02-24 03:52:32 +0000712 new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
713 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000714
Chris Lattner45d67d62003-02-24 03:52:32 +0000715 // Scan the basic blocks in the loop, replacing uses of our pointers with
Chris Lattneredda1af2003-12-10 15:56:24 +0000716 // uses of the allocas in question.
Chris Lattner45d67d62003-02-24 03:52:32 +0000717 //
Dan Gohman90071072008-06-22 20:18:58 +0000718 for (Loop::block_iterator I = CurLoop->block_begin(),
719 E = CurLoop->block_end(); I != E; ++I) {
720 BasicBlock *BB = *I;
Chris Lattner45d67d62003-02-24 03:52:32 +0000721 // Rewrite all loads and stores in the block of the pointer...
Dan Gohman90071072008-06-22 20:18:58 +0000722 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
Chris Lattner889f6202003-04-23 16:37:45 +0000723 if (LoadInst *L = dyn_cast<LoadInst>(II)) {
Chris Lattner45d67d62003-02-24 03:52:32 +0000724 std::map<Value*, AllocaInst*>::iterator
725 I = ValueToAllocaMap.find(L->getOperand(0));
726 if (I != ValueToAllocaMap.end())
727 L->setOperand(0, I->second); // Rewrite load instruction...
Chris Lattner889f6202003-04-23 16:37:45 +0000728 } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
Chris Lattner45d67d62003-02-24 03:52:32 +0000729 std::map<Value*, AllocaInst*>::iterator
730 I = ValueToAllocaMap.find(S->getOperand(1));
731 if (I != ValueToAllocaMap.end())
732 S->setOperand(1, I->second); // Rewrite store instruction...
733 }
734 }
Chris Lattner45d67d62003-02-24 03:52:32 +0000735 }
736
Chris Lattneredda1af2003-12-10 15:56:24 +0000737 // Now that the body of the loop uses the allocas instead of the original
738 // memory locations, insert code to copy the alloca value back into the
739 // original memory location on all exits from the loop. Note that we only
740 // want to insert one copy of the code in each exit block, though the loop may
741 // exit to the same block more than once.
742 //
Chris Lattnerc5ec1e12008-05-22 03:22:42 +0000743 SmallPtrSet<BasicBlock*, 16> ProcessedBlocks;
Chris Lattneredda1af2003-12-10 15:56:24 +0000744
Devang Patelb5933bb2007-08-21 00:31:24 +0000745 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner35eaa552004-04-18 22:15:13 +0000746 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattnerc5ec1e12008-05-22 03:22:42 +0000747 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
748 if (!ProcessedBlocks.insert(ExitBlocks[i]))
749 continue;
750
751 // Copy all of the allocas into their memory locations.
Dan Gohmanf96e1372008-05-23 21:05:58 +0000752 BasicBlock::iterator BI = ExitBlocks[i]->getFirstNonPHI();
Chris Lattnerc5ec1e12008-05-22 03:22:42 +0000753 Instruction *InsertPos = BI;
754 unsigned PVN = 0;
755 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
756 // Load from the alloca.
757 LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
Chris Lattnera3465782004-09-15 01:04:07 +0000758
Chris Lattnerc5ec1e12008-05-22 03:22:42 +0000759 // If this is a pointer type, update alias info appropriately.
760 if (isa<PointerType>(LI->getType()))
761 CurAST->copyValue(PointerValueNumbers[PVN++], LI);
Chris Lattnera3465782004-09-15 01:04:07 +0000762
Chris Lattnerc5ec1e12008-05-22 03:22:42 +0000763 // Store into the memory we promoted.
764 new StoreInst(LI, PromotedValues[i].second, InsertPos);
Chris Lattneredda1af2003-12-10 15:56:24 +0000765 }
Chris Lattnerc5ec1e12008-05-22 03:22:42 +0000766 }
Chris Lattneredda1af2003-12-10 15:56:24 +0000767
Chris Lattner45d67d62003-02-24 03:52:32 +0000768 // Now that we have done the deed, use the mem2reg functionality to promote
Chris Lattnera3465782004-09-15 01:04:07 +0000769 // all of the new allocas we just created into real SSA registers.
Chris Lattner45d67d62003-02-24 03:52:32 +0000770 //
771 std::vector<AllocaInst*> PromotedAllocas;
772 PromotedAllocas.reserve(PromotedValues.size());
773 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
774 PromotedAllocas.push_back(PromotedValues[i].first);
Devang Patelfc7fdef2007-06-07 21:57:03 +0000775 PromoteMemToReg(PromotedAllocas, *DT, *DF, CurAST);
Chris Lattner45d67d62003-02-24 03:52:32 +0000776}
777
Chris Lattnera3465782004-09-15 01:04:07 +0000778/// FindPromotableValuesInLoop - Check the current loop for stores to definite
Devang Patel464276f2007-09-19 20:18:51 +0000779/// pointers, which are not loaded and stored through may aliases and are safe
780/// for promotion. If these are found, create an alloca for the value, add it
781/// to the PromotedValues list, and keep track of the mapping from value to
782/// alloca.
Chris Lattnera3465782004-09-15 01:04:07 +0000783void LICM::FindPromotableValuesInLoop(
Chris Lattner45d67d62003-02-24 03:52:32 +0000784 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
785 std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
786 Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
787
Chris Lattnerc5ec1e12008-05-22 03:22:42 +0000788 SmallVector<BasicBlock*, 4> ExitingBlocks;
789 CurLoop->getExitingBlocks(ExitingBlocks);
Devang Patel464276f2007-09-19 20:18:51 +0000790
Chris Lattnera3465782004-09-15 01:04:07 +0000791 // Loop over all of the alias sets in the tracker object.
Chris Lattner0592bb72003-03-03 23:32:45 +0000792 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
793 I != E; ++I) {
794 AliasSet &AS = *I;
795 // We can promote this alias set if it has a store, if it is a "Must" alias
Chris Lattnera3465782004-09-15 01:04:07 +0000796 // set, if the pointer is loop invariant, and if we are not eliminating any
Chris Lattner20cda262004-03-15 04:11:30 +0000797 // volatile loads or stores.
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000798 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
799 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->first))
800 continue;
801
802 assert(!AS.empty() &&
803 "Must alias set should have at least one pointer element in it!");
804 Value *V = AS.begin()->first;
Chris Lattner45d67d62003-02-24 03:52:32 +0000805
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000806 // Check that all of the pointers in the alias set have the same type. We
807 // cannot (yet) promote a memory location that is loaded and stored in
808 // different sizes.
809 {
Chris Lattner0592bb72003-03-03 23:32:45 +0000810 bool PointerOk = true;
811 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
812 if (V->getType() != I->first->getType()) {
813 PointerOk = false;
814 break;
Chris Lattner45d67d62003-02-24 03:52:32 +0000815 }
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000816 if (!PointerOk)
817 continue;
Chris Lattner45d67d62003-02-24 03:52:32 +0000818 }
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000819
Chris Lattnerc5ec1e12008-05-22 03:22:42 +0000820 // It isn't safe to promote a load/store from the loop if the load/store is
821 // conditional. For example, turning:
822 //
823 // for () { if (c) *P += 1; }
824 //
825 // into:
826 //
827 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
828 //
829 // is not safe, because *P may only be valid to access if 'c' is true.
830 //
831 // It is safe to promote P if all uses are direct load/stores and if at
832 // least one is guaranteed to be executed.
833 bool GuaranteedToExecute = false;
834 bool InvalidInst = false;
835 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end();
836 UI != UE; ++UI) {
837 // Ignore instructions not in this loop.
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000838 Instruction *Use = dyn_cast<Instruction>(*UI);
839 if (!Use || !CurLoop->contains(Use->getParent()))
840 continue;
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000841
Chris Lattnerc5ec1e12008-05-22 03:22:42 +0000842 if (!isa<LoadInst>(Use) && !isa<StoreInst>(Use)) {
843 InvalidInst = true;
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000844 break;
Chris Lattnerc5ec1e12008-05-22 03:22:42 +0000845 }
846
847 if (!GuaranteedToExecute)
848 GuaranteedToExecute = isSafeToExecuteUnconditionally(*Use);
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000849 }
850
Chris Lattnerc5ec1e12008-05-22 03:22:42 +0000851 // If there is an non-load/store instruction in the loop, we can't promote
852 // it. If there isn't a guaranteed-to-execute instruction, we can't
853 // promote.
854 if (InvalidInst || !GuaranteedToExecute)
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000855 continue;
856
857 const Type *Ty = cast<PointerType>(V->getType())->getElementType();
858 AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
859 PromotedValues.push_back(std::make_pair(AI, V));
860
861 // Update the AST and alias analysis.
862 CurAST->copyValue(V, AI);
863
864 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
865 ValueToAllocaMap.insert(std::make_pair(I->first, AI));
866
867 DOUT << "LICM: Promoting value: " << *V << "\n";
Chris Lattner45d67d62003-02-24 03:52:32 +0000868 }
Chris Lattnera51fa882002-08-22 21:39:55 +0000869}
Devang Patelb98a0972007-07-31 08:01:41 +0000870
871/// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
872void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
873 AliasSetTracker *AST = LoopToAliasMap[L];
874 if (!AST)
875 return;
876
877 AST->copyValue(From, To);
878}
879
880/// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
881/// set.
882void LICM::deleteAnalysisValue(Value *V, Loop *L) {
883 AliasSetTracker *AST = LoopToAliasMap[L];
884 if (!AST)
885 return;
886
887 AST->deleteValue(V);
888}