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