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