blob: 554b5ec517b014f35c039d91ac072f0564712096 [file] [log] [blame]
Chris Lattner6ec05f52002-05-10 22:44:58 +00001//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
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
34#include "llvm/Transforms/Scalar.h"
Chris Lattner289ba2a2004-05-23 21:20:19 +000035#include "llvm/DerivedTypes.h"
36#include "llvm/Instructions.h"
37#include "llvm/Target/TargetData.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000038#include "llvm/Analysis/LoopInfo.h"
Chris Lattnera51fa882002-08-22 21:39:55 +000039#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner0592bb72003-03-03 23:32:45 +000040#include "llvm/Analysis/AliasSetTracker.h"
Chris Lattner64437692002-09-29 21:46:09 +000041#include "llvm/Analysis/Dominators.h"
Chris Lattner45d67d62003-02-24 03:52:32 +000042#include "llvm/Support/CFG.h"
Chris Lattner289ba2a2004-05-23 21:20:19 +000043#include "llvm/Transforms/Utils/PromoteMemToReg.h"
44#include "llvm/Transforms/Utils/Local.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000045#include "llvm/Support/CommandLine.h"
46#include "llvm/Support/Debug.h"
47#include "llvm/ADT/Statistic.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000048#include <algorithm>
Chris Lattnerc0517682003-12-09 17:18:00 +000049using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000050
Chris Lattner6ec05f52002-05-10 22:44:58 +000051namespace {
Chris Lattner17895702003-10-13 05:04:27 +000052 cl::opt<bool>
53 DisablePromotion("disable-licm-promotion", cl::Hidden,
54 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner45d67d62003-02-24 03:52:32 +000055
Chris Lattneraaaea512003-12-10 06:41:05 +000056 Statistic<> NumSunk("licm", "Number of instructions sunk out of loop");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000057 Statistic<> NumHoisted("licm", "Number of instructions hoisted out of loop");
Chris Lattneraaaea512003-12-10 06:41:05 +000058 Statistic<> NumMovedLoads("licm", "Number of load insts hoisted or sunk");
Chris Lattner20cda262004-03-15 04:11:30 +000059 Statistic<> NumMovedCalls("licm", "Number of call insts hoisted or sunk");
Chris Lattner17895702003-10-13 05:04:27 +000060 Statistic<> NumPromoted("licm",
61 "Number of memory locations promoted to registers");
Chris Lattner718b2212002-09-26 16:38:03 +000062
Chris Lattner65c11932003-12-09 19:32:44 +000063 struct LICM : public FunctionPass {
Chris Lattner113f4f42002-06-25 16:13:24 +000064 virtual bool runOnFunction(Function &F);
Chris Lattner6ec05f52002-05-10 22:44:58 +000065
Chris Lattnerf64f2d32002-09-26 16:52:07 +000066 /// This transformation requires natural loop information & requires that
67 /// loop preheaders be inserted into the CFG...
68 ///
Chris Lattner6ec05f52002-05-10 22:44:58 +000069 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +000070 AU.setPreservesCFG();
Chris Lattner72272a72003-10-12 21:52:28 +000071 AU.addRequiredID(LoopSimplifyID);
Chris Lattnerf0ed55d2002-08-08 19:01:30 +000072 AU.addRequired<LoopInfo>();
Chris Lattner64437692002-09-29 21:46:09 +000073 AU.addRequired<DominatorTree>();
Chris Lattner0592bb72003-03-03 23:32:45 +000074 AU.addRequired<DominanceFrontier>(); // For scalar promotion (mem2reg)
Chris Lattnera51fa882002-08-22 21:39:55 +000075 AU.addRequired<AliasAnalysis>();
Chris Lattner6ec05f52002-05-10 22:44:58 +000076 }
77
78 private:
Chris Lattnerc0517682003-12-09 17:18:00 +000079 // Various analyses that we use...
Chris Lattner45d67d62003-02-24 03:52:32 +000080 AliasAnalysis *AA; // Current AliasAnalysis information
Chris Lattnerc0517682003-12-09 17:18:00 +000081 LoopInfo *LI; // Current LoopInfo
82 DominatorTree *DT; // Dominator Tree for the current Loop...
Chris Lattnera906bac2003-10-05 21:20:13 +000083 DominanceFrontier *DF; // Current Dominance Frontier
Chris Lattnerc0517682003-12-09 17:18:00 +000084
85 // State that is updated as we process loops
Chris Lattner45d67d62003-02-24 03:52:32 +000086 bool Changed; // Set to true when we change anything.
87 BasicBlock *Preheader; // The preheader block of the current loop...
88 Loop *CurLoop; // The current loop we are working on...
Chris Lattner0592bb72003-03-03 23:32:45 +000089 AliasSetTracker *CurAST; // AliasSet information for the current loop...
Chris Lattner6ec05f52002-05-10 22:44:58 +000090
Chris Lattnerf64f2d32002-09-26 16:52:07 +000091 /// visitLoop - Hoist expressions out of the specified loop...
92 ///
Chris Lattner0592bb72003-03-03 23:32:45 +000093 void visitLoop(Loop *L, AliasSetTracker &AST);
Chris Lattner6ec05f52002-05-10 22:44:58 +000094
Chris Lattner547192d62003-12-19 07:22:45 +000095 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
96 /// dominated by the specified block, and that are in the current loop) in
97 /// reverse depth first order w.r.t the DominatorTree. This allows us to
98 /// visit uses before definitions, allowing us to sink a loop body in one
99 /// pass without iteration.
100 ///
101 void SinkRegion(DominatorTree::Node *N);
102
Chris Lattner64437692002-09-29 21:46:09 +0000103 /// HoistRegion - Walk the specified region of the CFG (defined by all
104 /// blocks dominated by the specified block, and that are in the current
105 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000106 /// visit definitions before uses, allowing us to hoist a loop body in one
Chris Lattner64437692002-09-29 21:46:09 +0000107 /// pass without iteration.
108 ///
109 void HoistRegion(DominatorTree::Node *N);
110
Chris Lattner05e86302002-09-29 22:26:07 +0000111 /// inSubLoop - Little predicate that returns true if the specified basic
112 /// block is in a subloop of the current one, not the current one itself.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000113 ///
Chris Lattner05e86302002-09-29 22:26:07 +0000114 bool inSubLoop(BasicBlock *BB) {
115 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000116 for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
117 if ((*I)->contains(BB))
Chris Lattner05e86302002-09-29 22:26:07 +0000118 return true; // A subloop actually contains this block!
119 return false;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000120 }
121
Chris Lattneraaaea512003-12-10 06:41:05 +0000122 /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
123 /// specified exit block of the loop is dominated by the specified block
124 /// that is in the body of the loop. We use these constraints to
125 /// dramatically limit the amount of the dominator tree that needs to be
126 /// searched.
127 bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
128 BasicBlock *BlockInLoop) const {
129 // If the block in the loop is the loop header, it must be dominated!
130 BasicBlock *LoopHeader = CurLoop->getHeader();
131 if (BlockInLoop == LoopHeader)
132 return true;
133
134 DominatorTree::Node *BlockInLoopNode = DT->getNode(BlockInLoop);
135 DominatorTree::Node *IDom = DT->getNode(ExitBlock);
136
137 // Because the exit block is not in the loop, we know we have to get _at
Chris Lattner289ba2a2004-05-23 21:20:19 +0000138 // least_ its immediate dominator.
Chris Lattneraaaea512003-12-10 06:41:05 +0000139 do {
140 // Get next Immediate Dominator.
141 IDom = IDom->getIDom();
142
143 // If we have got to the header of the loop, then the instructions block
144 // did not dominate the exit node, so we can't hoist it.
145 if (IDom->getBlock() == LoopHeader)
146 return false;
147
148 } while (IDom != BlockInLoopNode);
149
150 return true;
151 }
152
153 /// sink - When an instruction is found to only be used outside of the loop,
154 /// this function moves it to the exit blocks and patches up SSA form as
155 /// needed.
156 ///
157 void sink(Instruction &I);
158
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000159 /// hoist - When an instruction is found to only use loop invariant operands
160 /// that is safe to hoist, this instruction is called to do the dirty work.
161 ///
Chris Lattner113f4f42002-06-25 16:13:24 +0000162 void hoist(Instruction &I);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000163
Chris Lattneraaaea512003-12-10 06:41:05 +0000164 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
165 /// is not a trapping instruction or if it is a trapping instruction and is
166 /// guaranteed to execute.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000167 ///
Chris Lattneraaaea512003-12-10 06:41:05 +0000168 bool isSafeToExecuteUnconditionally(Instruction &I);
Tanya Lattner57c03df2003-08-05 18:45:46 +0000169
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000170 /// pointerInvalidatedByLoop - Return true if the body of this loop may
171 /// store into the memory location pointed to by V.
172 ///
Chris Lattner45d67d62003-02-24 03:52:32 +0000173 bool pointerInvalidatedByLoop(Value *V) {
Chris Lattner0592bb72003-03-03 23:32:45 +0000174 // Check to see if any of the basic blocks in CurLoop invalidate *V.
175 return CurAST->getAliasSetForPointer(V, 0).isMod();
Chris Lattner45d67d62003-02-24 03:52:32 +0000176 }
Chris Lattnera51fa882002-08-22 21:39:55 +0000177
Chris Lattneraaaea512003-12-10 06:41:05 +0000178 bool canSinkOrHoistInst(Instruction &I);
179 bool isLoopInvariantInst(Instruction &I);
180 bool isNotUsedInLoop(Instruction &I);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000181
Chris Lattner45d67d62003-02-24 03:52:32 +0000182 /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
183 /// to scalars as we can.
184 ///
185 void PromoteValuesInLoop();
186
Chris Lattnera3465782004-09-15 01:04:07 +0000187 /// FindPromotableValuesInLoop - Check the current loop for stores to
Misha Brukman9b8d3392003-09-11 15:32:37 +0000188 /// definite pointers, which are not loaded and stored through may aliases.
Chris Lattner45d67d62003-02-24 03:52:32 +0000189 /// If these are found, create an alloca for the value, add it to the
190 /// PromotedValues list, and keep track of the mapping from value to
191 /// alloca...
192 ///
Chris Lattnera3465782004-09-15 01:04:07 +0000193 void FindPromotableValuesInLoop(
Chris Lattner45d67d62003-02-24 03:52:32 +0000194 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
195 std::map<Value*, AllocaInst*> &Val2AlMap);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000196 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000197
Chris Lattnerc8b70922002-07-26 21:12:46 +0000198 RegisterOpt<LICM> X("licm", "Loop Invariant Code Motion");
Chris Lattner6ec05f52002-05-10 22:44:58 +0000199}
200
Chris Lattnerc0517682003-12-09 17:18:00 +0000201FunctionPass *llvm::createLICMPass() { return new LICM(); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000202
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000203/// runOnFunction - For LICM, this simply traverses the loop structure of the
204/// function, hoisting expressions out of loops if possible.
205///
Chris Lattner42ad6462004-06-19 20:23:35 +0000206bool LICM::runOnFunction(Function &) {
Chris Lattner45d67d62003-02-24 03:52:32 +0000207 Changed = false;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000208
Chris Lattner45d67d62003-02-24 03:52:32 +0000209 // Get our Loop and Alias Analysis information...
210 LI = &getAnalysis<LoopInfo>();
Chris Lattnera51fa882002-08-22 21:39:55 +0000211 AA = &getAnalysis<AliasAnalysis>();
Chris Lattnera906bac2003-10-05 21:20:13 +0000212 DF = &getAnalysis<DominanceFrontier>();
Tanya Lattnerdc3c9a82003-08-05 20:39:02 +0000213 DT = &getAnalysis<DominatorTree>();
Chris Lattnera51fa882002-08-22 21:39:55 +0000214
Chris Lattner45d67d62003-02-24 03:52:32 +0000215 // Hoist expressions out of all of the top-level loops.
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000216 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
Chris Lattner0592bb72003-03-03 23:32:45 +0000217 AliasSetTracker AST(*AA);
Chris Lattner65c11932003-12-09 19:32:44 +0000218 visitLoop(*I, AST);
Chris Lattner45d67d62003-02-24 03:52:32 +0000219 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000220 return Changed;
221}
222
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000223
224/// visitLoop - Hoist expressions out of the specified loop...
225///
Chris Lattner0592bb72003-03-03 23:32:45 +0000226void LICM::visitLoop(Loop *L, AliasSetTracker &AST) {
Chris Lattner6ec05f52002-05-10 22:44:58 +0000227 // Recurse through all subloops before we process this loop...
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000228 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
Chris Lattner0592bb72003-03-03 23:32:45 +0000229 AliasSetTracker SubAST(*AA);
Chris Lattner65c11932003-12-09 19:32:44 +0000230 visitLoop(*I, SubAST);
Chris Lattner45d67d62003-02-24 03:52:32 +0000231
232 // Incorporate information about the subloops into this loop...
Chris Lattner0592bb72003-03-03 23:32:45 +0000233 AST.add(SubAST);
Chris Lattner45d67d62003-02-24 03:52:32 +0000234 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000235 CurLoop = L;
Chris Lattner0592bb72003-03-03 23:32:45 +0000236 CurAST = &AST;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000237
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000238 // Get the preheader block to move instructions into...
239 Preheader = L->getLoopPreheader();
240 assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
241
Chris Lattner45d67d62003-02-24 03:52:32 +0000242 // Loop over the body of this loop, looking for calls, invokes, and stores.
Chris Lattner0592bb72003-03-03 23:32:45 +0000243 // Because subloops have already been incorporated into AST, we skip blocks in
Chris Lattner45d67d62003-02-24 03:52:32 +0000244 // subloops.
245 //
Chris Lattneraaaea512003-12-10 06:41:05 +0000246 for (std::vector<BasicBlock*>::const_iterator I = L->getBlocks().begin(),
247 E = L->getBlocks().end(); I != E; ++I)
Chris Lattner45d67d62003-02-24 03:52:32 +0000248 if (LI->getLoopFor(*I) == L) // Ignore blocks in subloops...
Chris Lattner0592bb72003-03-03 23:32:45 +0000249 AST.add(**I); // Incorporate the specified basic block
Chris Lattner45d67d62003-02-24 03:52:32 +0000250
Chris Lattner6ec05f52002-05-10 22:44:58 +0000251 // We want to visit all of the instructions in this loop... that are not parts
252 // of our subloops (they have already had their invariants hoisted out of
253 // their loop, into this loop, so there is no need to process the BODIES of
254 // the subloops).
255 //
Chris Lattner64437692002-09-29 21:46:09 +0000256 // Traverse the body of the loop in depth first order on the dominator tree so
257 // that we are guaranteed to see definitions before we see uses. This allows
Chris Lattner547192d62003-12-19 07:22:45 +0000258 // us to sink instructions in one pass, without iteration. AFter sinking
259 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner64437692002-09-29 21:46:09 +0000260 //
Chris Lattner547192d62003-12-19 07:22:45 +0000261 SinkRegion(DT->getNode(L->getHeader()));
Tanya Lattnerdc3c9a82003-08-05 20:39:02 +0000262 HoistRegion(DT->getNode(L->getHeader()));
Chris Lattner6ec05f52002-05-10 22:44:58 +0000263
Chris Lattner45d67d62003-02-24 03:52:32 +0000264 // Now that all loop invariants have been removed from the loop, promote any
265 // memory references to scalars that we can...
266 if (!DisablePromotion)
267 PromoteValuesInLoop();
268
Chris Lattner6ec05f52002-05-10 22:44:58 +0000269 // Clear out loops state information for the next iteration
270 CurLoop = 0;
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000271 Preheader = 0;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000272}
273
Chris Lattner547192d62003-12-19 07:22:45 +0000274/// SinkRegion - Walk the specified region of the CFG (defined by all blocks
275/// dominated by the specified block, and that are in the current loop) in
276/// reverse depth first order w.r.t the DominatorTree. This allows us to visit
277/// uses before definitions, allowing us to sink a loop body in one pass without
278/// iteration.
279///
280void LICM::SinkRegion(DominatorTree::Node *N) {
281 assert(N != 0 && "Null dominator tree node?");
282 BasicBlock *BB = N->getBlock();
283
284 // If this subregion is not in the top level loop at all, exit.
285 if (!CurLoop->contains(BB)) return;
286
287 // We are processing blocks in reverse dfo, so process children first...
288 const std::vector<DominatorTree::Node*> &Children = N->getChildren();
289 for (unsigned i = 0, e = Children.size(); i != e; ++i)
290 SinkRegion(Children[i]);
291
292 // Only need to process the contents of this block if it is not part of a
293 // subloop (which would already have been processed).
294 if (inSubLoop(BB)) return;
295
Chris Lattner91846012003-12-19 08:18:16 +0000296 for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
297 Instruction &I = *--II;
Chris Lattner547192d62003-12-19 07:22:45 +0000298
299 // Check to see if we can sink this instruction to the exit blocks
300 // of the loop. We can do this if the all users of the instruction are
301 // outside of the loop. In this case, it doesn't even matter if the
302 // operands of the instruction are loop invariant.
303 //
Chris Lattner91846012003-12-19 08:18:16 +0000304 if (canSinkOrHoistInst(I) && isNotUsedInLoop(I)) {
305 ++II;
Chris Lattner547192d62003-12-19 07:22:45 +0000306 sink(I);
Chris Lattner91846012003-12-19 08:18:16 +0000307 }
Chris Lattner547192d62003-12-19 07:22:45 +0000308 }
309}
310
311
Chris Lattner64437692002-09-29 21:46:09 +0000312/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
313/// dominated by the specified block, and that are in the current loop) in depth
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000314/// first order w.r.t the DominatorTree. This allows us to visit definitions
Chris Lattner64437692002-09-29 21:46:09 +0000315/// before uses, allowing us to hoist a loop body in one pass without iteration.
316///
317void LICM::HoistRegion(DominatorTree::Node *N) {
318 assert(N != 0 && "Null dominator tree node?");
Chris Lattner65c11932003-12-09 19:32:44 +0000319 BasicBlock *BB = N->getBlock();
Chris Lattner64437692002-09-29 21:46:09 +0000320
Chris Lattner05e86302002-09-29 22:26:07 +0000321 // If this subregion is not in the top level loop at all, exit.
Chris Lattner65c11932003-12-09 19:32:44 +0000322 if (!CurLoop->contains(BB)) return;
Chris Lattner64437692002-09-29 21:46:09 +0000323
Chris Lattneraaaea512003-12-10 06:41:05 +0000324 // Only need to process the contents of this block if it is not part of a
325 // subloop (which would already have been processed).
Chris Lattner65c11932003-12-09 19:32:44 +0000326 if (!inSubLoop(BB))
Chris Lattneraaaea512003-12-10 06:41:05 +0000327 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
328 Instruction &I = *II++;
Chris Lattner547192d62003-12-19 07:22:45 +0000329
330 // Try hoisting the instruction out to the preheader. We can only do this
331 // if all of the operands of the instruction are loop invariant and if it
332 // is safe to hoist the instruction.
333 //
334 if (isLoopInvariantInst(I) && canSinkOrHoistInst(I) &&
335 isSafeToExecuteUnconditionally(I))
Chris Lattneraaaea512003-12-10 06:41:05 +0000336 hoist(I);
337 }
Chris Lattner64437692002-09-29 21:46:09 +0000338
339 const std::vector<DominatorTree::Node*> &Children = N->getChildren();
340 for (unsigned i = 0, e = Children.size(); i != e; ++i)
Chris Lattner42ad6462004-06-19 20:23:35 +0000341 HoistRegion(Children[i]);
Chris Lattner64437692002-09-29 21:46:09 +0000342}
343
Chris Lattneraaaea512003-12-10 06:41:05 +0000344/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
345/// instruction.
346///
347bool LICM::canSinkOrHoistInst(Instruction &I) {
Chris Lattner65c11932003-12-09 19:32:44 +0000348 // Loads have extra constraints we have to verify before we can hoist them.
349 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
350 if (LI->isVolatile())
351 return false; // Don't hoist volatile loads!
352
353 // Don't hoist loads which have may-aliased stores in loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000354 return !pointerInvalidatedByLoop(LI->getOperand(0));
Chris Lattner20cda262004-03-15 04:11:30 +0000355 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
356 // Handle obvious cases efficiently.
357 if (Function *Callee = CI->getCalledFunction()) {
358 if (AA->doesNotAccessMemory(Callee))
359 return true;
360 else if (AA->onlyReadsMemory(Callee)) {
361 // If this call only reads from memory and there are no writes to memory
362 // in the loop, we can hoist or sink the call as appropriate.
363 bool FoundMod = false;
364 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
365 I != E; ++I) {
366 AliasSet &AS = *I;
367 if (!AS.isForwardingAliasSet() && AS.isMod()) {
368 FoundMod = true;
369 break;
370 }
371 }
372 if (!FoundMod) return true;
373 }
374 }
375
376 // FIXME: This should use mod/ref information to see if we can hoist or sink
377 // the call.
378
379 return false;
Chris Lattner65c11932003-12-09 19:32:44 +0000380 }
381
Chris Lattneraaaea512003-12-10 06:41:05 +0000382 return isa<BinaryOperator>(I) || isa<ShiftInst>(I) || isa<CastInst>(I) ||
Chris Lattner20cda262004-03-15 04:11:30 +0000383 isa<SelectInst>(I) ||
Chris Lattneraaaea512003-12-10 06:41:05 +0000384 isa<GetElementPtrInst>(I) || isa<VANextInst>(I) || isa<VAArgInst>(I);
385}
386
387/// isNotUsedInLoop - Return true if the only users of this instruction are
388/// outside of the loop. If this is true, we can sink the instruction to the
389/// exit blocks of the loop.
390///
391bool LICM::isNotUsedInLoop(Instruction &I) {
Chris Lattner34399dd2003-12-11 22:23:32 +0000392 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
393 Instruction *User = cast<Instruction>(*UI);
394 if (PHINode *PN = dyn_cast<PHINode>(User)) {
395 // PHI node uses occur in predecessor blocks!
396 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
397 if (PN->getIncomingValue(i) == &I)
398 if (CurLoop->contains(PN->getIncomingBlock(i)))
399 return false;
400 } else if (CurLoop->contains(User->getParent())) {
Chris Lattneraaaea512003-12-10 06:41:05 +0000401 return false;
Chris Lattner34399dd2003-12-11 22:23:32 +0000402 }
403 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000404 return true;
405}
406
407
408/// isLoopInvariantInst - Return true if all operands of this instruction are
409/// loop invariant. We also filter out non-hoistable instructions here just for
410/// efficiency.
411///
412bool LICM::isLoopInvariantInst(Instruction &I) {
413 // The instruction is loop invariant if all of its operands are loop-invariant
414 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Chris Lattnerfc44a252004-04-18 22:46:08 +0000415 if (!CurLoop->isLoopInvariant(I.getOperand(i)))
Chris Lattneraaaea512003-12-10 06:41:05 +0000416 return false;
417
Chris Lattner65c11932003-12-09 19:32:44 +0000418 // If we got this far, the instruction is loop invariant!
419 return true;
420}
421
Chris Lattneraaaea512003-12-10 06:41:05 +0000422/// sink - When an instruction is found to only be used outside of the loop,
Chris Lattner91846012003-12-19 08:18:16 +0000423/// this function moves it to the exit blocks and patches up SSA form as needed.
424/// This method is guaranteed to remove the original instruction from its
425/// position, and may either delete it or move it to outside of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000426///
427void LICM::sink(Instruction &I) {
428 DEBUG(std::cerr << "LICM sinking instruction: " << I);
429
Chris Lattner35eaa552004-04-18 22:15:13 +0000430 std::vector<BasicBlock*> ExitBlocks;
431 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattner55c21132003-12-10 20:43:29 +0000432
433 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner20cda262004-03-15 04:11:30 +0000434 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattner55c21132003-12-10 20:43:29 +0000435 ++NumSunk;
436 Changed = true;
437
Chris Lattneraaaea512003-12-10 06:41:05 +0000438 // The case where there is only a single exit node of this loop is common
439 // enough that we handle it as a special (more efficient) case. It is more
440 // efficient to handle because there are no PHI nodes that need to be placed.
441 if (ExitBlocks.size() == 1) {
442 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
443 // Instruction is not used, just delete it.
Chris Lattner289ba2a2004-05-23 21:20:19 +0000444 CurAST->deleteValue(&I);
Chris Lattneraaaea512003-12-10 06:41:05 +0000445 I.getParent()->getInstList().erase(&I);
446 } else {
447 // Move the instruction to the start of the exit block, after any PHI
448 // nodes in it.
449 I.getParent()->getInstList().remove(&I);
450
451 BasicBlock::iterator InsertPt = ExitBlocks[0]->begin();
452 while (isa<PHINode>(InsertPt)) ++InsertPt;
453 ExitBlocks[0]->getInstList().insert(InsertPt, &I);
454 }
455 } else if (ExitBlocks.size() == 0) {
456 // The instruction is actually dead if there ARE NO exit blocks.
Chris Lattner289ba2a2004-05-23 21:20:19 +0000457 CurAST->deleteValue(&I);
Chris Lattneraaaea512003-12-10 06:41:05 +0000458 I.getParent()->getInstList().erase(&I);
Chris Lattneraaaea512003-12-10 06:41:05 +0000459 } else {
460 // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
461 // do all of the hard work of inserting PHI nodes as necessary. We convert
462 // the value into a stack object to get it to do this.
463
464 // Firstly, we create a stack object to hold the value...
Chris Lattner50eb7712004-07-27 07:38:32 +0000465 AllocaInst *AI = 0;
Chris Lattneraaaea512003-12-10 06:41:05 +0000466
Chris Lattner50eb7712004-07-27 07:38:32 +0000467 if (I.getType() != Type::VoidTy)
468 AI = new AllocaInst(I.getType(), 0, I.getName(),
469 I.getParent()->getParent()->front().begin());
470
Chris Lattneraaaea512003-12-10 06:41:05 +0000471 // Secondly, insert load instructions for each use of the instruction
472 // outside of the loop.
473 while (!I.use_empty()) {
474 Instruction *U = cast<Instruction>(I.use_back());
475
476 // If the user is a PHI Node, we actually have to insert load instructions
477 // in all predecessor blocks, not in the PHI block itself!
478 if (PHINode *UPN = dyn_cast<PHINode>(U)) {
479 // Only insert into each predecessor once, so that we don't have
480 // different incoming values from the same block!
481 std::map<BasicBlock*, Value*> InsertedBlocks;
482 for (unsigned i = 0, e = UPN->getNumIncomingValues(); i != e; ++i)
483 if (UPN->getIncomingValue(i) == &I) {
484 BasicBlock *Pred = UPN->getIncomingBlock(i);
485 Value *&PredVal = InsertedBlocks[Pred];
486 if (!PredVal) {
487 // Insert a new load instruction right before the terminator in
488 // the predecessor block.
489 PredVal = new LoadInst(AI, "", Pred->getTerminator());
490 }
491
492 UPN->setIncomingValue(i, PredVal);
493 }
494
495 } else {
496 LoadInst *L = new LoadInst(AI, "", U);
497 U->replaceUsesOfWith(&I, L);
498 }
499 }
500
501 // Thirdly, insert a copy of the instruction in each exit block of the loop
502 // that is dominated by the instruction, storing the result into the memory
503 // location. Be careful not to insert the instruction into any particular
504 // basic block more than once.
505 std::set<BasicBlock*> InsertedBlocks;
506 BasicBlock *InstOrigBB = I.getParent();
507
508 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
509 BasicBlock *ExitBlock = ExitBlocks[i];
510
511 if (isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB)) {
Chris Lattneraaaea512003-12-10 06:41:05 +0000512 // If we haven't already processed this exit block, do so now.
Chris Lattner63643142003-12-10 16:58:24 +0000513 if (InsertedBlocks.insert(ExitBlock).second) {
Chris Lattneraaaea512003-12-10 06:41:05 +0000514 // Insert the code after the last PHI node...
515 BasicBlock::iterator InsertPt = ExitBlock->begin();
516 while (isa<PHINode>(InsertPt)) ++InsertPt;
517
518 // If this is the first exit block processed, just move the original
519 // instruction, otherwise clone the original instruction and insert
520 // the copy.
521 Instruction *New;
Chris Lattner6281fd32003-12-10 22:35:56 +0000522 if (InsertedBlocks.size() == 1) {
Chris Lattneraaaea512003-12-10 06:41:05 +0000523 I.getParent()->getInstList().remove(&I);
524 ExitBlock->getInstList().insert(InsertPt, &I);
525 New = &I;
526 } else {
527 New = I.clone();
Chris Lattner50eb7712004-07-27 07:38:32 +0000528 if (!I.getName().empty())
529 New->setName(I.getName()+".le");
Chris Lattneraaaea512003-12-10 06:41:05 +0000530 ExitBlock->getInstList().insert(InsertPt, New);
531 }
532
533 // Now that we have inserted the instruction, store it into the alloca
Chris Lattner50eb7712004-07-27 07:38:32 +0000534 if (AI) new StoreInst(New, AI, InsertPt);
Chris Lattneraaaea512003-12-10 06:41:05 +0000535 }
536 }
537 }
Chris Lattner91846012003-12-19 08:18:16 +0000538
539 // If the instruction doesn't dominate any exit blocks, it must be dead.
540 if (InsertedBlocks.empty()) {
Chris Lattner289ba2a2004-05-23 21:20:19 +0000541 CurAST->deleteValue(&I);
Chris Lattner91846012003-12-19 08:18:16 +0000542 I.getParent()->getInstList().erase(&I);
543 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000544
545 // Finally, promote the fine value to SSA form.
Chris Lattner50eb7712004-07-27 07:38:32 +0000546 if (AI) {
547 std::vector<AllocaInst*> Allocas;
548 Allocas.push_back(AI);
Chris Lattnera3465782004-09-15 01:04:07 +0000549 PromoteMemToReg(Allocas, *DT, *DF, AA->getTargetData(), CurAST);
Chris Lattner50eb7712004-07-27 07:38:32 +0000550 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000551 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000552}
Chris Lattner64437692002-09-29 21:46:09 +0000553
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000554/// hoist - When an instruction is found to only use loop invariant operands
555/// that is safe to hoist, this instruction is called to do the dirty work.
556///
Chris Lattneraaaea512003-12-10 06:41:05 +0000557void LICM::hoist(Instruction &I) {
Brian Gaeke661963c2004-06-17 07:26:52 +0000558 DEBUG(std::cerr << "LICM hoisting to " << Preheader->getName()
Chris Lattner289ba2a2004-05-23 21:20:19 +0000559 << ": " << I);
Chris Lattner65c11932003-12-09 19:32:44 +0000560
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000561 // Remove the instruction from its current basic block... but don't delete the
562 // instruction.
Chris Lattneraaaea512003-12-10 06:41:05 +0000563 I.getParent()->getInstList().remove(&I);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000564
Chris Lattner718b2212002-09-26 16:38:03 +0000565 // Insert the new node in Preheader, before the terminator.
Chris Lattneraaaea512003-12-10 06:41:05 +0000566 Preheader->getInstList().insert(Preheader->getTerminator(), &I);
Chris Lattner718b2212002-09-26 16:38:03 +0000567
Chris Lattneraaaea512003-12-10 06:41:05 +0000568 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner20cda262004-03-15 04:11:30 +0000569 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattner718b2212002-09-26 16:38:03 +0000570 ++NumHoisted;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000571 Changed = true;
572}
573
Chris Lattneraaaea512003-12-10 06:41:05 +0000574/// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
575/// not a trapping instruction or if it is a trapping instruction and is
576/// guaranteed to execute.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000577///
Chris Lattneraaaea512003-12-10 06:41:05 +0000578bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
Chris Lattnerc0517682003-12-09 17:18:00 +0000579 // If it is not a trapping instruction, it is always safe to hoist.
580 if (!Inst.isTrapping()) return true;
581
582 // Otherwise we have to check to make sure that the instruction dominates all
583 // of the exit blocks. If it doesn't, then there is a path out of the loop
584 // which does not execute this instruction, so we can't hoist it.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000585
Chris Lattnerc0517682003-12-09 17:18:00 +0000586 // If the instruction is in the header block for the loop (which is very
587 // common), it is always guaranteed to dominate the exit blocks. Since this
588 // is a common case, and can save some work, check it now.
Chris Lattneraaaea512003-12-10 06:41:05 +0000589 if (Inst.getParent() == CurLoop->getHeader())
Chris Lattnerc0517682003-12-09 17:18:00 +0000590 return true;
Tanya Lattner57c03df2003-08-05 18:45:46 +0000591
Chris Lattnerc0517682003-12-09 17:18:00 +0000592 // Get the exit blocks for the current loop.
Chris Lattner35eaa552004-04-18 22:15:13 +0000593 std::vector<BasicBlock*> ExitBlocks;
594 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattnerc0517682003-12-09 17:18:00 +0000595
596 // For each exit block, get the DT node and walk up the DT until the
597 // instruction's basic block is found or we exit the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000598 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
599 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
600 return false;
Tanya Lattnerdc3c9a82003-08-05 20:39:02 +0000601
Tanya Lattner57c03df2003-08-05 18:45:46 +0000602 return true;
603}
604
Chris Lattnerd771fdf2002-09-26 16:19:31 +0000605
Chris Lattner45d67d62003-02-24 03:52:32 +0000606/// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
607/// stores out of the loop and moving loads to before the loop. We do this by
608/// looping over the stores in the loop, looking for stores to Must pointers
609/// which are loop invariant. We promote these memory locations to use allocas
610/// instead. These allocas can easily be raised to register values by the
611/// PromoteMem2Reg functionality.
612///
613void LICM::PromoteValuesInLoop() {
614 // PromotedValues - List of values that are promoted out of the loop. Each
Chris Lattner216c7b82003-09-10 05:29:43 +0000615 // value has an alloca instruction for it, and a canonical version of the
Chris Lattner45d67d62003-02-24 03:52:32 +0000616 // pointer.
617 std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
618 std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
619
Chris Lattnera3465782004-09-15 01:04:07 +0000620 FindPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
621 if (ValueToAllocaMap.empty()) return; // If there are values to promote.
Chris Lattner45d67d62003-02-24 03:52:32 +0000622
623 Changed = true;
624 NumPromoted += PromotedValues.size();
625
Chris Lattnera3465782004-09-15 01:04:07 +0000626 std::vector<Value*> PointerValueNumbers;
627
Chris Lattner45d67d62003-02-24 03:52:32 +0000628 // Emit a copy from the value into the alloca'd value in the loop preheader
629 TerminatorInst *LoopPredInst = Preheader->getTerminator();
630 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
Chris Lattnera3465782004-09-15 01:04:07 +0000631 Value *Ptr = PromotedValues[i].second;
632
633 // If we are promoting a pointer value, update alias information for the
634 // inserted load.
635 Value *LoadValue = 0;
636 if (isa<PointerType>(cast<PointerType>(Ptr->getType())->getElementType())) {
637 // Locate a load or store through the pointer, and assign the same value
638 // to LI as we are loading or storing. Since we know that the value is
639 // stored in this loop, this will always succeed.
640 for (Value::use_iterator UI = Ptr->use_begin(), E = Ptr->use_end();
641 UI != E; ++UI)
642 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
643 LoadValue = LI;
644 break;
645 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
646 if (SI->getOperand(1) == LI) {
647 LoadValue = SI->getOperand(0);
648 break;
649 }
650 }
651 assert(LoadValue && "No store through the pointer found!");
652 PointerValueNumbers.push_back(LoadValue); // Remember this for later.
653 }
654
655 // Load from the memory we are promoting.
656 LoadInst *LI = new LoadInst(Ptr, Ptr->getName()+".promoted", LoopPredInst);
657
658 if (LoadValue) CurAST->copyValue(LoadValue, LI);
659
660 // Store into the temporary alloca.
Chris Lattner45d67d62003-02-24 03:52:32 +0000661 new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
662 }
663
664 // Scan the basic blocks in the loop, replacing uses of our pointers with
Chris Lattneredda1af2003-12-10 15:56:24 +0000665 // uses of the allocas in question.
Chris Lattner45d67d62003-02-24 03:52:32 +0000666 //
667 const std::vector<BasicBlock*> &LoopBBs = CurLoop->getBlocks();
668 for (std::vector<BasicBlock*>::const_iterator I = LoopBBs.begin(),
669 E = LoopBBs.end(); I != E; ++I) {
670 // Rewrite all loads and stores in the block of the pointer...
671 for (BasicBlock::iterator II = (*I)->begin(), E = (*I)->end();
672 II != E; ++II) {
Chris Lattner889f6202003-04-23 16:37:45 +0000673 if (LoadInst *L = dyn_cast<LoadInst>(II)) {
Chris Lattner45d67d62003-02-24 03:52:32 +0000674 std::map<Value*, AllocaInst*>::iterator
675 I = ValueToAllocaMap.find(L->getOperand(0));
676 if (I != ValueToAllocaMap.end())
677 L->setOperand(0, I->second); // Rewrite load instruction...
Chris Lattner889f6202003-04-23 16:37:45 +0000678 } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
Chris Lattner45d67d62003-02-24 03:52:32 +0000679 std::map<Value*, AllocaInst*>::iterator
680 I = ValueToAllocaMap.find(S->getOperand(1));
681 if (I != ValueToAllocaMap.end())
682 S->setOperand(1, I->second); // Rewrite store instruction...
683 }
684 }
Chris Lattner45d67d62003-02-24 03:52:32 +0000685 }
686
Chris Lattneredda1af2003-12-10 15:56:24 +0000687 // Now that the body of the loop uses the allocas instead of the original
688 // memory locations, insert code to copy the alloca value back into the
689 // original memory location on all exits from the loop. Note that we only
690 // want to insert one copy of the code in each exit block, though the loop may
691 // exit to the same block more than once.
692 //
693 std::set<BasicBlock*> ProcessedBlocks;
694
Chris Lattner35eaa552004-04-18 22:15:13 +0000695 std::vector<BasicBlock*> ExitBlocks;
696 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattneredda1af2003-12-10 15:56:24 +0000697 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
Chris Lattner48b4b852003-12-10 16:57:24 +0000698 if (ProcessedBlocks.insert(ExitBlocks[i]).second) {
Chris Lattnera3465782004-09-15 01:04:07 +0000699 // Copy all of the allocas into their memory locations.
Chris Lattneredda1af2003-12-10 15:56:24 +0000700 BasicBlock::iterator BI = ExitBlocks[i]->begin();
701 while (isa<PHINode>(*BI))
Chris Lattnera3465782004-09-15 01:04:07 +0000702 ++BI; // Skip over all of the phi nodes in the block.
Chris Lattneredda1af2003-12-10 15:56:24 +0000703 Instruction *InsertPos = BI;
Chris Lattnera3465782004-09-15 01:04:07 +0000704 unsigned PVN = 0;
Chris Lattneredda1af2003-12-10 15:56:24 +0000705 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
Chris Lattnera3465782004-09-15 01:04:07 +0000706 // Load from the alloca.
Chris Lattneredda1af2003-12-10 15:56:24 +0000707 LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
Chris Lattnera3465782004-09-15 01:04:07 +0000708
709 // If this is a pointer type, update alias info appropriately.
710 if (isa<PointerType>(LI->getType()))
711 CurAST->copyValue(PointerValueNumbers[PVN++], LI);
712
713 // Store into the memory we promoted.
Chris Lattneredda1af2003-12-10 15:56:24 +0000714 new StoreInst(LI, PromotedValues[i].second, InsertPos);
715 }
716 }
717
Chris Lattner45d67d62003-02-24 03:52:32 +0000718 // Now that we have done the deed, use the mem2reg functionality to promote
Chris Lattnera3465782004-09-15 01:04:07 +0000719 // all of the new allocas we just created into real SSA registers.
Chris Lattner45d67d62003-02-24 03:52:32 +0000720 //
721 std::vector<AllocaInst*> PromotedAllocas;
722 PromotedAllocas.reserve(PromotedValues.size());
723 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
724 PromotedAllocas.push_back(PromotedValues[i].first);
Chris Lattnera3465782004-09-15 01:04:07 +0000725 PromoteMemToReg(PromotedAllocas, *DT, *DF, AA->getTargetData(), CurAST);
Chris Lattner45d67d62003-02-24 03:52:32 +0000726}
727
Chris Lattnera3465782004-09-15 01:04:07 +0000728/// FindPromotableValuesInLoop - Check the current loop for stores to definite
Chris Lattner45d67d62003-02-24 03:52:32 +0000729/// pointers, which are not loaded and stored through may aliases. If these are
730/// found, create an alloca for the value, add it to the PromotedValues list,
Chris Lattnera3465782004-09-15 01:04:07 +0000731/// and keep track of the mapping from value to alloca.
Chris Lattner45d67d62003-02-24 03:52:32 +0000732///
Chris Lattnera3465782004-09-15 01:04:07 +0000733void LICM::FindPromotableValuesInLoop(
Chris Lattner45d67d62003-02-24 03:52:32 +0000734 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
735 std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
736 Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
737
Chris Lattnera3465782004-09-15 01:04:07 +0000738 // Loop over all of the alias sets in the tracker object.
Chris Lattner0592bb72003-03-03 23:32:45 +0000739 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
740 I != E; ++I) {
741 AliasSet &AS = *I;
742 // We can promote this alias set if it has a store, if it is a "Must" alias
Chris Lattnera3465782004-09-15 01:04:07 +0000743 // set, if the pointer is loop invariant, and if we are not eliminating any
Chris Lattner20cda262004-03-15 04:11:30 +0000744 // volatile loads or stores.
Chris Lattner0592bb72003-03-03 23:32:45 +0000745 if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias() &&
Chris Lattnerfc44a252004-04-18 22:46:08 +0000746 !AS.isVolatile() && CurLoop->isLoopInvariant(AS.begin()->first)) {
Chris Lattner0592bb72003-03-03 23:32:45 +0000747 assert(AS.begin() != AS.end() &&
748 "Must alias set should have at least one pointer element in it!");
749 Value *V = AS.begin()->first;
Chris Lattner45d67d62003-02-24 03:52:32 +0000750
Chris Lattner0592bb72003-03-03 23:32:45 +0000751 // Check that all of the pointers in the alias set have the same type. We
752 // cannot (yet) promote a memory location that is loaded and stored in
753 // different sizes.
754 bool PointerOk = true;
755 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
756 if (V->getType() != I->first->getType()) {
757 PointerOk = false;
758 break;
Chris Lattner45d67d62003-02-24 03:52:32 +0000759 }
Chris Lattner0592bb72003-03-03 23:32:45 +0000760
761 if (PointerOk) {
762 const Type *Ty = cast<PointerType>(V->getType())->getElementType();
763 AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
764 PromotedValues.push_back(std::make_pair(AI, V));
Chris Lattnera3465782004-09-15 01:04:07 +0000765
766 // Update the AST and alias analysis.
767 CurAST->copyValue(V, AI);
Chris Lattner0592bb72003-03-03 23:32:45 +0000768
769 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
770 ValueToAllocaMap.insert(std::make_pair(I->first, AI));
771
772 DEBUG(std::cerr << "LICM: Promoting value: " << *V << "\n");
Chris Lattner45d67d62003-02-24 03:52:32 +0000773 }
774 }
775 }
Chris Lattnera51fa882002-08-22 21:39:55 +0000776}