1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass performs loop invariant code motion, attempting to remove as much
10 // code from the body of a loop as possible.  It does this by either hoisting
11 // code into the preheader block, or by sinking code to the exit blocks if it is
12 // safe.  This pass also promotes must-aliased memory locations in the loop to
13 // live in registers, thus hoisting and sinking "invariant" loads and stores.
14 //
15 // This pass uses alias analysis for two purposes:
16 //
17 //  1. Moving loop invariant loads and calls out of loops.  If we can determine
18 //     that a load or call inside of a loop never aliases anything stored to,
19 //     we can hoist it or sink it like any other instruction.
20 //  2. Scalar Promotion of Memory - If there is a store instruction inside of
21 //     the loop, we try to move the store to happen AFTER the loop instead of
22 //     inside of the loop.  This can only happen if a few conditions are true:
23 //       A. The pointer stored through is loop invariant
24 //       B. There are no stores or loads in the loop which _may_ alias the
25 //          pointer.  There are no calls in the loop which mod/ref the pointer.
26 //     If these conditions are true, we can promote the loads and stores in the
27 //     loop of the pointer to use a temporary alloca'd variable.  We then use
28 //     the SSAUpdater to construct the appropriate SSA form for the value.
29 //
30 //===----------------------------------------------------------------------===//
31 
32 #include "llvm/Transforms/Scalar/LICM.h"
33 #include "llvm/ADT/SetOperations.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/GuardUtils.h"
42 #include "llvm/Analysis/Loads.h"
43 #include "llvm/Analysis/LoopInfo.h"
44 #include "llvm/Analysis/LoopIterator.h"
45 #include "llvm/Analysis/LoopPass.h"
46 #include "llvm/Analysis/MemoryBuiltins.h"
47 #include "llvm/Analysis/MemorySSA.h"
48 #include "llvm/Analysis/MemorySSAUpdater.h"
49 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
50 #include "llvm/Analysis/ScalarEvolution.h"
51 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
52 #include "llvm/Analysis/TargetLibraryInfo.h"
53 #include "llvm/Analysis/ValueTracking.h"
54 #include "llvm/IR/CFG.h"
55 #include "llvm/IR/Constants.h"
56 #include "llvm/IR/DataLayout.h"
57 #include "llvm/IR/DebugInfoMetadata.h"
58 #include "llvm/IR/DerivedTypes.h"
59 #include "llvm/IR/Dominators.h"
60 #include "llvm/IR/Instructions.h"
61 #include "llvm/IR/IntrinsicInst.h"
62 #include "llvm/IR/LLVMContext.h"
63 #include "llvm/IR/Metadata.h"
64 #include "llvm/IR/PatternMatch.h"
65 #include "llvm/IR/PredIteratorCache.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/Debug.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Transforms/Scalar.h"
70 #include "llvm/Transforms/Scalar/LoopPassManager.h"
71 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
72 #include "llvm/Transforms/Utils/Local.h"
73 #include "llvm/Transforms/Utils/LoopUtils.h"
74 #include "llvm/Transforms/Utils/SSAUpdater.h"
75 #include <algorithm>
76 #include <utility>
77 using namespace llvm;
78 
79 #define DEBUG_TYPE "licm"
80 
81 STATISTIC(NumCreatedBlocks, "Number of blocks created");
82 STATISTIC(NumClonedBranches, "Number of branches cloned");
83 STATISTIC(NumSunk, "Number of instructions sunk out of loop");
84 STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
85 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
86 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
87 STATISTIC(NumPromoted, "Number of memory locations promoted to registers");
88 
89 /// Memory promotion is enabled by default.
90 static cl::opt<bool>
91     DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false),
92                      cl::desc("Disable memory promotion in LICM pass"));
93 
94 static cl::opt<bool> ControlFlowHoisting(
95     "licm-control-flow-hoisting", cl::Hidden, cl::init(false),
96     cl::desc("Enable control flow (and PHI) hoisting in LICM"));
97 
98 static cl::opt<uint32_t> MaxNumUsesTraversed(
99     "licm-max-num-uses-traversed", cl::Hidden, cl::init(8),
100     cl::desc("Max num uses visited for identifying load "
101              "invariance in loop using invariant start (default = 8)"));
102 
103 // Default value of zero implies we use the regular alias set tracker mechanism
104 // instead of the cross product using AA to identify aliasing of the memory
105 // location we are interested in.
106 static cl::opt<int>
107 LICMN2Theshold("licm-n2-threshold", cl::Hidden, cl::init(0),
108                cl::desc("How many instruction to cross product using AA"));
109 
110 // Experimental option to allow imprecision in LICM in pathological cases, in
111 // exchange for faster compile. This is to be removed if MemorySSA starts to
112 // address the same issue. This flag applies only when LICM uses MemorySSA
113 // instead on AliasSetTracker. LICM calls MemorySSAWalker's
114 // getClobberingMemoryAccess, up to the value of the Cap, getting perfect
115 // accuracy. Afterwards, LICM will call into MemorySSA's getDefiningAccess,
116 // which may not be precise, since optimizeUses is capped. The result is
117 // correct, but we may not get as "far up" as possible to get which access is
118 // clobbering the one queried.
119 cl::opt<unsigned> llvm::SetLicmMssaOptCap(
120     "licm-mssa-optimization-cap", cl::init(100), cl::Hidden,
121     cl::desc("Enable imprecision in LICM in pathological cases, in exchange "
122              "for faster compile. Caps the MemorySSA clobbering calls."));
123 
124 // Experimentally, memory promotion carries less importance than sinking and
125 // hoisting. Limit when we do promotion when using MemorySSA, in order to save
126 // compile time.
127 cl::opt<unsigned> llvm::SetLicmMssaNoAccForPromotionCap(
128     "licm-mssa-max-acc-promotion", cl::init(250), cl::Hidden,
129     cl::desc("[LICM & MemorySSA] When MSSA in LICM is disabled, this has no "
130              "effect. When MSSA in LICM is enabled, then this is the maximum "
131              "number of accesses allowed to be present in a loop in order to "
132              "enable memory promotion."));
133 
134 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
135 static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
136                                   const LoopSafetyInfo *SafetyInfo,
137                                   TargetTransformInfo *TTI, bool &FreeInLoop);
138 static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
139                   BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo,
140                   MemorySSAUpdater *MSSAU, ScalarEvolution *SE,
141                   OptimizationRemarkEmitter *ORE);
142 static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
143                  const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo,
144                  MemorySSAUpdater *MSSAU, OptimizationRemarkEmitter *ORE);
145 static bool isSafeToExecuteUnconditionally(Instruction &Inst,
146                                            const DominatorTree *DT,
147                                            const Loop *CurLoop,
148                                            const LoopSafetyInfo *SafetyInfo,
149                                            OptimizationRemarkEmitter *ORE,
150                                            const Instruction *CtxI = nullptr);
151 static bool pointerInvalidatedByLoop(MemoryLocation MemLoc,
152                                      AliasSetTracker *CurAST, Loop *CurLoop,
153                                      AliasAnalysis *AA);
154 static bool pointerInvalidatedByLoopWithMSSA(MemorySSA *MSSA, MemoryUse *MU,
155                                              Loop *CurLoop,
156                                              SinkAndHoistLICMFlags &Flags);
157 static Instruction *CloneInstructionInExitBlock(
158     Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI,
159     const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU);
160 
161 static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo,
162                              AliasSetTracker *AST, MemorySSAUpdater *MSSAU);
163 
164 static void moveInstructionBefore(Instruction &I, Instruction &Dest,
165                                   ICFLoopSafetyInfo &SafetyInfo,
166                                   MemorySSAUpdater *MSSAU, ScalarEvolution *SE);
167 
168 namespace {
169 struct LoopInvariantCodeMotion {
170   using ASTrackerMapTy = DenseMap<Loop *, std::unique_ptr<AliasSetTracker>>;
171   bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
172                  TargetLibraryInfo *TLI, TargetTransformInfo *TTI,
173                  ScalarEvolution *SE, MemorySSA *MSSA,
174                  OptimizationRemarkEmitter *ORE, bool DeleteAST);
175 
176   ASTrackerMapTy &getLoopToAliasSetMap() { return LoopToAliasSetMap; }
177   LoopInvariantCodeMotion(unsigned LicmMssaOptCap,
178                           unsigned LicmMssaNoAccForPromotionCap)
179       : LicmMssaOptCap(LicmMssaOptCap),
180         LicmMssaNoAccForPromotionCap(LicmMssaNoAccForPromotionCap) {}
181 
182 private:
183   ASTrackerMapTy LoopToAliasSetMap;
184   unsigned LicmMssaOptCap;
185   unsigned LicmMssaNoAccForPromotionCap;
186 
187   std::unique_ptr<AliasSetTracker>
188   collectAliasInfoForLoop(Loop *L, LoopInfo *LI, AliasAnalysis *AA);
189   std::unique_ptr<AliasSetTracker>
190   collectAliasInfoForLoopWithMSSA(Loop *L, AliasAnalysis *AA,
191                                   MemorySSAUpdater *MSSAU);
192 };
193 
194 struct LegacyLICMPass : public LoopPass {
195   static char ID; // Pass identification, replacement for typeid
196   LegacyLICMPass(
197       unsigned LicmMssaOptCap = SetLicmMssaOptCap,
198       unsigned LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap)
199       : LoopPass(ID), LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap) {
200     initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry());
201   }
202 
203   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
204     if (skipLoop(L)) {
205       // If we have run LICM on a previous loop but now we are skipping
206       // (because we've hit the opt-bisect limit), we need to clear the
207       // loop alias information.
208       LICM.getLoopToAliasSetMap().clear();
209       return false;
210     }
211 
212     auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
213     MemorySSA *MSSA = EnableMSSALoopDependency
214                           ? (&getAnalysis<MemorySSAWrapperPass>().getMSSA())
215                           : nullptr;
216     // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
217     // pass.  Function analyses need to be preserved across loop transformations
218     // but ORE cannot be preserved (see comment before the pass definition).
219     OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
220     return LICM.runOnLoop(L,
221                           &getAnalysis<AAResultsWrapperPass>().getAAResults(),
222                           &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
223                           &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
224                           &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
225                               *L->getHeader()->getParent()),
226                           &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
227                               *L->getHeader()->getParent()),
228                           SE ? &SE->getSE() : nullptr, MSSA, &ORE, false);
229   }
230 
231   /// This transformation requires natural loop information & requires that
232   /// loop preheaders be inserted into the CFG...
233   ///
234   void getAnalysisUsage(AnalysisUsage &AU) const override {
235     AU.addPreserved<DominatorTreeWrapperPass>();
236     AU.addPreserved<LoopInfoWrapperPass>();
237     AU.addRequired<TargetLibraryInfoWrapperPass>();
238     if (EnableMSSALoopDependency) {
239       AU.addRequired<MemorySSAWrapperPass>();
240       AU.addPreserved<MemorySSAWrapperPass>();
241     }
242     AU.addRequired<TargetTransformInfoWrapperPass>();
243     getLoopAnalysisUsage(AU);
244   }
245 
246   using llvm::Pass::doFinalization;
247 
248   bool doFinalization() override {
249     auto &AliasSetMap = LICM.getLoopToAliasSetMap();
250     // All loops in the AliasSetMap should be cleaned up already. The only case
251     // where we fail to do so is if an outer loop gets deleted before LICM
252     // visits it.
253     assert(all_of(AliasSetMap,
254                   [](LoopInvariantCodeMotion::ASTrackerMapTy::value_type &KV) {
255                     return !KV.first->getParentLoop();
256                   }) &&
257            "Didn't free loop alias sets");
258     AliasSetMap.clear();
259     return false;
260   }
261 
262 private:
263   LoopInvariantCodeMotion LICM;
264 
265   /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
266   void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
267                                Loop *L) override;
268 
269   /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
270   /// set.
271   void deleteAnalysisValue(Value *V, Loop *L) override;
272 
273   /// Simple Analysis hook. Delete loop L from alias set map.
274   void deleteAnalysisLoop(Loop *L) override;
275 };
276 } // namespace
277 
278 PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM,
279                                 LoopStandardAnalysisResults &AR, LPMUpdater &) {
280   const auto &FAM =
281       AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
282   Function *F = L.getHeader()->getParent();
283 
284   auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
285   // FIXME: This should probably be optional rather than required.
286   if (!ORE)
287     report_fatal_error("LICM: OptimizationRemarkEmitterAnalysis not "
288                        "cached at a higher level");
289 
290   LoopInvariantCodeMotion LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap);
291   if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.TLI, &AR.TTI, &AR.SE,
292                       AR.MSSA, ORE, true))
293     return PreservedAnalyses::all();
294 
295   auto PA = getLoopPassPreservedAnalyses();
296 
297   PA.preserve<DominatorTreeAnalysis>();
298   PA.preserve<LoopAnalysis>();
299   if (AR.MSSA)
300     PA.preserve<MemorySSAAnalysis>();
301 
302   return PA;
303 }
304 
305 char LegacyLICMPass::ID = 0;
306 INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
307                       false, false)
308 INITIALIZE_PASS_DEPENDENCY(LoopPass)
309 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
310 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
311 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
312 INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
313                     false)
314 
315 Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
316 Pass *llvm::createLICMPass(unsigned LicmMssaOptCap,
317                            unsigned LicmMssaNoAccForPromotionCap) {
318   return new LegacyLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap);
319 }
320 
321 /// Hoist expressions out of the specified loop. Note, alias info for inner
322 /// loop is not preserved so it is not a good idea to run LICM multiple
323 /// times on one loop.
324 /// We should delete AST for inner loops in the new pass manager to avoid
325 /// memory leak.
326 ///
327 bool LoopInvariantCodeMotion::runOnLoop(
328     Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
329     TargetLibraryInfo *TLI, TargetTransformInfo *TTI, ScalarEvolution *SE,
330     MemorySSA *MSSA, OptimizationRemarkEmitter *ORE, bool DeleteAST) {
331   bool Changed = false;
332 
333   assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
334 
335   // If this loop has metadata indicating that LICM is not to be performed then
336   // just exit.
337   if (hasDisableLICMTransformsHint(L)) {
338     return false;
339   }
340 
341   std::unique_ptr<AliasSetTracker> CurAST;
342   std::unique_ptr<MemorySSAUpdater> MSSAU;
343   bool NoOfMemAccTooLarge = false;
344   unsigned LicmMssaOptCounter = 0;
345 
346   if (!MSSA) {
347     LLVM_DEBUG(dbgs() << "LICM: Using Alias Set Tracker.\n");
348     CurAST = collectAliasInfoForLoop(L, LI, AA);
349   } else {
350     LLVM_DEBUG(dbgs() << "LICM: Using MemorySSA.\n");
351     MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
352 
353     unsigned AccessCapCount = 0;
354     for (auto *BB : L->getBlocks()) {
355       if (auto *Accesses = MSSA->getBlockAccesses(BB)) {
356         for (const auto &MA : *Accesses) {
357           (void)MA;
358           AccessCapCount++;
359           if (AccessCapCount > LicmMssaNoAccForPromotionCap) {
360             NoOfMemAccTooLarge = true;
361             break;
362           }
363         }
364       }
365       if (NoOfMemAccTooLarge)
366         break;
367     }
368   }
369 
370   // Get the preheader block to move instructions into...
371   BasicBlock *Preheader = L->getLoopPreheader();
372 
373   // Compute loop safety information.
374   ICFLoopSafetyInfo SafetyInfo(DT);
375   SafetyInfo.computeLoopSafetyInfo(L);
376 
377   // We want to visit all of the instructions in this loop... that are not parts
378   // of our subloops (they have already had their invariants hoisted out of
379   // their loop, into this loop, so there is no need to process the BODIES of
380   // the subloops).
381   //
382   // Traverse the body of the loop in depth first order on the dominator tree so
383   // that we are guaranteed to see definitions before we see uses.  This allows
384   // us to sink instructions in one pass, without iteration.  After sinking
385   // instructions, we perform another pass to hoist them out of the loop.
386   SinkAndHoistLICMFlags Flags = {NoOfMemAccTooLarge, LicmMssaOptCounter,
387                                  LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
388                                  /*IsSink=*/true};
389   if (L->hasDedicatedExits())
390     Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, TTI, L,
391                           CurAST.get(), MSSAU.get(), &SafetyInfo, Flags, ORE);
392   Flags.IsSink = false;
393   if (Preheader)
394     Changed |=
395         hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
396                     CurAST.get(), MSSAU.get(), SE, &SafetyInfo, Flags, ORE);
397 
398   // Now that all loop invariants have been removed from the loop, promote any
399   // memory references to scalars that we can.
400   // Don't sink stores from loops without dedicated block exits. Exits
401   // containing indirect branches are not transformed by loop simplify,
402   // make sure we catch that. An additional load may be generated in the
403   // preheader for SSA updater, so also avoid sinking when no preheader
404   // is available.
405   if (!DisablePromotion && Preheader && L->hasDedicatedExits() &&
406       !NoOfMemAccTooLarge) {
407     // Figure out the loop exits and their insertion points
408     SmallVector<BasicBlock *, 8> ExitBlocks;
409     L->getUniqueExitBlocks(ExitBlocks);
410 
411     // We can't insert into a catchswitch.
412     bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
413       return isa<CatchSwitchInst>(Exit->getTerminator());
414     });
415 
416     if (!HasCatchSwitch) {
417       SmallVector<Instruction *, 8> InsertPts;
418       SmallVector<MemoryAccess *, 8> MSSAInsertPts;
419       InsertPts.reserve(ExitBlocks.size());
420       if (MSSAU)
421         MSSAInsertPts.reserve(ExitBlocks.size());
422       for (BasicBlock *ExitBlock : ExitBlocks) {
423         InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
424         if (MSSAU)
425           MSSAInsertPts.push_back(nullptr);
426       }
427 
428       PredIteratorCache PIC;
429 
430       bool Promoted = false;
431 
432       // Build an AST using MSSA.
433       if (!CurAST.get())
434         CurAST = collectAliasInfoForLoopWithMSSA(L, AA, MSSAU.get());
435 
436       // Loop over all of the alias sets in the tracker object.
437       for (AliasSet &AS : *CurAST) {
438         // We can promote this alias set if it has a store, if it is a "Must"
439         // alias set, if the pointer is loop invariant, and if we are not
440         // eliminating any volatile loads or stores.
441         if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
442             !L->isLoopInvariant(AS.begin()->getValue()))
443           continue;
444 
445         assert(
446             !AS.empty() &&
447             "Must alias set should have at least one pointer element in it!");
448 
449         SmallSetVector<Value *, 8> PointerMustAliases;
450         for (const auto &ASI : AS)
451           PointerMustAliases.insert(ASI.getValue());
452 
453         Promoted |= promoteLoopAccessesToScalars(
454             PointerMustAliases, ExitBlocks, InsertPts, MSSAInsertPts, PIC, LI,
455             DT, TLI, L, CurAST.get(), MSSAU.get(), &SafetyInfo, ORE);
456       }
457 
458       // Once we have promoted values across the loop body we have to
459       // recursively reform LCSSA as any nested loop may now have values defined
460       // within the loop used in the outer loop.
461       // FIXME: This is really heavy handed. It would be a bit better to use an
462       // SSAUpdater strategy during promotion that was LCSSA aware and reformed
463       // it as it went.
464       if (Promoted)
465         formLCSSARecursively(*L, *DT, LI, SE);
466 
467       Changed |= Promoted;
468     }
469   }
470 
471   // Check that neither this loop nor its parent have had LCSSA broken. LICM is
472   // specifically moving instructions across the loop boundary and so it is
473   // especially in need of sanity checking here.
474   assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
475   assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
476          "Parent loop not left in LCSSA form after LICM!");
477 
478   // If this loop is nested inside of another one, save the alias information
479   // for when we process the outer loop.
480   if (!MSSAU.get() && CurAST.get() && L->getParentLoop() && !DeleteAST)
481     LoopToAliasSetMap[L] = std::move(CurAST);
482 
483   if (MSSAU.get() && VerifyMemorySSA)
484     MSSAU->getMemorySSA()->verifyMemorySSA();
485 
486   if (Changed && SE)
487     SE->forgetLoopDispositions(L);
488   return Changed;
489 }
490 
491 /// Walk the specified region of the CFG (defined by all blocks dominated by
492 /// the specified block, and that are in the current loop) in reverse depth
493 /// first order w.r.t the DominatorTree.  This allows us to visit uses before
494 /// definitions, allowing us to sink a loop body in one pass without iteration.
495 ///
496 bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
497                       DominatorTree *DT, TargetLibraryInfo *TLI,
498                       TargetTransformInfo *TTI, Loop *CurLoop,
499                       AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU,
500                       ICFLoopSafetyInfo *SafetyInfo,
501                       SinkAndHoistLICMFlags &Flags,
502                       OptimizationRemarkEmitter *ORE) {
503 
504   // Verify inputs.
505   assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
506          CurLoop != nullptr && SafetyInfo != nullptr &&
507          "Unexpected input to sinkRegion.");
508   assert(((CurAST != nullptr) ^ (MSSAU != nullptr)) &&
509          "Either AliasSetTracker or MemorySSA should be initialized.");
510 
511   // We want to visit children before parents. We will enque all the parents
512   // before their children in the worklist and process the worklist in reverse
513   // order.
514   SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
515 
516   bool Changed = false;
517   for (DomTreeNode *DTN : reverse(Worklist)) {
518     BasicBlock *BB = DTN->getBlock();
519     // Only need to process the contents of this block if it is not part of a
520     // subloop (which would already have been processed).
521     if (inSubLoop(BB, CurLoop, LI))
522       continue;
523 
524     for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
525       Instruction &I = *--II;
526 
527       // If the instruction is dead, we would try to sink it because it isn't
528       // used in the loop, instead, just delete it.
529       if (isInstructionTriviallyDead(&I, TLI)) {
530         LLVM_DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
531         salvageDebugInfo(I);
532         ++II;
533         eraseInstruction(I, *SafetyInfo, CurAST, MSSAU);
534         Changed = true;
535         continue;
536       }
537 
538       // Check to see if we can sink this instruction to the exit blocks
539       // of the loop.  We can do this if the all users of the instruction are
540       // outside of the loop.  In this case, it doesn't even matter if the
541       // operands of the instruction are loop invariant.
542       //
543       bool FreeInLoop = false;
544       if (isNotUsedOrFreeInLoop(I, CurLoop, SafetyInfo, TTI, FreeInLoop) &&
545           canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, MSSAU, true, &Flags,
546                              ORE) &&
547           !I.mayHaveSideEffects()) {
548         if (sink(I, LI, DT, CurLoop, SafetyInfo, MSSAU, ORE)) {
549           if (!FreeInLoop) {
550             ++II;
551             eraseInstruction(I, *SafetyInfo, CurAST, MSSAU);
552           }
553           Changed = true;
554         }
555       }
556     }
557   }
558   if (MSSAU && VerifyMemorySSA)
559     MSSAU->getMemorySSA()->verifyMemorySSA();
560   return Changed;
561 }
562 
563 namespace {
564 // This is a helper class for hoistRegion to make it able to hoist control flow
565 // in order to be able to hoist phis. The way this works is that we initially
566 // start hoisting to the loop preheader, and when we see a loop invariant branch
567 // we make note of this. When we then come to hoist an instruction that's
568 // conditional on such a branch we duplicate the branch and the relevant control
569 // flow, then hoist the instruction into the block corresponding to its original
570 // block in the duplicated control flow.
571 class ControlFlowHoister {
572 private:
573   // Information about the loop we are hoisting from
574   LoopInfo *LI;
575   DominatorTree *DT;
576   Loop *CurLoop;
577   MemorySSAUpdater *MSSAU;
578 
579   // A map of blocks in the loop to the block their instructions will be hoisted
580   // to.
581   DenseMap<BasicBlock *, BasicBlock *> HoistDestinationMap;
582 
583   // The branches that we can hoist, mapped to the block that marks a
584   // convergence point of their control flow.
585   DenseMap<BranchInst *, BasicBlock *> HoistableBranches;
586 
587 public:
588   ControlFlowHoister(LoopInfo *LI, DominatorTree *DT, Loop *CurLoop,
589                      MemorySSAUpdater *MSSAU)
590       : LI(LI), DT(DT), CurLoop(CurLoop), MSSAU(MSSAU) {}
591 
592   void registerPossiblyHoistableBranch(BranchInst *BI) {
593     // We can only hoist conditional branches with loop invariant operands.
594     if (!ControlFlowHoisting || !BI->isConditional() ||
595         !CurLoop->hasLoopInvariantOperands(BI))
596       return;
597 
598     // The branch destinations need to be in the loop, and we don't gain
599     // anything by duplicating conditional branches with duplicate successors,
600     // as it's essentially the same as an unconditional branch.
601     BasicBlock *TrueDest = BI->getSuccessor(0);
602     BasicBlock *FalseDest = BI->getSuccessor(1);
603     if (!CurLoop->contains(TrueDest) || !CurLoop->contains(FalseDest) ||
604         TrueDest == FalseDest)
605       return;
606 
607     // We can hoist BI if one branch destination is the successor of the other,
608     // or both have common successor which we check by seeing if the
609     // intersection of their successors is non-empty.
610     // TODO: This could be expanded to allowing branches where both ends
611     // eventually converge to a single block.
612     SmallPtrSet<BasicBlock *, 4> TrueDestSucc, FalseDestSucc;
613     TrueDestSucc.insert(succ_begin(TrueDest), succ_end(TrueDest));
614     FalseDestSucc.insert(succ_begin(FalseDest), succ_end(FalseDest));
615     BasicBlock *CommonSucc = nullptr;
616     if (TrueDestSucc.count(FalseDest)) {
617       CommonSucc = FalseDest;
618     } else if (FalseDestSucc.count(TrueDest)) {
619       CommonSucc = TrueDest;
620     } else {
621       set_intersect(TrueDestSucc, FalseDestSucc);
622       // If there's one common successor use that.
623       if (TrueDestSucc.size() == 1)
624         CommonSucc = *TrueDestSucc.begin();
625       // If there's more than one pick whichever appears first in the block list
626       // (we can't use the value returned by TrueDestSucc.begin() as it's
627       // unpredicatable which element gets returned).
628       else if (!TrueDestSucc.empty()) {
629         Function *F = TrueDest->getParent();
630         auto IsSucc = [&](BasicBlock &BB) { return TrueDestSucc.count(&BB); };
631         auto It = std::find_if(F->begin(), F->end(), IsSucc);
632         assert(It != F->end() && "Could not find successor in function");
633         CommonSucc = &*It;
634       }
635     }
636     // The common successor has to be dominated by the branch, as otherwise
637     // there will be some other path to the successor that will not be
638     // controlled by this branch so any phi we hoist would be controlled by the
639     // wrong condition. This also takes care of avoiding hoisting of loop back
640     // edges.
641     // TODO: In some cases this could be relaxed if the successor is dominated
642     // by another block that's been hoisted and we can guarantee that the
643     // control flow has been replicated exactly.
644     if (CommonSucc && DT->dominates(BI, CommonSucc))
645       HoistableBranches[BI] = CommonSucc;
646   }
647 
648   bool canHoistPHI(PHINode *PN) {
649     // The phi must have loop invariant operands.
650     if (!ControlFlowHoisting || !CurLoop->hasLoopInvariantOperands(PN))
651       return false;
652     // We can hoist phis if the block they are in is the target of hoistable
653     // branches which cover all of the predecessors of the block.
654     SmallPtrSet<BasicBlock *, 8> PredecessorBlocks;
655     BasicBlock *BB = PN->getParent();
656     for (BasicBlock *PredBB : predecessors(BB))
657       PredecessorBlocks.insert(PredBB);
658     // If we have less predecessor blocks than predecessors then the phi will
659     // have more than one incoming value for the same block which we can't
660     // handle.
661     // TODO: This could be handled be erasing some of the duplicate incoming
662     // values.
663     if (PredecessorBlocks.size() != pred_size(BB))
664       return false;
665     for (auto &Pair : HoistableBranches) {
666       if (Pair.second == BB) {
667         // Which blocks are predecessors via this branch depends on if the
668         // branch is triangle-like or diamond-like.
669         if (Pair.first->getSuccessor(0) == BB) {
670           PredecessorBlocks.erase(Pair.first->getParent());
671           PredecessorBlocks.erase(Pair.first->getSuccessor(1));
672         } else if (Pair.first->getSuccessor(1) == BB) {
673           PredecessorBlocks.erase(Pair.first->getParent());
674           PredecessorBlocks.erase(Pair.first->getSuccessor(0));
675         } else {
676           PredecessorBlocks.erase(Pair.first->getSuccessor(0));
677           PredecessorBlocks.erase(Pair.first->getSuccessor(1));
678         }
679       }
680     }
681     // PredecessorBlocks will now be empty if for every predecessor of BB we
682     // found a hoistable branch source.
683     return PredecessorBlocks.empty();
684   }
685 
686   BasicBlock *getOrCreateHoistedBlock(BasicBlock *BB) {
687     if (!ControlFlowHoisting)
688       return CurLoop->getLoopPreheader();
689     // If BB has already been hoisted, return that
690     if (HoistDestinationMap.count(BB))
691       return HoistDestinationMap[BB];
692 
693     // Check if this block is conditional based on a pending branch
694     auto HasBBAsSuccessor =
695         [&](DenseMap<BranchInst *, BasicBlock *>::value_type &Pair) {
696           return BB != Pair.second && (Pair.first->getSuccessor(0) == BB ||
697                                        Pair.first->getSuccessor(1) == BB);
698         };
699     auto It = std::find_if(HoistableBranches.begin(), HoistableBranches.end(),
700                            HasBBAsSuccessor);
701 
702     // If not involved in a pending branch, hoist to preheader
703     BasicBlock *InitialPreheader = CurLoop->getLoopPreheader();
704     if (It == HoistableBranches.end()) {
705       LLVM_DEBUG(dbgs() << "LICM using " << InitialPreheader->getName()
706                         << " as hoist destination for " << BB->getName()
707                         << "\n");
708       HoistDestinationMap[BB] = InitialPreheader;
709       return InitialPreheader;
710     }
711     BranchInst *BI = It->first;
712     assert(std::find_if(++It, HoistableBranches.end(), HasBBAsSuccessor) ==
713                HoistableBranches.end() &&
714            "BB is expected to be the target of at most one branch");
715 
716     LLVMContext &C = BB->getContext();
717     BasicBlock *TrueDest = BI->getSuccessor(0);
718     BasicBlock *FalseDest = BI->getSuccessor(1);
719     BasicBlock *CommonSucc = HoistableBranches[BI];
720     BasicBlock *HoistTarget = getOrCreateHoistedBlock(BI->getParent());
721 
722     // Create hoisted versions of blocks that currently don't have them
723     auto CreateHoistedBlock = [&](BasicBlock *Orig) {
724       if (HoistDestinationMap.count(Orig))
725         return HoistDestinationMap[Orig];
726       BasicBlock *New =
727           BasicBlock::Create(C, Orig->getName() + ".licm", Orig->getParent());
728       HoistDestinationMap[Orig] = New;
729       DT->addNewBlock(New, HoistTarget);
730       if (CurLoop->getParentLoop())
731         CurLoop->getParentLoop()->addBasicBlockToLoop(New, *LI);
732       ++NumCreatedBlocks;
733       LLVM_DEBUG(dbgs() << "LICM created " << New->getName()
734                         << " as hoist destination for " << Orig->getName()
735                         << "\n");
736       return New;
737     };
738     BasicBlock *HoistTrueDest = CreateHoistedBlock(TrueDest);
739     BasicBlock *HoistFalseDest = CreateHoistedBlock(FalseDest);
740     BasicBlock *HoistCommonSucc = CreateHoistedBlock(CommonSucc);
741 
742     // Link up these blocks with branches.
743     if (!HoistCommonSucc->getTerminator()) {
744       // The new common successor we've generated will branch to whatever that
745       // hoist target branched to.
746       BasicBlock *TargetSucc = HoistTarget->getSingleSuccessor();
747       assert(TargetSucc && "Expected hoist target to have a single successor");
748       HoistCommonSucc->moveBefore(TargetSucc);
749       BranchInst::Create(TargetSucc, HoistCommonSucc);
750     }
751     if (!HoistTrueDest->getTerminator()) {
752       HoistTrueDest->moveBefore(HoistCommonSucc);
753       BranchInst::Create(HoistCommonSucc, HoistTrueDest);
754     }
755     if (!HoistFalseDest->getTerminator()) {
756       HoistFalseDest->moveBefore(HoistCommonSucc);
757       BranchInst::Create(HoistCommonSucc, HoistFalseDest);
758     }
759 
760     // If BI is being cloned to what was originally the preheader then
761     // HoistCommonSucc will now be the new preheader.
762     if (HoistTarget == InitialPreheader) {
763       // Phis in the loop header now need to use the new preheader.
764       InitialPreheader->replaceSuccessorsPhiUsesWith(HoistCommonSucc);
765       if (MSSAU)
766         MSSAU->wireOldPredecessorsToNewImmediatePredecessor(
767             HoistTarget->getSingleSuccessor(), HoistCommonSucc, {HoistTarget});
768       // The new preheader dominates the loop header.
769       DomTreeNode *PreheaderNode = DT->getNode(HoistCommonSucc);
770       DomTreeNode *HeaderNode = DT->getNode(CurLoop->getHeader());
771       DT->changeImmediateDominator(HeaderNode, PreheaderNode);
772       // The preheader hoist destination is now the new preheader, with the
773       // exception of the hoist destination of this branch.
774       for (auto &Pair : HoistDestinationMap)
775         if (Pair.second == InitialPreheader && Pair.first != BI->getParent())
776           Pair.second = HoistCommonSucc;
777     }
778 
779     // Now finally clone BI.
780     ReplaceInstWithInst(
781         HoistTarget->getTerminator(),
782         BranchInst::Create(HoistTrueDest, HoistFalseDest, BI->getCondition()));
783     ++NumClonedBranches;
784 
785     assert(CurLoop->getLoopPreheader() &&
786            "Hoisting blocks should not have destroyed preheader");
787     return HoistDestinationMap[BB];
788   }
789 };
790 } // namespace
791 
792 
793 /// Return true if we know how to rewrite all uses of the given alloca after
794 /// hoisting it out of the loop.  The main concerns are a) potential captures
795 /// and b) invariant.start markers which don't capture, but are no longer
796 /// valid w/o a corresponding invariant.end.
797 static bool canRewriteUsesOfAlloca(AllocaInst &AI) {
798   // TODO: This looks a lot like capture tracking, but we need to remove any
799   // invariant starts if we extend the lifetime of the alloca by hoisting it.
800   // We should probably refactor capture tracking into a form which allows us
801   // to reuse the relevant bits and remove the duplicated logic here.
802 
803   SmallVector<Use *, 16> Worklist;
804   for (Use &U : AI.uses())
805     Worklist.push_back(&U);
806 
807   unsigned NumUsesExplored = 0;
808   while (!Worklist.empty()) {
809     Use *U = Worklist.pop_back_val();
810     Instruction *I = cast<Instruction>(U->getUser());
811     NumUsesExplored++;
812     if (NumUsesExplored > DefaultMaxUsesToExplore)
813       return false;
814     // Non capturing, terminating uses
815     if (isa<LoadInst>(I) ||
816         (isa<StoreInst>(I) && U->getOperandNo() == 1))
817       continue;
818     // Non capturing, non-terminating
819     if (!isa<BitCastInst>(I) && !isa<GetElementPtrInst>(I))
820       return false;
821     for (Use &U : I->uses())
822       Worklist.push_back(&U);
823   }
824   return true;
825 }
826 
827 /// Walk the specified region of the CFG (defined by all blocks dominated by
828 /// the specified block, and that are in the current loop) in depth first
829 /// order w.r.t the DominatorTree.  This allows us to visit definitions before
830 /// uses, allowing us to hoist a loop body in one pass without iteration.
831 ///
832 bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
833                        DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
834                        AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU,
835                        ScalarEvolution *SE, ICFLoopSafetyInfo *SafetyInfo,
836                        SinkAndHoistLICMFlags &Flags,
837                        OptimizationRemarkEmitter *ORE) {
838   // Verify inputs.
839   assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
840          CurLoop != nullptr && SafetyInfo != nullptr &&
841          "Unexpected input to hoistRegion.");
842   assert(((CurAST != nullptr) ^ (MSSAU != nullptr)) &&
843          "Either AliasSetTracker or MemorySSA should be initialized.");
844 
845   ControlFlowHoister CFH(LI, DT, CurLoop, MSSAU);
846 
847   // Keep track of instructions that have been hoisted, as they may need to be
848   // re-hoisted if they end up not dominating all of their uses.
849   SmallVector<Instruction *, 16> HoistedInstructions;
850 
851   // For PHI hoisting to work we need to hoist blocks before their successors.
852   // We can do this by iterating through the blocks in the loop in reverse
853   // post-order.
854   LoopBlocksRPO Worklist(CurLoop);
855   Worklist.perform(LI);
856   bool Changed = false;
857   for (BasicBlock *BB : Worklist) {
858     // Only need to process the contents of this block if it is not part of a
859     // subloop (which would already have been processed).
860     if (inSubLoop(BB, CurLoop, LI))
861       continue;
862 
863     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
864       Instruction &I = *II++;
865       // Try constant folding this instruction.  If all the operands are
866       // constants, it is technically hoistable, but it would be better to
867       // just fold it.
868       if (Constant *C = ConstantFoldInstruction(
869               &I, I.getModule()->getDataLayout(), TLI)) {
870         LLVM_DEBUG(dbgs() << "LICM folding inst: " << I << "  --> " << *C
871                           << '\n');
872         if (CurAST)
873           CurAST->copyValue(&I, C);
874         // FIXME MSSA: Such replacements may make accesses unoptimized (D51960).
875         I.replaceAllUsesWith(C);
876         if (isInstructionTriviallyDead(&I, TLI))
877           eraseInstruction(I, *SafetyInfo, CurAST, MSSAU);
878         Changed = true;
879         continue;
880       }
881 
882       // Try hoisting the instruction out to the preheader.  We can only do
883       // this if all of the operands of the instruction are loop invariant and
884       // if it is safe to hoist the instruction.
885       // TODO: It may be safe to hoist if we are hoisting to a conditional block
886       // and we have accurately duplicated the control flow from the loop header
887       // to that block.
888       if (CurLoop->hasLoopInvariantOperands(&I) &&
889           canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, MSSAU, true, &Flags,
890                              ORE) &&
891           isSafeToExecuteUnconditionally(
892               I, DT, CurLoop, SafetyInfo, ORE,
893               CurLoop->getLoopPreheader()->getTerminator())) {
894         hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
895               MSSAU, SE, ORE);
896         HoistedInstructions.push_back(&I);
897         Changed = true;
898         continue;
899       }
900 
901       // Attempt to remove floating point division out of the loop by
902       // converting it to a reciprocal multiplication.
903       if (I.getOpcode() == Instruction::FDiv &&
904           CurLoop->isLoopInvariant(I.getOperand(1)) &&
905           I.hasAllowReciprocal()) {
906         auto Divisor = I.getOperand(1);
907         auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0);
908         auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);
909         ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags());
910         SafetyInfo->insertInstructionTo(ReciprocalDivisor, I.getParent());
911         ReciprocalDivisor->insertBefore(&I);
912 
913         auto Product =
914             BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor);
915         Product->setFastMathFlags(I.getFastMathFlags());
916         SafetyInfo->insertInstructionTo(Product, I.getParent());
917         Product->insertAfter(&I);
918         I.replaceAllUsesWith(Product);
919         eraseInstruction(I, *SafetyInfo, CurAST, MSSAU);
920 
921         hoist(*ReciprocalDivisor, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB),
922               SafetyInfo, MSSAU, SE, ORE);
923         HoistedInstructions.push_back(ReciprocalDivisor);
924         Changed = true;
925         continue;
926       }
927 
928       auto IsInvariantStart = [&](Instruction &I) {
929         using namespace PatternMatch;
930         return I.use_empty() &&
931                match(&I, m_Intrinsic<Intrinsic::invariant_start>());
932       };
933       auto MustExecuteWithoutWritesBefore = [&](Instruction &I) {
934         return SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop) &&
935                SafetyInfo->doesNotWriteMemoryBefore(I, CurLoop);
936       };
937       if ((IsInvariantStart(I) || isGuard(&I)) &&
938           CurLoop->hasLoopInvariantOperands(&I) &&
939           MustExecuteWithoutWritesBefore(I)) {
940         hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
941               MSSAU, SE, ORE);
942         HoistedInstructions.push_back(&I);
943         Changed = true;
944         continue;
945       }
946 
947       if (isa<AllocaInst>(&I) &&
948           SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop) &&
949           canRewriteUsesOfAlloca(cast<AllocaInst>(I))) {
950         hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
951               MSSAU, SE, ORE);
952         HoistedInstructions.push_back(&I);
953         Changed = true;
954         continue;
955       }
956 
957       if (PHINode *PN = dyn_cast<PHINode>(&I)) {
958         if (CFH.canHoistPHI(PN)) {
959           // Redirect incoming blocks first to ensure that we create hoisted
960           // versions of those blocks before we hoist the phi.
961           for (unsigned int i = 0; i < PN->getNumIncomingValues(); ++i)
962             PN->setIncomingBlock(
963                 i, CFH.getOrCreateHoistedBlock(PN->getIncomingBlock(i)));
964           hoist(*PN, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
965                 MSSAU, SE, ORE);
966           assert(DT->dominates(PN, BB) && "Conditional PHIs not expected");
967           Changed = true;
968           continue;
969         }
970       }
971 
972       // Remember possibly hoistable branches so we can actually hoist them
973       // later if needed.
974       if (BranchInst *BI = dyn_cast<BranchInst>(&I))
975         CFH.registerPossiblyHoistableBranch(BI);
976     }
977   }
978 
979   // If we hoisted instructions to a conditional block they may not dominate
980   // their uses that weren't hoisted (such as phis where some operands are not
981   // loop invariant). If so make them unconditional by moving them to their
982   // immediate dominator. We iterate through the instructions in reverse order
983   // which ensures that when we rehoist an instruction we rehoist its operands,
984   // and also keep track of where in the block we are rehoisting to to make sure
985   // that we rehoist instructions before the instructions that use them.
986   Instruction *HoistPoint = nullptr;
987   if (ControlFlowHoisting) {
988     for (Instruction *I : reverse(HoistedInstructions)) {
989       if (!llvm::all_of(I->uses(),
990                         [&](Use &U) { return DT->dominates(I, U); })) {
991         BasicBlock *Dominator =
992             DT->getNode(I->getParent())->getIDom()->getBlock();
993         if (!HoistPoint || !DT->dominates(HoistPoint->getParent(), Dominator)) {
994           if (HoistPoint)
995             assert(DT->dominates(Dominator, HoistPoint->getParent()) &&
996                    "New hoist point expected to dominate old hoist point");
997           HoistPoint = Dominator->getTerminator();
998         }
999         LLVM_DEBUG(dbgs() << "LICM rehoisting to "
1000                           << HoistPoint->getParent()->getName()
1001                           << ": " << *I << "\n");
1002         moveInstructionBefore(*I, *HoistPoint, *SafetyInfo, MSSAU, SE);
1003         HoistPoint = I;
1004         Changed = true;
1005       }
1006     }
1007   }
1008   if (MSSAU && VerifyMemorySSA)
1009     MSSAU->getMemorySSA()->verifyMemorySSA();
1010 
1011     // Now that we've finished hoisting make sure that LI and DT are still
1012     // valid.
1013 #ifdef EXPENSIVE_CHECKS
1014   if (Changed) {
1015     assert(DT->verify(DominatorTree::VerificationLevel::Fast) &&
1016            "Dominator tree verification failed");
1017     LI->verify(*DT);
1018   }
1019 #endif
1020 
1021   return Changed;
1022 }
1023 
1024 // Return true if LI is invariant within scope of the loop. LI is invariant if
1025 // CurLoop is dominated by an invariant.start representing the same memory
1026 // location and size as the memory location LI loads from, and also the
1027 // invariant.start has no uses.
1028 static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT,
1029                                   Loop *CurLoop) {
1030   Value *Addr = LI->getOperand(0);
1031   const DataLayout &DL = LI->getModule()->getDataLayout();
1032   const uint32_t LocSizeInBits = DL.getTypeSizeInBits(LI->getType());
1033 
1034   // if the type is i8 addrspace(x)*, we know this is the type of
1035   // llvm.invariant.start operand
1036   auto *PtrInt8Ty = PointerType::get(Type::getInt8Ty(LI->getContext()),
1037                                      LI->getPointerAddressSpace());
1038   unsigned BitcastsVisited = 0;
1039   // Look through bitcasts until we reach the i8* type (this is invariant.start
1040   // operand type).
1041   while (Addr->getType() != PtrInt8Ty) {
1042     auto *BC = dyn_cast<BitCastInst>(Addr);
1043     // Avoid traversing high number of bitcast uses.
1044     if (++BitcastsVisited > MaxNumUsesTraversed || !BC)
1045       return false;
1046     Addr = BC->getOperand(0);
1047   }
1048 
1049   unsigned UsesVisited = 0;
1050   // Traverse all uses of the load operand value, to see if invariant.start is
1051   // one of the uses, and whether it dominates the load instruction.
1052   for (auto *U : Addr->users()) {
1053     // Avoid traversing for Load operand with high number of users.
1054     if (++UsesVisited > MaxNumUsesTraversed)
1055       return false;
1056     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
1057     // If there are escaping uses of invariant.start instruction, the load maybe
1058     // non-invariant.
1059     if (!II || II->getIntrinsicID() != Intrinsic::invariant_start ||
1060         !II->use_empty())
1061       continue;
1062     unsigned InvariantSizeInBits =
1063         cast<ConstantInt>(II->getArgOperand(0))->getSExtValue() * 8;
1064     // Confirm the invariant.start location size contains the load operand size
1065     // in bits. Also, the invariant.start should dominate the load, and we
1066     // should not hoist the load out of a loop that contains this dominating
1067     // invariant.start.
1068     if (LocSizeInBits <= InvariantSizeInBits &&
1069         DT->properlyDominates(II->getParent(), CurLoop->getHeader()))
1070       return true;
1071   }
1072 
1073   return false;
1074 }
1075 
1076 namespace {
1077 /// Return true if-and-only-if we know how to (mechanically) both hoist and
1078 /// sink a given instruction out of a loop.  Does not address legality
1079 /// concerns such as aliasing or speculation safety.
1080 bool isHoistableAndSinkableInst(Instruction &I) {
1081   // Only these instructions are hoistable/sinkable.
1082   return (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
1083           isa<FenceInst>(I) || isa<CastInst>(I) ||
1084           isa<UnaryOperator>(I) || isa<BinaryOperator>(I) ||
1085           isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||
1086           isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
1087           isa<ShuffleVectorInst>(I) || isa<ExtractValueInst>(I) ||
1088           isa<InsertValueInst>(I));
1089 }
1090 /// Return true if all of the alias sets within this AST are known not to
1091 /// contain a Mod, or if MSSA knows thare are no MemoryDefs in the loop.
1092 bool isReadOnly(AliasSetTracker *CurAST, const MemorySSAUpdater *MSSAU,
1093                 const Loop *L) {
1094   if (CurAST) {
1095     for (AliasSet &AS : *CurAST) {
1096       if (!AS.isForwardingAliasSet() && AS.isMod()) {
1097         return false;
1098       }
1099     }
1100     return true;
1101   } else { /*MSSAU*/
1102     for (auto *BB : L->getBlocks())
1103       if (MSSAU->getMemorySSA()->getBlockDefs(BB))
1104         return false;
1105     return true;
1106   }
1107 }
1108 
1109 /// Return true if I is the only Instruction with a MemoryAccess in L.
1110 bool isOnlyMemoryAccess(const Instruction *I, const Loop *L,
1111                         const MemorySSAUpdater *MSSAU) {
1112   for (auto *BB : L->getBlocks())
1113     if (auto *Accs = MSSAU->getMemorySSA()->getBlockAccesses(BB)) {
1114       int NotAPhi = 0;
1115       for (const auto &Acc : *Accs) {
1116         if (isa<MemoryPhi>(&Acc))
1117           continue;
1118         const auto *MUD = cast<MemoryUseOrDef>(&Acc);
1119         if (MUD->getMemoryInst() != I || NotAPhi++ == 1)
1120           return false;
1121       }
1122     }
1123   return true;
1124 }
1125 }
1126 
1127 bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,
1128                               Loop *CurLoop, AliasSetTracker *CurAST,
1129                               MemorySSAUpdater *MSSAU,
1130                               bool TargetExecutesOncePerLoop,
1131                               SinkAndHoistLICMFlags *Flags,
1132                               OptimizationRemarkEmitter *ORE) {
1133   // If we don't understand the instruction, bail early.
1134   if (!isHoistableAndSinkableInst(I))
1135     return false;
1136 
1137   MemorySSA *MSSA = MSSAU ? MSSAU->getMemorySSA() : nullptr;
1138   if (MSSA)
1139     assert(Flags != nullptr && "Flags cannot be null.");
1140 
1141   // Loads have extra constraints we have to verify before we can hoist them.
1142   if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
1143     if (!LI->isUnordered())
1144       return false; // Don't sink/hoist volatile or ordered atomic loads!
1145 
1146     // Loads from constant memory are always safe to move, even if they end up
1147     // in the same alias set as something that ends up being modified.
1148     if (AA->pointsToConstantMemory(LI->getOperand(0)))
1149       return true;
1150     if (LI->hasMetadata(LLVMContext::MD_invariant_load))
1151       return true;
1152 
1153     if (LI->isAtomic() && !TargetExecutesOncePerLoop)
1154       return false; // Don't risk duplicating unordered loads
1155 
1156     // This checks for an invariant.start dominating the load.
1157     if (isLoadInvariantInLoop(LI, DT, CurLoop))
1158       return true;
1159 
1160     bool Invalidated;
1161     if (CurAST)
1162       Invalidated = pointerInvalidatedByLoop(MemoryLocation::get(LI), CurAST,
1163                                              CurLoop, AA);
1164     else
1165       Invalidated = pointerInvalidatedByLoopWithMSSA(
1166           MSSA, cast<MemoryUse>(MSSA->getMemoryAccess(LI)), CurLoop, *Flags);
1167     // Check loop-invariant address because this may also be a sinkable load
1168     // whose address is not necessarily loop-invariant.
1169     if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand()))
1170       ORE->emit([&]() {
1171         return OptimizationRemarkMissed(
1172                    DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", LI)
1173                << "failed to move load with loop-invariant address "
1174                   "because the loop may invalidate its value";
1175       });
1176 
1177     return !Invalidated;
1178   } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1179     // Don't sink or hoist dbg info; it's legal, but not useful.
1180     if (isa<DbgInfoIntrinsic>(I))
1181       return false;
1182 
1183     // Don't sink calls which can throw.
1184     if (CI->mayThrow())
1185       return false;
1186 
1187     using namespace PatternMatch;
1188     if (match(CI, m_Intrinsic<Intrinsic::assume>()))
1189       // Assumes don't actually alias anything or throw
1190       return true;
1191 
1192     if (match(CI, m_Intrinsic<Intrinsic::experimental_widenable_condition>()))
1193       // Widenable conditions don't actually alias anything or throw
1194       return true;
1195 
1196     // Handle simple cases by querying alias analysis.
1197     FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
1198     if (Behavior == FMRB_DoesNotAccessMemory)
1199       return true;
1200     if (AliasAnalysis::onlyReadsMemory(Behavior)) {
1201       // A readonly argmemonly function only reads from memory pointed to by
1202       // it's arguments with arbitrary offsets.  If we can prove there are no
1203       // writes to this memory in the loop, we can hoist or sink.
1204       if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
1205         // TODO: expand to writeable arguments
1206         for (Value *Op : CI->arg_operands())
1207           if (Op->getType()->isPointerTy()) {
1208             bool Invalidated;
1209             if (CurAST)
1210               Invalidated = pointerInvalidatedByLoop(
1211                   MemoryLocation(Op, LocationSize::unknown(), AAMDNodes()),
1212                   CurAST, CurLoop, AA);
1213             else
1214               Invalidated = pointerInvalidatedByLoopWithMSSA(
1215                   MSSA, cast<MemoryUse>(MSSA->getMemoryAccess(CI)), CurLoop,
1216                   *Flags);
1217             if (Invalidated)
1218               return false;
1219           }
1220         return true;
1221       }
1222 
1223       // If this call only reads from memory and there are no writes to memory
1224       // in the loop, we can hoist or sink the call as appropriate.
1225       if (isReadOnly(CurAST, MSSAU, CurLoop))
1226         return true;
1227     }
1228 
1229     // FIXME: This should use mod/ref information to see if we can hoist or
1230     // sink the call.
1231 
1232     return false;
1233   } else if (auto *FI = dyn_cast<FenceInst>(&I)) {
1234     // Fences alias (most) everything to provide ordering.  For the moment,
1235     // just give up if there are any other memory operations in the loop.
1236     if (CurAST) {
1237       auto Begin = CurAST->begin();
1238       assert(Begin != CurAST->end() && "must contain FI");
1239       if (std::next(Begin) != CurAST->end())
1240         // constant memory for instance, TODO: handle better
1241         return false;
1242       auto *UniqueI = Begin->getUniqueInstruction();
1243       if (!UniqueI)
1244         // other memory op, give up
1245         return false;
1246       (void)FI; // suppress unused variable warning
1247       assert(UniqueI == FI && "AS must contain FI");
1248       return true;
1249     } else // MSSAU
1250       return isOnlyMemoryAccess(FI, CurLoop, MSSAU);
1251   } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
1252     if (!SI->isUnordered())
1253       return false; // Don't sink/hoist volatile or ordered atomic store!
1254 
1255     // We can only hoist a store that we can prove writes a value which is not
1256     // read or overwritten within the loop.  For those cases, we fallback to
1257     // load store promotion instead.  TODO: We can extend this to cases where
1258     // there is exactly one write to the location and that write dominates an
1259     // arbitrary number of reads in the loop.
1260     if (CurAST) {
1261       auto &AS = CurAST->getAliasSetFor(MemoryLocation::get(SI));
1262 
1263       if (AS.isRef() || !AS.isMustAlias())
1264         // Quick exit test, handled by the full path below as well.
1265         return false;
1266       auto *UniqueI = AS.getUniqueInstruction();
1267       if (!UniqueI)
1268         // other memory op, give up
1269         return false;
1270       assert(UniqueI == SI && "AS must contain SI");
1271       return true;
1272     } else { // MSSAU
1273       if (isOnlyMemoryAccess(SI, CurLoop, MSSAU))
1274         return true;
1275       // If there are more accesses than the Promotion cap, give up, we're not
1276       // walking a list that long.
1277       if (Flags->NoOfMemAccTooLarge)
1278         return false;
1279       // Check store only if there's still "quota" to check clobber.
1280       if (Flags->LicmMssaOptCounter >= Flags->LicmMssaOptCap)
1281         return false;
1282       // If there are interfering Uses (i.e. their defining access is in the
1283       // loop), or ordered loads (stored as Defs!), don't move this store.
1284       // Could do better here, but this is conservatively correct.
1285       // TODO: Cache set of Uses on the first walk in runOnLoop, update when
1286       // moving accesses. Can also extend to dominating uses.
1287       auto *SIMD = MSSA->getMemoryAccess(SI);
1288       for (auto *BB : CurLoop->getBlocks())
1289         if (auto *Accesses = MSSA->getBlockAccesses(BB)) {
1290           for (const auto &MA : *Accesses)
1291             if (const auto *MU = dyn_cast<MemoryUse>(&MA)) {
1292               auto *MD = MU->getDefiningAccess();
1293               if (!MSSA->isLiveOnEntryDef(MD) &&
1294                   CurLoop->contains(MD->getBlock()))
1295                 return false;
1296               // Disable hoisting past potentially interfering loads. Optimized
1297               // Uses may point to an access outside the loop, as getClobbering
1298               // checks the previous iteration when walking the backedge.
1299               // FIXME: More precise: no Uses that alias SI.
1300               if (!Flags->IsSink && !MSSA->dominates(SIMD, MU))
1301                 return false;
1302             } else if (const auto *MD = dyn_cast<MemoryDef>(&MA)) {
1303               if (auto *LI = dyn_cast<LoadInst>(MD->getMemoryInst())) {
1304                 (void)LI; // Silence warning.
1305                 assert(!LI->isUnordered() && "Expected unordered load");
1306                 return false;
1307               }
1308               // Any call, while it may not be clobbering SI, it may be a use.
1309               if (auto *CI = dyn_cast<CallInst>(MD->getMemoryInst())) {
1310                 // Check if the call may read from the memory locattion written
1311                 // to by SI. Check CI's attributes and arguments; the number of
1312                 // such checks performed is limited above by NoOfMemAccTooLarge.
1313                 ModRefInfo MRI = AA->getModRefInfo(CI, MemoryLocation::get(SI));
1314                 if (isModOrRefSet(MRI))
1315                   return false;
1316               }
1317             }
1318         }
1319 
1320       auto *Source = MSSA->getSkipSelfWalker()->getClobberingMemoryAccess(SI);
1321       Flags->LicmMssaOptCounter++;
1322       // If there are no clobbering Defs in the loop, store is safe to hoist.
1323       return MSSA->isLiveOnEntryDef(Source) ||
1324              !CurLoop->contains(Source->getBlock());
1325     }
1326   }
1327 
1328   assert(!I.mayReadOrWriteMemory() && "unhandled aliasing");
1329 
1330   // We've established mechanical ability and aliasing, it's up to the caller
1331   // to check fault safety
1332   return true;
1333 }
1334 
1335 /// Returns true if a PHINode is a trivially replaceable with an
1336 /// Instruction.
1337 /// This is true when all incoming values are that instruction.
1338 /// This pattern occurs most often with LCSSA PHI nodes.
1339 ///
1340 static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I) {
1341   for (const Value *IncValue : PN.incoming_values())
1342     if (IncValue != &I)
1343       return false;
1344 
1345   return true;
1346 }
1347 
1348 /// Return true if the instruction is free in the loop.
1349 static bool isFreeInLoop(const Instruction &I, const Loop *CurLoop,
1350                          const TargetTransformInfo *TTI) {
1351 
1352   if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1353     if (TTI->getUserCost(GEP) != TargetTransformInfo::TCC_Free)
1354       return false;
1355     // For a GEP, we cannot simply use getUserCost because currently it
1356     // optimistically assume that a GEP will fold into addressing mode
1357     // regardless of its users.
1358     const BasicBlock *BB = GEP->getParent();
1359     for (const User *U : GEP->users()) {
1360       const Instruction *UI = cast<Instruction>(U);
1361       if (CurLoop->contains(UI) &&
1362           (BB != UI->getParent() ||
1363            (!isa<StoreInst>(UI) && !isa<LoadInst>(UI))))
1364         return false;
1365     }
1366     return true;
1367   } else
1368     return TTI->getUserCost(&I) == TargetTransformInfo::TCC_Free;
1369 }
1370 
1371 /// Return true if the only users of this instruction are outside of
1372 /// the loop. If this is true, we can sink the instruction to the exit
1373 /// blocks of the loop.
1374 ///
1375 /// We also return true if the instruction could be folded away in lowering.
1376 /// (e.g.,  a GEP can be folded into a load as an addressing mode in the loop).
1377 static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
1378                                   const LoopSafetyInfo *SafetyInfo,
1379                                   TargetTransformInfo *TTI, bool &FreeInLoop) {
1380   const auto &BlockColors = SafetyInfo->getBlockColors();
1381   bool IsFree = isFreeInLoop(I, CurLoop, TTI);
1382   for (const User *U : I.users()) {
1383     const Instruction *UI = cast<Instruction>(U);
1384     if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
1385       const BasicBlock *BB = PN->getParent();
1386       // We cannot sink uses in catchswitches.
1387       if (isa<CatchSwitchInst>(BB->getTerminator()))
1388         return false;
1389 
1390       // We need to sink a callsite to a unique funclet.  Avoid sinking if the
1391       // phi use is too muddled.
1392       if (isa<CallInst>(I))
1393         if (!BlockColors.empty() &&
1394             BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
1395           return false;
1396     }
1397 
1398     if (CurLoop->contains(UI)) {
1399       if (IsFree) {
1400         FreeInLoop = true;
1401         continue;
1402       }
1403       return false;
1404     }
1405   }
1406   return true;
1407 }
1408 
1409 static Instruction *CloneInstructionInExitBlock(
1410     Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI,
1411     const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU) {
1412   Instruction *New;
1413   if (auto *CI = dyn_cast<CallInst>(&I)) {
1414     const auto &BlockColors = SafetyInfo->getBlockColors();
1415 
1416     // Sinking call-sites need to be handled differently from other
1417     // instructions.  The cloned call-site needs a funclet bundle operand
1418     // appropriate for its location in the CFG.
1419     SmallVector<OperandBundleDef, 1> OpBundles;
1420     for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
1421          BundleIdx != BundleEnd; ++BundleIdx) {
1422       OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
1423       if (Bundle.getTagID() == LLVMContext::OB_funclet)
1424         continue;
1425 
1426       OpBundles.emplace_back(Bundle);
1427     }
1428 
1429     if (!BlockColors.empty()) {
1430       const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
1431       assert(CV.size() == 1 && "non-unique color for exit block!");
1432       BasicBlock *BBColor = CV.front();
1433       Instruction *EHPad = BBColor->getFirstNonPHI();
1434       if (EHPad->isEHPad())
1435         OpBundles.emplace_back("funclet", EHPad);
1436     }
1437 
1438     New = CallInst::Create(CI, OpBundles);
1439   } else {
1440     New = I.clone();
1441   }
1442 
1443   ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
1444   if (!I.getName().empty())
1445     New->setName(I.getName() + ".le");
1446 
1447   if (MSSAU && MSSAU->getMemorySSA()->getMemoryAccess(&I)) {
1448     // Create a new MemoryAccess and let MemorySSA set its defining access.
1449     MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
1450         New, nullptr, New->getParent(), MemorySSA::Beginning);
1451     if (NewMemAcc) {
1452       if (auto *MemDef = dyn_cast<MemoryDef>(NewMemAcc))
1453         MSSAU->insertDef(MemDef, /*RenameUses=*/true);
1454       else {
1455         auto *MemUse = cast<MemoryUse>(NewMemAcc);
1456         MSSAU->insertUse(MemUse, /*RenameUses=*/true);
1457       }
1458     }
1459   }
1460 
1461   // Build LCSSA PHI nodes for any in-loop operands. Note that this is
1462   // particularly cheap because we can rip off the PHI node that we're
1463   // replacing for the number and blocks of the predecessors.
1464   // OPT: If this shows up in a profile, we can instead finish sinking all
1465   // invariant instructions, and then walk their operands to re-establish
1466   // LCSSA. That will eliminate creating PHI nodes just to nuke them when
1467   // sinking bottom-up.
1468   for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
1469        ++OI)
1470     if (Instruction *OInst = dyn_cast<Instruction>(*OI))
1471       if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
1472         if (!OLoop->contains(&PN)) {
1473           PHINode *OpPN =
1474               PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
1475                               OInst->getName() + ".lcssa", &ExitBlock.front());
1476           for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1477             OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
1478           *OI = OpPN;
1479         }
1480   return New;
1481 }
1482 
1483 static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo,
1484                              AliasSetTracker *AST, MemorySSAUpdater *MSSAU) {
1485   if (AST)
1486     AST->deleteValue(&I);
1487   if (MSSAU)
1488     MSSAU->removeMemoryAccess(&I);
1489   SafetyInfo.removeInstruction(&I);
1490   I.eraseFromParent();
1491 }
1492 
1493 static void moveInstructionBefore(Instruction &I, Instruction &Dest,
1494                                   ICFLoopSafetyInfo &SafetyInfo,
1495                                   MemorySSAUpdater *MSSAU,
1496                                   ScalarEvolution *SE) {
1497   SafetyInfo.removeInstruction(&I);
1498   SafetyInfo.insertInstructionTo(&I, Dest.getParent());
1499   I.moveBefore(&Dest);
1500   if (MSSAU)
1501     if (MemoryUseOrDef *OldMemAcc = cast_or_null<MemoryUseOrDef>(
1502             MSSAU->getMemorySSA()->getMemoryAccess(&I)))
1503       MSSAU->moveToPlace(OldMemAcc, Dest.getParent(), MemorySSA::End);
1504   if (SE)
1505     SE->forgetValue(&I);
1506 }
1507 
1508 static Instruction *sinkThroughTriviallyReplaceablePHI(
1509     PHINode *TPN, Instruction *I, LoopInfo *LI,
1510     SmallDenseMap<BasicBlock *, Instruction *, 32> &SunkCopies,
1511     const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop,
1512     MemorySSAUpdater *MSSAU) {
1513   assert(isTriviallyReplaceablePHI(*TPN, *I) &&
1514          "Expect only trivially replaceable PHI");
1515   BasicBlock *ExitBlock = TPN->getParent();
1516   Instruction *New;
1517   auto It = SunkCopies.find(ExitBlock);
1518   if (It != SunkCopies.end())
1519     New = It->second;
1520   else
1521     New = SunkCopies[ExitBlock] = CloneInstructionInExitBlock(
1522         *I, *ExitBlock, *TPN, LI, SafetyInfo, MSSAU);
1523   return New;
1524 }
1525 
1526 static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo) {
1527   BasicBlock *BB = PN->getParent();
1528   if (!BB->canSplitPredecessors())
1529     return false;
1530   // It's not impossible to split EHPad blocks, but if BlockColors already exist
1531   // it require updating BlockColors for all offspring blocks accordingly. By
1532   // skipping such corner case, we can make updating BlockColors after splitting
1533   // predecessor fairly simple.
1534   if (!SafetyInfo->getBlockColors().empty() && BB->getFirstNonPHI()->isEHPad())
1535     return false;
1536   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1537     BasicBlock *BBPred = *PI;
1538     if (isa<IndirectBrInst>(BBPred->getTerminator()))
1539       return false;
1540   }
1541   return true;
1542 }
1543 
1544 static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT,
1545                                         LoopInfo *LI, const Loop *CurLoop,
1546                                         LoopSafetyInfo *SafetyInfo,
1547                                         MemorySSAUpdater *MSSAU) {
1548 #ifndef NDEBUG
1549   SmallVector<BasicBlock *, 32> ExitBlocks;
1550   CurLoop->getUniqueExitBlocks(ExitBlocks);
1551   SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
1552                                              ExitBlocks.end());
1553 #endif
1554   BasicBlock *ExitBB = PN->getParent();
1555   assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block.");
1556 
1557   // Split predecessors of the loop exit to make instructions in the loop are
1558   // exposed to exit blocks through trivially replaceable PHIs while keeping the
1559   // loop in the canonical form where each predecessor of each exit block should
1560   // be contained within the loop. For example, this will convert the loop below
1561   // from
1562   //
1563   // LB1:
1564   //   %v1 =
1565   //   br %LE, %LB2
1566   // LB2:
1567   //   %v2 =
1568   //   br %LE, %LB1
1569   // LE:
1570   //   %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replaceable
1571   //
1572   // to
1573   //
1574   // LB1:
1575   //   %v1 =
1576   //   br %LE.split, %LB2
1577   // LB2:
1578   //   %v2 =
1579   //   br %LE.split2, %LB1
1580   // LE.split:
1581   //   %p1 = phi [%v1, %LB1]  <-- trivially replaceable
1582   //   br %LE
1583   // LE.split2:
1584   //   %p2 = phi [%v2, %LB2]  <-- trivially replaceable
1585   //   br %LE
1586   // LE:
1587   //   %p = phi [%p1, %LE.split], [%p2, %LE.split2]
1588   //
1589   const auto &BlockColors = SafetyInfo->getBlockColors();
1590   SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB));
1591   while (!PredBBs.empty()) {
1592     BasicBlock *PredBB = *PredBBs.begin();
1593     assert(CurLoop->contains(PredBB) &&
1594            "Expect all predecessors are in the loop");
1595     if (PN->getBasicBlockIndex(PredBB) >= 0) {
1596       BasicBlock *NewPred = SplitBlockPredecessors(
1597           ExitBB, PredBB, ".split.loop.exit", DT, LI, MSSAU, true);
1598       // Since we do not allow splitting EH-block with BlockColors in
1599       // canSplitPredecessors(), we can simply assign predecessor's color to
1600       // the new block.
1601       if (!BlockColors.empty())
1602         // Grab a reference to the ColorVector to be inserted before getting the
1603         // reference to the vector we are copying because inserting the new
1604         // element in BlockColors might cause the map to be reallocated.
1605         SafetyInfo->copyColors(NewPred, PredBB);
1606     }
1607     PredBBs.remove(PredBB);
1608   }
1609 }
1610 
1611 /// When an instruction is found to only be used outside of the loop, this
1612 /// function moves it to the exit blocks and patches up SSA form as needed.
1613 /// This method is guaranteed to remove the original instruction from its
1614 /// position, and may either delete it or move it to outside of the loop.
1615 ///
1616 static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
1617                  const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo,
1618                  MemorySSAUpdater *MSSAU, OptimizationRemarkEmitter *ORE) {
1619   LLVM_DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
1620   ORE->emit([&]() {
1621     return OptimizationRemark(DEBUG_TYPE, "InstSunk", &I)
1622            << "sinking " << ore::NV("Inst", &I);
1623   });
1624   bool Changed = false;
1625   if (isa<LoadInst>(I))
1626     ++NumMovedLoads;
1627   else if (isa<CallInst>(I))
1628     ++NumMovedCalls;
1629   ++NumSunk;
1630 
1631   // Iterate over users to be ready for actual sinking. Replace users via
1632   // unreachable blocks with undef and make all user PHIs trivially replaceable.
1633   SmallPtrSet<Instruction *, 8> VisitedUsers;
1634   for (Value::user_iterator UI = I.user_begin(), UE = I.user_end(); UI != UE;) {
1635     auto *User = cast<Instruction>(*UI);
1636     Use &U = UI.getUse();
1637     ++UI;
1638 
1639     if (VisitedUsers.count(User) || CurLoop->contains(User))
1640       continue;
1641 
1642     if (!DT->isReachableFromEntry(User->getParent())) {
1643       U = UndefValue::get(I.getType());
1644       Changed = true;
1645       continue;
1646     }
1647 
1648     // The user must be a PHI node.
1649     PHINode *PN = cast<PHINode>(User);
1650 
1651     // Surprisingly, instructions can be used outside of loops without any
1652     // exits.  This can only happen in PHI nodes if the incoming block is
1653     // unreachable.
1654     BasicBlock *BB = PN->getIncomingBlock(U);
1655     if (!DT->isReachableFromEntry(BB)) {
1656       U = UndefValue::get(I.getType());
1657       Changed = true;
1658       continue;
1659     }
1660 
1661     VisitedUsers.insert(PN);
1662     if (isTriviallyReplaceablePHI(*PN, I))
1663       continue;
1664 
1665     if (!canSplitPredecessors(PN, SafetyInfo))
1666       return Changed;
1667 
1668     // Split predecessors of the PHI so that we can make users trivially
1669     // replaceable.
1670     splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop, SafetyInfo, MSSAU);
1671 
1672     // Should rebuild the iterators, as they may be invalidated by
1673     // splitPredecessorsOfLoopExit().
1674     UI = I.user_begin();
1675     UE = I.user_end();
1676   }
1677 
1678   if (VisitedUsers.empty())
1679     return Changed;
1680 
1681 #ifndef NDEBUG
1682   SmallVector<BasicBlock *, 32> ExitBlocks;
1683   CurLoop->getUniqueExitBlocks(ExitBlocks);
1684   SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
1685                                              ExitBlocks.end());
1686 #endif
1687 
1688   // Clones of this instruction. Don't create more than one per exit block!
1689   SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
1690 
1691   // If this instruction is only used outside of the loop, then all users are
1692   // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
1693   // the instruction.
1694   SmallSetVector<User*, 8> Users(I.user_begin(), I.user_end());
1695   for (auto *UI : Users) {
1696     auto *User = cast<Instruction>(UI);
1697 
1698     if (CurLoop->contains(User))
1699       continue;
1700 
1701     PHINode *PN = cast<PHINode>(User);
1702     assert(ExitBlockSet.count(PN->getParent()) &&
1703            "The LCSSA PHI is not in an exit block!");
1704     // The PHI must be trivially replaceable.
1705     Instruction *New = sinkThroughTriviallyReplaceablePHI(
1706         PN, &I, LI, SunkCopies, SafetyInfo, CurLoop, MSSAU);
1707     PN->replaceAllUsesWith(New);
1708     eraseInstruction(*PN, *SafetyInfo, nullptr, nullptr);
1709     Changed = true;
1710   }
1711   return Changed;
1712 }
1713 
1714 /// When an instruction is found to only use loop invariant operands that
1715 /// is safe to hoist, this instruction is called to do the dirty work.
1716 ///
1717 static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
1718                   BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo,
1719                   MemorySSAUpdater *MSSAU, ScalarEvolution *SE,
1720                   OptimizationRemarkEmitter *ORE) {
1721   LLVM_DEBUG(dbgs() << "LICM hoisting to " << Dest->getName() << ": " << I
1722                     << "\n");
1723   ORE->emit([&]() {
1724     return OptimizationRemark(DEBUG_TYPE, "Hoisted", &I) << "hoisting "
1725                                                          << ore::NV("Inst", &I);
1726   });
1727 
1728   // Metadata can be dependent on conditions we are hoisting above.
1729   // Conservatively strip all metadata on the instruction unless we were
1730   // guaranteed to execute I if we entered the loop, in which case the metadata
1731   // is valid in the loop preheader.
1732   if (I.hasMetadataOtherThanDebugLoc() &&
1733       // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
1734       // time in isGuaranteedToExecute if we don't actually have anything to
1735       // drop.  It is a compile time optimization, not required for correctness.
1736       !SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop))
1737     I.dropUnknownNonDebugMetadata();
1738 
1739   if (isa<PHINode>(I))
1740     // Move the new node to the end of the phi list in the destination block.
1741     moveInstructionBefore(I, *Dest->getFirstNonPHI(), *SafetyInfo, MSSAU, SE);
1742   else
1743     // Move the new node to the destination block, before its terminator.
1744     moveInstructionBefore(I, *Dest->getTerminator(), *SafetyInfo, MSSAU, SE);
1745 
1746   // Apply line 0 debug locations when we are moving instructions to different
1747   // basic blocks because we want to avoid jumpy line tables.
1748   if (const DebugLoc &DL = I.getDebugLoc())
1749     I.setDebugLoc(DebugLoc::get(0, 0, DL.getScope(), DL.getInlinedAt()));
1750 
1751   if (isa<LoadInst>(I))
1752     ++NumMovedLoads;
1753   else if (isa<CallInst>(I))
1754     ++NumMovedCalls;
1755   ++NumHoisted;
1756 }
1757 
1758 /// Only sink or hoist an instruction if it is not a trapping instruction,
1759 /// or if the instruction is known not to trap when moved to the preheader.
1760 /// or if it is a trapping instruction and is guaranteed to execute.
1761 static bool isSafeToExecuteUnconditionally(Instruction &Inst,
1762                                            const DominatorTree *DT,
1763                                            const Loop *CurLoop,
1764                                            const LoopSafetyInfo *SafetyInfo,
1765                                            OptimizationRemarkEmitter *ORE,
1766                                            const Instruction *CtxI) {
1767   if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT))
1768     return true;
1769 
1770   bool GuaranteedToExecute =
1771       SafetyInfo->isGuaranteedToExecute(Inst, DT, CurLoop);
1772 
1773   if (!GuaranteedToExecute) {
1774     auto *LI = dyn_cast<LoadInst>(&Inst);
1775     if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand()))
1776       ORE->emit([&]() {
1777         return OptimizationRemarkMissed(
1778                    DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI)
1779                << "failed to hoist load with loop-invariant address "
1780                   "because load is conditionally executed";
1781       });
1782   }
1783 
1784   return GuaranteedToExecute;
1785 }
1786 
1787 namespace {
1788 class LoopPromoter : public LoadAndStorePromoter {
1789   Value *SomePtr; // Designated pointer to store to.
1790   const SmallSetVector<Value *, 8> &PointerMustAliases;
1791   SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
1792   SmallVectorImpl<Instruction *> &LoopInsertPts;
1793   SmallVectorImpl<MemoryAccess *> &MSSAInsertPts;
1794   PredIteratorCache &PredCache;
1795   AliasSetTracker &AST;
1796   MemorySSAUpdater *MSSAU;
1797   LoopInfo &LI;
1798   DebugLoc DL;
1799   int Alignment;
1800   bool UnorderedAtomic;
1801   AAMDNodes AATags;
1802   ICFLoopSafetyInfo &SafetyInfo;
1803 
1804   Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
1805     if (Instruction *I = dyn_cast<Instruction>(V))
1806       if (Loop *L = LI.getLoopFor(I->getParent()))
1807         if (!L->contains(BB)) {
1808           // We need to create an LCSSA PHI node for the incoming value and
1809           // store that.
1810           PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
1811                                         I->getName() + ".lcssa", &BB->front());
1812           for (BasicBlock *Pred : PredCache.get(BB))
1813             PN->addIncoming(I, Pred);
1814           return PN;
1815         }
1816     return V;
1817   }
1818 
1819 public:
1820   LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
1821                const SmallSetVector<Value *, 8> &PMA,
1822                SmallVectorImpl<BasicBlock *> &LEB,
1823                SmallVectorImpl<Instruction *> &LIP,
1824                SmallVectorImpl<MemoryAccess *> &MSSAIP, PredIteratorCache &PIC,
1825                AliasSetTracker &ast, MemorySSAUpdater *MSSAU, LoopInfo &li,
1826                DebugLoc dl, int alignment, bool UnorderedAtomic,
1827                const AAMDNodes &AATags, ICFLoopSafetyInfo &SafetyInfo)
1828       : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
1829         LoopExitBlocks(LEB), LoopInsertPts(LIP), MSSAInsertPts(MSSAIP),
1830         PredCache(PIC), AST(ast), MSSAU(MSSAU), LI(li), DL(std::move(dl)),
1831         Alignment(alignment), UnorderedAtomic(UnorderedAtomic), AATags(AATags),
1832         SafetyInfo(SafetyInfo) {}
1833 
1834   bool isInstInList(Instruction *I,
1835                     const SmallVectorImpl<Instruction *> &) const override {
1836     Value *Ptr;
1837     if (LoadInst *LI = dyn_cast<LoadInst>(I))
1838       Ptr = LI->getOperand(0);
1839     else
1840       Ptr = cast<StoreInst>(I)->getPointerOperand();
1841     return PointerMustAliases.count(Ptr);
1842   }
1843 
1844   void doExtraRewritesBeforeFinalDeletion() override {
1845     // Insert stores after in the loop exit blocks.  Each exit block gets a
1846     // store of the live-out values that feed them.  Since we've already told
1847     // the SSA updater about the defs in the loop and the preheader
1848     // definition, it is all set and we can start using it.
1849     for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
1850       BasicBlock *ExitBlock = LoopExitBlocks[i];
1851       Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
1852       LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
1853       Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
1854       Instruction *InsertPos = LoopInsertPts[i];
1855       StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
1856       if (UnorderedAtomic)
1857         NewSI->setOrdering(AtomicOrdering::Unordered);
1858       NewSI->setAlignment(MaybeAlign(Alignment));
1859       NewSI->setDebugLoc(DL);
1860       if (AATags)
1861         NewSI->setAAMetadata(AATags);
1862 
1863       if (MSSAU) {
1864         MemoryAccess *MSSAInsertPoint = MSSAInsertPts[i];
1865         MemoryAccess *NewMemAcc;
1866         if (!MSSAInsertPoint) {
1867           NewMemAcc = MSSAU->createMemoryAccessInBB(
1868               NewSI, nullptr, NewSI->getParent(), MemorySSA::Beginning);
1869         } else {
1870           NewMemAcc =
1871               MSSAU->createMemoryAccessAfter(NewSI, nullptr, MSSAInsertPoint);
1872         }
1873         MSSAInsertPts[i] = NewMemAcc;
1874         MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);
1875         // FIXME: true for safety, false may still be correct.
1876       }
1877     }
1878   }
1879 
1880   void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
1881     // Update alias analysis.
1882     AST.copyValue(LI, V);
1883   }
1884   void instructionDeleted(Instruction *I) const override {
1885     SafetyInfo.removeInstruction(I);
1886     AST.deleteValue(I);
1887     if (MSSAU)
1888       MSSAU->removeMemoryAccess(I);
1889   }
1890 };
1891 
1892 
1893 /// Return true iff we can prove that a caller of this function can not inspect
1894 /// the contents of the provided object in a well defined program.
1895 bool isKnownNonEscaping(Value *Object, const TargetLibraryInfo *TLI) {
1896   if (isa<AllocaInst>(Object))
1897     // Since the alloca goes out of scope, we know the caller can't retain a
1898     // reference to it and be well defined.  Thus, we don't need to check for
1899     // capture.
1900     return true;
1901 
1902   // For all other objects we need to know that the caller can't possibly
1903   // have gotten a reference to the object.  There are two components of
1904   // that:
1905   //   1) Object can't be escaped by this function.  This is what
1906   //      PointerMayBeCaptured checks.
1907   //   2) Object can't have been captured at definition site.  For this, we
1908   //      need to know the return value is noalias.  At the moment, we use a
1909   //      weaker condition and handle only AllocLikeFunctions (which are
1910   //      known to be noalias).  TODO
1911   return isAllocLikeFn(Object, TLI) &&
1912     !PointerMayBeCaptured(Object, true, true);
1913 }
1914 
1915 } // namespace
1916 
1917 /// Try to promote memory values to scalars by sinking stores out of the
1918 /// loop and moving loads to before the loop.  We do this by looping over
1919 /// the stores in the loop, looking for stores to Must pointers which are
1920 /// loop invariant.
1921 ///
1922 bool llvm::promoteLoopAccessesToScalars(
1923     const SmallSetVector<Value *, 8> &PointerMustAliases,
1924     SmallVectorImpl<BasicBlock *> &ExitBlocks,
1925     SmallVectorImpl<Instruction *> &InsertPts,
1926     SmallVectorImpl<MemoryAccess *> &MSSAInsertPts, PredIteratorCache &PIC,
1927     LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
1928     Loop *CurLoop, AliasSetTracker *CurAST, MemorySSAUpdater *MSSAU,
1929     ICFLoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE) {
1930   // Verify inputs.
1931   assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
1932          CurAST != nullptr && SafetyInfo != nullptr &&
1933          "Unexpected Input to promoteLoopAccessesToScalars");
1934 
1935   Value *SomePtr = *PointerMustAliases.begin();
1936   BasicBlock *Preheader = CurLoop->getLoopPreheader();
1937 
1938   // It is not safe to promote a load/store from the loop if the load/store is
1939   // conditional.  For example, turning:
1940   //
1941   //    for () { if (c) *P += 1; }
1942   //
1943   // into:
1944   //
1945   //    tmp = *P;  for () { if (c) tmp +=1; } *P = tmp;
1946   //
1947   // is not safe, because *P may only be valid to access if 'c' is true.
1948   //
1949   // The safety property divides into two parts:
1950   // p1) The memory may not be dereferenceable on entry to the loop.  In this
1951   //    case, we can't insert the required load in the preheader.
1952   // p2) The memory model does not allow us to insert a store along any dynamic
1953   //    path which did not originally have one.
1954   //
1955   // If at least one store is guaranteed to execute, both properties are
1956   // satisfied, and promotion is legal.
1957   //
1958   // This, however, is not a necessary condition. Even if no store/load is
1959   // guaranteed to execute, we can still establish these properties.
1960   // We can establish (p1) by proving that hoisting the load into the preheader
1961   // is safe (i.e. proving dereferenceability on all paths through the loop). We
1962   // can use any access within the alias set to prove dereferenceability,
1963   // since they're all must alias.
1964   //
1965   // There are two ways establish (p2):
1966   // a) Prove the location is thread-local. In this case the memory model
1967   // requirement does not apply, and stores are safe to insert.
1968   // b) Prove a store dominates every exit block. In this case, if an exit
1969   // blocks is reached, the original dynamic path would have taken us through
1970   // the store, so inserting a store into the exit block is safe. Note that this
1971   // is different from the store being guaranteed to execute. For instance,
1972   // if an exception is thrown on the first iteration of the loop, the original
1973   // store is never executed, but the exit blocks are not executed either.
1974 
1975   bool DereferenceableInPH = false;
1976   bool SafeToInsertStore = false;
1977 
1978   SmallVector<Instruction *, 64> LoopUses;
1979 
1980   // We start with an alignment of one and try to find instructions that allow
1981   // us to prove better alignment.
1982   unsigned Alignment = 1;
1983   // Keep track of which types of access we see
1984   bool SawUnorderedAtomic = false;
1985   bool SawNotAtomic = false;
1986   AAMDNodes AATags;
1987 
1988   const DataLayout &MDL = Preheader->getModule()->getDataLayout();
1989 
1990   bool IsKnownThreadLocalObject = false;
1991   if (SafetyInfo->anyBlockMayThrow()) {
1992     // If a loop can throw, we have to insert a store along each unwind edge.
1993     // That said, we can't actually make the unwind edge explicit. Therefore,
1994     // we have to prove that the store is dead along the unwind edge.  We do
1995     // this by proving that the caller can't have a reference to the object
1996     // after return and thus can't possibly load from the object.
1997     Value *Object = GetUnderlyingObject(SomePtr, MDL);
1998     if (!isKnownNonEscaping(Object, TLI))
1999       return false;
2000     // Subtlety: Alloca's aren't visible to callers, but *are* potentially
2001     // visible to other threads if captured and used during their lifetimes.
2002     IsKnownThreadLocalObject = !isa<AllocaInst>(Object);
2003   }
2004 
2005   // Check that all of the pointers in the alias set have the same type.  We
2006   // cannot (yet) promote a memory location that is loaded and stored in
2007   // different sizes.  While we are at it, collect alignment and AA info.
2008   for (Value *ASIV : PointerMustAliases) {
2009     // Check that all of the pointers in the alias set have the same type.  We
2010     // cannot (yet) promote a memory location that is loaded and stored in
2011     // different sizes.
2012     if (SomePtr->getType() != ASIV->getType())
2013       return false;
2014 
2015     for (User *U : ASIV->users()) {
2016       // Ignore instructions that are outside the loop.
2017       Instruction *UI = dyn_cast<Instruction>(U);
2018       if (!UI || !CurLoop->contains(UI))
2019         continue;
2020 
2021       // If there is an non-load/store instruction in the loop, we can't promote
2022       // it.
2023       if (LoadInst *Load = dyn_cast<LoadInst>(UI)) {
2024         if (!Load->isUnordered())
2025           return false;
2026 
2027         SawUnorderedAtomic |= Load->isAtomic();
2028         SawNotAtomic |= !Load->isAtomic();
2029 
2030         unsigned InstAlignment = Load->getAlignment();
2031         if (!InstAlignment)
2032           InstAlignment =
2033               MDL.getABITypeAlignment(Load->getType());
2034 
2035         // Note that proving a load safe to speculate requires proving
2036         // sufficient alignment at the target location.  Proving it guaranteed
2037         // to execute does as well.  Thus we can increase our guaranteed
2038         // alignment as well.
2039         if (!DereferenceableInPH || (InstAlignment > Alignment))
2040           if (isSafeToExecuteUnconditionally(*Load, DT, CurLoop, SafetyInfo,
2041                                              ORE, Preheader->getTerminator())) {
2042             DereferenceableInPH = true;
2043             Alignment = std::max(Alignment, InstAlignment);
2044           }
2045       } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
2046         // Stores *of* the pointer are not interesting, only stores *to* the
2047         // pointer.
2048         if (UI->getOperand(1) != ASIV)
2049           continue;
2050         if (!Store->isUnordered())
2051           return false;
2052 
2053         SawUnorderedAtomic |= Store->isAtomic();
2054         SawNotAtomic |= !Store->isAtomic();
2055 
2056         // If the store is guaranteed to execute, both properties are satisfied.
2057         // We may want to check if a store is guaranteed to execute even if we
2058         // already know that promotion is safe, since it may have higher
2059         // alignment than any other guaranteed stores, in which case we can
2060         // raise the alignment on the promoted store.
2061         unsigned InstAlignment = Store->getAlignment();
2062         if (!InstAlignment)
2063           InstAlignment =
2064               MDL.getABITypeAlignment(Store->getValueOperand()->getType());
2065 
2066         if (!DereferenceableInPH || !SafeToInsertStore ||
2067             (InstAlignment > Alignment)) {
2068           if (SafetyInfo->isGuaranteedToExecute(*UI, DT, CurLoop)) {
2069             DereferenceableInPH = true;
2070             SafeToInsertStore = true;
2071             Alignment = std::max(Alignment, InstAlignment);
2072           }
2073         }
2074 
2075         // If a store dominates all exit blocks, it is safe to sink.
2076         // As explained above, if an exit block was executed, a dominating
2077         // store must have been executed at least once, so we are not
2078         // introducing stores on paths that did not have them.
2079         // Note that this only looks at explicit exit blocks. If we ever
2080         // start sinking stores into unwind edges (see above), this will break.
2081         if (!SafeToInsertStore)
2082           SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) {
2083             return DT->dominates(Store->getParent(), Exit);
2084           });
2085 
2086         // If the store is not guaranteed to execute, we may still get
2087         // deref info through it.
2088         if (!DereferenceableInPH) {
2089           DereferenceableInPH = isDereferenceableAndAlignedPointer(
2090               Store->getPointerOperand(), Store->getValueOperand()->getType(),
2091               MaybeAlign(Store->getAlignment()), MDL,
2092               Preheader->getTerminator(), DT);
2093         }
2094       } else
2095         return false; // Not a load or store.
2096 
2097       // Merge the AA tags.
2098       if (LoopUses.empty()) {
2099         // On the first load/store, just take its AA tags.
2100         UI->getAAMetadata(AATags);
2101       } else if (AATags) {
2102         UI->getAAMetadata(AATags, /* Merge = */ true);
2103       }
2104 
2105       LoopUses.push_back(UI);
2106     }
2107   }
2108 
2109   // If we found both an unordered atomic instruction and a non-atomic memory
2110   // access, bail.  We can't blindly promote non-atomic to atomic since we
2111   // might not be able to lower the result.  We can't downgrade since that
2112   // would violate memory model.  Also, align 0 is an error for atomics.
2113   if (SawUnorderedAtomic && SawNotAtomic)
2114     return false;
2115 
2116   // If we're inserting an atomic load in the preheader, we must be able to
2117   // lower it.  We're only guaranteed to be able to lower naturally aligned
2118   // atomics.
2119   auto *SomePtrElemType = SomePtr->getType()->getPointerElementType();
2120   if (SawUnorderedAtomic &&
2121       Alignment < MDL.getTypeStoreSize(SomePtrElemType))
2122     return false;
2123 
2124   // If we couldn't prove we can hoist the load, bail.
2125   if (!DereferenceableInPH)
2126     return false;
2127 
2128   // We know we can hoist the load, but don't have a guaranteed store.
2129   // Check whether the location is thread-local. If it is, then we can insert
2130   // stores along paths which originally didn't have them without violating the
2131   // memory model.
2132   if (!SafeToInsertStore) {
2133     if (IsKnownThreadLocalObject)
2134       SafeToInsertStore = true;
2135     else {
2136       Value *Object = GetUnderlyingObject(SomePtr, MDL);
2137       SafeToInsertStore =
2138           (isAllocLikeFn(Object, TLI) || isa<AllocaInst>(Object)) &&
2139           !PointerMayBeCaptured(Object, true, true);
2140     }
2141   }
2142 
2143   // If we've still failed to prove we can sink the store, give up.
2144   if (!SafeToInsertStore)
2145     return false;
2146 
2147   // Otherwise, this is safe to promote, lets do it!
2148   LLVM_DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr
2149                     << '\n');
2150   ORE->emit([&]() {
2151     return OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar",
2152                               LoopUses[0])
2153            << "Moving accesses to memory location out of the loop";
2154   });
2155   ++NumPromoted;
2156 
2157   // Grab a debug location for the inserted loads/stores; given that the
2158   // inserted loads/stores have little relation to the original loads/stores,
2159   // this code just arbitrarily picks a location from one, since any debug
2160   // location is better than none.
2161   DebugLoc DL = LoopUses[0]->getDebugLoc();
2162 
2163   // We use the SSAUpdater interface to insert phi nodes as required.
2164   SmallVector<PHINode *, 16> NewPHIs;
2165   SSAUpdater SSA(&NewPHIs);
2166   LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
2167                         InsertPts, MSSAInsertPts, PIC, *CurAST, MSSAU, *LI, DL,
2168                         Alignment, SawUnorderedAtomic, AATags, *SafetyInfo);
2169 
2170   // Set up the preheader to have a definition of the value.  It is the live-out
2171   // value from the preheader that uses in the loop will use.
2172   LoadInst *PreheaderLoad = new LoadInst(
2173       SomePtr->getType()->getPointerElementType(), SomePtr,
2174       SomePtr->getName() + ".promoted", Preheader->getTerminator());
2175   if (SawUnorderedAtomic)
2176     PreheaderLoad->setOrdering(AtomicOrdering::Unordered);
2177   PreheaderLoad->setAlignment(MaybeAlign(Alignment));
2178   PreheaderLoad->setDebugLoc(DL);
2179   if (AATags)
2180     PreheaderLoad->setAAMetadata(AATags);
2181   SSA.AddAvailableValue(Preheader, PreheaderLoad);
2182 
2183   if (MSSAU) {
2184     MemoryAccess *PreheaderLoadMemoryAccess = MSSAU->createMemoryAccessInBB(
2185         PreheaderLoad, nullptr, PreheaderLoad->getParent(), MemorySSA::End);
2186     MemoryUse *NewMemUse = cast<MemoryUse>(PreheaderLoadMemoryAccess);
2187     MSSAU->insertUse(NewMemUse, /*RenameUses=*/true);
2188   }
2189 
2190   if (MSSAU && VerifyMemorySSA)
2191     MSSAU->getMemorySSA()->verifyMemorySSA();
2192   // Rewrite all the loads in the loop and remember all the definitions from
2193   // stores in the loop.
2194   Promoter.run(LoopUses);
2195 
2196   if (MSSAU && VerifyMemorySSA)
2197     MSSAU->getMemorySSA()->verifyMemorySSA();
2198   // If the SSAUpdater didn't use the load in the preheader, just zap it now.
2199   if (PreheaderLoad->use_empty())
2200     eraseInstruction(*PreheaderLoad, *SafetyInfo, CurAST, MSSAU);
2201 
2202   return true;
2203 }
2204 
2205 /// Returns an owning pointer to an alias set which incorporates aliasing info
2206 /// from L and all subloops of L.
2207 /// FIXME: In new pass manager, there is no helper function to handle loop
2208 /// analysis such as cloneBasicBlockAnalysis, so the AST needs to be recomputed
2209 /// from scratch for every loop. Hook up with the helper functions when
2210 /// available in the new pass manager to avoid redundant computation.
2211 std::unique_ptr<AliasSetTracker>
2212 LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
2213                                                  AliasAnalysis *AA) {
2214   std::unique_ptr<AliasSetTracker> CurAST;
2215   SmallVector<Loop *, 4> RecomputeLoops;
2216   for (Loop *InnerL : L->getSubLoops()) {
2217     auto MapI = LoopToAliasSetMap.find(InnerL);
2218     // If the AST for this inner loop is missing it may have been merged into
2219     // some other loop's AST and then that loop unrolled, and so we need to
2220     // recompute it.
2221     if (MapI == LoopToAliasSetMap.end()) {
2222       RecomputeLoops.push_back(InnerL);
2223       continue;
2224     }
2225     std::unique_ptr<AliasSetTracker> InnerAST = std::move(MapI->second);
2226 
2227     if (CurAST) {
2228       // What if InnerLoop was modified by other passes ?
2229       // Once we've incorporated the inner loop's AST into ours, we don't need
2230       // the subloop's anymore.
2231       CurAST->add(*InnerAST);
2232     } else {
2233       CurAST = std::move(InnerAST);
2234     }
2235     LoopToAliasSetMap.erase(MapI);
2236   }
2237   if (!CurAST)
2238     CurAST = std::make_unique<AliasSetTracker>(*AA);
2239 
2240   // Add everything from the sub loops that are no longer directly available.
2241   for (Loop *InnerL : RecomputeLoops)
2242     for (BasicBlock *BB : InnerL->blocks())
2243       CurAST->add(*BB);
2244 
2245   // And merge in this loop (without anything from inner loops).
2246   for (BasicBlock *BB : L->blocks())
2247     if (LI->getLoopFor(BB) == L)
2248       CurAST->add(*BB);
2249 
2250   return CurAST;
2251 }
2252 
2253 std::unique_ptr<AliasSetTracker>
2254 LoopInvariantCodeMotion::collectAliasInfoForLoopWithMSSA(
2255     Loop *L, AliasAnalysis *AA, MemorySSAUpdater *MSSAU) {
2256   auto *MSSA = MSSAU->getMemorySSA();
2257   auto CurAST = std::make_unique<AliasSetTracker>(*AA, MSSA, L);
2258   CurAST->addAllInstructionsInLoopUsingMSSA();
2259   return CurAST;
2260 }
2261 
2262 /// Simple analysis hook. Clone alias set info.
2263 ///
2264 void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
2265                                              Loop *L) {
2266   auto ASTIt = LICM.getLoopToAliasSetMap().find(L);
2267   if (ASTIt == LICM.getLoopToAliasSetMap().end())
2268     return;
2269 
2270   ASTIt->second->copyValue(From, To);
2271 }
2272 
2273 /// Simple Analysis hook. Delete value V from alias set
2274 ///
2275 void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) {
2276   auto ASTIt = LICM.getLoopToAliasSetMap().find(L);
2277   if (ASTIt == LICM.getLoopToAliasSetMap().end())
2278     return;
2279 
2280   ASTIt->second->deleteValue(V);
2281 }
2282 
2283 /// Simple Analysis hook. Delete value L from alias set map.
2284 ///
2285 void LegacyLICMPass::deleteAnalysisLoop(Loop *L) {
2286   if (!LICM.getLoopToAliasSetMap().count(L))
2287     return;
2288 
2289   LICM.getLoopToAliasSetMap().erase(L);
2290 }
2291 
2292 static bool pointerInvalidatedByLoop(MemoryLocation MemLoc,
2293                                      AliasSetTracker *CurAST, Loop *CurLoop,
2294                                      AliasAnalysis *AA) {
2295   // First check to see if any of the basic blocks in CurLoop invalidate *V.
2296   bool isInvalidatedAccordingToAST = CurAST->getAliasSetFor(MemLoc).isMod();
2297 
2298   if (!isInvalidatedAccordingToAST || !LICMN2Theshold)
2299     return isInvalidatedAccordingToAST;
2300 
2301   // Check with a diagnostic analysis if we can refine the information above.
2302   // This is to identify the limitations of using the AST.
2303   // The alias set mechanism used by LICM has a major weakness in that it
2304   // combines all things which may alias into a single set *before* asking
2305   // modref questions. As a result, a single readonly call within a loop will
2306   // collapse all loads and stores into a single alias set and report
2307   // invalidation if the loop contains any store. For example, readonly calls
2308   // with deopt states have this form and create a general alias set with all
2309   // loads and stores.  In order to get any LICM in loops containing possible
2310   // deopt states we need a more precise invalidation of checking the mod ref
2311   // info of each instruction within the loop and LI. This has a complexity of
2312   // O(N^2), so currently, it is used only as a diagnostic tool since the
2313   // default value of LICMN2Threshold is zero.
2314 
2315   // Don't look at nested loops.
2316   if (CurLoop->begin() != CurLoop->end())
2317     return true;
2318 
2319   int N = 0;
2320   for (BasicBlock *BB : CurLoop->getBlocks())
2321     for (Instruction &I : *BB) {
2322       if (N >= LICMN2Theshold) {
2323         LLVM_DEBUG(dbgs() << "Alasing N2 threshold exhausted for "
2324                           << *(MemLoc.Ptr) << "\n");
2325         return true;
2326       }
2327       N++;
2328       auto Res = AA->getModRefInfo(&I, MemLoc);
2329       if (isModSet(Res)) {
2330         LLVM_DEBUG(dbgs() << "Aliasing failed on " << I << " for "
2331                           << *(MemLoc.Ptr) << "\n");
2332         return true;
2333       }
2334     }
2335   LLVM_DEBUG(dbgs() << "Aliasing okay for " << *(MemLoc.Ptr) << "\n");
2336   return false;
2337 }
2338 
2339 static bool pointerInvalidatedByLoopWithMSSA(MemorySSA *MSSA, MemoryUse *MU,
2340                                              Loop *CurLoop,
2341                                              SinkAndHoistLICMFlags &Flags) {
2342   // For hoisting, use the walker to determine safety
2343   if (!Flags.IsSink) {
2344     MemoryAccess *Source;
2345     // See declaration of SetLicmMssaOptCap for usage details.
2346     if (Flags.LicmMssaOptCounter >= Flags.LicmMssaOptCap)
2347       Source = MU->getDefiningAccess();
2348     else {
2349       Source = MSSA->getSkipSelfWalker()->getClobberingMemoryAccess(MU);
2350       Flags.LicmMssaOptCounter++;
2351     }
2352     return !MSSA->isLiveOnEntryDef(Source) &&
2353            CurLoop->contains(Source->getBlock());
2354   }
2355 
2356   // For sinking, we'd need to check all Defs below this use. The getClobbering
2357   // call will look on the backedge of the loop, but will check aliasing with
2358   // the instructions on the previous iteration.
2359   // For example:
2360   // for (i ... )
2361   //   load a[i] ( Use (LoE)
2362   //   store a[i] ( 1 = Def (2), with 2 = Phi for the loop.
2363   //   i++;
2364   // The load sees no clobbering inside the loop, as the backedge alias check
2365   // does phi translation, and will check aliasing against store a[i-1].
2366   // However sinking the load outside the loop, below the store is incorrect.
2367 
2368   // For now, only sink if there are no Defs in the loop, and the existing ones
2369   // precede the use and are in the same block.
2370   // FIXME: Increase precision: Safe to sink if Use post dominates the Def;
2371   // needs PostDominatorTreeAnalysis.
2372   // FIXME: More precise: no Defs that alias this Use.
2373   if (Flags.NoOfMemAccTooLarge)
2374     return true;
2375   for (auto *BB : CurLoop->getBlocks())
2376     if (auto *Accesses = MSSA->getBlockDefs(BB))
2377       for (const auto &MA : *Accesses)
2378         if (const auto *MD = dyn_cast<MemoryDef>(&MA))
2379           if (MU->getBlock() != MD->getBlock() ||
2380               !MSSA->locallyDominates(MD, MU))
2381             return true;
2382   return false;
2383 }
2384 
2385 /// Little predicate that returns true if the specified basic block is in
2386 /// a subloop of the current one, not the current one itself.
2387 ///
2388 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
2389   assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
2390   return LI->getLoopFor(BB) != CurLoop;
2391 }
2392