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