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