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/MemoryBuiltins.h"
45 #include "llvm/Analysis/OptimizationRemarkEmitter.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/Scalar/LoopPassManager.h"
65 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
66 #include "llvm/Transforms/Utils/Local.h"
67 #include "llvm/Transforms/Utils/LoopUtils.h"
68 #include "llvm/Transforms/Utils/SSAUpdater.h"
69 #include <algorithm>
70 #include <utility>
71 using namespace llvm;
72 
73 #define DEBUG_TYPE "licm"
74 
75 STATISTIC(NumSunk, "Number of instructions sunk out of loop");
76 STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
77 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
78 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
79 STATISTIC(NumPromoted, "Number of memory locations promoted to registers");
80 
81 /// Memory promotion is enabled by default.
82 static cl::opt<bool>
83     DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false),
84                      cl::desc("Disable memory promotion in LICM pass"));
85 
86 static cl::opt<uint32_t> MaxNumUsesTraversed(
87     "licm-max-num-uses-traversed", cl::Hidden, cl::init(8),
88     cl::desc("Max num uses visited for identifying load "
89              "invariance in loop using invariant start (default = 8)"));
90 
91 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
92 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
93                             const LoopSafetyInfo *SafetyInfo);
94 static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
95                   const LoopSafetyInfo *SafetyInfo,
96                   OptimizationRemarkEmitter *ORE);
97 static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
98                  const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo,
99                  OptimizationRemarkEmitter *ORE);
100 static bool isSafeToExecuteUnconditionally(Instruction &Inst,
101                                            const DominatorTree *DT,
102                                            const Loop *CurLoop,
103                                            const LoopSafetyInfo *SafetyInfo,
104                                            OptimizationRemarkEmitter *ORE,
105                                            const Instruction *CtxI = nullptr);
106 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
107                                      const AAMDNodes &AAInfo,
108                                      AliasSetTracker *CurAST);
109 static Instruction *
110 CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
111                             const LoopInfo *LI,
112                             const LoopSafetyInfo *SafetyInfo);
113 
114 namespace {
115 struct LoopInvariantCodeMotion {
116   bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
117                  TargetLibraryInfo *TLI, ScalarEvolution *SE,
118                  OptimizationRemarkEmitter *ORE, bool DeleteAST);
119 
120   DenseMap<Loop *, AliasSetTracker *> &getLoopToAliasSetMap() {
121     return LoopToAliasSetMap;
122   }
123 
124 private:
125   DenseMap<Loop *, AliasSetTracker *> LoopToAliasSetMap;
126 
127   AliasSetTracker *collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
128                                            AliasAnalysis *AA);
129 };
130 
131 struct LegacyLICMPass : public LoopPass {
132   static char ID; // Pass identification, replacement for typeid
133   LegacyLICMPass() : LoopPass(ID) {
134     initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry());
135   }
136 
137   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
138     if (skipLoop(L)) {
139       // If we have run LICM on a previous loop but now we are skipping
140       // (because we've hit the opt-bisect limit), we need to clear the
141       // loop alias information.
142       for (auto &LTAS : LICM.getLoopToAliasSetMap())
143         delete LTAS.second;
144       LICM.getLoopToAliasSetMap().clear();
145       return false;
146     }
147 
148     auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
149     // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
150     // pass.  Function analyses need to be preserved across loop transformations
151     // but ORE cannot be preserved (see comment before the pass definition).
152     OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
153     return LICM.runOnLoop(L,
154                           &getAnalysis<AAResultsWrapperPass>().getAAResults(),
155                           &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
156                           &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
157                           &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
158                           SE ? &SE->getSE() : nullptr, &ORE, false);
159   }
160 
161   /// This transformation requires natural loop information & requires that
162   /// loop preheaders be inserted into the CFG...
163   ///
164   void getAnalysisUsage(AnalysisUsage &AU) const override {
165     AU.setPreservesCFG();
166     AU.addRequired<TargetLibraryInfoWrapperPass>();
167     getLoopAnalysisUsage(AU);
168   }
169 
170   using llvm::Pass::doFinalization;
171 
172   bool doFinalization() override {
173     assert(LICM.getLoopToAliasSetMap().empty() &&
174            "Didn't free loop alias sets");
175     return false;
176   }
177 
178 private:
179   LoopInvariantCodeMotion LICM;
180 
181   /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
182   void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
183                                Loop *L) override;
184 
185   /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
186   /// set.
187   void deleteAnalysisValue(Value *V, Loop *L) override;
188 
189   /// Simple Analysis hook. Delete loop L from alias set map.
190   void deleteAnalysisLoop(Loop *L) override;
191 };
192 } // namespace
193 
194 PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM,
195                                 LoopStandardAnalysisResults &AR, LPMUpdater &) {
196   const auto &FAM =
197       AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
198   Function *F = L.getHeader()->getParent();
199 
200   auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
201   // FIXME: This should probably be optional rather than required.
202   if (!ORE)
203     report_fatal_error("LICM: OptimizationRemarkEmitterAnalysis not "
204                        "cached at a higher level");
205 
206   LoopInvariantCodeMotion LICM;
207   if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.TLI, &AR.SE, ORE, true))
208     return PreservedAnalyses::all();
209 
210   auto PA = getLoopPassPreservedAnalyses();
211   PA.preserveSet<CFGAnalyses>();
212   return PA;
213 }
214 
215 char LegacyLICMPass::ID = 0;
216 INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
217                       false, false)
218 INITIALIZE_PASS_DEPENDENCY(LoopPass)
219 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
220 INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
221                     false)
222 
223 Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
224 
225 /// Hoist expressions out of the specified loop. Note, alias info for inner
226 /// loop is not preserved so it is not a good idea to run LICM multiple
227 /// times on one loop.
228 /// We should delete AST for inner loops in the new pass manager to avoid
229 /// memory leak.
230 ///
231 bool LoopInvariantCodeMotion::runOnLoop(Loop *L, AliasAnalysis *AA,
232                                         LoopInfo *LI, DominatorTree *DT,
233                                         TargetLibraryInfo *TLI,
234                                         ScalarEvolution *SE,
235                                         OptimizationRemarkEmitter *ORE,
236                                         bool DeleteAST) {
237   bool Changed = false;
238 
239   assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
240 
241   AliasSetTracker *CurAST = collectAliasInfoForLoop(L, LI, AA);
242 
243   // Get the preheader block to move instructions into...
244   BasicBlock *Preheader = L->getLoopPreheader();
245 
246   // Compute loop safety information.
247   LoopSafetyInfo SafetyInfo;
248   computeLoopSafetyInfo(&SafetyInfo, L);
249 
250   // We want to visit all of the instructions in this loop... that are not parts
251   // of our subloops (they have already had their invariants hoisted out of
252   // their loop, into this loop, so there is no need to process the BODIES of
253   // the subloops).
254   //
255   // Traverse the body of the loop in depth first order on the dominator tree so
256   // that we are guaranteed to see definitions before we see uses.  This allows
257   // us to sink instructions in one pass, without iteration.  After sinking
258   // instructions, we perform another pass to hoist them out of the loop.
259   //
260   if (L->hasDedicatedExits())
261     Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
262                           CurAST, &SafetyInfo, ORE);
263   if (Preheader)
264     Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
265                            CurAST, &SafetyInfo, ORE);
266 
267   // Now that all loop invariants have been removed from the loop, promote any
268   // memory references to scalars that we can.
269   // Don't sink stores from loops without dedicated block exits. Exits
270   // containing indirect branches are not transformed by loop simplify,
271   // make sure we catch that. An additional load may be generated in the
272   // preheader for SSA updater, so also avoid sinking when no preheader
273   // is available.
274   if (!DisablePromotion && Preheader && L->hasDedicatedExits()) {
275     // Figure out the loop exits and their insertion points
276     SmallVector<BasicBlock *, 8> ExitBlocks;
277     L->getUniqueExitBlocks(ExitBlocks);
278 
279     // We can't insert into a catchswitch.
280     bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
281       return isa<CatchSwitchInst>(Exit->getTerminator());
282     });
283 
284     if (!HasCatchSwitch) {
285       SmallVector<Instruction *, 8> InsertPts;
286       InsertPts.reserve(ExitBlocks.size());
287       for (BasicBlock *ExitBlock : ExitBlocks)
288         InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
289 
290       PredIteratorCache PIC;
291 
292       bool Promoted = false;
293 
294       // Loop over all of the alias sets in the tracker object.
295       for (AliasSet &AS : *CurAST) {
296         // We can promote this alias set if it has a store, if it is a "Must"
297         // alias set, if the pointer is loop invariant, and if we are not
298         // eliminating any volatile loads or stores.
299         if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
300             AS.isVolatile() || !L->isLoopInvariant(AS.begin()->getValue()))
301           continue;
302 
303         assert(
304             !AS.empty() &&
305             "Must alias set should have at least one pointer element in it!");
306 
307         SmallSetVector<Value *, 8> PointerMustAliases;
308         for (const auto &ASI : AS)
309           PointerMustAliases.insert(ASI.getValue());
310 
311         Promoted |= promoteLoopAccessesToScalars(PointerMustAliases, ExitBlocks,
312                                                  InsertPts, PIC, LI, DT, TLI, L,
313                                                  CurAST, &SafetyInfo, ORE);
314       }
315 
316       // Once we have promoted values across the loop body we have to
317       // recursively reform LCSSA as any nested loop may now have values defined
318       // within the loop used in the outer loop.
319       // FIXME: This is really heavy handed. It would be a bit better to use an
320       // SSAUpdater strategy during promotion that was LCSSA aware and reformed
321       // it as it went.
322       if (Promoted)
323         formLCSSARecursively(*L, *DT, LI, SE);
324 
325       Changed |= Promoted;
326     }
327   }
328 
329   // Check that neither this loop nor its parent have had LCSSA broken. LICM is
330   // specifically moving instructions across the loop boundary and so it is
331   // especially in need of sanity checking here.
332   assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
333   assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
334          "Parent loop not left in LCSSA form after LICM!");
335 
336   // If this loop is nested inside of another one, save the alias information
337   // for when we process the outer loop.
338   if (L->getParentLoop() && !DeleteAST)
339     LoopToAliasSetMap[L] = CurAST;
340   else
341     delete CurAST;
342 
343   if (Changed && SE)
344     SE->forgetLoopDispositions(L);
345   return Changed;
346 }
347 
348 /// Walk the specified region of the CFG (defined by all blocks dominated by
349 /// the specified block, and that are in the current loop) in reverse depth
350 /// first order w.r.t the DominatorTree.  This allows us to visit uses before
351 /// definitions, allowing us to sink a loop body in one pass without iteration.
352 ///
353 bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
354                       DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
355                       AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
356                       OptimizationRemarkEmitter *ORE) {
357 
358   // Verify inputs.
359   assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
360          CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
361          "Unexpected input to sinkRegion");
362 
363   // We want to visit children before parents. We will enque all the parents
364   // before their children in the worklist and process the worklist in reverse
365   // order.
366   SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
367 
368   bool Changed = false;
369   for (DomTreeNode *DTN : reverse(Worklist)) {
370     BasicBlock *BB = DTN->getBlock();
371     // Only need to process the contents of this block if it is not part of a
372     // subloop (which would already have been processed).
373     if (inSubLoop(BB, CurLoop, LI))
374       continue;
375 
376     for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
377       Instruction &I = *--II;
378 
379       // If the instruction is dead, we would try to sink it because it isn't
380       // used in the loop, instead, just delete it.
381       if (isInstructionTriviallyDead(&I, TLI)) {
382         DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
383         ++II;
384         CurAST->deleteValue(&I);
385         I.eraseFromParent();
386         Changed = true;
387         continue;
388       }
389 
390       // Check to see if we can sink this instruction to the exit blocks
391       // of the loop.  We can do this if the all users of the instruction are
392       // outside of the loop.  In this case, it doesn't even matter if the
393       // operands of the instruction are loop invariant.
394       //
395       if (isNotUsedInLoop(I, CurLoop, SafetyInfo) &&
396           canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo, ORE)) {
397         if (sink(I, LI, DT, CurLoop, SafetyInfo, ORE)) {
398           ++II;
399           CurAST->deleteValue(&I);
400           I.eraseFromParent();
401           Changed = true;
402         }
403       }
404     }
405   }
406   return Changed;
407 }
408 
409 /// Walk the specified region of the CFG (defined by all blocks dominated by
410 /// the specified block, and that are in the current loop) in depth first
411 /// order w.r.t the DominatorTree.  This allows us to visit definitions before
412 /// uses, allowing us to hoist a loop body in one pass without iteration.
413 ///
414 bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
415                        DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
416                        AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
417                        OptimizationRemarkEmitter *ORE) {
418   // Verify inputs.
419   assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
420          CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
421          "Unexpected input to hoistRegion");
422 
423   // We want to visit parents before children. We will enque all the parents
424   // before their children in the worklist and process the worklist in order.
425   SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
426 
427   bool Changed = false;
428   for (DomTreeNode *DTN : Worklist) {
429     BasicBlock *BB = DTN->getBlock();
430     // Only need to process the contents of this block if it is not part of a
431     // subloop (which would already have been processed).
432     if (!inSubLoop(BB, CurLoop, LI))
433       for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
434         Instruction &I = *II++;
435         // Try constant folding this instruction.  If all the operands are
436         // constants, it is technically hoistable, but it would be better to
437         // just fold it.
438         if (Constant *C = ConstantFoldInstruction(
439                 &I, I.getModule()->getDataLayout(), TLI)) {
440           DEBUG(dbgs() << "LICM folding inst: " << I << "  --> " << *C << '\n');
441           CurAST->copyValue(&I, C);
442           I.replaceAllUsesWith(C);
443           if (isInstructionTriviallyDead(&I, TLI)) {
444             CurAST->deleteValue(&I);
445             I.eraseFromParent();
446           }
447           Changed = true;
448           continue;
449         }
450 
451         // Attempt to remove floating point division out of the loop by
452         // converting it to a reciprocal multiplication.
453         if (I.getOpcode() == Instruction::FDiv &&
454             CurLoop->isLoopInvariant(I.getOperand(1)) &&
455             I.hasAllowReciprocal()) {
456           auto Divisor = I.getOperand(1);
457           auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0);
458           auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);
459           ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags());
460           ReciprocalDivisor->insertBefore(&I);
461 
462           auto Product =
463               BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor);
464           Product->setFastMathFlags(I.getFastMathFlags());
465           Product->insertAfter(&I);
466           I.replaceAllUsesWith(Product);
467           I.eraseFromParent();
468 
469           hoist(*ReciprocalDivisor, DT, CurLoop, SafetyInfo, ORE);
470           Changed = true;
471           continue;
472         }
473 
474         // Try hoisting the instruction out to the preheader.  We can only do
475         // this if all of the operands of the instruction are loop invariant and
476         // if it is safe to hoist the instruction.
477         //
478         if (CurLoop->hasLoopInvariantOperands(&I) &&
479             canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo, ORE) &&
480             isSafeToExecuteUnconditionally(
481                 I, DT, CurLoop, SafetyInfo, ORE,
482                 CurLoop->getLoopPreheader()->getTerminator()))
483           Changed |= hoist(I, DT, CurLoop, SafetyInfo, ORE);
484       }
485   }
486 
487   return Changed;
488 }
489 
490 /// Computes loop safety information, checks loop body & header
491 /// for the possibility of may throw exception.
492 ///
493 void llvm::computeLoopSafetyInfo(LoopSafetyInfo *SafetyInfo, Loop *CurLoop) {
494   assert(CurLoop != nullptr && "CurLoop cant be null");
495   BasicBlock *Header = CurLoop->getHeader();
496   // Setting default safety values.
497   SafetyInfo->MayThrow = false;
498   SafetyInfo->HeaderMayThrow = false;
499   // Iterate over header and compute safety info.
500   for (BasicBlock::iterator I = Header->begin(), E = Header->end();
501        (I != E) && !SafetyInfo->HeaderMayThrow; ++I)
502     SafetyInfo->HeaderMayThrow |=
503         !isGuaranteedToTransferExecutionToSuccessor(&*I);
504 
505   SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
506   // Iterate over loop instructions and compute safety info.
507   // Skip header as it has been computed and stored in HeaderMayThrow.
508   // The first block in loopinfo.Blocks is guaranteed to be the header.
509   assert(Header == *CurLoop->getBlocks().begin() &&
510          "First block must be header");
511   for (Loop::block_iterator BB = std::next(CurLoop->block_begin()),
512                             BBE = CurLoop->block_end();
513        (BB != BBE) && !SafetyInfo->MayThrow; ++BB)
514     for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
515          (I != E) && !SafetyInfo->MayThrow; ++I)
516       SafetyInfo->MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(&*I);
517 
518   // Compute funclet colors if we might sink/hoist in a function with a funclet
519   // personality routine.
520   Function *Fn = CurLoop->getHeader()->getParent();
521   if (Fn->hasPersonalityFn())
522     if (Constant *PersonalityFn = Fn->getPersonalityFn())
523       if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
524         SafetyInfo->BlockColors = colorEHFunclets(*Fn);
525 }
526 
527 // Return true if LI is invariant within scope of the loop. LI is invariant if
528 // CurLoop is dominated by an invariant.start representing the same memory
529 // location and size as the memory location LI loads from, and also the
530 // invariant.start has no uses.
531 static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT,
532                                   Loop *CurLoop) {
533   Value *Addr = LI->getOperand(0);
534   const DataLayout &DL = LI->getModule()->getDataLayout();
535   const uint32_t LocSizeInBits = DL.getTypeSizeInBits(
536       cast<PointerType>(Addr->getType())->getElementType());
537 
538   // if the type is i8 addrspace(x)*, we know this is the type of
539   // llvm.invariant.start operand
540   auto *PtrInt8Ty = PointerType::get(Type::getInt8Ty(LI->getContext()),
541                                      LI->getPointerAddressSpace());
542   unsigned BitcastsVisited = 0;
543   // Look through bitcasts until we reach the i8* type (this is invariant.start
544   // operand type).
545   while (Addr->getType() != PtrInt8Ty) {
546     auto *BC = dyn_cast<BitCastInst>(Addr);
547     // Avoid traversing high number of bitcast uses.
548     if (++BitcastsVisited > MaxNumUsesTraversed || !BC)
549       return false;
550     Addr = BC->getOperand(0);
551   }
552 
553   unsigned UsesVisited = 0;
554   // Traverse all uses of the load operand value, to see if invariant.start is
555   // one of the uses, and whether it dominates the load instruction.
556   for (auto *U : Addr->users()) {
557     // Avoid traversing for Load operand with high number of users.
558     if (++UsesVisited > MaxNumUsesTraversed)
559       return false;
560     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
561     // If there are escaping uses of invariant.start instruction, the load maybe
562     // non-invariant.
563     if (!II || II->getIntrinsicID() != Intrinsic::invariant_start ||
564         !II->use_empty())
565       continue;
566     unsigned InvariantSizeInBits =
567         cast<ConstantInt>(II->getArgOperand(0))->getSExtValue() * 8;
568     // Confirm the invariant.start location size contains the load operand size
569     // in bits. Also, the invariant.start should dominate the load, and we
570     // should not hoist the load out of a loop that contains this dominating
571     // invariant.start.
572     if (LocSizeInBits <= InvariantSizeInBits &&
573         DT->properlyDominates(II->getParent(), CurLoop->getHeader()))
574       return true;
575   }
576 
577   return false;
578 }
579 
580 bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,
581                               Loop *CurLoop, AliasSetTracker *CurAST,
582                               LoopSafetyInfo *SafetyInfo,
583                               OptimizationRemarkEmitter *ORE) {
584   // SafetyInfo is nullptr if we are checking for sinking from preheader to
585   // loop body.
586   const bool SinkingToLoopBody = !SafetyInfo;
587   // Loads have extra constraints we have to verify before we can hoist them.
588   if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
589     if (!LI->isUnordered())
590       return false; // Don't sink/hoist volatile or ordered atomic loads!
591 
592     // Loads from constant memory are always safe to move, even if they end up
593     // in the same alias set as something that ends up being modified.
594     if (AA->pointsToConstantMemory(LI->getOperand(0)))
595       return true;
596     if (LI->getMetadata(LLVMContext::MD_invariant_load))
597       return true;
598 
599     if (LI->isAtomic() && SinkingToLoopBody)
600       return false; // Don't sink unordered atomic loads to loop body.
601 
602     // This checks for an invariant.start dominating the load.
603     if (isLoadInvariantInLoop(LI, DT, CurLoop))
604       return true;
605 
606     // Don't hoist loads which have may-aliased stores in loop.
607     uint64_t Size = 0;
608     if (LI->getType()->isSized())
609       Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType());
610 
611     AAMDNodes AAInfo;
612     LI->getAAMetadata(AAInfo);
613 
614     bool Invalidated =
615         pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
616     // Check loop-invariant address because this may also be a sinkable load
617     // whose address is not necessarily loop-invariant.
618     if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand()))
619       ORE->emit([&]() {
620         return OptimizationRemarkMissed(
621                    DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", LI)
622                << "failed to move load with loop-invariant address "
623                   "because the loop may invalidate its value";
624       });
625 
626     return !Invalidated;
627   } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
628     // Don't sink or hoist dbg info; it's legal, but not useful.
629     if (isa<DbgInfoIntrinsic>(I))
630       return false;
631 
632     // Don't sink calls which can throw.
633     if (CI->mayThrow())
634       return false;
635 
636     // Handle simple cases by querying alias analysis.
637     FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
638     if (Behavior == FMRB_DoesNotAccessMemory)
639       return true;
640     if (AliasAnalysis::onlyReadsMemory(Behavior)) {
641       // A readonly argmemonly function only reads from memory pointed to by
642       // it's arguments with arbitrary offsets.  If we can prove there are no
643       // writes to this memory in the loop, we can hoist or sink.
644       if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
645         for (Value *Op : CI->arg_operands())
646           if (Op->getType()->isPointerTy() &&
647               pointerInvalidatedByLoop(Op, MemoryLocation::UnknownSize,
648                                        AAMDNodes(), CurAST))
649             return false;
650         return true;
651       }
652       // If this call only reads from memory and there are no writes to memory
653       // in the loop, we can hoist or sink the call as appropriate.
654       bool FoundMod = false;
655       for (AliasSet &AS : *CurAST) {
656         if (!AS.isForwardingAliasSet() && AS.isMod()) {
657           FoundMod = true;
658           break;
659         }
660       }
661       if (!FoundMod)
662         return true;
663     }
664 
665     // FIXME: This should use mod/ref information to see if we can hoist or
666     // sink the call.
667 
668     return false;
669   }
670 
671   // Only these instructions are hoistable/sinkable.
672   if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
673       !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
674       !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
675       !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
676       !isa<InsertValueInst>(I))
677     return false;
678 
679   // If we are checking for sinking from preheader to loop body it will be
680   // always safe as there is no speculative execution.
681   if (SinkingToLoopBody)
682     return true;
683 
684   // TODO: Plumb the context instruction through to make hoisting and sinking
685   // more powerful. Hoisting of loads already works due to the special casing
686   // above.
687   return isSafeToExecuteUnconditionally(I, DT, CurLoop, SafetyInfo, nullptr);
688 }
689 
690 /// Returns true if a PHINode is a trivially replaceable with an
691 /// Instruction.
692 /// This is true when all incoming values are that instruction.
693 /// This pattern occurs most often with LCSSA PHI nodes.
694 ///
695 static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) {
696   for (const Value *IncValue : PN.incoming_values())
697     if (IncValue != &I)
698       return false;
699 
700   return true;
701 }
702 
703 /// Return true if the only users of this instruction are outside of
704 /// the loop. If this is true, we can sink the instruction to the exit
705 /// blocks of the loop.
706 ///
707 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
708                             const LoopSafetyInfo *SafetyInfo) {
709   const auto &BlockColors = SafetyInfo->BlockColors;
710   for (const User *U : I.users()) {
711     const Instruction *UI = cast<Instruction>(U);
712     if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
713       const BasicBlock *BB = PN->getParent();
714       // We cannot sink uses in catchswitches.
715       if (isa<CatchSwitchInst>(BB->getTerminator()))
716         return false;
717 
718       // We need to sink a callsite to a unique funclet.  Avoid sinking if the
719       // phi use is too muddled.
720       if (isa<CallInst>(I))
721         if (!BlockColors.empty() &&
722             BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
723           return false;
724     }
725 
726     if (CurLoop->contains(UI))
727       return false;
728   }
729   return true;
730 }
731 
732 static Instruction *
733 CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
734                             const LoopInfo *LI,
735                             const LoopSafetyInfo *SafetyInfo) {
736   Instruction *New;
737   if (auto *CI = dyn_cast<CallInst>(&I)) {
738     const auto &BlockColors = SafetyInfo->BlockColors;
739 
740     // Sinking call-sites need to be handled differently from other
741     // instructions.  The cloned call-site needs a funclet bundle operand
742     // appropriate for it's location in the CFG.
743     SmallVector<OperandBundleDef, 1> OpBundles;
744     for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
745          BundleIdx != BundleEnd; ++BundleIdx) {
746       OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
747       if (Bundle.getTagID() == LLVMContext::OB_funclet)
748         continue;
749 
750       OpBundles.emplace_back(Bundle);
751     }
752 
753     if (!BlockColors.empty()) {
754       const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
755       assert(CV.size() == 1 && "non-unique color for exit block!");
756       BasicBlock *BBColor = CV.front();
757       Instruction *EHPad = BBColor->getFirstNonPHI();
758       if (EHPad->isEHPad())
759         OpBundles.emplace_back("funclet", EHPad);
760     }
761 
762     New = CallInst::Create(CI, OpBundles);
763   } else {
764     New = I.clone();
765   }
766 
767   ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
768   if (!I.getName().empty())
769     New->setName(I.getName() + ".le");
770 
771   // Build LCSSA PHI nodes for any in-loop operands. Note that this is
772   // particularly cheap because we can rip off the PHI node that we're
773   // replacing for the number and blocks of the predecessors.
774   // OPT: If this shows up in a profile, we can instead finish sinking all
775   // invariant instructions, and then walk their operands to re-establish
776   // LCSSA. That will eliminate creating PHI nodes just to nuke them when
777   // sinking bottom-up.
778   for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
779        ++OI)
780     if (Instruction *OInst = dyn_cast<Instruction>(*OI))
781       if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
782         if (!OLoop->contains(&PN)) {
783           PHINode *OpPN =
784               PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
785                               OInst->getName() + ".lcssa", &ExitBlock.front());
786           for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
787             OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
788           *OI = OpPN;
789         }
790   return New;
791 }
792 
793 static Instruction *sinkThroughTriviallyReplacablePHI(
794     PHINode *TPN, Instruction *I, LoopInfo *LI,
795     SmallDenseMap<BasicBlock *, Instruction *, 32> &SunkCopies,
796     const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop) {
797   assert(isTriviallyReplacablePHI(*TPN, *I) &&
798          "Expect only trivially replacalbe PHI");
799   BasicBlock *ExitBlock = TPN->getParent();
800   Instruction *New;
801   auto It = SunkCopies.find(ExitBlock);
802   if (It != SunkCopies.end())
803     New = It->second;
804   else
805     New = SunkCopies[ExitBlock] =
806         CloneInstructionInExitBlock(*I, *ExitBlock, *TPN, LI, SafetyInfo);
807   return New;
808 }
809 
810 static bool canSplitPredecessors(PHINode *PN) {
811   BasicBlock *BB = PN->getParent();
812   if (!BB->canSplitPredecessors())
813     return false;
814   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
815     BasicBlock *BBPred = *PI;
816     if (isa<IndirectBrInst>(BBPred->getTerminator()))
817       return false;
818   }
819   return true;
820 }
821 
822 static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT,
823                                         LoopInfo *LI, const Loop *CurLoop) {
824 #ifndef NDEBUG
825   SmallVector<BasicBlock *, 32> ExitBlocks;
826   CurLoop->getUniqueExitBlocks(ExitBlocks);
827   SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
828                                              ExitBlocks.end());
829 #endif
830   BasicBlock *ExitBB = PN->getParent();
831   assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block.");
832 
833   // Split predecessors of the loop exit to make instructions in the loop are
834   // exposed to exit blocks through trivially replacable PHIs while keeping the
835   // loop in the canonical form where each predecessor of each exit block should
836   // be contained within the loop. For example, this will convert the loop below
837   // from
838   //
839   // LB1:
840   //   %v1 =
841   //   br %LE, %LB2
842   // LB2:
843   //   %v2 =
844   //   br %LE, %LB1
845   // LE:
846   //   %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replacable
847   //
848   // to
849   //
850   // LB1:
851   //   %v1 =
852   //   br %LE.split, %LB2
853   // LB2:
854   //   %v2 =
855   //   br %LE.split2, %LB1
856   // LE.split:
857   //   %p1 = phi [%v1, %LB1]  <-- trivially replacable
858   //   br %LE
859   // LE.split2:
860   //   %p2 = phi [%v2, %LB2]  <-- trivially replacable
861   //   br %LE
862   // LE:
863   //   %p = phi [%p1, %LE.split], [%p2, %LE.split2]
864   //
865   SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB));
866   while (!PredBBs.empty()) {
867     BasicBlock *PredBB = *PredBBs.begin();
868     assert(CurLoop->contains(PredBB) &&
869            "Expect all predecessors are in the loop");
870     if (PN->getBasicBlockIndex(PredBB) >= 0)
871       SplitBlockPredecessors(ExitBB, PredBB, ".split.loop.exit", DT, LI, true);
872     PredBBs.remove(PredBB);
873   }
874 }
875 
876 /// When an instruction is found to only be used outside of the loop, this
877 /// function moves it to the exit blocks and patches up SSA form as needed.
878 /// This method is guaranteed to remove the original instruction from its
879 /// position, and may either delete it or move it to outside of the loop.
880 ///
881 static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
882                  const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo,
883                  OptimizationRemarkEmitter *ORE) {
884   DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
885   ORE->emit([&]() {
886     return OptimizationRemark(DEBUG_TYPE, "InstSunk", &I)
887            << "sinking " << ore::NV("Inst", &I);
888   });
889   bool Changed = false;
890   if (isa<LoadInst>(I))
891     ++NumMovedLoads;
892   else if (isa<CallInst>(I))
893     ++NumMovedCalls;
894   ++NumSunk;
895   Changed = true;
896 
897   // Iterate over users to be ready for actual sinking. Replace users via
898   // unrechable blocks with undef and make all user PHIs trivially replcable.
899   SmallPtrSet<Instruction *, 8> VisitedUsers;
900   for (Value::user_iterator UI = I.user_begin(), UE = I.user_end(); UI != UE;) {
901     auto *User = cast<Instruction>(*UI);
902     Use &U = UI.getUse();
903     ++UI;
904 
905     if (VisitedUsers.count(User))
906       continue;
907 
908     if (!DT->isReachableFromEntry(User->getParent())) {
909       User->replaceUsesOfWith(&I, UndefValue::get(I.getType()));
910       continue;
911     }
912 
913     // The user must be a PHI node.
914     PHINode *PN = cast<PHINode>(User);
915 
916     // Surprisingly, instructions can be used outside of loops without any
917     // exits.  This can only happen in PHI nodes if the incoming block is
918     // unreachable.
919     BasicBlock *BB = PN->getIncomingBlock(U);
920     if (!DT->isReachableFromEntry(BB)) {
921       U = UndefValue::get(I.getType());
922       continue;
923     }
924 
925     VisitedUsers.insert(PN);
926     if (isTriviallyReplacablePHI(*PN, I))
927       continue;
928 
929     if (!canSplitPredecessors(PN))
930       return false;
931 
932     // Split predecessors of the PHI so that we can make users trivially
933     // replacable.
934     splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop);
935 
936     // Should rebuild the iterators, as they may be invalidated by
937     // splitPredecessorsOfLoopExit().
938     UI = I.user_begin();
939     UE = I.user_end();
940   }
941 
942 #ifndef NDEBUG
943   SmallVector<BasicBlock *, 32> ExitBlocks;
944   CurLoop->getUniqueExitBlocks(ExitBlocks);
945   SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
946                                              ExitBlocks.end());
947 #endif
948 
949   // Clones of this instruction. Don't create more than one per exit block!
950   SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
951 
952   // If this instruction is only used outside of the loop, then all users are
953   // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
954   // the instruction.
955   while (!I.use_empty()) {
956     Value::user_iterator UI = I.user_begin();
957     PHINode *PN = cast<PHINode>(*UI);
958     assert(ExitBlockSet.count(PN->getParent()) &&
959            "The LCSSA PHI is not in an exit block!");
960     // The PHI must be trivially replacable.
961     Instruction *New = sinkThroughTriviallyReplacablePHI(PN, &I, LI, SunkCopies,
962                                                          SafetyInfo, CurLoop);
963     PN->replaceAllUsesWith(New);
964     PN->eraseFromParent();
965   }
966   return Changed;
967 }
968 
969 /// When an instruction is found to only use loop invariant operands that
970 /// is safe to hoist, this instruction is called to do the dirty work.
971 ///
972 static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
973                   const LoopSafetyInfo *SafetyInfo,
974                   OptimizationRemarkEmitter *ORE) {
975   auto *Preheader = CurLoop->getLoopPreheader();
976   DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I
977                << "\n");
978   ORE->emit([&]() {
979     return OptimizationRemark(DEBUG_TYPE, "Hoisted", &I) << "hoisting "
980                                                          << ore::NV("Inst", &I);
981   });
982 
983   // Metadata can be dependent on conditions we are hoisting above.
984   // Conservatively strip all metadata on the instruction unless we were
985   // guaranteed to execute I if we entered the loop, in which case the metadata
986   // is valid in the loop preheader.
987   if (I.hasMetadataOtherThanDebugLoc() &&
988       // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
989       // time in isGuaranteedToExecute if we don't actually have anything to
990       // drop.  It is a compile time optimization, not required for correctness.
991       !isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo))
992     I.dropUnknownNonDebugMetadata();
993 
994   // Move the new node to the Preheader, before its terminator.
995   I.moveBefore(Preheader->getTerminator());
996 
997   // Do not retain debug locations when we are moving instructions to different
998   // basic blocks, because we want to avoid jumpy line tables. Calls, however,
999   // need to retain their debug locs because they may be inlined.
1000   // FIXME: How do we retain source locations without causing poor debugging
1001   // behavior?
1002   if (!isa<CallInst>(I))
1003     I.setDebugLoc(DebugLoc());
1004 
1005   if (isa<LoadInst>(I))
1006     ++NumMovedLoads;
1007   else if (isa<CallInst>(I))
1008     ++NumMovedCalls;
1009   ++NumHoisted;
1010   return true;
1011 }
1012 
1013 /// Only sink or hoist an instruction if it is not a trapping instruction,
1014 /// or if the instruction is known not to trap when moved to the preheader.
1015 /// or if it is a trapping instruction and is guaranteed to execute.
1016 static bool isSafeToExecuteUnconditionally(Instruction &Inst,
1017                                            const DominatorTree *DT,
1018                                            const Loop *CurLoop,
1019                                            const LoopSafetyInfo *SafetyInfo,
1020                                            OptimizationRemarkEmitter *ORE,
1021                                            const Instruction *CtxI) {
1022   if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT))
1023     return true;
1024 
1025   bool GuaranteedToExecute =
1026       isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
1027 
1028   if (!GuaranteedToExecute) {
1029     auto *LI = dyn_cast<LoadInst>(&Inst);
1030     if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand()))
1031       ORE->emit([&]() {
1032         return OptimizationRemarkMissed(
1033                    DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI)
1034                << "failed to hoist load with loop-invariant address "
1035                   "because load is conditionally executed";
1036       });
1037   }
1038 
1039   return GuaranteedToExecute;
1040 }
1041 
1042 namespace {
1043 class LoopPromoter : public LoadAndStorePromoter {
1044   Value *SomePtr; // Designated pointer to store to.
1045   const SmallSetVector<Value *, 8> &PointerMustAliases;
1046   SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
1047   SmallVectorImpl<Instruction *> &LoopInsertPts;
1048   PredIteratorCache &PredCache;
1049   AliasSetTracker &AST;
1050   LoopInfo &LI;
1051   DebugLoc DL;
1052   int Alignment;
1053   bool UnorderedAtomic;
1054   AAMDNodes AATags;
1055 
1056   Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
1057     if (Instruction *I = dyn_cast<Instruction>(V))
1058       if (Loop *L = LI.getLoopFor(I->getParent()))
1059         if (!L->contains(BB)) {
1060           // We need to create an LCSSA PHI node for the incoming value and
1061           // store that.
1062           PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
1063                                         I->getName() + ".lcssa", &BB->front());
1064           for (BasicBlock *Pred : PredCache.get(BB))
1065             PN->addIncoming(I, Pred);
1066           return PN;
1067         }
1068     return V;
1069   }
1070 
1071 public:
1072   LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
1073                const SmallSetVector<Value *, 8> &PMA,
1074                SmallVectorImpl<BasicBlock *> &LEB,
1075                SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
1076                AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
1077                bool UnorderedAtomic, const AAMDNodes &AATags)
1078       : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
1079         LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
1080         LI(li), DL(std::move(dl)), Alignment(alignment),
1081         UnorderedAtomic(UnorderedAtomic), AATags(AATags) {}
1082 
1083   bool isInstInList(Instruction *I,
1084                     const SmallVectorImpl<Instruction *> &) const override {
1085     Value *Ptr;
1086     if (LoadInst *LI = dyn_cast<LoadInst>(I))
1087       Ptr = LI->getOperand(0);
1088     else
1089       Ptr = cast<StoreInst>(I)->getPointerOperand();
1090     return PointerMustAliases.count(Ptr);
1091   }
1092 
1093   void doExtraRewritesBeforeFinalDeletion() const override {
1094     // Insert stores after in the loop exit blocks.  Each exit block gets a
1095     // store of the live-out values that feed them.  Since we've already told
1096     // the SSA updater about the defs in the loop and the preheader
1097     // definition, it is all set and we can start using it.
1098     for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
1099       BasicBlock *ExitBlock = LoopExitBlocks[i];
1100       Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
1101       LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
1102       Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
1103       Instruction *InsertPos = LoopInsertPts[i];
1104       StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
1105       if (UnorderedAtomic)
1106         NewSI->setOrdering(AtomicOrdering::Unordered);
1107       NewSI->setAlignment(Alignment);
1108       NewSI->setDebugLoc(DL);
1109       if (AATags)
1110         NewSI->setAAMetadata(AATags);
1111     }
1112   }
1113 
1114   void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
1115     // Update alias analysis.
1116     AST.copyValue(LI, V);
1117   }
1118   void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); }
1119 };
1120 
1121 
1122 /// Return true iff we can prove that a caller of this function can not inspect
1123 /// the contents of the provided object in a well defined program.
1124 bool isKnownNonEscaping(Value *Object, const TargetLibraryInfo *TLI) {
1125   if (isa<AllocaInst>(Object))
1126     // Since the alloca goes out of scope, we know the caller can't retain a
1127     // reference to it and be well defined.  Thus, we don't need to check for
1128     // capture.
1129     return true;
1130 
1131   // For all other objects we need to know that the caller can't possibly
1132   // have gotten a reference to the object.  There are two components of
1133   // that:
1134   //   1) Object can't be escaped by this function.  This is what
1135   //      PointerMayBeCaptured checks.
1136   //   2) Object can't have been captured at definition site.  For this, we
1137   //      need to know the return value is noalias.  At the moment, we use a
1138   //      weaker condition and handle only AllocLikeFunctions (which are
1139   //      known to be noalias).  TODO
1140   return isAllocLikeFn(Object, TLI) &&
1141     !PointerMayBeCaptured(Object, true, true);
1142 }
1143 
1144 } // namespace
1145 
1146 /// Try to promote memory values to scalars by sinking stores out of the
1147 /// loop and moving loads to before the loop.  We do this by looping over
1148 /// the stores in the loop, looking for stores to Must pointers which are
1149 /// loop invariant.
1150 ///
1151 bool llvm::promoteLoopAccessesToScalars(
1152     const SmallSetVector<Value *, 8> &PointerMustAliases,
1153     SmallVectorImpl<BasicBlock *> &ExitBlocks,
1154     SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC,
1155     LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
1156     Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
1157     OptimizationRemarkEmitter *ORE) {
1158   // Verify inputs.
1159   assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
1160          CurAST != nullptr && SafetyInfo != nullptr &&
1161          "Unexpected Input to promoteLoopAccessesToScalars");
1162 
1163   Value *SomePtr = *PointerMustAliases.begin();
1164   BasicBlock *Preheader = CurLoop->getLoopPreheader();
1165 
1166   // It isn't safe to promote a load/store from the loop if the load/store is
1167   // conditional.  For example, turning:
1168   //
1169   //    for () { if (c) *P += 1; }
1170   //
1171   // into:
1172   //
1173   //    tmp = *P;  for () { if (c) tmp +=1; } *P = tmp;
1174   //
1175   // is not safe, because *P may only be valid to access if 'c' is true.
1176   //
1177   // The safety property divides into two parts:
1178   // p1) The memory may not be dereferenceable on entry to the loop.  In this
1179   //    case, we can't insert the required load in the preheader.
1180   // p2) The memory model does not allow us to insert a store along any dynamic
1181   //    path which did not originally have one.
1182   //
1183   // If at least one store is guaranteed to execute, both properties are
1184   // satisfied, and promotion is legal.
1185   //
1186   // This, however, is not a necessary condition. Even if no store/load is
1187   // guaranteed to execute, we can still establish these properties.
1188   // We can establish (p1) by proving that hoisting the load into the preheader
1189   // is safe (i.e. proving dereferenceability on all paths through the loop). We
1190   // can use any access within the alias set to prove dereferenceability,
1191   // since they're all must alias.
1192   //
1193   // There are two ways establish (p2):
1194   // a) Prove the location is thread-local. In this case the memory model
1195   // requirement does not apply, and stores are safe to insert.
1196   // b) Prove a store dominates every exit block. In this case, if an exit
1197   // blocks is reached, the original dynamic path would have taken us through
1198   // the store, so inserting a store into the exit block is safe. Note that this
1199   // is different from the store being guaranteed to execute. For instance,
1200   // if an exception is thrown on the first iteration of the loop, the original
1201   // store is never executed, but the exit blocks are not executed either.
1202 
1203   bool DereferenceableInPH = false;
1204   bool SafeToInsertStore = false;
1205 
1206   SmallVector<Instruction *, 64> LoopUses;
1207 
1208   // We start with an alignment of one and try to find instructions that allow
1209   // us to prove better alignment.
1210   unsigned Alignment = 1;
1211   // Keep track of which types of access we see
1212   bool SawUnorderedAtomic = false;
1213   bool SawNotAtomic = false;
1214   AAMDNodes AATags;
1215 
1216   const DataLayout &MDL = Preheader->getModule()->getDataLayout();
1217 
1218   bool IsKnownThreadLocalObject = false;
1219   if (SafetyInfo->MayThrow) {
1220     // If a loop can throw, we have to insert a store along each unwind edge.
1221     // That said, we can't actually make the unwind edge explicit. Therefore,
1222     // we have to prove that the store is dead along the unwind edge.  We do
1223     // this by proving that the caller can't have a reference to the object
1224     // after return and thus can't possibly load from the object.
1225     Value *Object = GetUnderlyingObject(SomePtr, MDL);
1226     if (!isKnownNonEscaping(Object, TLI))
1227       return false;
1228     // Subtlety: Alloca's aren't visible to callers, but *are* potentially
1229     // visible to other threads if captured and used during their lifetimes.
1230     IsKnownThreadLocalObject = !isa<AllocaInst>(Object);
1231   }
1232 
1233   // Check that all of the pointers in the alias set have the same type.  We
1234   // cannot (yet) promote a memory location that is loaded and stored in
1235   // different sizes.  While we are at it, collect alignment and AA info.
1236   for (Value *ASIV : PointerMustAliases) {
1237     // Check that all of the pointers in the alias set have the same type.  We
1238     // cannot (yet) promote a memory location that is loaded and stored in
1239     // different sizes.
1240     if (SomePtr->getType() != ASIV->getType())
1241       return false;
1242 
1243     for (User *U : ASIV->users()) {
1244       // Ignore instructions that are outside the loop.
1245       Instruction *UI = dyn_cast<Instruction>(U);
1246       if (!UI || !CurLoop->contains(UI))
1247         continue;
1248 
1249       // If there is an non-load/store instruction in the loop, we can't promote
1250       // it.
1251       if (LoadInst *Load = dyn_cast<LoadInst>(UI)) {
1252         assert(!Load->isVolatile() && "AST broken");
1253         if (!Load->isUnordered())
1254           return false;
1255 
1256         SawUnorderedAtomic |= Load->isAtomic();
1257         SawNotAtomic |= !Load->isAtomic();
1258 
1259         if (!DereferenceableInPH)
1260           DereferenceableInPH = isSafeToExecuteUnconditionally(
1261               *Load, DT, CurLoop, SafetyInfo, ORE, Preheader->getTerminator());
1262       } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
1263         // Stores *of* the pointer are not interesting, only stores *to* the
1264         // pointer.
1265         if (UI->getOperand(1) != ASIV)
1266           continue;
1267         assert(!Store->isVolatile() && "AST broken");
1268         if (!Store->isUnordered())
1269           return false;
1270 
1271         SawUnorderedAtomic |= Store->isAtomic();
1272         SawNotAtomic |= !Store->isAtomic();
1273 
1274         // If the store is guaranteed to execute, both properties are satisfied.
1275         // We may want to check if a store is guaranteed to execute even if we
1276         // already know that promotion is safe, since it may have higher
1277         // alignment than any other guaranteed stores, in which case we can
1278         // raise the alignment on the promoted store.
1279         unsigned InstAlignment = Store->getAlignment();
1280         if (!InstAlignment)
1281           InstAlignment =
1282               MDL.getABITypeAlignment(Store->getValueOperand()->getType());
1283 
1284         if (!DereferenceableInPH || !SafeToInsertStore ||
1285             (InstAlignment > Alignment)) {
1286           if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
1287             DereferenceableInPH = true;
1288             SafeToInsertStore = true;
1289             Alignment = std::max(Alignment, InstAlignment);
1290           }
1291         }
1292 
1293         // If a store dominates all exit blocks, it is safe to sink.
1294         // As explained above, if an exit block was executed, a dominating
1295         // store must have been been executed at least once, so we are not
1296         // introducing stores on paths that did not have them.
1297         // Note that this only looks at explicit exit blocks. If we ever
1298         // start sinking stores into unwind edges (see above), this will break.
1299         if (!SafeToInsertStore)
1300           SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) {
1301             return DT->dominates(Store->getParent(), Exit);
1302           });
1303 
1304         // If the store is not guaranteed to execute, we may still get
1305         // deref info through it.
1306         if (!DereferenceableInPH) {
1307           DereferenceableInPH = isDereferenceableAndAlignedPointer(
1308               Store->getPointerOperand(), Store->getAlignment(), MDL,
1309               Preheader->getTerminator(), DT);
1310         }
1311       } else
1312         return false; // Not a load or store.
1313 
1314       // Merge the AA tags.
1315       if (LoopUses.empty()) {
1316         // On the first load/store, just take its AA tags.
1317         UI->getAAMetadata(AATags);
1318       } else if (AATags) {
1319         UI->getAAMetadata(AATags, /* Merge = */ true);
1320       }
1321 
1322       LoopUses.push_back(UI);
1323     }
1324   }
1325 
1326   // If we found both an unordered atomic instruction and a non-atomic memory
1327   // access, bail.  We can't blindly promote non-atomic to atomic since we
1328   // might not be able to lower the result.  We can't downgrade since that
1329   // would violate memory model.  Also, align 0 is an error for atomics.
1330   if (SawUnorderedAtomic && SawNotAtomic)
1331     return false;
1332 
1333   // If we couldn't prove we can hoist the load, bail.
1334   if (!DereferenceableInPH)
1335     return false;
1336 
1337   // We know we can hoist the load, but don't have a guaranteed store.
1338   // Check whether the location is thread-local. If it is, then we can insert
1339   // stores along paths which originally didn't have them without violating the
1340   // memory model.
1341   if (!SafeToInsertStore) {
1342     if (IsKnownThreadLocalObject)
1343       SafeToInsertStore = true;
1344     else {
1345       Value *Object = GetUnderlyingObject(SomePtr, MDL);
1346       SafeToInsertStore =
1347           (isAllocLikeFn(Object, TLI) || isa<AllocaInst>(Object)) &&
1348           !PointerMayBeCaptured(Object, true, true);
1349     }
1350   }
1351 
1352   // If we've still failed to prove we can sink the store, give up.
1353   if (!SafeToInsertStore)
1354     return false;
1355 
1356   // Otherwise, this is safe to promote, lets do it!
1357   DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr
1358                << '\n');
1359   ORE->emit([&]() {
1360     return OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar",
1361                               LoopUses[0])
1362            << "Moving accesses to memory location out of the loop";
1363   });
1364   ++NumPromoted;
1365 
1366   // Grab a debug location for the inserted loads/stores; given that the
1367   // inserted loads/stores have little relation to the original loads/stores,
1368   // this code just arbitrarily picks a location from one, since any debug
1369   // location is better than none.
1370   DebugLoc DL = LoopUses[0]->getDebugLoc();
1371 
1372   // We use the SSAUpdater interface to insert phi nodes as required.
1373   SmallVector<PHINode *, 16> NewPHIs;
1374   SSAUpdater SSA(&NewPHIs);
1375   LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
1376                         InsertPts, PIC, *CurAST, *LI, DL, Alignment,
1377                         SawUnorderedAtomic, AATags);
1378 
1379   // Set up the preheader to have a definition of the value.  It is the live-out
1380   // value from the preheader that uses in the loop will use.
1381   LoadInst *PreheaderLoad = new LoadInst(
1382       SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator());
1383   if (SawUnorderedAtomic)
1384     PreheaderLoad->setOrdering(AtomicOrdering::Unordered);
1385   PreheaderLoad->setAlignment(Alignment);
1386   PreheaderLoad->setDebugLoc(DL);
1387   if (AATags)
1388     PreheaderLoad->setAAMetadata(AATags);
1389   SSA.AddAvailableValue(Preheader, PreheaderLoad);
1390 
1391   // Rewrite all the loads in the loop and remember all the definitions from
1392   // stores in the loop.
1393   Promoter.run(LoopUses);
1394 
1395   // If the SSAUpdater didn't use the load in the preheader, just zap it now.
1396   if (PreheaderLoad->use_empty())
1397     PreheaderLoad->eraseFromParent();
1398 
1399   return true;
1400 }
1401 
1402 /// Returns an owning pointer to an alias set which incorporates aliasing info
1403 /// from L and all subloops of L.
1404 /// FIXME: In new pass manager, there is no helper function to handle loop
1405 /// analysis such as cloneBasicBlockAnalysis, so the AST needs to be recomputed
1406 /// from scratch for every loop. Hook up with the helper functions when
1407 /// available in the new pass manager to avoid redundant computation.
1408 AliasSetTracker *
1409 LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
1410                                                  AliasAnalysis *AA) {
1411   AliasSetTracker *CurAST = nullptr;
1412   SmallVector<Loop *, 4> RecomputeLoops;
1413   for (Loop *InnerL : L->getSubLoops()) {
1414     auto MapI = LoopToAliasSetMap.find(InnerL);
1415     // If the AST for this inner loop is missing it may have been merged into
1416     // some other loop's AST and then that loop unrolled, and so we need to
1417     // recompute it.
1418     if (MapI == LoopToAliasSetMap.end()) {
1419       RecomputeLoops.push_back(InnerL);
1420       continue;
1421     }
1422     AliasSetTracker *InnerAST = MapI->second;
1423 
1424     if (CurAST != nullptr) {
1425       // What if InnerLoop was modified by other passes ?
1426       CurAST->add(*InnerAST);
1427 
1428       // Once we've incorporated the inner loop's AST into ours, we don't need
1429       // the subloop's anymore.
1430       delete InnerAST;
1431     } else {
1432       CurAST = InnerAST;
1433     }
1434     LoopToAliasSetMap.erase(MapI);
1435   }
1436   if (CurAST == nullptr)
1437     CurAST = new AliasSetTracker(*AA);
1438 
1439   auto mergeLoop = [&](Loop *L) {
1440     // Loop over the body of this loop, looking for calls, invokes, and stores.
1441     for (BasicBlock *BB : L->blocks())
1442       CurAST->add(*BB); // Incorporate the specified basic block
1443   };
1444 
1445   // Add everything from the sub loops that are no longer directly available.
1446   for (Loop *InnerL : RecomputeLoops)
1447     mergeLoop(InnerL);
1448 
1449   // And merge in this loop.
1450   mergeLoop(L);
1451 
1452   return CurAST;
1453 }
1454 
1455 /// Simple analysis hook. Clone alias set info.
1456 ///
1457 void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
1458                                              Loop *L) {
1459   AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
1460   if (!AST)
1461     return;
1462 
1463   AST->copyValue(From, To);
1464 }
1465 
1466 /// Simple Analysis hook. Delete value V from alias set
1467 ///
1468 void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) {
1469   AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
1470   if (!AST)
1471     return;
1472 
1473   AST->deleteValue(V);
1474 }
1475 
1476 /// Simple Analysis hook. Delete value L from alias set map.
1477 ///
1478 void LegacyLICMPass::deleteAnalysisLoop(Loop *L) {
1479   AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
1480   if (!AST)
1481     return;
1482 
1483   delete AST;
1484   LICM.getLoopToAliasSetMap().erase(L);
1485 }
1486 
1487 /// Return true if the body of this loop may store into the memory
1488 /// location pointed to by V.
1489 ///
1490 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
1491                                      const AAMDNodes &AAInfo,
1492                                      AliasSetTracker *CurAST) {
1493   // Check to see if any of the basic blocks in CurLoop invalidate *V.
1494   return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
1495 }
1496 
1497 /// Little predicate that returns true if the specified basic block is in
1498 /// a subloop of the current one, not the current one itself.
1499 ///
1500 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1501   assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1502   return LI->getLoopFor(BB) != CurLoop;
1503 }
1504