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"
43#include "llvm/ADT/Statistic.h"
51#include "llvm/Analysis/Loads.h"
65#include "llvm/IR/CFG.h"
66#include "llvm/IR/Constants.h"
67#include "llvm/IR/DataLayout.h"
70#include "llvm/IR/Dominators.h"
71#include "llvm/IR/IRBuilder.h"
74#include "llvm/IR/LLVMContext.h"
75#include "llvm/IR/Metadata.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(NumCreatedBlocks, "Number of blocks created");
99STATISTIC(NumClonedBranches, "Number of branches cloned");
100STATISTIC(NumSunk, "Number of instructions sunk out of loop");
101STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
102STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
103STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
104STATISTIC(NumPromotionCandidates, "Number of promotion candidates");
105STATISTIC(NumLoadPromoted, "Number of load-only promotions");
106STATISTIC(NumLoadStorePromoted, "Number of load and store promotions");
107STATISTIC(NumMinMaxHoisted,
108 "Number of min/max expressions hoisted out of the loop");
109STATISTIC(NumGEPsHoisted,
110 "Number of geps reassociated and hoisted out of the loop");
111STATISTIC(NumAddSubHoisted, "Number of add/subtract expressions reassociated "
112 "and hoisted out of the loop");
113STATISTIC(NumFPAssociationsHoisted, "Number of invariant FP expressions "
114 "reassociated and hoisted out of the loop");
115STATISTIC(NumIntAssociationsHoisted,
116 "Number of invariant int expressions "
117 "reassociated and hoisted out of the loop");
118STATISTIC(NumBOAssociationsHoisted, "Number of invariant BinaryOp expressions "
119 "reassociated and hoisted out of the loop");
120
121/// Memory promotion is enabled by default.
122static cl::opt<bool>
123 DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false),
124 cl::desc("Disable memory promotion in LICM pass"));
125
127 "licm-control-flow-hoisting", cl::Hidden, cl::init(false),
128 cl::desc("Enable control flow (and PHI) hoisting in LICM"));
129
130static cl::opt<bool>
131 SingleThread("licm-force-thread-model-single", cl::Hidden, cl::init(false),
132 cl::desc("Force thread model single in LICM pass"));
133
135 "licm-max-num-uses-traversed", cl::Hidden, cl::init(8),
136 cl::desc("Max num uses visited for identifying load "
137 "invariance in loop using invariant start (default = 8)"));
138
140 "licm-max-num-fp-reassociations", cl::init(5U), cl::Hidden,
141 cl::desc(
142 "Set upper limit for the number of transformations performed "
143 "during a single round of hoisting the reassociated expressions."));
144
146 "licm-max-num-int-reassociations", cl::init(5U), cl::Hidden,
147 cl::desc(
148 "Set upper limit for the number of transformations performed "
149 "during a single round of hoisting the reassociated expressions."));
150
151// Experimental option to allow imprecision in LICM in pathological cases, in
152// exchange for faster compile. This is to be removed if MemorySSA starts to
153// address the same issue. LICM calls MemorySSAWalker's
154// getClobberingMemoryAccess, up to the value of the Cap, getting perfect
155// accuracy. Afterwards, LICM will call into MemorySSA's getDefiningAccess,
156// which may not be precise, since optimizeUses is capped. The result is
157// correct, but we may not get as "far up" as possible to get which access is
158// clobbering the one queried.
160 "licm-mssa-optimization-cap", cl::init(100), cl::Hidden,
161 cl::desc("Enable imprecision in LICM in pathological cases, in exchange "
162 "for faster compile. Caps the MemorySSA clobbering calls."));
163
164// Experimentally, memory promotion carries less importance than sinking and
165// hoisting. Limit when we do promotion when using MemorySSA, in order to save
166// compile time.
168 "licm-mssa-max-acc-promotion", cl::init(250), cl::Hidden,
169 cl::desc("[LICM & MemorySSA] When MSSA in LICM is disabled, this has no "
170 "effect. When MSSA in LICM is enabled, then this is the maximum "
171 "number of accesses allowed to be present in a loop in order to "
172 "enable memory promotion."));
173
174static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
175static bool isNotUsedOrFoldableInLoop(const Instruction &I, const Loop *CurLoop,
176 const LoopSafetyInfo *SafetyInfo,
178 bool &FoldableInLoop, bool LoopNestMode);
179static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
180 BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo,
183static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
184 const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo,
187 Instruction &Inst, const DominatorTree *DT, const TargetLibraryInfo *TLI,
188 const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo,
189 OptimizationRemarkEmitter *ORE, const Instruction *CtxI,
190 AssumptionCache *AC, bool AllowSpeculation);
192 AAResults *AA, Loop *CurLoop,
193 SinkAndHoistLICMFlags &Flags);
194static bool pointerInvalidatedByLoop(MemorySSA *MSSA, MemoryUse *MU,
195 Loop *CurLoop, Instruction &I,
197 bool InvariantGroup);
198static bool pointerInvalidatedByBlock(BasicBlock &BB, MemorySSA &MSSA,
199 MemoryUse &MU);
200/// Aggregates various functions for hoisting computations out of loop.
201static bool hoistArithmetics(Instruction &I, Loop &L,
202 ICFLoopSafetyInfo &SafetyInfo,
204 DominatorTree *DT);
205static bool
207 BasicBlock *HoistDest, ICFLoopSafetyInfo *SafetyInfo,
210 SmallVectorImpl<Instruction *> &HoistedInstructions);
212 Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI,
213 const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater &MSSAU);
214
215static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo,
216 MemorySSAUpdater &MSSAU);
217
219 ICFLoopSafetyInfo &SafetyInfo,
221
222static void foreachMemoryAccess(MemorySSA *MSSA, Loop *L,
223 function_ref<void(Instruction *)> Fn);
225 std::pair<SmallSetVector<Value *, 8>, bool>;
228 DominatorTree *DT, ICFLoopSafetyInfo *SafetyInfo,
229 Loop *L);
230
231namespace {
232struct LoopInvariantCodeMotion {
233 bool runOnLoop(Loop *L, AAResults *AA, LoopInfo *LI, DominatorTree *DT,
236 OptimizationRemarkEmitter *ORE, bool LoopNestMode = false);
237
238 LoopInvariantCodeMotion(unsigned LicmMssaOptCap,
239 unsigned LicmMssaNoAccForPromotionCap,
240 bool LicmAllowSpeculation)
241 : LicmMssaOptCap(LicmMssaOptCap),
242 LicmMssaNoAccForPromotionCap(LicmMssaNoAccForPromotionCap),
243 LicmAllowSpeculation(LicmAllowSpeculation) {}
244
245private:
246 unsigned LicmMssaOptCap;
247 unsigned LicmMssaNoAccForPromotionCap;
248 bool LicmAllowSpeculation;
249};
250
251struct LegacyLICMPass : public LoopPass {
252 static char ID; // Pass identification, replacement for typeid
253 LegacyLICMPass(
254 unsigned LicmMssaOptCap = SetLicmMssaOptCap,
255 unsigned LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap,
256 bool LicmAllowSpeculation = true)
257 : LoopPass(ID), LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
258 LicmAllowSpeculation) {
260 }
261
262 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
263 if (skipLoop(L))
264 return false;
265
266 LLVM_DEBUG(dbgs() << "Perform LICM on Loop with header at block "
267 << L->getHeader()->getNameOrAsOperand() << "\n");
268
269 Function *F = L->getHeader()->getParent();
270
271 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
272 MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
273 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
274 // pass. Function analyses need to be preserved across loop transformations
275 // but ORE cannot be preserved (see comment before the pass definition).
276 OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
277 return LICM.runOnLoop(
278 L, &getAnalysis<AAResultsWrapperPass>().getAAResults(),
279 &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
280 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
281 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F),
282 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(*F),
283 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(*F),
284 SE ? &SE->getSE() : nullptr, MSSA, &ORE);
285 }
286
287 /// This transformation requires natural loop information & requires that
288 /// loop preheaders be inserted into the CFG...
289 ///
290 void getAnalysisUsage(AnalysisUsage &AU) const override {
291 AU.addPreserved<DominatorTreeWrapperPass>();
292 AU.addPreserved<LoopInfoWrapperPass>();
293 AU.addRequired<TargetLibraryInfoWrapperPass>();
294 AU.addRequired<MemorySSAWrapperPass>();
295 AU.addPreserved<MemorySSAWrapperPass>();
296 AU.addRequired<TargetTransformInfoWrapperPass>();
297 AU.addRequired<AssumptionCacheTracker>();
300 AU.addPreserved<LazyBlockFrequencyInfoPass>();
301 AU.addPreserved<LazyBranchProbabilityInfoPass>();
302 }
303
304private:
305 LoopInvariantCodeMotion LICM;
306};
307} // namespace
308
311 if (!AR.MSSA)
312 reportFatalUsageError("LICM requires MemorySSA (loop-mssa)");
313
314 // For the new PM, we also can't use OptimizationRemarkEmitter as an analysis
315 // pass. Function analyses need to be preserved across loop transformations
316 // but ORE cannot be preserved (see comment before the pass definition).
317 OptimizationRemarkEmitter ORE(L.getHeader()->getParent());
318
319 LoopInvariantCodeMotion LICM(Opts.MssaOptCap, Opts.MssaNoAccForPromotionCap,
320 Opts.AllowSpeculation);
321 if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.AC, &AR.TLI, &AR.TTI,
322 &AR.SE, AR.MSSA, &ORE))
323 return PreservedAnalyses::all();
324
326 PA.preserve<MemorySSAAnalysis>();
327
328 return PA;
329}
330
332 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
333 static_cast<PassInfoMixin<LICMPass> *>(this)->printPipeline(
334 OS, MapClassName2PassName);
335
336 OS << '<';
337 OS << (Opts.AllowSpeculation ? "" : "no-") << "allowspeculation";
338 OS << '>';
339}
340
343 LPMUpdater &) {
344 if (!AR.MSSA)
345 reportFatalUsageError("LNICM requires MemorySSA (loop-mssa)");
346
347 // For the new PM, we also can't use OptimizationRemarkEmitter as an analysis
348 // pass. Function analyses need to be preserved across loop transformations
349 // but ORE cannot be preserved (see comment before the pass definition).
351
352 LoopInvariantCodeMotion LICM(Opts.MssaOptCap, Opts.MssaNoAccForPromotionCap,
353 Opts.AllowSpeculation);
354
355 Loop &OutermostLoop = LN.getOutermostLoop();
356 bool Changed = LICM.runOnLoop(&OutermostLoop, &AR.AA, &AR.LI, &AR.DT, &AR.AC,
357 &AR.TLI, &AR.TTI, &AR.SE, AR.MSSA, &ORE, true);
358
359 if (!Changed)
360 return PreservedAnalyses::all();
361
363
364 PA.preserve<DominatorTreeAnalysis>();
365 PA.preserve<LoopAnalysis>();
366 PA.preserve<MemorySSAAnalysis>();
367
368 return PA;
369}
370
372 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
373 static_cast<PassInfoMixin<LNICMPass> *>(this)->printPipeline(
374 OS, MapClassName2PassName);
375
376 OS << '<';
377 OS << (Opts.AllowSpeculation ? "" : "no-") << "allowspeculation";
378 OS << '>';
379}
380
381char LegacyLICMPass::ID = 0;
382INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
383 false, false)
389INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
390 false)
391
392Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
393
398
400 unsigned LicmMssaOptCap, unsigned LicmMssaNoAccForPromotionCap, bool IsSink,
401 Loop &L, MemorySSA &MSSA)
404 IsSink(IsSink) {
405 unsigned AccessCapCount = 0;
406 for (auto *BB : L.getBlocks())
407 if (const auto *Accesses = MSSA.getBlockAccesses(BB))
408 for (const auto &MA : *Accesses) {
409 (void)MA;
410 ++AccessCapCount;
411 if (AccessCapCount > LicmMssaNoAccForPromotionCap) {
412 NoOfMemAccTooLarge = true;
413 return;
414 }
415 }
416}
417
418/// Hoist expressions out of the specified loop. Note, alias info for inner
419/// loop is not preserved so it is not a good idea to run LICM multiple
420/// times on one loop.
421bool LoopInvariantCodeMotion::runOnLoop(Loop *L, AAResults *AA, LoopInfo *LI,
425 ScalarEvolution *SE, MemorySSA *MSSA,
427 bool LoopNestMode) {
428 bool Changed = false;
429
430 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
431
432 // If this loop has metadata indicating that LICM is not to be performed then
433 // just exit.
435 return false;
436 }
437
438 // Don't sink stores from loops with coroutine suspend instructions.
439 // LICM would sink instructions into the default destination of
440 // the coroutine switch. The default destination of the switch is to
441 // handle the case where the coroutine is suspended, by which point the
442 // coroutine frame may have been destroyed. No instruction can be sunk there.
443 // FIXME: This would unfortunately hurt the performance of coroutines, however
444 // there is currently no general solution for this. Similar issues could also
445 // potentially happen in other passes where instructions are being moved
446 // across that edge.
447 bool HasCoroSuspendInst = llvm::any_of(L->getBlocks(), [](BasicBlock *BB) {
448 using namespace PatternMatch;
449 return any_of(make_pointer_range(*BB),
450 match_fn(m_Intrinsic<Intrinsic::coro_suspend>()));
451 });
452
453 MemorySSAUpdater MSSAU(MSSA);
454 SinkAndHoistLICMFlags Flags(LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
455 /*IsSink=*/true, *L, *MSSA);
456
457 // Get the preheader block to move instructions into...
458 BasicBlock *Preheader = L->getLoopPreheader();
459
460 // Compute loop safety information.
461 ICFLoopSafetyInfo SafetyInfo(L);
462
463 // We want to visit all of the instructions in this loop... that are not parts
464 // of our subloops (they have already had their invariants hoisted out of
465 // their loop, into this loop, so there is no need to process the BODIES of
466 // the subloops).
467 //
468 // Traverse the body of the loop in depth first order on the dominator tree so
469 // that we are guaranteed to see definitions before we see uses. This allows
470 // us to sink instructions in one pass, without iteration. After sinking
471 // instructions, we perform another pass to hoist them out of the loop.
472 if (L->hasDedicatedExits())
473 Changed |=
474 LoopNestMode
475 ? sinkRegionForLoopNest(DT->getNode(L->getHeader()), AA, LI, DT,
476 TLI, TTI, L, MSSAU, &SafetyInfo, Flags, ORE)
477 : sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, TTI, L,
478 MSSAU, &SafetyInfo, Flags, ORE);
479 Flags.setIsSink(false);
480 if (Preheader)
481 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, AC, TLI, L,
482 MSSAU, SE, &SafetyInfo, Flags, ORE, LoopNestMode,
483 LicmAllowSpeculation);
484
485 // Now that all loop invariants have been removed from the loop, promote any
486 // memory references to scalars that we can.
487 // Don't sink stores from loops without dedicated block exits. Exits
488 // containing indirect branches are not transformed by loop simplify,
489 // make sure we catch that. An additional load may be generated in the
490 // preheader for SSA updater, so also avoid sinking when no preheader
491 // is available.
492 if (!DisablePromotion && Preheader && L->hasDedicatedExits() &&
493 !Flags.tooManyMemoryAccesses() && !HasCoroSuspendInst) {
494 // Figure out the loop exits and their insertion points
495 SmallVector<BasicBlock *, 8> ExitBlocks;
496 L->getUniqueExitBlocks(ExitBlocks);
497
498 // We can't insert into a catchswitch.
499 bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
500 return isa<CatchSwitchInst>(Exit->getTerminator());
501 });
502
503 if (!HasCatchSwitch) {
505 SmallVector<MemoryAccess *, 8> MSSAInsertPts;
506 InsertPts.reserve(ExitBlocks.size());
507 MSSAInsertPts.reserve(ExitBlocks.size());
508 for (BasicBlock *ExitBlock : ExitBlocks) {
509 InsertPts.push_back(ExitBlock->getFirstInsertionPt());
510 MSSAInsertPts.push_back(nullptr);
511 }
512
514
515 // Promoting one set of accesses may make the pointers for another set
516 // loop invariant, so run this in a loop.
517 bool Promoted = false;
518 bool LocalPromoted;
519 do {
520 LocalPromoted = false;
521 for (auto [PointerMustAliases, HasReadsOutsideSet] :
522 collectPromotionCandidates(MSSA, AA, DT, &SafetyInfo, L)) {
523 LocalPromoted |= promoteLoopAccessesToScalars(
524 PointerMustAliases, ExitBlocks, InsertPts, MSSAInsertPts, PIC, LI,
525 DT, AC, TLI, TTI, L, MSSAU, &SafetyInfo, ORE,
526 LicmAllowSpeculation, HasReadsOutsideSet);
527 }
528 Promoted |= LocalPromoted;
529 } while (LocalPromoted);
530
531 // Once we have promoted values across the loop body we have to
532 // recursively reform LCSSA as any nested loop may now have values defined
533 // within the loop used in the outer loop.
534 // FIXME: This is really heavy handed. It would be a bit better to use an
535 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
536 // it as it went.
537 if (Promoted)
538 formLCSSARecursively(*L, *DT, LI, SE);
539
540 Changed |= Promoted;
541 }
542 }
543
544 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
545 // specifically moving instructions across the loop boundary and so it is
546 // especially in need of basic functional correctness checking here.
547 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
548 assert((L->isOutermost() || L->getParentLoop()->isLCSSAForm(*DT)) &&
549 "Parent loop not left in LCSSA form after LICM!");
550
551 if (VerifyMemorySSA)
552 MSSA->verifyMemorySSA();
553
554 if (Changed && SE)
556 return Changed;
557}
558
559/// Walk the specified region of the CFG (defined by all blocks dominated by
560/// the specified block, and that are in the current loop) in reverse depth
561/// first order w.r.t the DominatorTree. This allows us to visit uses before
562/// definitions, allowing us to sink a loop body in one pass without iteration.
563///
566 TargetTransformInfo *TTI, Loop *CurLoop,
567 MemorySSAUpdater &MSSAU, ICFLoopSafetyInfo *SafetyInfo,
569 OptimizationRemarkEmitter *ORE, Loop *OutermostLoop) {
570
571 // Verify inputs.
572 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
573 CurLoop != nullptr && SafetyInfo != nullptr &&
574 "Unexpected input to sinkRegion.");
575
576 // We want to visit children before parents. We will enqueue all the parents
577 // before their children in the worklist and process the worklist in reverse
578 // order.
580 collectChildrenInLoop(DT, N, CurLoop);
581
582 bool Changed = false;
583 for (BasicBlock *BB : reverse(Worklist)) {
584 // subloop (which would already have been processed).
585 if (inSubLoop(BB, CurLoop, LI))
586 continue;
587
588 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
589 Instruction &I = *--II;
590
591 // The instruction is not used in the loop if it is dead. In this case,
592 // we just delete it instead of sinking it.
593 if (isInstructionTriviallyDead(&I, TLI)) {
594 LLVM_DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
597 ++II;
598 eraseInstruction(I, *SafetyInfo, MSSAU);
599 Changed = true;
600 continue;
601 }
602
603 // Check to see if we can sink this instruction to the exit blocks
604 // of the loop. We can do this if the all users of the instruction are
605 // outside of the loop. In this case, it doesn't even matter if the
606 // operands of the instruction are loop invariant.
607 //
608 bool FoldableInLoop = false;
609 bool LoopNestMode = OutermostLoop != nullptr;
610 if (!I.mayHaveSideEffects() &&
611 isNotUsedOrFoldableInLoop(I, LoopNestMode ? OutermostLoop : CurLoop,
612 SafetyInfo, TTI, FoldableInLoop,
613 LoopNestMode) &&
614 canSinkOrHoistInst(I, AA, DT, CurLoop, MSSAU, true, Flags, ORE)) {
615 if (sink(I, LI, DT, CurLoop, SafetyInfo, MSSAU, ORE)) {
616 if (!FoldableInLoop) {
617 ++II;
619 eraseInstruction(I, *SafetyInfo, MSSAU);
620 }
621 Changed = true;
622 }
623 }
624 }
625 }
626 if (VerifyMemorySSA)
627 MSSAU.getMemorySSA()->verifyMemorySSA();
628 return Changed;
629}
630
633 TargetTransformInfo *TTI, Loop *CurLoop,
634 MemorySSAUpdater &MSSAU,
635 ICFLoopSafetyInfo *SafetyInfo,
638
639 bool Changed = false;
641 Worklist.insert(CurLoop);
642 appendLoopsToWorklist(*CurLoop, Worklist);
643 while (!Worklist.empty()) {
644 Loop *L = Worklist.pop_back_val();
645 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, TTI, L,
646 MSSAU, SafetyInfo, Flags, ORE, CurLoop);
647 }
648 return Changed;
649}
650
651namespace {
652// This is a helper class for hoistRegion to make it able to hoist control flow
653// in order to be able to hoist phis. The way this works is that we initially
654// start hoisting to the loop preheader, and when we see a loop invariant branch
655// we make note of this. When we then come to hoist an instruction that's
656// conditional on such a branch we duplicate the branch and the relevant control
657// flow, then hoist the instruction into the block corresponding to its original
658// block in the duplicated control flow.
659class ControlFlowHoister {
660private:
661 // Information about the loop we are hoisting from
662 LoopInfo *LI;
663 DominatorTree *DT;
664 Loop *CurLoop;
665 MemorySSAUpdater &MSSAU;
666
667 // A map of blocks in the loop to the block their instructions will be hoisted
668 // to.
669 DenseMap<BasicBlock *, BasicBlock *> HoistDestinationMap;
670
671 // The branches that we can hoist, mapped to the block that marks a
672 // convergence point of their control flow.
673 DenseMap<CondBrInst *, BasicBlock *> HoistableBranches;
674
675public:
676 ControlFlowHoister(LoopInfo *LI, DominatorTree *DT, Loop *CurLoop,
677 MemorySSAUpdater &MSSAU)
678 : LI(LI), DT(DT), CurLoop(CurLoop), MSSAU(MSSAU) {}
679
680 void registerPossiblyHoistableBranch(CondBrInst *BI) {
681 // We can only hoist conditional branches with loop invariant operands.
682 if (!ControlFlowHoisting || !CurLoop->hasLoopInvariantOperands(BI))
683 return;
684
685 // The branch destinations need to be in the loop, and we don't gain
686 // anything by duplicating conditional branches with duplicate successors,
687 // as it's essentially the same as an unconditional branch.
688 BasicBlock *TrueDest = BI->getSuccessor(0);
689 BasicBlock *FalseDest = BI->getSuccessor(1);
690 if (!CurLoop->contains(TrueDest) || !CurLoop->contains(FalseDest) ||
691 TrueDest == FalseDest)
692 return;
693
694 // We can hoist BI if one branch destination is the successor of the other,
695 // or both have common successor which we check by seeing if the
696 // intersection of their successors is non-empty.
697 // TODO: This could be expanded to allowing branches where both ends
698 // eventually converge to a single block.
699 SmallPtrSet<BasicBlock *, 4> TrueDestSucc(llvm::from_range,
700 successors(TrueDest));
701 SmallPtrSet<BasicBlock *, 4> FalseDestSucc(llvm::from_range,
702 successors(FalseDest));
703 BasicBlock *CommonSucc = nullptr;
704 if (TrueDestSucc.count(FalseDest)) {
705 CommonSucc = FalseDest;
706 } else if (FalseDestSucc.count(TrueDest)) {
707 CommonSucc = TrueDest;
708 } else {
709 set_intersect(TrueDestSucc, FalseDestSucc);
710 // If there's one common successor use that.
711 if (TrueDestSucc.size() == 1)
712 CommonSucc = *TrueDestSucc.begin();
713 // If there's more than one pick whichever appears first in the block list
714 // (we can't use the value returned by TrueDestSucc.begin() as it's
715 // unpredicatable which element gets returned).
716 else if (!TrueDestSucc.empty()) {
717 Function *F = TrueDest->getParent();
718 auto IsSucc = [&](BasicBlock &BB) { return TrueDestSucc.count(&BB); };
719 auto It = llvm::find_if(*F, IsSucc);
720 assert(It != F->end() && "Could not find successor in function");
721 CommonSucc = &*It;
722 }
723 }
724 // The common successor has to be dominated by the branch, as otherwise
725 // there will be some other path to the successor that will not be
726 // controlled by this branch so any phi we hoist would be controlled by the
727 // wrong condition. This also takes care of avoiding hoisting of loop back
728 // edges.
729 // TODO: In some cases this could be relaxed if the successor is dominated
730 // by another block that's been hoisted and we can guarantee that the
731 // control flow has been replicated exactly.
732 if (CommonSucc && DT->dominates(BI, CommonSucc))
733 HoistableBranches[BI] = CommonSucc;
734 }
735
736 bool canHoistPHI(PHINode *PN) {
737 // The phi must have loop invariant operands.
738 if (!ControlFlowHoisting || !CurLoop->hasLoopInvariantOperands(PN))
739 return false;
740 // We can hoist phis if the block they are in is the target of hoistable
741 // branches which cover all of the predecessors of the block.
742 BasicBlock *BB = PN->getParent();
743 SmallPtrSet<BasicBlock *, 8> PredecessorBlocks(llvm::from_range,
744 predecessors(BB));
745 // If we have less predecessor blocks than predecessors then the phi will
746 // have more than one incoming value for the same block which we can't
747 // handle.
748 // TODO: This could be handled be erasing some of the duplicate incoming
749 // values.
750 if (PredecessorBlocks.size() != pred_size(BB))
751 return false;
752 for (auto &Pair : HoistableBranches) {
753 if (Pair.second == BB) {
754 // Which blocks are predecessors via this branch depends on if the
755 // branch is triangle-like or diamond-like.
756 if (Pair.first->getSuccessor(0) == BB) {
757 PredecessorBlocks.erase(Pair.first->getParent());
758 PredecessorBlocks.erase(Pair.first->getSuccessor(1));
759 } else if (Pair.first->getSuccessor(1) == BB) {
760 PredecessorBlocks.erase(Pair.first->getParent());
761 PredecessorBlocks.erase(Pair.first->getSuccessor(0));
762 } else {
763 PredecessorBlocks.erase(Pair.first->getSuccessor(0));
764 PredecessorBlocks.erase(Pair.first->getSuccessor(1));
765 }
766 }
767 }
768 // PredecessorBlocks will now be empty if for every predecessor of BB we
769 // found a hoistable branch source.
770 return PredecessorBlocks.empty();
771 }
772
773 BasicBlock *getOrCreateHoistedBlock(BasicBlock *BB) {
775 return CurLoop->getLoopPreheader();
776 // If BB has already been hoisted, return that
777 if (auto It = HoistDestinationMap.find(BB); It != HoistDestinationMap.end())
778 return It->second;
779
780 // Check if this block is conditional based on a pending branch
781 auto HasBBAsSuccessor =
782 [&](DenseMap<CondBrInst *, BasicBlock *>::value_type &Pair) {
783 return BB != Pair.second && (Pair.first->getSuccessor(0) == BB ||
784 Pair.first->getSuccessor(1) == BB);
785 };
786 auto It = llvm::find_if(HoistableBranches, HasBBAsSuccessor);
787
788 // If not involved in a pending branch, hoist to preheader
789 BasicBlock *InitialPreheader = CurLoop->getLoopPreheader();
790 if (It == HoistableBranches.end()) {
791 LLVM_DEBUG(dbgs() << "LICM using "
792 << InitialPreheader->getNameOrAsOperand()
793 << " as hoist destination for "
794 << BB->getNameOrAsOperand() << "\n");
795 HoistDestinationMap[BB] = InitialPreheader;
796 return InitialPreheader;
797 }
798 CondBrInst *BI = It->first;
799 assert(std::none_of(std::next(It), HoistableBranches.end(),
800 HasBBAsSuccessor) &&
801 "BB is expected to be the target of at most one branch");
802
803 LLVMContext &C = BB->getContext();
804 BasicBlock *TrueDest = BI->getSuccessor(0);
805 BasicBlock *FalseDest = BI->getSuccessor(1);
806 BasicBlock *CommonSucc = HoistableBranches[BI];
807 BasicBlock *HoistTarget = getOrCreateHoistedBlock(BI->getParent());
808
809 // Create hoisted versions of blocks that currently don't have them
810 auto CreateHoistedBlock = [&](BasicBlock *Orig) {
811 auto [It, Inserted] = HoistDestinationMap.try_emplace(Orig);
812 if (!Inserted)
813 return It->second;
814 BasicBlock *New =
815 BasicBlock::Create(C, Orig->getName() + ".licm", Orig->getParent());
816 It->second = New;
817 DT->addNewBlock(New, HoistTarget);
818 if (CurLoop->getParentLoop())
819 CurLoop->getParentLoop()->addBasicBlockToLoop(New, *LI);
820 ++NumCreatedBlocks;
821 LLVM_DEBUG(dbgs() << "LICM created " << New->getName()
822 << " as hoist destination for " << Orig->getName()
823 << "\n");
824 return New;
825 };
826 BasicBlock *HoistTrueDest = CreateHoistedBlock(TrueDest);
827 BasicBlock *HoistFalseDest = CreateHoistedBlock(FalseDest);
828 BasicBlock *HoistCommonSucc = CreateHoistedBlock(CommonSucc);
829
830 // Link up these blocks with branches.
831 if (!HoistCommonSucc->hasTerminator()) {
832 // The new common successor we've generated will branch to whatever that
833 // hoist target branched to.
834 BasicBlock *TargetSucc = HoistTarget->getSingleSuccessor();
835 assert(TargetSucc && "Expected hoist target to have a single successor");
836 HoistCommonSucc->moveBefore(TargetSucc);
837 UncondBrInst::Create(TargetSucc, HoistCommonSucc);
838 }
839 if (!HoistTrueDest->hasTerminator()) {
840 HoistTrueDest->moveBefore(HoistCommonSucc);
841 UncondBrInst::Create(HoistCommonSucc, HoistTrueDest);
842 }
843 if (!HoistFalseDest->hasTerminator()) {
844 HoistFalseDest->moveBefore(HoistCommonSucc);
845 UncondBrInst::Create(HoistCommonSucc, HoistFalseDest);
846 }
847
848 // If BI is being cloned to what was originally the preheader then
849 // HoistCommonSucc will now be the new preheader.
850 if (HoistTarget == InitialPreheader) {
851 // Phis in the loop header now need to use the new preheader.
852 InitialPreheader->replaceSuccessorsPhiUsesWith(HoistCommonSucc);
854 HoistTarget->getSingleSuccessor(), HoistCommonSucc, {HoistTarget});
855 // The new preheader dominates the loop header.
856 DomTreeNode *PreheaderNode = DT->getNode(HoistCommonSucc);
857 DomTreeNode *HeaderNode = DT->getNode(CurLoop->getHeader());
858 DT->changeImmediateDominator(HeaderNode, PreheaderNode);
859 // The preheader hoist destination is now the new preheader, with the
860 // exception of the hoist destination of this branch.
861 for (auto &Pair : HoistDestinationMap)
862 if (Pair.second == InitialPreheader && Pair.first != BI->getParent())
863 Pair.second = HoistCommonSucc;
864 }
865
866 // Now finally clone BI.
867 auto *NewBI =
868 CondBrInst::Create(BI->getCondition(), HoistTrueDest, HoistFalseDest,
869 HoistTarget->getTerminator()->getIterator());
870 HoistTarget->getTerminator()->eraseFromParent();
871 // md_prof should also come from the original branch - since the
872 // condition was hoisted, the branch probabilities shouldn't change.
873 NewBI->copyMetadata(*BI, {LLVMContext::MD_prof});
874 // FIXME: Issue #152767: debug info should also be the same as the
875 // original branch, **if** the user explicitly indicated that.
876 NewBI->setDebugLoc(HoistTarget->getTerminator()->getDebugLoc());
877
878 ++NumClonedBranches;
879
880 assert(CurLoop->getLoopPreheader() &&
881 "Hoisting blocks should not have destroyed preheader");
882 return HoistDestinationMap[BB];
883 }
884};
885} // namespace
886
887/// Walk the specified region of the CFG (defined by all blocks dominated by
888/// the specified block, and that are in the current loop) in depth first
889/// order w.r.t the DominatorTree. This allows us to visit definitions before
890/// uses, allowing us to hoist a loop body in one pass without iteration.
891///
894 TargetLibraryInfo *TLI, Loop *CurLoop,
896 ICFLoopSafetyInfo *SafetyInfo,
898 OptimizationRemarkEmitter *ORE, bool LoopNestMode,
899 bool AllowSpeculation) {
900 // Verify inputs.
901 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
902 CurLoop != nullptr && SafetyInfo != nullptr &&
903 "Unexpected input to hoistRegion.");
904
905 ControlFlowHoister CFH(LI, DT, CurLoop, MSSAU);
906
907 // Keep track of instructions that have been hoisted, as they may need to be
908 // re-hoisted if they end up not dominating all of their uses.
909 SmallVector<Instruction *, 16> HoistedInstructions;
910
911 // For PHI hoisting to work we need to hoist blocks before their successors.
912 // We can do this by iterating through the blocks in the loop in reverse
913 // post-order.
914 LoopBlocksRPO Worklist(CurLoop);
915 Worklist.perform(LI);
916 bool Changed = false;
917 BasicBlock *Preheader = CurLoop->getLoopPreheader();
918 for (BasicBlock *BB : Worklist) {
919 // Only need to process the contents of this block if it is not part of a
920 // subloop (which would already have been processed).
921 if (!LoopNestMode && inSubLoop(BB, CurLoop, LI))
922 continue;
923
925 // Try hoisting the instruction out to the preheader. We can only do
926 // this if all of the operands of the instruction are loop invariant and
927 // if it is safe to hoist the instruction.
928 // TODO: It may be safe to hoist if we are hoisting to a conditional block
929 // and we have accurately duplicated the control flow from the loop header
930 // to that block.
931 if (CurLoop->hasLoopInvariantOperands(&I) &&
932 canSinkOrHoistInst(I, AA, DT, CurLoop, MSSAU, true, Flags, ORE) &&
933 isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo, ORE,
934 Preheader->getTerminator(), AC,
935 AllowSpeculation)) {
936 hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
937 MSSAU, SE, ORE);
938 HoistedInstructions.push_back(&I);
939 Changed = true;
940 continue;
941 }
942
943 if (auto *Ins = dyn_cast<InsertElementInst>(&I))
944 if (hoistInsertPastInsert(Ins, CurLoop, DT,
945 CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
946 MSSAU, SE, ORE, HoistedInstructions)) {
947 Changed = true;
948 continue;
949 }
950
951 // Attempt to remove floating point division out of the loop by
952 // converting it to a reciprocal multiplication.
953 if (I.getOpcode() == Instruction::FDiv && I.hasAllowReciprocal() &&
954 CurLoop->isLoopInvariant(I.getOperand(1))) {
955 auto Divisor = I.getOperand(1);
956 auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0);
957 auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);
958 ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags());
959 SafetyInfo->insertInstructionTo(ReciprocalDivisor, I.getParent());
960 ReciprocalDivisor->insertBefore(I.getIterator());
961 ReciprocalDivisor->setDebugLoc(I.getDebugLoc());
962
963 auto Product =
964 BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor);
965 Product->setFastMathFlags(I.getFastMathFlags());
966 SafetyInfo->insertInstructionTo(Product, I.getParent());
967 Product->insertAfter(I.getIterator());
968 Product->setDebugLoc(I.getDebugLoc());
969 I.replaceAllUsesWith(Product);
970 eraseInstruction(I, *SafetyInfo, MSSAU);
971
972 hoist(*ReciprocalDivisor, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB),
973 SafetyInfo, MSSAU, SE, ORE);
974 HoistedInstructions.push_back(ReciprocalDivisor);
975 Changed = true;
976 continue;
977 }
978
979 auto IsInvariantStart = [&](Instruction &I) {
980 using namespace PatternMatch;
981 return I.use_empty() &&
983 };
984 auto MustExecuteWithoutWritesBefore = [&](Instruction &I) {
985 return SafetyInfo->isGuaranteedToExecute(I, DT) &&
986 SafetyInfo->doesNotWriteMemoryBefore(I);
987 };
988 if ((IsInvariantStart(I) || isGuard(&I)) &&
989 CurLoop->hasLoopInvariantOperands(&I) &&
990 MustExecuteWithoutWritesBefore(I)) {
991 hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
992 MSSAU, SE, ORE);
993 HoistedInstructions.push_back(&I);
994 Changed = true;
995 continue;
996 }
997
998 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
999 if (CFH.canHoistPHI(PN)) {
1000 // Redirect incoming blocks first to ensure that we create hoisted
1001 // versions of those blocks before we hoist the phi.
1002 for (unsigned int i = 0; i < PN->getNumIncomingValues(); ++i)
1003 PN->setIncomingBlock(
1004 i, CFH.getOrCreateHoistedBlock(PN->getIncomingBlock(i)));
1005 hoist(*PN, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
1006 MSSAU, SE, ORE);
1007 assert(DT->dominates(PN, BB) && "Conditional PHIs not expected");
1008 Changed = true;
1009 continue;
1010 }
1011 }
1012
1013 // Try to reassociate instructions so that part of computations can be
1014 // done out of loop.
1015 if (hoistArithmetics(I, *CurLoop, *SafetyInfo, MSSAU, AC, DT)) {
1016 Changed = true;
1017 continue;
1018 }
1019
1020 // Remember possibly hoistable branches so we can actually hoist them
1021 // later if needed.
1022 if (CondBrInst *BI = dyn_cast<CondBrInst>(&I))
1023 CFH.registerPossiblyHoistableBranch(BI);
1024 }
1025 }
1026
1027 // If we hoisted instructions to a conditional block they may not dominate
1028 // their uses that weren't hoisted (such as phis where some operands are not
1029 // loop invariant). If so make them unconditional by moving them to their
1030 // immediate dominator. We iterate through the instructions in reverse order
1031 // which ensures that when we rehoist an instruction we rehoist its operands,
1032 // and also keep track of where in the block we are rehoisting to make sure
1033 // that we rehoist instructions before the instructions that use them.
1034 Instruction *HoistPoint = nullptr;
1035 if (ControlFlowHoisting) {
1036 for (Instruction *I : reverse(HoistedInstructions)) {
1037 if (!llvm::all_of(I->uses(),
1038 [&](Use &U) { return DT->dominates(I, U); })) {
1039 BasicBlock *Dominator =
1040 DT->getNode(I->getParent())->getIDom()->getBlock();
1041 if (!HoistPoint || !DT->dominates(HoistPoint->getParent(), Dominator)) {
1042 if (HoistPoint)
1043 assert(DT->dominates(Dominator, HoistPoint->getParent()) &&
1044 "New hoist point expected to dominate old hoist point");
1045 HoistPoint = Dominator->getTerminator();
1046 }
1047 LLVM_DEBUG(dbgs() << "LICM rehoisting to "
1048 << HoistPoint->getParent()->getNameOrAsOperand()
1049 << ": " << *I << "\n");
1050 moveInstructionBefore(*I, HoistPoint->getIterator(), *SafetyInfo, MSSAU,
1051 SE);
1052 HoistPoint = I;
1053 Changed = true;
1054 }
1055 }
1056 }
1057 if (VerifyMemorySSA)
1058 MSSAU.getMemorySSA()->verifyMemorySSA();
1059
1060 // Now that we've finished hoisting make sure that LI and DT are still
1061 // valid.
1062#ifdef EXPENSIVE_CHECKS
1063 if (Changed) {
1064 assert(DT->verify(DominatorTree::VerificationLevel::Fast) &&
1065 "Dominator tree verification failed");
1066 LI->verify();
1067 }
1068#endif
1069
1070 return Changed;
1071}
1072
1073static std::optional<uint64_t>
1075 // Must have constant insertion lane.
1076 auto *InsertedIdxCI = dyn_cast<ConstantInt>(Ins->getOperand(2));
1077 if (!InsertedIdxCI)
1078 return std::nullopt;
1079 auto *VecTy = cast<VectorType>(Ins->getType());
1080
1081 // Avoid hoisting past out of bounds inserts.
1082 if (InsertedIdxCI->isNegative() ||
1083 InsertedIdxCI->getValue().uge(
1084 VecTy->getElementCount().getKnownMinValue()))
1085 return std::nullopt;
1086 return InsertedIdxCI->getValue().getLimitedValue();
1087}
1088
1089static bool
1091 BasicBlock *HoistDest, ICFLoopSafetyInfo *SafetyInfo,
1094 SmallVectorImpl<Instruction *> &HoistedInstructions) {
1095 // Canonicalize:
1096 // %inner = insertelement %base, %variant, C1
1097 // %outer = insertelement %inner, %invariant, C2
1098 // into:
1099 // %outer = insertelement %base, %invariant, C2
1100 // %inner = insertelement %outer, %variant, C1
1101 // so we can hoist %outer
1102
1103 // The instruction we are hoisting must have invariant insertion data
1104 Value *InsertedElt = Ins->getOperand(1);
1105 if (!CurLoop->isLoopInvariant(InsertedElt))
1106 return false;
1107
1108 std::optional<uint64_t> HoistIdx = getConstantInsertionIndex(Ins);
1109 if (!HoistIdx)
1110 return false;
1111
1112 InsertElementInst *Inner = Ins;
1113 while (!CurLoop->isLoopInvariant(Inner->getOperand(0))) {
1114 // If the inner value isn't invariant, check to see if it is another insert
1115 // All instructions in the chain must be in the same basic block
1116 auto *InnerIns = dyn_cast<InsertElementInst>(Inner->getOperand(0));
1117 if (!InnerIns || InnerIns->getParent() != Ins->getParent())
1118 return false;
1119
1120 // Make sure not hoisting past insertions into the same lane
1121 std::optional<uint64_t> InsertIdx = getConstantInsertionIndex(InnerIns);
1122 if (!InsertIdx || *InsertIdx == *HoistIdx)
1123 return false;
1124
1125 // Instruction being hoisted past must only have one use
1126 if (!InnerIns->hasOneUse())
1127 return false;
1128
1129 Inner = InnerIns;
1130 }
1131
1132 // Base case of `insertelement <4 x i8> %invar0, i8 %invar1, i32 2` handled in
1133 // base LICM logic
1134 if (Inner == Ins)
1135 return false;
1136
1137 Ins->replaceAllUsesWith(Ins->getOperand(0));
1138 Ins->moveBefore(Inner->getIterator());
1139 Ins->setOperand(0, Inner->getOperand(0));
1140 Inner->setOperand(0, Ins);
1141 hoist(*Ins, DT, CurLoop, HoistDest, SafetyInfo, MSSAU, SE, ORE);
1142 HoistedInstructions.push_back(Ins);
1143 return true;
1144}
1145
1146// Return true if LI is invariant within scope of the loop. LI is invariant if
1147// CurLoop is dominated by an invariant.start representing the same memory
1148// location and size as the memory location LI loads from, and also the
1149// invariant.start has no uses.
1151 Loop *CurLoop) {
1152 Value *Addr = LI->getPointerOperand();
1153 const DataLayout &DL = LI->getDataLayout();
1154 const TypeSize LocSizeInBits = DL.getTypeSizeInBits(LI->getType());
1155
1156 // It is not currently possible for clang to generate an invariant.start
1157 // intrinsic with scalable vector types because we don't support thread local
1158 // sizeless types and we don't permit sizeless types in structs or classes.
1159 // Furthermore, even if support is added for this in future the intrinsic
1160 // itself is defined to have a size of -1 for variable sized objects. This
1161 // makes it impossible to verify if the intrinsic envelops our region of
1162 // interest. For example, both <vscale x 32 x i8> and <vscale x 16 x i8>
1163 // types would have a -1 parameter, but the former is clearly double the size
1164 // of the latter.
1165 if (LocSizeInBits.isScalable())
1166 return false;
1167
1168 // If we've ended up at a global/constant, bail. We shouldn't be looking at
1169 // uselists for non-local Values in a loop pass.
1170 if (isa<Constant>(Addr))
1171 return false;
1172
1173 unsigned UsesVisited = 0;
1174 // Traverse all uses of the load operand value, to see if invariant.start is
1175 // one of the uses, and whether it dominates the load instruction.
1176 for (auto *U : Addr->users()) {
1177 // Avoid traversing for Load operand with high number of users.
1178 if (++UsesVisited > MaxNumUsesTraversed)
1179 return false;
1181 // If there are escaping uses of invariant.start instruction, the load maybe
1182 // non-invariant.
1183 if (!II || II->getIntrinsicID() != Intrinsic::invariant_start ||
1184 !II->use_empty())
1185 continue;
1186 ConstantInt *InvariantSize = cast<ConstantInt>(II->getArgOperand(0));
1187 // The intrinsic supports having a -1 argument for variable sized objects
1188 // so we should check for that here.
1189 if (InvariantSize->isNegative())
1190 continue;
1191 uint64_t InvariantSizeInBits = InvariantSize->getSExtValue() * 8;
1192 // Confirm the invariant.start location size contains the load operand size
1193 // in bits. Also, the invariant.start should dominate the load, and we
1194 // should not hoist the load out of a loop that contains this dominating
1195 // invariant.start.
1196 if (LocSizeInBits.getFixedValue() <= InvariantSizeInBits &&
1197 DT->properlyDominates(II->getParent(), CurLoop->getHeader()))
1198 return true;
1199 }
1200
1201 return false;
1202}
1203
1204/// Return true if-and-only-if we know how to (mechanically) both hoist and
1205/// sink a given instruction out of a loop. Does not address legality
1206/// concerns such as aliasing or speculation safety.
1217
1218/// Return true if I is the only Instruction with a MemoryAccess in L.
1219static bool isOnlyMemoryAccess(const Instruction *I, const Loop *L,
1220 const MemorySSAUpdater &MSSAU) {
1221 for (auto *BB : L->getBlocks())
1222 if (auto *Accs = MSSAU.getMemorySSA()->getBlockAccesses(BB)) {
1223 int NotAPhi = 0;
1224 for (const auto &Acc : *Accs) {
1225 if (isa<MemoryPhi>(&Acc))
1226 continue;
1227 const auto *MUD = cast<MemoryUseOrDef>(&Acc);
1228 if (MUD->getMemoryInst() != I || NotAPhi++ == 1)
1229 return false;
1230 }
1231 }
1232 return true;
1233}
1234
1236 BatchAAResults &BAA,
1237 SinkAndHoistLICMFlags &Flags,
1238 MemoryUseOrDef *MA) {
1239 // See declaration of SetLicmMssaOptCap for usage details.
1240 if (Flags.tooManyClobberingCalls())
1241 return MA->getDefiningAccess();
1242
1243 MemoryAccess *Source =
1245 Flags.incrementClobberingCalls();
1246 return Source;
1247}
1248
1250 Loop *CurLoop, MemorySSA &MSSA,
1251 bool TargetExecutesOncePerLoop,
1252 SinkAndHoistLICMFlags &Flags,
1254 if (!LI.isUnordered())
1255 return false; // Don't sink/hoist volatile or ordered atomic loads!
1256
1257 // Loads from constant memory are always safe to move, even if they end up
1258 // in the same alias set as something that ends up being modified.
1259 if (!isModSet(AA->getModRefInfoMask(LI.getOperand(0))))
1260 return true;
1261 if (LI.hasMetadata(LLVMContext::MD_invariant_load))
1262 return true;
1263
1264 if (LI.isAtomic() && !TargetExecutesOncePerLoop)
1265 return false; // Don't risk duplicating unordered loads
1266
1267 // This checks for an invariant.start dominating the load.
1268 if (isLoadInvariantInLoop(&LI, DT, CurLoop))
1269 return true;
1270
1271 auto *MU = cast<MemoryUse>(MSSA.getMemoryAccess(&LI));
1272
1273 bool InvariantGroup = LI.hasMetadata(LLVMContext::MD_invariant_group);
1274
1275 bool Invalidated =
1276 pointerInvalidatedByLoop(&MSSA, MU, CurLoop, LI, Flags, InvariantGroup);
1277 // Check loop-invariant address because this may also be a sinkable load
1278 // whose address is not necessarily loop-invariant.
1279 if (ORE && Invalidated && CurLoop->isLoopInvariant(LI.getPointerOperand()))
1280 ORE->emit([&]() {
1282 DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", &LI)
1283 << "failed to move load with loop-invariant address "
1284 "because the loop may invalidate its value";
1285 });
1286
1287 return !Invalidated;
1288}
1289
1291 Loop *CurLoop, MemorySSAUpdater &MSSAU,
1292 bool TargetExecutesOncePerLoop,
1293 SinkAndHoistLICMFlags &Flags,
1295 // If we don't understand the instruction, bail early.
1297 return false;
1298
1299 MemorySSA *MSSA = MSSAU.getMemorySSA();
1300 // Loads have extra constraints we have to verify before we can hoist them.
1301 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
1302 return canHoistLoad(*LI, AA, DT, CurLoop, *MSSA, TargetExecutesOncePerLoop,
1303 Flags, ORE);
1304 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1305 // Don't sink calls which can throw.
1306 if (CI->mayThrow())
1307 return false;
1308
1309 // Convergent attribute has been used on operations that involve
1310 // inter-thread communication which results are implicitly affected by the
1311 // enclosing control flows. It is not safe to hoist or sink such operations
1312 // across control flow.
1313 if (CI->isConvergent())
1314 return false;
1315
1316 // FIXME: Current LLVM IR semantics don't work well with coroutines and
1317 // thread local globals. We currently treat getting the address of a thread
1318 // local global as not accessing memory, even though it may not be a
1319 // constant throughout a function with coroutines. Remove this check after
1320 // we better model semantics of thread local globals.
1321 if (CI->getFunction()->isPresplitCoroutine())
1322 return false;
1323
1324 using namespace PatternMatch;
1326 // Assumes don't actually alias anything or throw
1327 return true;
1328
1329 // Handle simple cases by querying alias analysis.
1330 MemoryEffects Behavior = AA->getMemoryEffects(CI);
1331
1332 if (Behavior.doesNotAccessMemory())
1333 return true;
1334 if (Behavior.onlyReadsMemory()) {
1335 // Might have stale MemoryDef for call that was later inferred to be
1336 // read-only.
1337 auto *MU = dyn_cast<MemoryUse>(MSSA->getMemoryAccess(CI));
1338 if (!MU)
1339 return false;
1340
1341 // If we can prove there are no writes to the memory read by the call, we
1342 // can hoist or sink.
1344 MSSA, MU, CurLoop, I, Flags, /*InvariantGroup=*/false);
1345 }
1346
1347 if (Behavior.onlyWritesMemory()) {
1348 // can hoist or sink if there are no conflicting read/writes to the
1349 // memory location written to by the call.
1350 return noConflictingReadWrites(CI, MSSA, AA, CurLoop, Flags);
1351 }
1352
1353 return false;
1354 } else if (auto *FI = dyn_cast<FenceInst>(&I)) {
1355 // Fences alias (most) everything to provide ordering. For the moment,
1356 // just give up if there are any other memory operations in the loop.
1357 return isOnlyMemoryAccess(FI, CurLoop, MSSAU);
1358 } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
1359 if (!SI->isUnordered())
1360 return false; // Don't sink/hoist volatile or ordered atomic store!
1361
1362 // We can only hoist a store that we can prove writes a value which is not
1363 // read or overwritten within the loop. For those cases, we fallback to
1364 // load store promotion instead. TODO: We can extend this to cases where
1365 // there is exactly one write to the location and that write dominates an
1366 // arbitrary number of reads in the loop.
1367 if (isOnlyMemoryAccess(SI, CurLoop, MSSAU))
1368 return true;
1369 return noConflictingReadWrites(SI, MSSA, AA, CurLoop, Flags);
1370 }
1371
1372 assert(!I.mayReadOrWriteMemory() && "unhandled aliasing");
1373
1374 // We've established mechanical ability and aliasing, it's up to the caller
1375 // to check fault safety
1376 return true;
1377}
1378
1379/// Returns true if a PHINode is a trivially replaceable with an
1380/// Instruction.
1381/// This is true when all incoming values are that instruction.
1382/// This pattern occurs most often with LCSSA PHI nodes.
1383///
1384static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I) {
1385 for (const Value *IncValue : PN.incoming_values())
1386 if (IncValue != &I)
1387 return false;
1388
1389 return true;
1390}
1391
1392/// Return true if the instruction is foldable in the loop.
1393static bool isFoldableInLoop(const Instruction &I, const Loop *CurLoop,
1394 const TargetTransformInfo *TTI) {
1395 if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
1396 InstructionCost CostI =
1397 TTI->getInstructionCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
1398 if (CostI != TargetTransformInfo::TCC_Free)
1399 return false;
1400 // For a GEP, we cannot simply use getInstructionCost because currently
1401 // it optimistically assumes that a GEP will fold into addressing mode
1402 // regardless of its users.
1403 const BasicBlock *BB = GEP->getParent();
1404 for (const User *U : GEP->users()) {
1405 const Instruction *UI = cast<Instruction>(U);
1406 if (CurLoop->contains(UI) &&
1407 (BB != UI->getParent() ||
1408 (!isa<StoreInst>(UI) && !isa<LoadInst>(UI))))
1409 return false;
1410 }
1411 return true;
1412 }
1413
1414 return false;
1415}
1416
1417/// Return true if the only users of this instruction are outside of
1418/// the loop. If this is true, we can sink the instruction to the exit
1419/// blocks of the loop.
1420///
1421/// We also return true if the instruction could be folded away in lowering.
1422/// (e.g., a GEP can be folded into a load as an addressing mode in the loop).
1423static bool isNotUsedOrFoldableInLoop(const Instruction &I, const Loop *CurLoop,
1424 const LoopSafetyInfo *SafetyInfo,
1426 bool &FoldableInLoop, bool LoopNestMode) {
1427 bool IsFoldable = isFoldableInLoop(I, CurLoop, TTI);
1428 for (const User *U : I.users()) {
1429 const Instruction *UI = cast<Instruction>(U);
1430 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
1431 const BasicBlock *BB = PN->getParent();
1432 // We cannot sink uses in catchswitches.
1434 return false;
1435
1436 // We need to sink a callsite to a unique funclet. Avoid sinking if the
1437 // phi use is too muddled.
1438 if (isa<CallInst>(I)) {
1439 const auto &BlockColors = SafetyInfo->getBlockColors();
1440 if (!BlockColors.empty() &&
1441 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
1442 return false;
1443 }
1444
1445 if (LoopNestMode) {
1446 while (isa<PHINode>(UI) && UI->hasOneUser() &&
1447 UI->getNumOperands() == 1) {
1448 if (!CurLoop->contains(UI))
1449 break;
1450 UI = cast<Instruction>(UI->user_back());
1451 }
1452 }
1453 }
1454
1455 if (CurLoop->contains(UI)) {
1456 if (IsFoldable) {
1457 FoldableInLoop = true;
1458 continue;
1459 }
1460 return false;
1461 }
1462 }
1463 return true;
1464}
1465
1467 Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI,
1468 const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater &MSSAU) {
1469 Instruction *New;
1470 if (auto *CI = dyn_cast<CallInst>(&I)) {
1471 const auto &BlockColors = SafetyInfo->getBlockColors();
1472
1473 // Sinking call-sites need to be handled differently from other
1474 // instructions. The cloned call-site needs a funclet bundle operand
1475 // appropriate for its location in the CFG.
1477 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
1478 BundleIdx != BundleEnd; ++BundleIdx) {
1479 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
1480 if (Bundle.getTagID() == LLVMContext::OB_funclet)
1481 continue;
1482
1483 OpBundles.emplace_back(Bundle);
1484 }
1485
1486 if (!BlockColors.empty()) {
1487 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
1488 assert(CV.size() == 1 && "non-unique color for exit block!");
1489 BasicBlock *BBColor = CV.front();
1490 BasicBlock::iterator EHPad = BBColor->getFirstNonPHIIt();
1491 if (EHPad->isEHPad())
1492 OpBundles.emplace_back("funclet", &*EHPad);
1493 }
1494
1495 New = CallInst::Create(CI, OpBundles);
1496 New->copyMetadata(*CI);
1497 } else {
1498 New = I.clone();
1499 }
1500
1501 New->insertInto(&ExitBlock, ExitBlock.getFirstInsertionPt());
1502 if (!I.getName().empty())
1503 New->setName(I.getName() + ".le");
1504
1505 if (MSSAU.getMemorySSA()->getMemoryAccess(&I)) {
1506 // Create a new MemoryAccess and let MemorySSA set its defining access.
1507 // After running some passes, MemorySSA might be outdated, and the
1508 // instruction `I` may have become a non-memory touching instruction.
1509 MemoryAccess *NewMemAcc = MSSAU.createMemoryAccessInBB(
1510 New, nullptr, New->getParent(), MemorySSA::Beginning,
1511 /*CreationMustSucceed=*/false);
1512 if (NewMemAcc) {
1513 if (auto *MemDef = dyn_cast<MemoryDef>(NewMemAcc))
1514 MSSAU.insertDef(MemDef, /*RenameUses=*/true);
1515 else {
1516 auto *MemUse = cast<MemoryUse>(NewMemAcc);
1517 MSSAU.insertUse(MemUse, /*RenameUses=*/true);
1518 }
1519 }
1520 }
1521
1522 // Build LCSSA PHI nodes for any in-loop operands (if legal). Note that
1523 // this is particularly cheap because we can rip off the PHI node that we're
1524 // replacing for the number and blocks of the predecessors.
1525 // OPT: If this shows up in a profile, we can instead finish sinking all
1526 // invariant instructions, and then walk their operands to re-establish
1527 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
1528 // sinking bottom-up.
1529 for (Use &Op : New->operands())
1530 if (LI->wouldBeOutOfLoopUseRequiringLCSSA(Op.get(), PN.getParent())) {
1531 auto *OInst = cast<Instruction>(Op.get());
1532 PHINode *OpPN =
1533 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
1534 OInst->getName() + ".lcssa");
1535 OpPN->insertBefore(ExitBlock.begin());
1536 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1537 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
1538 Op = OpPN;
1539 }
1540 return New;
1541}
1542
1544 MemorySSAUpdater &MSSAU) {
1545 MSSAU.removeMemoryAccess(&I);
1546 SafetyInfo.removeInstruction(&I);
1547 I.eraseFromParent();
1548}
1549
1551 ICFLoopSafetyInfo &SafetyInfo,
1552 MemorySSAUpdater &MSSAU,
1553 ScalarEvolution *SE) {
1554 SafetyInfo.removeInstruction(&I);
1555 SafetyInfo.insertInstructionTo(&I, Dest->getParent());
1556 I.moveBefore(*Dest->getParent(), Dest);
1558 MSSAU.getMemorySSA()->getMemoryAccess(&I)))
1559 MSSAU.moveToPlace(OldMemAcc, Dest->getParent(),
1561 if (SE)
1563}
1564
1566 PHINode *TPN, Instruction *I, LoopInfo *LI,
1568 const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop,
1569 MemorySSAUpdater &MSSAU) {
1571 "Expect only trivially replaceable PHI");
1572 BasicBlock *ExitBlock = TPN->getParent();
1573 auto [It, Inserted] = SunkCopies.try_emplace(ExitBlock);
1574 if (Inserted)
1575 It->second = cloneInstructionInExitBlock(*I, *ExitBlock, *TPN, LI,
1576 SafetyInfo, MSSAU);
1577 return It->second;
1578}
1579
1580static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo) {
1581 BasicBlock *BB = PN->getParent();
1582 if (!BB->canSplitPredecessors())
1583 return false;
1584 // It's not impossible to split EHPad blocks, but if BlockColors already exist
1585 // it require updating BlockColors for all offspring blocks accordingly. By
1586 // skipping such corner case, we can make updating BlockColors after splitting
1587 // predecessor fairly simple.
1588 if (!SafetyInfo->getBlockColors().empty() &&
1589 BB->getFirstNonPHIIt()->isEHPad())
1590 return false;
1591 for (BasicBlock *BBPred : predecessors(BB)) {
1592 if (isa<IndirectBrInst>(BBPred->getTerminator()))
1593 return false;
1594 }
1595 return true;
1596}
1597
1599 LoopInfo *LI, const Loop *CurLoop,
1600 LoopSafetyInfo *SafetyInfo,
1601 MemorySSAUpdater *MSSAU) {
1602#ifndef NDEBUG
1604 CurLoop->getUniqueExitBlocks(ExitBlocks);
1605 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(llvm::from_range, ExitBlocks);
1606#endif
1607 BasicBlock *ExitBB = PN->getParent();
1608 assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block.");
1609
1610 // Split predecessors of the loop exit to make instructions in the loop are
1611 // exposed to exit blocks through trivially replaceable PHIs while keeping the
1612 // loop in the canonical form where each predecessor of each exit block should
1613 // be contained within the loop. For example, this will convert the loop below
1614 // from
1615 //
1616 // LB1:
1617 // %v1 =
1618 // br %LE, %LB2
1619 // LB2:
1620 // %v2 =
1621 // br %LE, %LB1
1622 // LE:
1623 // %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replaceable
1624 //
1625 // to
1626 //
1627 // LB1:
1628 // %v1 =
1629 // br %LE.split, %LB2
1630 // LB2:
1631 // %v2 =
1632 // br %LE.split2, %LB1
1633 // LE.split:
1634 // %p1 = phi [%v1, %LB1] <-- trivially replaceable
1635 // br %LE
1636 // LE.split2:
1637 // %p2 = phi [%v2, %LB2] <-- trivially replaceable
1638 // br %LE
1639 // LE:
1640 // %p = phi [%p1, %LE.split], [%p2, %LE.split2]
1641 //
1642 const auto &BlockColors = SafetyInfo->getBlockColors();
1643 SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB));
1644 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
1645 while (!PredBBs.empty()) {
1646 BasicBlock *PredBB = *PredBBs.begin();
1647 assert(CurLoop->contains(PredBB) &&
1648 "Expect all predecessors are in the loop");
1649 if (PN->getBasicBlockIndex(PredBB) >= 0) {
1651 ExitBB, PredBB, ".split.loop.exit", &DTU, LI, MSSAU, true);
1652 // Since we do not allow splitting EH-block with BlockColors in
1653 // canSplitPredecessors(), we can simply assign predecessor's color to
1654 // the new block.
1655 if (!BlockColors.empty())
1656 // Grab a reference to the ColorVector to be inserted before getting the
1657 // reference to the vector we are copying because inserting the new
1658 // element in BlockColors might cause the map to be reallocated.
1659 SafetyInfo->copyColors(NewPred, PredBB);
1660 }
1661 PredBBs.remove(PredBB);
1662 }
1663}
1664
1665/// When an instruction is found to only be used outside of the loop, this
1666/// function moves it to the exit blocks and patches up SSA form as needed.
1667/// This method is guaranteed to remove the original instruction from its
1668/// position, and may either delete it or move it to outside of the loop.
1669///
1670static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
1671 const Loop *CurLoop, ICFLoopSafetyInfo *SafetyInfo,
1673 bool Changed = false;
1674 LLVM_DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
1675
1676 // Iterate over users to be ready for actual sinking. Replace users via
1677 // unreachable blocks with undef and make all user PHIs trivially replaceable.
1678 SmallPtrSet<Instruction *, 8> VisitedUsers;
1679 for (Instruction::user_iterator UI = I.user_begin(), UE = I.user_end();
1680 UI != UE;) {
1681 auto *User = cast<Instruction>(*UI);
1682 Use &U = UI.getUse();
1683 ++UI;
1684
1685 if (VisitedUsers.count(User) || CurLoop->contains(User))
1686 continue;
1687
1688 if (!DT->isReachableFromEntry(User->getParent())) {
1689 U = PoisonValue::get(I.getType());
1690 Changed = true;
1691 continue;
1692 }
1693
1694 // The user must be a PHI node.
1695 PHINode *PN = cast<PHINode>(User);
1696
1697 // Surprisingly, instructions can be used outside of loops without any
1698 // exits. This can only happen in PHI nodes if the incoming block is
1699 // unreachable.
1700 BasicBlock *BB = PN->getIncomingBlock(U);
1701 if (!DT->isReachableFromEntry(BB)) {
1702 U = PoisonValue::get(I.getType());
1703 Changed = true;
1704 continue;
1705 }
1706
1707 VisitedUsers.insert(PN);
1708 if (isTriviallyReplaceablePHI(*PN, I))
1709 continue;
1710
1711 if (!canSplitPredecessors(PN, SafetyInfo))
1712 return Changed;
1713
1714 // Split predecessors of the PHI so that we can make users trivially
1715 // replaceable.
1716 splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop, SafetyInfo, &MSSAU);
1717
1718 // Should rebuild the iterators, as they may be invalidated by
1719 // splitPredecessorsOfLoopExit().
1720 UI = I.user_begin();
1721 UE = I.user_end();
1722 }
1723
1724 if (VisitedUsers.empty())
1725 return Changed;
1726
1727 ORE->emit([&]() {
1728 return OptimizationRemark(DEBUG_TYPE, "InstSunk", &I)
1729 << "sinking " << ore::NV("Inst", &I);
1730 });
1731 if (isa<LoadInst>(I))
1732 ++NumMovedLoads;
1733 else if (isa<CallInst>(I))
1734 ++NumMovedCalls;
1735 ++NumSunk;
1736
1737#ifndef NDEBUG
1739 CurLoop->getUniqueExitBlocks(ExitBlocks);
1740 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(llvm::from_range, ExitBlocks);
1741#endif
1742
1743 // Clones of this instruction. Don't create more than one per exit block!
1745
1746 // If this instruction is only used outside of the loop, then all users are
1747 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
1748 // the instruction.
1749 // First check if I is worth sinking for all uses. Sink only when it is worth
1750 // across all uses.
1751 SmallSetVector<User*, 8> Users(I.user_begin(), I.user_end());
1752 for (auto *UI : Users) {
1753 auto *User = cast<Instruction>(UI);
1754
1755 if (CurLoop->contains(User))
1756 continue;
1757
1758 PHINode *PN = cast<PHINode>(User);
1759 assert(ExitBlockSet.count(PN->getParent()) &&
1760 "The LCSSA PHI is not in an exit block!");
1761
1762 // The PHI must be trivially replaceable.
1764 PN, &I, LI, SunkCopies, SafetyInfo, CurLoop, MSSAU);
1765 // As we sink the instruction out of the BB, drop its debug location.
1766 New->dropLocation();
1767 PN->replaceAllUsesWith(New);
1768 eraseInstruction(*PN, *SafetyInfo, MSSAU);
1769 Changed = true;
1770 }
1771 return Changed;
1772}
1773
1774/// When an instruction is found to only use loop invariant operands that
1775/// is safe to hoist, this instruction is called to do the dirty work.
1776///
1777static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
1778 BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo,
1781 LLVM_DEBUG(dbgs() << "LICM hoisting to " << Dest->getNameOrAsOperand() << ": "
1782 << I << "\n");
1783 ORE->emit([&]() {
1784 return OptimizationRemark(DEBUG_TYPE, "Hoisted", &I) << "hoisting "
1785 << ore::NV("Inst", &I);
1786 });
1787
1788 // Metadata can be dependent on conditions we are hoisting above.
1789 // Conservatively strip all metadata on the instruction unless we were
1790 // guaranteed to execute I if we entered the loop, in which case the metadata
1791 // is valid in the loop preheader.
1792 // Similarly, If I is a call and it is not guaranteed to execute in the loop,
1793 // then moving to the preheader means we should strip attributes on the call
1794 // that can cause UB since we may be hoisting above conditions that allowed
1795 // inferring those attributes. They may not be valid at the preheader.
1796 if ((I.hasMetadataOtherThanDebugLoc() || isa<CallInst>(I)) &&
1797 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
1798 // time in isGuaranteedToExecute if we don't actually have anything to
1799 // drop. It is a compile time optimization, not required for correctness.
1800 !SafetyInfo->isGuaranteedToExecute(I, DT)) {
1801 I.dropUBImplyingAttrsAndMetadata();
1802 }
1803
1804 if (isa<PHINode>(I))
1805 // Move the new node to the end of the phi list in the destination block.
1806 moveInstructionBefore(I, Dest->getFirstNonPHIIt(), *SafetyInfo, MSSAU, SE);
1807 else
1808 // Move the new node to the destination block, before its terminator.
1809 moveInstructionBefore(I, Dest->getTerminator()->getIterator(), *SafetyInfo,
1810 MSSAU, SE);
1811
1812 I.updateLocationAfterHoist();
1813
1814 if (isa<LoadInst>(I))
1815 ++NumMovedLoads;
1816 else if (isa<CallInst>(I))
1817 ++NumMovedCalls;
1818 ++NumHoisted;
1819}
1820
1821/// Only sink or hoist an instruction if it is not a trapping instruction,
1822/// or if the instruction is known not to trap when moved to the preheader.
1823/// or if it is a trapping instruction and is guaranteed to execute.
1825 Instruction &Inst, const DominatorTree *DT, const TargetLibraryInfo *TLI,
1826 const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo,
1827 OptimizationRemarkEmitter *ORE, const Instruction *CtxI,
1828 AssumptionCache *AC, bool AllowSpeculation) {
1829 if (AllowSpeculation &&
1830 isSafeToSpeculativelyExecute(&Inst, CtxI, AC, DT, TLI))
1831 return true;
1832
1833 bool GuaranteedToExecute = SafetyInfo->isGuaranteedToExecute(Inst, DT);
1834
1835 if (!GuaranteedToExecute) {
1836 auto *LI = dyn_cast<LoadInst>(&Inst);
1837 if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand()))
1838 ORE->emit([&]() {
1840 DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI)
1841 << "failed to hoist load with loop-invariant address "
1842 "because load is conditionally executed";
1843 });
1844 }
1845
1846 return GuaranteedToExecute;
1847}
1848
1849namespace {
1850class LoopPromoter : public LoadAndStorePromoter {
1851 Value *SomePtr; // Designated pointer to store to.
1852 SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
1853 SmallVectorImpl<BasicBlock::iterator> &LoopInsertPts;
1854 SmallVectorImpl<MemoryAccess *> &MSSAInsertPts;
1855 PredIteratorCache &PredCache;
1856 MemorySSAUpdater &MSSAU;
1857 LoopInfo &LI;
1858 DebugLoc DL;
1860 bool UnorderedAtomic;
1861 AAMDNodes AATags;
1862 ICFLoopSafetyInfo &SafetyInfo;
1863 bool CanInsertStoresInExitBlocks;
1865
1866 // We're about to add a use of V in a loop exit block. Insert an LCSSA phi
1867 // (if legal) if doing so would add an out-of-loop use to an instruction
1868 // defined in-loop.
1869 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
1870 if (!LI.wouldBeOutOfLoopUseRequiringLCSSA(V, BB))
1871 return V;
1872
1874 // We need to create an LCSSA PHI node for the incoming value and
1875 // store that.
1876 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
1877 I->getName() + ".lcssa");
1878 PN->insertBefore(BB->begin());
1879 for (BasicBlock *Pred : PredCache.get(BB))
1880 PN->addIncoming(I, Pred);
1881 return PN;
1882 }
1883
1884public:
1885 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
1886 SmallVectorImpl<BasicBlock *> &LEB,
1887 SmallVectorImpl<BasicBlock::iterator> &LIP,
1888 SmallVectorImpl<MemoryAccess *> &MSSAIP, PredIteratorCache &PIC,
1889 MemorySSAUpdater &MSSAU, LoopInfo &li, DebugLoc dl,
1890 Align Alignment, bool UnorderedAtomic, const AAMDNodes &AATags,
1891 ICFLoopSafetyInfo &SafetyInfo, bool CanInsertStoresInExitBlocks)
1892 : LoadAndStorePromoter(Insts, S), SomePtr(SP), LoopExitBlocks(LEB),
1893 LoopInsertPts(LIP), MSSAInsertPts(MSSAIP), PredCache(PIC), MSSAU(MSSAU),
1894 LI(li), DL(std::move(dl)), Alignment(Alignment),
1895 UnorderedAtomic(UnorderedAtomic), AATags(AATags),
1896 SafetyInfo(SafetyInfo),
1897 CanInsertStoresInExitBlocks(CanInsertStoresInExitBlocks), Uses(Insts) {}
1898
1899 void insertStoresInLoopExitBlocks() {
1900 // Insert stores after in the loop exit blocks. Each exit block gets a
1901 // store of the live-out values that feed them. Since we've already told
1902 // the SSA updater about the defs in the loop and the preheader
1903 // definition, it is all set and we can start using it.
1904 DIAssignID *NewID = nullptr;
1905 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
1906 BasicBlock *ExitBlock = LoopExitBlocks[i];
1907 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
1908 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
1909 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
1910 BasicBlock::iterator InsertPos = LoopInsertPts[i];
1911 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
1912 if (UnorderedAtomic)
1913 NewSI->setOrdering(AtomicOrdering::Unordered);
1914 NewSI->setAlignment(Alignment);
1915 NewSI->setDebugLoc(DL);
1916 // Attach DIAssignID metadata to the new store, generating it on the
1917 // first loop iteration.
1918 if (i == 0) {
1919 // NewSI will have its DIAssignID set here if there are any stores in
1920 // Uses with a DIAssignID attachment. This merged ID will then be
1921 // attached to the other inserted stores (in the branch below).
1922 NewSI->mergeDIAssignID(Uses);
1924 NewSI->getMetadata(LLVMContext::MD_DIAssignID));
1925 } else {
1926 // Attach the DIAssignID (or nullptr) merged from Uses in the branch
1927 // above.
1928 NewSI->setMetadata(LLVMContext::MD_DIAssignID, NewID);
1929 }
1930
1931 if (AATags)
1932 NewSI->setAAMetadata(AATags);
1933
1934 MemoryAccess *MSSAInsertPoint = MSSAInsertPts[i];
1935 MemoryAccess *NewMemAcc;
1936 if (!MSSAInsertPoint) {
1937 NewMemAcc = MSSAU.createMemoryAccessInBB(
1938 NewSI, nullptr, NewSI->getParent(), MemorySSA::Beginning);
1939 } else {
1940 NewMemAcc =
1941 MSSAU.createMemoryAccessAfter(NewSI, nullptr, MSSAInsertPoint);
1942 }
1943 MSSAInsertPts[i] = NewMemAcc;
1944 MSSAU.insertDef(cast<MemoryDef>(NewMemAcc), true);
1945 // FIXME: true for safety, false may still be correct.
1946 }
1947 }
1948
1949 void doExtraRewritesBeforeFinalDeletion() override {
1950 if (CanInsertStoresInExitBlocks)
1951 insertStoresInLoopExitBlocks();
1952 }
1953
1954 void instructionDeleted(Instruction *I) const override {
1955 SafetyInfo.removeInstruction(I);
1956 MSSAU.removeMemoryAccess(I);
1957 }
1958
1959 bool shouldDelete(Instruction *I) const override {
1960 if (isa<StoreInst>(I))
1961 return CanInsertStoresInExitBlocks;
1962 return true;
1963 }
1964};
1965
1966bool isNotCapturedBeforeOrInLoop(const Value *V, const Loop *L,
1967 DominatorTree *DT) {
1968 // We can perform the captured-before check against any instruction in the
1969 // loop header, as the loop header is reachable from any instruction inside
1970 // the loop.
1971 // TODO: ReturnCaptures=true shouldn't be necessary here.
1973 V, /*ReturnCaptures=*/true, L->getHeader()->getTerminator(), DT,
1974 /*IncludeI=*/false, CaptureComponents::Provenance));
1975}
1976
1977/// Return true if we can prove that a caller cannot inspect the object if an
1978/// unwind occurs inside the loop.
1979bool isNotVisibleOnUnwindInLoop(const Value *Object, const Loop *L,
1980 DominatorTree *DT) {
1981 bool RequiresNoCaptureBeforeUnwind;
1982 if (!isNotVisibleOnUnwind(Object, RequiresNoCaptureBeforeUnwind))
1983 return false;
1984
1985 return !RequiresNoCaptureBeforeUnwind ||
1986 isNotCapturedBeforeOrInLoop(Object, L, DT);
1987}
1988
1989bool isThreadLocalObject(const Value *Object, const Loop *L, DominatorTree *DT,
1991 // The object must be function-local to start with, and then not captured
1992 // before/in the loop.
1993 return (isIdentifiedFunctionLocal(Object) &&
1994 isNotCapturedBeforeOrInLoop(Object, L, DT)) ||
1995 (TTI->isSingleThreaded() || SingleThread);
1996}
1997
1998} // namespace
1999
2000/// Try to promote memory values to scalars by sinking stores out of the
2001/// loop and moving loads to before the loop. We do this by looping over
2002/// the stores in the loop, looking for stores to Must pointers which are
2003/// loop invariant.
2004///
2006 const SmallSetVector<Value *, 8> &PointerMustAliases,
2011 const TargetLibraryInfo *TLI, TargetTransformInfo *TTI, Loop *CurLoop,
2012 MemorySSAUpdater &MSSAU, ICFLoopSafetyInfo *SafetyInfo,
2013 OptimizationRemarkEmitter *ORE, bool AllowSpeculation,
2014 bool HasReadsOutsideSet) {
2015 // Verify inputs.
2016 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
2017 SafetyInfo != nullptr &&
2018 "Unexpected Input to promoteLoopAccessesToScalars");
2019
2020 LLVM_DEBUG({
2021 dbgs() << "Trying to promote set of must-aliased pointers:\n";
2022 for (Value *Ptr : PointerMustAliases)
2023 dbgs() << " " << *Ptr << "\n";
2024 });
2025 ++NumPromotionCandidates;
2026
2027 Value *SomePtr = *PointerMustAliases.begin();
2028 BasicBlock *Preheader = CurLoop->getLoopPreheader();
2029
2030 // It is not safe to promote a load/store from the loop if the load/store is
2031 // conditional. For example, turning:
2032 //
2033 // for () { if (c) *P += 1; }
2034 //
2035 // into:
2036 //
2037 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
2038 //
2039 // is not safe, because *P may only be valid to access if 'c' is true.
2040 //
2041 // The safety property divides into two parts:
2042 // p1) The memory may not be dereferenceable on entry to the loop. In this
2043 // case, we can't insert the required load in the preheader.
2044 // p2) The memory model does not allow us to insert a store along any dynamic
2045 // path which did not originally have one.
2046 //
2047 // If at least one store is guaranteed to execute, both properties are
2048 // satisfied, and promotion is legal.
2049 //
2050 // This, however, is not a necessary condition. Even if no store/load is
2051 // guaranteed to execute, we can still establish these properties.
2052 // We can establish (p1) by proving that hoisting the load into the preheader
2053 // is safe (i.e. proving dereferenceability on all paths through the loop). We
2054 // can use any access within the alias set to prove dereferenceability,
2055 // since they're all must alias.
2056 //
2057 // There are two ways establish (p2):
2058 // a) Prove the location is thread-local. In this case the memory model
2059 // requirement does not apply, and stores are safe to insert.
2060 // b) Prove a store dominates every exit block. In this case, if an exit
2061 // blocks is reached, the original dynamic path would have taken us through
2062 // the store, so inserting a store into the exit block is safe. Note that this
2063 // is different from the store being guaranteed to execute. For instance,
2064 // if an exception is thrown on the first iteration of the loop, the original
2065 // store is never executed, but the exit blocks are not executed either.
2066
2067 bool DereferenceableInPH = false;
2068 bool StoreIsGuaranteedToExecute = false;
2069 bool LoadIsGuaranteedToExecute = false;
2070 bool FoundLoadToPromote = false;
2071
2072 // Goes from Unknown to either Safe or Unsafe, but can't switch between them.
2073 enum {
2074 StoreSafe,
2075 StoreUnsafe,
2076 StoreSafetyUnknown,
2077 } StoreSafety = StoreSafetyUnknown;
2078
2080
2081 // We start with an alignment of one and try to find instructions that allow
2082 // us to prove better alignment.
2083 Align Alignment;
2084 // Keep track of which types of access we see
2085 bool SawUnorderedAtomic = false;
2086 bool SawNotAtomic = false;
2087 AAMDNodes AATags;
2088
2089 const DataLayout &MDL = Preheader->getDataLayout();
2090
2091 // If there are reads outside the promoted set, then promoting stores is
2092 // definitely not safe.
2093 if (HasReadsOutsideSet)
2094 StoreSafety = StoreUnsafe;
2095
2096 if (StoreSafety == StoreSafetyUnknown && SafetyInfo->anyBlockMayThrow()) {
2097 // If a loop can throw, we have to insert a store along each unwind edge.
2098 // That said, we can't actually make the unwind edge explicit. Therefore,
2099 // we have to prove that the store is dead along the unwind edge. We do
2100 // this by proving that the caller can't have a reference to the object
2101 // after return and thus can't possibly load from the object.
2102 Value *Object = getUnderlyingObject(SomePtr);
2103 if (!isNotVisibleOnUnwindInLoop(Object, CurLoop, DT))
2104 StoreSafety = StoreUnsafe;
2105 }
2106
2107 // Check that all accesses to pointers in the alias set use the same type.
2108 // We cannot (yet) promote a memory location that is loaded and stored in
2109 // different sizes. While we are at it, collect alignment and AA info.
2110 Type *AccessTy = nullptr;
2111 for (Value *ASIV : PointerMustAliases) {
2112 for (Use &U : ASIV->uses()) {
2113 // Ignore instructions that are outside the loop.
2114 Instruction *UI = dyn_cast<Instruction>(U.getUser());
2115 if (!UI || !CurLoop->contains(UI))
2116 continue;
2117
2118 // If there is an non-load/store instruction in the loop, we can't promote
2119 // it.
2120 if (LoadInst *Load = dyn_cast<LoadInst>(UI)) {
2121 if (!Load->isUnordered())
2122 return false;
2123
2124 SawUnorderedAtomic |= Load->isAtomic();
2125 SawNotAtomic |= !Load->isAtomic();
2126 FoundLoadToPromote = true;
2127
2128 Align InstAlignment = Load->getAlign();
2129
2130 if (!LoadIsGuaranteedToExecute)
2131 LoadIsGuaranteedToExecute =
2132 SafetyInfo->isGuaranteedToExecute(*UI, DT);
2133
2134 // Note that proving a load safe to speculate requires proving
2135 // sufficient alignment at the target location. Proving it guaranteed
2136 // to execute does as well. Thus we can increase our guaranteed
2137 // alignment as well.
2138 if (!DereferenceableInPH || (InstAlignment > Alignment))
2140 *Load, DT, TLI, CurLoop, SafetyInfo, ORE,
2141 Preheader->getTerminator(), AC, AllowSpeculation)) {
2142 DereferenceableInPH = true;
2143 Alignment = std::max(Alignment, InstAlignment);
2144 }
2145 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
2146 // Stores *of* the pointer are not interesting, only stores *to* the
2147 // pointer.
2148 if (U.getOperandNo() != StoreInst::getPointerOperandIndex())
2149 continue;
2150 if (!Store->isUnordered())
2151 return false;
2152
2153 SawUnorderedAtomic |= Store->isAtomic();
2154 SawNotAtomic |= !Store->isAtomic();
2155
2156 // If the store is guaranteed to execute, both properties are satisfied.
2157 // We may want to check if a store is guaranteed to execute even if we
2158 // already know that promotion is safe, since it may have higher
2159 // alignment than any other guaranteed stores, in which case we can
2160 // raise the alignment on the promoted store.
2161 Align InstAlignment = Store->getAlign();
2162 bool GuaranteedToExecute = SafetyInfo->isGuaranteedToExecute(*UI, DT);
2163 StoreIsGuaranteedToExecute |= GuaranteedToExecute;
2164 if (GuaranteedToExecute) {
2165 DereferenceableInPH = true;
2166 if (StoreSafety == StoreSafetyUnknown)
2167 StoreSafety = StoreSafe;
2168 Alignment = std::max(Alignment, InstAlignment);
2169 }
2170
2171 // If a store dominates all exit blocks, it is safe to sink.
2172 // As explained above, if an exit block was executed, a dominating
2173 // store must have been executed at least once, so we are not
2174 // introducing stores on paths that did not have them.
2175 // Note that this only looks at explicit exit blocks. If we ever
2176 // start sinking stores into unwind edges (see above), this will break.
2177 if (StoreSafety == StoreSafetyUnknown &&
2178 llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) {
2179 return DT->dominates(Store->getParent(), Exit);
2180 }))
2181 StoreSafety = StoreSafe;
2182
2183 // If the store is not guaranteed to execute, we may still get
2184 // deref info through it.
2185 if (!DereferenceableInPH) {
2186 DereferenceableInPH = isDereferenceableAndAlignedPointer(
2187 Store->getPointerOperand(), Store->getValueOperand()->getType(),
2188 Store->getAlign(),
2189 SimplifyQuery(MDL, TLI, DT, AC, Preheader->getTerminator()));
2190 }
2191 } else
2192 continue; // Not a load or store.
2193
2194 if (!AccessTy)
2195 AccessTy = getLoadStoreType(UI);
2196 else if (AccessTy != getLoadStoreType(UI))
2197 return false;
2198
2199 // Merge the AA tags.
2200 if (LoopUses.empty()) {
2201 // On the first load/store, just take its AA tags.
2202 AATags = UI->getAAMetadata();
2203 } else if (AATags) {
2204 AATags = AATags.merge(UI->getAAMetadata());
2205 }
2206
2207 LoopUses.push_back(UI);
2208 }
2209 }
2210
2211 // If we found both an unordered atomic instruction and a non-atomic memory
2212 // access, bail. We can't blindly promote non-atomic to atomic since we
2213 // might not be able to lower the result. We can't downgrade since that
2214 // would violate memory model. Also, align 0 is an error for atomics.
2215 if (SawUnorderedAtomic && SawNotAtomic)
2216 return false;
2217
2218 // If we're inserting an atomic load in the preheader, we must be able to
2219 // lower it. We're only guaranteed to be able to lower naturally aligned
2220 // atomics.
2221 if (SawUnorderedAtomic && Alignment < MDL.getTypeStoreSize(AccessTy))
2222 return false;
2223
2224 // If we couldn't prove we can hoist the load, bail.
2225 if (!DereferenceableInPH) {
2226 LLVM_DEBUG(dbgs() << "Not promoting: Not dereferenceable in preheader\n");
2227 return false;
2228 }
2229
2230 // We know we can hoist the load, but don't have a guaranteed store.
2231 // Check whether the location is writable and thread-local. If it is, then we
2232 // can insert stores along paths which originally didn't have them without
2233 // violating the memory model.
2234 if (StoreSafety == StoreSafetyUnknown) {
2235 Value *Object = getUnderlyingObject(SomePtr);
2236 bool ExplicitlyDereferenceableOnly;
2237 // The dereferenceability query here is only required to satisfy the
2238 // writable contract, actual dereferenceability has already been proven
2239 // above. As such, we can ignore frees.
2240 if (isWritableObject(Object, ExplicitlyDereferenceableOnly) &&
2241 (!ExplicitlyDereferenceableOnly ||
2242 isDereferenceablePointer(SomePtr, AccessTy, MDL,
2243 /*IgnoreFree=*/true)) &&
2244 isThreadLocalObject(Object, CurLoop, DT, TTI))
2245 StoreSafety = StoreSafe;
2246 }
2247
2248 // If we've still failed to prove we can sink the store, hoist the load
2249 // only, if possible.
2250 if (StoreSafety != StoreSafe && !FoundLoadToPromote)
2251 // If we cannot hoist the load either, give up.
2252 return false;
2253
2254 // Lets do the promotion!
2255 if (StoreSafety == StoreSafe) {
2256 LLVM_DEBUG(dbgs() << "LICM: Promoting load/store of the value: " << *SomePtr
2257 << '\n');
2258 ++NumLoadStorePromoted;
2259 } else {
2260 LLVM_DEBUG(dbgs() << "LICM: Promoting load of the value: " << *SomePtr
2261 << '\n');
2262 ++NumLoadPromoted;
2263 }
2264
2265 ORE->emit([&]() {
2266 return OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar",
2267 LoopUses[0])
2268 << "Moving accesses to memory location out of the loop";
2269 });
2270
2271 // Look at all the loop uses, and try to merge their locations.
2272 std::vector<DebugLoc> LoopUsesLocs;
2273 for (auto U : LoopUses)
2274 LoopUsesLocs.push_back(U->getDebugLoc());
2275 auto DL = DebugLoc::getMergedLocations(LoopUsesLocs);
2276
2277 // We use the SSAUpdater interface to insert phi nodes as required.
2279 SSAUpdater SSA(&NewPHIs);
2280 LoopPromoter Promoter(SomePtr, LoopUses, SSA, ExitBlocks, InsertPts,
2281 MSSAInsertPts, PIC, MSSAU, *LI, DL, Alignment,
2282 SawUnorderedAtomic,
2283 StoreIsGuaranteedToExecute ? AATags : AAMDNodes(),
2284 *SafetyInfo, StoreSafety == StoreSafe);
2285
2286 // Set up the preheader to have a definition of the value. It is the live-out
2287 // value from the preheader that uses in the loop will use.
2288 LoadInst *PreheaderLoad = nullptr;
2289 if (FoundLoadToPromote || !StoreIsGuaranteedToExecute) {
2290 PreheaderLoad =
2291 new LoadInst(AccessTy, SomePtr, SomePtr->getName() + ".promoted",
2292 Preheader->getTerminator()->getIterator());
2293 if (SawUnorderedAtomic)
2294 PreheaderLoad->setOrdering(AtomicOrdering::Unordered);
2295 PreheaderLoad->setAlignment(Alignment);
2296 PreheaderLoad->setDebugLoc(DebugLoc::getDropped());
2297 if (AATags && LoadIsGuaranteedToExecute)
2298 PreheaderLoad->setAAMetadata(AATags);
2299
2300 MemoryAccess *PreheaderLoadMemoryAccess = MSSAU.createMemoryAccessInBB(
2301 PreheaderLoad, nullptr, PreheaderLoad->getParent(), MemorySSA::End);
2302 MemoryUse *NewMemUse = cast<MemoryUse>(PreheaderLoadMemoryAccess);
2303 MSSAU.insertUse(NewMemUse, /*RenameUses=*/true);
2304 SSA.AddAvailableValue(Preheader, PreheaderLoad);
2305 } else {
2306 SSA.AddAvailableValue(Preheader, PoisonValue::get(AccessTy));
2307 }
2308
2309 if (VerifyMemorySSA)
2310 MSSAU.getMemorySSA()->verifyMemorySSA();
2311 // Rewrite all the loads in the loop and remember all the definitions from
2312 // stores in the loop.
2313 Promoter.run(LoopUses);
2314
2315 if (VerifyMemorySSA)
2316 MSSAU.getMemorySSA()->verifyMemorySSA();
2317 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
2318 if (PreheaderLoad && PreheaderLoad->use_empty())
2319 eraseInstruction(*PreheaderLoad, *SafetyInfo, MSSAU);
2320
2321 return true;
2322}
2323
2324static void foreachMemoryAccess(MemorySSA *MSSA, Loop *L,
2325 function_ref<void(Instruction *)> Fn) {
2326 for (const BasicBlock *BB : L->blocks())
2327 if (const auto *Accesses = MSSA->getBlockAccesses(BB))
2328 for (const auto &Access : *Accesses)
2329 if (const auto *MUD = dyn_cast<MemoryUseOrDef>(&Access))
2330 Fn(MUD->getMemoryInst());
2331}
2332
2333/// Returns whether \p I is a memory access that may be a candidate for
2334/// promotion out of the loop \p L.
2335static bool isPotentiallyPromotable(const Instruction *I, const Loop *L) {
2336 if (const auto *SI = dyn_cast<StoreInst>(I)) {
2337 const Value *PtrOp = SI->getPointerOperand();
2338 if (isStrongerThanMonotonic(SI->getOrdering()))
2339 return false;
2340 return !isa<ConstantData>(PtrOp) && L->isLoopInvariant(PtrOp);
2341 }
2342 if (const auto *LI = dyn_cast<LoadInst>(I)) {
2343 const Value *PtrOp = LI->getPointerOperand();
2344 if (isStrongerThanMonotonic(LI->getOrdering()))
2345 return false;
2346 return !isa<ConstantData>(PtrOp) && L->isLoopInvariant(PtrOp);
2347 }
2348 return false;
2349}
2350
2351/// Returns the potentially promotable stores with AA tags that are valid along
2352/// all non-unwinding execution paths of the loop \p L, which allows for the AA
2353/// tags to be used when deciding promotions.
2357 StoresByLoc;
2358 foreachMemoryAccess(MSSA, L, [&](Instruction *I) {
2359 const auto *SI = dyn_cast<StoreInst>(I);
2360 if (SI && SI->getAAMetadata() && isPotentiallyPromotable(SI, L))
2361 StoresByLoc[MemoryLocation::get(SI)].push_back(SI);
2362 });
2363
2364 // This only looks at explicit exiting blocks. If we ever start sinking
2365 // stores into unwind edges, this will break.
2366 SmallVector<BasicBlock *, 4> ExitingBlocks;
2367 L->getExitingBlocks(ExitingBlocks);
2368
2369 SmallPtrSet<const StoreInst *, 8> StoresWithInvariantAATags;
2370 for (const auto &Stores : llvm::make_second_range(StoresByLoc)) {
2371 // Without exiting blocks the loop is never left, and promotion has no
2372 // exit block to insert a store into either.
2373 if (llvm::all_of(ExitingBlocks, [&](BasicBlock *ExitingBB) {
2374 return llvm::any_of(Stores, [&](const StoreInst *SI) {
2375 return DT->dominates(SI->getParent(), ExitingBB);
2376 });
2377 }))
2378 StoresWithInvariantAATags.insert_range(Stores);
2379 }
2380 return StoresWithInvariantAATags;
2381}
2382
2383// The bool indicates whether there might be reads outside the set, in which
2384// case only loads may be promoted.
2387 DominatorTree *DT, ICFLoopSafetyInfo *SafetyInfo,
2388 Loop *L) {
2389 BatchAAResults BatchAA(*AA);
2390 AliasSetTracker AST(BatchAA);
2391
2392 // Only conditionally executed stores need this, so compute it on demand to
2393 // keep the common case free.
2394 std::optional<SmallPtrSet<const StoreInst *, 8>> StoresWithInvariantAATags;
2395 auto HasInvariantAATags = [&](const StoreInst *SI) {
2396 if (!StoresWithInvariantAATags)
2397 StoresWithInvariantAATags = collectStoresWithInvariantAATags(MSSA, DT, L);
2398 return StoresWithInvariantAATags->contains(SI);
2399 };
2400
2401 // Populate AST with potentially promotable accesses.
2402 SmallPtrSet<Value *, 16> AttemptingPromotion;
2403 foreachMemoryAccess(MSSA, L, [&](Instruction *I) {
2404 if (isPotentiallyPromotable(I, L)) {
2405 AttemptingPromotion.insert(I);
2407 SI && SI->getAAMetadata() &&
2408 !SafetyInfo->isGuaranteedToExecute(*SI, DT) &&
2409 !HasInvariantAATags(SI)) {
2410 // Promotion requires inserting a new store at the loop exits; we need
2411 // to prove that store doesn't alias anything, in addition to proving
2412 // aliasing for the stores we're removing. The new store is executed
2413 // unconditionally, so when we're proving aliasing for that store, we
2414 // can only rely on AA tags that likewise hold unconditionally.
2415 AST.addWithoutAATags(SI);
2416 } else {
2417 AST.add(I);
2418 }
2419 }
2420 });
2421
2422 // We're only interested in must-alias sets that contain a mod.
2424 for (AliasSet &AS : AST)
2425 if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias())
2426 Sets.push_back({&AS, false});
2427
2428 if (Sets.empty())
2429 return {}; // Nothing to promote...
2430
2431 // Discard any sets for which there is an aliasing non-promotable access.
2432 foreachMemoryAccess(MSSA, L, [&](Instruction *I) {
2433 if (AttemptingPromotion.contains(I))
2434 return;
2435
2437 ModRefInfo MR = Pair.getPointer()->aliasesUnknownInst(I, BatchAA);
2438 // Cannot promote if there are writes outside the set.
2439 if (isModSet(MR))
2440 return true;
2441 if (isRefSet(MR)) {
2442 // Remember reads outside the set.
2443 Pair.setInt(true);
2444 // If this is a mod-only set and there are reads outside the set,
2445 // we will not be able to promote, so bail out early.
2446 return !Pair.getPointer()->isRef();
2447 }
2448 return false;
2449 });
2450 });
2451
2453 for (auto [Set, HasReadsOutsideSet] : Sets) {
2454 SmallSetVector<Value *, 8> PointerMustAliases;
2455 for (const auto &MemLoc : *Set)
2456 PointerMustAliases.insert(const_cast<Value *>(MemLoc.Ptr));
2457 Result.emplace_back(std::move(PointerMustAliases), HasReadsOutsideSet);
2458 }
2459
2460 return Result;
2461}
2462
2463// For a given store instruction or writeonly call instruction, this function
2464// checks that there are no read or writes that conflict with the memory
2465// access in the instruction
2467 AAResults *AA, Loop *CurLoop,
2468 SinkAndHoistLICMFlags &Flags) {
2470 // If there are more accesses than the Promotion cap, then give up as we're
2471 // not walking a list that long.
2472 if (Flags.tooManyMemoryAccesses())
2473 return false;
2474
2475 auto *IMD = MSSA->getMemoryAccess(I);
2476 BatchAAResults BAA(*AA);
2477 auto *Source = getClobberingMemoryAccess(*MSSA, BAA, Flags, IMD);
2478 // Make sure there are no clobbers inside the loop.
2479 if (!MSSA->isLiveOnEntryDef(Source) && CurLoop->contains(Source->getBlock()))
2480 return false;
2481
2482 // If there are interfering Uses don't move this store.
2483 // TODO: Cache set of Uses on the first walk in runOnLoop, update when
2484 // moving accesses. Can also extend to dominating uses.
2485 for (auto *BB : CurLoop->getBlocks()) {
2486 auto *Accesses = MSSA->getBlockAccesses(BB);
2487 if (!Accesses)
2488 continue;
2489 for (const auto &MA : *Accesses) {
2490 // Accesses are ordered. If we find one that I dominates we can stop.
2491 if (!Flags.getIsSink() && MSSA->dominates(IMD, &MA))
2492 break;
2493
2494 if (const auto *MemUseOrDef = dyn_cast<MemoryUseOrDef>(&MA)) {
2495 // Skip unrelated accesses.
2496 if (isNoModRef(BAA.getModRefInfo(MemUseOrDef->getMemoryInst(), I)))
2497 continue;
2498
2499 return false;
2500 }
2501 }
2502 }
2503 return true;
2504}
2505
2507 Loop *CurLoop, Instruction &I,
2508 SinkAndHoistLICMFlags &Flags,
2509 bool InvariantGroup) {
2510 // For hoisting, use the walker to determine safety
2511 if (!Flags.getIsSink()) {
2512 // If hoisting an invariant group, we only need to check that there
2513 // is no store to the loaded pointer between the start of the loop,
2514 // and the load (since all values must be the same).
2515
2516 // This can be checked in two conditions:
2517 // 1) if the memoryaccess is outside the loop
2518 // 2) the earliest access is at the loop header,
2519 // if the memory loaded is the phi node
2520
2521 BatchAAResults BAA(MSSA->getAA());
2522 MemoryAccess *Source = getClobberingMemoryAccess(*MSSA, BAA, Flags, MU);
2523 return !MSSA->isLiveOnEntryDef(Source) &&
2524 CurLoop->contains(Source->getBlock()) &&
2525 !(InvariantGroup && Source->getBlock() == CurLoop->getHeader() && isa<MemoryPhi>(Source));
2526 }
2527
2528 // For sinking, we'd need to check all Defs below this use. The getClobbering
2529 // call will look on the backedge of the loop, but will check aliasing with
2530 // the instructions on the previous iteration.
2531 // For example:
2532 // for (i ... )
2533 // load a[i] ( Use (LoE)
2534 // store a[i] ( 1 = Def (2), with 2 = Phi for the loop.
2535 // i++;
2536 // The load sees no clobbering inside the loop, as the backedge alias check
2537 // does phi translation, and will check aliasing against store a[i-1].
2538 // However sinking the load outside the loop, below the store is incorrect.
2539
2540 // For now, only sink if there are no Defs in the loop, and the existing ones
2541 // precede the use and are in the same block.
2542 // FIXME: Increase precision: Safe to sink if Use post dominates the Def;
2543 // needs PostDominatorTreeAnalysis.
2544 // FIXME: More precise: no Defs that alias this Use.
2545 if (Flags.tooManyMemoryAccesses())
2546 return true;
2547 for (auto *BB : CurLoop->getBlocks())
2548 if (pointerInvalidatedByBlock(*BB, *MSSA, *MU))
2549 return true;
2550 // When sinking, the source block may not be part of the loop so check it.
2551 if (!CurLoop->contains(&I))
2552 return pointerInvalidatedByBlock(*I.getParent(), *MSSA, *MU);
2553
2554 return false;
2555}
2556
2558 if (const auto *Accesses = MSSA.getBlockDefs(&BB))
2559 for (const auto &MA : *Accesses)
2560 if (const auto *MD = dyn_cast<MemoryDef>(&MA))
2561 if (MU.getBlock() != MD->getBlock() || !MSSA.locallyDominates(MD, &MU))
2562 return true;
2563 return false;
2564}
2565
2566/// Try to simplify things like (A < INV_1 AND icmp A < INV_2) into (A <
2567/// min(INV_1, INV_2)), if INV_1 and INV_2 are both loop invariants and their
2568/// minimun can be computed outside of loop, and X is not a loop-invariant.
2569static bool hoistMinMax(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo,
2570 MemorySSAUpdater &MSSAU) {
2571 bool Inverse = false;
2572 using namespace PatternMatch;
2573 Value *Cond1, *Cond2;
2574 if (match(&I, m_LogicalOr(m_Value(Cond1), m_Value(Cond2)))) {
2575 Inverse = true;
2576 } else if (match(&I, m_LogicalAnd(m_Value(Cond1), m_Value(Cond2)))) {
2577 // Do nothing
2578 } else
2579 return false;
2580
2581 auto MatchICmpAgainstInvariant = [&](Value *C, CmpPredicate &P, Value *&LHS,
2582 Value *&RHS) {
2583 if (!match(C, m_OneUse(m_ICmp(P, m_Value(LHS), m_Value(RHS)))))
2584 return false;
2585 if (!LHS->getType()->isIntegerTy())
2586 return false;
2588 return false;
2589 if (L.isLoopInvariant(LHS)) {
2590 std::swap(LHS, RHS);
2592 }
2593 if (L.isLoopInvariant(LHS) || !L.isLoopInvariant(RHS))
2594 return false;
2595 if (Inverse)
2597 return true;
2598 };
2599 CmpPredicate P1, P2;
2600 Value *LHS1, *LHS2, *RHS1, *RHS2;
2601 if (!MatchICmpAgainstInvariant(Cond1, P1, LHS1, RHS1) ||
2602 !MatchICmpAgainstInvariant(Cond2, P2, LHS2, RHS2))
2603 return false;
2604 auto MatchingPred = CmpPredicate::getMatching(P1, P2);
2605 if (!MatchingPred || LHS1 != LHS2)
2606 return false;
2607
2608 // Everything is fine, we can do the transform.
2609 bool UseMin = ICmpInst::isLT(*MatchingPred) || ICmpInst::isLE(*MatchingPred);
2610 assert(
2611 (UseMin || ICmpInst::isGT(*MatchingPred) ||
2612 ICmpInst::isGE(*MatchingPred)) &&
2613 "Relational predicate is either less (or equal) or greater (or equal)!");
2614 Intrinsic::ID id = ICmpInst::isSigned(*MatchingPred)
2615 ? (UseMin ? Intrinsic::smin : Intrinsic::smax)
2616 : (UseMin ? Intrinsic::umin : Intrinsic::umax);
2617 auto *Preheader = L.getLoopPreheader();
2618 assert(Preheader && "Loop is not in simplify form?");
2619 IRBuilder<> Builder(Preheader->getTerminator());
2620 // We are about to create a new guaranteed use for RHS2 which might not exist
2621 // before (if it was a non-taken input of logical and/or instruction). If it
2622 // was poison, we need to freeze it. Note that no new use for LHS and RHS1 are
2623 // introduced, so they don't need this.
2624 if (isa<SelectInst>(I))
2625 RHS2 = Builder.CreateFreeze(RHS2, RHS2->getName() + ".fr");
2626 Value *NewRHS = Builder.CreateBinaryIntrinsic(
2627 id, RHS1, RHS2, nullptr,
2628 StringRef("invariant.") +
2629 (ICmpInst::isSigned(*MatchingPred) ? "s" : "u") +
2630 (UseMin ? "min" : "max"));
2631 Builder.SetInsertPoint(&I);
2632 ICmpInst::Predicate P = *MatchingPred;
2633 if (Inverse)
2635 Value *NewCond = Builder.CreateICmp(P, LHS1, NewRHS);
2636 NewCond->takeName(&I);
2637 I.replaceAllUsesWith(NewCond);
2638 eraseInstruction(I, SafetyInfo, MSSAU);
2639 Instruction &CondI1 = *cast<Instruction>(Cond1);
2640 Instruction &CondI2 = *cast<Instruction>(Cond2);
2641 salvageDebugInfo(CondI1);
2642 salvageDebugInfo(CondI2);
2643 eraseInstruction(CondI1, SafetyInfo, MSSAU);
2644 eraseInstruction(CondI2, SafetyInfo, MSSAU);
2645 return true;
2646}
2647
2648/// Reassociate gep (gep ptr, idx1), idx2 to gep (gep ptr, idx2), idx1 if
2649/// this allows hoisting the inner GEP.
2650static bool hoistGEP(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo,
2652 DominatorTree *DT) {
2654 if (!GEP)
2655 return false;
2656
2657 // Do not try to hoist a constant GEP out of the loop via reassociation.
2658 // Constant GEPs can often be folded into addressing modes, and reassociating
2659 // them may inhibit CSE of a common base.
2660 if (GEP->hasAllConstantIndices())
2661 return false;
2662
2663 auto *Src = dyn_cast<GetElementPtrInst>(GEP->getPointerOperand());
2664 if (!Src || !Src->hasOneUse() || !L.contains(Src))
2665 return false;
2666
2667 Value *SrcPtr = Src->getPointerOperand();
2668 auto LoopInvariant = [&](Value *V) { return L.isLoopInvariant(V); };
2669 if (!L.isLoopInvariant(SrcPtr) || !all_of(GEP->indices(), LoopInvariant))
2670 return false;
2671
2672 // This can only happen if !AllowSpeculation, otherwise this would already be
2673 // handled.
2674 // FIXME: Should we respect AllowSpeculation in these reassociation folds?
2675 // The flag exists to prevent metadata dropping, which is not relevant here.
2676 if (all_of(Src->indices(), LoopInvariant))
2677 return false;
2678
2679 // The swapped GEPs are inbounds if both original GEPs are inbounds
2680 // and the sign of the offsets is the same. For simplicity, only
2681 // handle both offsets being non-negative.
2682 const DataLayout &DL = GEP->getDataLayout();
2683 auto NonNegative = [&](Value *V) {
2684 return isKnownNonNegative(V, SimplifyQuery(DL, DT, AC, GEP));
2685 };
2686 bool IsInBounds = Src->isInBounds() && GEP->isInBounds() &&
2687 all_of(Src->indices(), NonNegative) &&
2688 all_of(GEP->indices(), NonNegative);
2689
2690 BasicBlock *Preheader = L.getLoopPreheader();
2691 IRBuilder<> Builder(Preheader->getTerminator());
2692 Value *NewSrc = Builder.CreateGEP(GEP->getSourceElementType(), SrcPtr,
2693 SmallVector<Value *>(GEP->indices()),
2694 "invariant.gep", IsInBounds);
2695 Builder.SetInsertPoint(GEP);
2696 Value *NewGEP = Builder.CreateGEP(Src->getSourceElementType(), NewSrc,
2697 SmallVector<Value *>(Src->indices()), "gep",
2698 IsInBounds);
2699 GEP->replaceAllUsesWith(NewGEP);
2700 eraseInstruction(*GEP, SafetyInfo, MSSAU);
2701 salvageDebugInfo(*Src);
2702 eraseInstruction(*Src, SafetyInfo, MSSAU);
2703 return true;
2704}
2705
2706/// Try to turn things like "LV + C1 < C2" into "LV < C2 - C1". Here
2707/// C1 and C2 are loop invariants and LV is a loop-variant.
2708static bool hoistAdd(ICmpInst::Predicate Pred, Value *VariantLHS,
2709 Value *InvariantRHS, ICmpInst &ICmp, Loop &L,
2710 ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU,
2711 AssumptionCache *AC, DominatorTree *DT) {
2712 assert(!L.isLoopInvariant(VariantLHS) && "Precondition.");
2713 assert(L.isLoopInvariant(InvariantRHS) && "Precondition.");
2714
2715 bool IsSigned = ICmpInst::isSigned(Pred);
2716
2717 // Try to represent VariantLHS as sum of invariant and variant operands.
2718 using namespace PatternMatch;
2719 Value *VariantOp, *InvariantOp;
2720 if (IsSigned && !match(VariantLHS, m_NSWAddLike(m_Value(VariantOp),
2721 m_Value(InvariantOp))))
2722 return false;
2723 if (!IsSigned && !match(VariantLHS, m_NUWAddLike(m_Value(VariantOp),
2724 m_Value(InvariantOp))))
2725 return false;
2726
2727 // LHS itself is a loop-variant, try to represent it in the form:
2728 // "VariantOp + InvariantOp". If it is possible, then we can reassociate.
2729 if (L.isLoopInvariant(VariantOp))
2730 std::swap(VariantOp, InvariantOp);
2731 if (L.isLoopInvariant(VariantOp) || !L.isLoopInvariant(InvariantOp))
2732 return false;
2733
2734 // In order to turn "LV + C1 < C2" into "LV < C2 - C1", we need to be able to
2735 // freely move values from left side of inequality to right side (just as in
2736 // normal linear arithmetics). Overflows make things much more complicated, so
2737 // we want to avoid this.
2738 auto &DL = L.getHeader()->getDataLayout();
2739 SimplifyQuery SQ(DL, DT, AC, &ICmp);
2740 if (IsSigned && computeOverflowForSignedSub(InvariantRHS, InvariantOp, SQ) !=
2742 return false;
2743 if (!IsSigned &&
2744 computeOverflowForUnsignedSub(InvariantRHS, InvariantOp, SQ) !=
2746 return false;
2747 auto *Preheader = L.getLoopPreheader();
2748 assert(Preheader && "Loop is not in simplify form?");
2749 IRBuilder<> Builder(Preheader->getTerminator());
2750 Value *NewCmpOp =
2751 Builder.CreateSub(InvariantRHS, InvariantOp, "invariant.op",
2752 /*HasNUW*/ !IsSigned, /*HasNSW*/ IsSigned);
2753 ICmp.setPredicate(Pred);
2754 ICmp.setOperand(0, VariantOp);
2755 ICmp.setOperand(1, NewCmpOp);
2756 // The new LHS is a different value, so a samesign (or any other
2757 // poison-generating) flag asserted about the old operands may no longer hold.
2759
2760 Instruction &DeadI = cast<Instruction>(*VariantLHS);
2761 salvageDebugInfo(DeadI);
2762 eraseInstruction(DeadI, SafetyInfo, MSSAU);
2763 return true;
2764}
2765
2766/// Try to reassociate and hoist the following two patterns:
2767/// LV - C1 < C2 --> LV < C1 + C2,
2768/// C1 - LV < C2 --> LV > C1 - C2.
2769static bool hoistSub(ICmpInst::Predicate Pred, Value *VariantLHS,
2770 Value *InvariantRHS, ICmpInst &ICmp, Loop &L,
2771 ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU,
2772 AssumptionCache *AC, DominatorTree *DT) {
2773 assert(!L.isLoopInvariant(VariantLHS) && "Precondition.");
2774 assert(L.isLoopInvariant(InvariantRHS) && "Precondition.");
2775
2776 bool IsSigned = ICmpInst::isSigned(Pred);
2777
2778 // Try to represent VariantLHS as sum of invariant and variant operands.
2779 using namespace PatternMatch;
2780 Value *VariantOp, *InvariantOp;
2781 if (IsSigned &&
2782 !match(VariantLHS, m_NSWSub(m_Value(VariantOp), m_Value(InvariantOp))))
2783 return false;
2784 if (!IsSigned &&
2785 !match(VariantLHS, m_NUWSub(m_Value(VariantOp), m_Value(InvariantOp))))
2786 return false;
2787
2788 bool VariantSubtracted = false;
2789 // LHS itself is a loop-variant, try to represent it in the form:
2790 // "VariantOp + InvariantOp". If it is possible, then we can reassociate. If
2791 // the variant operand goes with minus, we use a slightly different scheme.
2792 if (L.isLoopInvariant(VariantOp)) {
2793 std::swap(VariantOp, InvariantOp);
2794 VariantSubtracted = true;
2795 Pred = ICmpInst::getSwappedPredicate(Pred);
2796 }
2797 if (L.isLoopInvariant(VariantOp) || !L.isLoopInvariant(InvariantOp))
2798 return false;
2799
2800 // In order to turn "LV - C1 < C2" into "LV < C2 + C1", we need to be able to
2801 // freely move values from left side of inequality to right side (just as in
2802 // normal linear arithmetics). Overflows make things much more complicated, so
2803 // we want to avoid this. Likewise, for "C1 - LV < C2" we need to prove that
2804 // "C1 - C2" does not overflow.
2805 auto &DL = L.getHeader()->getDataLayout();
2806 SimplifyQuery SQ(DL, DT, AC, &ICmp);
2807 if (VariantSubtracted && IsSigned) {
2808 // C1 - LV < C2 --> LV > C1 - C2
2809 if (computeOverflowForSignedSub(InvariantOp, InvariantRHS, SQ) !=
2811 return false;
2812 } else if (VariantSubtracted && !IsSigned) {
2813 // C1 - LV < C2 --> LV > C1 - C2
2814 if (computeOverflowForUnsignedSub(InvariantOp, InvariantRHS, SQ) !=
2816 return false;
2817 } else if (!VariantSubtracted && IsSigned) {
2818 // LV - C1 < C2 --> LV < C1 + C2
2819 if (computeOverflowForSignedAdd(InvariantOp, InvariantRHS, SQ) !=
2821 return false;
2822 } else { // !VariantSubtracted && !IsSigned
2823 // LV - C1 < C2 --> LV < C1 + C2
2824 if (computeOverflowForUnsignedAdd(InvariantOp, InvariantRHS, SQ) !=
2826 return false;
2827 }
2828 auto *Preheader = L.getLoopPreheader();
2829 assert(Preheader && "Loop is not in simplify form?");
2830 IRBuilder<> Builder(Preheader->getTerminator());
2831 Value *NewCmpOp =
2832 VariantSubtracted
2833 ? Builder.CreateSub(InvariantOp, InvariantRHS, "invariant.op",
2834 /*HasNUW*/ !IsSigned, /*HasNSW*/ IsSigned)
2835 : Builder.CreateAdd(InvariantOp, InvariantRHS, "invariant.op",
2836 /*HasNUW*/ !IsSigned, /*HasNSW*/ IsSigned);
2837 ICmp.setPredicate(Pred);
2838 ICmp.setOperand(0, VariantOp);
2839 ICmp.setOperand(1, NewCmpOp);
2840 // The new LHS is a different value, so a samesign (or any other
2841 // poison-generating) flag asserted about the old operands may no longer hold.
2843
2844 Instruction &DeadI = cast<Instruction>(*VariantLHS);
2845 salvageDebugInfo(DeadI);
2846 eraseInstruction(DeadI, SafetyInfo, MSSAU);
2847 return true;
2848}
2849
2850/// Reassociate and hoist add/sub expressions.
2851static bool hoistAddSub(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo,
2853 DominatorTree *DT) {
2854 using namespace PatternMatch;
2855 CmpPredicate Pred;
2856 Value *LHS, *RHS;
2857 if (!match(&I, m_ICmp(Pred, m_Value(LHS), m_Value(RHS))))
2858 return false;
2859
2860 // Put variant operand to LHS position.
2861 if (L.isLoopInvariant(LHS)) {
2862 std::swap(LHS, RHS);
2863 Pred = ICmpInst::getSwappedPredicate(Pred);
2864 }
2865 // We want to delete the initial operation after reassociation, so only do it
2866 // if it has no other uses.
2867 if (L.isLoopInvariant(LHS) || !L.isLoopInvariant(RHS) || !LHS->hasOneUse())
2868 return false;
2869
2870 // TODO: We could go with smarter context, taking common dominator of all I's
2871 // users instead of I itself.
2872 if (hoistAdd(Pred, LHS, RHS, cast<ICmpInst>(I), L, SafetyInfo, MSSAU, AC, DT))
2873 return true;
2874
2875 if (hoistSub(Pred, LHS, RHS, cast<ICmpInst>(I), L, SafetyInfo, MSSAU, AC, DT))
2876 return true;
2877
2878 return false;
2879}
2880
2881static bool isReassociableOp(Instruction *I, unsigned IntOpcode,
2882 unsigned FPOpcode) {
2883 if (I->getOpcode() == IntOpcode)
2884 return true;
2885 if (I->getOpcode() == FPOpcode && I->hasAllowReassoc() &&
2886 I->hasNoSignedZeros())
2887 return true;
2888 return false;
2889}
2890
2891/// Try to reassociate expressions like ((A1 * B1) + (A2 * B2) + ...) * C where
2892/// A1, A2, ... and C are loop invariants into expressions like
2893/// ((A1 * C * B1) + (A2 * C * B2) + ...) and hoist the (A1 * C), (A2 * C), ...
2894/// invariant expressions. This functions returns true only if any hoisting has
2895/// actually occurred.
2897 ICFLoopSafetyInfo &SafetyInfo,
2899 DominatorTree *DT) {
2900 if (!isReassociableOp(&I, Instruction::Mul, Instruction::FMul))
2901 return false;
2902 Value *VariantOp = I.getOperand(0);
2903 Value *InvariantOp = I.getOperand(1);
2904 if (L.isLoopInvariant(VariantOp))
2905 std::swap(VariantOp, InvariantOp);
2906 if (L.isLoopInvariant(VariantOp) || !L.isLoopInvariant(InvariantOp))
2907 return false;
2908 Value *Factor = InvariantOp;
2909
2910 // First, we need to make sure we should do the transformation.
2911 SmallVector<Use *> Changes;
2914 if (BinaryOperator *VariantBinOp = dyn_cast<BinaryOperator>(VariantOp))
2915 Worklist.push_back(VariantBinOp);
2916 while (!Worklist.empty()) {
2917 BinaryOperator *BO = Worklist.pop_back_val();
2918 if (!BO->hasOneUse())
2919 return false;
2920 if (isReassociableOp(BO, Instruction::Add, Instruction::FAdd) &&
2923 Worklist.push_back(cast<BinaryOperator>(BO->getOperand(0)));
2924 Worklist.push_back(cast<BinaryOperator>(BO->getOperand(1)));
2925 Adds.push_back(BO);
2926 continue;
2927 }
2928 if (!isReassociableOp(BO, Instruction::Mul, Instruction::FMul) ||
2929 L.isLoopInvariant(BO))
2930 return false;
2931 Use &U0 = BO->getOperandUse(0);
2932 Use &U1 = BO->getOperandUse(1);
2933 if (L.isLoopInvariant(U0))
2934 Changes.push_back(&U0);
2935 else if (L.isLoopInvariant(U1))
2936 Changes.push_back(&U1);
2937 else
2938 return false;
2939 unsigned Limit = I.getType()->isIntOrIntVectorTy()
2942 if (Changes.size() > Limit)
2943 return false;
2944 }
2945 if (Changes.empty())
2946 return false;
2947
2948 // Drop the poison flags for any adds we looked through.
2949 if (I.getType()->isIntOrIntVectorTy()) {
2950 for (auto *Add : Adds)
2951 Add->dropPoisonGeneratingFlags();
2952 }
2953
2954 // We know we should do it so let's do the transformation.
2955 auto *Preheader = L.getLoopPreheader();
2956 assert(Preheader && "Loop is not in simplify form?");
2957 IRBuilder<> Builder(Preheader->getTerminator());
2958 for (auto *U : Changes) {
2959 assert(L.isLoopInvariant(U->get()));
2960 auto *Ins = cast<BinaryOperator>(U->getUser());
2961 Value *Mul;
2962 if (I.getType()->isIntOrIntVectorTy()) {
2963 Mul = Builder.CreateMul(U->get(), Factor, "factor.op.mul");
2964 // Drop the poison flags on the original multiply.
2965 Ins->dropPoisonGeneratingFlags();
2966 } else
2967 Mul = Builder.CreateFMulFMF(U->get(), Factor, Ins, "factor.op.fmul");
2968
2969 // Rewrite the reassociable instruction.
2970 unsigned OpIdx = U->getOperandNo();
2971 auto *LHS = OpIdx == 0 ? Mul : Ins->getOperand(0);
2972 auto *RHS = OpIdx == 1 ? Mul : Ins->getOperand(1);
2973 auto *NewBO =
2974 BinaryOperator::Create(Ins->getOpcode(), LHS, RHS,
2975 Ins->getName() + ".reass", Ins->getIterator());
2976 NewBO->setDebugLoc(DebugLoc::getDropped());
2977 NewBO->copyIRFlags(Ins);
2978 if (VariantOp == Ins)
2979 VariantOp = NewBO;
2980 Ins->replaceAllUsesWith(NewBO);
2981 eraseInstruction(*Ins, SafetyInfo, MSSAU);
2982 }
2983
2984 I.replaceAllUsesWith(VariantOp);
2985 eraseInstruction(I, SafetyInfo, MSSAU);
2986 return true;
2987}
2988
2989/// Reassociate associative binary expressions of the form
2990///
2991/// 1. "(LV op C1) op C2" ==> "LV op (C1 op C2)"
2992/// 2. "(C1 op LV) op C2" ==> "LV op (C1 op C2)"
2993/// 3. "C2 op (C1 op LV)" ==> "LV op (C1 op C2)"
2994/// 4. "C2 op (LV op C1)" ==> "LV op (C1 op C2)"
2995///
2996/// where op is an associative BinOp, LV is a loop variant, and C1 and C2 are
2997/// loop invariants that we want to hoist, noting that associativity implies
2998/// commutativity.
3000 ICFLoopSafetyInfo &SafetyInfo,
3002 DominatorTree *DT) {
3003 auto *BO = dyn_cast<BinaryOperator>(&I);
3004 if (!BO || !BO->isAssociative())
3005 return false;
3006
3007 Instruction::BinaryOps Opcode = BO->getOpcode();
3008 bool LVInRHS = L.isLoopInvariant(BO->getOperand(0));
3009 auto *BO0 = dyn_cast<BinaryOperator>(BO->getOperand(LVInRHS));
3010 if (!BO0 || BO0->getOpcode() != Opcode || !BO0->isAssociative() ||
3011 BO0->hasNUsesOrMore(BO0->getType()->isIntegerTy() ? 2 : 3))
3012 return false;
3013
3014 Value *LV = BO0->getOperand(0);
3015 Value *C1 = BO0->getOperand(1);
3016 Value *C2 = BO->getOperand(!LVInRHS);
3017
3018 assert(BO->isCommutative() && BO0->isCommutative() &&
3019 "Associativity implies commutativity");
3020 if (L.isLoopInvariant(LV) && !L.isLoopInvariant(C1))
3021 std::swap(LV, C1);
3022 if (L.isLoopInvariant(LV) || !L.isLoopInvariant(C1) || !L.isLoopInvariant(C2))
3023 return false;
3024
3025 auto *Preheader = L.getLoopPreheader();
3026 assert(Preheader && "Loop is not in simplify form?");
3027
3028 IRBuilder<> Builder(Preheader->getTerminator());
3029 auto *Inv = Builder.CreateBinOp(Opcode, C1, C2, "invariant.op");
3030
3031 auto *NewBO = BinaryOperator::Create(
3032 Opcode, LV, Inv, BO->getName() + ".reass", BO->getIterator());
3033 NewBO->setDebugLoc(DebugLoc::getDropped());
3034
3035 if (Opcode == Instruction::FAdd || Opcode == Instruction::FMul) {
3036 // Intersect FMF flags for FADD and FMUL.
3037 FastMathFlags Intersect = BO->getFastMathFlags() & BO0->getFastMathFlags();
3038 if (auto *I = dyn_cast<Instruction>(Inv))
3039 I->setFastMathFlags(Intersect);
3040 NewBO->setFastMathFlags(Intersect);
3041 } else {
3042 OverflowTracking Flags;
3043 Flags.AllKnownNonNegative = false;
3044 Flags.AllKnownNonZero = false;
3045 Flags.mergeFlags(*BO);
3046 Flags.mergeFlags(*BO0);
3047 // If `Inv` was not constant-folded, a new Instruction has been created.
3048 if (auto *I = dyn_cast<Instruction>(Inv))
3049 Flags.applyFlags(*I);
3050 Flags.applyFlags(*NewBO);
3051 }
3052
3053 BO->replaceAllUsesWith(NewBO);
3054 eraseInstruction(*BO, SafetyInfo, MSSAU);
3055
3056 // (LV op C1) might not be erased if it has more uses than the one we just
3057 // replaced.
3058 if (BO0->use_empty()) {
3059 salvageDebugInfo(*BO0);
3060 eraseInstruction(*BO0, SafetyInfo, MSSAU);
3061 }
3062
3063 return true;
3064}
3065
3066/// Reassociate add/sub expressions of the form:
3067///
3068/// 1. "(LV + C1) - C2" ==> "LV + (C1 - C2)"
3069/// 2. "(LV - C1) - C2" ==> "LV - (C1 + C2)"
3070/// 3. "(LV - C1) + C2" ==> "LV + (C2 - C1)"
3071///
3072/// where LV is a loop variant, and C1 and C2 are loop invariants.
3073/// Sub is not associative, but these algebraic identities allow hoisting
3074/// invariant computations out of the loop.
3076 ICFLoopSafetyInfo &SafetyInfo,
3078 DominatorTree *DT) {
3079 using namespace PatternMatch;
3080
3081 Instruction *BO;
3082 Value *LV, *C1, *C2;
3083 Instruction::BinaryOps InvOp, ResultOp;
3084
3085 // Try to match one of three reassociation patterns involving sub.
3086 //
3087 // 1. (LV + C1) - C2 ==> LV + (C1 - C2)
3088 // 2. (LV - C1) - C2 ==> LV - (C1 + C2)
3089 // 3. (LV - C1) + C2 ==> LV + (C2 - C1)
3090 // ^ ^
3091 // \ \___ InvOp
3092 // \
3093 // \____ ResultOp
3094 //
3095 if (match(&I,
3097 m_Value(C2)))) {
3098 // Case 1.
3099 //
3100 // Depending on which of the addition is invariant, we might need to swap
3101 // the arguments
3102 if (L.isLoopInvariant(LV) && !L.isLoopInvariant(C1))
3103 std::swap(LV, C1);
3104 InvOp = Instruction::Sub;
3105 ResultOp = Instruction::Add;
3106 } else if (match(&I, m_Sub(m_OneUse(m_Instruction(
3107 BO, m_Sub(m_Value(LV), m_Value(C1)))),
3108 m_Value(C2)))) {
3109 // Case 2.
3110 InvOp = Instruction::Add;
3111 ResultOp = Instruction::Sub;
3112 } else if (match(&I, m_c_Add(m_OneUse(m_Instruction(
3113 BO, m_Sub(m_Value(LV), m_Value(C1)))),
3114 m_Value(C2)))) {
3115 // Case 3.
3116 //
3117 // We use (C2 - C1) as the invariant as opposed to case 1, but instead of
3118 // adding a special case in invariant creation, we can just swap the
3119 // operands here.
3120 std::swap(C1, C2);
3121 InvOp = Instruction::Sub;
3122 ResultOp = Instruction::Add;
3123 } else {
3124 return false;
3125 }
3126
3127 if (L.isLoopInvariant(LV) || !L.isLoopInvariant(C1) || !L.isLoopInvariant(C2))
3128 return false;
3129
3130 auto *Preheader = L.getLoopPreheader();
3131 assert(Preheader && "Loop is not in simplify form?");
3132
3133 IRBuilder<> Builder(Preheader->getTerminator());
3134 auto *Inv = Builder.CreateBinOp(InvOp, C1, C2, "invariant.op");
3135
3136 auto *NewBO = BinaryOperator::Create(ResultOp, LV, Inv,
3137 I.getName() + ".reass", I.getIterator());
3138 NewBO->setDebugLoc(DebugLoc::getDropped());
3139
3140 // No overflow flags are set on the new instructions -- reassociation
3141 // involving sub does not preserve nsw/nuw in general.
3142
3143 I.replaceAllUsesWith(NewBO);
3144 eraseInstruction(I, SafetyInfo, MSSAU);
3145
3146 salvageDebugInfo(*BO);
3147 eraseInstruction(*BO, SafetyInfo, MSSAU);
3148
3149 return true;
3150}
3151
3153 ICFLoopSafetyInfo &SafetyInfo,
3155 DominatorTree *DT) {
3156 // Optimize complex patterns, such as (x < INV1 && x < INV2), turning them
3157 // into (x < min(INV1, INV2)), and hoisting the invariant part of this
3158 // expression out of the loop.
3159 if (hoistMinMax(I, L, SafetyInfo, MSSAU)) {
3160 ++NumHoisted;
3161 ++NumMinMaxHoisted;
3162 return true;
3163 }
3164
3165 // Try to hoist GEPs by reassociation.
3166 if (hoistGEP(I, L, SafetyInfo, MSSAU, AC, DT)) {
3167 ++NumHoisted;
3168 ++NumGEPsHoisted;
3169 return true;
3170 }
3171
3172 // Try to hoist add/sub's by reassociation.
3173 if (hoistAddSub(I, L, SafetyInfo, MSSAU, AC, DT)) {
3174 ++NumHoisted;
3175 ++NumAddSubHoisted;
3176 return true;
3177 }
3178
3179 bool IsInt = I.getType()->isIntOrIntVectorTy();
3180 if (hoistMulAddAssociation(I, L, SafetyInfo, MSSAU, AC, DT)) {
3181 ++NumHoisted;
3182 if (IsInt)
3183 ++NumIntAssociationsHoisted;
3184 else
3185 ++NumFPAssociationsHoisted;
3186 return true;
3187 }
3188
3189 if (hoistBOAssociation(I, L, SafetyInfo, MSSAU, AC, DT)) {
3190 ++NumHoisted;
3191 ++NumBOAssociationsHoisted;
3192 return true;
3193 }
3194
3195 if (hoistSubAddAssociation(I, L, SafetyInfo, MSSAU, AC, DT)) {
3196 ++NumHoisted;
3197 ++NumBOAssociationsHoisted;
3198 return true;
3199 }
3200
3201 return false;
3202}
3203
3204/// Little predicate that returns true if the specified basic block is in
3205/// a subloop of the current one, not the current one itself.
3206///
3207static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
3208 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
3209 return LI->getLoopFor(BB) != CurLoop;
3210}
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...
iv Induction Variable Users
Definition IVUsers.cpp:48
static bool isReassociableOp(Instruction *I, unsigned IntOpcode, unsigned FPOpcode)
Definition LICM.cpp:2881
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:1423
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:2650
static cl::opt< bool > SingleThread("licm-force-thread-model-single", cl::Hidden, cl::init(false), cl::desc("Force thread model single in LICM pass"))
static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT, LoopInfo *LI, const Loop *CurLoop, LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU)
Definition LICM.cpp:1598
static bool hoistInsertPastInsert(InsertElementInst *Ins, Loop *CurLoop, DominatorTree *DT, BasicBlock *HoistDest, ICFLoopSafetyInfo *SafetyInfo, MemorySSAUpdater &MSSAU, ScalarEvolution *SE, OptimizationRemarkEmitter *ORE, SmallVectorImpl< Instruction * > &HoistedInstructions)
Definition LICM.cpp:1090
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:1393
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:2355
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:2569
static void moveInstructionBefore(Instruction &I, BasicBlock::iterator Dest, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, ScalarEvolution *SE)
Definition LICM.cpp:1550
static Instruction * cloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI, const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater &MSSAU)
Definition LICM.cpp:1466
static cl::opt< bool > ControlFlowHoisting("licm-control-flow-hoisting", cl::Hidden, cl::init(false), cl::desc("Enable control flow (and PHI) hoisting in LICM"))
static bool pointerInvalidatedByLoop(MemorySSA *MSSA, MemoryUse *MU, Loop *CurLoop, Instruction &I, SinkAndHoistLICMFlags &Flags, bool InvariantGroup)
Definition LICM.cpp:2506
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:3075
static SmallVector< PointersAndHasReadsOutsideSet, 0 > collectPromotionCandidates(MemorySSA *MSSA, AliasAnalysis *AA, DominatorTree *DT, ICFLoopSafetyInfo *SafetyInfo, Loop *L)
Definition LICM.cpp:2386
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:2708
static MemoryAccess * getClobberingMemoryAccess(MemorySSA &MSSA, BatchAAResults &BAA, SinkAndHoistLICMFlags &Flags, MemoryUseOrDef *MA)
Definition LICM.cpp:1235
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:1777
static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo)
Definition LICM.cpp:1580
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:1670
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:2335
static bool hoistAddSub(Instruction &I, Loop &L, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU, AssumptionCache *AC, DominatorTree *DT)
Reassociate and hoist add/sub expressions.
Definition LICM.cpp:2851
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:2896
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:1219
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:2324
static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT, Loop *CurLoop)
Definition LICM.cpp:1150
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:1207
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:1565
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:3207
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:2769
static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU)
Definition LICM.cpp:1543
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:1824
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:3152
static bool noConflictingReadWrites(Instruction *I, MemorySSA *MSSA, AAResults *AA, Loop *CurLoop, SinkAndHoistLICMFlags &Flags)
Definition LICM.cpp:2466
static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I)
Returns true if a PHINode is a trivially replaceable with an Instruction.
Definition LICM.cpp:1384
std::pair< SmallSetVector< Value *, 8 >, bool > PointersAndHasReadsOutsideSet
Definition LICM.cpp:224
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:1074
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:2999
static bool pointerInvalidatedByBlock(BasicBlock &BB, MemorySSA &MSSA, MemoryUse &MU)
Definition LICM.cpp:2557
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 generic set operations that may be used on set's of different types,...
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
LLVM_ABI void replaceSuccessorsPhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block's successors to refer to basic block New instead of basic bl...
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
bool hasTerminator() const LLVM_READONLY
Returns whether the block has a terminator.
Definition BasicBlock.h:232
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
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 LLVMContext & getContext() const
Get the context in which this basic block lives.
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
Definition BasicBlock.h:373
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...
Conditional Branch instruction.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
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
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:251
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:341
iterator end()
Definition DenseMap.h:169
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
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:2908
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...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
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.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
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:331
LLVM_ABI PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
Definition LICM.cpp:309
LLVM_ABI PreservedAnalyses run(LoopNest &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
Definition LICM.cpp:341
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Definition LICM.cpp:371
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
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
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.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
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)
LLVM_ABI void wireOldPredecessorsToNewImmediatePredecessor(BasicBlock *Old, BasicBlock *New, ArrayRef< BasicBlock * > Preds, bool IdenticalEdgesWereMerged=true)
A new empty BasicBlock (New) now branches directly to Old.
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
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()
void setIncomingBlock(unsigned i, BasicBlock *BB)
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:399
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
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
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:1739
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:1290
auto pred_end(const MachineBasicBlock *BB)
void set_intersect(S1Ty &S1, const S2Ty &S2)
set_intersect(A, B) - Compute A := A ^ B Identical to set_intersection, except that it works on set<>...
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
auto successors(const MachineBasicBlock *BB)
@ 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:633
auto cast_or_null(const Y &Val)
Definition Casting.h:714
auto pred_size(const MachineBasicBlock *BB)
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:392
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:892
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:1746
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:407
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...
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:1409
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:1917
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.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1772
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:2192
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:564
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:1249
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
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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:2005
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:631
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:763
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.