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