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