blob: c9ade92804aecce006093ffbfe7561dafe49a949 [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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
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"
Chris Lattner289ba2a2004-05-23 21:20:19 +000045#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Reid Spencer557ab152007-02-05 23:32:05 +000046#include "llvm/Support/CFG.h"
47#include "llvm/Support/Compiler.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000048#include "llvm/Support/CommandLine.h"
49#include "llvm/Support/Debug.h"
50#include "llvm/ADT/Statistic.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000051#include <algorithm>
Chris Lattnerc0517682003-12-09 17:18:00 +000052using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000053
Chris Lattner79a42ac2006-12-19 21:40:18 +000054STATISTIC(NumSunk , "Number of instructions sunk out of loop");
55STATISTIC(NumHoisted , "Number of instructions hoisted out of loop");
56STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
57STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
58STATISTIC(NumPromoted , "Number of memory locations promoted to registers");
59
Chris Lattner6ec05f52002-05-10 22:44:58 +000060namespace {
Chris Lattner17895702003-10-13 05:04:27 +000061 cl::opt<bool>
62 DisablePromotion("disable-licm-promotion", cl::Hidden,
63 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner45d67d62003-02-24 03:52:32 +000064
Devang Patel69730c92007-03-07 04:41:30 +000065 struct VISIBILITY_HIDDEN LICM : public LoopPass {
66 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
Chris Lattner6ec05f52002-05-10 22:44:58 +000067
Chris Lattnerf64f2d32002-09-26 16:52:07 +000068 /// This transformation requires natural loop information & requires that
69 /// loop preheaders be inserted into the CFG...
70 ///
Chris Lattner6ec05f52002-05-10 22:44:58 +000071 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +000072 AU.setPreservesCFG();
Chris Lattner72272a72003-10-12 21:52:28 +000073 AU.addRequiredID(LoopSimplifyID);
Chris Lattnerf0ed55d2002-08-08 19:01:30 +000074 AU.addRequired<LoopInfo>();
Owen Anderson9a6091d2007-04-18 05:43:13 +000075 AU.addRequired<ETForest>();
76 AU.addRequired<DominatorTree>(); // For scalar promotion (mem2reg)
Chris Lattner0592bb72003-03-03 23:32:45 +000077 AU.addRequired<DominanceFrontier>(); // For scalar promotion (mem2reg)
Chris Lattnera51fa882002-08-22 21:39:55 +000078 AU.addRequired<AliasAnalysis>();
Chris Lattner6ec05f52002-05-10 22:44:58 +000079 }
80
Dan Gohman2ce11162007-04-17 18:21:36 +000081 bool doFinalization() {
Devang Patel69730c92007-03-07 04:41:30 +000082 LoopToAliasMap.clear();
83 return false;
84 }
85
Chris Lattner6ec05f52002-05-10 22:44:58 +000086 private:
Chris Lattnerc0517682003-12-09 17:18:00 +000087 // Various analyses that we use...
Chris Lattner45d67d62003-02-24 03:52:32 +000088 AliasAnalysis *AA; // Current AliasAnalysis information
Chris Lattnerc0517682003-12-09 17:18:00 +000089 LoopInfo *LI; // Current LoopInfo
Owen Anderson9a6091d2007-04-18 05:43:13 +000090 ETForest *ET; // ETForest for the current Loop...
Chris Lattnerc0517682003-12-09 17:18:00 +000091 DominatorTree *DT; // Dominator Tree for the current Loop...
Chris Lattnera906bac2003-10-05 21:20:13 +000092 DominanceFrontier *DF; // Current Dominance Frontier
Chris Lattnerc0517682003-12-09 17:18:00 +000093
94 // State that is updated as we process loops
Chris Lattner45d67d62003-02-24 03:52:32 +000095 bool Changed; // Set to true when we change anything.
96 BasicBlock *Preheader; // The preheader block of the current loop...
97 Loop *CurLoop; // The current loop we are working on...
Chris Lattner0592bb72003-03-03 23:32:45 +000098 AliasSetTracker *CurAST; // AliasSet information for the current loop...
Devang Patel69730c92007-03-07 04:41:30 +000099 std::map<Loop *, AliasSetTracker *> LoopToAliasMap;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000100
Chris Lattner547192d62003-12-19 07:22:45 +0000101 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
102 /// dominated by the specified block, and that are in the current loop) in
Owen Anderson9a6091d2007-04-18 05:43:13 +0000103 /// reverse depth first order w.r.t the ETForest. This allows us to
Chris Lattner547192d62003-12-19 07:22:45 +0000104 /// visit uses before definitions, allowing us to sink a loop body in one
105 /// pass without iteration.
106 ///
Owen Anderson9a6091d2007-04-18 05:43:13 +0000107 void SinkRegion(BasicBlock *BB);
Chris Lattner547192d62003-12-19 07:22:45 +0000108
Chris Lattner64437692002-09-29 21:46:09 +0000109 /// HoistRegion - Walk the specified region of the CFG (defined by all
110 /// blocks dominated by the specified block, and that are in the current
Owen Anderson9a6091d2007-04-18 05:43:13 +0000111 /// loop) in depth first order w.r.t the ETForest. This allows us to
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000112 /// visit definitions before uses, allowing us to hoist a loop body in one
Chris Lattner64437692002-09-29 21:46:09 +0000113 /// pass without iteration.
114 ///
Owen Anderson9a6091d2007-04-18 05:43:13 +0000115 void HoistRegion(BasicBlock *BB);
Chris Lattner64437692002-09-29 21:46:09 +0000116
Chris Lattner05e86302002-09-29 22:26:07 +0000117 /// inSubLoop - Little predicate that returns true if the specified basic
118 /// block is in a subloop of the current one, not the current one itself.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000119 ///
Chris Lattner05e86302002-09-29 22:26:07 +0000120 bool inSubLoop(BasicBlock *BB) {
121 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000122 for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
123 if ((*I)->contains(BB))
Chris Lattner05e86302002-09-29 22:26:07 +0000124 return true; // A subloop actually contains this block!
125 return false;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000126 }
127
Chris Lattneraaaea512003-12-10 06:41:05 +0000128 /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
129 /// specified exit block of the loop is dominated by the specified block
130 /// that is in the body of the loop. We use these constraints to
131 /// dramatically limit the amount of the dominator tree that needs to be
132 /// searched.
133 bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
134 BasicBlock *BlockInLoop) const {
135 // If the block in the loop is the loop header, it must be dominated!
136 BasicBlock *LoopHeader = CurLoop->getHeader();
137 if (BlockInLoop == LoopHeader)
138 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000139
Owen Anderson9a6091d2007-04-18 05:43:13 +0000140 BasicBlock *IDom = ExitBlock;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000141
Chris Lattneraaaea512003-12-10 06:41:05 +0000142 // Because the exit block is not in the loop, we know we have to get _at
Chris Lattner289ba2a2004-05-23 21:20:19 +0000143 // least_ its immediate dominator.
Chris Lattneraaaea512003-12-10 06:41:05 +0000144 do {
145 // Get next Immediate Dominator.
Owen Anderson9a6091d2007-04-18 05:43:13 +0000146 IDom = ET->getIDom(IDom);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000147
Chris Lattneraaaea512003-12-10 06:41:05 +0000148 // If we have got to the header of the loop, then the instructions block
149 // did not dominate the exit node, so we can't hoist it.
Owen Anderson9a6091d2007-04-18 05:43:13 +0000150 if (IDom == LoopHeader)
Chris Lattneraaaea512003-12-10 06:41:05 +0000151 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000152
Owen Anderson9a6091d2007-04-18 05:43:13 +0000153 } while (IDom != BlockInLoop);
Chris Lattneraaaea512003-12-10 06:41:05 +0000154
155 return true;
156 }
157
158 /// sink - When an instruction is found to only be used outside of the loop,
159 /// this function moves it to the exit blocks and patches up SSA form as
160 /// needed.
161 ///
162 void sink(Instruction &I);
163
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000164 /// hoist - When an instruction is found to only use loop invariant operands
165 /// that is safe to hoist, this instruction is called to do the dirty work.
166 ///
Chris Lattner113f4f42002-06-25 16:13:24 +0000167 void hoist(Instruction &I);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000168
Chris Lattneraaaea512003-12-10 06:41:05 +0000169 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
170 /// is not a trapping instruction or if it is a trapping instruction and is
171 /// guaranteed to execute.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000172 ///
Chris Lattneraaaea512003-12-10 06:41:05 +0000173 bool isSafeToExecuteUnconditionally(Instruction &I);
Tanya Lattner57c03df2003-08-05 18:45:46 +0000174
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000175 /// pointerInvalidatedByLoop - Return true if the body of this loop may
176 /// store into the memory location pointed to by V.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000177 ///
Chris Lattnerb1374092004-11-26 21:20:09 +0000178 bool pointerInvalidatedByLoop(Value *V, unsigned Size) {
Chris Lattner0592bb72003-03-03 23:32:45 +0000179 // Check to see if any of the basic blocks in CurLoop invalidate *V.
Chris Lattnerb1374092004-11-26 21:20:09 +0000180 return CurAST->getAliasSetForPointer(V, Size).isMod();
Chris Lattner45d67d62003-02-24 03:52:32 +0000181 }
Chris Lattnera51fa882002-08-22 21:39:55 +0000182
Chris Lattneraaaea512003-12-10 06:41:05 +0000183 bool canSinkOrHoistInst(Instruction &I);
184 bool isLoopInvariantInst(Instruction &I);
185 bool isNotUsedInLoop(Instruction &I);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000186
Chris Lattner45d67d62003-02-24 03:52:32 +0000187 /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
188 /// to scalars as we can.
189 ///
190 void PromoteValuesInLoop();
191
Chris Lattnera3465782004-09-15 01:04:07 +0000192 /// FindPromotableValuesInLoop - Check the current loop for stores to
Misha Brukman9b8d3392003-09-11 15:32:37 +0000193 /// definite pointers, which are not loaded and stored through may aliases.
Chris Lattner45d67d62003-02-24 03:52:32 +0000194 /// If these are found, create an alloca for the value, add it to the
195 /// PromotedValues list, and keep track of the mapping from value to
196 /// alloca...
197 ///
Chris Lattnera3465782004-09-15 01:04:07 +0000198 void FindPromotableValuesInLoop(
Chris Lattner45d67d62003-02-24 03:52:32 +0000199 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
200 std::map<Value*, AllocaInst*> &Val2AlMap);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000201 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000202
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000203 RegisterPass<LICM> X("licm", "Loop Invariant Code Motion");
Chris Lattner6ec05f52002-05-10 22:44:58 +0000204}
205
Devang Patel69730c92007-03-07 04:41:30 +0000206LoopPass *llvm::createLICMPass() { return new LICM(); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000207
Devang Patel69730c92007-03-07 04:41:30 +0000208/// Hoist expressions out of the specified loop...
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000209///
Devang Patel69730c92007-03-07 04:41:30 +0000210bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
Chris Lattner45d67d62003-02-24 03:52:32 +0000211 Changed = false;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000212
Chris Lattner45d67d62003-02-24 03:52:32 +0000213 // Get our Loop and Alias Analysis information...
214 LI = &getAnalysis<LoopInfo>();
Chris Lattnera51fa882002-08-22 21:39:55 +0000215 AA = &getAnalysis<AliasAnalysis>();
Chris Lattnera906bac2003-10-05 21:20:13 +0000216 DF = &getAnalysis<DominanceFrontier>();
Owen Anderson9a6091d2007-04-18 05:43:13 +0000217 ET = &getAnalysis<ETForest>();
Tanya Lattnerdc3c9a82003-08-05 20:39:02 +0000218 DT = &getAnalysis<DominatorTree>();
Chris Lattnera51fa882002-08-22 21:39:55 +0000219
Devang Patel69730c92007-03-07 04:41:30 +0000220 CurAST = new AliasSetTracker(*AA);
221 // Collect Alias info frmo subloops
222 for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
223 LoopItr != LoopItrE; ++LoopItr) {
224 Loop *InnerL = *LoopItr;
225 AliasSetTracker *InnerAST = LoopToAliasMap[InnerL];
226 assert (InnerAST && "Where is my AST?");
227
228 // What if InnerLoop was modified by other passes ?
229 CurAST->add(*InnerAST);
Chris Lattner45d67d62003-02-24 03:52:32 +0000230 }
Devang Patel69730c92007-03-07 04:41:30 +0000231
Chris Lattner6ec05f52002-05-10 22:44:58 +0000232 CurLoop = L;
233
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000234 // Get the preheader block to move instructions into...
235 Preheader = L->getLoopPreheader();
236 assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
237
Chris Lattner45d67d62003-02-24 03:52:32 +0000238 // Loop over the body of this loop, looking for calls, invokes, and stores.
Chris Lattner0592bb72003-03-03 23:32:45 +0000239 // Because subloops have already been incorporated into AST, we skip blocks in
Chris Lattner45d67d62003-02-24 03:52:32 +0000240 // subloops.
241 //
Chris Lattneraaaea512003-12-10 06:41:05 +0000242 for (std::vector<BasicBlock*>::const_iterator I = L->getBlocks().begin(),
243 E = L->getBlocks().end(); I != E; ++I)
Chris Lattner45d67d62003-02-24 03:52:32 +0000244 if (LI->getLoopFor(*I) == L) // Ignore blocks in subloops...
Chris Lattner28d921d2007-04-14 23:32:02 +0000245 CurAST->add(**I); // Incorporate the specified basic block
Chris Lattner45d67d62003-02-24 03:52:32 +0000246
Chris Lattner6ec05f52002-05-10 22:44:58 +0000247 // We want to visit all of the instructions in this loop... that are not parts
248 // of our subloops (they have already had their invariants hoisted out of
249 // their loop, into this loop, so there is no need to process the BODIES of
250 // the subloops).
251 //
Chris Lattner64437692002-09-29 21:46:09 +0000252 // Traverse the body of the loop in depth first order on the dominator tree so
253 // that we are guaranteed to see definitions before we see uses. This allows
Chris Lattner547192d62003-12-19 07:22:45 +0000254 // us to sink instructions in one pass, without iteration. AFter sinking
255 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner64437692002-09-29 21:46:09 +0000256 //
Owen Anderson9a6091d2007-04-18 05:43:13 +0000257 SinkRegion(L->getHeader());
258 HoistRegion(L->getHeader());
Chris Lattner6ec05f52002-05-10 22:44:58 +0000259
Chris Lattner45d67d62003-02-24 03:52:32 +0000260 // Now that all loop invariants have been removed from the loop, promote any
261 // memory references to scalars that we can...
262 if (!DisablePromotion)
263 PromoteValuesInLoop();
264
Chris Lattner6ec05f52002-05-10 22:44:58 +0000265 // Clear out loops state information for the next iteration
266 CurLoop = 0;
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000267 Preheader = 0;
Devang Patel69730c92007-03-07 04:41:30 +0000268
269 LoopToAliasMap[L] = CurAST;
270 return Changed;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000271}
272
Chris Lattner547192d62003-12-19 07:22:45 +0000273/// SinkRegion - Walk the specified region of the CFG (defined by all blocks
274/// dominated by the specified block, and that are in the current loop) in
Owen Anderson9a6091d2007-04-18 05:43:13 +0000275/// reverse depth first order w.r.t the ETForest. This allows us to visit
Chris Lattner547192d62003-12-19 07:22:45 +0000276/// uses before definitions, allowing us to sink a loop body in one pass without
277/// iteration.
278///
Owen Anderson9a6091d2007-04-18 05:43:13 +0000279void LICM::SinkRegion(BasicBlock *BB) {
280 assert(BB != 0 && "Null sink block?");
Chris Lattner547192d62003-12-19 07:22:45 +0000281
282 // If this subregion is not in the top level loop at all, exit.
283 if (!CurLoop->contains(BB)) return;
284
285 // We are processing blocks in reverse dfo, so process children first...
Owen Anderson9a6091d2007-04-18 05:43:13 +0000286 std::vector<BasicBlock*> Children;
287 ET->getChildren(BB, Children);
Chris Lattner547192d62003-12-19 07:22:45 +0000288 for (unsigned i = 0, e = Children.size(); i != e; ++i)
289 SinkRegion(Children[i]);
290
291 // Only need to process the contents of this block if it is not part of a
292 // subloop (which would already have been processed).
293 if (inSubLoop(BB)) return;
294
Chris Lattner91846012003-12-19 08:18:16 +0000295 for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
296 Instruction &I = *--II;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000297
Chris Lattner547192d62003-12-19 07:22:45 +0000298 // Check to see if we can sink this instruction to the exit blocks
299 // of the loop. We can do this if the all users of the instruction are
300 // outside of the loop. In this case, it doesn't even matter if the
301 // operands of the instruction are loop invariant.
302 //
Chris Lattnerfaf77912005-03-25 00:22:36 +0000303 if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
Chris Lattner91846012003-12-19 08:18:16 +0000304 ++II;
Chris Lattner547192d62003-12-19 07:22:45 +0000305 sink(I);
Chris Lattner91846012003-12-19 08:18:16 +0000306 }
Chris Lattner547192d62003-12-19 07:22:45 +0000307 }
308}
309
310
Chris Lattner64437692002-09-29 21:46:09 +0000311/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
312/// dominated by the specified block, and that are in the current loop) in depth
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000313/// first order w.r.t the DominatorTree. This allows us to visit definitions
Chris Lattner64437692002-09-29 21:46:09 +0000314/// before uses, allowing us to hoist a loop body in one pass without iteration.
315///
Owen Anderson9a6091d2007-04-18 05:43:13 +0000316void LICM::HoistRegion(BasicBlock *BB) {
317 assert(BB != 0 && "Null hoist block?");
Chris Lattner64437692002-09-29 21:46:09 +0000318
Chris Lattner05e86302002-09-29 22:26:07 +0000319 // If this subregion is not in the top level loop at all, exit.
Chris Lattner65c11932003-12-09 19:32:44 +0000320 if (!CurLoop->contains(BB)) return;
Chris Lattner64437692002-09-29 21:46:09 +0000321
Chris Lattneraaaea512003-12-10 06:41:05 +0000322 // Only need to process the contents of this block if it is not part of a
323 // subloop (which would already have been processed).
Chris Lattner65c11932003-12-09 19:32:44 +0000324 if (!inSubLoop(BB))
Chris Lattneraaaea512003-12-10 06:41:05 +0000325 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
326 Instruction &I = *II++;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000327
Chris Lattner547192d62003-12-19 07:22:45 +0000328 // Try hoisting the instruction out to the preheader. We can only do this
329 // if all of the operands of the instruction are loop invariant and if it
330 // is safe to hoist the instruction.
331 //
Misha Brukmanb1c93172005-04-21 23:48:37 +0000332 if (isLoopInvariantInst(I) && canSinkOrHoistInst(I) &&
Chris Lattner547192d62003-12-19 07:22:45 +0000333 isSafeToExecuteUnconditionally(I))
Chris Lattner49771a02006-06-26 19:10:05 +0000334 hoist(I);
Chris Lattneraaaea512003-12-10 06:41:05 +0000335 }
Chris Lattner64437692002-09-29 21:46:09 +0000336
Owen Anderson9a6091d2007-04-18 05:43:13 +0000337 std::vector<BasicBlock*> Children;
338 ET->getChildren(BB, Children);
Chris Lattner64437692002-09-29 21:46:09 +0000339 for (unsigned i = 0, e = Children.size(); i != e; ++i)
Chris Lattner42ad6462004-06-19 20:23:35 +0000340 HoistRegion(Children[i]);
Chris Lattner64437692002-09-29 21:46:09 +0000341}
342
Chris Lattneraaaea512003-12-10 06:41:05 +0000343/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
344/// instruction.
345///
346bool LICM::canSinkOrHoistInst(Instruction &I) {
Chris Lattner65c11932003-12-09 19:32:44 +0000347 // Loads have extra constraints we have to verify before we can hoist them.
348 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
349 if (LI->isVolatile())
350 return false; // Don't hoist volatile loads!
351
352 // Don't hoist loads which have may-aliased stores in loop.
Chris Lattnerb1374092004-11-26 21:20:09 +0000353 unsigned Size = 0;
354 if (LI->getType()->isSized())
355 Size = AA->getTargetData().getTypeSize(LI->getType());
356 return !pointerInvalidatedByLoop(LI->getOperand(0), Size);
Chris Lattner20cda262004-03-15 04:11:30 +0000357 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
358 // Handle obvious cases efficiently.
359 if (Function *Callee = CI->getCalledFunction()) {
Chris Lattnerb17f3e12004-12-15 07:22:25 +0000360 AliasAnalysis::ModRefBehavior Behavior =AA->getModRefBehavior(Callee, CI);
361 if (Behavior == AliasAnalysis::DoesNotAccessMemory)
Chris Lattner20cda262004-03-15 04:11:30 +0000362 return true;
Chris Lattnerb17f3e12004-12-15 07:22:25 +0000363 else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
Chris Lattner20cda262004-03-15 04:11:30 +0000364 // If this call only reads from memory and there are no writes to memory
365 // in the loop, we can hoist or sink the call as appropriate.
366 bool FoundMod = false;
367 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
368 I != E; ++I) {
369 AliasSet &AS = *I;
370 if (!AS.isForwardingAliasSet() && AS.isMod()) {
371 FoundMod = true;
372 break;
373 }
374 }
375 if (!FoundMod) return true;
376 }
377 }
378
379 // FIXME: This should use mod/ref information to see if we can hoist or sink
380 // the call.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000381
Chris Lattner20cda262004-03-15 04:11:30 +0000382 return false;
Chris Lattner65c11932003-12-09 19:32:44 +0000383 }
384
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000385 // Otherwise these instructions are hoistable/sinkable
Reid Spencer2341c222007-02-02 02:16:23 +0000386 return isa<BinaryOperator>(I) || isa<CastInst>(I) ||
Reid Spencer266e42b2006-12-23 06:05:41 +0000387 isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I);
Chris Lattneraaaea512003-12-10 06:41:05 +0000388}
389
390/// isNotUsedInLoop - Return true if the only users of this instruction are
391/// outside of the loop. If this is true, we can sink the instruction to the
392/// exit blocks of the loop.
393///
394bool LICM::isNotUsedInLoop(Instruction &I) {
Chris Lattner34399dd2003-12-11 22:23:32 +0000395 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
396 Instruction *User = cast<Instruction>(*UI);
397 if (PHINode *PN = dyn_cast<PHINode>(User)) {
398 // PHI node uses occur in predecessor blocks!
399 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
400 if (PN->getIncomingValue(i) == &I)
401 if (CurLoop->contains(PN->getIncomingBlock(i)))
402 return false;
403 } else if (CurLoop->contains(User->getParent())) {
Chris Lattneraaaea512003-12-10 06:41:05 +0000404 return false;
Chris Lattner34399dd2003-12-11 22:23:32 +0000405 }
406 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000407 return true;
408}
409
410
411/// isLoopInvariantInst - Return true if all operands of this instruction are
412/// loop invariant. We also filter out non-hoistable instructions here just for
413/// efficiency.
414///
415bool LICM::isLoopInvariantInst(Instruction &I) {
416 // The instruction is loop invariant if all of its operands are loop-invariant
417 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Chris Lattnerfc44a252004-04-18 22:46:08 +0000418 if (!CurLoop->isLoopInvariant(I.getOperand(i)))
Chris Lattneraaaea512003-12-10 06:41:05 +0000419 return false;
420
Chris Lattner65c11932003-12-09 19:32:44 +0000421 // If we got this far, the instruction is loop invariant!
422 return true;
423}
424
Chris Lattneraaaea512003-12-10 06:41:05 +0000425/// sink - When an instruction is found to only be used outside of the loop,
Chris Lattner91846012003-12-19 08:18:16 +0000426/// this function moves it to the exit blocks and patches up SSA form as needed.
427/// This method is guaranteed to remove the original instruction from its
428/// position, and may either delete it or move it to outside of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000429///
430void LICM::sink(Instruction &I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000431 DOUT << "LICM sinking instruction: " << I;
Chris Lattneraaaea512003-12-10 06:41:05 +0000432
Chris Lattner35eaa552004-04-18 22:15:13 +0000433 std::vector<BasicBlock*> ExitBlocks;
434 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattner55c21132003-12-10 20:43:29 +0000435
436 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner20cda262004-03-15 04:11:30 +0000437 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattner55c21132003-12-10 20:43:29 +0000438 ++NumSunk;
439 Changed = true;
440
Chris Lattneraaaea512003-12-10 06:41:05 +0000441 // The case where there is only a single exit node of this loop is common
442 // enough that we handle it as a special (more efficient) case. It is more
443 // efficient to handle because there are no PHI nodes that need to be placed.
444 if (ExitBlocks.size() == 1) {
445 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
446 // Instruction is not used, just delete it.
Chris Lattner289ba2a2004-05-23 21:20:19 +0000447 CurAST->deleteValue(&I);
Chris Lattner1d7ec202006-09-12 19:17:09 +0000448 if (!I.use_empty()) // If I has users in unreachable blocks, eliminate.
449 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner49771a02006-06-26 19:10:05 +0000450 I.eraseFromParent();
Chris Lattneraaaea512003-12-10 06:41:05 +0000451 } else {
452 // Move the instruction to the start of the exit block, after any PHI
453 // nodes in it.
Chris Lattner49771a02006-06-26 19:10:05 +0000454 I.removeFromParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000455
Chris Lattneraaaea512003-12-10 06:41:05 +0000456 BasicBlock::iterator InsertPt = ExitBlocks[0]->begin();
457 while (isa<PHINode>(InsertPt)) ++InsertPt;
458 ExitBlocks[0]->getInstList().insert(InsertPt, &I);
459 }
460 } else if (ExitBlocks.size() == 0) {
461 // The instruction is actually dead if there ARE NO exit blocks.
Chris Lattner289ba2a2004-05-23 21:20:19 +0000462 CurAST->deleteValue(&I);
Chris Lattner1d7ec202006-09-12 19:17:09 +0000463 if (!I.use_empty()) // If I has users in unreachable blocks, eliminate.
464 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner49771a02006-06-26 19:10:05 +0000465 I.eraseFromParent();
Chris Lattneraaaea512003-12-10 06:41:05 +0000466 } else {
467 // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
468 // do all of the hard work of inserting PHI nodes as necessary. We convert
469 // the value into a stack object to get it to do this.
470
471 // Firstly, we create a stack object to hold the value...
Chris Lattner50eb7712004-07-27 07:38:32 +0000472 AllocaInst *AI = 0;
Chris Lattneraaaea512003-12-10 06:41:05 +0000473
Chris Lattner50eb7712004-07-27 07:38:32 +0000474 if (I.getType() != Type::VoidTy)
475 AI = new AllocaInst(I.getType(), 0, I.getName(),
Dan Gohmandcb291f2007-03-22 16:38:57 +0000476 I.getParent()->getParent()->getEntryBlock().begin());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000477
Chris Lattneraaaea512003-12-10 06:41:05 +0000478 // Secondly, insert load instructions for each use of the instruction
479 // outside of the loop.
480 while (!I.use_empty()) {
481 Instruction *U = cast<Instruction>(I.use_back());
482
483 // If the user is a PHI Node, we actually have to insert load instructions
484 // in all predecessor blocks, not in the PHI block itself!
485 if (PHINode *UPN = dyn_cast<PHINode>(U)) {
486 // Only insert into each predecessor once, so that we don't have
487 // different incoming values from the same block!
488 std::map<BasicBlock*, Value*> InsertedBlocks;
489 for (unsigned i = 0, e = UPN->getNumIncomingValues(); i != e; ++i)
490 if (UPN->getIncomingValue(i) == &I) {
491 BasicBlock *Pred = UPN->getIncomingBlock(i);
492 Value *&PredVal = InsertedBlocks[Pred];
493 if (!PredVal) {
494 // Insert a new load instruction right before the terminator in
495 // the predecessor block.
496 PredVal = new LoadInst(AI, "", Pred->getTerminator());
497 }
498
499 UPN->setIncomingValue(i, PredVal);
500 }
501
502 } else {
503 LoadInst *L = new LoadInst(AI, "", U);
504 U->replaceUsesOfWith(&I, L);
505 }
506 }
507
508 // Thirdly, insert a copy of the instruction in each exit block of the loop
509 // that is dominated by the instruction, storing the result into the memory
510 // location. Be careful not to insert the instruction into any particular
511 // basic block more than once.
512 std::set<BasicBlock*> InsertedBlocks;
513 BasicBlock *InstOrigBB = I.getParent();
514
515 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
516 BasicBlock *ExitBlock = ExitBlocks[i];
517
518 if (isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB)) {
Chris Lattneraaaea512003-12-10 06:41:05 +0000519 // If we haven't already processed this exit block, do so now.
Chris Lattner63643142003-12-10 16:58:24 +0000520 if (InsertedBlocks.insert(ExitBlock).second) {
Chris Lattneraaaea512003-12-10 06:41:05 +0000521 // Insert the code after the last PHI node...
522 BasicBlock::iterator InsertPt = ExitBlock->begin();
523 while (isa<PHINode>(InsertPt)) ++InsertPt;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000524
Chris Lattneraaaea512003-12-10 06:41:05 +0000525 // If this is the first exit block processed, just move the original
526 // instruction, otherwise clone the original instruction and insert
527 // the copy.
528 Instruction *New;
Chris Lattner6281fd32003-12-10 22:35:56 +0000529 if (InsertedBlocks.size() == 1) {
Chris Lattner49771a02006-06-26 19:10:05 +0000530 I.removeFromParent();
Chris Lattneraaaea512003-12-10 06:41:05 +0000531 ExitBlock->getInstList().insert(InsertPt, &I);
532 New = &I;
533 } else {
534 New = I.clone();
Chris Lattnerfaf77912005-03-25 00:22:36 +0000535 CurAST->copyValue(&I, New);
Chris Lattner50eb7712004-07-27 07:38:32 +0000536 if (!I.getName().empty())
537 New->setName(I.getName()+".le");
Chris Lattneraaaea512003-12-10 06:41:05 +0000538 ExitBlock->getInstList().insert(InsertPt, New);
539 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000540
Chris Lattneraaaea512003-12-10 06:41:05 +0000541 // Now that we have inserted the instruction, store it into the alloca
Chris Lattner50eb7712004-07-27 07:38:32 +0000542 if (AI) new StoreInst(New, AI, InsertPt);
Chris Lattneraaaea512003-12-10 06:41:05 +0000543 }
544 }
545 }
Chris Lattner91846012003-12-19 08:18:16 +0000546
547 // If the instruction doesn't dominate any exit blocks, it must be dead.
548 if (InsertedBlocks.empty()) {
Chris Lattner289ba2a2004-05-23 21:20:19 +0000549 CurAST->deleteValue(&I);
Chris Lattner49771a02006-06-26 19:10:05 +0000550 I.eraseFromParent();
Chris Lattner91846012003-12-19 08:18:16 +0000551 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000552
Chris Lattneraaaea512003-12-10 06:41:05 +0000553 // Finally, promote the fine value to SSA form.
Chris Lattner50eb7712004-07-27 07:38:32 +0000554 if (AI) {
555 std::vector<AllocaInst*> Allocas;
556 Allocas.push_back(AI);
Chris Lattnera3465782004-09-15 01:04:07 +0000557 PromoteMemToReg(Allocas, *DT, *DF, AA->getTargetData(), CurAST);
Chris Lattner50eb7712004-07-27 07:38:32 +0000558 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000559 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000560}
Chris Lattner64437692002-09-29 21:46:09 +0000561
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000562/// hoist - When an instruction is found to only use loop invariant operands
563/// that is safe to hoist, this instruction is called to do the dirty work.
564///
Chris Lattneraaaea512003-12-10 06:41:05 +0000565void LICM::hoist(Instruction &I) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000566 DOUT << "LICM hoisting to " << Preheader->getName() << ": " << I;
Chris Lattner65c11932003-12-09 19:32:44 +0000567
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000568 // Remove the instruction from its current basic block... but don't delete the
569 // instruction.
Chris Lattner49771a02006-06-26 19:10:05 +0000570 I.removeFromParent();
Chris Lattner6ec05f52002-05-10 22:44:58 +0000571
Chris Lattner718b2212002-09-26 16:38:03 +0000572 // Insert the new node in Preheader, before the terminator.
Chris Lattneraaaea512003-12-10 06:41:05 +0000573 Preheader->getInstList().insert(Preheader->getTerminator(), &I);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000574
Chris Lattneraaaea512003-12-10 06:41:05 +0000575 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner20cda262004-03-15 04:11:30 +0000576 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattner718b2212002-09-26 16:38:03 +0000577 ++NumHoisted;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000578 Changed = true;
579}
580
Chris Lattneraaaea512003-12-10 06:41:05 +0000581/// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
582/// not a trapping instruction or if it is a trapping instruction and is
583/// guaranteed to execute.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000584///
Chris Lattneraaaea512003-12-10 06:41:05 +0000585bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
Chris Lattnerc0517682003-12-09 17:18:00 +0000586 // If it is not a trapping instruction, it is always safe to hoist.
587 if (!Inst.isTrapping()) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000588
Chris Lattnerc0517682003-12-09 17:18:00 +0000589 // Otherwise we have to check to make sure that the instruction dominates all
590 // of the exit blocks. If it doesn't, then there is a path out of the loop
591 // which does not execute this instruction, so we can't hoist it.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000592
Chris Lattnerc0517682003-12-09 17:18:00 +0000593 // If the instruction is in the header block for the loop (which is very
594 // common), it is always guaranteed to dominate the exit blocks. Since this
595 // is a common case, and can save some work, check it now.
Chris Lattneraaaea512003-12-10 06:41:05 +0000596 if (Inst.getParent() == CurLoop->getHeader())
Chris Lattnerc0517682003-12-09 17:18:00 +0000597 return true;
Tanya Lattner57c03df2003-08-05 18:45:46 +0000598
Chris Lattner6e455602004-11-29 21:26:12 +0000599 // It's always safe to load from a global or alloca.
600 if (isa<LoadInst>(Inst))
601 if (isa<AllocationInst>(Inst.getOperand(0)) ||
602 isa<GlobalVariable>(Inst.getOperand(0)))
603 return true;
604
Chris Lattnerc0517682003-12-09 17:18:00 +0000605 // Get the exit blocks for the current loop.
Chris Lattner35eaa552004-04-18 22:15:13 +0000606 std::vector<BasicBlock*> ExitBlocks;
607 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattnerc0517682003-12-09 17:18:00 +0000608
Owen Anderson9a6091d2007-04-18 05:43:13 +0000609 // For each exit block, walk up the ET until the
Chris Lattnerc0517682003-12-09 17:18:00 +0000610 // instruction's basic block is found or we exit the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000611 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
612 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
613 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000614
Tanya Lattner57c03df2003-08-05 18:45:46 +0000615 return true;
616}
617
Chris Lattnerd771fdf2002-09-26 16:19:31 +0000618
Chris Lattner45d67d62003-02-24 03:52:32 +0000619/// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
620/// stores out of the loop and moving loads to before the loop. We do this by
621/// looping over the stores in the loop, looking for stores to Must pointers
622/// which are loop invariant. We promote these memory locations to use allocas
623/// instead. These allocas can easily be raised to register values by the
624/// PromoteMem2Reg functionality.
625///
626void LICM::PromoteValuesInLoop() {
627 // PromotedValues - List of values that are promoted out of the loop. Each
Chris Lattner216c7b82003-09-10 05:29:43 +0000628 // value has an alloca instruction for it, and a canonical version of the
Chris Lattner45d67d62003-02-24 03:52:32 +0000629 // pointer.
630 std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
631 std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
632
Chris Lattnera3465782004-09-15 01:04:07 +0000633 FindPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
634 if (ValueToAllocaMap.empty()) return; // If there are values to promote.
Chris Lattner45d67d62003-02-24 03:52:32 +0000635
636 Changed = true;
637 NumPromoted += PromotedValues.size();
638
Chris Lattnera3465782004-09-15 01:04:07 +0000639 std::vector<Value*> PointerValueNumbers;
640
Chris Lattner45d67d62003-02-24 03:52:32 +0000641 // Emit a copy from the value into the alloca'd value in the loop preheader
642 TerminatorInst *LoopPredInst = Preheader->getTerminator();
643 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
Chris Lattnera3465782004-09-15 01:04:07 +0000644 Value *Ptr = PromotedValues[i].second;
645
646 // If we are promoting a pointer value, update alias information for the
647 // inserted load.
648 Value *LoadValue = 0;
649 if (isa<PointerType>(cast<PointerType>(Ptr->getType())->getElementType())) {
650 // Locate a load or store through the pointer, and assign the same value
651 // to LI as we are loading or storing. Since we know that the value is
652 // stored in this loop, this will always succeed.
653 for (Value::use_iterator UI = Ptr->use_begin(), E = Ptr->use_end();
654 UI != E; ++UI)
655 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
656 LoadValue = LI;
657 break;
658 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattnerf11216d2004-09-15 02:34:40 +0000659 if (SI->getOperand(1) == Ptr) {
Chris Lattnera3465782004-09-15 01:04:07 +0000660 LoadValue = SI->getOperand(0);
661 break;
662 }
663 }
664 assert(LoadValue && "No store through the pointer found!");
665 PointerValueNumbers.push_back(LoadValue); // Remember this for later.
666 }
667
668 // Load from the memory we are promoting.
669 LoadInst *LI = new LoadInst(Ptr, Ptr->getName()+".promoted", LoopPredInst);
670
671 if (LoadValue) CurAST->copyValue(LoadValue, LI);
672
673 // Store into the temporary alloca.
Chris Lattner45d67d62003-02-24 03:52:32 +0000674 new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
675 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000676
Chris Lattner45d67d62003-02-24 03:52:32 +0000677 // Scan the basic blocks in the loop, replacing uses of our pointers with
Chris Lattneredda1af2003-12-10 15:56:24 +0000678 // uses of the allocas in question.
Chris Lattner45d67d62003-02-24 03:52:32 +0000679 //
680 const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
681 for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
682 E = LoopBBs.end(); I != E; ++I) {
683 // Rewrite all loads and stores in the block of the pointer...
684 for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
685 II != E; ++II) {
Chris Lattner889f6202003-04-23 16:37:45 +0000686 if (LoadInst *L = dyn_cast<LoadInst>(II)) {
Chris Lattner45d67d62003-02-24 03:52:32 +0000687 std::map<Value*, AllocaInst*>::iterator
688 I = ValueToAllocaMap.find(L->getOperand(0));
689 if (I != ValueToAllocaMap.end())
690 L->setOperand(0, I->second); // Rewrite load instruction...
Chris Lattner889f6202003-04-23 16:37:45 +0000691 } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
Chris Lattner45d67d62003-02-24 03:52:32 +0000692 std::map<Value*, AllocaInst*>::iterator
693 I = ValueToAllocaMap.find(S->getOperand(1));
694 if (I != ValueToAllocaMap.end())
695 S->setOperand(1, I->second); // Rewrite store instruction...
696 }
697 }
Chris Lattner45d67d62003-02-24 03:52:32 +0000698 }
699
Chris Lattneredda1af2003-12-10 15:56:24 +0000700 // Now that the body of the loop uses the allocas instead of the original
701 // memory locations, insert code to copy the alloca value back into the
702 // original memory location on all exits from the loop. Note that we only
703 // want to insert one copy of the code in each exit block, though the loop may
704 // exit to the same block more than once.
705 //
706 std::set<BasicBlock*> ProcessedBlocks;
707
Chris Lattner35eaa552004-04-18 22:15:13 +0000708 std::vector<BasicBlock*> ExitBlocks;
709 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattneredda1af2003-12-10 15:56:24 +0000710 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
Chris Lattner48b4b852003-12-10 16:57:24 +0000711 if (ProcessedBlocks.insert(ExitBlocks[i]).second) {
Chris Lattnera3465782004-09-15 01:04:07 +0000712 // Copy all of the allocas into their memory locations.
Chris Lattneredda1af2003-12-10 15:56:24 +0000713 BasicBlock::iterator BI = ExitBlocks[i]->begin();
714 while (isa<PHINode>(*BI))
Chris Lattnera3465782004-09-15 01:04:07 +0000715 ++BI; // Skip over all of the phi nodes in the block.
Chris Lattneredda1af2003-12-10 15:56:24 +0000716 Instruction *InsertPos = BI;
Chris Lattnera3465782004-09-15 01:04:07 +0000717 unsigned PVN = 0;
Chris Lattneredda1af2003-12-10 15:56:24 +0000718 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
Chris Lattnera3465782004-09-15 01:04:07 +0000719 // Load from the alloca.
Chris Lattneredda1af2003-12-10 15:56:24 +0000720 LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
Chris Lattnera3465782004-09-15 01:04:07 +0000721
722 // If this is a pointer type, update alias info appropriately.
723 if (isa<PointerType>(LI->getType()))
724 CurAST->copyValue(PointerValueNumbers[PVN++], LI);
725
726 // Store into the memory we promoted.
Chris Lattneredda1af2003-12-10 15:56:24 +0000727 new StoreInst(LI, PromotedValues[i].second, InsertPos);
728 }
729 }
730
Chris Lattner45d67d62003-02-24 03:52:32 +0000731 // Now that we have done the deed, use the mem2reg functionality to promote
Chris Lattnera3465782004-09-15 01:04:07 +0000732 // all of the new allocas we just created into real SSA registers.
Chris Lattner45d67d62003-02-24 03:52:32 +0000733 //
734 std::vector<AllocaInst*> PromotedAllocas;
735 PromotedAllocas.reserve(PromotedValues.size());
736 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
737 PromotedAllocas.push_back(PromotedValues[i].first);
Chris Lattnera3465782004-09-15 01:04:07 +0000738 PromoteMemToReg(PromotedAllocas, *DT, *DF, AA->getTargetData(), CurAST);
Chris Lattner45d67d62003-02-24 03:52:32 +0000739}
740
Chris Lattnera3465782004-09-15 01:04:07 +0000741/// FindPromotableValuesInLoop - Check the current loop for stores to definite
Chris Lattner45d67d62003-02-24 03:52:32 +0000742/// pointers, which are not loaded and stored through may aliases. If these are
743/// found, create an alloca for the value, add it to the PromotedValues list,
Chris Lattnera3465782004-09-15 01:04:07 +0000744/// and keep track of the mapping from value to alloca.
Chris Lattner45d67d62003-02-24 03:52:32 +0000745///
Chris Lattnera3465782004-09-15 01:04:07 +0000746void LICM::FindPromotableValuesInLoop(
Chris Lattner45d67d62003-02-24 03:52:32 +0000747 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
748 std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
749 Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
750
Chris Lattnera3465782004-09-15 01:04:07 +0000751 // Loop over all of the alias sets in the tracker object.
Chris Lattner0592bb72003-03-03 23:32:45 +0000752 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
753 I != E; ++I) {
754 AliasSet &AS = *I;
755 // We can promote this alias set if it has a store, if it is a "Must" alias
Chris Lattnera3465782004-09-15 01:04:07 +0000756 // set, if the pointer is loop invariant, and if we are not eliminating any
Chris Lattner20cda262004-03-15 04:11:30 +0000757 // volatile loads or stores.
Chris Lattner0592bb72003-03-03 23:32:45 +0000758 if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias() &&
Chris Lattnerfc44a252004-04-18 22:46:08 +0000759 !AS.isVolatile() && CurLoop->isLoopInvariant(AS.begin()->first)) {
Chris Lattner0592bb72003-03-03 23:32:45 +0000760 assert(AS.begin() != AS.end() &&
761 "Must alias set should have at least one pointer element in it!");
762 Value *V = AS.begin()->first;
Chris Lattner45d67d62003-02-24 03:52:32 +0000763
Chris Lattner0592bb72003-03-03 23:32:45 +0000764 // Check that all of the pointers in the alias set have the same type. We
765 // cannot (yet) promote a memory location that is loaded and stored in
766 // different sizes.
767 bool PointerOk = true;
768 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
769 if (V->getType() != I->first->getType()) {
770 PointerOk = false;
771 break;
Chris Lattner45d67d62003-02-24 03:52:32 +0000772 }
Chris Lattner0592bb72003-03-03 23:32:45 +0000773
774 if (PointerOk) {
775 const Type *Ty = cast<PointerType>(V->getType())->getElementType();
776 AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
777 PromotedValues.push_back(std::make_pair(AI, V));
Chris Lattnera3465782004-09-15 01:04:07 +0000778
779 // Update the AST and alias analysis.
780 CurAST->copyValue(V, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000781
Chris Lattner0592bb72003-03-03 23:32:45 +0000782 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
783 ValueToAllocaMap.insert(std::make_pair(I->first, AI));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000784
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000785 DOUT << "LICM: Promoting value: " << *V << "\n";
Chris Lattner45d67d62003-02-24 03:52:32 +0000786 }
787 }
788 }
Chris Lattnera51fa882002-08-22 21:39:55 +0000789}