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