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