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