c16ffdbf64db2100da594570c601d652d8286c65
[oota-llvm.git] / lib / Transforms / Scalar / LICM.cpp
1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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 SSAUpdater to construct the appropriate SSA form for the value.
30 //
31 //===----------------------------------------------------------------------===//
32
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/ValueTracking.h"
42 #include "llvm/IR/CFG.h"
43 #include "llvm/IR/Constants.h"
44 #include "llvm/IR/DataLayout.h"
45 #include "llvm/IR/DerivedTypes.h"
46 #include "llvm/IR/Dominators.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/IntrinsicInst.h"
49 #include "llvm/IR/LLVMContext.h"
50 #include "llvm/IR/Metadata.h"
51 #include "llvm/IR/PredIteratorCache.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Target/TargetLibraryInfo.h"
56 #include "llvm/Transforms/Utils/Local.h"
57 #include "llvm/Transforms/Utils/LoopUtils.h"
58 #include "llvm/Transforms/Utils/SSAUpdater.h"
59 #include <algorithm>
60 using namespace llvm;
61
62 #define DEBUG_TYPE "licm"
63
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");
69
70 static cl::opt<bool>
71 DisablePromotion("disable-licm-promotion", cl::Hidden,
72                  cl::desc("Disable memory promotion in LICM pass"));
73
74 namespace {
75   struct LICM : public LoopPass {
76     static char ID; // Pass identification, replacement for typeid
77     LICM() : LoopPass(ID) {
78       initializeLICMPass(*PassRegistry::getPassRegistry());
79     }
80
81     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
82
83     /// This transformation requires natural loop information & requires that
84     /// loop preheaders be inserted into the CFG...
85     ///
86     void getAnalysisUsage(AnalysisUsage &AU) const override {
87       AU.setPreservesCFG();
88       AU.addRequired<DominatorTreeWrapperPass>();
89       AU.addRequired<LoopInfo>();
90       AU.addRequiredID(LoopSimplifyID);
91       AU.addPreservedID(LoopSimplifyID);
92       AU.addRequiredID(LCSSAID);
93       AU.addPreservedID(LCSSAID);
94       AU.addRequired<AliasAnalysis>();
95       AU.addPreserved<AliasAnalysis>();
96       AU.addPreserved<ScalarEvolution>();
97       AU.addRequired<TargetLibraryInfo>();
98     }
99
100     using llvm::Pass::doFinalization;
101
102     bool doFinalization() override {
103       assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets");
104       return false;
105     }
106
107   private:
108     AliasAnalysis *AA;       // Current AliasAnalysis information
109     LoopInfo      *LI;       // Current LoopInfo
110     DominatorTree *DT;       // Dominator Tree for the current Loop.
111
112     const DataLayout *DL;    // DataLayout for constant folding.
113     TargetLibraryInfo *TLI;  // TargetLibraryInfo for constant folding.
114
115     // State that is updated as we process loops.
116     bool Changed;            // Set to true when we change anything.
117     BasicBlock *Preheader;   // The preheader block of the current loop...
118     Loop *CurLoop;           // The current loop we are working on...
119     AliasSetTracker *CurAST; // AliasSet information for the current loop...
120     bool MayThrow;           // The current loop contains an instruction which
121                              // may throw, thus preventing code motion of
122                              // instructions with side effects.
123     DenseMap<Loop*, AliasSetTracker*> LoopToAliasSetMap;
124
125     /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
126     void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
127                                  Loop *L) override;
128
129     /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
130     /// set.
131     void deleteAnalysisValue(Value *V, Loop *L) override;
132
133     /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
134     /// dominated by the specified block, and that are in the current loop) in
135     /// reverse depth first order w.r.t the DominatorTree.  This allows us to
136     /// visit uses before definitions, allowing us to sink a loop body in one
137     /// pass without iteration.
138     ///
139     void SinkRegion(DomTreeNode *N);
140
141     /// HoistRegion - Walk the specified region of the CFG (defined by all
142     /// blocks dominated by the specified block, and that are in the current
143     /// loop) in depth first order w.r.t the DominatorTree.  This allows us to
144     /// visit definitions before uses, allowing us to hoist a loop body in one
145     /// pass without iteration.
146     ///
147     void HoistRegion(DomTreeNode *N);
148
149     /// inSubLoop - Little predicate that returns true if the specified basic
150     /// block is in a subloop of the current one, not the current one itself.
151     ///
152     bool inSubLoop(BasicBlock *BB) {
153       assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
154       return LI->getLoopFor(BB) != CurLoop;
155     }
156
157     /// sink - When an instruction is found to only be used outside of the loop,
158     /// this function moves it to the exit blocks and patches up SSA form as
159     /// needed.
160     ///
161     void sink(Instruction &I);
162
163     /// hoist - When an instruction is found to only use loop invariant operands
164     /// that is safe to hoist, this instruction is called to do the dirty work.
165     ///
166     void hoist(Instruction &I);
167
168     /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
169     /// is not a trapping instruction or if it is a trapping instruction and is
170     /// guaranteed to execute.
171     ///
172     bool isSafeToExecuteUnconditionally(Instruction &I);
173
174     /// isGuaranteedToExecute - Check that the instruction is guaranteed to
175     /// execute.
176     ///
177     bool isGuaranteedToExecute(Instruction &I);
178
179     /// pointerInvalidatedByLoop - Return true if the body of this loop may
180     /// store into the memory location pointed to by V.
181     ///
182     bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
183                                   const MDNode *TBAAInfo) {
184       // Check to see if any of the basic blocks in CurLoop invalidate *V.
185       return CurAST->getAliasSetForPointer(V, Size, TBAAInfo).isMod();
186     }
187
188     bool canSinkOrHoistInst(Instruction &I);
189     bool isNotUsedInLoop(Instruction &I);
190
191     void PromoteAliasSet(AliasSet &AS,
192                          SmallVectorImpl<BasicBlock*> &ExitBlocks,
193                          SmallVectorImpl<Instruction*> &InsertPts,
194                          PredIteratorCache &PIC);
195   };
196 }
197
198 char LICM::ID = 0;
199 INITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false)
200 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
201 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
202 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
203 INITIALIZE_PASS_DEPENDENCY(LCSSA)
204 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
205 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
206 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
207 INITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false)
208
209 Pass *llvm::createLICMPass() { return new LICM(); }
210
211 /// Hoist expressions out of the specified loop. Note, alias info for inner
212 /// loop is not preserved so it is not a good idea to run LICM multiple
213 /// times on one loop.
214 ///
215 bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
216   if (skipOptnoneFunction(L))
217     return false;
218
219   Changed = false;
220
221   // Get our Loop and Alias Analysis information...
222   LI = &getAnalysis<LoopInfo>();
223   AA = &getAnalysis<AliasAnalysis>();
224   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
225
226   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
227   DL = DLP ? &DLP->getDataLayout() : nullptr;
228   TLI = &getAnalysis<TargetLibraryInfo>();
229
230   assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
231
232   CurAST = new AliasSetTracker(*AA);
233   // Collect Alias info from subloops.
234   for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
235        LoopItr != LoopItrE; ++LoopItr) {
236     Loop *InnerL = *LoopItr;
237     AliasSetTracker *InnerAST = LoopToAliasSetMap[InnerL];
238     assert(InnerAST && "Where is my AST?");
239
240     // What if InnerLoop was modified by other passes ?
241     CurAST->add(*InnerAST);
242
243     // Once we've incorporated the inner loop's AST into ours, we don't need the
244     // subloop's anymore.
245     delete InnerAST;
246     LoopToAliasSetMap.erase(InnerL);
247   }
248
249   CurLoop = L;
250
251   // Get the preheader block to move instructions into...
252   Preheader = L->getLoopPreheader();
253
254   // Loop over the body of this loop, looking for calls, invokes, and stores.
255   // Because subloops have already been incorporated into AST, we skip blocks in
256   // subloops.
257   //
258   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
259        I != E; ++I) {
260     BasicBlock *BB = *I;
261     if (LI->getLoopFor(BB) == L)        // Ignore blocks in subloops.
262       CurAST->add(*BB);                 // Incorporate the specified basic block
263   }
264
265   MayThrow = false;
266   // TODO: We've already searched for instructions which may throw in subloops.
267   // We may want to reuse this information.
268   for (Loop::block_iterator BB = L->block_begin(), BBE = L->block_end();
269        (BB != BBE) && !MayThrow ; ++BB)
270     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
271          (I != E) && !MayThrow; ++I)
272       MayThrow |= I->mayThrow();
273
274   // We want to visit all of the instructions in this loop... that are not parts
275   // of our subloops (they have already had their invariants hoisted out of
276   // their loop, into this loop, so there is no need to process the BODIES of
277   // the subloops).
278   //
279   // Traverse the body of the loop in depth first order on the dominator tree so
280   // that we are guaranteed to see definitions before we see uses.  This allows
281   // us to sink instructions in one pass, without iteration.  After sinking
282   // instructions, we perform another pass to hoist them out of the loop.
283   //
284   if (L->hasDedicatedExits())
285     SinkRegion(DT->getNode(L->getHeader()));
286   if (Preheader)
287     HoistRegion(DT->getNode(L->getHeader()));
288
289   // Now that all loop invariants have been removed from the loop, promote any
290   // memory references to scalars that we can.
291   if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) {
292     SmallVector<BasicBlock *, 8> ExitBlocks;
293     SmallVector<Instruction *, 8> InsertPts;
294     PredIteratorCache PIC;
295
296     // Loop over all of the alias sets in the tracker object.
297     for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
298          I != E; ++I)
299       PromoteAliasSet(*I, ExitBlocks, InsertPts, PIC);
300
301     // Once we have promoted values across the loop body we have to recursively
302     // reform LCSSA as any nested loop may now have values defined within the
303     // loop used in the outer loop.
304     // FIXME: This is really heavy handed. It would be a bit better to use an
305     // SSAUpdater strategy during promotion that was LCSSA aware and reformed
306     // it as it went.
307     if (Changed)
308       formLCSSARecursively(*L, *DT, getAnalysisIfAvailable<ScalarEvolution>());
309   }
310
311   // Check that neither this loop nor its parent have had LCSSA broken. LICM is
312   // specifically moving instructions across the loop boundary and so it is
313   // especially in need of sanity checking here.
314   assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
315   assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
316          "Parent loop not left in LCSSA form after LICM!");
317
318   // Clear out loops state information for the next iteration
319   CurLoop = nullptr;
320   Preheader = nullptr;
321
322   // If this loop is nested inside of another one, save the alias information
323   // for when we process the outer loop.
324   if (L->getParentLoop())
325     LoopToAliasSetMap[L] = CurAST;
326   else
327     delete CurAST;
328   return Changed;
329 }
330
331 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
332 /// dominated by the specified block, and that are in the current loop) in
333 /// reverse depth first order w.r.t the DominatorTree.  This allows us to visit
334 /// uses before definitions, allowing us to sink a loop body in one pass without
335 /// iteration.
336 ///
337 void LICM::SinkRegion(DomTreeNode *N) {
338   assert(N != nullptr && "Null dominator tree node?");
339   BasicBlock *BB = N->getBlock();
340
341   // If this subregion is not in the top level loop at all, exit.
342   if (!CurLoop->contains(BB)) return;
343
344   // We are processing blocks in reverse dfo, so process children first.
345   const std::vector<DomTreeNode*> &Children = N->getChildren();
346   for (unsigned i = 0, e = Children.size(); i != e; ++i)
347     SinkRegion(Children[i]);
348
349   // Only need to process the contents of this block if it is not part of a
350   // subloop (which would already have been processed).
351   if (inSubLoop(BB)) return;
352
353   for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
354     Instruction &I = *--II;
355
356     // If the instruction is dead, we would try to sink it because it isn't used
357     // in the loop, instead, just delete it.
358     if (isInstructionTriviallyDead(&I, TLI)) {
359       DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
360       ++II;
361       CurAST->deleteValue(&I);
362       I.eraseFromParent();
363       Changed = true;
364       continue;
365     }
366
367     // Check to see if we can sink this instruction to the exit blocks
368     // of the loop.  We can do this if the all users of the instruction are
369     // outside of the loop.  In this case, it doesn't even matter if the
370     // operands of the instruction are loop invariant.
371     //
372     if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
373       ++II;
374       sink(I);
375     }
376   }
377 }
378
379 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
380 /// dominated by the specified block, and that are in the current loop) in depth
381 /// first order w.r.t the DominatorTree.  This allows us to visit definitions
382 /// before uses, allowing us to hoist a loop body in one pass without iteration.
383 ///
384 void LICM::HoistRegion(DomTreeNode *N) {
385   assert(N != nullptr && "Null dominator tree node?");
386   BasicBlock *BB = N->getBlock();
387
388   // If this subregion is not in the top level loop at all, exit.
389   if (!CurLoop->contains(BB)) return;
390
391   // Only need to process the contents of this block if it is not part of a
392   // subloop (which would already have been processed).
393   if (!inSubLoop(BB))
394     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
395       Instruction &I = *II++;
396
397       // Try constant folding this instruction.  If all the operands are
398       // constants, it is technically hoistable, but it would be better to just
399       // fold it.
400       if (Constant *C = ConstantFoldInstruction(&I, DL, TLI)) {
401         DEBUG(dbgs() << "LICM folding inst: " << I << "  --> " << *C << '\n');
402         CurAST->copyValue(&I, C);
403         CurAST->deleteValue(&I);
404         I.replaceAllUsesWith(C);
405         I.eraseFromParent();
406         continue;
407       }
408
409       // Try hoisting the instruction out to the preheader.  We can only do this
410       // if all of the operands of the instruction are loop invariant and if it
411       // is safe to hoist the instruction.
412       //
413       if (CurLoop->hasLoopInvariantOperands(&I) && canSinkOrHoistInst(I) &&
414           isSafeToExecuteUnconditionally(I))
415         hoist(I);
416     }
417
418   const std::vector<DomTreeNode*> &Children = N->getChildren();
419   for (unsigned i = 0, e = Children.size(); i != e; ++i)
420     HoistRegion(Children[i]);
421 }
422
423 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
424 /// instruction.
425 ///
426 bool LICM::canSinkOrHoistInst(Instruction &I) {
427   // Loads have extra constraints we have to verify before we can hoist them.
428   if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
429     if (!LI->isUnordered())
430       return false;        // Don't hoist volatile/atomic loads!
431
432     // Loads from constant memory are always safe to move, even if they end up
433     // in the same alias set as something that ends up being modified.
434     if (AA->pointsToConstantMemory(LI->getOperand(0)))
435       return true;
436     if (LI->getMetadata("invariant.load"))
437       return true;
438
439     // Don't hoist loads which have may-aliased stores in loop.
440     uint64_t Size = 0;
441     if (LI->getType()->isSized())
442       Size = AA->getTypeStoreSize(LI->getType());
443     return !pointerInvalidatedByLoop(LI->getOperand(0), Size,
444                                      LI->getMetadata(LLVMContext::MD_tbaa));
445   } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
446     // Don't sink or hoist dbg info; it's legal, but not useful.
447     if (isa<DbgInfoIntrinsic>(I))
448       return false;
449
450     // Handle simple cases by querying alias analysis.
451     AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
452     if (Behavior == AliasAnalysis::DoesNotAccessMemory)
453       return true;
454     if (AliasAnalysis::onlyReadsMemory(Behavior)) {
455       // If this call only reads from memory and there are no writes to memory
456       // in the loop, we can hoist or sink the call as appropriate.
457       bool FoundMod = false;
458       for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
459            I != E; ++I) {
460         AliasSet &AS = *I;
461         if (!AS.isForwardingAliasSet() && AS.isMod()) {
462           FoundMod = true;
463           break;
464         }
465       }
466       if (!FoundMod) return true;
467     }
468
469     // FIXME: This should use mod/ref information to see if we can hoist or
470     // sink the call.
471
472     return false;
473   }
474
475   // Only these instructions are hoistable/sinkable.
476   if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
477       !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
478       !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
479       !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
480       !isa<InsertValueInst>(I))
481     return false;
482
483   return isSafeToExecuteUnconditionally(I);
484 }
485
486 /// \brief Returns true if a PHINode is a trivially replaceable with an
487 /// Instruction.
488 ///
489 /// This is true when all incoming values are that instruction. This pattern
490 /// occurs most often with LCSSA PHI nodes.
491 static bool isTriviallyReplacablePHI(PHINode &PN, Instruction &I) {
492   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
493     if (PN.getIncomingValue(i) != &I)
494       return false;
495
496   return true;
497 }
498
499 /// isNotUsedInLoop - Return true if the only users of this instruction are
500 /// outside of the loop.  If this is true, we can sink the instruction to the
501 /// exit blocks of the loop.
502 ///
503 bool LICM::isNotUsedInLoop(Instruction &I) {
504   for (User *U : I.users()) {
505     Instruction *UI = cast<Instruction>(U);
506     if (PHINode *PN = dyn_cast<PHINode>(UI)) {
507       // A PHI node where all of the incoming values are this instruction are
508       // special -- they can just be RAUW'ed with the instruction and thus
509       // don't require a use in the predecessor. This is a particular important
510       // special case because it is the pattern found in LCSSA form.
511       if (isTriviallyReplacablePHI(*PN, I)) {
512         if (CurLoop->contains(PN))
513           return false;
514         else
515           continue;
516       }
517
518       // Otherwise, PHI node uses occur in predecessor blocks if the incoming
519       // values. Check for such a use being inside the loop.
520       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
521         if (PN->getIncomingValue(i) == &I)
522           if (CurLoop->contains(PN->getIncomingBlock(i)))
523             return false;
524
525       continue;
526     }
527
528     if (CurLoop->contains(UI))
529       return false;
530   }
531   return true;
532 }
533
534 /// sink - When an instruction is found to only be used outside of the loop,
535 /// this function moves it to the exit blocks and patches up SSA form as needed.
536 /// This method is guaranteed to remove the original instruction from its
537 /// position, and may either delete it or move it to outside of the loop.
538 ///
539 void LICM::sink(Instruction &I) {
540   DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
541
542   if (isa<LoadInst>(I)) ++NumMovedLoads;
543   else if (isa<CallInst>(I)) ++NumMovedCalls;
544   ++NumSunk;
545   Changed = true;
546
547 #ifndef NDEBUG
548   SmallVector<BasicBlock *, 32> ExitBlocks;
549   CurLoop->getUniqueExitBlocks(ExitBlocks);
550   SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end());
551 #endif
552
553   // Clones of this instruction. Don't create more than one per exit block!
554   SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
555
556   // If this instruction is only used outside of the loop, then all users are
557   // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
558   // the instruction.
559   while (!I.use_empty()) {
560     // The user must be a PHI node.
561     PHINode *PN = cast<PHINode>(I.user_back());
562
563     BasicBlock *ExitBlock = PN->getParent();
564     assert(ExitBlockSet.count(ExitBlock) &&
565            "The LCSSA PHI is not in an exit block!");
566
567     Instruction *New;
568     auto It = SunkCopies.find(ExitBlock);
569     if (It != SunkCopies.end()) {
570       New = It->second;
571     } else {
572       New = I.clone();
573       SunkCopies[ExitBlock] = New;
574       ExitBlock->getInstList().insert(ExitBlock->getFirstInsertionPt(), New);
575       if (!I.getName().empty())
576         New->setName(I.getName() + ".le");
577
578       // Build LCSSA PHI nodes for any in-loop operands. Note that this is
579       // particularly cheap because we can rip off the PHI node that we're
580       // replacing for the number and blocks of the predecessors.
581       // OPT: If this shows up in a profile, we can instead finish sinking all
582       // invariant instructions, and then walk their operands to re-establish
583       // LCSSA. That will eliminate creating PHI nodes just to nuke them when
584       // sinking bottom-up.
585       for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
586            ++OI)
587         if (Instruction *OInst = dyn_cast<Instruction>(*OI))
588           if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
589             if (!OLoop->contains(PN)) {
590               PHINode *OpPN = PHINode::Create(
591                   OInst->getType(), PN->getNumIncomingValues(),
592                   OInst->getName() + ".lcssa", ExitBlock->begin());
593               for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
594                 OpPN->addIncoming(OInst, PN->getIncomingBlock(i));
595               *OI = OpPN;
596             }
597     }
598
599     PN->replaceAllUsesWith(New);
600     PN->eraseFromParent();
601   }
602
603   CurAST->deleteValue(&I);
604   I.eraseFromParent();
605 }
606
607 /// hoist - When an instruction is found to only use loop invariant operands
608 /// that is safe to hoist, this instruction is called to do the dirty work.
609 ///
610 void LICM::hoist(Instruction &I) {
611   DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": "
612         << I << "\n");
613
614   // Move the new node to the Preheader, before its terminator.
615   I.moveBefore(Preheader->getTerminator());
616
617   if (isa<LoadInst>(I)) ++NumMovedLoads;
618   else if (isa<CallInst>(I)) ++NumMovedCalls;
619   ++NumHoisted;
620   Changed = true;
621 }
622
623 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
624 /// not a trapping instruction or if it is a trapping instruction and is
625 /// guaranteed to execute.
626 ///
627 bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
628   // If it is not a trapping instruction, it is always safe to hoist.
629   if (isSafeToSpeculativelyExecute(&Inst))
630     return true;
631
632   return isGuaranteedToExecute(Inst);
633 }
634
635 bool LICM::isGuaranteedToExecute(Instruction &Inst) {
636
637   // Somewhere in this loop there is an instruction which may throw and make us
638   // exit the loop.
639   if (MayThrow)
640     return false;
641
642   // Otherwise we have to check to make sure that the instruction dominates all
643   // of the exit blocks.  If it doesn't, then there is a path out of the loop
644   // which does not execute this instruction, so we can't hoist it.
645
646   // If the instruction is in the header block for the loop (which is very
647   // common), it is always guaranteed to dominate the exit blocks.  Since this
648   // is a common case, and can save some work, check it now.
649   if (Inst.getParent() == CurLoop->getHeader())
650     return true;
651
652   // Get the exit blocks for the current loop.
653   SmallVector<BasicBlock*, 8> ExitBlocks;
654   CurLoop->getExitBlocks(ExitBlocks);
655
656   // Verify that the block dominates each of the exit blocks of the loop.
657   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
658     if (!DT->dominates(Inst.getParent(), ExitBlocks[i]))
659       return false;
660
661   // As a degenerate case, if the loop is statically infinite then we haven't
662   // proven anything since there are no exit blocks.
663   if (ExitBlocks.empty())
664     return false;
665
666   return true;
667 }
668
669 namespace {
670   class LoopPromoter : public LoadAndStorePromoter {
671     Value *SomePtr;  // Designated pointer to store to.
672     SmallPtrSet<Value*, 4> &PointerMustAliases;
673     SmallVectorImpl<BasicBlock*> &LoopExitBlocks;
674     SmallVectorImpl<Instruction*> &LoopInsertPts;
675     PredIteratorCache &PredCache;
676     AliasSetTracker &AST;
677     LoopInfo &LI;
678     DebugLoc DL;
679     int Alignment;
680     MDNode *TBAATag;
681
682     Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
683       if (Instruction *I = dyn_cast<Instruction>(V))
684         if (Loop *L = LI.getLoopFor(I->getParent()))
685           if (!L->contains(BB)) {
686             // We need to create an LCSSA PHI node for the incoming value and
687             // store that.
688             PHINode *PN = PHINode::Create(
689                 I->getType(), PredCache.GetNumPreds(BB),
690                 I->getName() + ".lcssa", BB->begin());
691             for (BasicBlock **PI = PredCache.GetPreds(BB); *PI; ++PI)
692               PN->addIncoming(I, *PI);
693             return PN;
694           }
695       return V;
696     }
697
698   public:
699     LoopPromoter(Value *SP, const SmallVectorImpl<Instruction *> &Insts,
700                  SSAUpdater &S, SmallPtrSet<Value *, 4> &PMA,
701                  SmallVectorImpl<BasicBlock *> &LEB,
702                  SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
703                  AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
704                  MDNode *TBAATag)
705         : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
706           LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
707           LI(li), DL(dl), Alignment(alignment), TBAATag(TBAATag) {}
708
709     bool isInstInList(Instruction *I,
710                       const SmallVectorImpl<Instruction*> &) const override {
711       Value *Ptr;
712       if (LoadInst *LI = dyn_cast<LoadInst>(I))
713         Ptr = LI->getOperand(0);
714       else
715         Ptr = cast<StoreInst>(I)->getPointerOperand();
716       return PointerMustAliases.count(Ptr);
717     }
718
719     void doExtraRewritesBeforeFinalDeletion() const override {
720       // Insert stores after in the loop exit blocks.  Each exit block gets a
721       // store of the live-out values that feed them.  Since we've already told
722       // the SSA updater about the defs in the loop and the preheader
723       // definition, it is all set and we can start using it.
724       for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
725         BasicBlock *ExitBlock = LoopExitBlocks[i];
726         Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
727         LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
728         Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
729         Instruction *InsertPos = LoopInsertPts[i];
730         StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
731         NewSI->setAlignment(Alignment);
732         NewSI->setDebugLoc(DL);
733         if (TBAATag) NewSI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
734       }
735     }
736
737     void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
738       // Update alias analysis.
739       AST.copyValue(LI, V);
740     }
741     void instructionDeleted(Instruction *I) const override {
742       AST.deleteValue(I);
743     }
744   };
745 } // end anon namespace
746
747 /// PromoteAliasSet - Try to promote memory values to scalars by sinking
748 /// stores out of the loop and moving loads to before the loop.  We do this by
749 /// looping over the stores in the loop, looking for stores to Must pointers
750 /// which are loop invariant.
751 ///
752 void LICM::PromoteAliasSet(AliasSet &AS,
753                            SmallVectorImpl<BasicBlock*> &ExitBlocks,
754                            SmallVectorImpl<Instruction*> &InsertPts,
755                            PredIteratorCache &PIC) {
756   // We can promote this alias set if it has a store, if it is a "Must" alias
757   // set, if the pointer is loop invariant, and if we are not eliminating any
758   // volatile loads or stores.
759   if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
760       AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
761     return;
762
763   assert(!AS.empty() &&
764          "Must alias set should have at least one pointer element in it!");
765   Value *SomePtr = AS.begin()->getValue();
766
767   // It isn't safe to promote a load/store from the loop if the load/store is
768   // conditional.  For example, turning:
769   //
770   //    for () { if (c) *P += 1; }
771   //
772   // into:
773   //
774   //    tmp = *P;  for () { if (c) tmp +=1; } *P = tmp;
775   //
776   // is not safe, because *P may only be valid to access if 'c' is true.
777   //
778   // It is safe to promote P if all uses are direct load/stores and if at
779   // least one is guaranteed to be executed.
780   bool GuaranteedToExecute = false;
781
782   SmallVector<Instruction*, 64> LoopUses;
783   SmallPtrSet<Value*, 4> PointerMustAliases;
784
785   // We start with an alignment of one and try to find instructions that allow
786   // us to prove better alignment.
787   unsigned Alignment = 1;
788   MDNode *TBAATag = nullptr;
789
790   // Check that all of the pointers in the alias set have the same type.  We
791   // cannot (yet) promote a memory location that is loaded and stored in
792   // different sizes.  While we are at it, collect alignment and TBAA info.
793   for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
794     Value *ASIV = ASI->getValue();
795     PointerMustAliases.insert(ASIV);
796
797     // Check that all of the pointers in the alias set have the same type.  We
798     // cannot (yet) promote a memory location that is loaded and stored in
799     // different sizes.
800     if (SomePtr->getType() != ASIV->getType())
801       return;
802
803     for (User *U : ASIV->users()) {
804       // Ignore instructions that are outside the loop.
805       Instruction *UI = dyn_cast<Instruction>(U);
806       if (!UI || !CurLoop->contains(UI))
807         continue;
808
809       // If there is an non-load/store instruction in the loop, we can't promote
810       // it.
811       if (LoadInst *load = dyn_cast<LoadInst>(UI)) {
812         assert(!load->isVolatile() && "AST broken");
813         if (!load->isSimple())
814           return;
815       } else if (StoreInst *store = dyn_cast<StoreInst>(UI)) {
816         // Stores *of* the pointer are not interesting, only stores *to* the
817         // pointer.
818         if (UI->getOperand(1) != ASIV)
819           continue;
820         assert(!store->isVolatile() && "AST broken");
821         if (!store->isSimple())
822           return;
823
824         // Note that we only check GuaranteedToExecute inside the store case
825         // so that we do not introduce stores where they did not exist before
826         // (which would break the LLVM concurrency model).
827
828         // If the alignment of this instruction allows us to specify a more
829         // restrictive (and performant) alignment and if we are sure this
830         // instruction will be executed, update the alignment.
831         // Larger is better, with the exception of 0 being the best alignment.
832         unsigned InstAlignment = store->getAlignment();
833         if ((InstAlignment > Alignment || InstAlignment == 0) && Alignment != 0)
834           if (isGuaranteedToExecute(*UI)) {
835             GuaranteedToExecute = true;
836             Alignment = InstAlignment;
837           }
838
839         if (!GuaranteedToExecute)
840           GuaranteedToExecute = isGuaranteedToExecute(*UI);
841
842       } else
843         return; // Not a load or store.
844
845       // Merge the TBAA tags.
846       if (LoopUses.empty()) {
847         // On the first load/store, just take its TBAA tag.
848         TBAATag = UI->getMetadata(LLVMContext::MD_tbaa);
849       } else if (TBAATag) {
850         TBAATag = MDNode::getMostGenericTBAA(TBAATag,
851                                        UI->getMetadata(LLVMContext::MD_tbaa));
852       }
853
854       LoopUses.push_back(UI);
855     }
856   }
857
858   // If there isn't a guaranteed-to-execute instruction, we can't promote.
859   if (!GuaranteedToExecute)
860     return;
861
862   // Otherwise, this is safe to promote, lets do it!
863   DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n');
864   Changed = true;
865   ++NumPromoted;
866
867   // Grab a debug location for the inserted loads/stores; given that the
868   // inserted loads/stores have little relation to the original loads/stores,
869   // this code just arbitrarily picks a location from one, since any debug
870   // location is better than none.
871   DebugLoc DL = LoopUses[0]->getDebugLoc();
872
873   // Figure out the loop exits and their insertion points, if this is the
874   // first promotion.
875   if (ExitBlocks.empty()) {
876     CurLoop->getUniqueExitBlocks(ExitBlocks);
877     InsertPts.resize(ExitBlocks.size());
878     for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
879       InsertPts[i] = ExitBlocks[i]->getFirstInsertionPt();
880   }
881
882   // We use the SSAUpdater interface to insert phi nodes as required.
883   SmallVector<PHINode*, 16> NewPHIs;
884   SSAUpdater SSA(&NewPHIs);
885   LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
886                         InsertPts, PIC, *CurAST, *LI, DL, Alignment, TBAATag);
887
888   // Set up the preheader to have a definition of the value.  It is the live-out
889   // value from the preheader that uses in the loop will use.
890   LoadInst *PreheaderLoad =
891     new LoadInst(SomePtr, SomePtr->getName()+".promoted",
892                  Preheader->getTerminator());
893   PreheaderLoad->setAlignment(Alignment);
894   PreheaderLoad->setDebugLoc(DL);
895   if (TBAATag) PreheaderLoad->setMetadata(LLVMContext::MD_tbaa, TBAATag);
896   SSA.AddAvailableValue(Preheader, PreheaderLoad);
897
898   // Rewrite all the loads in the loop and remember all the definitions from
899   // stores in the loop.
900   Promoter.run(LoopUses);
901
902   // If the SSAUpdater didn't use the load in the preheader, just zap it now.
903   if (PreheaderLoad->use_empty())
904     PreheaderLoad->eraseFromParent();
905 }
906
907
908 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
909 void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
910   AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
911   if (!AST)
912     return;
913
914   AST->copyValue(From, To);
915 }
916
917 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
918 /// set.
919 void LICM::deleteAnalysisValue(Value *V, Loop *L) {
920   AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
921   if (!AST)
922     return;
923
924   AST->deleteValue(V);
925 }