LLVM 24.0.0git
LICM.cpp
Go to the documentation of this file.
1//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass performs loop invariant code motion, attempting to remove as much
10// code from the body of a loop as possible. It does this by either hoisting
11// code into the preheader block, or by sinking code to the exit blocks if it is
12// safe. This pass also promotes must-aliased memory locations in the loop to
13// live in registers, thus hoisting and sinking "invariant" loads and stores.
14//
15// Hoisting operations out of loops is a canonicalization transform. It
16// enables and simplifies subsequent optimizations in the middle-end.
17// Rematerialization of hoisted instructions to reduce register pressure is the
18// responsibility of the back-end, which has more accurate information about
19// register pressure and also handles other optimizations than LICM that
20// increase live-ranges.
21//
22// This pass uses alias analysis for two purposes:
23//
24// 1. Moving loop invariant loads and calls out of loops. If we can determine
25// that a load or call inside of a loop never aliases anything stored to,
26// we can hoist it or sink it like any other instruction.
27// 2. Scalar Promotion of Memory - If there is a store instruction inside of
28// the loop, we try to move the store to happen AFTER the loop instead of
29// inside of the loop. This can only happen if a few conditions are true:
30// A. The pointer stored through is loop invariant
31// B. There are no stores or loads in the loop which _may_ alias the
32// pointer. There are no calls in the loop which mod/ref the pointer.
33// If these conditions are true, we can promote the loads and stores in the
34// loop of the pointer to use a temporary alloca'd variable. We then use
35// the SSAUpdater to construct the appropriate SSA form for the value.
36//
37//===----------------------------------------------------------------------===//
38
40#include "llvm/ADT/DenseMap.h"
42#include "llvm/ADT/Statistic.h"
50#include "llvm/Analysis/Loads.h"
64#include "llvm/IR/CFG.h"
65#include "llvm/IR/Constants.h"
66#include "llvm/IR/DataLayout.h"
69#include "llvm/IR/Dominators.h"
70#include "llvm/IR/IRBuilder.h"
73#include "llvm/IR/LLVMContext.h"
74#include "llvm/IR/Metadata.h"
75#include "llvm/IR/Module.h"
80#include "llvm/Support/Debug.h"
88#include <algorithm>
89#include <utility>
90using namespace llvm;
91
92namespace llvm {
93class LPMUpdater;
94} // namespace llvm
95
96#define DEBUG_TYPE "licm"
97
98STATISTIC(NumSunk, "Number of instructions sunk out of loop");
99STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
100STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
101STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
102STATISTIC(NumPromotionCandidates, "Number of promotion candidates");
103STATISTIC(NumLoadPromoted, "Number of load-only promotions");
104STATISTIC(NumLoadStorePromoted, "Number of load and store promotions");
105STATISTIC(NumMinMaxHoisted,
106 "Number of min/max expressions hoisted out of the loop");
107STATISTIC(NumGEPsHoisted,
108 "Number of geps reassociated and hoisted out of the loop");
109STATISTIC(NumAddSubHoisted, "Number of add/subtract expressions reassociated "
110 "and hoisted out of the loop");
111STATISTIC(NumFPAssociationsHoisted, "Number of invariant FP expressions "
112 "reassociated and hoisted out of the loop");
113STATISTIC(NumIntAssociationsHoisted,
114 "Number of invariant int expressions "
115 "reassociated and hoisted out of the loop");
116STATISTIC(NumBOAssociationsHoisted, "Number of invariant BinaryOp expressions "
117 "reassociated and hoisted out of the loop");
118
119/// Memory promotion is enabled by default.
120static cl::opt<bool>
121 DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false),
122 cl::desc("Disable memory promotion in LICM pass"));
123
125 "licm-max-num-uses-traversed", cl::Hidden, cl::init(8),
126 cl::desc("Max num uses visited for identifying load "
127 "invariance in loop using invariant start (default = 8)"));
128
130 "licm-max-num-fp-reassociations", cl::init(5U), cl::Hidden,
131 cl::desc(
132 "Set upper limit for the number of transformations performed "
133 "during a single round of hoisting the reassociated expressions."));
134
136 "licm-max-num-int-reassociations", cl::init(5U), cl::Hidden,
137 cl::desc(
138 "Set upper limit for the number of transformations performed "
139 "during a single round of hoisting the reassociated expressions."));
140
141// Experimental option to allow imprecision in LICM in pathological cases, in
142// exchange for faster compile. This is to be removed if MemorySSA starts to
143// address the same issue. LICM calls MemorySSAWalker's
144// getClobberingMemoryAccess, up to the value of the Cap, getting perfect
145// accuracy. Afterwards, LICM will call into MemorySSA's getDefiningAccess,
146// which may not be precise, since optimizeUses is capped. The result is
147// correct, but we may not get as "far up" as possible to get which access is
148// clobbering the one queried.
150 "licm-mssa-optimization-cap", cl::init(100), cl::Hidden,
151 cl::desc("Enable imprecision in LICM in pathological cases, in exchange "
152 "for faster compile. Caps the MemorySSA clobbering calls."));
153
154// Experimentally, memory promotion carries less importance than sinking and
155// hoisting. Limit when we do promotion when using MemorySSA, in order to save
156// compile time.
158 "licm-mssa-max-acc-promotion", cl::init(250), cl::Hidden,
159 cl::desc("[LICM & MemorySSA] When MSSA in LICM is disabled, this has no "
160 "effect. When MSSA in LICM is enabled, then this is the maximum "
161 "number of accesses allowed to be present in a loop in order to "
162 "enable memory promotion."));
163
164static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
165static bool isNotUsedOrFoldableInLoop(const Instruction &I, const Loop *CurLoop,
166 const LoopSafetyInfo *SafetyInfo,
168 bool &FoldableInLoop, bool LoopNestMode);
169static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
170 BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo,
173static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
174 const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo,
177 Instruction &Inst, const DominatorTree *DT, const TargetLibraryInfo *TLI,
178 const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo,
179 OptimizationRemarkEmitter *ORE, const Instruction *CtxI,
180 AssumptionCache *AC, bool AllowSpeculation);
182 AAResults *AA, Loop *CurLoop,
183 SinkAndHoistLICMFlags &Flags);
184static bool pointerInvalidatedByLoop(MemorySSA *MSSA, MemoryUse *MU,
185 Loop *CurLoop, Instruction &I,
187 bool InvariantGroup);
188static bool pointerInvalidatedByBlock(BasicBlock &BB, MemorySSA &MSSA,
189 MemoryUse &MU);
190/// Aggregates various functions for hoisting computations out of loop.
191static bool hoistArithmetics(Instruction &I, Loop &L,
192 ICFLoopSafetyInfo &SafetyInfo,
194 DominatorTree *DT);
195static bool hoistInsertPastInsert(InsertElementInst *Ins, Loop *CurLoop,
196 DominatorTree *DT, BasicBlock *HoistDest,
197 ICFLoopSafetyInfo *SafetyInfo,
201 Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI,
202 const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater &MSSAU);
203
204static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo,
205 MemorySSAUpdater &MSSAU);
206
208 ICFLoopSafetyInfo &SafetyInfo,
210
211static void foreachMemoryAccess(MemorySSA *MSSA, Loop *L,
212 function_ref<void(Instruction *)> Fn);
214 std::pair<SmallSetVector<Value *, 8>, bool>;
217 DominatorTree *DT, ICFLoopSafetyInfo *SafetyInfo,
218 Loop *L);
219
220namespace {
221struct LoopInvariantCodeMotion {
222 bool runOnLoop(Loop *L, AAResults *AA, LoopInfo *LI, DominatorTree *DT,
225 OptimizationRemarkEmitter *ORE, bool LoopNestMode = false);
226
227 LoopInvariantCodeMotion(unsigned LicmMssaOptCap,
228 unsigned LicmMssaNoAccForPromotionCap,
229 bool LicmAllowSpeculation)
230 : LicmMssaOptCap(LicmMssaOptCap),
231 LicmMssaNoAccForPromotionCap(LicmMssaNoAccForPromotionCap),
232 LicmAllowSpeculation(LicmAllowSpeculation) {}
233
234private:
235 unsigned LicmMssaOptCap;
236 unsigned LicmMssaNoAccForPromotionCap;
237 bool LicmAllowSpeculation;
238};
239
240struct LegacyLICMPass : public LoopPass {
241 static char ID; // Pass identification, replacement for typeid
242 LegacyLICMPass(
243 unsigned LicmMssaOptCap = SetLicmMssaOptCap,
244 unsigned LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap,
245 bool LicmAllowSpeculation = true)
246 : LoopPass(ID), LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
247 LicmAllowSpeculation) {
249 }
250
251 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
252 if (skipLoop(L))
253 return false;
254
255 LLVM_DEBUG(dbgs() << "Perform LICM on Loop with header at block "
256 << L->getHeader()->getNameOrAsOperand() << "\n");
257
258 Function *F = L->getHeader()->getParent();
259
260 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
261 MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
262 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
263 // pass. Function analyses need to be preserved across loop transformations
264 // but ORE cannot be preserved (see comment before the pass definition).
265 OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
266 return LICM.runOnLoop(
267 L, &getAnalysis<AAResultsWrapperPass>().getAAResults(),
268 &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
269 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
270 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F),
271 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(*F),
272 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(*F),
273 SE ? &SE->getSE() : nullptr, MSSA, &ORE);
274 }
275
276 /// This transformation requires natural loop information & requires that
277 /// loop preheaders be inserted into the CFG...
278 ///
279 void getAnalysisUsage(AnalysisUsage &AU) const override {
280 AU.addPreserved<DominatorTreeWrapperPass>();
281 AU.addPreserved<LoopInfoWrapperPass>();
282 AU.addRequired<TargetLibraryInfoWrapperPass>();
283 AU.addRequired<MemorySSAWrapperPass>();
284 AU.addPreserved<MemorySSAWrapperPass>();
285 AU.addRequired<TargetTransformInfoWrapperPass>();
286 AU.addRequired<AssumptionCacheTracker>();
289 AU.addPreserved<LazyBlockFrequencyInfoPass>();
290 AU.addPreserved<LazyBranchProbabilityInfoPass>();
291 }
292
293private:
294 LoopInvariantCodeMotion LICM;
295};
296} // namespace
297
300 if (!AR.MSSA)
301 reportFatalUsageError("LICM requires MemorySSA (loop-mssa)");
302
303 // For the new PM, we also can't use OptimizationRemarkEmitter as an analysis
304 // pass. Function analyses need to be preserved across loop transformations
305 // but ORE cannot be preserved (see comment before the pass definition).
306 OptimizationRemarkEmitter ORE(L.getHeader()->getParent());
307
308 LoopInvariantCodeMotion LICM(Opts.MssaOptCap, Opts.MssaNoAccForPromotionCap,
309 Opts.AllowSpeculation);
310 if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.AC, &AR.TLI, &AR.TTI,
311 &AR.SE, AR.MSSA, &ORE))
312 return PreservedAnalyses::all();
313
315 PA.preserve<MemorySSAAnalysis>();
316
317 return PA;
318}
319
321 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
322 static_cast<PassInfoMixin<LICMPass> *>(this)->printPipeline(
323 OS, MapClassName2PassName);
324
325 OS << '<';
326 OS << (Opts.AllowSpeculation ? "" : "no-") << "allowspeculation";
327 OS << '>';
328}
329
332 LPMUpdater &) {
333 if (!AR.MSSA)
334 reportFatalUsageError("LNICM requires MemorySSA (loop-mssa)");
335
336 // For the new PM, we also can't use OptimizationRemarkEmitter as an analysis
337 // pass. Function analyses need to be preserved across loop transformations
338 // but ORE cannot be preserved (see comment before the pass definition).
340
341 LoopInvariantCodeMotion LICM(Opts.MssaOptCap, Opts.MssaNoAccForPromotionCap,
342 Opts.AllowSpeculation);
343
344 Loop &OutermostLoop = LN.getOutermostLoop();
345 bool Changed = LICM.runOnLoop(&OutermostLoop, &AR.AA, &AR.LI, &AR.DT, &AR.AC,
346 &AR.TLI, &AR.TTI, &AR.SE, AR.MSSA, &ORE, true);
347
348 if (!Changed)
349 return PreservedAnalyses::all();
350
352
353 PA.preserve<DominatorTreeAnalysis>();
354 PA.preserve<LoopAnalysis>();
355 PA.preserve<MemorySSAAnalysis>();
356
357 return PA;
358}
359
361 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
362 static_cast<PassInfoMixin<LNICMPass> *>(this)->printPipeline(
363 OS, MapClassName2PassName);
364
365 OS << '<';
366 OS << (Opts.AllowSpeculation ? "" : "no-") << "allowspeculation";
367 OS << '>';
368}
369
370char LegacyLICMPass::ID = 0;
371INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
372 false, false)
378INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
379 false)
380
381Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
382
387
389 unsigned LicmMssaOptCap, unsigned LicmMssaNoAccForPromotionCap, bool IsSink,
390 Loop &L, MemorySSA &MSSA)
393 IsSink(IsSink) {
394 unsigned AccessCapCount = 0;
395 for (auto *BB : L.getBlocks())
396 if (const auto *Accesses = MSSA.getBlockAccesses(BB))
397 for (const auto &MA : *Accesses) {
398 (void)MA;
399 ++AccessCapCount;
400 if (AccessCapCount > LicmMssaNoAccForPromotionCap) {
401 NoOfMemAccTooLarge = true;
402 return;
403 }
404 }
405}
406
407/// Hoist expressions out of the specified loop. Note, alias info for inner
408/// loop is not preserved so it is not a good idea to run LICM multiple
409/// times on one loop.
410bool LoopInvariantCodeMotion::runOnLoop(Loop *L, AAResults *AA, LoopInfo *LI,
414 ScalarEvolution *SE, MemorySSA *MSSA,
416 bool LoopNestMode) {
417 bool Changed = false;
418
419 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
420
421 // If this loop has metadata indicating that LICM is not to be performed then
422 // just exit.
424 return false;
425 }
426
427 // Don't sink stores from loops with coroutine suspend instructions.
428 // LICM would sink instructions into the default destination of
429 // the coroutine switch. The default destination of the switch is to
430 // handle the case where the coroutine is suspended, by which point the
431 // coroutine frame may have been destroyed. No instruction can be sunk there.
432 // FIXME: This would unfortunately hurt the performance of coroutines, however
433 // there is currently no general solution for this. Similar issues could also
434 // potentially happen in other passes where instructions are being moved
435 // across that edge.
436 bool HasCoroSuspendInst = llvm::any_of(L->getBlocks(), [](BasicBlock *BB) {
437 using namespace PatternMatch;
438 return any_of(make_pointer_range(*BB),
439 match_fn(m_Intrinsic<Intrinsic::coro_suspend>()));
440 });
441
442 MemorySSAUpdater MSSAU(MSSA);
443 SinkAndHoistLICMFlags Flags(LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
444 /*IsSink=*/true, *L, *MSSA);
445
446 // Get the preheader block to move instructions into...
447 BasicBlock *Preheader = L->getLoopPreheader();
448
449 // Compute loop safety information.
450 ICFLoopSafetyInfo SafetyInfo(L);
451
452 // We want to visit all of the instructions in this loop... that are not parts
453 // of our subloops (they have already had their invariants hoisted out of
454 // their loop, into this loop, so there is no need to process the BODIES of
455 // the subloops).
456 //
457 // Traverse the body of the loop in depth first order on the dominator tree so
458 // that we are guaranteed to see definitions before we see uses. This allows
459 // us to sink instructions in one pass, without iteration. After sinking
460 // instructions, we perform another pass to hoist them out of the loop.
461 if (L->hasDedicatedExits())
462 Changed |=
463 LoopNestMode
464 ? sinkRegionForLoopNest(DT->getNode(L->getHeader()), AA, LI, DT,
465 TLI, TTI, L, MSSAU, &SafetyInfo, Flags, ORE)
466 : sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, TTI, L,
467 MSSAU, &SafetyInfo, Flags, ORE);
468 Flags.setIsSink(false);
469 if (Preheader)
470 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, AC, TLI, L,
471 MSSAU, SE, &SafetyInfo, Flags, ORE, LoopNestMode,
472 LicmAllowSpeculation);
473
474 // Now that all loop invariants have been removed from the loop, promote any
475 // memory references to scalars that we can.
476 // Don't sink stores from loops without dedicated block exits. Exits
477 // containing indirect branches are not transformed by loop simplify,
478 // make sure we catch that. An additional load may be generated in the
479 // preheader for SSA updater, so also avoid sinking when no preheader
480 // is available.
481 if (!DisablePromotion && Preheader && L->hasDedicatedExits() &&
482 !Flags.tooManyMemoryAccesses() && !HasCoroSuspendInst) {
483 // Figure out the loop exits and their insertion points
484 SmallVector<BasicBlock *, 8> ExitBlocks;
485 L->getUniqueExitBlocks(ExitBlocks);
486
487 // We can't insert into a catchswitch.
488 bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
489 return isa<CatchSwitchInst>(Exit->getTerminator());
490 });
491
492 if (!HasCatchSwitch) {
494 SmallVector<MemoryAccess *, 8> MSSAInsertPts;
495 InsertPts.reserve(ExitBlocks.size());
496 MSSAInsertPts.reserve(ExitBlocks.size());
497 for (BasicBlock *ExitBlock : ExitBlocks) {
498 InsertPts.push_back(ExitBlock->getFirstInsertionPt());
499 MSSAInsertPts.push_back(nullptr);
500 }
501
503
504 // Promoting one set of accesses may make the pointers for another set
505 // loop invariant, so run this in a loop.
506 bool Promoted = false;
507 bool LocalPromoted;
508 do {
509 LocalPromoted = false;
510 for (auto [PointerMustAliases, HasReadsOutsideSet] :
511 collectPromotionCandidates(MSSA, AA, DT, &SafetyInfo, L)) {
512 LocalPromoted |= promoteLoopAccessesToScalars(
513 PointerMustAliases, ExitBlocks, InsertPts, MSSAInsertPts, PIC, LI,
514 DT, AC, TLI, TTI, L, MSSAU, &SafetyInfo, ORE,
515 LicmAllowSpeculation, HasReadsOutsideSet);
516 }
517 Promoted |= LocalPromoted;
518 } while (LocalPromoted);
519
520 // Once we have promoted values across the loop body we have to
521 // recursively reform LCSSA as any nested loop may now have values defined
522 // within the loop used in the outer loop.
523 // FIXME: This is really heavy handed. It would be a bit better to use an
524 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
525 // it as it went.
526 if (Promoted)
527 formLCSSARecursively(*L, *DT, LI, SE);
528
529 Changed |= Promoted;
530 }
531 }
532
533 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
534 // specifically moving instructions across the loop boundary and so it is
535 // especially in need of basic functional correctness checking here.
536 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
537 assert((L->isOutermost() || L->getParentLoop()->isLCSSAForm(*DT)) &&
538 "Parent loop not left in LCSSA form after LICM!");
539
540 if (VerifyMemorySSA)
541 MSSA->verifyMemorySSA();
542
543 if (Changed && SE)
545 return Changed;
546}
547
548/// Walk the specified region of the CFG (defined by all blocks dominated by
549/// the specified block, and that are in the current loop) in reverse depth
550/// first order w.r.t the DominatorTree. This allows us to visit uses before
551/// definitions, allowing us to sink a loop body in one pass without iteration.
552///
555 TargetTransformInfo *TTI, Loop *CurLoop,
556 MemorySSAUpdater &MSSAU, ICFLoopSafetyInfo *SafetyInfo,
558 OptimizationRemarkEmitter *ORE, Loop *OutermostLoop) {
559
560 // Verify inputs.
561 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
562 CurLoop != nullptr && SafetyInfo != nullptr &&
563 "Unexpected input to sinkRegion.");
564
565 // We want to visit children before parents. We will enqueue all the parents
566 // before their children in the worklist and process the worklist in reverse
567 // order.
569 collectChildrenInLoop(DT, N, CurLoop);
570
571 bool Changed = false;
572 for (BasicBlock *BB : reverse(Worklist)) {
573 // subloop (which would already have been processed).
574 if (inSubLoop(BB, CurLoop, LI))
575 continue;
576
577 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
578 Instruction &I = *--II;
579
580 // The instruction is not used in the loop if it is dead. In this case,
581 // we just delete it instead of sinking it.
582 if (isInstructionTriviallyDead(&I, TLI)) {
583 LLVM_DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
586 ++II;
587 eraseInstruction(I, *SafetyInfo, MSSAU);
588 Changed = true;
589 continue;
590 }
591
592 // Check to see if we can sink this instruction to the exit blocks
593 // of the loop. We can do this if the all users of the instruction are
594 // outside of the loop. In this case, it doesn't even matter if the
595 // operands of the instruction are loop invariant.
596 //
597 bool FoldableInLoop = false;
598 bool LoopNestMode = OutermostLoop != nullptr;
599 if (!I.mayHaveSideEffects() &&
600 isNotUsedOrFoldableInLoop(I, LoopNestMode ? OutermostLoop : CurLoop,
601 SafetyInfo, TTI, FoldableInLoop,
602 LoopNestMode) &&
603 canSinkOrHoistInst(I, AA, DT, CurLoop, MSSAU, true, Flags, ORE)) {
604 if (sink(I, LI, DT, CurLoop, SafetyInfo, MSSAU, ORE)) {
605 if (!FoldableInLoop) {
606 ++II;
608 eraseInstruction(I, *SafetyInfo, MSSAU);
609 }
610 Changed = true;
611 }
612 }
613 }
614 }
615 if (VerifyMemorySSA)
616 MSSAU.getMemorySSA()->verifyMemorySSA();
617 return Changed;
618}
619
622 TargetTransformInfo *TTI, Loop *CurLoop,
623 MemorySSAUpdater &MSSAU,
624 ICFLoopSafetyInfo *SafetyInfo,
627
628 bool Changed = false;
630 Worklist.insert(CurLoop);
631 appendLoopsToWorklist(*CurLoop, Worklist);
632 while (!Worklist.empty()) {
633 Loop *L = Worklist.pop_back_val();
634 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, TTI, L,
635 MSSAU, SafetyInfo, Flags, ORE, CurLoop);
636 }
637 return Changed;
638}
639
640/// Walk the specified region of the CFG (defined by all blocks dominated by
641/// the specified block, and that are in the current loop) in depth first
642/// order w.r.t the DominatorTree. This allows us to visit definitions before
643/// uses, allowing us to hoist a loop body in one pass without iteration.
644///
647 TargetLibraryInfo *TLI, Loop *CurLoop,
649 ICFLoopSafetyInfo *SafetyInfo,
651 OptimizationRemarkEmitter *ORE, bool LoopNestMode,
652 bool AllowSpeculation) {
653 // Verify inputs.
654 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
655 CurLoop != nullptr && SafetyInfo != nullptr &&
656 "Unexpected input to hoistRegion.");
657
658 LoopBlocksRPO Worklist(CurLoop);
659 Worklist.perform(LI);
660 bool Changed = false;
661 BasicBlock *Preheader = CurLoop->getLoopPreheader();
662 for (BasicBlock *BB : Worklist) {
663 // Only need to process the contents of this block if it is not part of a
664 // subloop (which would already have been processed).
665 if (!LoopNestMode && inSubLoop(BB, CurLoop, LI))
666 continue;
667
669 // Try hoisting the instruction out to the preheader. We can only do
670 // this if all of the operands of the instruction are loop invariant and
671 // if it is safe to hoist the instruction.
672 if (CurLoop->hasLoopInvariantOperands(&I) &&
673 canSinkOrHoistInst(I, AA, DT, CurLoop, MSSAU, true, Flags, ORE) &&
674 isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo, ORE,
675 Preheader->getTerminator(), AC,
676 AllowSpeculation)) {
677 hoist(I, DT, CurLoop, Preheader, SafetyInfo, MSSAU, SE, ORE);
678 Changed = true;
679 continue;
680 }
681
682 if (auto *Ins = dyn_cast<InsertElementInst>(&I))
683 if (hoistInsertPastInsert(Ins, CurLoop, DT, Preheader, SafetyInfo,
684 MSSAU, SE, ORE)) {
685 Changed = true;
686 continue;
687 }
688
689 // Attempt to remove floating point division out of the loop by
690 // converting it to a reciprocal multiplication.
691 if (I.getOpcode() == Instruction::FDiv && I.hasAllowReciprocal() &&
692 CurLoop->isLoopInvariant(I.getOperand(1))) {
693 auto Divisor = I.getOperand(1);
694 auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0);
695 auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);
696 ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags());
697 SafetyInfo->insertInstructionTo(ReciprocalDivisor, I.getParent());
698 ReciprocalDivisor->insertBefore(I.getIterator());
699 ReciprocalDivisor->setDebugLoc(I.getDebugLoc());
700
701 auto Product =
702 BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor);
703 Product->setFastMathFlags(I.getFastMathFlags());
704 SafetyInfo->insertInstructionTo(Product, I.getParent());
705 Product->insertAfter(I.getIterator());
706 Product->setDebugLoc(I.getDebugLoc());
707 I.replaceAllUsesWith(Product);
708 eraseInstruction(I, *SafetyInfo, MSSAU);
709
710 hoist(*ReciprocalDivisor, DT, CurLoop, Preheader, SafetyInfo, MSSAU, SE,
711 ORE);
712 Changed = true;
713 continue;
714 }
715
716 auto IsInvariantStart = [&](Instruction &I) {
717 using namespace PatternMatch;
718 return I.use_empty() &&
720 };
721 auto MustExecuteWithoutWritesBefore = [&](Instruction &I) {
722 return SafetyInfo->isGuaranteedToExecute(I, DT) &&
723 SafetyInfo->doesNotWriteMemoryBefore(I);
724 };
725 if ((IsInvariantStart(I) || isGuard(&I)) &&
726 CurLoop->hasLoopInvariantOperands(&I) &&
727 MustExecuteWithoutWritesBefore(I)) {
728 hoist(I, DT, CurLoop, Preheader, SafetyInfo, MSSAU, SE, ORE);
729 Changed = true;
730 continue;
731 }
732
733 // Try to reassociate instructions so that part of computations can be
734 // done out of loop.
735 if (hoistArithmetics(I, *CurLoop, *SafetyInfo, MSSAU, AC, DT)) {
736 Changed = true;
737 continue;
738 }
739 }
740 }
741
742 if (VerifyMemorySSA)
743 MSSAU.getMemorySSA()->verifyMemorySSA();
744
745 // Now that we've finished hoisting make sure that LI and DT are still
746 // valid.
747#ifdef EXPENSIVE_CHECKS
748 if (Changed) {
749 assert(DT->verify(DominatorTree::VerificationLevel::Fast) &&
750 "Dominator tree verification failed");
751 LI->verify();
752 }
753#endif
754
755 return Changed;
756}
757
758static std::optional<uint64_t>
760 // Must have constant insertion lane.
761 auto *InsertedIdxCI = dyn_cast<ConstantInt>(Ins->getOperand(2));
762 if (!InsertedIdxCI)
763 return std::nullopt;
764 auto *VecTy = cast<VectorType>(Ins->getType());
765
766 // Avoid hoisting past out of bounds inserts.
767 if (InsertedIdxCI->isNegative() ||
768 InsertedIdxCI->getValue().uge(
769 VecTy->getElementCount().getKnownMinValue()))
770 return std::nullopt;
771 return InsertedIdxCI->getValue().getLimitedValue();
772}
773
775 DominatorTree *DT, BasicBlock *HoistDest,
776 ICFLoopSafetyInfo *SafetyInfo,
779 // Canonicalize:
780 // %inner = insertelement %base, %variant, C1
781 // %outer = insertelement %inner, %invariant, C2
782 // into:
783 // %outer = insertelement %base, %invariant, C2
784 // %inner = insertelement %outer, %variant, C1
785 // so we can hoist %outer
786
787 // The instruction we are hoisting must have invariant insertion data
788 Value *InsertedElt = Ins->getOperand(1);
789 if (!CurLoop->isLoopInvariant(InsertedElt))
790 return false;
791
792 std::optional<uint64_t> HoistIdx = getConstantInsertionIndex(Ins);
793 if (!HoistIdx)
794 return false;
795
796 InsertElementInst *Inner = Ins;
797 while (!CurLoop->isLoopInvariant(Inner->getOperand(0))) {
798 // If the inner value isn't invariant, check to see if it is another insert
799 // All instructions in the chain must be in the same basic block
800 auto *InnerIns = dyn_cast<InsertElementInst>(Inner->getOperand(0));
801 if (!InnerIns || InnerIns->getParent() != Ins->getParent())
802 return false;
803
804 // Make sure not hoisting past insertions into the same lane
805 std::optional<uint64_t> InsertIdx = getConstantInsertionIndex(InnerIns);
806 if (!InsertIdx || *InsertIdx == *HoistIdx)
807 return false;
808
809 // Instruction being hoisted past must only have one use
810 if (!InnerIns->hasOneUse())
811 return false;
812
813 Inner = InnerIns;
814 }
815
816 // Base case of `insertelement <4 x i8> %invar0, i8 %invar1, i32 2` handled in
817 // base LICM logic
818 if (Inner == Ins)
819 return false;
820
821 Ins->replaceAllUsesWith(Ins->getOperand(0));
822 Ins->moveBefore(Inner->getIterator());
823 Ins->setOperand(0, Inner->getOperand(0));
824 Inner->setOperand(0, Ins);
825 hoist(*Ins, DT, CurLoop, HoistDest, SafetyInfo, MSSAU, SE, ORE);
826 return true;
827}
828
829// Return true if LI is invariant within scope of the loop. LI is invariant if
830// CurLoop is dominated by an invariant.start representing the same memory
831// location and size as the memory location LI loads from, and also the
832// invariant.start has no uses.
834 Loop *CurLoop) {
835 Value *Addr = LI->getPointerOperand();
836 const DataLayout &DL = LI->getDataLayout();
837 const TypeSize LocSizeInBits = DL.getTypeSizeInBits(LI->getType());
838
839 // It is not currently possible for clang to generate an invariant.start
840 // intrinsic with scalable vector types because we don't support thread local
841 // sizeless types and we don't permit sizeless types in structs or classes.
842 // Furthermore, even if support is added for this in future the intrinsic
843 // itself is defined to have a size of -1 for variable sized objects. This
844 // makes it impossible to verify if the intrinsic envelops our region of
845 // interest. For example, both <vscale x 32 x i8> and <vscale x 16 x i8>
846 // types would have a -1 parameter, but the former is clearly double the size
847 // of the latter.
848 if (LocSizeInBits.isScalable())
849 return false;
850
851 // If we've ended up at a global/constant, bail. We shouldn't be looking at
852 // uselists for non-local Values in a loop pass.
853 if (isa<Constant>(Addr))
854 return false;
855
856 unsigned UsesVisited = 0;
857 // Traverse all uses of the load operand value, to see if invariant.start is
858 // one of the uses, and whether it dominates the load instruction.
859 for (auto *U : Addr->users()) {
860 // Avoid traversing for Load operand with high number of users.
861 if (++UsesVisited > MaxNumUsesTraversed)
862 return false;
864 // If there are escaping uses of invariant.start instruction, the load maybe
865 // non-invariant.
866 if (!II || II->getIntrinsicID() != Intrinsic::invariant_start ||
867 !II->use_empty())
868 continue;
869 ConstantInt *InvariantSize = cast<ConstantInt>(II->getArgOperand(0));
870 // The intrinsic supports having a -1 argument for variable sized objects
871 // so we should check for that here.
872 if (InvariantSize->isNegative())
873 continue;
874 uint64_t InvariantSizeInBits = InvariantSize->getSExtValue() * 8;
875 // Confirm the invariant.start location size contains the load operand size
876 // in bits. Also, the invariant.start should dominate the load, and we
877 // should not hoist the load out of a loop that contains this dominating
878 // invariant.start.
879 if (LocSizeInBits.getFixedValue() <= InvariantSizeInBits &&
880 DT->properlyDominates(II->getParent(), CurLoop->getHeader()))
881 return true;
882 }
883
884 return false;
885}
886
887/// Return true if-and-only-if we know how to (mechanically) both hoist and
888/// sink a given instruction out of a loop. Does not address legality
889/// concerns such as aliasing or speculation safety.
900
901/// Return true if I is the only Instruction with a MemoryAccess in L.
902static bool isOnlyMemoryAccess(const Instruction *I, const Loop *L,
903 const MemorySSAUpdater &MSSAU) {
904 for (auto *BB : L->getBlocks())
905 if (auto *Accs = MSSAU.getMemorySSA()->getBlockAccesses(BB)) {
906 int NotAPhi = 0;
907 for (const auto &Acc : *Accs) {
908 if (isa<MemoryPhi>(&Acc))
909 continue;
910 const auto *MUD = cast<MemoryUseOrDef>(&Acc);
911 if (MUD->getMemoryInst() != I || NotAPhi++ == 1)
912 return false;
913 }
914 }
915 return true;
916}
917
919 BatchAAResults &BAA,
921 MemoryUseOrDef *MA) {
922 // See declaration of SetLicmMssaOptCap for usage details.
923 if (Flags.tooManyClobberingCalls())
924 return MA->getDefiningAccess();
925
926 MemoryAccess *Source =
928 Flags.incrementClobberingCalls();
929 return Source;
930}
931
933 Loop *CurLoop, MemorySSA &MSSA,
934 bool TargetExecutesOncePerLoop,
937 if (!LI.isUnordered())
938 return false; // Don't sink/hoist volatile or ordered atomic loads!
939
940 // Loads from constant memory are always safe to move, even if they end up
941 // in the same alias set as something that ends up being modified.
942 if (!isModSet(AA->getModRefInfoMask(LI.getOperand(0))))
943 return true;
944 if (LI.hasMetadata(LLVMContext::MD_invariant_load))
945 return true;
946
947 if (LI.isAtomic() && !TargetExecutesOncePerLoop)
948 return false; // Don't risk duplicating unordered loads
949
950 // This checks for an invariant.start dominating the load.
951 if (isLoadInvariantInLoop(&LI, DT, CurLoop))
952 return true;
953
954 auto *MU = cast<MemoryUse>(MSSA.getMemoryAccess(&LI));
955
956 bool InvariantGroup = LI.hasMetadata(LLVMContext::MD_invariant_group);
957
958 bool Invalidated =
959 pointerInvalidatedByLoop(&MSSA, MU, CurLoop, LI, Flags, InvariantGroup);
960 // Check loop-invariant address because this may also be a sinkable load
961 // whose address is not necessarily loop-invariant.
962 if (ORE && Invalidated && CurLoop->isLoopInvariant(LI.getPointerOperand()))
963 ORE->emit([&]() {
965 DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", &LI)
966 << "failed to move load with loop-invariant address "
967 "because the loop may invalidate its value";
968 });
969
970 return !Invalidated;
971}
972
974 Loop *CurLoop, MemorySSAUpdater &MSSAU,
975 bool TargetExecutesOncePerLoop,
978 // If we don't understand the instruction, bail early.
980 return false;
981
982 MemorySSA *MSSA = MSSAU.getMemorySSA();
983 // Loads have extra constraints we have to verify before we can hoist them.
984 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
985 return canHoistLoad(*LI, AA, DT, CurLoop, *MSSA, TargetExecutesOncePerLoop,
986 Flags, ORE);
987 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
988 // Don't sink calls which can throw.
989 if (CI->mayThrow())
990 return false;
991
992 // Convergent attribute has been used on operations that involve
993 // inter-thread communication which results are implicitly affected by the
994 // enclosing control flows. It is not safe to hoist or sink such operations
995 // across control flow.
996 if (CI->isConvergent())
997 return false;
998
999 // FIXME: Current LLVM IR semantics don't work well with coroutines and
1000 // thread local globals. We currently treat getting the address of a thread
1001 // local global as not accessing memory, even though it may not be a
1002 // constant throughout a function with coroutines. Remove this check after
1003 // we better model semantics of thread local globals.
1004 if (CI->getFunction()->isPresplitCoroutine())
1005 return false;
1006
1007 using namespace PatternMatch;
1009 // Assumes don't actually alias anything or throw
1010 return true;
1011
1012 // Handle simple cases by querying alias analysis.
1013 MemoryEffects Behavior = AA->getMemoryEffects(CI);
1014
1015 if (Behavior.doesNotAccessMemory())
1016 return true;
1017 if (Behavior.onlyReadsMemory()) {
1018 // Might have stale MemoryDef for call that was later inferred to be
1019 // read-only.
1020 auto *MU = dyn_cast<MemoryUse>(MSSA->getMemoryAccess(CI));
1021 if (!MU)
1022 return false;
1023
1024 // If we can prove there are no writes to the memory read by the call, we
1025 // can hoist or sink.
1027 MSSA, MU, CurLoop, I, Flags, /*InvariantGroup=*/false);
1028 }
1029
1030 if (Behavior.onlyWritesMemory()) {
1031 // can hoist or sink if there are no conflicting read/writes to the
1032 // memory location written to by the call.
1033 return noConflictingReadWrites(CI, MSSA, AA, CurLoop, Flags);
1034 }
1035
1036 return false;
1037 } else if (auto *FI = dyn_cast<FenceInst>(&I)) {
1038 // Fences alias (most) everything to provide ordering. For the moment,
1039 // just give up if there are any other memory operations in the loop.
1040 return isOnlyMemoryAccess(FI, CurLoop, MSSAU);
1041 } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
1042 if (!SI->isUnordered())
1043 return false; // Don't sink/hoist volatile or ordered atomic store!
1044
1045 // We can only hoist a store that we can prove writes a value which is not
1046 // read or overwritten within the loop. For those cases, we fallback to
1047 // load store promotion instead. TODO: We can extend this to cases where
1048 // there is exactly one write to the location and that write dominates an
1049 // arbitrary number of reads in the loop.
1050 if (isOnlyMemoryAccess(SI, CurLoop, MSSAU))
1051 return true;
1052 return noConflictingReadWrites(SI, MSSA, AA, CurLoop, Flags);
1053 }
1054
1055 assert(!I.mayReadOrWriteMemory() && "unhandled aliasing");
1056
1057 // We've established mechanical ability and aliasing, it's up to the caller
1058 // to check fault safety
1059 return true;
1060}
1061
1062/// Returns true if a PHINode is a trivially replaceable with an
1063/// Instruction.
1064/// This is true when all incoming values are that instruction.
1065/// This pattern occurs most often with LCSSA PHI nodes.
1066///
1067static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I) {
1068 for (const Value *IncValue : PN.incoming_values())
1069 if (IncValue != &I)
1070 return false;
1071
1072 return true;
1073}
1074
1075/// Return true if the instruction is foldable in the loop.
1076static bool isFoldableInLoop(const Instruction &I, const Loop *CurLoop,
1077 const TargetTransformInfo *TTI) {
1078 if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1079 InstructionCost CostI =
1080 TTI->getInstructionCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
1081 if (CostI != TargetTransformInfo::TCC_Free)
1082 return false;
1083 // For a GEP, we cannot simply use getInstructionCost because currently
1084 // it optimistically assumes that a GEP will fold into addressing mode
1085 // regardless of its users.
1086 const BasicBlock *BB = GEP->getParent();
1087 for (const User *U : GEP->users()) {
1088 const Instruction *UI = cast<Instruction>(U);
1089 if (CurLoop->contains(UI) &&
1090 (BB != UI->getParent() ||
1091 (!isa<StoreInst>(UI) && !isa<LoadInst>(UI))))
1092 return false;
1093 }
1094 return true;
1095 }
1096
1097 return false;
1098}
1099
1100/// Return true if the only users of this instruction are outside of
1101/// the loop. If this is true, we can sink the instruction to the exit
1102/// blocks of the loop.
1103///
1104/// We also return true if the instruction could be folded away in lowering.
1105/// (e.g., a GEP can be folded into a load as an addressing mode in the loop).
1106static bool isNotUsedOrFoldableInLoop(const Instruction &I, const Loop *CurLoop,
1107 const LoopSafetyInfo *SafetyInfo,
1109 bool &FoldableInLoop, bool LoopNestMode) {
1110 bool IsFoldable = isFoldableInLoop(I, CurLoop, TTI);
1111 for (const User *U : I.users()) {
1112 const Instruction *UI = cast<Instruction>(U);
1113 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
1114 const BasicBlock *BB = PN->getParent();
1115 // We cannot sink uses in catchswitches.
1117 return false;
1118
1119 // We need to sink a callsite to a unique funclet. Avoid sinking if the
1120 // phi use is too muddled.
1121 if (isa<CallInst>(I)) {
1122 const auto &BlockColors = SafetyInfo->getBlockColors();
1123 if (!BlockColors.empty() &&
1124 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
1125 return false;
1126 }
1127
1128 if (LoopNestMode) {
1129 while (isa<PHINode>(UI) && UI->hasOneUser() &&
1130 UI->getNumOperands() == 1) {
1131 if (!CurLoop->contains(UI))
1132 break;
1133 UI = cast<Instruction>(UI->user_back());
1134 }
1135 }
1136 }
1137
1138 if (CurLoop->contains(UI)) {
1139 if (IsFoldable) {
1140 FoldableInLoop = true;
1141 continue;
1142 }
1143 return false;
1144 }
1145 }
1146 return true;
1147}
1148
1150 Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI,
1151 const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater &MSSAU) {
1152 Instruction *New;
1153 if (auto *CI = dyn_cast<CallInst>(&I)) {
1154 const auto &BlockColors = SafetyInfo->getBlockColors();
1155
1156 // Sinking call-sites need to be handled differently from other
1157 // instructions. The cloned call-site needs a funclet bundle operand
1158 // appropriate for its location in the CFG.
1160 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
1161 BundleIdx != BundleEnd; ++BundleIdx) {
1162 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
1163 if (Bundle.getTagID() == LLVMContext::OB_funclet)
1164 continue;
1165
1166 OpBundles.emplace_back(Bundle);
1167 }
1168
1169 if (!BlockColors.empty()) {
1170 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
1171 assert(CV.size() == 1 && "non-unique color for exit block!");
1172 BasicBlock *BBColor = CV.front();
1173 BasicBlock::iterator EHPad = BBColor->getFirstNonPHIIt();
1174 if (EHPad->isEHPad())
1175 OpBundles.emplace_back("funclet", &*EHPad);
1176 }
1177
1178 New = CallInst::Create(CI, OpBundles);
1179 New->copyMetadata(*CI);
1180 } else {
1181 New = I.clone();
1182 }
1183
1184 New->insertInto(&ExitBlock, ExitBlock.getFirstInsertionPt());
1185 if (!I.getName().empty())
1186 New->setName(I.getName() + ".le");
1187
1188 if (MSSAU.getMemorySSA()->getMemoryAccess(&I)) {
1189 // Create a new MemoryAccess and let MemorySSA set its defining access.
1190 // After running some passes, MemorySSA might be outdated, and the
1191 // instruction `I` may have become a non-memory touching instruction.
1192 MemoryAccess *NewMemAcc = MSSAU.createMemoryAccessInBB(
1193 New, nullptr, New->getParent(), MemorySSA::Beginning,
1194 /*CreationMustSucceed=*/false);
1195 if (NewMemAcc) {
1196 if (auto *MemDef = dyn_cast<MemoryDef>(NewMemAcc))
1197 MSSAU.insertDef(MemDef, /*RenameUses=*/true);
1198 else {
1199 auto *MemUse = cast<MemoryUse>(NewMemAcc);
1200 MSSAU.insertUse(MemUse, /*RenameUses=*/true);
1201 }
1202 }
1203 }
1204
1205 // Build LCSSA PHI nodes for any in-loop operands (if legal). Note that
1206 // this is particularly cheap because we can rip off the PHI node that we're
1207 // replacing for the number and blocks of the predecessors.
1208 // OPT: If this shows up in a profile, we can instead finish sinking all
1209 // invariant instructions, and then walk their operands to re-establish
1210 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
1211 // sinking bottom-up.
1212 for (Use &Op : New->operands())
1213 if (LI->wouldBeOutOfLoopUseRequiringLCSSA(Op.get(), PN.getParent())) {
1214 auto *OInst = cast<Instruction>(Op.get());
1215 PHINode *OpPN =
1216 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
1217 OInst->getName() + ".lcssa");
1218 OpPN->insertBefore(ExitBlock.begin());
1219 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1220 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
1221 Op = OpPN;
1222 }
1223 return New;
1224}
1225
1227 MemorySSAUpdater &MSSAU) {
1228 MSSAU.removeMemoryAccess(&I);
1229 SafetyInfo.removeInstruction(&I);
1230 I.eraseFromParent();
1231}
1232
1234 ICFLoopSafetyInfo &SafetyInfo,
1235 MemorySSAUpdater &MSSAU,
1236 ScalarEvolution *SE) {
1237 SafetyInfo.removeInstruction(&I);
1238 SafetyInfo.insertInstructionTo(&I, Dest->getParent());
1239 I.moveBefore(*Dest->getParent(), Dest);
1241 MSSAU.getMemorySSA()->getMemoryAccess(&I)))
1242 MSSAU.moveToPlace(OldMemAcc, Dest->getParent(),
1244 if (SE)
1246}
1247
1249 PHINode *TPN, Instruction *I, LoopInfo *LI,
1251 const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop,
1252 MemorySSAUpdater &MSSAU) {
1254 "Expect only trivially replaceable PHI");
1255 BasicBlock *ExitBlock = TPN->getParent();
1256 auto [It, Inserted] = SunkCopies.try_emplace(ExitBlock);
1257 if (Inserted)
1258 It->second = cloneInstructionInExitBlock(*I, *ExitBlock, *TPN, LI,
1259 SafetyInfo, MSSAU);
1260 return It->second;
1261}
1262
1263static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo) {
1264 BasicBlock *BB = PN->getParent();
1265 if (!BB->canSplitPredecessors())
1266 return false;
1267 // It's not impossible to split EHPad blocks, but if BlockColors already exist
1268 // it require updating BlockColors for all offspring blocks accordingly. By
1269 // skipping such corner case, we can make updating BlockColors after splitting
1270 // predecessor fairly simple.
1271 if (!SafetyInfo->getBlockColors().empty() &&
1272 BB->getFirstNonPHIIt()->isEHPad())
1273 return false;
1274 for (BasicBlock *BBPred : predecessors(BB)) {
1275 if (isa<IndirectBrInst>(BBPred->getTerminator()))
1276 return false;
1277 }
1278 return true;
1279}
1280
1282 LoopInfo *LI, const Loop *CurLoop,
1283 LoopSafetyInfo *SafetyInfo,
1284 MemorySSAUpdater *MSSAU) {
1285#ifndef NDEBUG
1287 CurLoop->getUniqueExitBlocks(ExitBlocks);
1288 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(llvm::from_range, ExitBlocks);
1289#endif
1290 BasicBlock *ExitBB = PN->getParent();
1291 assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block.");
1292
1293 // Split predecessors of the loop exit to make instructions in the loop are
1294 // exposed to exit blocks through trivially replaceable PHIs while keeping the
1295 // loop in the canonical form where each predecessor of each exit block should
1296 // be contained within the loop. For example, this will convert the loop below
1297 // from
1298 //
1299 // LB1:
1300 // %v1 =
1301 // br %LE, %LB2
1302 // LB2:
1303 // %v2 =
1304 // br %LE, %LB1
1305 // LE:
1306 // %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replaceable
1307 //
1308 // to
1309 //
1310 // LB1:
1311 // %v1 =
1312 // br %LE.split, %LB2
1313 // LB2:
1314 // %v2 =
1315 // br %LE.split2, %LB1
1316 // LE.split:
1317 // %p1 = phi [%v1, %LB1] <-- trivially replaceable
1318 // br %LE
1319 // LE.split2:
1320 // %p2 = phi [%v2, %LB2] <-- trivially replaceable
1321 // br %LE
1322 // LE:
1323 // %p = phi [%p1, %LE.split], [%p2, %LE.split2]
1324 //
1325 const auto &BlockColors = SafetyInfo->getBlockColors();
1326 SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB));
1327 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
1328 while (!PredBBs.empty()) {
1329 BasicBlock *PredBB = *PredBBs.begin();
1330 assert(CurLoop->contains(PredBB) &&
1331 "Expect all predecessors are in the loop");
1332 if (PN->getBasicBlockIndex(PredBB) >= 0) {
1334 ExitBB, PredBB, ".split.loop.exit", &DTU, LI, MSSAU, true);
1335 // Since we do not allow splitting EH-block with BlockColors in
1336 // canSplitPredecessors(), we can simply assign predecessor's color to
1337 // the new block.
1338 if (!BlockColors.empty())
1339 // Grab a reference to the ColorVector to be inserted before getting the
1340 // reference to the vector we are copying because inserting the new
1341 // element in BlockColors might cause the map to be reallocated.
1342 SafetyInfo->copyColors(NewPred, PredBB);
1343 }
1344 PredBBs.remove(PredBB);
1345 }
1346}
1347
1348/// When an instruction is found to only be used outside of the loop, this
1349/// function moves it to the exit blocks and patches up SSA form as needed.
1350/// This method is guaranteed to remove the original instruction from its
1351/// position, and may either delete it or move it to outside of the loop.
1352///
1353static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
1354 const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo,
1356 bool Changed = false;
1357 LLVM_DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
1358
1359 // Iterate over users to be ready for actual sinking. Replace users via
1360 // unreachable blocks with undef and make all user PHIs trivially replaceable.
1361 SmallPtrSet<Instruction *, 8> VisitedUsers;
1362 for (Instruction::user_iterator UI = I.user_begin(), UE = I.user_end();
1363 UI != UE;) {
1364 auto *User = cast<Instruction>(*UI);
1365 Use &U = UI.getUse();
1366 ++UI;
1367
1368 if (VisitedUsers.count(User) || CurLoop->contains(User))
1369 continue;
1370
1371 if (!DT->isReachableFromEntry(User->getParent())) {
1372 U = PoisonValue::get(I.getType());
1373 Changed = true;
1374 continue;
1375 }
1376
1377 // The user must be a PHI node.
1378 PHINode *PN = cast<PHINode>(User);
1379
1380 // Surprisingly, instructions can be used outside of loops without any
1381 // exits. This can only happen in PHI nodes if the incoming block is
1382 // unreachable.
1383 BasicBlock *BB = PN->getIncomingBlock(U);
1384 if (!DT->isReachableFromEntry(BB)) {
1385 U = PoisonValue::get(I.getType());
1386 Changed = true;
1387 continue;
1388 }
1389
1390 VisitedUsers.insert(PN);
1391 if (isTriviallyReplaceablePHI(*PN, I))
1392 continue;
1393
1394 if (!canSplitPredecessors(PN, SafetyInfo))
1395 return Changed;
1396
1397 // Split predecessors of the PHI so that we can make users trivially
1398 // replaceable.
1399 splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop, SafetyInfo, &MSSAU);
1400
1401 // Should rebuild the iterators, as they may be invalidated by
1402 // splitPredecessorsOfLoopExit().
1403 UI = I.user_begin();
1404 UE = I.user_end();
1405 }
1406
1407 if (VisitedUsers.empty())
1408 return Changed;
1409
1410 ORE->emit([&]() {
1411 return OptimizationRemark(DEBUG_TYPE, "InstSunk", &I)
1412 << "sinking " << ore::NV("Inst", &I);
1413 });
1414 if (isa<LoadInst>(I))
1415 ++NumMovedLoads;
1416 else if (isa<CallInst>(I))
1417 ++NumMovedCalls;
1418 ++NumSunk;
1419
1420#ifndef NDEBUG
1422 CurLoop->getUniqueExitBlocks(ExitBlocks);
1423 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(llvm::from_range, ExitBlocks);
1424#endif
1425
1426 // Clones of this instruction. Don't create more than one per exit block!
1428
1429 // If this instruction is only used outside of the loop, then all users are
1430 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
1431 // the instruction.
1432 // First check if I is worth sinking for all uses. Sink only when it is worth
1433 // across all uses.
1434 SmallSetVector<User*, 8> Users(I.user_begin(), I.user_end());
1435 for (auto *UI : Users) {
1436 auto *User = cast<Instruction>(UI);
1437
1438 if (CurLoop->contains(User))
1439 continue;
1440
1441 PHINode *PN = cast<PHINode>(User);
1442 assert(ExitBlockSet.count(PN->getParent()) &&
1443 "The LCSSA PHI is not in an exit block!");
1444
1445 // The PHI must be trivially replaceable.
1447 PN, &I, LI, SunkCopies, SafetyInfo, CurLoop, MSSAU);
1448 // As we sink the instruction out of the BB, drop its debug location.
1449 New->dropLocation();
1450 PN->replaceAllUsesWith(New);
1451 eraseInstruction(*PN, *SafetyInfo, MSSAU);
1452 Changed = true;
1453 }
1454 return Changed;
1455}
1456
1457/// When an instruction is found to only use loop invariant operands that
1458/// is safe to hoist, this instruction is called to do the dirty work.
1459///
1460static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
1461 BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo,
1464 LLVM_DEBUG(dbgs() << "LICM hoisting to " << Dest->getNameOrAsOperand() << ": "
1465 << I << "\n");
1466 ORE->emit([&]() {
1467 return OptimizationRemark(DEBUG_TYPE, "Hoisted", &I) << "hoisting "
1468 << ore::NV("Inst", &I);
1469 });
1470
1471 // Metadata can be dependent on conditions we are hoisting above.
1472 // Conservatively strip all metadata on the instruction unless we were
1473 // guaranteed to execute I if we entered the loop, in which case the metadata
1474 // is valid in the loop preheader.
1475 // Similarly, If I is a call and it is not guaranteed to execute in the loop,
1476 // then moving to the preheader means we should strip attributes on the call
1477 // that can cause UB since we may be hoisting above conditions that allowed
1478 // inferring those attributes. They may not be valid at the preheader.
1479 if ((I.hasMetadataOtherThanDebugLoc() || isa<CallInst>(I)) &&
1480 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
1481 // time in isGuaranteedToExecute if we don't actually have anything to
1482 // drop. It is a compile time optimization, not required for correctness.
1483 !SafetyInfo->isGuaranteedToExecute(I, DT)) {
1484 I.dropUBImplyingAttrsAndMetadata();
1485 }
1486
1487 if (isa<PHINode>(I))
1488 // Move the new node to the end of the phi list in the destination block.
1489 moveInstructionBefore(I, Dest->getFirstNonPHIIt(), *SafetyInfo, MSSAU, SE);
1490 else
1491 // Move the new node to the destination block, before its terminator.
1492 moveInstructionBefore(I, Dest->getTerminator()->getIterator(), *SafetyInfo,
1493 MSSAU, SE);
1494
1495 I.updateLocationAfterHoist();
1496
1497 if (isa<LoadInst>(I))
1498 ++NumMovedLoads;
1499 else if (isa<CallInst>(I))
1500 ++NumMovedCalls;
1501 ++NumHoisted;
1502}
1503
1504/// Only sink or hoist an instruction if it is not a trapping instruction,
1505/// or if the instruction is known not to trap when moved to the preheader.
1506/// or if it is a trapping instruction and is guaranteed to execute.
1508 Instruction &Inst, const DominatorTree *DT, const TargetLibraryInfo *TLI,
1509 const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo,
1510 OptimizationRemarkEmitter *ORE, const Instruction *CtxI,
1511 AssumptionCache *AC, bool AllowSpeculation) {
1512 if (AllowSpeculation &&
1513 isSafeToSpeculativelyExecute(&Inst, CtxI, AC, DT, TLI))
1514 return true;
1515
1516 bool GuaranteedToExecute = SafetyInfo->isGuaranteedToExecute(Inst, DT);
1517
1518 if (!GuaranteedToExecute) {
1519 auto *LI = dyn_cast<LoadInst>(&Inst);
1520 if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand()))
1521 ORE->emit([&]() {
1523 DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI)
1524 << "failed to hoist load with loop-invariant address "
1525 "because load is conditionally executed";
1526 });
1527 }
1528
1529 return GuaranteedToExecute;
1530}
1531
1532namespace {
1533class LoopPromoter : public LoadAndStorePromoter {
1534 Value *SomePtr; // Designated pointer to store to.
1535 SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
1536 SmallVectorImpl<BasicBlock::iterator> &LoopInsertPts;
1537 SmallVectorImpl<MemoryAccess *> &MSSAInsertPts;
1538 PredIteratorCache &PredCache;
1539 MemorySSAUpdater &MSSAU;
1540 LoopInfo &LI;
1541 DebugLoc DL;
1543 bool UnorderedAtomic;
1544 AAMDNodes AATags;
1545 ICFLoopSafetyInfo &SafetyInfo;
1546 bool CanInsertStoresInExitBlocks;
1548
1549 // We're about to add a use of V in a loop exit block. Insert an LCSSA phi
1550 // (if legal) if doing so would add an out-of-loop use to an instruction
1551 // defined in-loop.
1552 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
1553 if (!LI.wouldBeOutOfLoopUseRequiringLCSSA(V, BB))
1554 return V;
1555
1557 // We need to create an LCSSA PHI node for the incoming value and
1558 // store that.
1559 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
1560 I->getName() + ".lcssa");
1561 PN->insertBefore(BB->begin());
1562 for (BasicBlock *Pred : PredCache.get(BB))
1563 PN->addIncoming(I, Pred);
1564 return PN;
1565 }
1566
1567public:
1568 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
1569 SmallVectorImpl<BasicBlock *> &LEB,
1570 SmallVectorImpl<BasicBlock::iterator> &LIP,
1571 SmallVectorImpl<MemoryAccess *> &MSSAIP, PredIteratorCache &PIC,
1572 MemorySSAUpdater &MSSAU, LoopInfo &li, DebugLoc dl,
1573 Align Alignment, bool UnorderedAtomic, const AAMDNodes &AATags,
1574 ICFLoopSafetyInfo &SafetyInfo, bool CanInsertStoresInExitBlocks)
1575 : LoadAndStorePromoter(Insts, S), SomePtr(SP), LoopExitBlocks(LEB),
1576 LoopInsertPts(LIP), MSSAInsertPts(MSSAIP), PredCache(PIC), MSSAU(MSSAU),
1577 LI(li), DL(std::move(dl)), Alignment(Alignment),
1578 UnorderedAtomic(UnorderedAtomic), AATags(AATags),
1579 SafetyInfo(SafetyInfo),
1580 CanInsertStoresInExitBlocks(CanInsertStoresInExitBlocks), Uses(Insts) {}
1581
1582 void insertStoresInLoopExitBlocks() {
1583 // Insert stores after in the loop exit blocks. Each exit block gets a
1584 // store of the live-out values that feed them. Since we've already told
1585 // the SSA updater about the defs in the loop and the preheader
1586 // definition, it is all set and we can start using it.
1587 DIAssignID *NewID = nullptr;
1588 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
1589 BasicBlock *ExitBlock = LoopExitBlocks[i];
1590 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
1591 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
1592 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
1593 BasicBlock::iterator InsertPos = LoopInsertPts[i];
1594 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
1595 if (UnorderedAtomic)
1596 NewSI->setOrdering(AtomicOrdering::Unordered);
1597 NewSI->setAlignment(Alignment);
1598 NewSI->setDebugLoc(DL);
1599 // Attach DIAssignID metadata to the new store, generating it on the
1600 // first loop iteration.
1601 if (i == 0) {
1602 // NewSI will have its DIAssignID set here if there are any stores in
1603 // Uses with a DIAssignID attachment. This merged ID will then be
1604 // attached to the other inserted stores (in the branch below).
1605 NewSI->mergeDIAssignID(Uses);
1607 NewSI->getMetadata(LLVMContext::MD_DIAssignID));
1608 } else {
1609 // Attach the DIAssignID (or nullptr) merged from Uses in the branch
1610 // above.
1611 NewSI->setMetadata(LLVMContext::MD_DIAssignID, NewID);
1612 }
1613
1614 if (AATags)
1615 NewSI->setAAMetadata(AATags);
1616
1617 MemoryAccess *MSSAInsertPoint = MSSAInsertPts[i];
1618 MemoryAccess *NewMemAcc;
1619 if (!MSSAInsertPoint) {
1620 NewMemAcc = MSSAU.createMemoryAccessInBB(
1621 NewSI, nullptr, NewSI->getParent(), MemorySSA::Beginning);
1622 } else {
1623 NewMemAcc =
1624 MSSAU.createMemoryAccessAfter(NewSI, nullptr, MSSAInsertPoint);
1625 }
1626 MSSAInsertPts[i] = NewMemAcc;
1627 MSSAU.insertDef(cast<MemoryDef>(NewMemAcc), true);
1628 // FIXME: true for safety, false may still be correct.
1629 }
1630 }
1631
1632 void doExtraRewritesBeforeFinalDeletion() override {
1633 if (CanInsertStoresInExitBlocks)
1634 insertStoresInLoopExitBlocks();
1635 }
1636
1637 void instructionDeleted(Instruction *I) const override {
1638 SafetyInfo.removeInstruction(I);
1639 MSSAU.removeMemoryAccess(I);
1640 }
1641
1642 bool shouldDelete(Instruction *I) const override {
1643 if (isa<StoreInst>(I))
1644 return CanInsertStoresInExitBlocks;
1645 return true;
1646 }
1647};
1648
1649bool isNotCapturedBeforeOrInLoop(const Value *V, const Loop *L,
1650 DominatorTree *DT) {
1651 // We can perform the captured-before check against any instruction in the
1652 // loop header, as the loop header is reachable from any instruction inside
1653 // the loop.
1654 // TODO: ReturnCaptures=true shouldn't be necessary here.
1656 V, /*ReturnCaptures=*/true, L->getHeader()->getTerminator(), DT,
1657 /*IncludeI=*/false, CaptureComponents::Provenance));
1658}
1659
1660/// Return true if we can prove that a caller cannot inspect the object if an
1661/// unwind occurs inside the loop.
1662bool isNotVisibleOnUnwindInLoop(const Value *Object, const Loop *L,
1663 DominatorTree *DT) {
1664 bool RequiresNoCaptureBeforeUnwind;
1665 if (!isNotVisibleOnUnwind(Object, RequiresNoCaptureBeforeUnwind))
1666 return false;
1667
1668 return !RequiresNoCaptureBeforeUnwind ||
1669 isNotCapturedBeforeOrInLoop(Object, L, DT);
1670}
1671
1672bool isThreadLocalObject(const Value *Object, const Loop *L,
1673 DominatorTree *DT) {
1674 // The object must be function-local to start with, and then not captured
1675 // before/in the loop.
1676 if (isIdentifiedFunctionLocal(Object) &&
1677 isNotCapturedBeforeOrInLoop(Object, L, DT))
1678 return true;
1679
1680 // In a single-threaded environment, all objects are effectively thread-local.
1681 const Module *M = L->getHeader()->getModule();
1682 return M->getThreadModel() == ThreadModel::Single;
1683}
1684
1685} // namespace
1686
1687/// Try to promote memory values to scalars by sinking stores out of the
1688/// loop and moving loads to before the loop. We do this by looping over
1689/// the stores in the loop, looking for stores to Must pointers which are
1690/// loop invariant.
1691///
1693 const SmallSetVector<Value *, 8> &PointerMustAliases,
1698 const TargetLibraryInfo *TLI, TargetTransformInfo *TTI, Loop *CurLoop,
1699 MemorySSAUpdater &MSSAU, ICFLoopSafetyInfo *SafetyInfo,
1700 OptimizationRemarkEmitter *ORE, bool AllowSpeculation,
1701 bool HasReadsOutsideSet) {
1702 // Verify inputs.
1703 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
1704 SafetyInfo != nullptr &&
1705 "Unexpected Input to promoteLoopAccessesToScalars");
1706
1707 LLVM_DEBUG({
1708 dbgs() << "Trying to promote set of must-aliased pointers:\n";
1709 for (Value *Ptr : PointerMustAliases)
1710 dbgs() << " " << *Ptr << "\n";
1711 });
1712 ++NumPromotionCandidates;
1713
1714 Value *SomePtr = *PointerMustAliases.begin();
1715 BasicBlock *Preheader = CurLoop->getLoopPreheader();
1716
1717 // It is not safe to promote a load/store from the loop if the load/store is
1718 // conditional. For example, turning:
1719 //
1720 // for () { if (c) *P += 1; }
1721 //
1722 // into:
1723 //
1724 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
1725 //
1726 // is not safe, because *P may only be valid to access if 'c' is true.
1727 //
1728 // The safety property divides into two parts:
1729 // p1) The memory may not be dereferenceable on entry to the loop. In this
1730 // case, we can't insert the required load in the preheader.
1731 // p2) The memory model does not allow us to insert a store along any dynamic
1732 // path which did not originally have one.
1733 //
1734 // If at least one store is guaranteed to execute, both properties are
1735 // satisfied, and promotion is legal.
1736 //
1737 // This, however, is not a necessary condition. Even if no store/load is
1738 // guaranteed to execute, we can still establish these properties.
1739 // We can establish (p1) by proving that hoisting the load into the preheader
1740 // is safe (i.e. proving dereferenceability on all paths through the loop). We
1741 // can use any access within the alias set to prove dereferenceability,
1742 // since they're all must alias.
1743 //
1744 // There are two ways establish (p2):
1745 // a) Prove the location is thread-local. In this case the memory model
1746 // requirement does not apply, and stores are safe to insert.
1747 // b) Prove a store dominates every exit block. In this case, if an exit
1748 // blocks is reached, the original dynamic path would have taken us through
1749 // the store, so inserting a store into the exit block is safe. Note that this
1750 // is different from the store being guaranteed to execute. For instance,
1751 // if an exception is thrown on the first iteration of the loop, the original
1752 // store is never executed, but the exit blocks are not executed either.
1753
1754 bool DereferenceableInPH = false;
1755 bool StoreIsGuaranteedToExecute = false;
1756 bool LoadIsGuaranteedToExecute = false;
1757 bool FoundLoadToPromote = false;
1758
1759 // Goes from Unknown to either Safe or Unsafe, but can't switch between them.
1760 enum {
1761 StoreSafe,
1762 StoreUnsafe,
1763 StoreSafetyUnknown,
1764 } StoreSafety = StoreSafetyUnknown;
1765
1767
1768 // We start with an alignment of one and try to find instructions that allow
1769 // us to prove better alignment.
1770 Align Alignment;
1771 // Keep track of which types of access we see
1772 bool SawUnorderedAtomic = false;
1773 bool SawNotAtomic = false;
1774 AAMDNodes AATags;
1775
1776 const DataLayout &MDL = Preheader->getDataLayout();
1777
1778 // If there are reads outside the promoted set, then promoting stores is
1779 // definitely not safe.
1780 if (HasReadsOutsideSet)
1781 StoreSafety = StoreUnsafe;
1782
1783 if (StoreSafety == StoreSafetyUnknown && SafetyInfo->anyBlockMayThrow()) {
1784 // If a loop can throw, we have to insert a store along each unwind edge.
1785 // That said, we can't actually make the unwind edge explicit. Therefore,
1786 // we have to prove that the store is dead along the unwind edge. We do
1787 // this by proving that the caller can't have a reference to the object
1788 // after return and thus can't possibly load from the object.
1789 Value *Object = getUnderlyingObject(SomePtr);
1790 if (!isNotVisibleOnUnwindInLoop(Object, CurLoop, DT))
1791 StoreSafety = StoreUnsafe;
1792 }
1793
1794 // Check that all accesses to pointers in the alias set use the same type.
1795 // We cannot (yet) promote a memory location that is loaded and stored in
1796 // different sizes. While we are at it, collect alignment and AA info.
1797 Type *AccessTy = nullptr;
1798 for (Value *ASIV : PointerMustAliases) {
1799 for (Use &U : ASIV->uses()) {
1800 // Ignore instructions that are outside the loop.
1801 Instruction *UI = dyn_cast<Instruction>(U.getUser());
1802 if (!UI || !CurLoop->contains(UI))
1803 continue;
1804
1805 // If there is an non-load/store instruction in the loop, we can't promote
1806 // it.
1807 if (LoadInst *Load = dyn_cast<LoadInst>(UI)) {
1808 if (!Load->isUnordered())
1809 return false;
1810
1811 SawUnorderedAtomic |= Load->isAtomic();
1812 SawNotAtomic |= !Load->isAtomic();
1813 FoundLoadToPromote = true;
1814
1815 Align InstAlignment = Load->getAlign();
1816
1817 if (!LoadIsGuaranteedToExecute)
1818 LoadIsGuaranteedToExecute =
1819 SafetyInfo->isGuaranteedToExecute(*UI, DT);
1820
1821 // Note that proving a load safe to speculate requires proving
1822 // sufficient alignment at the target location. Proving it guaranteed
1823 // to execute does as well. Thus we can increase our guaranteed
1824 // alignment as well.
1825 if (!DereferenceableInPH || (InstAlignment > Alignment))
1827 *Load, DT, TLI, CurLoop, SafetyInfo, ORE,
1828 Preheader->getTerminator(), AC, AllowSpeculation)) {
1829 DereferenceableInPH = true;
1830 Alignment = std::max(Alignment, InstAlignment);
1831 }
1832 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
1833 // Stores *of* the pointer are not interesting, only stores *to* the
1834 // pointer.
1835 if (U.getOperandNo() != StoreInst::getPointerOperandIndex())
1836 continue;
1837 if (!Store->isUnordered())
1838 return false;
1839
1840 SawUnorderedAtomic |= Store->isAtomic();
1841 SawNotAtomic |= !Store->isAtomic();
1842
1843 // If the store is guaranteed to execute, both properties are satisfied.
1844 // We may want to check if a store is guaranteed to execute even if we
1845 // already know that promotion is safe, since it may have higher
1846 // alignment than any other guaranteed stores, in which case we can
1847 // raise the alignment on the promoted store.
1848 Align InstAlignment = Store->getAlign();
1849 bool GuaranteedToExecute = SafetyInfo->isGuaranteedToExecute(*UI, DT);
1850 StoreIsGuaranteedToExecute |= GuaranteedToExecute;
1851 if (GuaranteedToExecute) {
1852 DereferenceableInPH = true;
1853 if (StoreSafety == StoreSafetyUnknown)
1854 StoreSafety = StoreSafe;
1855 Alignment = std::max(Alignment, InstAlignment);
1856 }
1857
1858 // If a store dominates all exit blocks, it is safe to sink.
1859 // As explained above, if an exit block was executed, a dominating
1860 // store must have been executed at least once, so we are not
1861 // introducing stores on paths that did not have them.
1862 // Note that this only looks at explicit exit blocks. If we ever
1863 // start sinking stores into unwind edges (see above), this will break.
1864 if (StoreSafety == StoreSafetyUnknown &&
1865 llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) {
1866 return DT->dominates(Store->getParent(), Exit);
1867 }))
1868 StoreSafety = StoreSafe;
1869
1870 // If the store is not guaranteed to execute, we may still get
1871 // deref info through it.
1872 if (!DereferenceableInPH) {
1873 DereferenceableInPH = isDereferenceableAndAlignedPointer(
1874 Store->getPointerOperand(), Store->getValueOperand()->getType(),
1875 Store->getAlign(),
1876 SimplifyQuery(MDL, TLI, DT, AC, Preheader->getTerminator()));
1877 }
1878 } else
1879 continue; // Not a load or store.
1880
1881 if (!AccessTy)
1882 AccessTy = getLoadStoreType(UI);
1883 else if (AccessTy != getLoadStoreType(UI))
1884 return false;
1885
1886 // Merge the AA tags.
1887 if (LoopUses.empty()) {
1888 // On the first load/store, just take its AA tags.
1889 AATags = UI->getAAMetadata();
1890 } else if (AATags) {
1891 AATags = AATags.merge(UI->getAAMetadata());
1892 }
1893
1894 LoopUses.push_back(UI);
1895 }
1896 }
1897
1898 // If we found both an unordered atomic instruction and a non-atomic memory
1899 // access, bail. We can't blindly promote non-atomic to atomic since we
1900 // might not be able to lower the result. We can't downgrade since that
1901 // would violate memory model. Also, align 0 is an error for atomics.
1902 if (SawUnorderedAtomic && SawNotAtomic)
1903 return false;
1904
1905 // If we're inserting an atomic load in the preheader, we must be able to
1906 // lower it. We're only guaranteed to be able to lower naturally aligned
1907 // atomics.
1908 if (SawUnorderedAtomic && Alignment < MDL.getTypeStoreSize(AccessTy))
1909 return false;
1910
1911 // If we couldn't prove we can hoist the load, bail.
1912 if (!DereferenceableInPH) {
1913 LLVM_DEBUG(dbgs() << "Not promoting: Not dereferenceable in preheader\n");
1914 return false;
1915 }
1916
1917 // We know we can hoist the load, but don't have a guaranteed store.
1918 // Check whether the location is writable and thread-local. If it is, then we
1919 // can insert stores along paths which originally didn't have them without
1920 // violating the memory model.
1921 if (StoreSafety == StoreSafetyUnknown) {
1922 Value *Object = getUnderlyingObject(SomePtr);
1923 bool ExplicitlyDereferenceableOnly;
1924 // The dereferenceability query here is only required to satisfy the
1925 // writable contract, actual dereferenceability has already been proven
1926 // above. As such, we can ignore frees.
1927 if (isWritableObject(Object, ExplicitlyDereferenceableOnly) &&
1928 (!ExplicitlyDereferenceableOnly ||
1929 isDereferenceablePointer(SomePtr, AccessTy, MDL,
1930 /*IgnoreFree=*/true)) &&
1931 isThreadLocalObject(Object, CurLoop, DT))
1932 StoreSafety = StoreSafe;
1933 }
1934
1935 // If we've still failed to prove we can sink the store, hoist the load
1936 // only, if possible.
1937 if (StoreSafety != StoreSafe && !FoundLoadToPromote)
1938 // If we cannot hoist the load either, give up.
1939 return false;
1940
1941 // Lets do the promotion!
1942 if (StoreSafety == StoreSafe) {
1943 LLVM_DEBUG(dbgs() << "LICM: Promoting load/store of the value: " << *SomePtr
1944 << '\n');
1945 ++NumLoadStorePromoted;
1946 } else {
1947 LLVM_DEBUG(dbgs() << "LICM: Promoting load of the value: " << *SomePtr
1948 << '\n');
1949 ++NumLoadPromoted;
1950 }
1951
1952 ORE->emit([&]() {
1953 return OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar",
1954 LoopUses[0])
1955 << "Moving accesses to memory location out of the loop";
1956 });
1957
1958 // Look at all the loop uses, and try to merge their locations.
1959 std::vector<DebugLoc> LoopUsesLocs;
1960 for (auto U : LoopUses)
1961 LoopUsesLocs.push_back(U->getDebugLoc());
1962 auto DL = DebugLoc::getMergedLocations(LoopUsesLocs);
1963
1964 // We use the SSAUpdater interface to insert phi nodes as required.
1966 SSAUpdater SSA(&NewPHIs);
1967 LoopPromoter Promoter(SomePtr, LoopUses, SSA, ExitBlocks, InsertPts,
1968 MSSAInsertPts, PIC, MSSAU, *LI, DL, Alignment,
1969 SawUnorderedAtomic,
1970 StoreIsGuaranteedToExecute ? AATags : AAMDNodes(),
1971 *SafetyInfo, StoreSafety == StoreSafe);
1972
1973 // Set up the preheader to have a definition of the value. It is the live-out
1974 // value from the preheader that uses in the loop will use.
1975 LoadInst *PreheaderLoad = nullptr;
1976 if (FoundLoadToPromote || !StoreIsGuaranteedToExecute) {
1977 PreheaderLoad =
1978 new LoadInst(AccessTy, SomePtr, SomePtr->getName() + ".promoted",
1979 Preheader->getTerminator()->getIterator());
1980 if (SawUnorderedAtomic)
1981 PreheaderLoad->setOrdering(AtomicOrdering::Unordered);
1982 PreheaderLoad->setAlignment(Alignment);
1983 PreheaderLoad->setDebugLoc(DebugLoc::getDropped());
1984 if (AATags && LoadIsGuaranteedToExecute)
1985 PreheaderLoad->setAAMetadata(AATags);
1986
1987 MemoryAccess *PreheaderLoadMemoryAccess = MSSAU.createMemoryAccessInBB(
1988 PreheaderLoad, nullptr, PreheaderLoad->getParent(), MemorySSA::End);
1989 MemoryUse *NewMemUse = cast<MemoryUse>(PreheaderLoadMemoryAccess);
1990 MSSAU.insertUse(NewMemUse, /*RenameUses=*/true);
1991 SSA.AddAvailableValue(Preheader, PreheaderLoad);
1992 } else {
1993 SSA.AddAvailableValue(Preheader, PoisonValue::get(AccessTy));
1994 }
1995
1996 if (VerifyMemorySSA)
1997 MSSAU.getMemorySSA()->verifyMemorySSA();
1998 // Rewrite all the loads in the loop and remember all the definitions from
1999 // stores in the loop.
2000 Promoter.run(LoopUses);
2001
2002 if (VerifyMemorySSA)
2003 MSSAU.getMemorySSA()->verifyMemorySSA();
2004 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
2005 if (PreheaderLoad && PreheaderLoad->use_empty())
2006 eraseInstruction(*PreheaderLoad, *SafetyInfo, MSSAU);
2007
2008 return true;
2009}
2010
2011static void foreachMemoryAccess(MemorySSA *MSSA, Loop *L,
2012 function_ref<void(Instruction *)> Fn) {
2013 for (const BasicBlock *BB : L->blocks())
2014 if (const auto *Accesses = MSSA->getBlockAccesses(BB))
2015 for (const auto &Access : *Accesses)
2016 if (const auto *MUD = dyn_cast<MemoryUseOrDef>(&Access))
2017 Fn(MUD->getMemoryInst());
2018}
2019
2020/// Returns whether \p I is a memory access that may be a candidate for
2021/// promotion out of the loop \p L.
2022static bool isPotentiallyPromotable(const Instruction *I, const Loop *L) {
2023 if (const auto *SI = dyn_cast<StoreInst>(I)) {
2024 const Value *PtrOp = SI->getPointerOperand();
2025 if (isStrongerThanMonotonic(SI->getOrdering()))
2026 return false;
2027 return !isa<ConstantData>(PtrOp) && L->isLoopInvariant(PtrOp);
2028 }
2029 if (const auto *LI = dyn_cast<LoadInst>(I)) {
2030 const Value *PtrOp = LI->getPointerOperand();
2031 if (isStrongerThanMonotonic(LI->getOrdering()))
2032 return false;
2033 return !isa<ConstantData>(PtrOp) && L->isLoopInvariant(PtrOp);
2034 }
2035 return false;
2036}
2037
2038/// Returns the potentially promotable stores with AA tags that are valid along
2039/// all non-unwinding execution paths of the loop \p L, which allows for the AA
2040/// tags to be used when deciding promotions.
2044 StoresByLoc;
2045 foreachMemoryAccess(MSSA, L, [&](Instruction *I) {
2046 const auto *SI = dyn_cast<StoreInst>(I);
2047 if (SI && SI->getAAMetadata() && isPotentiallyPromotable(SI, L))
2048 StoresByLoc[MemoryLocation::get(SI)].push_back(SI);
2049 });
2050
2051 // This only looks at explicit exiting blocks. If we ever start sinking
2052 // stores into unwind edges, this will break.
2053 SmallVector<BasicBlock *, 4> ExitingBlocks;
2054 L->getExitingBlocks(ExitingBlocks);
2055
2056 SmallPtrSet<const StoreInst *, 8> StoresWithInvariantAATags;
2057 for (const auto &Stores : llvm::make_second_range(StoresByLoc)) {
2058 // Without exiting blocks the loop is never left, and promotion has no
2059 // exit block to insert a store into either.
2060 if (llvm::all_of(ExitingBlocks, [&](BasicBlock *ExitingBB) {
2061 return llvm::any_of(Stores, [&](const StoreInst *SI) {
2062 return DT->dominates(SI->getParent(), ExitingBB);
2063 });
2064 }))
2065 StoresWithInvariantAATags.insert_range(Stores);
2066 }
2067 return StoresWithInvariantAATags;
2068}
2069
2070// The bool indicates whether there might be reads outside the set, in which
2071// case only loads may be promoted.
2074 DominatorTree *DT, ICFLoopSafetyInfo *SafetyInfo,
2075 Loop *L) {
2076 BatchAAResults BatchAA(*AA);
2077 AliasSetTracker AST(BatchAA);
2078
2079 // Only conditionally executed stores need this, so compute it on demand to
2080 // keep the common case free.
2081 std::optional<SmallPtrSet<const StoreInst *, 8>> StoresWithInvariantAATags;
2082 auto HasInvariantAATags = [&](const StoreInst *SI) {
2083 if (!StoresWithInvariantAATags)
2084 StoresWithInvariantAATags = collectStoresWithInvariantAATags(MSSA, DT, L);
2085 return StoresWithInvariantAATags->contains(SI);
2086 };
2087
2088 // Populate AST with potentially promotable accesses.
2089 SmallPtrSet<Value *, 16> AttemptingPromotion;
2090 foreachMemoryAccess(MSSA, L, [&](Instruction *I) {
2091 if (isPotentiallyPromotable(I, L)) {
2092 AttemptingPromotion.insert(I);
2094 SI && SI->getAAMetadata() &&
2095 !SafetyInfo->isGuaranteedToExecute(*SI, DT) &&
2096 !HasInvariantAATags(SI)) {
2097 // Promotion requires inserting a new store at the loop exits; we need
2098 // to prove that store doesn't alias anything, in addition to proving
2099 // aliasing for the stores we're removing. The new store is executed
2100 // unconditionally, so when we're proving aliasing for that store, we
2101 // can only rely on AA tags that likewise hold unconditionally.
2102 AST.addWithoutAATags(SI);
2103 } else {
2104 AST.add(I);
2105 }
2106 }
2107 });
2108
2109 // We're only interested in must-alias sets that contain a mod.
2111 for (AliasSet &AS : AST)
2112 if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias())
2113 Sets.push_back({&AS, false});
2114
2115 if (Sets.empty())
2116 return {}; // Nothing to promote...
2117
2118 // Discard any sets for which there is an aliasing non-promotable access.
2119 foreachMemoryAccess(MSSA, L, [&](Instruction *I) {
2120 if (AttemptingPromotion.contains(I))
2121 return;
2122
2124 ModRefInfo MR = Pair.getPointer()->aliasesUnknownInst(I, BatchAA);
2125 // Cannot promote if there are writes outside the set.
2126 if (isModSet(MR))
2127 return true;
2128 if (isRefSet(MR)) {
2129 // Remember reads outside the set.
2130 Pair.setInt(true);
2131 // If this is a mod-only set and there are reads outside the set,
2132 // we will not be able to promote, so bail out early.
2133 return !Pair.getPointer()->isRef();
2134 }
2135 return false;
2136 });
2137 });
2138
2140 for (auto [Set, HasReadsOutsideSet] : Sets) {
2141 SmallSetVector<Value *, 8> PointerMustAliases;
2142 for (const auto &MemLoc : *Set)
2143 PointerMustAliases.insert(const_cast<Value *>(MemLoc.Ptr));
2144 Result.emplace_back(std::move(PointerMustAliases), HasReadsOutsideSet);
2145 }
2146
2147 return Result;
2148}
2149
2150// For a given store instruction or writeonly call instruction, this function
2151// checks that there are no read or writes that conflict with the memory
2152// access in the instruction
2154 AAResults *AA, Loop *CurLoop,
2155 SinkAndHoistLICMFlags &Flags) {
2157 // If there are more accesses than the Promotion cap, then give up as we're
2158 // not walking a list that long.
2159 if (Flags.tooManyMemoryAccesses())
2160 return false;
2161
2162 auto *IMD = MSSA->getMemoryAccess(I);
2163 BatchAAResults BAA(*AA);
2164 auto *Source = getClobberingMemoryAccess(*MSSA, BAA, Flags, IMD);
2165 // Make sure there are no clobbers inside the loop.
2166 if (!MSSA->isLiveOnEntryDef(Source) && CurLoop->contains(Source->getBlock()))
2167 return false;
2168
2169 // If there are interfering Uses don't move this store.
2170 // TODO: Cache set of Uses on the first walk in runOnLoop, update when
2171 // moving accesses. Can also extend to dominating uses.
2172 for (auto *BB : CurLoop->getBlocks()) {
2173 auto *Accesses = MSSA->getBlockAccesses(BB);
2174 if (!Accesses)
2175 continue;
2176 for (const auto &MA : *Accesses) {
2177 // Accesses are ordered. If we find one that I dominates we can stop.
2178 if (!Flags.getIsSink() && MSSA->dominates(IMD, &MA))
2179 break;
2180
2181 if (const auto *MemUseOrDef = dyn_cast<MemoryUseOrDef>(&MA)) {
2182 // Skip unrelated accesses.
2183 if (isNoModRef(BAA.getModRefInfo(MemUseOrDef->getMemoryInst(), I)))
2184 continue;
2185
2186 return false;
2187 }
2188 }
2189 }
2190 return true;
2191}
2192
2194 Loop *CurLoop, Instruction &I,
2195 SinkAndHoistLICMFlags &Flags,
2196 bool InvariantGroup) {
2197 // For hoisting, use the walker to determine safety
2198 if (!Flags.getIsSink()) {
2199 // If hoisting an invariant group, we only need to check that there
2200 // is no store to the loaded pointer between the start of the loop,
2201 // and the load (since all values must be the same).
2202
2203 // This can be checked in two conditions:
2204 // 1) if the memoryaccess is outside the loop
2205 // 2) the earliest access is at the loop header,
2206 // if the memory loaded is the phi node
2207
2208 BatchAAResults BAA(MSSA->getAA());
2209 MemoryAccess *Source = getClobberingMemoryAccess(*MSSA, BAA, Flags, MU);
2210 return !MSSA->isLiveOnEntryDef(Source) &&
2211 CurLoop->contains(Source->getBlock()) &&
2212 !(InvariantGroup && Source->getBlock() == CurLoop->getHeader() && isa<MemoryPhi>(Source));
2213 }
2214
2215 // For sinking, we'd need to check all Defs below this use. The getClobbering
2216 // call will look on the backedge of the loop, but will check aliasing with
2217 // the instructions on the previous iteration.
2218 // For example:
2219 // for (i ... )
2220 // load a[i] ( Use (LoE)
2221 // store a[i] ( 1 = Def (2), with 2 = Phi for the loop.
2222 // i++;
2223 // The load sees no clobbering inside the loop, as the backedge alias check
2224 // does phi translation, and will check aliasing against store a[i-1].
2225 // However sinking the load outside the loop, below the store is incorrect.
2226
2227 // For now, only sink if there are no Defs in the loop, and the existing ones
2228 // precede the use and are in the same block.
2229 // FIXME: Increase precision: Safe to sink if Use post dominates the Def;
2230 // needs PostDominatorTreeAnalysis.
2231 // FIXME: More precise: no Defs that alias this Use.
2232 if (Flags.tooManyMemoryAccesses())
2233 return true;
2234 for (auto *BB : CurLoop->getBlocks())
2235 if (pointerInvalidatedByBlock(*BB, *MSSA, *MU))
2236 return true;
2237 // When sinking, the source block may not be part of the loop so check it.
2238 if (!CurLoop->contains(&I))
2239 return pointerInvalidatedByBlock(*I.getParent(), *MSSA, *MU);
2240
2241 return false;
2242}
2243
2245 if (const auto *Accesses = MSSA.getBlockDefs(&BB))
2246 for (const auto &MA : *Accesses)
2247 if (const auto *MD = dyn_cast<MemoryDef>(&MA))
2248 if (MU.getBlock() != MD->getBlock() || !MSSA.locallyDominates(MD, &MU))
2249 return true;
2250 return false;
2251}
2252
2253/// Try to simplify things like (A < INV_1 AND icmp A < INV_2) into (A <
2254/// min(INV_1, INV_2)), if INV_1 and INV_2 are both loop invariants and their
2255/// minimun can be computed outside of loop, and X is not a loop-invariant.
2256static bool hoistMinMax(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo,
2257 MemorySSAUpdater &MSSAU) {
2258 bool Inverse = false;
2259 using namespace PatternMatch;
2260 Value *Cond1, *Cond2;
2261 if (match(&I, m_LogicalOr(m_Value(Cond1), m_Value(Cond2)))) {
2262 Inverse = true;
2263 } else if (match(&I, m_LogicalAnd(m_Value(Cond1), m_Value(Cond2)))) {
2264 // Do nothing
2265 } else
2266 return false;
2267
2268 auto MatchICmpAgainstInvariant = [&](Value *C, CmpPredicate &P, Value *&LHS,
2269 Value *&RHS) {
2270 if (!match(C, m_OneUse(m_ICmp(P, m_Value(LHS), m_Value(RHS)))))
2271 return false;
2272 if (!LHS->getType()->isIntegerTy())
2273 return false;
2275 return false;
2276 if (L.isLoopInvariant(LHS)) {
2277 std::swap(LHS, RHS);
2279 }
2280 if (L.isLoopInvariant(LHS) || !L.isLoopInvariant(RHS))
2281 return false;
2282 if (Inverse)
2284 return true;
2285 };
2286 CmpPredicate P1, P2;
2287 Value *LHS1, *LHS2, *RHS1, *RHS2;
2288 if (!MatchICmpAgainstInvariant(Cond1, P1, LHS1, RHS1) ||
2289 !MatchICmpAgainstInvariant(Cond2, P2, LHS2, RHS2))
2290 return false;
2291 auto MatchingPred = CmpPredicate::getMatching(P1, P2);
2292 if (!MatchingPred || LHS1 != LHS2)
2293 return false;
2294
2295 // Everything is fine, we can do the transform.
2296 bool UseMin = ICmpInst::isLT(*MatchingPred) || ICmpInst::isLE(*MatchingPred);
2297 assert(
2298 (UseMin || ICmpInst::isGT(*MatchingPred) ||
2299 ICmpInst::isGE(*MatchingPred)) &&
2300 "Relational predicate is either less (or equal) or greater (or equal)!");
2301 Intrinsic::ID id = ICmpInst::isSigned(*MatchingPred)
2302 ? (UseMin ? Intrinsic::smin : Intrinsic::smax)
2303 : (UseMin ? Intrinsic::umin : Intrinsic::umax);
2304 auto *Preheader = L.getLoopPreheader();
2305 assert(Preheader && "Loop is not in simplify form?");
2306 IRBuilder<> Builder(Preheader->getTerminator());
2307 // We are about to create a new guaranteed use for RHS2 which might not exist
2308 // before (if it was a non-taken input of logical and/or instruction). If it
2309 // was poison, we need to freeze it. Note that no new use for LHS and RHS1 are
2310 // introduced, so they don't need this.
2311 if (isa<SelectInst>(I))
2312 RHS2 = Builder.CreateFreeze(RHS2, RHS2->getName() + ".fr");
2313 Value *NewRHS = Builder.CreateBinaryIntrinsic(
2314 id, RHS1, RHS2, nullptr,
2315 StringRef("invariant.") +
2316 (ICmpInst::isSigned(*MatchingPred) ? "s" : "u") +
2317 (UseMin ? "min" : "max"));
2318 Builder.SetInsertPoint(&I);
2319 ICmpInst::Predicate P = *MatchingPred;
2320 if (Inverse)
2322 Value *NewCond = Builder.CreateICmp(P, LHS1, NewRHS);
2323 NewCond->takeName(&I);
2324 I.replaceAllUsesWith(NewCond);
2325 eraseInstruction(I, SafetyInfo, MSSAU);
2326 Instruction &CondI1 = *cast<Instruction>(Cond1);
2327 Instruction &CondI2 = *cast<Instruction>(Cond2);
2328 salvageDebugInfo(CondI1);
2329 salvageDebugInfo(CondI2);
2330 eraseInstruction(CondI1, SafetyInfo, MSSAU);
2331 eraseInstruction(CondI2, SafetyInfo, MSSAU);
2332 return true;
2333}
2334
2335/// Reassociate gep (gep ptr, idx1), idx2 to gep (gep ptr, idx2), idx1 if
2336/// this allows hoisting the inner GEP.
2337static bool hoistGEP(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo,
2339 DominatorTree *DT) {
2341 if (!GEP)
2342 return false;
2343
2344 // Do not try to hoist a constant GEP out of the loop via reassociation.
2345 // Constant GEPs can often be folded into addressing modes, and reassociating
2346 // them may inhibit CSE of a common base.
2347 if (GEP->hasAllConstantIndices())
2348 return false;
2349
2350 auto *Src = dyn_cast<GetElementPtrInst>(GEP->getPointerOperand());
2351 if (!Src || !Src->hasOneUse() || !L.contains(Src))
2352 return false;
2353
2354 Value *SrcPtr = Src->getPointerOperand();
2355 auto LoopInvariant = [&](Value *V) { return L.isLoopInvariant(V); };
2356 if (!L.isLoopInvariant(SrcPtr) || !all_of(GEP->indices(), LoopInvariant))
2357 return false;
2358
2359 // This can only happen if !AllowSpeculation, otherwise this would already be
2360 // handled.
2361 // FIXME: Should we respect AllowSpeculation in these reassociation folds?
2362 // The flag exists to prevent metadata dropping, which is not relevant here.
2363 if (all_of(Src->indices(), LoopInvariant))
2364 return false;
2365
2366 // The swapped GEPs are inbounds if both original GEPs are inbounds
2367 // and the sign of the offsets is the same. For simplicity, only
2368 // handle both offsets being non-negative.
2369 const DataLayout &DL = GEP->getDataLayout();
2370 auto NonNegative = [&](Value *V) {
2371 return isKnownNonNegative(V, SimplifyQuery(DL, DT, AC, GEP));
2372 };
2373 bool IsInBounds = Src->isInBounds() && GEP->isInBounds() &&
2374 all_of(Src->indices(), NonNegative) &&
2375 all_of(GEP->indices(), NonNegative);
2376
2377 BasicBlock *Preheader = L.getLoopPreheader();
2378 IRBuilder<> Builder(Preheader->getTerminator());
2379 Value *NewSrc = Builder.CreateGEP(GEP->getSourceElementType(), SrcPtr,
2380 SmallVector<Value *>(GEP->indices()),
2381 "invariant.gep", IsInBounds);
2382 Builder.SetInsertPoint(GEP);
2383 Value *NewGEP = Builder.CreateGEP(Src->getSourceElementType(), NewSrc,
2384 SmallVector<Value *>(Src->indices()), "gep",
2385 IsInBounds);
2386 GEP->replaceAllUsesWith(NewGEP);
2387 eraseInstruction(*GEP, SafetyInfo, MSSAU);
2388 salvageDebugInfo(*Src);
2389 eraseInstruction(*Src, SafetyInfo, MSSAU);
2390 return true;
2391}
2392
2393/// Try to turn things like "LV + C1 < C2" into "LV < C2 - C1". Here
2394/// C1 and C2 are loop invariants and LV is a loop-variant.
2395static bool hoistAdd(ICmpInst::Predicate Pred, Value *VariantLHS,
2396 Value *InvariantRHS, ICmpInst &ICmp, Loop &L,
2397 ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU,
2398 AssumptionCache *AC, DominatorTree *DT) {
2399 assert(!L.isLoopInvariant(VariantLHS) && "Precondition.");
2400 assert(L.isLoopInvariant(InvariantRHS) && "Precondition.");
2401
2402 bool IsSigned = ICmpInst::isSigned(Pred);
2403
2404 // Try to represent VariantLHS as sum of invariant and variant operands.
2405 using namespace PatternMatch;
2406 Value *VariantOp, *InvariantOp;
2407 if (IsSigned && !match(VariantLHS, m_NSWAddLike(m_Value(VariantOp),
2408 m_Value(InvariantOp))))
2409 return false;
2410 if (!IsSigned && !match(VariantLHS, m_NUWAddLike(m_Value(VariantOp),
2411 m_Value(InvariantOp))))
2412 return false;
2413
2414 // LHS itself is a loop-variant, try to represent it in the form:
2415 // "VariantOp + InvariantOp". If it is possible, then we can reassociate.
2416 if (L.isLoopInvariant(VariantOp))
2417 std::swap(VariantOp, InvariantOp);
2418 if (L.isLoopInvariant(VariantOp) || !L.isLoopInvariant(InvariantOp))
2419 return false;
2420
2421 // In order to turn "LV + C1 < C2" into "LV < C2 - C1", we need to be able to
2422 // freely move values from left side of inequality to right side (just as in
2423 // normal linear arithmetics). Overflows make things much more complicated, so
2424 // we want to avoid this.
2425 auto &DL = L.getHeader()->getDataLayout();
2426 SimplifyQuery SQ(DL, DT, AC, &ICmp);
2427 if (IsSigned && computeOverflowForSignedSub(InvariantRHS, InvariantOp, SQ) !=
2429 return false;
2430 if (!IsSigned &&
2431 computeOverflowForUnsignedSub(InvariantRHS, InvariantOp, SQ) !=
2433 return false;
2434 auto *Preheader = L.getLoopPreheader();
2435 assert(Preheader && "Loop is not in simplify form?");
2436 IRBuilder<> Builder(Preheader->getTerminator());
2437 Value *NewCmpOp =
2438 Builder.CreateSub(InvariantRHS, InvariantOp, "invariant.op",
2439 /*HasNUW*/ !IsSigned, /*HasNSW*/ IsSigned);
2440 ICmp.setPredicate(Pred);
2441 ICmp.setOperand(0, VariantOp);
2442 ICmp.setOperand(1, NewCmpOp);
2443 // The new LHS is a different value, so a samesign (or any other
2444 // poison-generating) flag asserted about the old operands may no longer hold.
2446
2447 Instruction &DeadI = cast<Instruction>(*VariantLHS);
2448 salvageDebugInfo(DeadI);
2449 eraseInstruction(DeadI, SafetyInfo, MSSAU);
2450 return true;
2451}
2452
2453/// Try to reassociate and hoist the following two patterns:
2454/// LV - C1 < C2 --> LV < C1 + C2,
2455/// C1 - LV < C2 --> LV > C1 - C2.
2456static bool hoistSub(ICmpInst::Predicate Pred, Value *VariantLHS,
2457 Value *InvariantRHS, ICmpInst &ICmp, Loop &L,
2458 ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU,
2459 AssumptionCache *AC, DominatorTree *DT) {
2460 assert(!L.isLoopInvariant(VariantLHS) && "Precondition.");
2461 assert(L.isLoopInvariant(InvariantRHS) && "Precondition.");
2462
2463 bool IsSigned = ICmpInst::isSigned(Pred);
2464
2465 // Try to represent VariantLHS as sum of invariant and variant operands.
2466 using namespace PatternMatch;
2467 Value *VariantOp, *InvariantOp;
2468 if (IsSigned &&
2469 !match(VariantLHS, m_NSWSub(m_Value(VariantOp), m_Value(InvariantOp))))
2470 return false;
2471 if (!IsSigned &&
2472 !match(VariantLHS, m_NUWSub(m_Value(VariantOp), m_Value(InvariantOp))))
2473 return false;
2474
2475 bool VariantSubtracted = false;
2476 // LHS itself is a loop-variant, try to represent it in the form:
2477 // "VariantOp + InvariantOp". If it is possible, then we can reassociate. If
2478 // the variant operand goes with minus, we use a slightly different scheme.
2479 if (L.isLoopInvariant(VariantOp)) {
2480 std::swap(VariantOp, InvariantOp);
2481 VariantSubtracted = true;
2482 Pred = ICmpInst::getSwappedPredicate(Pred);
2483 }
2484 if (L.isLoopInvariant(VariantOp) || !L.isLoopInvariant(InvariantOp))
2485 return false;
2486
2487 // In order to turn "LV - C1 < C2" into "LV < C2 + C1", we need to be able to
2488 // freely move values from left side of inequality to right side (just as in
2489 // normal linear arithmetics). Overflows make things much more complicated, so
2490 // we want to avoid this. Likewise, for "C1 - LV < C2" we need to prove that
2491 // "C1 - C2" does not overflow.
2492 auto &DL = L.getHeader()->getDataLayout();
2493 SimplifyQuery SQ(DL, DT, AC, &ICmp);
2494 if (VariantSubtracted && IsSigned) {
2495 // C1 - LV < C2 --> LV > C1 - C2
2496 if (computeOverflowForSignedSub(InvariantOp, InvariantRHS, SQ) !=
2498 return false;
2499 } else if (VariantSubtracted && !IsSigned) {
2500 // C1 - LV < C2 --> LV > C1 - C2
2501 if (computeOverflowForUnsignedSub(InvariantOp, InvariantRHS, SQ) !=
2503 return false;
2504 } else if (!VariantSubtracted && IsSigned) {
2505 // LV - C1 < C2 --> LV < C1 + C2
2506 if (computeOverflowForSignedAdd(InvariantOp, InvariantRHS, SQ) !=
2508 return false;
2509 } else { // !VariantSubtracted && !IsSigned
2510 // LV - C1 < C2 --> LV < C1 + C2
2511 if (computeOverflowForUnsignedAdd(InvariantOp, InvariantRHS, SQ) !=
2513 return false;
2514 }
2515 auto *Preheader = L.getLoopPreheader();
2516 assert(Preheader && "Loop is not in simplify form?");
2517 IRBuilder<> Builder(Preheader->getTerminator());
2518 Value *NewCmpOp =
2519 VariantSubtracted
2520 ? Builder.CreateSub(InvariantOp, InvariantRHS, "invariant.op",
2521 /*HasNUW*/ !IsSigned, /*HasNSW*/ IsSigned)
2522 : Builder.CreateAdd(InvariantOp, InvariantRHS, "invariant.op",
2523 /*HasNUW*/ !IsSigned, /*HasNSW*/ IsSigned);
2524 ICmp.setPredicate(Pred);
2525 ICmp.setOperand(0, VariantOp);
2526 ICmp.setOperand(1, NewCmpOp);
2527 // The new LHS is a different value, so a samesign (or any other
2528 // poison-generating) flag asserted about the old operands may no longer hold.
2530
2531 Instruction &DeadI = cast<Instruction>(*VariantLHS);
2532 salvageDebugInfo(DeadI);
2533 eraseInstruction(DeadI, SafetyInfo, MSSAU);
2534 return true;
2535}
2536
2537/// Reassociate and hoist add/sub expressions.
2538static bool hoistAddSub(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo,
2540 DominatorTree *DT) {
2541 using namespace PatternMatch;
2542 CmpPredicate Pred;
2543 Value *LHS, *RHS;
2544 if (!match(&I, m_ICmp(Pred, m_Value(LHS), m_Value(RHS))))
2545 return false;
2546
2547 // Put variant operand to LHS position.
2548 if (L.isLoopInvariant(LHS)) {
2549 std::swap(LHS, RHS);
2550 Pred = ICmpInst::getSwappedPredicate(Pred);
2551 }
2552 // We want to delete the initial operation after reassociation, so only do it
2553 // if it has no other uses.
2554 if (L.isLoopInvariant(LHS) || !L.isLoopInvariant(RHS) || !LHS->hasOneUse())
2555 return false;
2556
2557 // TODO: We could go with smarter context, taking common dominator of all I's
2558 // users instead of I itself.
2559 if (hoistAdd(Pred, LHS, RHS, cast<ICmpInst>(I), L, SafetyInfo, MSSAU, AC, DT))
2560 return true;
2561
2562 if (hoistSub(Pred, LHS, RHS, cast<ICmpInst>(I), L, SafetyInfo, MSSAU, AC, DT))
2563 return true;
2564
2565 return false;
2566}
2567
2568static bool isReassociableOp(Instruction *I, unsigned IntOpcode,
2569 unsigned FPOpcode) {
2570 if (I->getOpcode() == IntOpcode)
2571 return true;
2572 if (I->getOpcode() == FPOpcode && I->hasAllowReassoc() &&
2573 I->hasNoSignedZeros())
2574 return true;
2575 return false;
2576}
2577
2578/// Try to reassociate expressions like ((A1 * B1) + (A2 * B2) + ...) * C where
2579/// A1, A2, ... and C are loop invariants into expressions like
2580/// ((A1 * C * B1) + (A2 * C * B2) + ...) and hoist the (A1 * C), (A2 * C), ...
2581/// invariant expressions. This functions returns true only if any hoisting has
2582/// actually occurred.
2584 ICFLoopSafetyInfo &SafetyInfo,
2586 DominatorTree *DT) {
2587 if (!isReassociableOp(&I, Instruction::Mul, Instruction::FMul))
2588 return false;
2589 Value *VariantOp = I.getOperand(0);
2590 Value *InvariantOp = I.getOperand(1);
2591 if (L.isLoopInvariant(VariantOp))
2592 std::swap(VariantOp, InvariantOp);
2593 if (L.isLoopInvariant(VariantOp) || !L.isLoopInvariant(InvariantOp))
2594 return false;
2595 Value *Factor = InvariantOp;
2596
2597 // First, we need to make sure we should do the transformation.
2598 SmallVector<Use *> Changes;
2601 if (BinaryOperator *VariantBinOp = dyn_cast<BinaryOperator>(VariantOp))
2602 Worklist.push_back(VariantBinOp);
2603 while (!Worklist.empty()) {
2604 BinaryOperator *BO = Worklist.pop_back_val();
2605 if (!BO->hasOneUse())
2606 return false;
2607 if (isReassociableOp(BO, Instruction::Add, Instruction::FAdd) &&
2610 Worklist.push_back(cast<BinaryOperator>(BO->getOperand(0)));
2611 Worklist.push_back(cast<BinaryOperator>(BO->getOperand(1)));
2612 Adds.push_back(BO);
2613 continue;
2614 }
2615 if (!isReassociableOp(BO, Instruction::Mul, Instruction::FMul) ||
2616 L.isLoopInvariant(BO))
2617 return false;
2618 Use &U0 = BO->getOperandUse(0);
2619 Use &U1 = BO->getOperandUse(1);
2620 if (L.isLoopInvariant(U0))
2621 Changes.push_back(&U0);
2622 else if (L.isLoopInvariant(U1))
2623 Changes.push_back(&U1);
2624 else
2625 return false;
2626 unsigned Limit = I.getType()->isIntOrIntVectorTy()
2629 if (Changes.size() > Limit)
2630 return false;
2631 }
2632 if (Changes.empty())
2633 return false;
2634
2635 // Drop the poison flags for any adds we looked through.
2636 if (I.getType()->isIntOrIntVectorTy()) {
2637 for (auto *Add : Adds)
2638 Add->dropPoisonGeneratingFlags();
2639 }
2640
2641 // We know we should do it so let's do the transformation.
2642 auto *Preheader = L.getLoopPreheader();
2643 assert(Preheader && "Loop is not in simplify form?");
2644 IRBuilder<> Builder(Preheader->getTerminator());
2645 for (auto *U : Changes) {
2646 assert(L.isLoopInvariant(U->get()));
2647 auto *Ins = cast<BinaryOperator>(U->getUser());
2648 Value *Mul;
2649 if (I.getType()->isIntOrIntVectorTy()) {
2650 Mul = Builder.CreateMul(U->get(), Factor, "factor.op.mul");
2651 // Drop the poison flags on the original multiply.
2652 Ins->dropPoisonGeneratingFlags();
2653 } else
2654 Mul = Builder.CreateFMulFMF(U->get(), Factor, Ins, "factor.op.fmul");
2655
2656 // Rewrite the reassociable instruction.
2657 unsigned OpIdx = U->getOperandNo();
2658 auto *LHS = OpIdx == 0 ? Mul : Ins->getOperand(0);
2659 auto *RHS = OpIdx == 1 ? Mul : Ins->getOperand(1);
2660 auto *NewBO =
2661 BinaryOperator::Create(Ins->getOpcode(), LHS, RHS,
2662 Ins->getName() + ".reass", Ins->getIterator());
2663 NewBO->setDebugLoc(DebugLoc::getDropped());
2664 NewBO->copyIRFlags(Ins);
2665 if (VariantOp == Ins)
2666 VariantOp = NewBO;
2667 Ins->replaceAllUsesWith(NewBO);
2668 eraseInstruction(*Ins, SafetyInfo, MSSAU);
2669 }
2670
2671 I.replaceAllUsesWith(VariantOp);
2672 eraseInstruction(I, SafetyInfo, MSSAU);
2673 return true;
2674}
2675
2676/// Reassociate associative binary expressions of the form
2677///
2678/// 1. "(LV op C1) op C2" ==> "LV op (C1 op C2)"
2679/// 2. "(C1 op LV) op C2" ==> "LV op (C1 op C2)"
2680/// 3. "C2 op (C1 op LV)" ==> "LV op (C1 op C2)"
2681/// 4. "C2 op (LV op C1)" ==> "LV op (C1 op C2)"
2682///
2683/// where op is an associative BinOp, LV is a loop variant, and C1 and C2 are
2684/// loop invariants that we want to hoist, noting that associativity implies
2685/// commutativity.
2687 ICFLoopSafetyInfo &SafetyInfo,
2689 DominatorTree *DT) {
2690 auto *BO = dyn_cast<BinaryOperator>(&I);
2691 if (!BO || !BO->isAssociative())
2692 return false;
2693
2694 Instruction::BinaryOps Opcode = BO->getOpcode();
2695 bool LVInRHS = L.isLoopInvariant(BO->getOperand(0));
2696 auto *BO0 = dyn_cast<BinaryOperator>(BO->getOperand(LVInRHS));
2697 if (!BO0 || BO0->getOpcode() != Opcode || !BO0->isAssociative() ||
2698 BO0->hasNUsesOrMore(BO0->getType()->isIntegerTy() ? 2 : 3))
2699 return false;
2700
2701 Value *LV = BO0->getOperand(0);
2702 Value *C1 = BO0->getOperand(1);
2703 Value *C2 = BO->getOperand(!LVInRHS);
2704
2705 assert(BO->isCommutative() && BO0->isCommutative() &&
2706 "Associativity implies commutativity");
2707 if (L.isLoopInvariant(LV) && !L.isLoopInvariant(C1))
2708 std::swap(LV, C1);
2709 if (L.isLoopInvariant(LV) || !L.isLoopInvariant(C1) || !L.isLoopInvariant(C2))
2710 return false;
2711
2712 auto *Preheader = L.getLoopPreheader();
2713 assert(Preheader && "Loop is not in simplify form?");
2714
2715 IRBuilder<> Builder(Preheader->getTerminator());
2716 auto *Inv = Builder.CreateBinOp(Opcode, C1, C2, "invariant.op");
2717
2718 auto *NewBO = BinaryOperator::Create(
2719 Opcode, LV, Inv, BO->getName() + ".reass", BO->getIterator());
2720 NewBO->setDebugLoc(DebugLoc::getDropped());
2721
2722 if (Opcode == Instruction::FAdd || Opcode == Instruction::FMul) {
2723 // Intersect FMF flags for FADD and FMUL.
2724 FastMathFlags Intersect = BO->getFastMathFlags() & BO0->getFastMathFlags();
2725 if (auto *I = dyn_cast<Instruction>(Inv))
2726 I->setFastMathFlags(Intersect);
2727 NewBO->setFastMathFlags(Intersect);
2728 } else {
2729 OverflowTracking Flags;
2730 Flags.AllKnownNonNegative = false;
2731 Flags.AllKnownNonZero = false;
2732 Flags.mergeFlags(*BO);
2733 Flags.mergeFlags(*BO0);
2734 // If `Inv` was not constant-folded, a new Instruction has been created.
2735 if (auto *I = dyn_cast<Instruction>(Inv))
2736 Flags.applyFlags(*I);
2737 Flags.applyFlags(*NewBO);
2738 }
2739
2740 BO->replaceAllUsesWith(NewBO);
2741 eraseInstruction(*BO, SafetyInfo, MSSAU);
2742
2743 // (LV op C1) might not be erased if it has more uses than the one we just
2744 // replaced.
2745 if (BO0->use_empty()) {
2746 salvageDebugInfo(*BO0);
2747 eraseInstruction(*BO0, SafetyInfo, MSSAU);
2748 }
2749
2750 return true;
2751}
2752
2753/// Reassociate add/sub expressions of the form:
2754///
2755/// 1. "(LV + C1) - C2" ==> "LV + (C1 - C2)"
2756/// 2. "(LV - C1) - C2" ==> "LV - (C1 + C2)"
2757/// 3. "(LV - C1) + C2" ==> "LV + (C2 - C1)"
2758///
2759/// where LV is a loop variant, and C1 and C2 are loop invariants.
2760/// Sub is not associative, but these algebraic identities allow hoisting
2761/// invariant computations out of the loop.
2763 ICFLoopSafetyInfo &SafetyInfo,
2765 DominatorTree *DT) {
2766 using namespace PatternMatch;
2767
2768 Instruction *BO;
2769 Value *LV, *C1, *C2;
2770 Instruction::BinaryOps InvOp, ResultOp;
2771
2772 // Try to match one of three reassociation patterns involving sub.
2773 //
2774 // 1. (LV + C1) - C2 ==> LV + (C1 - C2)
2775 // 2. (LV - C1) - C2 ==> LV - (C1 + C2)
2776 // 3. (LV - C1) + C2 ==> LV + (C2 - C1)
2777 // ^ ^
2778 // \ \___ InvOp
2779 // \
2780 // \____ ResultOp
2781 //
2782 if (match(&I,
2784 m_Value(C2)))) {
2785 // Case 1.
2786 //
2787 // Depending on which of the addition is invariant, we might need to swap
2788 // the arguments
2789 if (L.isLoopInvariant(LV) && !L.isLoopInvariant(C1))
2790 std::swap(LV, C1);
2791 InvOp = Instruction::Sub;
2792 ResultOp = Instruction::Add;
2793 } else if (match(&I, m_Sub(m_OneUse(m_Instruction(
2794 BO, m_Sub(m_Value(LV), m_Value(C1)))),
2795 m_Value(C2)))) {
2796 // Case 2.
2797 InvOp = Instruction::Add;
2798 ResultOp = Instruction::Sub;
2799 } else if (match(&I, m_c_Add(m_OneUse(m_Instruction(
2800 BO, m_Sub(m_Value(LV), m_Value(C1)))),
2801 m_Value(C2)))) {
2802 // Case 3.
2803 //
2804 // We use (C2 - C1) as the invariant as opposed to case 1, but instead of
2805 // adding a special case in invariant creation, we can just swap the
2806 // operands here.
2807 std::swap(C1, C2);
2808 InvOp = Instruction::Sub;
2809 ResultOp = Instruction::Add;
2810 } else {
2811 return false;
2812 }
2813
2814 if (L.isLoopInvariant(LV) || !L.isLoopInvariant(C1) || !L.isLoopInvariant(C2))
2815 return false;
2816
2817 auto *Preheader = L.getLoopPreheader();
2818 assert(Preheader && "Loop is not in simplify form?");
2819
2820 IRBuilder<> Builder(Preheader->getTerminator());
2821 auto *Inv = Builder.CreateBinOp(InvOp, C1, C2, "invariant.op");
2822
2823 auto *NewBO = BinaryOperator::Create(ResultOp, LV, Inv,
2824 I.getName() + ".reass", I.getIterator());
2825 NewBO->setDebugLoc(DebugLoc::getDropped());
2826
2827 // No overflow flags are set on the new instructions -- reassociation
2828 // involving sub does not preserve nsw/nuw in general.
2829
2830 I.replaceAllUsesWith(NewBO);
2831 eraseInstruction(I, SafetyInfo, MSSAU);
2832
2833 salvageDebugInfo(*BO);
2834 eraseInstruction(*BO, SafetyInfo, MSSAU);
2835
2836 return true;
2837}
2838
2840 ICFLoopSafetyInfo &SafetyInfo,
2842 DominatorTree *DT) {
2843 // Optimize complex patterns, such as (x < INV1 && x < INV2), turning them
2844 // into (x < min(INV1, INV2)), and hoisting the invariant part of this
2845 // expression out of the loop.
2846 if (hoistMinMax(I, L, SafetyInfo, MSSAU)) {
2847 ++NumHoisted;
2848 ++NumMinMaxHoisted;
2849 return true;
2850 }
2851
2852 // Try to hoist GEPs by reassociation.
2853 if (hoistGEP(I, L, SafetyInfo, MSSAU, AC, DT)) {
2854 ++NumHoisted;
2855 ++NumGEPsHoisted;
2856 return true;
2857 }
2858
2859 // Try to hoist add/sub's by reassociation.
2860 if (hoistAddSub(I, L, SafetyInfo, MSSAU, AC, DT)) {
2861 ++NumHoisted;
2862 ++NumAddSubHoisted;
2863 return true;
2864 }
2865
2866 bool IsInt = I.getType()->isIntOrIntVectorTy();
2867 if (hoistMulAddAssociation(I, L, SafetyInfo, MSSAU, AC, DT)) {
2868 ++NumHoisted;
2869 if (IsInt)
2870 ++NumIntAssociationsHoisted;
2871 else
2872 ++NumFPAssociationsHoisted;
2873 return true;
2874 }
2875
2876 if (hoistBOAssociation(I, L, SafetyInfo, MSSAU, AC, DT)) {
2877 ++NumHoisted;
2878 ++NumBOAssociationsHoisted;
2879 return true;
2880 }
2881
2882 if (hoistSubAddAssociation(I, L, SafetyInfo, MSSAU, AC, DT)) {
2883 ++NumHoisted;
2884 ++NumBOAssociationsHoisted;
2885 return true;
2886 }
2887
2888 return false;
2889}
2890
2891/// Little predicate that returns true if the specified basic block is in
2892/// a subloop of the current one, not the current one itself.
2893///
2894static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
2895 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
2896 return LI->getLoopFor(BB) != CurLoop;
2897}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
unsigned uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
DXIL Forward Handle Accesses
DXIL Resource Access
This file defines the DenseMap class.
early cse Early CSE w MemorySSA
#define DEBUG_TYPE
Hexagon Common GEP
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
iv Induction Variable Users
Definition IVUsers.cpp:48
static bool isReassociableOp(Instruction *I, unsigned IntOpcode, unsigned FPOpcode)
Definition LICM.cpp:2568
static bool isNotUsedOrFoldableInLoop(const Instruction &I, const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo, TargetTransformInfo *TTI, bool &FoldableInLoop, bool LoopNestMode)
Return true if the only users of this instruction are outside of the loop.
Definition LICM.cpp:1106
static bool hoistGEP(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, AssumptionCache *AC, DominatorTree *DT)
Reassociate gep (gep ptr, idx1), idx2 to gep (gep ptr, idx2), idx1 if this allows hoisting the inner ...
Definition LICM.cpp:2337
static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT, LoopInfo *LI, const Loop *CurLoop, LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU)
Definition LICM.cpp:1281
static cl::opt< unsigned > FPAssociationUpperLimit("licm-max-num-fp-reassociations", cl::init(5U), cl::Hidden, cl::desc("Set upper limit for the number of transformations performed " "during a single round of hoisting the reassociated expressions."))
static bool isFoldableInLoop(const Instruction &I, const Loop *CurLoop, const TargetTransformInfo *TTI)
Return true if the instruction is foldable in the loop.
Definition LICM.cpp:1076
static SmallPtrSet< const StoreInst *, 8 > collectStoresWithInvariantAATags(MemorySSA *MSSA, DominatorTree *DT, Loop *L)
Returns the potentially promotable stores with AA tags that are valid along all non-unwinding executi...
Definition LICM.cpp:2042
static bool hoistMinMax(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU)
Try to simplify things like (A < INV_1 AND icmp A < INV_2) into (A < min(INV_1, INV_2)),...
Definition LICM.cpp:2256
static void moveInstructionBefore(Instruction &I, BasicBlock::iterator Dest, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, ScalarEvolution *SE)
Definition LICM.cpp:1233
static Instruction * cloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI, const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater &MSSAU)
Definition LICM.cpp:1149
static bool pointerInvalidatedByLoop(MemorySSA *MSSA, MemoryUse *MU, Loop *CurLoop, Instruction &I, SinkAndHoistLICMFlags &Flags, bool InvariantGroup)
Definition LICM.cpp:2193
static bool hoistSubAddAssociation(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, AssumptionCache *AC, DominatorTree *DT)
Reassociate add/sub expressions of the form:
Definition LICM.cpp:2762
static SmallVector< PointersAndHasReadsOutsideSet, 0 > collectPromotionCandidates(MemorySSA *MSSA, AliasAnalysis *AA, DominatorTree *DT, ICFLoopSafetyInfo *SafetyInfo, Loop *L)
Definition LICM.cpp:2073
static bool hoistAdd(ICmpInst::Predicate Pred, Value *VariantLHS, Value *InvariantRHS, ICmpInst &ICmp, Loop &L, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, AssumptionCache *AC, DominatorTree *DT)
Try to turn things like "LV + C1 < C2" into "LV < C2 - C1".
Definition LICM.cpp:2395
static MemoryAccess * getClobberingMemoryAccess(MemorySSA &MSSA, BatchAAResults &BAA, SinkAndHoistLICMFlags &Flags, MemoryUseOrDef *MA)
Definition LICM.cpp:918
static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo, MemorySSAUpdater &MSSAU, ScalarEvolution *SE, OptimizationRemarkEmitter *ORE)
When an instruction is found to only use loop invariant operands that is safe to hoist,...
Definition LICM.cpp:1460
static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo)
Definition LICM.cpp:1263
static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT, const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo, MemorySSAUpdater &MSSAU, OptimizationRemarkEmitter *ORE)
When an instruction is found to only be used outside of the loop, this function moves it to the exit ...
Definition LICM.cpp:1353
static bool isPotentiallyPromotable(const Instruction *I, const Loop *L)
Returns whether I is a memory access that may be a candidate for promotion out of the loop L.
Definition LICM.cpp:2022
static bool hoistAddSub(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, AssumptionCache *AC, DominatorTree *DT)
Reassociate and hoist add/sub expressions.
Definition LICM.cpp:2538
static bool hoistMulAddAssociation(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, AssumptionCache *AC, DominatorTree *DT)
Try to reassociate expressions like ((A1 * B1) + (A2 * B2) + ...) * C where A1, A2,...
Definition LICM.cpp:2583
static cl::opt< uint32_t > MaxNumUsesTraversed("licm-max-num-uses-traversed", cl::Hidden, cl::init(8), cl::desc("Max num uses visited for identifying load " "invariance in loop using invariant start (default = 8)"))
static bool isOnlyMemoryAccess(const Instruction *I, const Loop *L, const MemorySSAUpdater &MSSAU)
Return true if I is the only Instruction with a MemoryAccess in L.
Definition LICM.cpp:902
static cl::opt< unsigned > IntAssociationUpperLimit("licm-max-num-int-reassociations", cl::init(5U), cl::Hidden, cl::desc("Set upper limit for the number of transformations performed " "during a single round of hoisting the reassociated expressions."))
static void foreachMemoryAccess(MemorySSA *MSSA, Loop *L, function_ref< void(Instruction *)> Fn)
Definition LICM.cpp:2011
static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT, Loop *CurLoop)
Definition LICM.cpp:833
static bool hoistInsertPastInsert(InsertElementInst *Ins, Loop *CurLoop, DominatorTree *DT, BasicBlock *HoistDest, ICFLoopSafetyInfo *SafetyInfo, MemorySSAUpdater &MSSAU, ScalarEvolution *SE, OptimizationRemarkEmitter *ORE)
Definition LICM.cpp:774
static bool isHoistableAndSinkableInst(Instruction &I)
Return true if-and-only-if we know how to (mechanically) both hoist and sink a given instruction out ...
Definition LICM.cpp:890
static Instruction * sinkThroughTriviallyReplaceablePHI(PHINode *TPN, Instruction *I, LoopInfo *LI, SmallDenseMap< BasicBlock *, Instruction *, 32 > &SunkCopies, const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop, MemorySSAUpdater &MSSAU)
Definition LICM.cpp:1248
static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI)
Little predicate that returns true if the specified basic block is in a subloop of the current one,...
Definition LICM.cpp:2894
static bool hoistSub(ICmpInst::Predicate Pred, Value *VariantLHS, Value *InvariantRHS, ICmpInst &ICmp, Loop &L, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, AssumptionCache *AC, DominatorTree *DT)
Try to reassociate and hoist the following two patterns: LV - C1 < C2 --> LV < C1 + C2,...
Definition LICM.cpp:2456
static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU)
Definition LICM.cpp:1226
static bool isSafeToExecuteUnconditionally(Instruction &Inst, const DominatorTree *DT, const TargetLibraryInfo *TLI, const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE, const Instruction *CtxI, AssumptionCache *AC, bool AllowSpeculation)
Only sink or hoist an instruction if it is not a trapping instruction, or if the instruction is known...
Definition LICM.cpp:1507
static bool hoistArithmetics(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, AssumptionCache *AC, DominatorTree *DT)
Aggregates various functions for hoisting computations out of loop.
Definition LICM.cpp:2839
static bool noConflictingReadWrites(Instruction *I, MemorySSA *MSSA, AAResults *AA, Loop *CurLoop, SinkAndHoistLICMFlags &Flags)
Definition LICM.cpp:2153
static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I)
Returns true if a PHINode is a trivially replaceable with an Instruction.
Definition LICM.cpp:1067
std::pair< SmallSetVector< Value *, 8 >, bool > PointersAndHasReadsOutsideSet
Definition LICM.cpp:213
static cl::opt< bool > DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false), cl::desc("Disable memory promotion in LICM pass"))
Memory promotion is enabled by default.
static std::optional< uint64_t > getConstantInsertionIndex(InsertElementInst *Ins)
Definition LICM.cpp:759
static bool hoistBOAssociation(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, AssumptionCache *AC, DominatorTree *DT)
Reassociate associative binary expressions of the form.
Definition LICM.cpp:2686
static bool pointerInvalidatedByBlock(BasicBlock &BB, MemorySSA &MSSA, MemoryUse &MU)
Definition LICM.cpp:2244
This file defines the interface for the loop nest analysis.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility analysis objects describing memory locations.
Memory SSA
Definition MemorySSA.cpp:73
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
This file contains the declarations for metadata subclasses.
Contains a collection of routines for determining if a given instruction is guaranteed to execute if ...
uint64_t IntrinsicInst * II
#define P(N)
if(PassOpts->AAPipeline)
PassInstrumentationCallbacks PIC
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file provides a priority worklist.
static DominatorTree getDomTree(Function &F)
Remove Loads Into Fake Uses
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
static cl::opt< bool > DisablePromotion("disable-type-promotion", cl::Hidden, cl::init(false), cl::desc("Disable type promotion pass"))
Value * RHS
Value * LHS
BinaryOperator * Mul
LLVM_ABI void addWithoutAATags(StoreInst *SI)
LLVM_ABI void add(const MemoryLocation &Loc)
These methods are used to add different types of instructions to the alias sets.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI bool canSplitPredecessors() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
Definition InstrTypes.h:831
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
bool isSigned() const
Definition InstrTypes.h:993
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isNegative() const
Definition Constants.h:214
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition Constants.h:174
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition DataLayout.h:579
static LLVM_ABI DebugLoc getMergedLocations(ArrayRef< DebugLoc > Locs)
Try to combine the vector of locations passed as input in a single one.
Definition DebugLoc.cpp:160
static DebugLoc getDropped()
Definition DebugLoc.h:155
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:348
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
This implementation of LoopSafetyInfo use ImplicitControlFlowTracking to give precise answers on "may...
bool doesNotWriteMemoryBefore(const BasicBlock *BB) const
Returns true if we could not execute a memory-modifying instruction before we enter BB under assumpti...
bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT) const override
Returns true if the instruction in a loop is guaranteed to execute at least once (under the assumptio...
void removeInstruction(const Instruction *Inst)
Inform safety info that we are planning to remove the instruction Inst from its block.
bool anyBlockMayThrow() const override
Returns true iff any block of the loop for which this info is contains an instruction that may throw ...
void insertInstructionTo(const Instruction *Inst, const BasicBlock *BB)
Inform the safety info that we are planning to insert a new instruction Inst into the basic block BB.
This instruction compares its operands according to the predicate given to the constructor.
static bool isGE(Predicate P)
Return true if the predicate is SGE or UGE.
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
static bool isGT(Predicate P)
Return true if the predicate is SGT or UGT.
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
static bool isLE(Predicate P)
Return true if the predicate is SLE or ULE.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2917
This instruction inserts a single (scalar) element into a VectorType value.
VectorType * getType() const
Overload to return most specific vector type.
LLVM_ABI void mergeDIAssignID(ArrayRef< const Instruction * > SourceInstructions)
Merge the DIAssignID metadata from this instruction and those attached to instructions in SourceInstr...
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
user_iterator_impl< Instruction > user_iterator
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
Instruction * user_back()
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Definition LICM.cpp:320
LLVM_ABI PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
Definition LICM.cpp:298
LLVM_ABI PreservedAnalyses run(LoopNest &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
Definition LICM.cpp:330
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Definition LICM.cpp:360
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
static void getLazyBFIAnalysisUsage(AnalysisUsage &AU)
Helper for client passes to set up the analysis usage on behalf of this pass.
Helper class for promoting a collection of loads and stores into SSA Form using the SSAUpdater.
Definition SSAUpdater.h:149
An instruction for reading from memory.
void setAlignment(Align Align)
Value * getPointerOperand()
void setOrdering(AtomicOrdering Ordering)
Sets the ordering constraint of this load instruction.
bool isUnordered() const
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:594
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getHeader() const
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
void getUniqueExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all unique successor blocks of this loop.
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
LLVM_ABI bool wouldBeOutOfLoopUseRequiringLCSSA(const Value *V, const BasicBlock *ExitBB) const
This class represents a loop nest and can be used to query its properties.
Function * getParent() const
Return the function to which the loop-nest belongs.
Loop & getOutermostLoop() const
Return the outermost loop in the loop nest.
Captures loop safety information.
Definition MustExecute.h:55
LLVM_ABI void copyColors(BasicBlock *New, BasicBlock *Old)
Copy colors of block Old into the block New.
LLVM_ABI const DenseMap< BasicBlock *, ColorVector > & getBlockColors() const
Returns block colors map that is used to update funclet operand bundles.
virtual bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT) const =0
Returns true if the instruction in a loop is guaranteed to execute at least once (under the assumptio...
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
Definition LoopInfo.cpp:73
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition LoopInfo.cpp:67
BasicBlock * getBlock() const
Definition MemorySSA.h:162
bool onlyWritesMemory() const
Whether this function only (at most) writes memory.
Definition ModRef.h:252
bool doesNotAccessMemory() const
Whether this function accesses no memory.
Definition ModRef.h:246
bool onlyReadsMemory() const
Whether this function only (at most) reads memory.
Definition ModRef.h:249
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:922
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
LLVM_ABI void insertDef(MemoryDef *Def, bool RenameUses=false)
Insert a definition into the MemorySSA IR.
LLVM_ABI void insertUse(MemoryUse *Use, bool RenameUses=false)
LLVM_ABI MemoryAccess * createMemoryAccessInBB(Instruction *I, MemoryAccess *Definition, const BasicBlock *BB, MemorySSA::InsertionPlace Point, bool CreationMustSucceed=true)
Create a MemoryAccess in MemorySSA at a specified point in a block.
LLVM_ABI void removeMemoryAccess(MemoryAccess *, bool OptimizePhis=false)
Remove a MemoryAccess from MemorySSA, including updating all definitions and uses.
LLVM_ABI MemoryUseOrDef * createMemoryAccessAfter(Instruction *I, MemoryAccess *Definition, MemoryAccess *InsertPt)
Create a MemoryAccess in MemorySSA after an existing MemoryAccess.
LLVM_ABI void moveToPlace(MemoryUseOrDef *What, BasicBlock *BB, MemorySSA::InsertionPlace Where)
MemoryAccess * getClobberingMemoryAccess(const Instruction *I, BatchAAResults &AA)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
Definition MemorySSA.h:1035
Legacy analysis pass which computes MemorySSA.
Definition MemorySSA.h:975
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition MemorySSA.h:702
AliasAnalysis & getAA()
Definition MemorySSA.h:800
DefsList * getBlockDefs(const BasicBlock *BB) const
Return the list of MemoryDef's and MemoryPhi's for a given basic block.
Definition MemorySSA.h:765
LLVM_ABI MemorySSAWalker * getSkipSelfWalker()
AccessList * getBlockAccesses(const BasicBlock *BB) const
Return the list of MemoryAccess's for a given basic block.
Definition MemorySSA.h:758
LLVM_ABI bool dominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in potentially different blocks, determine whether MemoryAccess A dominates...
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition MemorySSA.h:720
LLVM_ABI bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in the same basic block, determine whether MemoryAccess A dominates MemoryA...
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
Definition MemorySSA.h:740
Class that has the common methods + fields of memory uses/defs.
Definition MemorySSA.h:250
MemoryAccess * getDefiningAccess() const
Get the access that produces the memory state used by this Use.
Definition MemorySSA.h:260
Represents read-only accesses to memory.
Definition MemorySSA.h:310
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
Diagnostic information for applied optimization remarks.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
op_range incoming_values()
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Pass interface - Implemented by all 'passes'.
Definition Pass.h:99
PointerIntPair - This class implements a pair of a pointer and small integer.
void setInt(IntType IntVal) &
PointerTy getPointer() const
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
PredIteratorCache - This class is an extremely trivial cache for predecessor iterator queries.
size_t size(BasicBlock *BB)
ArrayRef< BasicBlock * > get(BasicBlock *BB)
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
bool empty() const
Determine if the PriorityWorklist is empty or not.
bool insert(const T &X)
Insert a new element into the PriorityWorklist.
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition SSAUpdater.h:39
The main scalar evolution driver.
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
LLVM_ABI void forgetLoopDispositions()
Called when the client has changed the disposition of values in this loop.
bool remove(const value_type &X)
Remove an item from the set vector.
Definition SetVector.h:187
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
iterator begin()
Get an iterator to the beginning of the SetVector.
Definition SetVector.h:112
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
Flags controlling how much is checked when sinking or hoisting instructions.
Definition LoopUtils.h:123
LLVM_ABI SinkAndHoistLICMFlags(unsigned LicmMssaOptCap, unsigned LicmMssaNoAccForPromotionCap, bool IsSink, Loop &L, MemorySSA &MSSA)
Definition LICM.cpp:388
unsigned LicmMssaNoAccForPromotionCap
Definition LoopUtils.h:142
A version of PriorityWorklist that selects small size optimized data structures for the vector and ma...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
void setAlignment(Align Align)
void setOrdering(AtomicOrdering Ordering)
Sets the ordering constraint of this store instruction.
static unsigned getPointerOperandIndex()
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Provides information about what library functions are available for the current target.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCC_Free
Expected to fold away in lowering.
EltTy front() const
unsigned size() const
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
const Use & getOperandUse(unsigned i) const
Definition User.h:220
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI bool hasOneUser() const
Return true if there is exactly one user of this value.
Definition Value.cpp:163
LLVM_ABI std::string getNameOrAsOperand() const
Definition Value.cpp:461
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
iterator_range< user_iterator > users()
Definition Value.h:428
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
Abstract Attribute helper functions.
Definition Attributor.h:165
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
initializer< Ty > init(const Ty &Val)
DiagnosticInfoOptimizationBase::Argument NV
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
@ NeverOverflows
Never overflows.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT, Loop *CurLoop, MemorySSAUpdater &MSSAU, bool TargetExecutesOncePerLoop, SinkAndHoistLICMFlags &LICMFlags, OptimizationRemarkEmitter *ORE=nullptr)
Returns true if is legal to hoist or sink this instruction disregarding the possible introduction of ...
Definition LICM.cpp:973
auto pred_end(const MachineBasicBlock *BB)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool isStrongerThanMonotonic(AtomicOrdering AO)
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition Utils.cpp:1675
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
constexpr from_range_t from_range
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition LCSSA.cpp:469
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
auto cast_or_null(const Y &Val)
Definition Casting.h:714
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI bool PointerMayBeCapturedBefore(const Value *V, bool ReturnCaptures, const Instruction *I, const DominatorTree *DT, bool IncludeI=false, unsigned MaxUsesToExplore=0, const LoopInfo *LI=nullptr)
PointerMayBeCapturedBefore - Return true if this pointer value may be captured by the enclosing funct...
LLVM_ABI Pass * createLICMPass()
Definition LICM.cpp:381
LLVM_ABI SmallVector< BasicBlock *, 16 > collectChildrenInLoop(DominatorTree *DT, DomTreeNode *N, const Loop *CurLoop)
Does a BFS from a given node to all of its children inside a given loop.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition Dominators.h:65
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
LLVM_ABI bool hoistRegion(DomTreeNode *, AAResults *, LoopInfo *, DominatorTree *, AssumptionCache *, TargetLibraryInfo *, Loop *, MemorySSAUpdater &, ScalarEvolution *, ICFLoopSafetyInfo *, SinkAndHoistLICMFlags &, OptimizationRemarkEmitter *, bool, bool AllowSpeculation)
Walk the specified region of the CFG (defined by all blocks dominated by the specified block,...
Definition LICM.cpp:645
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:402
LLVM_ABI bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental....
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI void initializeLegacyLICMPassPass(PassRegistry &)
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_TEMPLATE_ABI void appendLoopsToWorklist(RangeT &&, SmallPriorityWorklist< Loop *, 4 > &)
Utility that implements appending of loops onto a worklist given a range.
LLVM_ABI bool isNotVisibleOnUnwind(const Value *Object, bool &RequiresNoCaptureBeforeUnwind)
Return true if Object memory is not visible after an unwind, in the sense that program semantics cann...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
LLVM_ABI BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
TargetTransformInfo TTI
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:85
LLVM_ABI bool salvageKnowledge(Instruction *I, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr)
Calls BuildAssumeFromInst and if the resulting llvm.assume is valid insert if before I.
LLVM_ABI bool hasDisableLICMTransformsHint(const Loop *L)
Look for the loop attribute that disables the LICM transformation heuristics.
LLVM_ABI OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
@ Add
Sum of integers.
DWARFExpression::Operation Op
LLVM_ABI bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const SimplifyQuery &Q, bool IgnoreFree=false)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition Loads.cpp:244
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool isIdentifiedFunctionLocal(const Value *V)
Return true if V is umabigously identified at the function-level.
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
Definition STLExtras.h:1425
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
LLVM_ABI OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
TinyPtrVector< BasicBlock * > ColorVector
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
auto predecessors(const MachineBasicBlock *BB)
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
LLVM_ABI bool sinkRegion(DomTreeNode *, AAResults *, LoopInfo *, DominatorTree *, TargetLibraryInfo *, TargetTransformInfo *, Loop *CurLoop, MemorySSAUpdater &, ICFLoopSafetyInfo *, SinkAndHoistLICMFlags &, OptimizationRemarkEmitter *, Loop *OutermostLoop=nullptr)
Walk the specified region of the CFG (defined by all blocks dominated by the specified block,...
Definition LICM.cpp:553
LLVM_ABI OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
LLVM_ABI cl::opt< unsigned > SetLicmMssaNoAccForPromotionCap
LLVM_ABI bool canHoistLoad(LoadInst &LI, AAResults *AA, DominatorTree *DT, Loop *CurLoop, MemorySSA &MSSA, bool TargetExecutesOncePerLoop, SinkAndHoistLICMFlags &LICMFlags, OptimizationRemarkEmitter *ORE=nullptr)
Returns true if it is legal to hoist LI out of CurLoop.
Definition LICM.cpp:932
LLVM_ABI bool isDereferenceablePointer(const Value *V, Type *Ty, const SimplifyQuery &Q, bool IgnoreFree=false)
Equivalent to isDereferenceableAndAlignedPointer with an alignment of 1.
Definition Loads.cpp:264
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:375
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI bool promoteLoopAccessesToScalars(const SmallSetVector< Value *, 8 > &, SmallVectorImpl< BasicBlock * > &, SmallVectorImpl< BasicBlock::iterator > &, SmallVectorImpl< MemoryAccess * > &, PredIteratorCache &, LoopInfo *, DominatorTree *, AssumptionCache *AC, const TargetLibraryInfo *, TargetTransformInfo *, Loop *, MemorySSAUpdater &, ICFLoopSafetyInfo *, OptimizationRemarkEmitter *, bool AllowSpeculation, bool HasReadsOutsideSet)
Try to promote memory values to scalars by sinking stores out of the loop and moving loads to before ...
Definition LICM.cpp:1692
bool isNoModRef(const ModRefInfo MRI)
Definition ModRef.h:40
LLVM_ABI cl::opt< unsigned > SetLicmMssaOptCap
LLVM_ABI bool sinkRegionForLoopNest(DomTreeNode *, AAResults *, LoopInfo *, DominatorTree *, TargetLibraryInfo *, TargetTransformInfo *, Loop *, MemorySSAUpdater &, ICFLoopSafetyInfo *, SinkAndHoistLICMFlags &, OptimizationRemarkEmitter *)
Call sinkRegion on loops contained within the specified loop in order from innermost to outermost.
Definition LICM.cpp:620
bool isRefSet(const ModRefInfo MRI)
Definition ModRef.h:52
LLVM_ABI bool isWritableObject(const Value *Object, bool &ExplicitlyDereferenceableOnly)
Return true if the Object is writable, in the sense that any location based on this pointer that can ...
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:774
LLVM_ABI AAMDNodes merge(const AAMDNodes &Other) const
Given two sets of AAMDNodes applying to potentially different locations, determine the best AAMDNodes...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
A lightweight accessor for an operand bundle meant to be passed around by value.
uint32_t getTagID() const
Return the tag of this operand bundle as an integer.