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