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