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