blob: 128a0d82335ef701f83b3fa471b4a448f751ead4 [file] [log] [blame]
Chris Lattnere0e734e2002-05-10 22:44:58 +00001//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
2//
Chris Lattner2e6e7412003-02-24 03:52:32 +00003// This pass is a simple loop invariant code motion pass. An interesting aspect
4// of this pass is that it uses alias analysis for two purposes:
5//
6// 1. Moving loop invariant loads out of loops. If we can determine that a
7// load inside of a loop never aliases anything stored to, we can hoist it
8// like any other instruction.
9// 2. Scalar Promotion of Memory - If there is a store instruction inside of
10// the loop, we try to move the store to happen AFTER the loop instead of
11// inside of the loop. This can only happen if a few conditions are true:
12// A. The pointer stored through is loop invariant
13// B. There are no stores or loads in the loop which _may_ alias the
14// pointer. There are no calls in the loop which mod/ref the pointer.
15// If these conditions are true, we can promote the loads and stores in the
16// loop of the pointer to use a temporary alloca'd variable. We then use
17// the mem2reg functionality to construct the appropriate SSA form for the
18// variable.
Chris Lattnere0e734e2002-05-10 22:44:58 +000019//
Chris Lattnere0e734e2002-05-10 22:44:58 +000020//===----------------------------------------------------------------------===//
21
22#include "llvm/Transforms/Scalar.h"
Chris Lattner2e6e7412003-02-24 03:52:32 +000023#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Chris Lattnere0e734e2002-05-10 22:44:58 +000024#include "llvm/Transforms/Utils/Local.h"
25#include "llvm/Analysis/LoopInfo.h"
Chris Lattnerf5e84aa2002-08-22 21:39:55 +000026#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner952eaee2002-09-29 21:46:09 +000027#include "llvm/Analysis/Dominators.h"
Chris Lattner2e6e7412003-02-24 03:52:32 +000028#include "llvm/Instructions.h"
29#include "llvm/DerivedTypes.h"
Chris Lattnerfb743a92003-03-03 17:25:18 +000030#include "llvm/Target/TargetData.h"
Chris Lattnere0e734e2002-05-10 22:44:58 +000031#include "llvm/Support/InstVisitor.h"
Chris Lattner2e6e7412003-02-24 03:52:32 +000032#include "llvm/Support/CFG.h"
Chris Lattnera92f6962002-10-01 22:38:41 +000033#include "Support/Statistic.h"
Chris Lattner2e6e7412003-02-24 03:52:32 +000034#include "Support/CommandLine.h"
Chris Lattnerb4613732002-09-29 22:26:07 +000035#include "llvm/Assembly/Writer.h"
Chris Lattnere0e734e2002-05-10 22:44:58 +000036#include <algorithm>
37
Chris Lattnere0e734e2002-05-10 22:44:58 +000038namespace {
Chris Lattner2e6e7412003-02-24 03:52:32 +000039 cl::opt<bool> DisablePromotion("disable-licm-promotion", cl::Hidden,
40 cl::desc("Disable memory promotion in LICM pass"));
41
Chris Lattnera92f6962002-10-01 22:38:41 +000042 Statistic<> NumHoisted("licm", "Number of instructions hoisted out of loop");
43 Statistic<> NumHoistedLoads("licm", "Number of load insts hoisted");
Chris Lattner2e6e7412003-02-24 03:52:32 +000044 Statistic<> NumPromoted("licm", "Number of memory locations promoted to registers");
Chris Lattner9646e6b2002-09-26 16:38:03 +000045
Chris Lattner2e6e7412003-02-24 03:52:32 +000046 /// LoopBodyInfo - We recursively traverse loops from most-deeply-nested to
47 /// least-deeply-nested. For all of the loops nested within the current one,
48 /// we keep track of information so that we don't have to repeat queries.
49 ///
50 struct LoopBodyInfo {
51 std::vector<CallInst*> Calls; // Call instructions in loop
52 std::vector<InvokeInst*> Invokes; // Invoke instructions in loop
53
54 // StoredPointers - Targets of store instructions...
55 std::set<Value*> StoredPointers;
56
57 // LoadedPointers - Source pointers for load instructions...
58 std::set<Value*> LoadedPointers;
59
60 enum PointerClass {
61 PointerUnknown = 0, // Nothing is known about this pointer yet
62 PointerMustStore, // Memory is stored to ONLY through this pointer
63 PointerMayStore, // Memory is stored to through this or other pointers
64 PointerNoStore // Memory is not modified in this loop
65 };
66
67 // PointerIsModified - Keep track of information as we find out about it in
68 // the loop body...
69 //
70 std::map<Value*, enum PointerClass> PointerIsModified;
71
72 /// CantModifyAnyPointers - Return true if no memory modifying instructions
73 /// occur in this loop. This is just a conservative approximation, because
74 /// a call may not actually store anything.
75 bool CantModifyAnyPointers() const {
76 return Calls.empty() && Invokes.empty() && StoredPointers.empty();
77 }
78
79 /// incorporate - Incorporate information about a subloop into the current
80 /// loop.
81 void incorporate(const LoopBodyInfo &OtherLBI);
82 void incorporate(BasicBlock &BB); // do the same for a basic block
83
84 PointerClass getPointerInfo(Value *V, AliasAnalysis &AA) {
85 PointerClass &VInfo = PointerIsModified[V];
86 if (VInfo == PointerUnknown)
87 VInfo = calculatePointerInfo(V, AA);
88 return VInfo;
89 }
90 private:
91 /// calculatePointerInfo - Calculate information about the specified
92 /// pointer.
93 PointerClass calculatePointerInfo(Value *V, AliasAnalysis &AA) const;
94 };
95}
96
97/// incorporate - Incorporate information about a subloop into the current loop.
98void LoopBodyInfo::incorporate(const LoopBodyInfo &OtherLBI) {
99 // Do not incorporate NonModifiedPointers (which is just a cache) because it
100 // is too much trouble to make sure it's still valid.
101 Calls.insert (Calls.end(), OtherLBI.Calls.begin(), OtherLBI.Calls.end());
102 Invokes.insert(Invokes.end(),OtherLBI.Invokes.begin(),OtherLBI.Invokes.end());
103 StoredPointers.insert(OtherLBI.StoredPointers.begin(),
104 OtherLBI.StoredPointers.end());
105 LoadedPointers.insert(OtherLBI.LoadedPointers.begin(),
106 OtherLBI.LoadedPointers.end());
107}
108
109void LoopBodyInfo::incorporate(BasicBlock &BB) {
110 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
111 if (CallInst *CI = dyn_cast<CallInst>(&*I))
112 Calls.push_back(CI);
113 else if (StoreInst *SI = dyn_cast<StoreInst>(&*I))
114 StoredPointers.insert(SI->getOperand(1));
115 else if (LoadInst *LI = dyn_cast<LoadInst>(&*I))
116 LoadedPointers.insert(LI->getOperand(0));
117
118 if (InvokeInst *II = dyn_cast<InvokeInst>(BB.getTerminator()))
119 Invokes.push_back(II);
120}
121
122
123// calculatePointerInfo - Calculate information about the specified pointer.
124LoopBodyInfo::PointerClass LoopBodyInfo::calculatePointerInfo(Value *V,
125 AliasAnalysis &AA) const {
126 for (unsigned i = 0, e = Calls.size(); i != e; ++i)
Chris Lattner2d0a4a42003-02-26 19:28:57 +0000127 if (AA.getModRefInfo(Calls[i], V, ~0))
Chris Lattner2e6e7412003-02-24 03:52:32 +0000128 return PointerMayStore;
129
130 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
Chris Lattner2d0a4a42003-02-26 19:28:57 +0000131 if (AA.getModRefInfo(Invokes[i], V, ~0))
Chris Lattner2e6e7412003-02-24 03:52:32 +0000132 return PointerMayStore;
133
134 PointerClass Result = PointerNoStore;
135 for (std::set<Value*>::const_iterator I = StoredPointers.begin(),
136 E = StoredPointers.end(); I != E; ++I)
Chris Lattner2d0a4a42003-02-26 19:28:57 +0000137 if (AA.alias(V, ~0, *I, ~0))
Chris Lattner2e6e7412003-02-24 03:52:32 +0000138 if (V == *I)
139 Result = PointerMustStore; // If this is the only alias, return must
140 else
141 return PointerMayStore; // We have to return may
142 return Result;
143}
144
145namespace {
Chris Lattnere0e734e2002-05-10 22:44:58 +0000146 struct LICM : public FunctionPass, public InstVisitor<LICM> {
Chris Lattner7e708292002-06-25 16:13:24 +0000147 virtual bool runOnFunction(Function &F);
Chris Lattnere0e734e2002-05-10 22:44:58 +0000148
Chris Lattner94170592002-09-26 16:52:07 +0000149 /// This transformation requires natural loop information & requires that
150 /// loop preheaders be inserted into the CFG...
151 ///
Chris Lattnere0e734e2002-05-10 22:44:58 +0000152 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnercb2610e2002-10-21 20:00:28 +0000153 AU.setPreservesCFG();
Chris Lattnereb53ae42002-09-26 16:19:31 +0000154 AU.addRequiredID(LoopPreheadersID);
Chris Lattner5f0eb8d2002-08-08 19:01:30 +0000155 AU.addRequired<LoopInfo>();
Chris Lattner952eaee2002-09-29 21:46:09 +0000156 AU.addRequired<DominatorTree>();
Chris Lattner2e6e7412003-02-24 03:52:32 +0000157 AU.addRequired<DominanceFrontier>();
Chris Lattnerf5e84aa2002-08-22 21:39:55 +0000158 AU.addRequired<AliasAnalysis>();
Chris Lattnere0e734e2002-05-10 22:44:58 +0000159 }
160
161 private:
Chris Lattner2e6e7412003-02-24 03:52:32 +0000162 LoopInfo *LI; // Current LoopInfo
163 AliasAnalysis *AA; // Current AliasAnalysis information
164 bool Changed; // Set to true when we change anything.
165 BasicBlock *Preheader; // The preheader block of the current loop...
166 Loop *CurLoop; // The current loop we are working on...
167 LoopBodyInfo *CurLBI; // Information about the current loop...
Chris Lattnere0e734e2002-05-10 22:44:58 +0000168
Chris Lattner94170592002-09-26 16:52:07 +0000169 /// visitLoop - Hoist expressions out of the specified loop...
170 ///
Chris Lattner2e6e7412003-02-24 03:52:32 +0000171 void visitLoop(Loop *L, LoopBodyInfo &LBI);
Chris Lattnere0e734e2002-05-10 22:44:58 +0000172
Chris Lattner952eaee2002-09-29 21:46:09 +0000173 /// HoistRegion - Walk the specified region of the CFG (defined by all
174 /// blocks dominated by the specified block, and that are in the current
175 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
176 /// visit defintions before uses, allowing us to hoist a loop body in one
177 /// pass without iteration.
178 ///
179 void HoistRegion(DominatorTree::Node *N);
180
Chris Lattnerb4613732002-09-29 22:26:07 +0000181 /// inSubLoop - Little predicate that returns true if the specified basic
182 /// block is in a subloop of the current one, not the current one itself.
Chris Lattner94170592002-09-26 16:52:07 +0000183 ///
Chris Lattnerb4613732002-09-29 22:26:07 +0000184 bool inSubLoop(BasicBlock *BB) {
185 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
Chris Lattnere0e734e2002-05-10 22:44:58 +0000186 for (unsigned i = 0, e = CurLoop->getSubLoops().size(); i != e; ++i)
187 if (CurLoop->getSubLoops()[i]->contains(BB))
Chris Lattnerb4613732002-09-29 22:26:07 +0000188 return true; // A subloop actually contains this block!
189 return false;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000190 }
191
Chris Lattner94170592002-09-26 16:52:07 +0000192 /// hoist - When an instruction is found to only use loop invariant operands
193 /// that is safe to hoist, this instruction is called to do the dirty work.
194 ///
Chris Lattner7e708292002-06-25 16:13:24 +0000195 void hoist(Instruction &I);
Chris Lattnere0e734e2002-05-10 22:44:58 +0000196
Chris Lattner94170592002-09-26 16:52:07 +0000197 /// pointerInvalidatedByLoop - Return true if the body of this loop may
198 /// store into the memory location pointed to by V.
199 ///
Chris Lattner2e6e7412003-02-24 03:52:32 +0000200 bool pointerInvalidatedByLoop(Value *V) {
201 // Check to see if any of the basic blocks in CurLoop invalidate V.
202 return CurLBI->getPointerInfo(V, *AA) != LoopBodyInfo::PointerNoStore;
203 }
Chris Lattnerf5e84aa2002-08-22 21:39:55 +0000204
Chris Lattner94170592002-09-26 16:52:07 +0000205 /// isLoopInvariant - Return true if the specified value is loop invariant
206 ///
Chris Lattnere0e734e2002-05-10 22:44:58 +0000207 inline bool isLoopInvariant(Value *V) {
208 if (Instruction *I = dyn_cast<Instruction>(V))
209 return !CurLoop->contains(I->getParent());
210 return true; // All non-instructions are loop invariant
211 }
212
Chris Lattner2e6e7412003-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
218 /// findPromotableValuesInLoop - Check the current loop for stores to
219 /// definate pointers, which are not loaded and stored through may aliases.
220 /// 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 ///
224 void findPromotableValuesInLoop(
225 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
226 std::map<Value*, AllocaInst*> &Val2AlMap);
227
228
Chris Lattner94170592002-09-26 16:52:07 +0000229 /// Instruction visitation handlers... these basically control whether or
230 /// not the specified instruction types are hoisted.
231 ///
Chris Lattnere0e734e2002-05-10 22:44:58 +0000232 friend class InstVisitor<LICM>;
Chris Lattner7e708292002-06-25 16:13:24 +0000233 void visitBinaryOperator(Instruction &I) {
234 if (isLoopInvariant(I.getOperand(0)) && isLoopInvariant(I.getOperand(1)))
Chris Lattnere0e734e2002-05-10 22:44:58 +0000235 hoist(I);
236 }
Chris Lattner9b2b80f2002-08-14 18:22:19 +0000237 void visitCastInst(CastInst &CI) {
238 Instruction &I = (Instruction&)CI;
239 if (isLoopInvariant(I.getOperand(0))) hoist(I);
Chris Lattner0513e9f2002-08-14 18:18:02 +0000240 }
Chris Lattner7e708292002-06-25 16:13:24 +0000241 void visitShiftInst(ShiftInst &I) { visitBinaryOperator((Instruction&)I); }
Chris Lattnere0e734e2002-05-10 22:44:58 +0000242
Chris Lattnereb53ae42002-09-26 16:19:31 +0000243 void visitLoadInst(LoadInst &LI);
Chris Lattnerf5e84aa2002-08-22 21:39:55 +0000244
Chris Lattner7e708292002-06-25 16:13:24 +0000245 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
246 Instruction &I = (Instruction&)GEPI;
247 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
248 if (!isLoopInvariant(I.getOperand(i))) return;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000249 hoist(I);
250 }
251 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000252
Chris Lattnera6275cc2002-07-26 21:12:46 +0000253 RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
Chris Lattnere0e734e2002-05-10 22:44:58 +0000254}
255
256Pass *createLICMPass() { return new LICM(); }
257
Chris Lattner94170592002-09-26 16:52:07 +0000258/// runOnFunction - For LICM, this simply traverses the loop structure of the
259/// function, hoisting expressions out of loops if possible.
260///
Chris Lattner7e708292002-06-25 16:13:24 +0000261bool LICM::runOnFunction(Function &) {
Chris Lattner2e6e7412003-02-24 03:52:32 +0000262 Changed = false;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000263
Chris Lattner2e6e7412003-02-24 03:52:32 +0000264 // Get our Loop and Alias Analysis information...
265 LI = &getAnalysis<LoopInfo>();
Chris Lattnerf5e84aa2002-08-22 21:39:55 +0000266 AA = &getAnalysis<AliasAnalysis>();
267
Chris Lattner2e6e7412003-02-24 03:52:32 +0000268 // Hoist expressions out of all of the top-level loops.
269 const std::vector<Loop*> &TopLevelLoops = LI->getTopLevelLoops();
270 for (std::vector<Loop*>::const_iterator I = TopLevelLoops.begin(),
271 E = TopLevelLoops.end(); I != E; ++I) {
272 LoopBodyInfo LBI;
273 LICM::visitLoop(*I, LBI);
274 }
Chris Lattnere0e734e2002-05-10 22:44:58 +0000275 return Changed;
276}
277
Chris Lattner94170592002-09-26 16:52:07 +0000278
279/// visitLoop - Hoist expressions out of the specified loop...
280///
Chris Lattner2e6e7412003-02-24 03:52:32 +0000281void LICM::visitLoop(Loop *L, LoopBodyInfo &LBI) {
Chris Lattnere0e734e2002-05-10 22:44:58 +0000282 // Recurse through all subloops before we process this loop...
Chris Lattner2e6e7412003-02-24 03:52:32 +0000283 for (std::vector<Loop*>::const_iterator I = L->getSubLoops().begin(),
284 E = L->getSubLoops().end(); I != E; ++I) {
285 LoopBodyInfo SubLBI;
286 LICM::visitLoop(*I, SubLBI);
287
288 // Incorporate information about the subloops into this loop...
289 LBI.incorporate(SubLBI);
290 }
Chris Lattnere0e734e2002-05-10 22:44:58 +0000291 CurLoop = L;
Chris Lattner2e6e7412003-02-24 03:52:32 +0000292 CurLBI = &LBI;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000293
Chris Lattner99a57212002-09-26 19:40:25 +0000294 // Get the preheader block to move instructions into...
295 Preheader = L->getLoopPreheader();
296 assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
297
Chris Lattner2e6e7412003-02-24 03:52:32 +0000298 // Loop over the body of this loop, looking for calls, invokes, and stores.
299 // Because subloops have already been incorporated into LBI, we skip blocks in
300 // subloops.
301 //
302 const std::vector<BasicBlock*> &LoopBBs = L->getBlocks();
303 for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
304 E = LoopBBs.end(); I != E; ++I)
305 if (LI->getLoopFor(*I) == L) // Ignore blocks in subloops...
306 LBI.incorporate(**I); // Incorporate the specified basic block
307
Chris Lattnere0e734e2002-05-10 22:44:58 +0000308 // We want to visit all of the instructions in this loop... that are not parts
309 // of our subloops (they have already had their invariants hoisted out of
310 // their loop, into this loop, so there is no need to process the BODIES of
311 // the subloops).
312 //
Chris Lattner952eaee2002-09-29 21:46:09 +0000313 // Traverse the body of the loop in depth first order on the dominator tree so
314 // that we are guaranteed to see definitions before we see uses. This allows
315 // us to perform the LICM transformation in one pass, without iteration.
316 //
317 HoistRegion(getAnalysis<DominatorTree>()[L->getHeader()]);
Chris Lattnere0e734e2002-05-10 22:44:58 +0000318
Chris Lattner2e6e7412003-02-24 03:52:32 +0000319 // Now that all loop invariants have been removed from the loop, promote any
320 // memory references to scalars that we can...
321 if (!DisablePromotion)
322 PromoteValuesInLoop();
323
Chris Lattnere0e734e2002-05-10 22:44:58 +0000324 // Clear out loops state information for the next iteration
325 CurLoop = 0;
Chris Lattner99a57212002-09-26 19:40:25 +0000326 Preheader = 0;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000327}
328
Chris Lattner952eaee2002-09-29 21:46:09 +0000329/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
330/// dominated by the specified block, and that are in the current loop) in depth
331/// first order w.r.t the DominatorTree. This allows us to visit defintions
332/// before uses, allowing us to hoist a loop body in one pass without iteration.
333///
334void LICM::HoistRegion(DominatorTree::Node *N) {
335 assert(N != 0 && "Null dominator tree node?");
336
Chris Lattnerb4613732002-09-29 22:26:07 +0000337 // If this subregion is not in the top level loop at all, exit.
338 if (!CurLoop->contains(N->getNode())) return;
Chris Lattner952eaee2002-09-29 21:46:09 +0000339
Chris Lattnerb4613732002-09-29 22:26:07 +0000340 // Only need to hoist the contents of this block if it is not part of a
341 // subloop (which would already have been hoisted)
342 if (!inSubLoop(N->getNode()))
343 visit(*N->getNode());
Chris Lattner952eaee2002-09-29 21:46:09 +0000344
345 const std::vector<DominatorTree::Node*> &Children = N->getChildren();
346 for (unsigned i = 0, e = Children.size(); i != e; ++i)
347 HoistRegion(Children[i]);
348}
349
350
Chris Lattner94170592002-09-26 16:52:07 +0000351/// hoist - When an instruction is found to only use loop invariant operands
352/// that is safe to hoist, this instruction is called to do the dirty work.
353///
Chris Lattner7e708292002-06-25 16:13:24 +0000354void LICM::hoist(Instruction &Inst) {
Chris Lattnerb4613732002-09-29 22:26:07 +0000355 DEBUG(std::cerr << "LICM hoisting to";
356 WriteAsOperand(std::cerr, Preheader, false);
357 std::cerr << ": " << Inst);
Chris Lattnere0e734e2002-05-10 22:44:58 +0000358
Chris Lattner99a57212002-09-26 19:40:25 +0000359 // Remove the instruction from its current basic block... but don't delete the
360 // instruction.
361 Inst.getParent()->getInstList().remove(&Inst);
Chris Lattnere0e734e2002-05-10 22:44:58 +0000362
Chris Lattner9646e6b2002-09-26 16:38:03 +0000363 // Insert the new node in Preheader, before the terminator.
Chris Lattner99a57212002-09-26 19:40:25 +0000364 Preheader->getInstList().insert(Preheader->getTerminator(), &Inst);
Chris Lattner9646e6b2002-09-26 16:38:03 +0000365
Chris Lattner9646e6b2002-09-26 16:38:03 +0000366 ++NumHoisted;
Chris Lattnere0e734e2002-05-10 22:44:58 +0000367 Changed = true;
368}
369
Chris Lattnereb53ae42002-09-26 16:19:31 +0000370
371void LICM::visitLoadInst(LoadInst &LI) {
372 if (isLoopInvariant(LI.getOperand(0)) &&
Chris Lattner99a57212002-09-26 19:40:25 +0000373 !pointerInvalidatedByLoop(LI.getOperand(0))) {
Chris Lattnereb53ae42002-09-26 16:19:31 +0000374 hoist(LI);
Chris Lattner99a57212002-09-26 19:40:25 +0000375 ++NumHoistedLoads;
376 }
Chris Lattnereb53ae42002-09-26 16:19:31 +0000377}
378
Chris Lattner2e6e7412003-02-24 03:52:32 +0000379/// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
380/// stores out of the loop and moving loads to before the loop. We do this by
381/// looping over the stores in the loop, looking for stores to Must pointers
382/// which are loop invariant. We promote these memory locations to use allocas
383/// instead. These allocas can easily be raised to register values by the
384/// PromoteMem2Reg functionality.
385///
386void LICM::PromoteValuesInLoop() {
387 // PromotedValues - List of values that are promoted out of the loop. Each
388 // value has an alloca instruction for it, and a cannonical version of the
389 // pointer.
390 std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
391 std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
392
393 findPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
394 if (ValueToAllocaMap.empty()) return; // If there are values to promote...
395
396 Changed = true;
397 NumPromoted += PromotedValues.size();
398
399 // Emit a copy from the value into the alloca'd value in the loop preheader
400 TerminatorInst *LoopPredInst = Preheader->getTerminator();
401 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
402 // Load from the memory we are promoting...
403 LoadInst *LI = new LoadInst(PromotedValues[i].second,
404 PromotedValues[i].second->getName()+".promoted",
405 LoopPredInst);
406 // Store into the temporary alloca...
407 new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
408 }
409
410 // Scan the basic blocks in the loop, replacing uses of our pointers with
411 // uses of the allocas in question. If we find a branch that exits the
412 // loop, make sure to put reload code into all of the successors of the
413 // loop.
414 //
415 const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
416 for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
417 E = LoopBBs.end(); I != E; ++I) {
418 // Rewrite all loads and stores in the block of the pointer...
419 for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
420 II != E; ++II) {
421 if (LoadInst *L = dyn_cast<LoadInst>(&*II)) {
422 std::map<Value*, AllocaInst*>::iterator
423 I = ValueToAllocaMap.find(L->getOperand(0));
424 if (I != ValueToAllocaMap.end())
425 L->setOperand(0, I->second); // Rewrite load instruction...
426 } else if (StoreInst *S = dyn_cast<StoreInst>(&*II)) {
427 std::map<Value*, AllocaInst*>::iterator
428 I = ValueToAllocaMap.find(S->getOperand(1));
429 if (I != ValueToAllocaMap.end())
430 S->setOperand(1, I->second); // Rewrite store instruction...
431 }
432 }
433
434 // Check to see if any successors of this block are outside of the loop.
435 // If so, we need to copy the value from the alloca back into the memory
436 // location...
437 //
438 for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI)
439 if (!CurLoop->contains(*SI)) {
440 // Copy all of the allocas into their memory locations...
Chris Lattner8601a9b2003-02-27 21:59:36 +0000441 BasicBlock::iterator BI = (*SI)->begin();
442 while (isa<PHINode>(*BI))
443 ++BI; // Skip over all of the phi nodes in the block...
444 Instruction *InsertPos = BI;
Chris Lattner2e6e7412003-02-24 03:52:32 +0000445 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
446 // Load from the alloca...
447 LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
448 // Store into the memory we promoted...
449 new StoreInst(LI, PromotedValues[i].second, InsertPos);
450 }
451 }
452 }
453
454 // Now that we have done the deed, use the mem2reg functionality to promote
455 // all of the new allocas we just created into real SSA registers...
456 //
457 std::vector<AllocaInst*> PromotedAllocas;
458 PromotedAllocas.reserve(PromotedValues.size());
459 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
460 PromotedAllocas.push_back(PromotedValues[i].first);
Chris Lattnerfb743a92003-03-03 17:25:18 +0000461 PromoteMemToReg(PromotedAllocas, getAnalysis<DominanceFrontier>(),
462 AA->getTargetData());
Chris Lattner2e6e7412003-02-24 03:52:32 +0000463}
464
465/// findPromotableValuesInLoop - Check the current loop for stores to definate
466/// pointers, which are not loaded and stored through may aliases. If these are
467/// found, create an alloca for the value, add it to the PromotedValues list,
468/// and keep track of the mapping from value to alloca...
469///
470void LICM::findPromotableValuesInLoop(
471 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
472 std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
473 Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
474
475 for (std::set<Value*>::iterator I = CurLBI->StoredPointers.begin(),
476 E = CurLBI->StoredPointers.end(); I != E; ++I) {
477 Value *V = *I;
478 if (isLoopInvariant(V) &&
479 CurLBI->getPointerInfo(V, *AA) == LoopBodyInfo::PointerMustStore) {
480
481 // Don't add a new entry for this stored pointer if it aliases something
482 // we have already processed.
483 std::map<Value*, AllocaInst*>::iterator V2AMI =
484 ValueToAllocaMap.lower_bound(V);
485 if (V2AMI == ValueToAllocaMap.end() || V2AMI->first != V) {
486 // Check to make sure that any loads in the loop are either NO or MUST
487 // aliases. We cannot rewrite loads that _might_ come from this memory
488 // location.
489
490 bool PointerOk = true;
491 for (std::set<Value*>::const_iterator I =CurLBI->LoadedPointers.begin(),
Chris Lattnercaadc932003-02-28 19:21:40 +0000492 E = CurLBI->LoadedPointers.end(); PointerOk && I != E; ++I)
493 switch (AA->alias(V, ~0, *I, ~0)) {
494 case AliasAnalysis::MustAlias:
495 if (V->getType() != (*I)->getType())
496 PointerOk = false;
497 break;
498 case AliasAnalysis::MayAlias:
Chris Lattner2e6e7412003-02-24 03:52:32 +0000499 PointerOk = false;
Chris Lattnercaadc932003-02-28 19:21:40 +0000500 case AliasAnalysis::NoAlias:
Chris Lattner2e6e7412003-02-24 03:52:32 +0000501 break;
502 }
503
504 if (PointerOk) {
505 const Type *Ty = cast<PointerType>(V->getType())->getElementType();
506 AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
507 PromotedValues.push_back(std::make_pair(AI, V));
508 ValueToAllocaMap.insert(V2AMI, std::make_pair(V, AI));
509
510 DEBUG(std::cerr << "LICM: Promoting value: " << *V << "\n");
511
512 // Loop over all of the loads and stores that alias this pointer,
513 // adding them to the Value2AllocaMap as well...
514 for (std::set<Value*>::const_iterator
515 I = CurLBI->LoadedPointers.begin(),
516 E = CurLBI->LoadedPointers.end(); I != E; ++I)
Chris Lattner2d0a4a42003-02-26 19:28:57 +0000517 if (AA->alias(V, ~0, *I, ~0) == AliasAnalysis::MustAlias)
Chris Lattner2e6e7412003-02-24 03:52:32 +0000518 ValueToAllocaMap[*I] = AI;
519
520 for (std::set<Value*>::const_iterator
521 I = CurLBI->StoredPointers.begin(),
522 E = CurLBI->StoredPointers.end(); I != E; ++I)
Chris Lattner2d0a4a42003-02-26 19:28:57 +0000523 if (AA->alias(V, ~0, *I, ~0) == AliasAnalysis::MustAlias)
Chris Lattner2e6e7412003-02-24 03:52:32 +0000524 ValueToAllocaMap[*I] = AI;
525 }
526 }
527 }
528 }
Chris Lattnerf5e84aa2002-08-22 21:39:55 +0000529}