1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
16 // This pass uses alias analysis for two purposes:
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 SSAUpdater to construct the appropriate SSA form for the value.
31 //===----------------------------------------------------------------------===//
33 #include "llvm/Transforms/Scalar.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AliasSetTracker.h"
37 #include "llvm/Analysis/ConstantFolding.h"
38 #include "llvm/Analysis/LoopInfo.h"
39 #include "llvm/Analysis/LoopPass.h"
40 #include "llvm/Analysis/ScalarEvolution.h"
41 #include "llvm/Analysis/TargetLibraryInfo.h"
42 #include "llvm/Analysis/ValueTracking.h"
43 #include "llvm/IR/CFG.h"
44 #include "llvm/IR/Constants.h"
45 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/DerivedTypes.h"
47 #include "llvm/IR/Dominators.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/IntrinsicInst.h"
50 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/IR/Metadata.h"
52 #include "llvm/IR/PredIteratorCache.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Transforms/Utils/Local.h"
57 #include "llvm/Transforms/Utils/LoopUtils.h"
58 #include "llvm/Transforms/Utils/SSAUpdater.h"
62 #define DEBUG_TYPE "licm"
64 STATISTIC(NumSunk , "Number of instructions sunk out of loop");
65 STATISTIC(NumHoisted , "Number of instructions hoisted out of loop");
66 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
67 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
68 STATISTIC(NumPromoted , "Number of memory locations promoted to registers");
71 DisablePromotion("disable-licm-promotion", cl::Hidden,
72 cl::desc("Disable memory promotion in LICM pass"));
74 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
75 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop);
76 static bool hoist(Instruction &I, BasicBlock *Preheader);
77 static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
78 const Loop *CurLoop, AliasSetTracker *CurAST );
79 static bool isGuaranteedToExecute(const Instruction &Inst,
80 const DominatorTree *DT,
82 const LICMSafetyInfo *SafetyInfo);
83 static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
84 const DominatorTree *DT,
85 const TargetLibraryInfo *TLI,
87 const LICMSafetyInfo *SafetyInfo,
88 const Instruction *CtxI = nullptr);
89 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
90 const AAMDNodes &AAInfo,
91 AliasSetTracker *CurAST);
92 static Instruction *CloneInstructionInExitBlock(const Instruction &I,
93 BasicBlock &ExitBlock,
96 static bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA,
97 DominatorTree *DT, TargetLibraryInfo *TLI,
98 Loop *CurLoop, AliasSetTracker *CurAST,
99 LICMSafetyInfo *SafetyInfo);
102 struct LICM : public LoopPass {
103 static char ID; // Pass identification, replacement for typeid
104 LICM() : LoopPass(ID) {
105 initializeLICMPass(*PassRegistry::getPassRegistry());
108 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
110 /// This transformation requires natural loop information & requires that
111 /// loop preheaders be inserted into the CFG...
113 void getAnalysisUsage(AnalysisUsage &AU) const override {
114 AU.setPreservesCFG();
115 AU.addRequired<DominatorTreeWrapperPass>();
116 AU.addRequired<LoopInfoWrapperPass>();
117 AU.addRequiredID(LoopSimplifyID);
118 AU.addPreservedID(LoopSimplifyID);
119 AU.addRequiredID(LCSSAID);
120 AU.addPreservedID(LCSSAID);
121 AU.addRequired<AliasAnalysis>();
122 AU.addPreserved<AliasAnalysis>();
123 AU.addPreserved<ScalarEvolutionWrapperPass>();
124 AU.addRequired<TargetLibraryInfoWrapperPass>();
127 using llvm::Pass::doFinalization;
129 bool doFinalization() override {
130 assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets");
135 AliasAnalysis *AA; // Current AliasAnalysis information
136 LoopInfo *LI; // Current LoopInfo
137 DominatorTree *DT; // Dominator Tree for the current Loop.
139 TargetLibraryInfo *TLI; // TargetLibraryInfo for constant folding.
141 // State that is updated as we process loops.
142 bool Changed; // Set to true when we change anything.
143 BasicBlock *Preheader; // The preheader block of the current loop...
144 Loop *CurLoop; // The current loop we are working on...
145 AliasSetTracker *CurAST; // AliasSet information for the current loop...
146 DenseMap<Loop*, AliasSetTracker*> LoopToAliasSetMap;
148 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
149 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
152 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
154 void deleteAnalysisValue(Value *V, Loop *L) override;
156 /// Simple Analysis hook. Delete loop L from alias set map.
157 void deleteAnalysisLoop(Loop *L) override;
162 INITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false)
163 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
164 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
165 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
166 INITIALIZE_PASS_DEPENDENCY(LCSSA)
167 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
168 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
169 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
170 INITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false)
172 Pass *llvm::createLICMPass() { return new LICM(); }
174 /// Hoist expressions out of the specified loop. Note, alias info for inner
175 /// loop is not preserved so it is not a good idea to run LICM multiple
176 /// times on one loop.
178 bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
179 if (skipOptnoneFunction(L))
184 // Get our Loop and Alias Analysis information...
185 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
186 AA = &getAnalysis<AliasAnalysis>();
187 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
189 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
191 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
193 CurAST = new AliasSetTracker(*AA);
194 // Collect Alias info from subloops.
195 for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
196 LoopItr != LoopItrE; ++LoopItr) {
197 Loop *InnerL = *LoopItr;
198 AliasSetTracker *InnerAST = LoopToAliasSetMap[InnerL];
199 assert(InnerAST && "Where is my AST?");
201 // What if InnerLoop was modified by other passes ?
202 CurAST->add(*InnerAST);
204 // Once we've incorporated the inner loop's AST into ours, we don't need the
205 // subloop's anymore.
207 LoopToAliasSetMap.erase(InnerL);
212 // Get the preheader block to move instructions into...
213 Preheader = L->getLoopPreheader();
215 // Loop over the body of this loop, looking for calls, invokes, and stores.
216 // Because subloops have already been incorporated into AST, we skip blocks in
219 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
222 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops.
223 CurAST->add(*BB); // Incorporate the specified basic block
226 // Compute loop safety information.
227 LICMSafetyInfo SafetyInfo;
228 computeLICMSafetyInfo(&SafetyInfo, CurLoop);
230 // We want to visit all of the instructions in this loop... that are not parts
231 // of our subloops (they have already had their invariants hoisted out of
232 // their loop, into this loop, so there is no need to process the BODIES of
235 // Traverse the body of the loop in depth first order on the dominator tree so
236 // that we are guaranteed to see definitions before we see uses. This allows
237 // us to sink instructions in one pass, without iteration. After sinking
238 // instructions, we perform another pass to hoist them out of the loop.
240 if (L->hasDedicatedExits())
241 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, CurLoop,
242 CurAST, &SafetyInfo);
244 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI,
245 CurLoop, CurAST, &SafetyInfo);
247 // Now that all loop invariants have been removed from the loop, promote any
248 // memory references to scalars that we can.
249 if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) {
250 SmallVector<BasicBlock *, 8> ExitBlocks;
251 SmallVector<Instruction *, 8> InsertPts;
252 PredIteratorCache PIC;
254 // Loop over all of the alias sets in the tracker object.
255 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
257 Changed |= promoteLoopAccessesToScalars(*I, ExitBlocks, InsertPts,
258 PIC, LI, DT, CurLoop,
259 CurAST, &SafetyInfo);
261 // Once we have promoted values across the loop body we have to recursively
262 // reform LCSSA as any nested loop may now have values defined within the
263 // loop used in the outer loop.
264 // FIXME: This is really heavy handed. It would be a bit better to use an
265 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
268 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
269 formLCSSARecursively(*L, *DT, LI, SEWP ? &SEWP->getSE() : nullptr);
273 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
274 // specifically moving instructions across the loop boundary and so it is
275 // especially in need of sanity checking here.
276 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
277 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
278 "Parent loop not left in LCSSA form after LICM!");
280 // Clear out loops state information for the next iteration
284 // If this loop is nested inside of another one, save the alias information
285 // for when we process the outer loop.
286 if (L->getParentLoop())
287 LoopToAliasSetMap[L] = CurAST;
293 /// Walk the specified region of the CFG (defined by all blocks dominated by
294 /// the specified block, and that are in the current loop) in reverse depth
295 /// first order w.r.t the DominatorTree. This allows us to visit uses before
296 /// definitions, allowing us to sink a loop body in one pass without iteration.
298 bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
299 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
300 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
303 assert(N != nullptr && AA != nullptr && LI != nullptr &&
304 DT != nullptr && CurLoop != nullptr && CurAST != nullptr &&
305 SafetyInfo != nullptr && "Unexpected input to sinkRegion");
307 // Set changed as false.
308 bool Changed = false;
310 BasicBlock *BB = N->getBlock();
311 // If this subregion is not in the top level loop at all, exit.
312 if (!CurLoop->contains(BB)) return Changed;
314 // We are processing blocks in reverse dfo, so process children first.
315 const std::vector<DomTreeNode*> &Children = N->getChildren();
316 for (unsigned i = 0, e = Children.size(); i != e; ++i)
318 sinkRegion(Children[i], AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
319 // Only need to process the contents of this block if it is not part of a
320 // subloop (which would already have been processed).
321 if (inSubLoop(BB,CurLoop,LI)) return Changed;
323 for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
324 Instruction &I = *--II;
326 // If the instruction is dead, we would try to sink it because it isn't used
327 // in the loop, instead, just delete it.
328 if (isInstructionTriviallyDead(&I, TLI)) {
329 DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
331 CurAST->deleteValue(&I);
337 // Check to see if we can sink this instruction to the exit blocks
338 // of the loop. We can do this if the all users of the instruction are
339 // outside of the loop. In this case, it doesn't even matter if the
340 // operands of the instruction are loop invariant.
342 if (isNotUsedInLoop(I, CurLoop) &&
343 canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo)) {
345 Changed |= sink(I, LI, DT, CurLoop, CurAST);
351 /// Walk the specified region of the CFG (defined by all blocks dominated by
352 /// the specified block, and that are in the current loop) in depth first
353 /// order w.r.t the DominatorTree. This allows us to visit definitions before
354 /// uses, allowing us to hoist a loop body in one pass without iteration.
356 bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
357 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
358 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
360 assert(N != nullptr && AA != nullptr && LI != nullptr &&
361 DT != nullptr && CurLoop != nullptr && CurAST != nullptr &&
362 SafetyInfo != nullptr && "Unexpected input to hoistRegion");
363 // Set changed as false.
364 bool Changed = false;
366 BasicBlock *BB = N->getBlock();
367 // If this subregion is not in the top level loop at all, exit.
368 if (!CurLoop->contains(BB)) return Changed;
369 // Only need to process the contents of this block if it is not part of a
370 // subloop (which would already have been processed).
371 if (!inSubLoop(BB, CurLoop, LI))
372 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
373 Instruction &I = *II++;
374 // Try constant folding this instruction. If all the operands are
375 // constants, it is technically hoistable, but it would be better to just
377 if (Constant *C = ConstantFoldInstruction(
378 &I, I.getModule()->getDataLayout(), TLI)) {
379 DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n');
380 CurAST->copyValue(&I, C);
381 CurAST->deleteValue(&I);
382 I.replaceAllUsesWith(C);
387 // Try hoisting the instruction out to the preheader. We can only do this
388 // if all of the operands of the instruction are loop invariant and if it
389 // is safe to hoist the instruction.
391 if (CurLoop->hasLoopInvariantOperands(&I) &&
392 canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo) &&
393 isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo,
394 CurLoop->getLoopPreheader()->getTerminator()))
395 Changed |= hoist(I, CurLoop->getLoopPreheader());
398 const std::vector<DomTreeNode*> &Children = N->getChildren();
399 for (unsigned i = 0, e = Children.size(); i != e; ++i)
401 hoistRegion(Children[i], AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
405 /// Computes loop safety information, checks loop body & header
406 /// for the possibility of may throw exception.
408 void llvm::computeLICMSafetyInfo(LICMSafetyInfo * SafetyInfo, Loop * CurLoop) {
409 assert(CurLoop != nullptr && "CurLoop cant be null");
410 BasicBlock *Header = CurLoop->getHeader();
411 // Setting default safety values.
412 SafetyInfo->MayThrow = false;
413 SafetyInfo->HeaderMayThrow = false;
414 // Iterate over header and compute safety info.
415 for (BasicBlock::iterator I = Header->begin(), E = Header->end();
416 (I != E) && !SafetyInfo->HeaderMayThrow; ++I)
417 SafetyInfo->HeaderMayThrow |= I->mayThrow();
419 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
420 // Iterate over loop instructions and compute safety info.
421 for (Loop::block_iterator BB = CurLoop->block_begin(),
422 BBE = CurLoop->block_end(); (BB != BBE) && !SafetyInfo->MayThrow ; ++BB)
423 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
424 (I != E) && !SafetyInfo->MayThrow; ++I)
425 SafetyInfo->MayThrow |= I->mayThrow();
428 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
431 bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA, DominatorTree *DT,
432 TargetLibraryInfo *TLI, Loop *CurLoop,
433 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
434 // Loads have extra constraints we have to verify before we can hoist them.
435 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
436 if (!LI->isUnordered())
437 return false; // Don't hoist volatile/atomic loads!
439 // Loads from constant memory are always safe to move, even if they end up
440 // in the same alias set as something that ends up being modified.
441 if (AA->pointsToConstantMemory(LI->getOperand(0)))
443 if (LI->getMetadata(LLVMContext::MD_invariant_load))
446 // Don't hoist loads which have may-aliased stores in loop.
448 if (LI->getType()->isSized())
449 Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType());
452 LI->getAAMetadata(AAInfo);
454 return !pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
455 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
456 // Don't sink or hoist dbg info; it's legal, but not useful.
457 if (isa<DbgInfoIntrinsic>(I))
460 // Handle simple cases by querying alias analysis.
461 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
462 if (Behavior == FMRB_DoesNotAccessMemory)
464 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
465 // If this call only reads from memory and there are no writes to memory
466 // in the loop, we can hoist or sink the call as appropriate.
467 bool FoundMod = false;
468 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
471 if (!AS.isForwardingAliasSet() && AS.isMod()) {
476 if (!FoundMod) return true;
479 // FIXME: This should use mod/ref information to see if we can hoist or
485 // Only these instructions are hoistable/sinkable.
486 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
487 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
488 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
489 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
490 !isa<InsertValueInst>(I))
493 // TODO: Plumb the context instruction through to make hoisting and sinking
494 // more powerful. Hoisting of loads already works due to the special casing
496 return isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo,
500 /// Returns true if a PHINode is a trivially replaceable with an
502 /// This is true when all incoming values are that instruction.
503 /// This pattern occurs most often with LCSSA PHI nodes.
505 static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) {
506 for (const Value *IncValue : PN.incoming_values())
513 /// Return true if the only users of this instruction are outside of
514 /// the loop. If this is true, we can sink the instruction to the exit
515 /// blocks of the loop.
517 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop) {
518 for (const User *U : I.users()) {
519 const Instruction *UI = cast<Instruction>(U);
520 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
521 // A PHI node where all of the incoming values are this instruction are
522 // special -- they can just be RAUW'ed with the instruction and thus
523 // don't require a use in the predecessor. This is a particular important
524 // special case because it is the pattern found in LCSSA form.
525 if (isTriviallyReplacablePHI(*PN, I)) {
526 if (CurLoop->contains(PN))
532 // Otherwise, PHI node uses occur in predecessor blocks if the incoming
533 // values. Check for such a use being inside the loop.
534 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
535 if (PN->getIncomingValue(i) == &I)
536 if (CurLoop->contains(PN->getIncomingBlock(i)))
542 if (CurLoop->contains(UI))
548 static Instruction *CloneInstructionInExitBlock(const Instruction &I,
549 BasicBlock &ExitBlock,
551 const LoopInfo *LI) {
552 Instruction *New = I.clone();
553 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
554 if (!I.getName().empty()) New->setName(I.getName() + ".le");
556 // Build LCSSA PHI nodes for any in-loop operands. Note that this is
557 // particularly cheap because we can rip off the PHI node that we're
558 // replacing for the number and blocks of the predecessors.
559 // OPT: If this shows up in a profile, we can instead finish sinking all
560 // invariant instructions, and then walk their operands to re-establish
561 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
562 // sinking bottom-up.
563 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
565 if (Instruction *OInst = dyn_cast<Instruction>(*OI))
566 if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
567 if (!OLoop->contains(&PN)) {
569 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
570 OInst->getName() + ".lcssa", ExitBlock.begin());
571 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
572 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
578 /// When an instruction is found to only be used outside of the loop, this
579 /// function moves it to the exit blocks and patches up SSA form as needed.
580 /// This method is guaranteed to remove the original instruction from its
581 /// position, and may either delete it or move it to outside of the loop.
583 static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
584 const Loop *CurLoop, AliasSetTracker *CurAST ) {
585 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
586 bool Changed = false;
587 if (isa<LoadInst>(I)) ++NumMovedLoads;
588 else if (isa<CallInst>(I)) ++NumMovedCalls;
593 SmallVector<BasicBlock *, 32> ExitBlocks;
594 CurLoop->getUniqueExitBlocks(ExitBlocks);
595 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
599 // Clones of this instruction. Don't create more than one per exit block!
600 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
602 // If this instruction is only used outside of the loop, then all users are
603 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
605 while (!I.use_empty()) {
606 Value::user_iterator UI = I.user_begin();
607 auto *User = cast<Instruction>(*UI);
608 if (!DT->isReachableFromEntry(User->getParent())) {
609 User->replaceUsesOfWith(&I, UndefValue::get(I.getType()));
612 // The user must be a PHI node.
613 PHINode *PN = cast<PHINode>(User);
615 // Surprisingly, instructions can be used outside of loops without any
616 // exits. This can only happen in PHI nodes if the incoming block is
618 Use &U = UI.getUse();
619 BasicBlock *BB = PN->getIncomingBlock(U);
620 if (!DT->isReachableFromEntry(BB)) {
621 U = UndefValue::get(I.getType());
625 BasicBlock *ExitBlock = PN->getParent();
626 assert(ExitBlockSet.count(ExitBlock) &&
627 "The LCSSA PHI is not in an exit block!");
630 auto It = SunkCopies.find(ExitBlock);
631 if (It != SunkCopies.end())
634 New = SunkCopies[ExitBlock] =
635 CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI);
637 PN->replaceAllUsesWith(New);
638 PN->eraseFromParent();
641 CurAST->deleteValue(&I);
646 /// When an instruction is found to only use loop invariant operands that
647 /// is safe to hoist, this instruction is called to do the dirty work.
649 static bool hoist(Instruction &I, BasicBlock *Preheader) {
650 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": "
652 // Move the new node to the Preheader, before its terminator.
653 I.moveBefore(Preheader->getTerminator());
655 if (isa<LoadInst>(I)) ++NumMovedLoads;
656 else if (isa<CallInst>(I)) ++NumMovedCalls;
661 /// Only sink or hoist an instruction if it is not a trapping instruction,
662 /// or if the instruction is known not to trap when moved to the preheader.
663 /// or if it is a trapping instruction and is guaranteed to execute.
664 static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
665 const DominatorTree *DT,
666 const TargetLibraryInfo *TLI,
668 const LICMSafetyInfo *SafetyInfo,
669 const Instruction *CtxI) {
670 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT, TLI))
673 return isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
676 static bool isGuaranteedToExecute(const Instruction &Inst,
677 const DominatorTree *DT,
679 const LICMSafetyInfo * SafetyInfo) {
681 // We have to check to make sure that the instruction dominates all
682 // of the exit blocks. If it doesn't, then there is a path out of the loop
683 // which does not execute this instruction, so we can't hoist it.
685 // If the instruction is in the header block for the loop (which is very
686 // common), it is always guaranteed to dominate the exit blocks. Since this
687 // is a common case, and can save some work, check it now.
688 if (Inst.getParent() == CurLoop->getHeader())
689 // If there's a throw in the header block, we can't guarantee we'll reach
691 return !SafetyInfo->HeaderMayThrow;
693 // Somewhere in this loop there is an instruction which may throw and make us
695 if (SafetyInfo->MayThrow)
698 // Get the exit blocks for the current loop.
699 SmallVector<BasicBlock*, 8> ExitBlocks;
700 CurLoop->getExitBlocks(ExitBlocks);
702 // Verify that the block dominates each of the exit blocks of the loop.
703 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
704 if (!DT->dominates(Inst.getParent(), ExitBlocks[i]))
707 // As a degenerate case, if the loop is statically infinite then we haven't
708 // proven anything since there are no exit blocks.
709 if (ExitBlocks.empty())
716 class LoopPromoter : public LoadAndStorePromoter {
717 Value *SomePtr; // Designated pointer to store to.
718 SmallPtrSetImpl<Value*> &PointerMustAliases;
719 SmallVectorImpl<BasicBlock*> &LoopExitBlocks;
720 SmallVectorImpl<Instruction*> &LoopInsertPts;
721 PredIteratorCache &PredCache;
722 AliasSetTracker &AST;
728 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
729 if (Instruction *I = dyn_cast<Instruction>(V))
730 if (Loop *L = LI.getLoopFor(I->getParent()))
731 if (!L->contains(BB)) {
732 // We need to create an LCSSA PHI node for the incoming value and
734 PHINode *PN = PHINode::Create(
735 I->getType(), PredCache.size(BB),
736 I->getName() + ".lcssa", BB->begin());
737 for (BasicBlock *Pred : PredCache.get(BB))
738 PN->addIncoming(I, Pred);
745 LoopPromoter(Value *SP,
746 ArrayRef<const Instruction *> Insts,
747 SSAUpdater &S, SmallPtrSetImpl<Value *> &PMA,
748 SmallVectorImpl<BasicBlock *> &LEB,
749 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
750 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
751 const AAMDNodes &AATags)
752 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
753 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
754 LI(li), DL(dl), Alignment(alignment), AATags(AATags) {}
756 bool isInstInList(Instruction *I,
757 const SmallVectorImpl<Instruction*> &) const override {
759 if (LoadInst *LI = dyn_cast<LoadInst>(I))
760 Ptr = LI->getOperand(0);
762 Ptr = cast<StoreInst>(I)->getPointerOperand();
763 return PointerMustAliases.count(Ptr);
766 void doExtraRewritesBeforeFinalDeletion() const override {
767 // Insert stores after in the loop exit blocks. Each exit block gets a
768 // store of the live-out values that feed them. Since we've already told
769 // the SSA updater about the defs in the loop and the preheader
770 // definition, it is all set and we can start using it.
771 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
772 BasicBlock *ExitBlock = LoopExitBlocks[i];
773 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
774 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
775 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
776 Instruction *InsertPos = LoopInsertPts[i];
777 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
778 NewSI->setAlignment(Alignment);
779 NewSI->setDebugLoc(DL);
780 if (AATags) NewSI->setAAMetadata(AATags);
784 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
785 // Update alias analysis.
786 AST.copyValue(LI, V);
788 void instructionDeleted(Instruction *I) const override {
792 } // end anon namespace
794 /// Try to promote memory values to scalars by sinking stores out of the
795 /// loop and moving loads to before the loop. We do this by looping over
796 /// the stores in the loop, looking for stores to Must pointers which are
799 bool llvm::promoteLoopAccessesToScalars(AliasSet &AS,
800 SmallVectorImpl<BasicBlock*>&ExitBlocks,
801 SmallVectorImpl<Instruction*>&InsertPts,
802 PredIteratorCache &PIC, LoopInfo *LI,
803 DominatorTree *DT, Loop *CurLoop,
804 AliasSetTracker *CurAST,
805 LICMSafetyInfo * SafetyInfo) {
807 assert(LI != nullptr && DT != nullptr &&
808 CurLoop != nullptr && CurAST != nullptr &&
809 SafetyInfo != nullptr &&
810 "Unexpected Input to promoteLoopAccessesToScalars");
811 // Initially set Changed status to false.
812 bool Changed = false;
813 // We can promote this alias set if it has a store, if it is a "Must" alias
814 // set, if the pointer is loop invariant, and if we are not eliminating any
815 // volatile loads or stores.
816 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
817 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
820 assert(!AS.empty() &&
821 "Must alias set should have at least one pointer element in it!");
823 Value *SomePtr = AS.begin()->getValue();
824 BasicBlock * Preheader = CurLoop->getLoopPreheader();
826 // It isn't safe to promote a load/store from the loop if the load/store is
827 // conditional. For example, turning:
829 // for () { if (c) *P += 1; }
833 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
835 // is not safe, because *P may only be valid to access if 'c' is true.
837 // It is safe to promote P if all uses are direct load/stores and if at
838 // least one is guaranteed to be executed.
839 bool GuaranteedToExecute = false;
841 SmallVector<Instruction*, 64> LoopUses;
842 SmallPtrSet<Value*, 4> PointerMustAliases;
844 // We start with an alignment of one and try to find instructions that allow
845 // us to prove better alignment.
846 unsigned Alignment = 1;
848 bool HasDedicatedExits = CurLoop->hasDedicatedExits();
850 // Check that all of the pointers in the alias set have the same type. We
851 // cannot (yet) promote a memory location that is loaded and stored in
852 // different sizes. While we are at it, collect alignment and AA info.
853 for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
854 Value *ASIV = ASI->getValue();
855 PointerMustAliases.insert(ASIV);
857 // Check that all of the pointers in the alias set have the same type. We
858 // cannot (yet) promote a memory location that is loaded and stored in
860 if (SomePtr->getType() != ASIV->getType())
863 for (User *U : ASIV->users()) {
864 // Ignore instructions that are outside the loop.
865 Instruction *UI = dyn_cast<Instruction>(U);
866 if (!UI || !CurLoop->contains(UI))
869 // If there is an non-load/store instruction in the loop, we can't promote
871 if (const LoadInst *load = dyn_cast<LoadInst>(UI)) {
872 assert(!load->isVolatile() && "AST broken");
873 if (!load->isSimple())
875 } else if (const StoreInst *store = dyn_cast<StoreInst>(UI)) {
876 // Stores *of* the pointer are not interesting, only stores *to* the
878 if (UI->getOperand(1) != ASIV)
880 assert(!store->isVolatile() && "AST broken");
881 if (!store->isSimple())
883 // Don't sink stores from loops without dedicated block exits. Exits
884 // containing indirect branches are not transformed by loop simplify,
885 // make sure we catch that. An additional load may be generated in the
886 // preheader for SSA updater, so also avoid sinking when no preheader
888 if (!HasDedicatedExits || !Preheader)
891 // Note that we only check GuaranteedToExecute inside the store case
892 // so that we do not introduce stores where they did not exist before
893 // (which would break the LLVM concurrency model).
895 // If the alignment of this instruction allows us to specify a more
896 // restrictive (and performant) alignment and if we are sure this
897 // instruction will be executed, update the alignment.
898 // Larger is better, with the exception of 0 being the best alignment.
899 unsigned InstAlignment = store->getAlignment();
900 if ((InstAlignment > Alignment || InstAlignment == 0) && Alignment != 0)
901 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
902 GuaranteedToExecute = true;
903 Alignment = InstAlignment;
906 if (!GuaranteedToExecute)
907 GuaranteedToExecute = isGuaranteedToExecute(*UI, DT,
908 CurLoop, SafetyInfo);
911 return Changed; // Not a load or store.
913 // Merge the AA tags.
914 if (LoopUses.empty()) {
915 // On the first load/store, just take its AA tags.
916 UI->getAAMetadata(AATags);
918 UI->getAAMetadata(AATags, /* Merge = */ true);
921 LoopUses.push_back(UI);
925 // If there isn't a guaranteed-to-execute instruction, we can't promote.
926 if (!GuaranteedToExecute)
929 // Otherwise, this is safe to promote, lets do it!
930 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n');
934 // Grab a debug location for the inserted loads/stores; given that the
935 // inserted loads/stores have little relation to the original loads/stores,
936 // this code just arbitrarily picks a location from one, since any debug
937 // location is better than none.
938 DebugLoc DL = LoopUses[0]->getDebugLoc();
940 // Figure out the loop exits and their insertion points, if this is the
942 if (ExitBlocks.empty()) {
943 CurLoop->getUniqueExitBlocks(ExitBlocks);
944 InsertPts.resize(ExitBlocks.size());
945 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
946 InsertPts[i] = ExitBlocks[i]->getFirstInsertionPt();
949 // We use the SSAUpdater interface to insert phi nodes as required.
950 SmallVector<PHINode*, 16> NewPHIs;
951 SSAUpdater SSA(&NewPHIs);
952 LoopPromoter Promoter(SomePtr, LoopUses, SSA,
953 PointerMustAliases, ExitBlocks,
954 InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags);
956 // Set up the preheader to have a definition of the value. It is the live-out
957 // value from the preheader that uses in the loop will use.
958 LoadInst *PreheaderLoad =
959 new LoadInst(SomePtr, SomePtr->getName()+".promoted",
960 Preheader->getTerminator());
961 PreheaderLoad->setAlignment(Alignment);
962 PreheaderLoad->setDebugLoc(DL);
963 if (AATags) PreheaderLoad->setAAMetadata(AATags);
964 SSA.AddAvailableValue(Preheader, PreheaderLoad);
966 // Rewrite all the loads in the loop and remember all the definitions from
967 // stores in the loop.
968 Promoter.run(LoopUses);
970 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
971 if (PreheaderLoad->use_empty())
972 PreheaderLoad->eraseFromParent();
977 /// Simple analysis hook. Clone alias set info.
979 void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
980 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
984 AST->copyValue(From, To);
987 /// Simple Analysis hook. Delete value V from alias set
989 void LICM::deleteAnalysisValue(Value *V, Loop *L) {
990 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
997 /// Simple Analysis hook. Delete value L from alias set map.
999 void LICM::deleteAnalysisLoop(Loop *L) {
1000 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
1005 LoopToAliasSetMap.erase(L);
1009 /// Return true if the body of this loop may store into the memory
1010 /// location pointed to by V.
1012 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
1013 const AAMDNodes &AAInfo,
1014 AliasSetTracker *CurAST) {
1015 // Check to see if any of the basic blocks in CurLoop invalidate *V.
1016 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
1019 /// Little predicate that returns true if the specified basic block is in
1020 /// a subloop of the current one, not the current one itself.
1022 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1023 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1024 return LI->getLoopFor(BB) != CurLoop;