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