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