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