LLVM 24.0.0git
GVN.cpp
Go to the documentation of this file.
1//===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
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 global value numbering to eliminate fully redundant
10// instructions. It also performs simple dead load elimination.
11//
12// Note that this pass does the value numbering itself; it does not use the
13// ValueNumbering analysis passes.
14//
15//===----------------------------------------------------------------------===//
16
18#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/Hashing.h"
21#include "llvm/ADT/MapVector.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/SetVector.h"
27#include "llvm/ADT/Statistic.h"
31#include "llvm/Analysis/CFG.h"
36#include "llvm/Analysis/Loads.h"
46#include "llvm/IR/Attributes.h"
47#include "llvm/IR/BasicBlock.h"
48#include "llvm/IR/Constant.h"
49#include "llvm/IR/Constants.h"
50#include "llvm/IR/DebugLoc.h"
51#include "llvm/IR/Dominators.h"
52#include "llvm/IR/Function.h"
53#include "llvm/IR/InstrTypes.h"
54#include "llvm/IR/Instruction.h"
57#include "llvm/IR/LLVMContext.h"
58#include "llvm/IR/Metadata.h"
59#include "llvm/IR/Module.h"
60#include "llvm/IR/PassManager.h"
62#include "llvm/IR/Type.h"
63#include "llvm/IR/Use.h"
64#include "llvm/IR/Value.h"
66#include "llvm/Pass.h"
70#include "llvm/Support/Debug.h"
77#include <algorithm>
78#include <cassert>
79#include <cstdint>
80#include <optional>
81#include <utility>
82
83using namespace llvm;
84using namespace llvm::VNCoercion;
85using namespace PatternMatch;
86
89
90#define DEBUG_TYPE "gvn"
91
92STATISTIC(NumGVNInstr, "Number of instructions deleted");
93STATISTIC(NumGVNLoad, "Number of loads deleted");
94STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
95STATISTIC(NumGVNBlocks, "Number of blocks merged");
96STATISTIC(NumGVNSimpl, "Number of instructions simplified");
97STATISTIC(NumGVNEqProp, "Number of equalities propagated");
98STATISTIC(NumPRELoad, "Number of loads PRE'd");
99STATISTIC(NumPRELoopLoad, "Number of loop loads PRE'd");
100STATISTIC(NumPRELoadMoved2CEPred,
101 "Number of loads moved to predecessor of a critical edge in PRE");
102
103STATISTIC(IsValueFullyAvailableInBlockNumSpeculationsMax,
104 "Number of blocks speculated as available in "
105 "IsValueFullyAvailableInBlock(), max");
106STATISTIC(MaxBBSpeculationCutoffReachedTimes,
107 "Number of times we we reached gvn-max-block-speculations cut-off "
108 "preventing further exploration");
109
110static cl::opt<bool> GVNEnableScalarPRE("enable-scalar-pre", cl::init(true),
111 cl::Hidden);
112static cl::opt<bool> GVNEnableLoadPRE("enable-load-pre", cl::init(true));
113static cl::opt<bool> GVNEnableLoadInLoopPRE("enable-load-in-loop-pre",
114 cl::init(true));
115static cl::opt<bool>
116GVNEnableSplitBackedgeInLoadPRE("enable-split-backedge-in-load-pre",
117 cl::init(false));
118static cl::opt<bool> GVNEnableMemDep("enable-gvn-memdep", cl::init(true));
119static cl::opt<bool> GVNEnableMemorySSA("enable-gvn-memoryssa",
120 cl::init(false));
121
123 "gvn-scan-users-limit", cl::Hidden, cl::init(100),
124 cl::desc("The number of memory accesses to scan in a block in reaching "
125 "memory values analysis (default = 100)"));
126
128 "gvn-max-num-deps", cl::Hidden, cl::init(100),
129 cl::desc("Max number of dependences to attempt Load PRE (default = 100)"));
130
131// This is based on IsValueFullyAvailableInBlockNumSpeculationsMax stat.
133 "gvn-max-block-speculations", cl::Hidden, cl::init(600),
134 cl::desc("Max number of blocks we're willing to speculate on (and recurse "
135 "into) when deducing if a value is fully available or not in GVN "
136 "(default = 600)"));
137
139 "gvn-max-num-visited-insts", cl::Hidden, cl::init(100),
140 cl::desc("Max number of visited instructions when trying to find "
141 "dominating value of select dependency (default = 100)"));
142
144 "gvn-max-num-insns", cl::Hidden, cl::init(100),
145 cl::desc("Max number of instructions to scan in each basic block in GVN "
146 "(default = 100)"));
147
150 bool Commutative = false;
151 // The type is not necessarily the result type of the expression, it may be
152 // any additional type needed to disambiguate the expression.
153 Type *Ty = nullptr;
155
156 AttributeList Attrs;
157
159
160 bool operator==(const Expression &Other) const {
161 if (Opcode != Other.Opcode)
162 return false;
163 if (Opcode == ~0U || Opcode == ~1U)
164 return true;
165 if (Ty != Other.Ty)
166 return false;
167 if (VarArgs != Other.VarArgs)
168 return false;
169 if ((!Attrs.isEmpty() || !Other.Attrs.isEmpty()) &&
170 !Attrs.intersectWith(Ty->getContext(), Other.Attrs).has_value())
171 return false;
172 return true;
173 }
174
176 return hash_combine(Value.Opcode, Value.Ty,
177 hash_combine_range(Value.VarArgs));
178 }
179};
180
182 static unsigned getHashValue(const GVNPass::Expression &E) {
183 using llvm::hash_value;
184
185 return static_cast<unsigned>(hash_value(E));
186 }
187
188 static bool isEqual(const GVNPass::Expression &LHS,
189 const GVNPass::Expression &RHS) {
190 return LHS == RHS;
191 }
192};
193
194/// Represents a particular available value that we know how to materialize.
195/// Materialization of an AvailableValue never fails. An AvailableValue is
196/// implicitly associated with a rematerialization point which is the
197/// location of the instruction from which it was formed.
199 enum class ValType {
200 SimpleVal, // A simple offsetted value that is accessed.
201 LoadVal, // A value produced by a load.
202 MemIntrin, // A memory intrinsic which is loaded from.
203 UndefVal, // A UndefValue representing a value from dead block (which
204 // is not yet physically removed from the CFG).
205 SelectVal, // A pointer select which is loaded from and for which the load
206 // can be replace by a value select.
207 };
208
209 /// Val - The value that is live out of the block.
211 /// Kind of the live-out value.
213
214 /// Offset - The byte offset in Val that is interesting for the load query.
215 unsigned Offset = 0;
216 /// V1, V2 - The dominating non-clobbered values of SelectVal.
217 Value *V1 = nullptr, *V2 = nullptr;
218
219 static AvailableValue get(Value *V, unsigned Offset = 0) {
220 AvailableValue Res;
221 Res.Val = V;
223 Res.Offset = Offset;
224 return Res;
225 }
226
227 static AvailableValue getMI(MemIntrinsic *MI, unsigned Offset = 0) {
228 AvailableValue Res;
229 Res.Val = MI;
231 Res.Offset = Offset;
232 return Res;
233 }
234
235 static AvailableValue getLoad(LoadInst *Load, unsigned Offset = 0) {
236 AvailableValue Res;
237 Res.Val = Load;
239 Res.Offset = Offset;
240 return Res;
241 }
242
244 AvailableValue Res;
245 Res.Val = nullptr;
247 Res.Offset = 0;
248 return Res;
249 }
250
252 AvailableValue Res;
253 Res.Val = Cond;
255 Res.Offset = 0;
256 Res.V1 = V1;
257 Res.V2 = V2;
258 return Res;
259 }
260
261 bool isSimpleValue() const { return Kind == ValType::SimpleVal; }
262 bool isCoercedLoadValue() const { return Kind == ValType::LoadVal; }
263 bool isMemIntrinValue() const { return Kind == ValType::MemIntrin; }
264 bool isUndefValue() const { return Kind == ValType::UndefVal; }
265 bool isSelectValue() const { return Kind == ValType::SelectVal; }
266
268 assert(isSimpleValue() && "Wrong accessor");
269 return Val;
270 }
271
273 assert(isCoercedLoadValue() && "Wrong accessor");
274 return cast<LoadInst>(Val);
275 }
276
278 assert(isMemIntrinValue() && "Wrong accessor");
279 return cast<MemIntrinsic>(Val);
280 }
281
283 assert(isSelectValue() && "Wrong accessor");
284 return Val;
285 }
286
287 /// Emit code at the specified insertion point to adjust the value defined
288 /// here to the specified type. This handles various coercion cases.
290};
291
292/// Represents an AvailableValue which can be rematerialized at the end of
293/// the associated BasicBlock.
295 /// BB - The basic block in question.
296 BasicBlock *BB = nullptr;
297
298 /// AV - The actual available value.
300
303 Res.BB = BB;
304 Res.AV = std::move(AV);
305 return Res;
306 }
307
309 unsigned Offset = 0) {
310 return get(BB, AvailableValue::get(V, Offset));
311 }
312
316
317 /// Emit code at the end of this block to adjust the value defined here to
318 /// the specified type. This handles various coercion cases.
320 return AV.MaterializeAdjustedValue(Load, BB->getTerminator());
321 }
322};
323
324//===----------------------------------------------------------------------===//
325// ValueTable Internal Functions
326//===----------------------------------------------------------------------===//
327
328GVNPass::Expression GVNPass::ValueTable::createExpr(Instruction *I) {
329 Expression E;
330 E.Ty = I->getType();
331 E.Opcode = I->getOpcode();
332 if (const GCRelocateInst *GCR = dyn_cast<GCRelocateInst>(I)) {
333 // gc.relocate is 'special' call: its second and third operands are
334 // not real values, but indices into statepoint's argument list.
335 // Use the refered to values for purposes of identity.
336 E.VarArgs.push_back(lookupOrAdd(GCR->getOperand(0)));
337 E.VarArgs.push_back(lookupOrAdd(GCR->getBasePtr()));
338 E.VarArgs.push_back(lookupOrAdd(GCR->getDerivedPtr()));
339 } else {
340 for (Use &Op : I->operands())
341 E.VarArgs.push_back(lookupOrAdd(Op));
342 }
343 if (I->isCommutative()) {
344 // Ensure that commutative instructions that only differ by a permutation
345 // of their operands get the same value number by sorting the operand value
346 // numbers. Since commutative operands are the 1st two operands it is more
347 // efficient to sort by hand rather than using, say, std::sort.
348 assert(I->getNumOperands() >= 2 && "Unsupported commutative instruction!");
349 if (E.VarArgs[0] > E.VarArgs[1])
350 std::swap(E.VarArgs[0], E.VarArgs[1]);
351 E.Commutative = true;
352 }
353
354 if (auto *C = dyn_cast<CmpInst>(I)) {
355 // Sort the operand value numbers so x<y and y>x get the same value number.
356 CmpInst::Predicate Predicate = C->getPredicate();
357 if (E.VarArgs[0] > E.VarArgs[1]) {
358 std::swap(E.VarArgs[0], E.VarArgs[1]);
360 }
361 E.Opcode = (C->getOpcode() << 8) | Predicate;
362 E.Commutative = true;
363 } else if (auto *IVI = dyn_cast<InsertValueInst>(I)) {
364 E.VarArgs.append(IVI->idx_begin(), IVI->idx_end());
365 } else if (auto *SVI = dyn_cast<ShuffleVectorInst>(I)) {
366 ArrayRef<int> ShuffleMask = SVI->getShuffleMask();
367 E.VarArgs.append(ShuffleMask.begin(), ShuffleMask.end());
368 } else if (auto *CB = dyn_cast<CallBase>(I)) {
369 E.Attrs = CB->getAttributes();
370 }
371
372 return E;
373}
374
375GVNPass::Expression GVNPass::ValueTable::createCmpExpr(
376 unsigned Opcode, CmpInst::Predicate Predicate, Value *LHS, Value *RHS) {
377 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
378 "Not a comparison!");
381 E.VarArgs.push_back(lookupOrAdd(LHS));
382 E.VarArgs.push_back(lookupOrAdd(RHS));
383
384 // Sort the operand value numbers so x<y and y>x get the same value number.
385 if (E.VarArgs[0] > E.VarArgs[1]) {
386 std::swap(E.VarArgs[0], E.VarArgs[1]);
388 }
389 E.Opcode = (Opcode << 8) | Predicate;
390 E.Commutative = true;
391 return E;
392}
393
394GVNPass::Expression
395GVNPass::ValueTable::createExtractvalueExpr(ExtractValueInst *EI) {
396 assert(EI && "Not an ExtractValueInst?");
398 E.Ty = EI->getType();
399 E.Opcode = 0;
400
401 WithOverflowInst *WO = dyn_cast<WithOverflowInst>(EI->getAggregateOperand());
402 if (WO != nullptr && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
403 // EI is an extract from one of our with.overflow intrinsics. Synthesize
404 // a semantically equivalent expression instead of an extract value
405 // expression.
406 E.Opcode = WO->getBinaryOp();
407 E.VarArgs.push_back(lookupOrAdd(WO->getLHS()));
408 E.VarArgs.push_back(lookupOrAdd(WO->getRHS()));
409 return E;
410 }
411
412 // Not a recognised intrinsic. Fall back to producing an extract value
413 // expression.
414 E.Opcode = EI->getOpcode();
415 for (Use &Op : EI->operands())
416 E.VarArgs.push_back(lookupOrAdd(Op));
417
418 append_range(E.VarArgs, EI->indices());
419
420 return E;
421}
422
423GVNPass::Expression GVNPass::ValueTable::createGEPExpr(GetElementPtrInst *GEP) {
425 Type *PtrTy = GEP->getType()->getScalarType();
426 const DataLayout &DL = GEP->getDataLayout();
427 unsigned BitWidth = DL.getIndexTypeSizeInBits(PtrTy);
428 SmallMapVector<Value *, APInt, 4> VariableOffsets;
429 APInt ConstantOffset(BitWidth, 0);
430 if (GEP->collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset)) {
431 // Convert into offset representation, to recognize equivalent address
432 // calculations that use different type encoding.
433 LLVMContext &Context = GEP->getContext();
434 E.Opcode = GEP->getOpcode();
435 E.Ty = nullptr;
436 E.VarArgs.push_back(lookupOrAdd(GEP->getPointerOperand()));
437 for (const auto &[V, Scale] : VariableOffsets) {
438 E.VarArgs.push_back(lookupOrAdd(V));
439 E.VarArgs.push_back(lookupOrAdd(ConstantInt::get(Context, Scale)));
440 }
441 if (!ConstantOffset.isZero())
442 E.VarArgs.push_back(
443 lookupOrAdd(ConstantInt::get(Context, ConstantOffset)));
444 } else {
445 // If converting to offset representation fails (for scalable vectors),
446 // fall back to type-based implementation.
447 E.Opcode = GEP->getOpcode();
448 E.Ty = GEP->getSourceElementType();
449 for (Use &Op : GEP->operands())
450 E.VarArgs.push_back(lookupOrAdd(Op));
451 }
452 return E;
453}
454
455//===----------------------------------------------------------------------===//
456// ValueTable External Functions
457//===----------------------------------------------------------------------===//
458
459GVNPass::ValueTable::ValueTable() = default;
460GVNPass::ValueTable::ValueTable(const ValueTable &) = default;
461GVNPass::ValueTable::ValueTable(ValueTable &&) = default;
462GVNPass::ValueTable::~ValueTable() = default;
463GVNPass::ValueTable &
464GVNPass::ValueTable::operator=(const GVNPass::ValueTable &Arg) = default;
465
466/// add - Insert a value into the table with a specified value number.
467void GVNPass::ValueTable::add(Value *V, uint32_t Num) {
468 ValueNumbering.insert(std::make_pair(V, Num));
469 if (PHINode *PN = dyn_cast<PHINode>(V))
470 NumberingPhi[Num] = PN;
471}
472
473/// Include the incoming memory state into the hash of the expression for the
474/// given instruction. If the incoming memory state is:
475/// * LiveOnEntry, add the value number of the entry block,
476/// * a MemoryPhi, add the value number of the basic block corresponding to that
477/// MemoryPhi,
478/// * a MemoryDef, add the value number of the memory setting instruction.
479void GVNPass::ValueTable::addMemoryStateToExp(Instruction *I, Expression &Exp) {
480 assert(MSSA && "addMemoryStateToExp should not be called without MemorySSA");
481 assert(MSSA->getMemoryAccess(I) && "Instruction does not access memory");
482 MemoryAccess *MA = MSSA->getSkipSelfWalker()->getClobberingMemoryAccess(I);
483 Exp.VarArgs.push_back(lookupOrAdd(MA));
484}
485
486uint32_t GVNPass::ValueTable::lookupOrAddCall(CallInst *C) {
487 // FIXME: Currently the calls which may access the thread id may
488 // be considered as not accessing the memory. But this is
489 // problematic for coroutines, since coroutines may resume in a
490 // different thread. So we disable the optimization here for the
491 // correctness. However, it may block many other correct
492 // optimizations. Revert this one when we detect the memory
493 // accessing kind more precisely.
494 if (C->getFunction()->isPresplitCoroutine()) {
495 ValueNumbering[C] = NextValueNumber;
496 return NextValueNumber++;
497 }
498
499 // Do not combine convergent calls since they implicitly depend on the set of
500 // threads that is currently executing, and they might be in different basic
501 // blocks.
502 if (C->isConvergent()) {
503 ValueNumbering[C] = NextValueNumber;
504 return NextValueNumber++;
505 }
506
507 if (AA->doesNotAccessMemory(C)) {
508 Expression Exp = createExpr(C);
509 uint32_t E = assignExpNewValueNum(Exp).first;
510 ValueNumbering[C] = E;
511 return E;
512 }
513
514 if (MD && AA->onlyReadsMemory(C)) {
515 Expression Exp = createExpr(C);
516 auto [E, IsValNumNew] = assignExpNewValueNum(Exp);
517 if (IsValNumNew) {
518 ValueNumbering[C] = E;
519 return E;
520 }
521
522 MemDepResult LocalDep = MD->getDependency(C);
523
524 if (!LocalDep.isDef() && !LocalDep.isNonLocal()) {
525 ValueNumbering[C] = NextValueNumber;
526 return NextValueNumber++;
527 }
528
529 if (LocalDep.isDef()) {
530 // For masked load/store intrinsics, the local_dep may actually be
531 // a normal load or store instruction.
532 CallInst *LocalDepCall = dyn_cast<CallInst>(LocalDep.getInst());
533
534 if (!LocalDepCall || LocalDepCall->arg_size() != C->arg_size()) {
535 ValueNumbering[C] = NextValueNumber;
536 return NextValueNumber++;
537 }
538
539 for (unsigned I = 0, E = C->arg_size(); I < E; ++I) {
540 uint32_t CVN = lookupOrAdd(C->getArgOperand(I));
541 uint32_t LocalDepCallVN = lookupOrAdd(LocalDepCall->getArgOperand(I));
542 if (CVN != LocalDepCallVN) {
543 ValueNumbering[C] = NextValueNumber;
544 return NextValueNumber++;
545 }
546 }
547
548 uint32_t V = lookupOrAdd(LocalDepCall);
549 ValueNumbering[C] = V;
550 return V;
551 }
552
553 // Non-local case.
555 MD->getNonLocalCallDependency(C);
556 // FIXME: Move the checking logic to MemDep!
557 CallInst *CDep = nullptr;
558
559 // Check to see if we have a single dominating call instruction that is
560 // identical to C.
561 for (const NonLocalDepEntry &I : Deps) {
562 if (I.getResult().isNonLocal())
563 continue;
564
565 // We don't handle non-definitions. If we already have a call, reject
566 // instruction dependencies.
567 if (!I.getResult().isDef() || CDep != nullptr) {
568 CDep = nullptr;
569 break;
570 }
571
572 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I.getResult().getInst());
573 // FIXME: All duplicated with non-local case.
574 if (NonLocalDepCall && DT->properlyDominates(I.getBB(), C->getParent())) {
575 CDep = NonLocalDepCall;
576 continue;
577 }
578
579 CDep = nullptr;
580 break;
581 }
582
583 if (!CDep) {
584 ValueNumbering[C] = NextValueNumber;
585 return NextValueNumber++;
586 }
587
588 if (CDep->arg_size() != C->arg_size()) {
589 ValueNumbering[C] = NextValueNumber;
590 return NextValueNumber++;
591 }
592 for (unsigned I = 0, E = C->arg_size(); I < E; ++I) {
593 uint32_t CVN = lookupOrAdd(C->getArgOperand(I));
594 uint32_t CDepVN = lookupOrAdd(CDep->getArgOperand(I));
595 if (CVN != CDepVN) {
596 ValueNumbering[C] = NextValueNumber;
597 return NextValueNumber++;
598 }
599 }
600
601 uint32_t V = lookupOrAdd(CDep);
602 ValueNumbering[C] = V;
603 return V;
604 }
605
606 if (MSSA && IsMSSAEnabled && AA->onlyReadsMemory(C)) {
607 Expression Exp = createExpr(C);
608 addMemoryStateToExp(C, Exp);
609 auto [V, _] = assignExpNewValueNum(Exp);
610 ValueNumbering[C] = V;
611 return V;
612 }
613
614 ValueNumbering[C] = NextValueNumber;
615 return NextValueNumber++;
616}
617
618/// Returns the value number for the specified load or store instruction.
619uint32_t GVNPass::ValueTable::computeLoadStoreVN(Instruction *I) {
620 if (!MSSA || !IsMSSAEnabled) {
621 ValueNumbering[I] = NextValueNumber;
622 return NextValueNumber++;
623 }
624
626 Exp.Ty = I->getType();
627 Exp.Opcode = I->getOpcode();
628 for (Use &Op : I->operands())
629 Exp.VarArgs.push_back(lookupOrAdd(Op));
630 addMemoryStateToExp(I, Exp);
631
632 auto [V, _] = assignExpNewValueNum(Exp);
633 ValueNumbering[I] = V;
634 return V;
635}
636
637/// Returns true if a value number exists for the specified value.
638bool GVNPass::ValueTable::exists(Value *V) const {
639 return ValueNumbering.contains(V);
640}
641
642uint32_t GVNPass::ValueTable::lookupOrAdd(MemoryAccess *MA) {
643 return MSSA->isLiveOnEntryDef(MA) || isa<MemoryPhi>(MA)
644 ? lookupOrAdd(MA->getBlock())
645 : lookupOrAdd(cast<MemoryUseOrDef>(MA)->getMemoryInst());
646}
647
648/// lookupOrAdd - Returns the value number for the specified value, assigning
649/// it a new number if it did not have one before.
650uint32_t GVNPass::ValueTable::lookupOrAdd(Value *V) {
651 auto VI = ValueNumbering.find(V);
652 if (VI != ValueNumbering.end())
653 return VI->second;
654
655 auto *I = dyn_cast<Instruction>(V);
656 if (!I) {
657 ValueNumbering[V] = NextValueNumber;
658 if (isa<BasicBlock>(V))
659 NumberingBB[NextValueNumber] = cast<BasicBlock>(V);
660 return NextValueNumber++;
661 }
662
663 Expression Exp;
664 switch (I->getOpcode()) {
665 case Instruction::Call:
666 return lookupOrAddCall(cast<CallInst>(I));
667 case Instruction::FNeg:
668 case Instruction::Add:
669 case Instruction::FAdd:
670 case Instruction::Sub:
671 case Instruction::FSub:
672 case Instruction::Mul:
673 case Instruction::FMul:
674 case Instruction::UDiv:
675 case Instruction::SDiv:
676 case Instruction::FDiv:
677 case Instruction::URem:
678 case Instruction::SRem:
679 case Instruction::FRem:
680 case Instruction::Shl:
681 case Instruction::LShr:
682 case Instruction::AShr:
683 case Instruction::And:
684 case Instruction::Or:
685 case Instruction::Xor:
686 case Instruction::ICmp:
687 case Instruction::FCmp:
688 case Instruction::Trunc:
689 case Instruction::ZExt:
690 case Instruction::SExt:
691 case Instruction::FPToUI:
692 case Instruction::FPToSI:
693 case Instruction::UIToFP:
694 case Instruction::SIToFP:
695 case Instruction::FPTrunc:
696 case Instruction::FPExt:
697 case Instruction::PtrToInt:
698 case Instruction::PtrToAddr:
699 case Instruction::IntToPtr:
700 case Instruction::AddrSpaceCast:
701 case Instruction::BitCast:
702 case Instruction::Select:
703 case Instruction::Freeze:
704 case Instruction::ExtractElement:
705 case Instruction::InsertElement:
706 case Instruction::ShuffleVector:
707 case Instruction::InsertValue:
708 Exp = createExpr(I);
709 break;
710 case Instruction::GetElementPtr:
711 Exp = createGEPExpr(cast<GetElementPtrInst>(I));
712 break;
713 case Instruction::ExtractValue:
714 Exp = createExtractvalueExpr(cast<ExtractValueInst>(I));
715 break;
716 case Instruction::PHI:
717 ValueNumbering[V] = NextValueNumber;
718 NumberingPhi[NextValueNumber] = cast<PHINode>(V);
719 return NextValueNumber++;
720 case Instruction::Load:
721 case Instruction::Store:
722 return computeLoadStoreVN(I);
723 default:
724 ValueNumbering[V] = NextValueNumber;
725 return NextValueNumber++;
726 }
727
728 uint32_t E = assignExpNewValueNum(Exp).first;
729 ValueNumbering[V] = E;
730 return E;
731}
732
733/// Returns the value number of the specified value. Fails if
734/// the value has not yet been numbered.
735uint32_t GVNPass::ValueTable::lookup(Value *V, bool Verify) const {
736 auto VI = ValueNumbering.find(V);
737 if (Verify) {
738 assert(VI != ValueNumbering.end() && "Value not numbered?");
739 return VI->second;
740 }
741 return (VI != ValueNumbering.end()) ? VI->second : 0;
742}
743
744/// Returns the value number of the given comparison,
745/// assigning it a new number if it did not have one before. Useful when
746/// we deduced the result of a comparison, but don't immediately have an
747/// instruction realizing that comparison to hand.
748uint32_t GVNPass::ValueTable::lookupOrAddCmp(unsigned Opcode,
749 CmpInst::Predicate Predicate,
750 Value *LHS, Value *RHS) {
751 Expression Exp = createCmpExpr(Opcode, Predicate, LHS, RHS);
752 return assignExpNewValueNum(Exp).first;
753}
754
755/// Returns the value number of ptrtoint \p Ptr to \Ty.
756uint32_t GVNPass::ValueTable::lookupPtrToInt(Value *Ptr, Type *Ty) {
757 Expression Exp(Instruction::PtrToInt);
758 Exp.Ty = Ty;
759 Exp.VarArgs.push_back(lookupOrAdd(Ptr));
760 return ExpressionNumbering.lookup(Exp);
761}
762
763/// Remove all entries from the ValueTable.
765 ValueNumbering.clear();
766 ExpressionNumbering.clear();
767 NumberingPhi.clear();
768 NumberingBB.clear();
769 PhiTranslateTable.clear();
770 NextValueNumber = 1;
771 Expressions.clear();
772 ExprIdx.clear();
773 NextExprNumber = 0;
774}
775
776/// Remove a value from the value numbering.
778 uint32_t Num = ValueNumbering.lookup(V);
779 ValueNumbering.erase(V);
780 // If V is PHINode, V <--> value number is an one-to-one mapping.
781 if (isa<PHINode>(V))
782 NumberingPhi.erase(Num);
783 else if (isa<BasicBlock>(V))
784 NumberingBB.erase(Num);
785}
786
787/// verifyRemoved - Verify that the value is removed from all internal data
788/// structures.
789void GVNPass::ValueTable::verifyRemoved(const Value *V) const {
790 assert(!ValueNumbering.contains(V) &&
791 "Inst still occurs in value numbering map!");
792}
793
794//===----------------------------------------------------------------------===//
795// LeaderMap External Functions
796//===----------------------------------------------------------------------===//
797
798/// Push a new Value to the LeaderTable onto the list for its value number.
799void GVNPass::LeaderMap::insert(uint32_t N, Value *V, const BasicBlock *BB) {
800 const auto &[It, Inserted] = NumToLeaders.try_emplace(N, V, BB, nullptr);
801 if (!Inserted) {
802 // Key already exists: insert new node after the head.
803 auto *NewSlot = TableAllocator.Allocate<LeaderListNode>();
804 new (NewSlot) LeaderListNode(V, BB, It->second.Next);
805 It->second.Next = NewSlot;
806 }
807}
808
809/// Scan the list of values corresponding to a given
810/// value number, and remove the given instruction if encountered.
811void GVNPass::LeaderMap::erase(uint32_t N, Instruction *I,
812 const BasicBlock *BB) {
813 auto It = NumToLeaders.find(N);
814 if (It == NumToLeaders.end())
815 return;
816
817 LeaderListNode *Prev = nullptr;
818 LeaderListNode *Curr = &It->second;
819
820 while (Curr && (Curr->Entry.Val != I || Curr->Entry.BB != BB)) {
821 Prev = Curr;
822 Curr = Curr->Next;
823 }
824
825 if (!Curr)
826 return;
827
828 if (Prev) {
829 // Non-head node: unlink and destroy.
830 Prev->Next = Curr->Next;
831 Curr->~LeaderListNode();
832 TableAllocator.Deallocate<LeaderListNode>(Curr);
833 } else {
834 // Head node (stored by value in DenseMap).
835 if (!Curr->Next) {
836 // Only node; erase from map (DenseMap calls the destructor).
837 NumToLeaders.erase(It);
838 } else {
839 // Move second node's data into head, then destroy second node.
840 LeaderListNode *Next = Curr->Next;
841 Curr->Entry.Val = std::move(Next->Entry.Val);
842 Curr->Entry.BB = Next->Entry.BB;
843 Curr->Next = Next->Next;
844 Next->~LeaderListNode();
845 TableAllocator.Deallocate<LeaderListNode>(Next);
846 }
847 }
848}
849
850//===----------------------------------------------------------------------===//
851// GVN Pass
852//===----------------------------------------------------------------------===//
853
855 return Options.AllowScalarPRE.value_or(GVNEnableScalarPRE);
856}
857
859 return Options.AllowLoadPRE.value_or(GVNEnableLoadPRE);
860}
861
863 return Options.AllowLoadInLoopPRE.value_or(GVNEnableLoadInLoopPRE);
864}
865
867 return Options.AllowLoadPRESplitBackedge.value_or(
869}
870
872 return Options.AllowMemDep.value_or(GVNEnableMemDep);
873}
874
876 return Options.AllowMemorySSA.value_or(GVNEnableMemorySSA);
877}
878
880 // FIXME: The order of evaluation of these 'getResult' calls is very
881 // significant! Re-ordering these variables will cause GVN when run alone to
882 // be less effective! We should fix memdep and basic-aa to not exhibit this
883 // behavior, but until then don't change the order here.
884 auto &AC = AM.getResult<AssumptionAnalysis>(F);
885 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
886 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
887 auto &AA = AM.getResult<AAManager>(F);
888 auto *MemDep =
890 auto &LI = AM.getResult<LoopAnalysis>(F);
891 auto *MSSA = AM.getCachedResult<MemorySSAAnalysis>(F);
892 if (isMemorySSAEnabled() && !MSSA) {
893 assert(!MemDep &&
894 "On-demand computation of MemSSA implies that MemDep is disabled!");
895 MSSA = &AM.getResult<MemorySSAAnalysis>(F);
896 }
898 bool Changed = runImpl(F, AC, DT, TLI, AA, MemDep, LI, &ORE,
899 MSSA ? &MSSA->getMSSA() : nullptr);
900 if (!Changed)
901 return PreservedAnalyses::all();
905 if (MSSA)
908 return PA;
909}
910
912 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
913 static_cast<PassInfoMixin<GVNPass> *>(this)->printPipeline(
914 OS, MapClassName2PassName);
915
916 OS << '<';
917 if (Options.AllowScalarPRE != std::nullopt)
918 OS << (*Options.AllowScalarPRE ? "" : "no-") << "scalar-pre;";
919 if (Options.AllowLoadPRE != std::nullopt)
920 OS << (*Options.AllowLoadPRE ? "" : "no-") << "load-pre;";
921 if (Options.AllowLoadPRESplitBackedge != std::nullopt)
922 OS << (*Options.AllowLoadPRESplitBackedge ? "" : "no-")
923 << "split-backedge-load-pre;";
924 if (Options.AllowMemDep != std::nullopt)
925 OS << (*Options.AllowMemDep ? "" : "no-") << "memdep;";
926 if (Options.AllowMemorySSA != std::nullopt)
927 OS << (*Options.AllowMemorySSA ? "" : "no-") << "memoryssa";
928 OS << '>';
929}
930
932 salvageKnowledge(I, AC);
934 removeInstruction(I);
935}
936
937enum class AvailabilityState : char {
938 /// We know the block *is not* fully available. This is a fixpoint.
940 /// We know the block *is* fully available. This is a fixpoint.
942 /// We do not know whether the block is fully available or not,
943 /// but we are currently speculating that it will be.
944 /// If it would have turned out that the block was, in fact, not fully
945 /// available, this would have been cleaned up into an Unavailable.
947};
948
949/// Return true if we can prove that the value
950/// we're analyzing is fully available in the specified block. As we go, keep
951/// track of which blocks we know are fully alive in FullyAvailableBlocks. This
952/// map is actually a tri-state map with the following values:
953/// 0) we know the block *is not* fully available.
954/// 1) we know the block *is* fully available.
955/// 2) we do not know whether the block is fully available or not, but we are
956/// currently speculating that it will be.
958 BasicBlock *BB,
959 DenseMap<BasicBlock *, AvailabilityState> &FullyAvailableBlocks) {
961 std::optional<BasicBlock *> UnavailableBB;
962
963 // The number of times we didn't find an entry for a block in a map and
964 // optimistically inserted an entry marking block as speculatively available.
965 unsigned NumNewNewSpeculativelyAvailableBBs = 0;
966
967#ifndef NDEBUG
968 SmallPtrSet<BasicBlock *, 32> NewSpeculativelyAvailableBBs;
970#endif
971
972 Worklist.emplace_back(BB);
973 while (!Worklist.empty()) {
974 BasicBlock *CurrBB = Worklist.pop_back_val(); // LoadFO - depth-first!
975 // Optimistically assume that the block is Speculatively Available and check
976 // to see if we already know about this block in one lookup.
977 std::pair<DenseMap<BasicBlock *, AvailabilityState>::iterator, bool> IV =
978 FullyAvailableBlocks.try_emplace(
980 AvailabilityState &State = IV.first->second;
981
982 // Did the entry already exist for this block?
983 if (!IV.second) {
984 if (State == AvailabilityState::Unavailable) {
985 UnavailableBB = CurrBB;
986 break; // Backpropagate unavailability info.
987 }
988
989#ifndef NDEBUG
990 AvailableBBs.emplace_back(CurrBB);
991#endif
992 continue; // Don't recurse further, but continue processing worklist.
993 }
994
995 // No entry found for block.
996 ++NumNewNewSpeculativelyAvailableBBs;
997 bool OutOfBudget = NumNewNewSpeculativelyAvailableBBs > MaxBBSpeculations;
998
999 // If we have exhausted our budget, mark this block as unavailable.
1000 // Also, if this block has no predecessors, the value isn't live-in here.
1001 if (OutOfBudget || pred_empty(CurrBB)) {
1002 MaxBBSpeculationCutoffReachedTimes += (int)OutOfBudget;
1004 UnavailableBB = CurrBB;
1005 break; // Backpropagate unavailability info.
1006 }
1007
1008 // Tentatively consider this block as speculatively available.
1009#ifndef NDEBUG
1010 NewSpeculativelyAvailableBBs.insert(CurrBB);
1011#endif
1012 // And further recurse into block's predecessors, in depth-first order!
1013 Worklist.append(pred_begin(CurrBB), pred_end(CurrBB));
1014 }
1015
1016#if LLVM_ENABLE_STATS
1017 IsValueFullyAvailableInBlockNumSpeculationsMax.updateMax(
1018 NumNewNewSpeculativelyAvailableBBs);
1019#endif
1020
1021 // If the block isn't marked as fixpoint yet
1022 // (the Unavailable and Available states are fixpoints).
1023 auto MarkAsFixpointAndEnqueueSuccessors =
1024 [&](BasicBlock *BB, AvailabilityState FixpointState) {
1025 auto It = FullyAvailableBlocks.find(BB);
1026 if (It == FullyAvailableBlocks.end())
1027 return; // Never queried this block, leave as-is.
1028 switch (AvailabilityState &State = It->second) {
1031 return; // Don't backpropagate further, continue processing worklist.
1033 State = FixpointState;
1034#ifndef NDEBUG
1035 assert(NewSpeculativelyAvailableBBs.erase(BB) &&
1036 "Found a speculatively available successor leftover?");
1037#endif
1038 // Queue successors for further processing.
1039 Worklist.append(succ_begin(BB), succ_end(BB));
1040 return;
1041 }
1042 };
1043
1044 if (UnavailableBB) {
1045 // Okay, we have encountered an unavailable block.
1046 // Mark speculatively available blocks reachable from UnavailableBB as
1047 // unavailable as well. Paths are terminated when they reach blocks not in
1048 // FullyAvailableBlocks or they are not marked as speculatively available.
1049 Worklist.clear();
1050 Worklist.append(succ_begin(*UnavailableBB), succ_end(*UnavailableBB));
1051 while (!Worklist.empty())
1052 MarkAsFixpointAndEnqueueSuccessors(Worklist.pop_back_val(),
1054 }
1055
1056#ifndef NDEBUG
1057 Worklist.clear();
1058 for (BasicBlock *AvailableBB : AvailableBBs)
1059 Worklist.append(succ_begin(AvailableBB), succ_end(AvailableBB));
1060 while (!Worklist.empty())
1061 MarkAsFixpointAndEnqueueSuccessors(Worklist.pop_back_val(),
1063
1064 assert(NewSpeculativelyAvailableBBs.empty() &&
1065 "Must have fixed all the new speculatively available blocks.");
1066#endif
1067
1068 return !UnavailableBB;
1069}
1070
1071/// If the specified OldValue exists in ValuesPerBlock, replace its value with
1072/// NewValue.
1074 SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock, Value *OldValue,
1075 Value *NewValue) {
1076 for (AvailableValueInBlock &V : ValuesPerBlock) {
1077 if (V.AV.Val == OldValue)
1078 V.AV.Val = NewValue;
1079 if (V.AV.isSelectValue()) {
1080 if (V.AV.V1 == OldValue)
1081 V.AV.V1 = NewValue;
1082 if (V.AV.V2 == OldValue)
1083 V.AV.V2 = NewValue;
1084 }
1085 }
1086}
1087
1088/// Given a set of loads specified by ValuesPerBlock,
1089/// construct SSA form, allowing us to eliminate Load. This returns the value
1090/// that should be used at Load's definition site.
1091static Value *
1094 GVNPass &GVN) {
1095 // Check for the fully redundant, dominating load case. In this case, we can
1096 // just use the dominating value directly.
1097 if (ValuesPerBlock.size() == 1 &&
1098 GVN.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
1099 Load->getParent())) {
1100 assert(!ValuesPerBlock[0].AV.isUndefValue() &&
1101 "Dead BB dominate this block");
1102 return ValuesPerBlock[0].MaterializeAdjustedValue(Load);
1103 }
1104
1105 // Otherwise, we have to construct SSA form.
1107 SSAUpdater SSAUpdate(&NewPHIs);
1108 SSAUpdate.Initialize(Load->getType(), Load->getName());
1109
1110 for (const AvailableValueInBlock &AV : ValuesPerBlock) {
1111 BasicBlock *BB = AV.BB;
1112
1113 if (AV.AV.isUndefValue())
1114 continue;
1115
1116 if (SSAUpdate.HasValueForBlock(BB))
1117 continue;
1118
1119 // If the value is the load that we will be eliminating, and the block it's
1120 // available in is the block that the load is in, then don't add it as
1121 // SSAUpdater will resolve the value to the relevant phi which may let it
1122 // avoid phi construction entirely if there's actually only one value.
1123 if (BB == Load->getParent() &&
1124 ((AV.AV.isSimpleValue() && AV.AV.getSimpleValue() == Load) ||
1125 (AV.AV.isCoercedLoadValue() && AV.AV.getCoercedLoadValue() == Load)))
1126 continue;
1127
1128 SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(Load));
1129 }
1130
1131 // Perform PHI construction.
1132 return SSAUpdate.GetValueInMiddleOfBlock(Load->getParent());
1133}
1134
1136 Instruction *InsertPt) const {
1137 Value *Res;
1138 Type *LoadTy = Load->getType();
1139 const DataLayout &DL = Load->getDataLayout();
1140 if (isSimpleValue()) {
1141 Res = getSimpleValue();
1142 if (Res->getType() != LoadTy) {
1143 Res = getValueForLoad(Res, Offset, LoadTy, InsertPt, Load->getFunction());
1144
1145 LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset
1146 << " " << *getSimpleValue() << '\n'
1147 << *Res << '\n'
1148 << "\n\n\n");
1149 }
1150 } else if (isCoercedLoadValue()) {
1151 LoadInst *CoercedLoad = getCoercedLoadValue();
1152 if (CoercedLoad->getType() == LoadTy && Offset == 0) {
1153 Res = CoercedLoad;
1154 combineMetadataForCSE(CoercedLoad, Load, false);
1155 } else {
1156 Res = getValueForLoad(CoercedLoad, Offset, LoadTy, InsertPt,
1157 Load->getFunction());
1158 // We are adding a new user for this load, for which the original
1159 // metadata may not hold. Additionally, the new load may have a different
1160 // size and type, so their metadata cannot be combined in any
1161 // straightforward way.
1162 // Drop all metadata that is not known to cause immediate UB on violation,
1163 // unless the load has !noundef, in which case all metadata violations
1164 // will be promoted to UB.
1165 // !noalias and !alias.scope are kept: the load is not moved and still
1166 // accesses the same memory, and these are independent of the load type
1167 // and offset, so they remain valid for the coerced result.
1168 if (!CoercedLoad->hasMetadata(LLVMContext::MD_noundef))
1169 CoercedLoad->dropUnknownNonDebugMetadata(
1170 {LLVMContext::MD_dereferenceable,
1171 LLVMContext::MD_dereferenceable_or_null,
1172 LLVMContext::MD_invariant_load, LLVMContext::MD_invariant_group,
1173 LLVMContext::MD_alias_scope, LLVMContext::MD_noalias});
1174 LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset
1175 << " " << *getCoercedLoadValue() << '\n'
1176 << *Res << '\n'
1177 << "\n\n\n");
1178 }
1179 } else if (isMemIntrinValue()) {
1181 InsertPt, DL);
1182 LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
1183 << " " << *getMemIntrinValue() << '\n'
1184 << *Res << '\n'
1185 << "\n\n\n");
1186 } else if (isSelectValue()) {
1187 // Introduce a new value select for a load from an eligible pointer select.
1189 assert(V1 && V2 && "both value operands of the select must be present");
1190 Res = SelectInst::Create(Cond, V1, V2, "", InsertPt->getIterator());
1191 // We use the DebugLoc from the original load here, as this instruction
1192 // materializes the value that would previously have been loaded.
1193 cast<SelectInst>(Res)->setDebugLoc(Load->getDebugLoc());
1194 } else {
1195 llvm_unreachable("Should not materialize value from dead block");
1196 }
1197 assert(Res && "failed to materialize?");
1198 return Res;
1199}
1200
1201static bool isLifetimeStart(const Instruction *Inst) {
1202 if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
1203 return II->getIntrinsicID() == Intrinsic::lifetime_start;
1204 return false;
1205}
1206
1207/// Assuming To can be reached from both From and Between, does Between lie on
1208/// every path from From to To?
1209static bool liesBetween(const Instruction *From, Instruction *Between,
1210 const Instruction *To, const DominatorTree *DT) {
1211 if (From->getParent() == Between->getParent())
1212 return DT->dominates(From, Between);
1214 Exclusion.insert(Between->getParent());
1215 return !isPotentiallyReachable(From, To, &Exclusion, DT);
1216}
1217
1219 const DominatorTree *DT) {
1220 Value *PtrOp = Load->getPointerOperand();
1221 if (!PtrOp->hasUseList())
1222 return nullptr;
1223
1224 Instruction *OtherAccess = nullptr;
1225
1226 for (auto *U : PtrOp->users()) {
1227 if (U != Load && (isa<LoadInst>(U) || isa<StoreInst>(U))) {
1228 auto *I = cast<Instruction>(U);
1229 if (I->getFunction() == Load->getFunction() && DT->dominates(I, Load)) {
1230 // Use the most immediately dominating value.
1231 if (OtherAccess) {
1232 if (DT->dominates(OtherAccess, I))
1233 OtherAccess = I;
1234 else
1235 assert(U == OtherAccess || DT->dominates(I, OtherAccess));
1236 } else
1237 OtherAccess = I;
1238 }
1239 }
1240 }
1241
1242 if (OtherAccess)
1243 return OtherAccess;
1244
1245 // There is no dominating use, check if we can find a closest non-dominating
1246 // use that lies between any other potentially available use and Load.
1247 for (auto *U : PtrOp->users()) {
1248 if (U != Load && (isa<LoadInst>(U) || isa<StoreInst>(U))) {
1249 auto *I = cast<Instruction>(U);
1250 if (I->getFunction() == Load->getFunction() &&
1251 isPotentiallyReachable(I, Load, nullptr, DT)) {
1252 if (OtherAccess) {
1253 if (liesBetween(OtherAccess, I, Load, DT)) {
1254 OtherAccess = I;
1255 } else if (!liesBetween(I, OtherAccess, Load, DT)) {
1256 // These uses are both partially available at Load were it not for
1257 // the clobber, but neither lies strictly after the other.
1258 OtherAccess = nullptr;
1259 break;
1260 } // else: keep current OtherAccess since it lies between U and
1261 // Load.
1262 } else {
1263 OtherAccess = I;
1264 }
1265 }
1266 }
1267 }
1268
1269 return OtherAccess;
1270}
1271
1272/// Try to locate the three instruction involved in a missed
1273/// load-elimination case that is due to an intervening store.
1275 const DominatorTree *DT,
1277 using namespace ore;
1278
1279 OptimizationRemarkMissed R(DEBUG_TYPE, "LoadClobbered", Load);
1280 R << "load of type " << NV("Type", Load->getType()) << " not eliminated"
1281 << setExtraArgs();
1282
1283 const Instruction *OtherAccess = findMayClobberedPtrAccess(Load, DT);
1284 if (OtherAccess)
1285 R << " in favor of " << NV("OtherAccess", OtherAccess);
1286
1287 R << " because it is clobbered by " << NV("ClobberedBy", DepInst);
1288
1289 ORE->emit(R);
1290}
1291
1292// Find a dominating value for Loc memory location in the extended basic block
1293// (chain of basic blocks with single predecessors) starting From instruction.
1294// Returns the value from a matching load or a simple store to the same pointer.
1296 Instruction *From, AAResults *AA) {
1297 uint32_t NumVisitedInsts = 0;
1298 BasicBlock *FromBB = From->getParent();
1299 BatchAAResults BatchAA(*AA);
1300 for (BasicBlock *BB = FromBB; BB; BB = BB->getSinglePredecessor())
1301 for (auto *Inst = BB == FromBB ? From : BB->getTerminator();
1302 Inst != nullptr; Inst = Inst->getPrevNode()) {
1303 // Stop the search if limit is reached.
1304 if (++NumVisitedInsts > MaxNumVisitedInsts)
1305 return nullptr;
1306 if (isModSet(BatchAA.getModRefInfo(Inst, Loc))) {
1307 // A simple store to the exact location can forward its value.
1308 if (auto *SI = dyn_cast<StoreInst>(Inst))
1309 if (SI->isSimple() && SI->getPointerOperand() == Loc.Ptr &&
1310 SI->getValueOperand()->getType() == LoadTy)
1311 return SI->getValueOperand();
1312 return nullptr;
1313 }
1314 if (auto *LI = dyn_cast<LoadInst>(Inst))
1315 if (LI->getPointerOperand() == Loc.Ptr && LI->getType() == LoadTy)
1316 return LI;
1317 }
1318 return nullptr;
1319}
1320
1321std::optional<AvailableValue>
1322GVNPass::analyzeSelectAvailability(LoadInst *Load, Value *Cond, Value *TrueAddr,
1323 Value *FalseAddr, Instruction *From) {
1324 assert(TrueAddr->getType() == Load->getPointerOperandType() &&
1325 "Invalid address type of true side of select dependency");
1326 assert(FalseAddr->getType() == Load->getPointerOperandType() &&
1327 "Invalid address type of false side of select dependency");
1328 // We can convert a load through a select address into a select of the two
1329 // loaded values only if both sides have a dominating, non-clobbered value of
1330 // the right type in the extended basic block ending at From.
1331 auto Loc = MemoryLocation::get(Load);
1332 Value *V1 = findDominatingValue(Loc.getWithNewPtr(TrueAddr), Load->getType(),
1333 From, getAliasAnalysis());
1334 if (!V1)
1335 return std::nullopt;
1336 Value *V2 = findDominatingValue(Loc.getWithNewPtr(FalseAddr), Load->getType(),
1337 From, getAliasAnalysis());
1338 if (!V2)
1339 return std::nullopt;
1340 return AvailableValue::getSelect(Cond, V1, V2);
1341}
1342
1343std::optional<AvailableValue>
1344GVNPass::analyzeLoadAvailability(LoadInst *Load, const ReachingMemVal &Dep,
1345 Value *Address) {
1346 assert(Load->isUnordered() && "rules below are incorrect for ordered access");
1347 assert((Dep.Kind == DepKind::Def || Dep.Kind == DepKind::Clobber) &&
1348 "expected a local dependence");
1349
1350 Instruction *DepInst = Dep.Inst;
1351
1352 const DataLayout &DL = Load->getDataLayout();
1353 if (Dep.Kind == DepKind::Clobber) {
1354 // If the dependence is to a store that writes to a superset of the bits
1355 // read by the load, we can extract the bits we need for the load from the
1356 // stored value.
1357 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
1358 // Can't forward from non-atomic to atomic without violating memory model.
1359 if (Address && Load->isAtomic() <= DepSI->isAtomic()) {
1360 int Offset =
1361 analyzeLoadFromClobberingStore(Load->getType(), Address, DepSI, DL);
1362 if (Offset != -1)
1363 return AvailableValue::get(DepSI->getValueOperand(), Offset);
1364 }
1365 }
1366
1367 // Check to see if we have something like this:
1368 // load i32* P
1369 // load i8* (P+1)
1370 // if we have this, replace the later with an extraction from the former.
1371 if (LoadInst *DepLoad = dyn_cast<LoadInst>(DepInst)) {
1372 // If this is a clobber and L is the first instruction in its block, then
1373 // we have the first instruction in the entry block.
1374 // Can't forward from non-atomic to atomic without violating memory model.
1375 if (DepLoad != Load && Address &&
1376 Load->isAtomic() <= DepLoad->isAtomic()) {
1377 Type *LoadType = Load->getType();
1378 int Offset = Dep.Offset;
1379
1380 if (!isMemorySSAEnabled()) {
1381 // If MD reported clobber, check it was nested.
1382 if (canCoerceMustAliasedValueToLoad(DepLoad, LoadType,
1383 DepLoad->getFunction())) {
1384 const auto ClobberOff = MD->getClobberOffset(DepLoad);
1385 // GVN has no deal with a negative offset.
1386 Offset = (ClobberOff == std::nullopt || *ClobberOff < 0)
1387 ? -1
1388 : *ClobberOff;
1389 }
1390 } else {
1391 if (!canCoerceMustAliasedValueToLoad(DepLoad, LoadType,
1392 DepLoad->getFunction()) ||
1393 Offset < 0)
1394 Offset = -1;
1395 }
1396 if (Offset == -1)
1397 Offset =
1398 analyzeLoadFromClobberingLoad(LoadType, Address, DepLoad, DL);
1399 if (Offset != -1)
1400 return AvailableValue::getLoad(DepLoad, Offset);
1401 }
1402 }
1403
1404 // If the clobbering value is a memset/memcpy/memmove, see if we can
1405 // forward a value on from it.
1406 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
1407 if (Address && !Load->isAtomic()) {
1409 DepMI, DL);
1410 if (Offset != -1)
1411 return AvailableValue::getMI(DepMI, Offset);
1412 }
1413 }
1414
1415 // Nothing known about this clobber, have to be conservative.
1416 LLVM_DEBUG(
1417 // fast print dep, using operator<< on instruction is too slow.
1418 dbgs() << "GVN: load "; Load->printAsOperand(dbgs());
1419 dbgs() << " is clobbered by " << *DepInst << '\n';);
1420 if (ORE->allowExtraAnalysis(DEBUG_TYPE))
1421 reportMayClobberedLoad(Load, DepInst, DT, ORE);
1422
1423 return std::nullopt;
1424 }
1425 assert(Dep.Kind == DepKind::Def && "follows from above");
1426
1427 // Loading the alloca -> undef.
1428 // Loading immediately after lifetime begin -> undef.
1429 if (isa<AllocaInst>(DepInst) || isLifetimeStart(DepInst))
1430 return AvailableValue::get(UndefValue::get(Load->getType()));
1431
1432 if (Constant *InitVal =
1433 getInitialValueOfAllocation(DepInst, TLI, Load->getType()))
1434 return AvailableValue::get(InitVal);
1435
1436 if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
1437 // Reject loads and stores that are to the same address but are of
1438 // different types if we have to. If the stored value is convertable to
1439 // the loaded value, we can reuse it.
1440 if (!canCoerceMustAliasedValueToLoad(S->getValueOperand(), Load->getType(),
1441 S->getFunction()))
1442 return std::nullopt;
1443
1444 // Can't forward from non-atomic to atomic without violating memory model.
1445 if (S->isAtomic() < Load->isAtomic())
1446 return std::nullopt;
1447
1448 return AvailableValue::get(S->getValueOperand());
1449 }
1450
1451 if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
1452 // If the types mismatch and we can't handle it, reject reuse of the load.
1453 // If the stored value is larger or equal to the loaded value, we can reuse
1454 // it.
1455 if (!canCoerceMustAliasedValueToLoad(LD, Load->getType(),
1456 LD->getFunction()))
1457 return std::nullopt;
1458
1459 // Can't forward from non-atomic to atomic without violating memory model.
1460 if (LD->isAtomic() < Load->isAtomic())
1461 return std::nullopt;
1462
1463 return AvailableValue::getLoad(LD);
1464 }
1465
1466 // Check if load with Addr dependent from select can be converted to select
1467 // between load values. There must be no instructions between the found
1468 // loads and DepInst that may clobber the loads.
1469 if (auto *Sel = dyn_cast<SelectInst>(DepInst)) {
1470 assert(Sel->getType() == Load->getPointerOperandType());
1471 if (auto AV = analyzeSelectAvailability(Load, Sel->getCondition(),
1472 Sel->getTrueValue(),
1473 Sel->getFalseValue(), DepInst))
1474 return AV;
1475 return std::nullopt;
1476 }
1477
1478 // Unknown def - must be conservative.
1479 LLVM_DEBUG(
1480 // fast print dep, using operator<< on instruction is too slow.
1481 dbgs() << "GVN: load "; Load->printAsOperand(dbgs());
1482 dbgs() << " has unknown def " << *DepInst << '\n';);
1483 return std::nullopt;
1484}
1485
1486void GVNPass::analyzeLoadAvailability(LoadInst *Load,
1487 SmallVectorImpl<ReachingMemVal> &Deps,
1488 AvailValInBlkVect &ValuesPerBlock,
1489 UnavailBlkVect &UnavailableBlocks) {
1490 // Filter out useless results (non-locals, etc). Keep track of the blocks
1491 // where we have a value available in repl, also keep track of whether we see
1492 // dependencies that produce an unknown value for the load (such as a call
1493 // that could potentially clobber the load).
1494 for (const auto &Dep : Deps) {
1495 BasicBlock *DepBB = Dep.Block;
1496
1497 if (DeadBlocks.count(DepBB)) {
1498 // Dead dependent mem-op disguise as a load evaluating the same value
1499 // as the load in question.
1500 ValuesPerBlock.push_back(AvailableValueInBlock::getUndef(DepBB));
1501 continue;
1502 }
1503
1504 if (Dep.Kind == DepKind::Other) {
1505 UnavailableBlocks.push_back(DepBB);
1506 continue;
1507 }
1508
1509 // The load address is a select in this block: try to rematerialize the
1510 // load as a select of the two reaching values (one per side). The values
1511 // are searched for at the end of DepBB.
1512 if (Dep.Kind == DepKind::Select) {
1513 if (auto AV = analyzeSelectAvailability(
1514 Load, const_cast<Value *>(Dep.SelCond),
1515 const_cast<Value *>(Dep.SelTrueAddr),
1516 const_cast<Value *>(Dep.SelFalseAddr), DepBB->getTerminator())) {
1517 ValuesPerBlock.push_back(
1518 AvailableValueInBlock::get(DepBB, std::move(*AV)));
1519 } else {
1520 UnavailableBlocks.push_back(DepBB);
1521 }
1522 continue;
1523 }
1524
1525 // The address being loaded in this non-local block may not be the same as
1526 // the pointer operand of the load if PHI translation occurs. Make sure
1527 // to consider the right address.
1528 if (auto AV =
1529 analyzeLoadAvailability(Load, Dep, const_cast<Value *>(Dep.Addr))) {
1530 // subtlety: because we know this was a non-local dependency, we know
1531 // it's safe to materialize anywhere between the instruction within
1532 // DepInfo and the end of it's block.
1533 ValuesPerBlock.push_back(
1534 AvailableValueInBlock::get(DepBB, std::move(*AV)));
1535 } else {
1536 UnavailableBlocks.push_back(DepBB);
1537 }
1538 }
1539
1540 assert(Deps.size() == ValuesPerBlock.size() + UnavailableBlocks.size() &&
1541 "post condition violation");
1542}
1543
1544/// Given the following code, v1 is partially available on some edges, but not
1545/// available on the edge from PredBB. This function tries to find if there is
1546/// another identical load in the other successor of PredBB.
1547///
1548/// v0 = load %addr
1549/// br %LoadBB
1550///
1551/// LoadBB:
1552/// v1 = load %addr
1553/// ...
1554///
1555/// PredBB:
1556/// ...
1557/// br %cond, label %LoadBB, label %SuccBB
1558///
1559/// SuccBB:
1560/// v2 = load %addr
1561/// ...
1562///
1563LoadInst *GVNPass::findLoadToHoistIntoPred(BasicBlock *Pred, BasicBlock *LoadBB,
1564 LoadInst *Load) {
1565 // For simplicity we handle a Pred has 2 successors only.
1566 auto *Term = Pred->getTerminator();
1567 if (Term->getNumSuccessors() != 2 || Term->isSpecialTerminator())
1568 return nullptr;
1569 auto *SuccBB = Term->getSuccessor(0);
1570 if (SuccBB == LoadBB)
1571 SuccBB = Term->getSuccessor(1);
1572 if (!SuccBB->getSinglePredecessor())
1573 return nullptr;
1574
1575 unsigned int NumInsts = MaxNumInsnsPerBlock;
1576 for (Instruction &Inst : *SuccBB) {
1577 if (Inst.isDebugOrPseudoInst())
1578 continue;
1579 if (--NumInsts == 0)
1580 return nullptr;
1581
1582 if (!Inst.isIdenticalTo(Load))
1583 continue;
1584
1585 bool HasLocalDep = true;
1586 if (!isMemorySSAEnabled()) {
1587 MemDepResult Dep = MD->getDependency(&Inst);
1588 HasLocalDep = !Dep.isNonLocal();
1589 } else {
1590 auto *MSSA = MSSAU->getMemorySSA();
1591 // Do not hoist if the identical load has ordering constraint.
1592 if (auto *MA = MSSA->getMemoryAccess(&Inst); MA && isa<MemoryUse>(MA)) {
1593 auto *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(MA);
1594 HasLocalDep = Clobber->getBlock() == SuccBB;
1595 }
1596 }
1597
1598 // If an identical load doesn't depends on any local instructions, it can
1599 // be safely moved to PredBB.
1600 // Also check for the implicit control flow instructions. See the comments
1601 // in performLoadPRE for details.
1602 if (!HasLocalDep && !ICF->isDominatedByICFIFromSameBlock(&Inst))
1603 return cast<LoadInst>(&Inst);
1604
1605 // Otherwise there is something in the same BB clobbers the memory, we can't
1606 // move this and later load to PredBB.
1607 return nullptr;
1608 }
1609
1610 return nullptr;
1611}
1612
1613void GVNPass::eliminatePartiallyRedundantLoad(
1614 LoadInst *Load, AvailValInBlkVect &ValuesPerBlock,
1615 MapVector<BasicBlock *, Value *> &AvailableLoads,
1616 MapVector<BasicBlock *, LoadInst *> *CriticalEdgePredAndLoad) {
1617 for (const auto &AvailableLoad : AvailableLoads) {
1618 BasicBlock *UnavailableBlock = AvailableLoad.first;
1619 Value *LoadPtr = AvailableLoad.second;
1620
1621 auto *NewLoad =
1622 new LoadInst(Load->getType(), LoadPtr, Load->getName() + ".pre",
1623 Load->getProperties(),
1624 UnavailableBlock->getTerminator()->getIterator());
1625 NewLoad->setDebugLoc(Load->getDebugLoc());
1626 if (MSSAU) {
1627 auto *NewAccess = MSSAU->createMemoryAccessInBB(
1628 NewLoad, nullptr, NewLoad->getParent(), MemorySSA::BeforeTerminator);
1629 if (auto *NewDef = dyn_cast<MemoryDef>(NewAccess))
1630 MSSAU->insertDef(NewDef, /*RenameUses=*/true);
1631 else
1632 MSSAU->insertUse(cast<MemoryUse>(NewAccess), /*RenameUses=*/true);
1633 }
1634
1635 // Transfer the old load's AA tags to the new load.
1636 AAMDNodes Tags = Load->getAAMetadata();
1637 if (Tags)
1638 NewLoad->setAAMetadata(Tags);
1639
1640 if (auto *MD = Load->getMetadata(LLVMContext::MD_invariant_load))
1641 NewLoad->setMetadata(LLVMContext::MD_invariant_load, MD);
1642 if (auto *InvGroupMD = Load->getMetadata(LLVMContext::MD_invariant_group))
1643 NewLoad->setMetadata(LLVMContext::MD_invariant_group, InvGroupMD);
1644 if (auto *RangeMD = Load->getMetadata(LLVMContext::MD_range))
1645 NewLoad->setMetadata(LLVMContext::MD_range, RangeMD);
1646 if (auto *NoFPClassMD = Load->getMetadata(LLVMContext::MD_nofpclass))
1647 NewLoad->setMetadata(LLVMContext::MD_nofpclass, NoFPClassMD);
1648
1649 if (auto *AccessMD = Load->getMetadata(LLVMContext::MD_access_group))
1650 if (LI->getLoopFor(Load->getParent()) == LI->getLoopFor(UnavailableBlock))
1651 NewLoad->setMetadata(LLVMContext::MD_access_group, AccessMD);
1652
1653 // We do not propagate the old load's debug location, because the new
1654 // load now lives in a different BB, and we want to avoid a jumpy line
1655 // table.
1656 // FIXME: How do we retain source locations without causing poor debugging
1657 // behavior?
1658
1659 // Add the newly created load.
1660 ValuesPerBlock.push_back(
1661 AvailableValueInBlock::get(UnavailableBlock, NewLoad));
1662 if (MD)
1663 MD->invalidateCachedPointerInfo(LoadPtr);
1664 LLVM_DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
1665
1666 // For PredBB in CriticalEdgePredAndLoad we need to replace the uses of old
1667 // load instruction with the new created load instruction.
1668 if (CriticalEdgePredAndLoad) {
1669 auto It = CriticalEdgePredAndLoad->find(UnavailableBlock);
1670 if (It != CriticalEdgePredAndLoad->end()) {
1671 ++NumPRELoadMoved2CEPred;
1672 ICF->insertInstructionTo(NewLoad, UnavailableBlock);
1673 LoadInst *OldLoad = It->second;
1674 combineMetadataForCSE(NewLoad, OldLoad, /*DoesKMove=*/true);
1675 OldLoad->replaceAllUsesWith(NewLoad);
1676 replaceValuesPerBlockEntry(ValuesPerBlock, OldLoad, NewLoad);
1677 if (uint32_t ValNo = VN.lookup(OldLoad, false))
1678 LeaderTable.erase(ValNo, OldLoad, OldLoad->getParent());
1679 removeInstruction(OldLoad);
1680 }
1681 }
1682 }
1683
1684 // Perform PHI construction.
1685 Value *V = constructSSAForLoadSet(Load, ValuesPerBlock, *this);
1686 // constructSSAForLoadSet is responsible for combining metadata.
1687 ICF->removeUsersOf(Load);
1688 Load->replaceAllUsesWith(V);
1689 if (isa<PHINode>(V))
1690 V->takeName(Load);
1691 if (Instruction *I = dyn_cast<Instruction>(V))
1692 I->setDebugLoc(Load->getDebugLoc());
1693 if (MD && V->getType()->isPtrOrPtrVectorTy())
1694 MD->invalidateCachedPointerInfo(V);
1695 ORE->emit([&]() {
1696 return OptimizationRemark(DEBUG_TYPE, "LoadPRE", Load)
1697 << "load eliminated by PRE";
1698 });
1700}
1701
1702bool GVNPass::performLoadPRE(LoadInst *Load, AvailValInBlkVect &ValuesPerBlock,
1703 UnavailBlkVect &UnavailableBlocks) {
1704 // Okay, we have *some* definitions of the value. This means that the value
1705 // is available in some of our (transitive) predecessors. Lets think about
1706 // doing PRE of this load. This will involve inserting a new load into the
1707 // predecessor when it's not available. We could do this in general, but
1708 // prefer to not increase code size. As such, we only do this when we know
1709 // that we only have to insert *one* load (which means we're basically moving
1710 // the load, not inserting a new one).
1711
1712 SmallPtrSet<BasicBlock *, 4> Blockers(llvm::from_range, UnavailableBlocks);
1713
1714 // Let's find the first basic block with more than one predecessor. Walk
1715 // backwards through predecessors if needed.
1716 BasicBlock *LoadBB = Load->getParent();
1717 BasicBlock *TmpBB = LoadBB;
1718
1719 // Check that there is no implicit control flow instructions above our load in
1720 // its block. If there is an instruction that doesn't always pass the
1721 // execution to the following instruction, then moving through it may become
1722 // invalid. For example:
1723 //
1724 // int arr[LEN];
1725 // int index = ???;
1726 // ...
1727 // guard(0 <= index && index < LEN);
1728 // use(arr[index]);
1729 //
1730 // It is illegal to move the array access to any point above the guard,
1731 // because if the index is out of bounds we should deoptimize rather than
1732 // access the array.
1733 // Check that there is no guard in this block above our instruction.
1734 bool MustEnsureSafetyOfSpeculativeExecution =
1735 ICF->isDominatedByICFIFromSameBlock(Load);
1736
1737 while (TmpBB->getSinglePredecessor()) {
1738 TmpBB = TmpBB->getSinglePredecessor();
1739 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1740 return false;
1741 if (Blockers.count(TmpBB))
1742 return false;
1743
1744 // If any of these blocks has more than one successor (i.e. if the edge we
1745 // just traversed was critical), then there are other paths through this
1746 // block along which the load may not be anticipated. Hoisting the load
1747 // above this block would be adding the load to execution paths along
1748 // which it was not previously executed.
1749 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1750 return false;
1751
1752 // Check that there is no implicit control flow in a block above.
1753 MustEnsureSafetyOfSpeculativeExecution =
1754 MustEnsureSafetyOfSpeculativeExecution || ICF->hasICF(TmpBB);
1755 }
1756
1757 assert(TmpBB);
1758 LoadBB = TmpBB;
1759
1760 // Check to see how many predecessors have the loaded value fully
1761 // available.
1762 MapVector<BasicBlock *, Value *> PredLoads;
1763 DenseMap<BasicBlock *, AvailabilityState> FullyAvailableBlocks;
1764 for (const AvailableValueInBlock &AV : ValuesPerBlock)
1765 FullyAvailableBlocks[AV.BB] = AvailabilityState::Available;
1766 for (BasicBlock *UnavailableBB : UnavailableBlocks)
1767 FullyAvailableBlocks[UnavailableBB] = AvailabilityState::Unavailable;
1768
1769 // The edge from Pred to LoadBB is a critical edge will be splitted.
1770 SmallVector<BasicBlock *, 4> CriticalEdgePredSplit;
1771 // The edge from Pred to LoadBB is a critical edge, another successor of Pred
1772 // contains a load can be moved to Pred. This data structure maps the Pred to
1773 // the movable load.
1774 MapVector<BasicBlock *, LoadInst *> CriticalEdgePredAndLoad;
1775 for (BasicBlock *Pred : predecessors(LoadBB)) {
1776 // If any predecessor block is an EH pad that does not allow non-PHI
1777 // instructions before the terminator, we can't PRE the load.
1778 if (Pred->getTerminator()->isEHPad()) {
1779 LLVM_DEBUG(
1780 dbgs() << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD PREDECESSOR '"
1781 << Pred->getName() << "': " << *Load << '\n');
1782 return false;
1783 }
1784
1785 if (isValueFullyAvailableInBlock(Pred, FullyAvailableBlocks)) {
1786 continue;
1787 }
1788
1789 if (Pred->getTerminator()->getNumSuccessors() != 1) {
1790 if (isa<IndirectBrInst>(Pred->getTerminator())) {
1791 LLVM_DEBUG(
1792 dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
1793 << Pred->getName() << "': " << *Load << '\n');
1794 return false;
1795 }
1796
1797 if (LoadBB->isEHPad()) {
1798 LLVM_DEBUG(
1799 dbgs() << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD CRITICAL EDGE '"
1800 << Pred->getName() << "': " << *Load << '\n');
1801 return false;
1802 }
1803
1804 // Do not split backedge as it will break the canonical loop form.
1806 if (DT->dominates(LoadBB, Pred)) {
1807 LLVM_DEBUG(
1808 dbgs()
1809 << "COULD NOT PRE LOAD BECAUSE OF A BACKEDGE CRITICAL EDGE '"
1810 << Pred->getName() << "': " << *Load << '\n');
1811 return false;
1812 }
1813
1814 if (LoadInst *LI = findLoadToHoistIntoPred(Pred, LoadBB, Load))
1815 CriticalEdgePredAndLoad[Pred] = LI;
1816 else
1817 CriticalEdgePredSplit.push_back(Pred);
1818 } else {
1819 // Only add the predecessors that will not be split for now.
1820 PredLoads[Pred] = nullptr;
1821 }
1822 }
1823
1824 // Decide whether PRE is profitable for this load.
1825 unsigned NumInsertPreds = PredLoads.size() + CriticalEdgePredSplit.size();
1826 unsigned NumUnavailablePreds = NumInsertPreds +
1827 CriticalEdgePredAndLoad.size();
1828 assert(NumUnavailablePreds != 0 &&
1829 "Fully available value should already be eliminated!");
1830 (void)NumUnavailablePreds;
1831
1832 // If we need to insert new load in multiple predecessors, reject it.
1833 // FIXME: If we could restructure the CFG, we could make a common pred with
1834 // all the preds that don't have an available Load and insert a new load into
1835 // that one block.
1836 if (NumInsertPreds > 1)
1837 return false;
1838
1839 // Now we know where we will insert load. We must ensure that it is safe
1840 // to speculatively execute the load at that points.
1841 if (MustEnsureSafetyOfSpeculativeExecution) {
1842 if (CriticalEdgePredSplit.size())
1844 DT))
1845 return false;
1846 for (auto &PL : PredLoads)
1847 if (!isSafeToSpeculativelyExecute(Load, PL.first->getTerminator(), AC,
1848 DT))
1849 return false;
1850 for (auto &CEP : CriticalEdgePredAndLoad)
1851 if (!isSafeToSpeculativelyExecute(Load, CEP.first->getTerminator(), AC,
1852 DT))
1853 return false;
1854 }
1855
1856 // Split critical edges, and update the unavailable predecessors accordingly.
1857 for (BasicBlock *OrigPred : CriticalEdgePredSplit) {
1858 BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
1859 assert(!PredLoads.count(OrigPred) && "Split edges shouldn't be in map!");
1860 PredLoads[NewPred] = nullptr;
1861 LLVM_DEBUG(dbgs() << "Split critical edge " << OrigPred->getName() << "->"
1862 << LoadBB->getName() << '\n');
1863 }
1864
1865 for (auto &CEP : CriticalEdgePredAndLoad)
1866 PredLoads[CEP.first] = nullptr;
1867
1868 // Check if the load can safely be moved to all the unavailable predecessors.
1869 bool CanDoPRE = true;
1870 const DataLayout &DL = Load->getDataLayout();
1871 SmallVector<Instruction*, 8> NewInsts;
1872 for (auto &PredLoad : PredLoads) {
1873 BasicBlock *UnavailablePred = PredLoad.first;
1874
1875 // Do PHI translation to get its value in the predecessor if necessary. The
1876 // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
1877 // We do the translation for each edge we skipped by going from Load's block
1878 // to LoadBB, otherwise we might miss pieces needing translation.
1879
1880 // If all preds have a single successor, then we know it is safe to insert
1881 // the load on the pred (?!?), so we can insert code to materialize the
1882 // pointer if it is not available.
1883 Value *LoadPtr = Load->getPointerOperand();
1884 BasicBlock *Cur = Load->getParent();
1885 while (Cur != LoadBB) {
1886 PHITransAddr Address(LoadPtr, DL, AC);
1887 LoadPtr = Address.translateWithInsertion(Cur, Cur->getSinglePredecessor(),
1888 *DT, NewInsts);
1889 if (!LoadPtr) {
1890 CanDoPRE = false;
1891 break;
1892 }
1893 Cur = Cur->getSinglePredecessor();
1894 }
1895
1896 if (LoadPtr) {
1897 PHITransAddr Address(LoadPtr, DL, AC);
1898 LoadPtr = Address.translateWithInsertion(LoadBB, UnavailablePred, *DT,
1899 NewInsts);
1900 }
1901 // If we couldn't find or insert a computation of this phi translated value,
1902 // we fail PRE.
1903 if (!LoadPtr) {
1904 LLVM_DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
1905 << *Load->getPointerOperand() << "\n");
1906 CanDoPRE = false;
1907 break;
1908 }
1909
1910 PredLoad.second = LoadPtr;
1911 }
1912
1913 if (!CanDoPRE) {
1914 while (!NewInsts.empty()) {
1915 // Erase instructions generated by the failed PHI translation before
1916 // trying to number them. PHI translation might insert instructions
1917 // in basic blocks other than the current one, and we delete them
1918 // directly, as salvageAndRemoveInstruction only allows removing from the
1919 // current basic block.
1920 NewInsts.pop_back_val()->eraseFromParent();
1921 }
1922 // HINT: Don't revert the edge-splitting as following transformation may
1923 // also need to split these critical edges.
1924 return !CriticalEdgePredSplit.empty();
1925 }
1926
1927 // Okay, we can eliminate this load by inserting a reload in the predecessor
1928 // and using PHI construction to get the value in the other predecessors, do
1929 // it.
1930 LLVM_DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *Load << '\n');
1931 LLVM_DEBUG(if (!NewInsts.empty()) dbgs() << "INSERTED " << NewInsts.size()
1932 << " INSTS: " << *NewInsts.back()
1933 << '\n');
1934
1935 // Assign value numbers to the new instructions.
1936 for (Instruction *I : NewInsts) {
1937 // Instructions that have been inserted in predecessor(s) to materialize
1938 // the load address do not retain their original debug locations. Doing
1939 // so could lead to confusing (but correct) source attributions.
1940 I->updateLocationAfterHoist();
1941
1942 // FIXME: We really _ought_ to insert these value numbers into their
1943 // parent's availability map. However, in doing so, we risk getting into
1944 // ordering issues. If a block hasn't been processed yet, we would be
1945 // marking a value as AVAIL-IN, which isn't what we intend.
1946 VN.lookupOrAdd(I);
1947 }
1948
1949 eliminatePartiallyRedundantLoad(Load, ValuesPerBlock, PredLoads,
1950 &CriticalEdgePredAndLoad);
1951 ++NumPRELoad;
1952 return true;
1953}
1954
1955bool GVNPass::performLoopLoadPRE(LoadInst *Load,
1956 AvailValInBlkVect &ValuesPerBlock,
1957 UnavailBlkVect &UnavailableBlocks) {
1958 const Loop *L = LI->getLoopFor(Load->getParent());
1959 // TODO: Generalize to other loop blocks that dominate the latch.
1960 if (!L || L->getHeader() != Load->getParent())
1961 return false;
1962
1963 BasicBlock *Preheader = L->getLoopPreheader();
1964 BasicBlock *Latch = L->getLoopLatch();
1965 if (!Preheader || !Latch)
1966 return false;
1967
1968 Value *LoadPtr = Load->getPointerOperand();
1969 // Must be available in preheader.
1970 if (!L->isLoopInvariant(LoadPtr))
1971 return false;
1972
1973 // We plan to hoist the load to preheader without introducing a new fault.
1974 // In order to do it, we need to prove that we cannot side-exit the loop
1975 // once loop header is first entered before execution of the load.
1976 if (ICF->isDominatedByICFIFromSameBlock(Load))
1977 return false;
1978
1979 BasicBlock *LoopBlock = nullptr;
1980 for (auto *Blocker : UnavailableBlocks) {
1981 // Blockers from outside the loop are handled in preheader.
1982 if (!L->contains(Blocker))
1983 continue;
1984
1985 // Only allow one loop block. Loop header is not less frequently executed
1986 // than each loop block, and likely it is much more frequently executed. But
1987 // in case of multiple loop blocks, we need extra information (such as block
1988 // frequency info) to understand whether it is profitable to PRE into
1989 // multiple loop blocks.
1990 if (LoopBlock)
1991 return false;
1992
1993 // Do not sink into inner loops. This may be non-profitable.
1994 if (L != LI->getLoopFor(Blocker))
1995 return false;
1996
1997 // Blocks that dominate the latch execute on every single iteration, maybe
1998 // except the last one. So PREing into these blocks doesn't make much sense
1999 // in most cases. But the blocks that do not necessarily execute on each
2000 // iteration are sometimes much colder than the header, and this is when
2001 // PRE is potentially profitable.
2002 if (DT->dominates(Blocker, Latch))
2003 return false;
2004
2005 // Make sure that the terminator itself doesn't clobber.
2006 if (Blocker->getTerminator()->mayWriteToMemory())
2007 return false;
2008
2009 LoopBlock = Blocker;
2010 }
2011
2012 if (!LoopBlock)
2013 return false;
2014
2015 // Make sure the memory at this pointer cannot be freed, therefore we can
2016 // safely reload from it after clobber.
2017 if (LoadPtr->canBeFreed())
2018 return false;
2019
2020 // TODO: Support critical edge splitting if blocker has more than 1 successor.
2021 MapVector<BasicBlock *, Value *> AvailableLoads;
2022 AvailableLoads[LoopBlock] = LoadPtr;
2023 AvailableLoads[Preheader] = LoadPtr;
2024
2025 LLVM_DEBUG(dbgs() << "GVN REMOVING PRE LOOP LOAD: " << *Load << '\n');
2026 eliminatePartiallyRedundantLoad(Load, ValuesPerBlock, AvailableLoads,
2027 /*CriticalEdgePredAndLoad*/ nullptr);
2028 ++NumPRELoopLoad;
2029 return true;
2030}
2031
2034 using namespace ore;
2035
2036 ORE->emit([&]() {
2037 return OptimizationRemark(DEBUG_TYPE, "LoadElim", Load)
2038 << "load of type " << NV("Type", Load->getType()) << " eliminated"
2039 << setExtraArgs() << " in favor of "
2040 << NV("InfavorOfValue", AvailableValue);
2041 });
2042}
2043
2044/// Attempt to eliminate a load whose dependencies are
2045/// non-local by performing PHI construction.
2046bool GVNPass::processNonLocalLoad(LoadInst *Load) {
2047 // Non-local speculations are not allowed under asan.
2048 if (Load->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
2049 Load->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
2050 return false;
2051
2052 // Find the non-local dependencies of the load.
2053 LoadDepVect Deps;
2054 MD->getNonLocalPointerDependency(Load, Deps);
2055
2056 // If we had to process more than one hundred blocks to find the
2057 // dependencies, this load isn't worth worrying about. Optimizing
2058 // it will be too expensive.
2059 unsigned NumDeps = Deps.size();
2060 if (NumDeps > MaxNumDeps)
2061 return false;
2062
2064 MemVals.reserve(Deps.size());
2065
2066 for (const NonLocalDepResult &Dep : Deps) {
2067 const auto &R = Dep.getResult();
2068 SelectAddr SelAddr = Dep.getAddress();
2069 BasicBlock *BB = Dep.getBB();
2070 Instruction *Inst = R.getInst();
2071 if (R.isSelect()) {
2072 auto [Cond, Addrs] = SelAddr.getSelectCondAndAddrs();
2073 MemVals.emplace_back(
2074 ReachingMemVal::getSelect(BB, Cond, Addrs.first, Addrs.second));
2075 continue;
2076 }
2077 Value *Address = SelAddr.getAddr();
2078 if (R.isClobber())
2079 MemVals.emplace_back(ReachingMemVal::getClobber(Address, Inst));
2080 else if (R.isDef())
2081 MemVals.emplace_back(ReachingMemVal::getDef(Address, Inst));
2082 else
2083 MemVals.emplace_back(ReachingMemVal::getUnknown(BB, Address, Inst));
2084 }
2085
2086 return processNonLocalLoad(Load, MemVals);
2087}
2088
2089bool GVNPass::processNonLocalLoad(LoadInst *Load,
2090 SmallVectorImpl<ReachingMemVal> &Deps) {
2091 // If we had a phi translation failure, we'll have a single entry which is a
2092 // clobber in the current block. Reject this early.
2093 if (Deps.size() == 1 && Deps[0].Kind == DepKind::Other) {
2094 LLVM_DEBUG(dbgs() << "GVN: non-local load "; Load->printAsOperand(dbgs());
2095 dbgs() << " has unknown dependencies\n";);
2096 return false;
2097 }
2098
2099 bool Changed = false;
2100 // This is a limited form of scalar PRE for load indices. If this load follows
2101 // a GEP, see if we can PRE the indices before analyzing.
2102 if (isScalarPREEnabled()) {
2103 if (GetElementPtrInst *GEP =
2104 dyn_cast<GetElementPtrInst>(Load->getOperand(0))) {
2105 for (Use &U : GEP->indices())
2106 if (Instruction *I = dyn_cast<Instruction>(U.get()))
2107 Changed |= performScalarPRE(I);
2108 }
2109 }
2110
2111 // Step 1: Analyze the availability of the load.
2112 AvailValInBlkVect ValuesPerBlock;
2113 UnavailBlkVect UnavailableBlocks;
2114 analyzeLoadAvailability(Load, Deps, ValuesPerBlock, UnavailableBlocks);
2115
2116 // If we have no predecessors that produce a known value for this load, exit
2117 // early.
2118 if (ValuesPerBlock.empty())
2119 return Changed;
2120
2121 // Step 2: Eliminate fully redundancy.
2122 //
2123 // If all of the instructions we depend on produce a known value for this
2124 // load, then it is fully redundant and we can use PHI insertion to compute
2125 // its value. Insert PHIs and remove the fully redundant value now.
2126 if (UnavailableBlocks.empty()) {
2127 LLVM_DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *Load << '\n');
2128
2129 // Perform PHI construction.
2130 Value *V = constructSSAForLoadSet(Load, ValuesPerBlock, *this);
2131 // constructSSAForLoadSet is responsible for combining metadata.
2132 ICF->removeUsersOf(Load);
2133 Load->replaceAllUsesWith(V);
2134
2135 if (isa<PHINode>(V))
2136 V->takeName(Load);
2137 if (Instruction *I = dyn_cast<Instruction>(V))
2138 // If instruction I has debug info, then we should not update it.
2139 // Also, if I has a null DebugLoc, then it is still potentially incorrect
2140 // to propagate Load's DebugLoc because Load may not post-dominate I.
2141 if (Load->getDebugLoc() && Load->getParent() == I->getParent())
2142 I->setDebugLoc(Load->getDebugLoc());
2143 if (MD && V->getType()->isPtrOrPtrVectorTy())
2144 MD->invalidateCachedPointerInfo(V);
2145 ++NumGVNLoad;
2146 reportLoadElim(Load, V, ORE);
2148 return true;
2149 }
2150
2151 // Step 3: Eliminate partial redundancy.
2152 if (!isLoadPREEnabled())
2153 return Changed;
2154 if (!isLoadInLoopPREEnabled() && LI->getLoopFor(Load->getParent()))
2155 return Changed;
2156
2157 if (performLoopLoadPRE(Load, ValuesPerBlock, UnavailableBlocks) ||
2158 performLoadPRE(Load, ValuesPerBlock, UnavailableBlocks))
2159 return true;
2160
2161 return Changed;
2162}
2163
2164bool GVNPass::processAssumeIntrinsic(AssumeInst *IntrinsicI) {
2165 Value *V = IntrinsicI->getArgOperand(0);
2166
2167 if (ConstantInt *Cond = dyn_cast<ConstantInt>(V)) {
2168 if (Cond->isZero()) {
2169 Type *Int8Ty = Type::getInt8Ty(V->getContext());
2170 Type *PtrTy = PointerType::get(V->getContext(), 0);
2171 // Insert a new store to null instruction before the load to indicate that
2172 // this code is not reachable. FIXME: We could insert unreachable
2173 // instruction directly because we can modify the CFG.
2174 auto *NewS =
2175 new StoreInst(PoisonValue::get(Int8Ty), Constant::getNullValue(PtrTy),
2176 IntrinsicI->getIterator());
2177 if (MSSAU) {
2178 const MemoryUseOrDef *FirstNonDom = nullptr;
2179 const auto *AL =
2180 MSSAU->getMemorySSA()->getBlockAccesses(IntrinsicI->getParent());
2181
2182 // If there are accesses in the current basic block, find the first one
2183 // that does not come before NewS. The new memory access is inserted
2184 // after the found access or before the terminator if no such access is
2185 // found.
2186 if (AL) {
2187 for (const auto &Acc : *AL) {
2188 if (auto *Current = dyn_cast<MemoryUseOrDef>(&Acc))
2189 if (!Current->getMemoryInst()->comesBefore(NewS)) {
2190 FirstNonDom = Current;
2191 break;
2192 }
2193 }
2194 }
2195
2196 auto *NewDef =
2197 FirstNonDom ? MSSAU->createMemoryAccessBefore(
2198 NewS, nullptr,
2199 const_cast<MemoryUseOrDef *>(FirstNonDom))
2200 : MSSAU->createMemoryAccessInBB(
2201 NewS, nullptr,
2202 NewS->getParent(), MemorySSA::BeforeTerminator);
2203
2204 MSSAU->insertDef(cast<MemoryDef>(NewDef), /*RenameUses=*/false);
2205 }
2206 }
2207 if (isAssumeWithEmptyBundle(*IntrinsicI)) {
2208 salvageAndRemoveInstruction(IntrinsicI);
2209 return true;
2210 }
2211 return false;
2212 }
2213
2214 if (isa<Constant>(V)) {
2215 // If it's not false, and constant, it must evaluate to true. This means our
2216 // assume is assume(true), and thus, pointless, and we don't want to do
2217 // anything more here.
2218 return false;
2219 }
2220
2221 Constant *True = ConstantInt::getTrue(V->getContext());
2222 return propagateEquality(V, True, IntrinsicI);
2223}
2224
2227 I->replaceAllUsesWith(Repl);
2228}
2229
2230/// If a load has !invariant.group, try to find the most-dominating instruction
2231/// with the same metadata and equivalent pointer (modulo bitcasts and zero
2232/// GEPs). If one is found that dominates the load, its value can be reused.
2234 Value *PointerOperand = L->getPointerOperand()->stripPointerCasts();
2235
2236 // It's not safe to walk the use list of a global value because function
2237 // passes aren't allowed to look outside their functions.
2238 // FIXME: this could be fixed by filtering instructions from outside of
2239 // current function.
2240 if (isa<Constant>(PointerOperand))
2241 return nullptr;
2242
2243 // Queue to process all pointers that are equivalent to load operand.
2244 SmallVector<Value *, 8> PointerUsesQueue;
2245 PointerUsesQueue.push_back(PointerOperand);
2246
2247 Instruction *MostDominatingInstruction = L;
2248
2249 // FIXME: This loop is potentially O(n^2) due to repeated dominates checks.
2250 while (!PointerUsesQueue.empty()) {
2251 Value *Ptr = PointerUsesQueue.pop_back_val();
2252 assert(Ptr && !isa<GlobalValue>(Ptr) &&
2253 "Null or GlobalValue should not be inserted");
2254
2255 for (User *U : Ptr->users()) {
2256 auto *I = dyn_cast<Instruction>(U);
2257 if (!I || I == L || !DT.dominates(I, MostDominatingInstruction))
2258 continue;
2259
2260 // Add bitcasts and zero GEPs to queue.
2261 // TODO: Should drop bitcast?
2262 if (isa<BitCastInst>(I) ||
2264 cast<GetElementPtrInst>(I)->hasAllZeroIndices())) {
2265 PointerUsesQueue.push_back(I);
2266 continue;
2267 }
2268
2269 // If we hit a load/store with an invariant.group metadata and the same
2270 // pointer operand, we can assume that value pointed to by the pointer
2271 // operand didn't change.
2272 if (I->hasMetadata(LLVMContext::MD_invariant_group) &&
2273 Ptr == getLoadStorePointerOperand(I) && !I->isVolatile())
2274 MostDominatingInstruction = I;
2275 }
2276 }
2277
2278 return MostDominatingInstruction != L ? MostDominatingInstruction : nullptr;
2279}
2280
2281/// Return the memory location accessed by the (masked) load/store instruction
2282/// `I`, if the instruction could potentially provide a useful value for
2283/// eliminating the load.
2284static std::optional<MemoryLocation>
2286 const TargetLibraryInfo *TLI) {
2287 if (auto *LI = dyn_cast<LoadInst>(I))
2288 return MemoryLocation::get(LI);
2289
2290 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2291 switch (II->getIntrinsicID()) {
2292 case Intrinsic::masked_load:
2293 return MemoryLocation::getForArgument(II, 0, TLI);
2294 case Intrinsic::masked_store:
2295 if (AllowStores)
2296 return MemoryLocation::getForArgument(II, 1, TLI);
2297 return std::nullopt;
2298 default:
2299 break;
2300 }
2301 }
2302
2303 if (!AllowStores)
2304 return std::nullopt;
2305
2306 if (auto *SI = dyn_cast<StoreInst>(I))
2307 return MemoryLocation::get(SI);
2308 return std::nullopt;
2309}
2310
2311/// Scan the users of each MemoryAccess in `ClobbersList` that belong to `BB`,
2312/// looking for memory reads whose location aliases `Loc` and dominates our
2313/// load.
2314std::optional<GVNPass::ReachingMemVal> GVNPass::scanMemoryAccessesUsers(
2315 const MemoryLocation &Loc, bool IsInvariantLoad, BasicBlock *BB,
2316 const SmallVectorImpl<MemoryAccess *> &ClobbersList, MemorySSA &MSSA,
2317 BatchAAResults &AA, LoadInst *L) {
2318
2319 // Prefer a candidate that is closer to the load within the same block.
2320 auto UpdateChoice = [&](std::optional<ReachingMemVal> &Choice,
2321 AliasResult &AR, Instruction *Candidate) {
2322 if (!Choice) {
2323 if (AR == AliasResult::PartialAlias)
2324 Choice = ReachingMemVal::getClobber(Loc.Ptr, Candidate, AR.getOffset());
2325 else
2326 Choice = ReachingMemVal::getDef(Loc.Ptr, Candidate);
2327 return;
2328 }
2329 if (!MSSA.locallyDominates(MSSA.getMemoryAccess(Choice->Inst),
2330 MSSA.getMemoryAccess(Candidate)))
2331 return;
2332
2333 if (AR == AliasResult::PartialAlias) {
2334 Choice->Kind = DepKind::Clobber;
2335 Choice->Offset = AR.getOffset();
2336 } else {
2337 Choice->Kind = DepKind::Def;
2338 Choice->Offset = -1;
2339 }
2340
2341 Choice->Inst = Candidate;
2342 Choice->Block = Candidate->getParent();
2343 };
2344
2345 std::optional<ReachingMemVal> ReachingVal;
2346 for (MemoryAccess *MA : ClobbersList) {
2347 unsigned Scanned = 0;
2348 for (User *U : MA->users()) {
2349 if (++Scanned >= ScanUsersLimit)
2350 return ReachingMemVal::getUnknown(BB, Loc.Ptr);
2351
2352 auto *UseOrDef = dyn_cast<MemoryUseOrDef>(U);
2353 if (!UseOrDef || UseOrDef->getBlock() != BB)
2354 continue;
2355
2356 Instruction *MemI = UseOrDef->getMemoryInst();
2357 if (MemI == L ||
2358 (L && !MSSA.locallyDominates(UseOrDef, MSSA.getMemoryAccess(L))))
2359 continue;
2360
2361 if (auto MaybeLoc = maybeLoadStoreLocation(MemI, IsInvariantLoad, TLI)) {
2362 AliasResult AR = AA.alias(*MaybeLoc, Loc);
2363 // If the locations do not certainly alias, we cannot possibly infer the
2364 // following load loads the same value.
2366 continue;
2367
2368 // Locations partially overlap, but neither is a subset of the other, or
2369 // the second location is before the first.
2370 if (AR == AliasResult::PartialAlias &&
2371 (!AR.hasOffset() || AR.getOffset() < 0))
2372 continue;
2373
2374 // Found candidate, the new load memory location and the given location
2375 // must alias: precise overlap, or subset with non-negative offset.
2376 UpdateChoice(ReachingVal, AR, MemI);
2377 }
2378 }
2379 if (ReachingVal)
2380 break;
2381 }
2382
2383 return ReachingVal;
2384}
2385
2386/// Check if a given MemoryAccess (usually a MemoryDef) actually modifies a
2387/// given location. Returns a ReachingMemVal describing the dependency.
2388std::optional<GVNPass::ReachingMemVal> GVNPass::accessMayModifyLocation(
2389 MemoryAccess *ClobberMA, const MemoryLocation &Loc, bool IsInvariantLoad,
2390 BasicBlock *BB, MemorySSA &MSSA, BatchAAResults &AA) {
2391 assert(ClobberMA->getBlock() == BB);
2392
2393 // If the clobbering access is the entry memory state, we cannot say anything
2394 // about the content of the memory, except when we are accessing a local
2395 // object, which can be turned later into producing `undef`.
2396 if (MSSA.isLiveOnEntryDef(ClobberMA)) {
2398 if (Alloc->getParent() == BB)
2399 return ReachingMemVal::getDef(Loc.Ptr, const_cast<AllocaInst *>(Alloc));
2400 return ReachingMemVal::getUnknown(BB, Loc.Ptr);
2401 }
2402
2403 // Loads from "constant" memory can't be clobbered.
2404 if (IsInvariantLoad || AA.pointsToConstantMemory(Loc))
2405 return std::nullopt;
2406
2407 auto GetOrdering = [](const Instruction *I) {
2408 if (auto *L = dyn_cast<LoadInst>(I))
2409 return L->getOrdering();
2410 return cast<StoreInst>(I)->getOrdering();
2411 };
2412 Instruction *ClobberI = cast<MemoryDef>(ClobberMA)->getMemoryInst();
2413
2414 // Check if the clobbering access is a load or a store that we can reuse.
2415 if (auto MaybeLoc = maybeLoadStoreLocation(ClobberI, true, TLI)) {
2416 AliasResult AR = AA.alias(*MaybeLoc, Loc);
2417 if (AR == AliasResult::MustAlias)
2418 return ReachingMemVal::getDef(Loc.Ptr, ClobberI);
2419
2420 if (AR == AliasResult::NoAlias) {
2421 // If the locations do not alias we may still be able to skip over the
2422 // clobbering instruction, even if it is atomic.
2423 // The original load is either non-atomic or unordered. We can reorder
2424 // these across non-atomic, unordered or monotonic loads or across any
2425 // store.
2426 if (!ClobberI->isAtomic() ||
2427 !isStrongerThan(GetOrdering(ClobberI), AtomicOrdering::Monotonic) ||
2428 isa<StoreInst>(ClobberI))
2429 return std::nullopt;
2430 return ReachingMemVal::getClobber(Loc.Ptr, ClobberI);
2431 }
2432
2433 // Skip over volatile loads (the original load is non-volatile, non-atomic).
2434 if (!ClobberI->isAtomic() && isa<LoadInst>(ClobberI))
2435 return std::nullopt;
2436
2437 if (AR == AliasResult::MayAlias ||
2439 (!AR.hasOffset() || AR.getOffset() < 0)))
2440 return ReachingMemVal::getClobber(Loc.Ptr, ClobberI);
2441
2442 // The only option left is a store of the superset of the required bits.
2444 AR.getOffset() > 0 &&
2445 "Must be the superset/partial overlap case with positive offset");
2446 return ReachingMemVal::getClobber(Loc.Ptr, ClobberI, AR.getOffset());
2447 }
2448
2449 if (auto *II = dyn_cast<IntrinsicInst>(ClobberI)) {
2451 return std::nullopt;
2452 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
2453 MemoryLocation IIObjLoc = MemoryLocation::getForArgument(II, 0, TLI);
2454 if (AA.isMustAlias(IIObjLoc, Loc))
2455 return ReachingMemVal::getDef(Loc.Ptr, ClobberI);
2456 return std::nullopt;
2457 }
2458 }
2459
2460 // If we are at a malloc-like function call, we can turn the load into `undef`
2461 // or zero.
2462 if (isNoAliasCall(ClobberI)) {
2463 const Value *Obj = getUnderlyingObject(Loc.Ptr);
2464 if (Obj == ClobberI || AA.isMustAlias(ClobberI, Loc.Ptr))
2465 return ReachingMemVal::getDef(Loc.Ptr, ClobberI);
2466 }
2467
2468 // Can reorder loads across a release fence.
2469 if (auto *FI = dyn_cast<FenceInst>(ClobberI))
2470 if (FI->getOrdering() == AtomicOrdering::Release)
2471 return std::nullopt;
2472
2473 // See if the clobber instruction (e.g., a generic call) may modify the
2474 // location.
2475 ModRefInfo MR = AA.getModRefInfo(ClobberI, Loc);
2476 // If may modify the location, analyze deeper, to exclude accesses to
2477 // non-escaping local allocations.
2478 if (MR == ModRefInfo::NoModRef || MR == ModRefInfo::Ref)
2479 return std::nullopt;
2480
2481 // Conservatively assume the clobbering memory access may overwrite the
2482 // location.
2483 return ReachingMemVal::getClobber(Loc.Ptr, ClobberI);
2484}
2485
2486/// Collect the predecessors of block, while doing phi-translation of the memory
2487/// address and the memory clobber. Return false if the block should be marked
2488/// as clobbering the memory location in an unknown way.
2489bool GVNPass::collectPredecessors(BasicBlock *BB, const PHITransAddr &Addr,
2490 MemoryAccess *ClobberMA,
2491 DependencyBlockSet &Blocks,
2492 SmallVectorImpl<BasicBlock *> &Worklist) {
2493 if (Addr.needsPHITranslationFromBlock(BB) &&
2495 return false;
2496
2497 auto *MPhi =
2498 ClobberMA->getBlock() == BB ? dyn_cast<MemoryPhi>(ClobberMA) : nullptr;
2500 for (BasicBlock *Pred : predecessors(BB)) {
2501 // Skip unreachable predecessors.
2502 if (!DT->isReachableFromEntry(Pred))
2503 continue;
2504
2505 // Skip already visited predecessors.
2506 if (llvm::any_of(Preds, [Pred](const auto &P) { return P.first == Pred; }))
2507 continue;
2508
2509 PHITransAddr TransAddr = Addr;
2510 if (TransAddr.needsPHITranslationFromBlock(BB))
2511 TransAddr.translateValue(BB, Pred, DT, false);
2512
2513 auto It = Blocks.find(Pred);
2514 if (It != Blocks.end()) {
2515 // If we reach a visited block with a different address, set the
2516 // current block as clobbering the memory location in an unknown way
2517 // (by returning false).
2518 if (It->second.Addr.getAddr() != TransAddr.getAddr())
2519 return false;
2520 // Otherwise, just stop the traversal.
2521 continue;
2522 }
2523
2524 Preds.emplace_back(
2525 Pred, DependencyBlockInfo(TransAddr,
2526 MPhi ? MPhi->getIncomingValueForBlock(Pred)
2527 : ClobberMA));
2528 }
2529
2530 // We collected the predecessors and stored them in Preds. Now, populate the
2531 // worklist with the predecessors found, and cache the eventual translated
2532 // address for each block.
2533 for (auto &P : Preds) {
2534 [[maybe_unused]] auto It =
2535 Blocks.try_emplace(P.first, std::move(P.second)).first;
2536 Worklist.push_back(P.first);
2537 }
2538
2539 return true;
2540}
2541
2542/// Build a list of MemoryAccesses whose users could potentially alias the
2543/// memory location being queried. Starts from StartInfo's initial clobber,
2544/// walk the use-def chain to the final clobber. If the chain extends beyond
2545/// `BB`, continue into that block but only if it is in the previously collected
2546/// set.
2547void GVNPass::collectClobberList(SmallVectorImpl<MemoryAccess *> &Clobbers,
2548 BasicBlock *BB,
2549 const DependencyBlockInfo &StartInfo,
2550 const DependencyBlockSet &Blocks,
2551 MemorySSA &MSSA) {
2552 MemoryAccess *MA = StartInfo.InitialClobberMA;
2553 MemoryAccess *LastMA = StartInfo.ClobberMA;
2554
2555 for (;;) {
2556 while (MA != LastMA) {
2557 Clobbers.push_back(MA);
2558 MA = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
2559 }
2560 Clobbers.push_back(MA);
2561
2562 if (MSSA.isLiveOnEntryDef(MA) ||
2563 (MA->getBlock() == BB && !isa<MemoryPhi>(MA)))
2564 break;
2565
2566 // If the final clobber in the current block is a MemoryPhi, go to the
2567 // immediate dominator; otherwise, just get to the block containing the
2568 // final clobber.
2569 if (MA->getBlock() == BB)
2570 BB = DT->getNode(BB)->getIDom()->getBlock();
2571 else
2572 BB = MA->getBlock();
2573
2574 auto It = Blocks.find(BB);
2575 if (It == Blocks.end())
2576 break;
2577
2578 MA = It->second.InitialClobberMA;
2579 LastMA = It->second.ClobberMA;
2580 if (MA == Clobbers.back())
2581 Clobbers.pop_back();
2582 }
2583}
2584
2585/// Entrypoint for the MemorySSA-based redundant load elimination algorithm.
2586/// Given as input a load instruction, the function computes the set of reaching
2587/// memory values, one per predecessor path, that analyzeLoadAvailability can
2588/// later use to establish whether the load may be eliminated. A reaching value
2589/// may be of the following descriptor kind:
2590/// * Def: a precise instruction that produces the exact bits the load would
2591/// read (e.g., an equivalent load or a MustAlias store);
2592/// * Clobber: a write that clobbers a superset of the bits the load would read
2593/// (e.g., a memset over a larger region);
2594/// * Other: we know which block defines the memory location in some way, but
2595/// could not identify a precise instruction (e.g., memory already live at
2596/// function entry).
2597bool GVNPass::findReachingValuesForLoad(LoadInst *L,
2598 SmallVectorImpl<ReachingMemVal> &Values,
2599 MemorySSA &MSSA, AAResults &AAR) {
2600 EarliestEscapeAnalysis EA(*DT, LI);
2601 BatchAAResults AA(AAR, &EA);
2602 BasicBlock *StartBlock = L->getParent();
2603 bool IsInvariantLoad = L->hasMetadata(LLVMContext::MD_invariant_load);
2604 // TODO: Simplify later work by just getClobberingMemoryAccess().
2605 MemoryAccess *ClobberMA = MSSA.getMemoryAccess(L)->getDefiningAccess();
2606 const MemoryLocation Loc = MemoryLocation::get(L);
2607
2608 // Fast path for load tagged with !invariant.group.
2609 if (L->hasMetadata(LLVMContext::MD_invariant_group)) {
2610 if (Instruction *G = findInvariantGroupValue(L, *DT)) {
2611 Values.emplace_back(
2612 ReachingMemVal::getDef(getLoadStorePointerOperand(G), G));
2613 return true;
2614 }
2615 }
2616
2617 // Phase 1. First off, look for a local dependency to avoid having to
2618 // disambiguate between before the load and after the load of the starting
2619 // block (as the load may be visited from a backedge).
2620 do {
2621 // Scan users of the clobbering memory access.
2622 if (auto RMV = scanMemoryAccessesUsers(
2623 Loc, IsInvariantLoad, StartBlock,
2624 SmallVector<MemoryAccess *, 1>{ClobberMA}, MSSA, AA, L)) {
2625 Values.emplace_back(*RMV);
2626 return true;
2627 }
2628
2629 // Exit from here, and proceed visiting predecessors if the clobbering
2630 // access is non-local or is a MemoryPhi.
2631 if (ClobberMA->getBlock() != StartBlock || isa<MemoryPhi>(ClobberMA))
2632 break;
2633
2634 // Check if the clobber actually aliases the load location.
2635 if (auto RMV = accessMayModifyLocation(ClobberMA, Loc, IsInvariantLoad,
2636 StartBlock, MSSA, AA)) {
2637 Values.emplace_back(*RMV);
2638 return true;
2639 }
2640
2641 // It may happen that the clobbering memory access does not actually
2642 // clobber our load location, transition to its defining memory access.
2643 ClobberMA = cast<MemoryUseOrDef>(ClobberMA)->getDefiningAccess();
2644 } while (ClobberMA->getBlock() == StartBlock);
2645
2646 // Non-local speculations are not allowed under ASan.
2647 if (L->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
2648 L->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
2649 return false;
2650
2651 // Phase 2. Walk backwards through the CFG, collecting all the blocks that
2652 // contain an instruction that modifies the load memory location, or that lie
2653 // on a path between a clobbering block and our load. Start off by collecting
2654 // the predecessors of `StartBlock`. All the visited blocks are stored in a
2655 // the set `Blocks`. If possible, the memory address maintained for the block
2656 // visited does get phi-translated.
2657 DependencyBlockSet Blocks;
2658 SmallVector<BasicBlock *, 16> InitialWorklist;
2659 const DataLayout &DL = L->getModule()->getDataLayout();
2660 if (!collectPredecessors(StartBlock,
2661 PHITransAddr(L->getPointerOperand(), DL, AC),
2662 ClobberMA, Blocks, InitialWorklist))
2663 return false;
2664
2665 // Do a bottom-up DFS.
2666 auto Worklist = InitialWorklist;
2667 while (!Worklist.empty()) {
2668 auto *BB = Worklist.pop_back_val();
2669 DependencyBlockInfo &Info = Blocks.find(BB)->second;
2670
2671 // Phi-translation may have failed.
2672 if (!Info.Addr.getAddr())
2673 continue;
2674
2675 // If the clobbering memory access is in the current block and it indeed
2676 // clobbers our load location, record the dependency and do not visit the
2677 // predecessors of this block further, continue with the blocks in the
2678 // worklist.
2679 if (Info.ClobberMA->getBlock() == BB && !isa<MemoryPhi>(Info.ClobberMA)) {
2680 if (auto RMV = accessMayModifyLocation(
2681 Info.ClobberMA, Loc.getWithNewPtr(Info.Addr.getAddr()),
2682 IsInvariantLoad, BB, MSSA, AA)) {
2683 Info.MemVal = RMV;
2684 continue;
2685 }
2686 assert(!MSSA.isLiveOnEntryDef(Info.ClobberMA) &&
2687 "LiveOnEntry aliases everything");
2688
2689 // If, however, the clobbering memory access does not actually clobber
2690 // our load location, transition to its defining memory access, but
2691 // keep examining the same basic block.
2692 Info.ClobberMA =
2693 cast<MemoryUseOrDef>(Info.ClobberMA)->getDefiningAccess();
2694 Worklist.emplace_back(BB);
2695 continue;
2696 }
2697
2698 // At this point we know the current block is "transparent", i.e. the memory
2699 // location is not modified when execution goes through this block.
2700 // Continue to its predecessors, unless a predecessor has already been
2701 // visited with a different address. We currently cannot represent such a
2702 // dependency.
2703 if (BB == StartBlock && Info.Addr.getAddr() != L->getPointerOperand()) {
2704 Info.ForceUnknown = true;
2705 continue;
2706 }
2707 if (BB != StartBlock &&
2708 !collectPredecessors(BB, Info.Addr, Info.ClobberMA, Blocks, Worklist))
2709 Info.ForceUnknown = true;
2710 }
2711
2712 // Phase 3. We have collected all the blocks that either write a value to the
2713 // memory location of the load, or there exists a path to the load, along
2714 // which the memory location is not modified. Perform a second DFS to find
2715 // load-to-load dependencies; namely, look at the dominating memory reads,
2716 // that alias our load. These are the MemoryUses that are users of the
2717 // MemoryDefs we previously identified. If no memory read is encountered,
2718 // either confirm the clobbering write found before or set to unknown.
2719 Worklist = InitialWorklist;
2720 for (BasicBlock *BB : Worklist) {
2721 DependencyBlockInfo &Info = Blocks.find(BB)->second;
2722 Info.Visited = true;
2723 }
2724
2726 while (!Worklist.empty()) {
2727 auto *BB = Worklist.pop_back_val();
2728 DependencyBlockInfo &Info = Blocks.find(BB)->second;
2729
2730 // If phi-translation failed, assume the memory location is modified in
2731 // unknown way.
2732 if (!Info.Addr.getAddr()) {
2733 Values.push_back(ReachingMemVal::getUnknown(BB, nullptr));
2734 continue;
2735 }
2736
2737 Clobbers.clear();
2738 collectClobberList(Clobbers, BB, Info, Blocks, MSSA);
2739 if (auto RMV =
2740 scanMemoryAccessesUsers(Loc.getWithNewPtr(Info.Addr.getAddr()),
2741 IsInvariantLoad, BB, Clobbers, MSSA, AA)) {
2742 Values.push_back(*RMV);
2743 continue;
2744 }
2745
2746 // If no reusable memory use was found, and the current block is not
2747 // transparent, use the already established memory def.
2748 if (Info.MemVal) {
2749 Values.push_back(*Info.MemVal);
2750 continue;
2751 }
2752
2753 if (Info.ForceUnknown) {
2754 Values.push_back(ReachingMemVal::getUnknown(BB, Info.Addr.getAddr()));
2755 continue;
2756 }
2757
2758 // If the current block is transparent, continue to its predecessors.
2759 for (BasicBlock *Pred : predecessors(BB)) {
2760 auto It = Blocks.find(Pred);
2761 if (It == Blocks.end())
2762 continue;
2763 DependencyBlockInfo &PredInfo = It->second;
2764 if (PredInfo.Visited)
2765 continue;
2766 PredInfo.Visited = true;
2767 Worklist.push_back(Pred);
2768 }
2769 }
2770
2771 return true;
2772}
2773
2774/// Attempt to eliminate a load, first by eliminating it
2775/// locally, and then attempting non-local elimination if that fails.
2776bool GVNPass::processLoad(LoadInst *L) {
2777 if (!MD && !isMemorySSAEnabled())
2778 return false;
2779
2780 // This code hasn't been audited for ordered or volatile memory access.
2781 if (!L->isUnordered())
2782 return false;
2783
2784 if (L->getType()->isTokenLikeTy())
2785 return false;
2786
2787 if (L->use_empty()) {
2789 return true;
2790 }
2791
2792 ReachingMemVal MemVal = ReachingMemVal::getUnknown(nullptr, nullptr);
2793 if (!isMemorySSAEnabled()) {
2794 // ... to a pointer that has been loaded from before...
2795 MemDepResult Dep = MD->getDependency(L);
2796
2797 // If it is defined in another block, try harder.
2798 if (Dep.isNonLocal())
2799 return processNonLocalLoad(L);
2800
2801 // Only handle the local case below.
2802 if (Dep.isDef())
2803 MemVal = ReachingMemVal::getDef(L->getPointerOperand(), Dep.getInst());
2804 else if (Dep.isClobber())
2805 MemVal =
2806 ReachingMemVal::getClobber(L->getPointerOperand(), Dep.getInst());
2807 } else {
2809 if (!findReachingValuesForLoad(L, MemVals, *MSSAU->getMemorySSA(), *AA))
2810 return false; // Too many dependencies.
2811 assert(MemVals.size() && "Expected at least an unknown value");
2812 if (MemVals.size() > 1 || MemVals[0].Block != L->getParent())
2813 return processNonLocalLoad(L, MemVals);
2814
2815 MemVal = MemVals[0];
2816 }
2817
2818 if (MemVal.Kind == DepKind::Other) {
2819 // This might be a NonFuncLocal or an Unknown.
2820 LLVM_DEBUG(
2821 // fast print dep, using operator<< on instruction is too slow.
2822 dbgs() << "GVN: load "; L->printAsOperand(dbgs());
2823 dbgs() << " has unknown dependence\n";);
2824 return false;
2825 }
2826
2827 auto AV = analyzeLoadAvailability(L, MemVal, L->getPointerOperand());
2828 if (!AV)
2829 return false;
2830
2832
2833 // MaterializeAdjustedValue is responsible for combining metadata.
2834 ICF->removeUsersOf(L);
2835 L->replaceAllUsesWith(AvailableValue);
2836 if (MSSAU)
2837 MSSAU->removeMemoryAccess(L);
2838 ++NumGVNLoad;
2841 // Tell MDA to reexamine the reused pointer since we might have more
2842 // information after forwarding it.
2843 if (MD && AvailableValue->getType()->isPtrOrPtrVectorTy())
2844 MD->invalidateCachedPointerInfo(AvailableValue);
2845 return true;
2846}
2847
2848// Attempt to process masked loads which have loaded from
2849// masked stores with the same mask
2850bool GVNPass::processMaskedLoad(IntrinsicInst *I) {
2851 if (!MD)
2852 return false;
2853 MemDepResult Dep = MD->getDependency(I);
2854 Instruction *DepInst = Dep.getInst();
2855 if (!DepInst || !Dep.isLocal() || !Dep.isDef())
2856 return false;
2857
2858 Value *Mask = I->getOperand(1);
2859 Value *Passthrough = I->getOperand(2);
2860 Value *StoreVal;
2861 if (!match(DepInst,
2862 m_MaskedStore(m_Value(StoreVal), m_Value(), m_Specific(Mask))) ||
2863 StoreVal->getType() != I->getType())
2864 return false;
2865
2866 // Remove the load but generate a select for the passthrough
2867 Value *OpToForward = llvm::SelectInst::Create(Mask, StoreVal, Passthrough, "",
2868 I->getIterator());
2869
2870 ICF->removeUsersOf(I);
2871 I->replaceAllUsesWith(OpToForward);
2873 ++NumGVNLoad;
2874 return true;
2875}
2876
2877/// Return a pair the first field showing the value number of \p Exp and the
2878/// second field showing whether it is a value number newly created.
2879std::pair<uint32_t, bool>
2880GVNPass::ValueTable::assignExpNewValueNum(Expression &Exp) {
2881 uint32_t &E = ExpressionNumbering[Exp];
2882 bool CreateNewValNum = !E;
2883 if (CreateNewValNum) {
2884 Expressions.push_back(Exp);
2885 if (ExprIdx.size() < NextValueNumber + 1)
2886 ExprIdx.resize(NextValueNumber * 2);
2887 E = NextValueNumber;
2888 ExprIdx[NextValueNumber++] = NextExprNumber++;
2889 }
2890 return {E, CreateNewValNum};
2891}
2892
2893/// Return whether all the values related with the same \p num are
2894/// defined in \p BB.
2895bool GVNPass::ValueTable::areAllValsInBB(uint32_t Num, const BasicBlock *BB,
2896 GVNPass &GVN) {
2897 return all_of(
2898 GVN.LeaderTable.getLeaders(Num),
2899 [=](const LeaderMap::LeaderTableEntry &L) { return L.BB == BB; });
2900}
2901
2902/// Wrap phiTranslateImpl to provide caching functionality.
2903uint32_t GVNPass::ValueTable::phiTranslate(const BasicBlock *Pred,
2904 const BasicBlock *PhiBlock,
2905 uint32_t Num, GVNPass &GVN) {
2906 auto FindRes = PhiTranslateTable.find({Num, Pred});
2907 if (FindRes != PhiTranslateTable.end())
2908 return FindRes->second;
2909 uint32_t NewNum = phiTranslateImpl(Pred, PhiBlock, Num, GVN);
2910 PhiTranslateTable.insert({{Num, Pred}, NewNum});
2911 return NewNum;
2912}
2913
2914// Return true if the value number \p Num and NewNum have equal value.
2915// Return false if the result is unknown.
2916bool GVNPass::ValueTable::areCallValsEqual(uint32_t Num, uint32_t NewNum,
2917 const BasicBlock *Pred,
2918 const BasicBlock *PhiBlock,
2919 GVNPass &GVN) {
2920 CallInst *Call = nullptr;
2921 auto Leaders = GVN.LeaderTable.getLeaders(Num);
2922 for (const auto &Entry : Leaders) {
2923 Call = dyn_cast<CallInst>(&*Entry.Val);
2924 if (Call && Call->getParent() == PhiBlock)
2925 break;
2926 }
2927
2928 if (AA->doesNotAccessMemory(Call))
2929 return true;
2930
2931 if (!MD || !AA->onlyReadsMemory(Call))
2932 return false;
2933
2934 MemDepResult LocalDep = MD->getDependency(Call);
2935 if (!LocalDep.isNonLocal())
2936 return false;
2937
2940
2941 // Check to see if the Call has no function local clobber.
2942 for (const NonLocalDepEntry &D : Deps) {
2943 if (D.getResult().isNonFuncLocal())
2944 return true;
2945 }
2946 return false;
2947}
2948
2949/// Translate value number \p Num using phis, so that it has the values of
2950/// the phis in BB.
2951uint32_t GVNPass::ValueTable::phiTranslateImpl(const BasicBlock *Pred,
2952 const BasicBlock *PhiBlock,
2953 uint32_t Num, GVNPass &GVN) {
2954 // See if we can refine the value number by looking at the PN incoming value
2955 // for the given predecessor.
2956 if (PHINode *PN = NumberingPhi[Num]) {
2957 if (PN->getParent() != PhiBlock)
2958 return Num;
2959 for (unsigned I = 0; I != PN->getNumIncomingValues(); ++I) {
2960 if (PN->getIncomingBlock(I) != Pred)
2961 continue;
2962 if (uint32_t TransVal = lookup(PN->getIncomingValue(I), false))
2963 return TransVal;
2964 }
2965 return Num;
2966 }
2967
2968 if (BasicBlock *BB = NumberingBB[Num]) {
2969 assert(MSSA && "NumberingBB is non-empty only when using MemorySSA");
2970 // Value numbers of basic blocks are used to represent memory state in
2971 // load/store instructions and read-only function calls when said state is
2972 // set by a MemoryPhi.
2973 if (BB != PhiBlock)
2974 return Num;
2975 MemoryPhi *MPhi = MSSA->getMemoryAccess(BB);
2976 for (unsigned i = 0, N = MPhi->getNumIncomingValues(); i != N; ++i) {
2977 if (MPhi->getIncomingBlock(i) != Pred)
2978 continue;
2979 MemoryAccess *MA = MPhi->getIncomingValue(i);
2980 if (auto *PredPhi = dyn_cast<MemoryPhi>(MA))
2981 return lookupOrAdd(PredPhi->getBlock());
2982 if (MSSA->isLiveOnEntryDef(MA))
2983 return lookupOrAdd(&BB->getParent()->getEntryBlock());
2984 return lookupOrAdd(cast<MemoryUseOrDef>(MA)->getMemoryInst());
2985 }
2987 "CFG/MemorySSA mismatch: predecessor not found among incoming blocks");
2988 }
2989
2990 // If there is any value related with Num is defined in a BB other than
2991 // PhiBlock, it cannot depend on a phi in PhiBlock without going through
2992 // a backedge. We can do an early exit in that case to save compile time.
2993 if (!areAllValsInBB(Num, PhiBlock, GVN))
2994 return Num;
2995
2996 if (Num >= ExprIdx.size() || ExprIdx[Num] == 0)
2997 return Num;
2998 Expression Exp = Expressions[ExprIdx[Num]];
2999
3000 for (unsigned I = 0; I < Exp.VarArgs.size(); I++) {
3001 // For InsertValue and ExtractValue, some varargs are index numbers
3002 // instead of value numbers. Those index numbers should not be
3003 // translated.
3004 if ((I > 1 && Exp.Opcode == Instruction::InsertValue) ||
3005 (I > 0 && Exp.Opcode == Instruction::ExtractValue) ||
3006 (I > 1 && Exp.Opcode == Instruction::ShuffleVector))
3007 continue;
3008 Exp.VarArgs[I] = phiTranslate(Pred, PhiBlock, Exp.VarArgs[I], GVN);
3009 }
3010
3011 if (Exp.Commutative) {
3012 assert(Exp.VarArgs.size() >= 2 && "Unsupported commutative instruction!");
3013 if (Exp.VarArgs[0] > Exp.VarArgs[1]) {
3014 std::swap(Exp.VarArgs[0], Exp.VarArgs[1]);
3015 uint32_t Opcode = Exp.Opcode >> 8;
3016 if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp)
3017 Exp.Opcode = (Opcode << 8) |
3019 static_cast<CmpInst::Predicate>(Exp.Opcode & 255));
3020 }
3021 }
3022
3023 if (uint32_t NewNum = ExpressionNumbering[Exp]) {
3024 if (Exp.Opcode == Instruction::Call && NewNum != Num)
3025 return areCallValsEqual(Num, NewNum, Pred, PhiBlock, GVN) ? NewNum : Num;
3026 return NewNum;
3027 }
3028 return Num;
3029}
3030
3031/// Erase stale entry from phiTranslate cache so phiTranslate can be computed
3032/// again.
3033void GVNPass::ValueTable::eraseTranslateCacheEntry(
3034 uint32_t Num, const BasicBlock &CurrBlock) {
3035 for (const BasicBlock *Pred : predecessors(&CurrBlock))
3036 PhiTranslateTable.erase({Num, Pred});
3037}
3038
3039// In order to find a leader for a given value number at a
3040// specific basic block, we first obtain the list of all Values for that number,
3041// and then scan the list to find one whose block dominates the block in
3042// question. This is fast because dominator tree queries consist of only
3043// a few comparisons of DFS numbers.
3044Value *GVNPass::findLeader(const BasicBlock *BB, uint32_t Num) {
3045 auto Leaders = LeaderTable.getLeaders(Num);
3046 if (Leaders.empty())
3047 return nullptr;
3048
3049 Value *Val = nullptr;
3050 for (const auto &Entry : Leaders) {
3051 if (DT->dominates(Entry.BB, BB)) {
3052 Val = Entry.Val;
3053 if (isa<Constant>(Val))
3054 return Val;
3055 }
3056 }
3057
3058 return Val;
3059}
3060
3061/// There is an edge from 'Src' to 'Dst'. Return
3062/// true if every path from the entry block to 'Dst' passes via this edge. In
3063/// particular 'Dst' must not be reachable via another edge from 'Src'.
3065 DominatorTree *DT) {
3066 // While in theory it is interesting to consider the case in which Dst has
3067 // more than one predecessor, because Dst might be part of a loop which is
3068 // only reachable from Src, in practice it is pointless since at the time
3069 // GVN runs all such loops have preheaders, which means that Dst will have
3070 // been changed to have only one predecessor, namely Src.
3071 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
3072 assert((!Pred || Pred == E.getStart()) &&
3073 "No edge between these basic blocks!");
3074 return Pred != nullptr;
3075}
3076
3077void GVNPass::assignBlockRPONumber(Function &F) {
3078 BlockRPONumber.clear();
3079 uint32_t NextBlockNumber = 1;
3080 ReversePostOrderTraversal<Function *> RPOT(&F);
3081 for (BasicBlock *BB : RPOT)
3082 BlockRPONumber[BB] = NextBlockNumber++;
3083 InvalidBlockRPONumbers = false;
3084}
3085
3086/// The given values are known to be equal in every use
3087/// dominated by 'Root'. Exploit this, for example by replacing 'LHS' with
3088/// 'RHS' everywhere in the scope. Returns whether a change was made.
3089/// The Root may either be a basic block edge (for conditions) or an
3090/// instruction (for assumes).
3091bool GVNPass::propagateEquality(
3092 Value *LHS, Value *RHS,
3093 const std::variant<BasicBlockEdge, Instruction *> &Root) {
3095 Worklist.push_back(std::make_pair(LHS, RHS));
3096 bool Changed = false;
3097 SmallVector<const BasicBlock *> DominatedBlocks;
3098 if (const BasicBlockEdge *Edge = std::get_if<BasicBlockEdge>(&Root)) {
3099 // For speed, compute a conservative fast approximation to
3100 // DT->dominates(Root, Root.getEnd());
3102 DominatedBlocks.push_back(Edge->getEnd());
3103 } else {
3104 Instruction *I = std::get<Instruction *>(Root);
3105 for (const auto *Node : DT->getNode(I->getParent())->children())
3106 DominatedBlocks.push_back(Node->getBlock());
3107 }
3108
3109 while (!Worklist.empty()) {
3110 std::pair<Value*, Value*> Item = Worklist.pop_back_val();
3111 LHS = Item.first; RHS = Item.second;
3112
3113 if (LHS == RHS)
3114 continue;
3115 assert(LHS->getType() == RHS->getType() && "Equality but unequal types!");
3116
3117 // Don't try to propagate equalities between constants.
3119 continue;
3120
3121 // Prefer a constant on the right-hand side, or an Argument if no constants.
3123 std::swap(LHS, RHS);
3124 assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!");
3125 const DataLayout &DL =
3127 ? cast<Argument>(LHS)->getParent()->getDataLayout()
3128 : cast<Instruction>(LHS)->getDataLayout();
3129
3130 // If there is no obvious reason to prefer the left-hand side over the
3131 // right-hand side, ensure the longest lived term is on the right-hand side,
3132 // so the shortest lived term will be replaced by the longest lived.
3133 // This tends to expose more simplifications.
3134 uint32_t LVN = VN.lookupOrAdd(LHS);
3135 if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
3137 // Move the 'oldest' value to the right-hand side, using the value number
3138 // as a proxy for age.
3139 uint32_t RVN = VN.lookupOrAdd(RHS);
3140 if (LVN < RVN) {
3141 std::swap(LHS, RHS);
3142 LVN = RVN;
3143 }
3144 }
3145
3146 // If value numbering later sees that an instruction in the scope is equal
3147 // to 'LHS' then ensure it will be turned into 'RHS'. In order to preserve
3148 // the invariant that instructions only occur in the leader table for their
3149 // own value number (this is used by removeFromLeaderTable), do not do this
3150 // if RHS is an instruction (if an instruction in the scope is morphed into
3151 // LHS then it will be turned into RHS by the next GVN iteration anyway, so
3152 // using the leader table is about compiling faster, not optimizing better).
3153 // The leader table only tracks basic blocks, not edges. Only add to if we
3154 // have the simple case where the edge dominates the end.
3156 for (const BasicBlock *BB : DominatedBlocks)
3157 LeaderTable.insert(LVN, RHS, BB);
3158
3159 // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope. As
3160 // LHS always has at least one use that is not dominated by Root, this will
3161 // never do anything if LHS has only one use.
3162 if (!LHS->hasOneUse()) {
3163 // Create a callback that captures the DL.
3164 auto CanReplacePointersCallBack = [&DL](const Use &U, const Value *To) {
3165 return canReplacePointersInUseIfEqual(U, To, DL);
3166 };
3167 unsigned NumReplacements;
3168 if (const BasicBlockEdge *Edge = std::get_if<BasicBlockEdge>(&Root))
3169 NumReplacements = replaceDominatedUsesWithIf(
3170 LHS, RHS, *DT, *Edge, CanReplacePointersCallBack);
3171 else
3172 NumReplacements = replaceDominatedUsesWithIf(
3173 LHS, RHS, *DT, std::get<Instruction *>(Root),
3174 CanReplacePointersCallBack);
3175
3176 if (NumReplacements > 0) {
3177 Changed = true;
3178 NumGVNEqProp += NumReplacements;
3179 // Cached information for anything that uses LHS will be invalid.
3180 if (MD)
3181 MD->invalidateCachedPointerInfo(LHS);
3182 }
3183 }
3184
3185 // Now try to deduce additional equalities from this one. For example, if
3186 // the known equality was "(A != B)" == "false" then it follows that A and B
3187 // are equal in the scope. Only boolean equalities with an explicit true or
3188 // false RHS are currently supported.
3189 if (!RHS->getType()->isIntegerTy(1))
3190 // Not a boolean equality - bail out.
3191 continue;
3192 ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
3193 if (!CI)
3194 // RHS neither 'true' nor 'false' - bail out.
3195 continue;
3196 // Whether RHS equals 'true'. Otherwise it equals 'false'.
3197 bool IsKnownTrue = CI->isMinusOne();
3198 bool IsKnownFalse = !IsKnownTrue;
3199
3200 // If "A && B" is known true then both A and B are known true. If "A || B"
3201 // is known false then both A and B are known false.
3202 Value *A, *B;
3203 if ((IsKnownTrue && match(LHS, m_LogicalAnd(m_Value(A), m_Value(B)))) ||
3204 (IsKnownFalse && match(LHS, m_LogicalOr(m_Value(A), m_Value(B))))) {
3205 Worklist.push_back(std::make_pair(A, RHS));
3206 Worklist.push_back(std::make_pair(B, RHS));
3207 continue;
3208 }
3209
3210 // If we are propagating an equality like "(A == B)" == "true" then also
3211 // propagate the equality A == B. When propagating a comparison such as
3212 // "(A >= B)" == "true", replace all instances of "A < B" with "false".
3213 if (CmpInst *Cmp = dyn_cast<CmpInst>(LHS)) {
3214 Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
3215
3216 // If "A == B" is known true, or "A != B" is known false, then replace
3217 // A with B everywhere in the scope. For floating point operations, we
3218 // have to be careful since equality does not always imply equivalance.
3219 if (Cmp->isEquivalence(IsKnownFalse))
3220 Worklist.push_back(std::make_pair(Op0, Op1));
3221
3222 // If "A >= B" is known true, replace "A < B" with false everywhere.
3223 CmpInst::Predicate NotPred = Cmp->getInversePredicate();
3224 Constant *NotVal = ConstantInt::get(Cmp->getType(), IsKnownFalse);
3225 // Since we don't have the instruction "A < B" immediately to hand, work
3226 // out the value number that it would have and use that to find an
3227 // appropriate instruction (if any).
3228 uint32_t NextNum = VN.getNextUnusedValueNumber();
3229 uint32_t Num = VN.lookupOrAddCmp(Cmp->getOpcode(), NotPred, Op0, Op1);
3230 // If the number we were assigned was brand new then there is no point in
3231 // looking for an instruction realizing it: there cannot be one!
3232 if (Num < NextNum) {
3233 for (const auto &Entry : LeaderTable.getLeaders(Num)) {
3234 // Only look at leaders that either dominate the start of the edge,
3235 // or are dominated by the end. This check is not necessary for
3236 // correctness, it only discards cases for which the following
3237 // use replacement will not work anyway.
3238 if (const BasicBlockEdge *Edge = std::get_if<BasicBlockEdge>(&Root)) {
3239 if (!DT->dominates(Entry.BB, Edge->getStart()) &&
3240 !DT->dominates(Edge->getEnd(), Entry.BB))
3241 continue;
3242 } else {
3243 auto *InstBB = std::get<Instruction *>(Root)->getParent();
3244 if (!DT->dominates(Entry.BB, InstBB) &&
3245 !DT->dominates(InstBB, Entry.BB))
3246 continue;
3247 }
3248
3249 Value *NotCmp = Entry.Val;
3250 if (NotCmp && isa<Instruction>(NotCmp)) {
3251 unsigned NumReplacements;
3252 if (const BasicBlockEdge *Edge = std::get_if<BasicBlockEdge>(&Root))
3253 NumReplacements =
3254 replaceDominatedUsesWith(NotCmp, NotVal, *DT, *Edge);
3255 else
3256 NumReplacements = replaceDominatedUsesWith(
3257 NotCmp, NotVal, *DT, std::get<Instruction *>(Root));
3258 Changed |= NumReplacements > 0;
3259 NumGVNEqProp += NumReplacements;
3260 // Cached information for anything that uses NotCmp will be invalid.
3261 if (MD)
3262 MD->invalidateCachedPointerInfo(NotCmp);
3263 }
3264 }
3265 }
3266 // Ensure that any instruction in scope that gets the "A < B" value number
3267 // is replaced with false.
3268 // The leader table only tracks basic blocks, not edges. Only add to if we
3269 // have the simple case where the edge dominates the end.
3270 for (const BasicBlock *BB : DominatedBlocks)
3271 LeaderTable.insert(Num, NotVal, BB);
3272
3273 continue;
3274 }
3275
3276 // Propagate equalities that results from truncation with no unsigned wrap
3277 // like (trunc nuw i64 %v to i1) == "true" or (trunc nuw i64 %v to i1) ==
3278 // "false"
3279 if (match(LHS, m_NUWTrunc(m_Value(A)))) {
3280 Worklist.emplace_back(A, ConstantInt::get(A->getType(), IsKnownTrue));
3281 continue;
3282 }
3283
3284 if (match(LHS, m_Not(m_Value(A)))) {
3285 Worklist.emplace_back(A, ConstantInt::get(A->getType(), !IsKnownTrue));
3286 continue;
3287 }
3288 }
3289
3290 return Changed;
3291}
3292
3293/// When calculating availability, handle an instruction
3294/// by inserting it into the appropriate sets.
3295bool GVNPass::processInstruction(Instruction *I) {
3296 // If the instruction can be easily simplified then do so now in preference
3297 // to value numbering it. Value numbering often exposes redundancies, for
3298 // example if it determines that %y is equal to %x then the instruction
3299 // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
3300 const DataLayout &DL = I->getDataLayout();
3301 if (Value *V = simplifyInstruction(I, {DL, TLI, DT, AC})) {
3302 bool Changed = false;
3303 if (!I->use_empty()) {
3304 // Simplification can cause a special instruction to become not special.
3305 // For example, devirtualization to a willreturn function.
3306 ICF->removeUsersOf(I);
3307 I->replaceAllUsesWith(V);
3308 Changed = true;
3309 }
3310 if (isInstructionTriviallyDead(I, TLI)) {
3312 Changed = true;
3313 }
3314 if (Changed) {
3315 if (MD && V->getType()->isPtrOrPtrVectorTy())
3316 MD->invalidateCachedPointerInfo(V);
3317 ++NumGVNSimpl;
3318 return true;
3319 }
3320 }
3321
3322 if (auto *Assume = dyn_cast<AssumeInst>(I))
3323 return processAssumeIntrinsic(Assume);
3324
3325 if (LoadInst *Load = dyn_cast<LoadInst>(I)) {
3326 if (processLoad(Load))
3327 return true;
3328
3329 unsigned Num = VN.lookupOrAdd(Load);
3330 LeaderTable.insert(Num, Load, Load->getParent());
3331 return false;
3332 }
3333
3335 processMaskedLoad(cast<IntrinsicInst>(I)))
3336 return true;
3337
3338 // For conditional branches, we can perform simple conditional propagation on
3339 // the condition value itself.
3340 if (CondBrInst *BI = dyn_cast<CondBrInst>(I)) {
3341 if (isa<Constant>(BI->getCondition()))
3342 return processFoldableCondBr(BI);
3343
3344 Value *BranchCond = BI->getCondition();
3345 BasicBlock *TrueSucc = BI->getSuccessor(0);
3346 BasicBlock *FalseSucc = BI->getSuccessor(1);
3347 // Avoid multiple edges early.
3348 if (TrueSucc == FalseSucc)
3349 return false;
3350
3351 BasicBlock *Parent = BI->getParent();
3352 bool Changed = false;
3353
3355 BasicBlockEdge TrueE(Parent, TrueSucc);
3356 Changed |= propagateEquality(BranchCond, TrueVal, TrueE);
3357
3359 BasicBlockEdge FalseE(Parent, FalseSucc);
3360 Changed |= propagateEquality(BranchCond, FalseVal, FalseE);
3361
3362 return Changed;
3363 }
3364
3365 // For switches, propagate the case values into the case destinations.
3366 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
3367 Value *SwitchCond = SI->getCondition();
3368 BasicBlock *Parent = SI->getParent();
3369 bool Changed = false;
3370
3371 // Remember how many outgoing edges there are to every successor.
3372 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
3373 for (BasicBlock *Succ : successors(Parent))
3374 ++SwitchEdges[Succ];
3375
3376 for (const auto &Case : SI->cases()) {
3377 BasicBlock *Dst = Case.getCaseSuccessor();
3378 // If there is only a single edge, propagate the case value into it.
3379 if (SwitchEdges.lookup(Dst) == 1) {
3380 BasicBlockEdge E(Parent, Dst);
3381 Changed |= propagateEquality(SwitchCond, Case.getCaseValue(), E);
3382 }
3383 }
3384 return Changed;
3385 }
3386
3387 // Instructions with void type don't return a value, so there's
3388 // no point in trying to find redundancies in them.
3389 if (I->getType()->isVoidTy())
3390 return false;
3391
3392 uint32_t NextNum = VN.getNextUnusedValueNumber();
3393 unsigned Num = VN.lookupOrAdd(I);
3394
3395 // Allocations are always uniquely numbered, so we can save time and memory
3396 // by fast failing them.
3397 if (isa<AllocaInst>(I) || I->isTerminator() || isa<PHINode>(I)) {
3398 LeaderTable.insert(Num, I, I->getParent());
3399 return false;
3400 }
3401
3402 // A ptrtoaddr and a ptrtoint of the same pointer compute the same value when
3403 // the address width equals the pointer representation width.
3404 if (auto *PTA = dyn_cast<PtrToAddrInst>(I)) {
3405 const DataLayout &DL = I->getDataLayout();
3406 unsigned AS = PTA->getPointerAddressSpace();
3407 if (DL.getAddressSizeInBits(AS) == DL.getPointerSizeInBits(AS) &&
3408 !DL.hasUnstableRepresentation(AS)) {
3409 uint32_t PTINum =
3410 VN.lookupPtrToInt(PTA->getPointerOperand(), PTA->getType());
3411 if (Value *PTI = findLeader(I->getParent(), PTINum)) {
3414 return true;
3415 }
3416 }
3417 }
3418
3419 // If the number we were assigned was a brand new VN, then we don't
3420 // need to do a lookup to see if the number already exists
3421 // somewhere in the domtree: it can't!
3422 if (Num >= NextNum) {
3423 LeaderTable.insert(Num, I, I->getParent());
3424 return false;
3425 }
3426
3427 // Perform fast-path value-number based elimination of values inherited from
3428 // dominators.
3429 Value *Repl = findLeader(I->getParent(), Num);
3430 if (!Repl) {
3431 // Failure, just remember this instance for future use.
3432 LeaderTable.insert(Num, I, I->getParent());
3433 return false;
3434 }
3435
3436 if (Repl == I) {
3437 // If I was the result of a shortcut PRE, it might already be in the table
3438 // and the best replacement for itself. Nothing to do.
3439 return false;
3440 }
3441
3442 // Remove it!
3444 if (MD && Repl->getType()->isPtrOrPtrVectorTy())
3445 MD->invalidateCachedPointerInfo(Repl);
3447 return true;
3448}
3449
3450/// runOnFunction - This is the main transformation entry point for a function.
3451bool GVNPass::runImpl(Function &F, AssumptionCache &RunAC, DominatorTree &RunDT,
3452 const TargetLibraryInfo &RunTLI, AAResults &RunAA,
3453 MemoryDependenceResults *RunMD, LoopInfo &LI,
3454 OptimizationRemarkEmitter *RunORE, MemorySSA *MSSA) {
3455 AC = &RunAC;
3456 DT = &RunDT;
3457 VN.setDomTree(DT);
3458 TLI = &RunTLI;
3459 AA = &RunAA;
3460 VN.setAliasAnalysis(&RunAA);
3461 MD = RunMD;
3462 ImplicitControlFlowTracking ImplicitCFT;
3463 ICF = &ImplicitCFT;
3464 this->LI = &LI;
3465 VN.setMemDep(MD);
3466 // Propagate the MSSA-enabled flag so the value-numbering paths in
3467 // lookupOrAddCall() and computeLoadStoreVN(), which depends on whether
3468 // IsMSSAEnabled is turned on.
3469 VN.setMemorySSA(MSSA, isMemorySSAEnabled());
3470 ORE = RunORE;
3471 InvalidBlockRPONumbers = true;
3472 MemorySSAUpdater Updater(MSSA);
3473 MSSAU = MSSA ? &Updater : nullptr;
3474
3475 bool Changed = false;
3476 bool ShouldContinue = true;
3477
3478 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
3479 // Merge unconditional branches, allowing PRE to catch more
3480 // optimization opportunities.
3481 for (BasicBlock &BB : make_early_inc_range(F)) {
3482 bool RemovedBlock = MergeBlockIntoPredecessor(&BB, &DTU, &LI, MSSAU, MD);
3483 if (RemovedBlock)
3484 ++NumGVNBlocks;
3485
3486 Changed |= RemovedBlock;
3487 }
3488 DTU.flush();
3489
3490 unsigned Iteration = 0;
3491 while (ShouldContinue) {
3492 LLVM_DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
3493 (void) Iteration;
3494 ShouldContinue = iterateOnFunction(F);
3495 Changed |= ShouldContinue;
3496 ++Iteration;
3497 }
3498
3499 if (isScalarPREEnabled()) {
3500 // Fabricate val-num for dead-code in order to suppress assertion in
3501 // performPRE().
3502 assignValNumForDeadCode();
3503 bool PREChanged = true;
3504 while (PREChanged) {
3505 PREChanged = performPRE(F);
3506 Changed |= PREChanged;
3507 }
3508 }
3509
3510 // FIXME: Should perform GVN again after PRE does something. PRE can move
3511 // computations into blocks where they become fully redundant. Note that
3512 // we can't do this until PRE's critical edge splitting updates memdep.
3513 // Actually, when this happens, we should just fully integrate PRE into GVN.
3514
3515 cleanupGlobalSets();
3516 // Do not cleanup DeadBlocks in cleanupGlobalSets() as it's called for each
3517 // iteration.
3518 DeadBlocks.clear();
3519
3520 if (MSSA && VerifyMemorySSA)
3521 MSSA->verifyMemorySSA();
3522
3523 return Changed;
3524}
3525
3526bool GVNPass::processBlock(BasicBlock *BB) {
3527 if (DeadBlocks.count(BB))
3528 return false;
3529
3530 bool ChangedFunction = false;
3531
3532 // Since we may not have visited the input blocks of the phis, we can't
3533 // use our normal hash approach for phis. Instead, simply look for
3534 // obvious duplicates. The first pass of GVN will tend to create
3535 // identical phis, and the second or later passes can eliminate them.
3536 SmallPtrSet<PHINode *, 8> PHINodesToRemove;
3537 ChangedFunction |= EliminateDuplicatePHINodes(BB, PHINodesToRemove);
3538 for (PHINode *PN : PHINodesToRemove) {
3539 removeInstruction(PN);
3540 }
3541 for (Instruction &Inst : make_early_inc_range(*BB))
3542 ChangedFunction |= processInstruction(&Inst);
3543 return ChangedFunction;
3544}
3545
3546// Instantiate an expression in a predecessor that lacked it.
3547bool GVNPass::performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred,
3548 BasicBlock *Curr, unsigned int ValNo) {
3549 // Because we are going top-down through the block, all value numbers
3550 // will be available in the predecessor by the time we need them. Any
3551 // that weren't originally present will have been instantiated earlier
3552 // in this loop.
3553 bool Success = true;
3554 for (unsigned I = 0, E = Instr->getNumOperands(); I != E; ++I) {
3555 Value *Op = Instr->getOperand(I);
3557 continue;
3558 // This could be a newly inserted instruction, in which case, we won't
3559 // find a value number, and should give up before we hurt ourselves.
3560 // FIXME: Rewrite the infrastructure to let it easier to value number
3561 // and process newly inserted instructions.
3562 if (!VN.exists(Op)) {
3563 Success = false;
3564 break;
3565 }
3566 uint32_t TValNo =
3567 VN.phiTranslate(Pred, Curr, VN.lookup(Op), *this);
3568 if (Value *V = findLeader(Pred, TValNo)) {
3569 Instr->setOperand(I, V);
3570 } else {
3571 Success = false;
3572 break;
3573 }
3574 }
3575
3576 // Fail out if we encounter an operand that is not available in
3577 // the PRE predecessor. This is typically because of loads which
3578 // are not value numbered precisely.
3579 if (!Success)
3580 return false;
3581
3582 Instr->insertBefore(Pred->getTerminator()->getIterator());
3583 Instr->setName(Instr->getName() + ".pre");
3584 Instr->setDebugLoc(Instr->getDebugLoc());
3585
3586 ICF->insertInstructionTo(Instr, Pred);
3587
3588 unsigned Num = VN.lookupOrAdd(Instr);
3589 VN.add(Instr, Num);
3590
3591 // Update the availability map to include the new instruction.
3592 LeaderTable.insert(Num, Instr, Pred);
3593 return true;
3594}
3595
3596bool GVNPass::performScalarPRE(Instruction *CurInst) {
3597 if (isa<AllocaInst>(CurInst) || CurInst->isTerminator() ||
3598 isa<PHINode>(CurInst) || CurInst->getType()->isVoidTy() ||
3599 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
3600 CurInst->getType()->isTokenLikeTy())
3601 return false;
3602
3603 // Don't do PRE on compares. The PHI would prevent CodeGenPrepare from
3604 // sinking the compare again, and it would force the code generator to
3605 // move the i1 from processor flags or predicate registers into a general
3606 // purpose register.
3607 if (isa<CmpInst>(CurInst))
3608 return false;
3609
3610 // Don't do PRE on GEPs. The inserted PHI would prevent CodeGenPrepare from
3611 // sinking the addressing mode computation back to its uses. Extending the
3612 // GEP's live range increases the register pressure, and therefore it can
3613 // introduce unnecessary spills.
3614 //
3615 // This doesn't prevent Load PRE. PHI translation will make the GEP available
3616 // to the load by moving it to the predecessor block if necessary.
3617 if (isa<GetElementPtrInst>(CurInst))
3618 return false;
3619
3620 if (auto *CallB = dyn_cast<CallBase>(CurInst)) {
3621 // We don't currently value number ANY inline asm calls.
3622 if (CallB->isInlineAsm())
3623 return false;
3624 }
3625
3626 uint32_t ValNo = VN.lookup(CurInst);
3627
3628 // Look for the predecessors for PRE opportunities. We're
3629 // only trying to solve the basic diamond case, where
3630 // a value is computed in the successor and one predecessor,
3631 // but not the other. We also explicitly disallow cases
3632 // where the successor is its own predecessor, because they're
3633 // more complicated to get right.
3634 unsigned NumWith = 0;
3635 unsigned NumWithout = 0;
3636 BasicBlock *PREPred = nullptr;
3637 BasicBlock *CurrentBlock = CurInst->getParent();
3638
3639 // Update the RPO numbers for this function.
3640 if (InvalidBlockRPONumbers)
3641 assignBlockRPONumber(*CurrentBlock->getParent());
3642
3644 for (BasicBlock *P : predecessors(CurrentBlock)) {
3645 // We're not interested in PRE where blocks with predecessors that are
3646 // not reachable.
3647 if (!DT->isReachableFromEntry(P)) {
3648 NumWithout = 2;
3649 break;
3650 }
3651 // It is not safe to do PRE when P->CurrentBlock is a loop backedge.
3652 assert(BlockRPONumber.count(P) && BlockRPONumber.count(CurrentBlock) &&
3653 "Invalid BlockRPONumber map.");
3654 if (BlockRPONumber[P] >= BlockRPONumber[CurrentBlock]) {
3655 NumWithout = 2;
3656 break;
3657 }
3658
3659 uint32_t TValNo = VN.phiTranslate(P, CurrentBlock, ValNo, *this);
3660 Value *PredV = findLeader(P, TValNo);
3661 if (!PredV) {
3662 PredMap.push_back(std::make_pair(static_cast<Value *>(nullptr), P));
3663 PREPred = P;
3664 ++NumWithout;
3665 } else if (PredV == CurInst) {
3666 // CurInst dominates this predecessor.
3667 NumWithout = 2;
3668 break;
3669 } else {
3670 PredMap.push_back(std::make_pair(PredV, P));
3671 ++NumWith;
3672 }
3673 }
3674
3675 // Don't do PRE when it might increase code size, i.e. when
3676 // we would need to insert instructions in more than one pred.
3677 if (NumWithout > 1 || NumWith == 0)
3678 return false;
3679
3680 // We may have a case where all predecessors have the instruction,
3681 // and we just need to insert a phi node. Otherwise, perform
3682 // insertion.
3683 Instruction *PREInstr = nullptr;
3684
3685 if (NumWithout != 0) {
3686 if (!isSafeToSpeculativelyExecute(CurInst)) {
3687 // It is only valid to insert a new instruction if the current instruction
3688 // is always executed. An instruction with implicit control flow could
3689 // prevent us from doing it. If we cannot speculate the execution, then
3690 // PRE should be prohibited.
3691 if (ICF->isDominatedByICFIFromSameBlock(CurInst))
3692 return false;
3693 }
3694
3695 // Don't do PRE across indirect branch.
3696 if (isa<IndirectBrInst>(PREPred->getTerminator()))
3697 return false;
3698
3699 // We can't do PRE safely on a critical edge, so instead we schedule
3700 // the edge to be split and perform the PRE the next time we iterate
3701 // on the function.
3702 unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
3703 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
3704 ToSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
3705 return false;
3706 }
3707 // We need to insert somewhere, so let's give it a shot.
3708 PREInstr = CurInst->clone();
3709 if (!performScalarPREInsertion(PREInstr, PREPred, CurrentBlock, ValNo)) {
3710 // If we failed insertion, make sure we remove the instruction.
3711#ifndef NDEBUG
3712 verifyRemoved(PREInstr);
3713#endif
3714 PREInstr->deleteValue();
3715 return false;
3716 }
3717 }
3718
3719 // Either we should have filled in the PRE instruction, or we should
3720 // not have needed insertions.
3721 assert(PREInstr != nullptr || NumWithout == 0);
3722
3723 ++NumGVNPRE;
3724
3725 // Create a PHI to make the value available in this block.
3726 PHINode *Phi = PHINode::Create(CurInst->getType(), PredMap.size(),
3727 CurInst->getName() + ".pre-phi");
3728 Phi->insertBefore(CurrentBlock->begin());
3729 for (auto &[V, BB] : PredMap) {
3730 if (V) {
3731 // If we use an existing value in this phi, we have to patch the original
3732 // value because the phi will be used to replace a later value.
3733 patchReplacementInstruction(CurInst, V);
3734 Phi->addIncoming(V, BB);
3735 } else
3736 Phi->addIncoming(PREInstr, PREPred);
3737 }
3738
3739 VN.add(Phi, ValNo);
3740 // After creating a new PHI for ValNo, the phi translate result for ValNo will
3741 // be changed, so erase the related stale entries in phi translate cache.
3742 VN.eraseTranslateCacheEntry(ValNo, *CurrentBlock);
3743 LeaderTable.insert(ValNo, Phi, CurrentBlock);
3744 Phi->setDebugLoc(CurInst->getDebugLoc());
3745 CurInst->replaceAllUsesWith(Phi);
3746 if (MD && Phi->getType()->isPtrOrPtrVectorTy())
3747 MD->invalidateCachedPointerInfo(Phi);
3748 LeaderTable.erase(ValNo, CurInst, CurrentBlock);
3749
3750 LLVM_DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
3751 removeInstruction(CurInst);
3752
3753 return true;
3754}
3755
3756/// Perform a purely local form of PRE that looks for diamond
3757/// control flow patterns and attempts to perform simple PRE at the join point.
3758bool GVNPass::performPRE(Function &F) {
3759 bool Changed = false;
3760 for (BasicBlock *CurrentBlock : depth_first(&F.getEntryBlock())) {
3761 // Nothing to PRE in the entry block.
3762 if (CurrentBlock == &F.getEntryBlock())
3763 continue;
3764
3765 // Don't perform PRE on an EH pad.
3766 if (CurrentBlock->isEHPad())
3767 continue;
3768
3769 for (BasicBlock::iterator BI = CurrentBlock->begin(),
3770 BE = CurrentBlock->end();
3771 BI != BE;) {
3772 Instruction *CurInst = &*BI++;
3773 Changed |= performScalarPRE(CurInst);
3774 }
3775 }
3776
3777 if (splitCriticalEdges())
3778 Changed = true;
3779
3780 return Changed;
3781}
3782
3783/// Split the critical edge connecting the given two blocks, and return
3784/// the block inserted to the critical edge.
3785BasicBlock *GVNPass::splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ) {
3786 // GVN does not require loop-simplify, do not try to preserve it if it is not
3787 // possible.
3789 Pred, Succ,
3790 CriticalEdgeSplittingOptions(DT, LI, MSSAU).unsetPreserveLoopSimplify());
3791 if (BB) {
3792 if (MD)
3793 MD->invalidateCachedPredecessors();
3794 InvalidBlockRPONumbers = true;
3795 }
3796 return BB;
3797}
3798
3799/// Split critical edges found during the previous
3800/// iteration that may enable further optimization.
3801bool GVNPass::splitCriticalEdges() {
3802 if (ToSplit.empty())
3803 return false;
3804
3805 bool Changed = false;
3806 do {
3807 std::pair<Instruction *, unsigned> Edge = ToSplit.pop_back_val();
3808 Changed |= SplitCriticalEdge(Edge.first, Edge.second,
3809 CriticalEdgeSplittingOptions(DT, LI, MSSAU)) !=
3810 nullptr;
3811 } while (!ToSplit.empty());
3812 if (Changed) {
3813 if (MD)
3814 MD->invalidateCachedPredecessors();
3815 InvalidBlockRPONumbers = true;
3816 }
3817 return Changed;
3818}
3819
3820/// Executes one iteration of GVN.
3821bool GVNPass::iterateOnFunction(Function &F) {
3822 cleanupGlobalSets();
3823
3824 // Top-down walk of the dominator tree.
3825 bool Changed = false;
3826 // Needed for value numbering with phi construction to work.
3827 // RPOT walks the graph in its constructor and will not be invalidated during
3828 // processBlock.
3829 ReversePostOrderTraversal<Function *> RPOT(&F);
3830
3831 for (BasicBlock *BB : RPOT)
3832 Changed |= processBlock(BB);
3833
3834 return Changed;
3835}
3836
3837void GVNPass::cleanupGlobalSets() {
3838 VN.clear();
3839 LeaderTable.clear();
3840 BlockRPONumber.clear();
3841 ICF->clear();
3842 InvalidBlockRPONumbers = true;
3843}
3844
3845void GVNPass::removeInstruction(Instruction *I) {
3846 VN.erase(I);
3847 if (MD) MD->removeInstruction(I);
3848 if (MSSAU)
3849 MSSAU->removeMemoryAccess(I);
3850#ifndef NDEBUG
3851 verifyRemoved(I);
3852#endif
3853 ICF->removeInstruction(I);
3854 I->eraseFromParent();
3855 ++NumGVNInstr;
3856}
3857
3858/// Verify that the specified instruction does not occur in our
3859/// internal data structures.
3860void GVNPass::verifyRemoved(const Instruction *Inst) const {
3861 VN.verifyRemoved(Inst);
3862}
3863
3864/// BB is declared dead, which implied other blocks become dead as well. This
3865/// function is to add all these blocks to "DeadBlocks". For the dead blocks'
3866/// live successors, update their phi nodes by replacing the operands
3867/// corresponding to dead blocks with UndefVal.
3868void GVNPass::addDeadBlock(BasicBlock *BB) {
3870 SmallSetVector<BasicBlock *, 4> DF;
3871
3872 NewDead.push_back(BB);
3873 while (!NewDead.empty()) {
3874 BasicBlock *D = NewDead.pop_back_val();
3875 if (DeadBlocks.count(D))
3876 continue;
3877
3878 // All blocks dominated by D are dead.
3879 SmallVector<BasicBlock *, 8> Dom;
3880 DT->getDescendants(D, Dom);
3881 DeadBlocks.insert_range(Dom);
3882
3883 // Figure out the dominance-frontier(D).
3884 for (BasicBlock *B : Dom) {
3885 for (BasicBlock *S : successors(B)) {
3886 if (DeadBlocks.count(S))
3887 continue;
3888
3889 bool AllPredDead = true;
3890 for (BasicBlock *P : predecessors(S))
3891 if (!DeadBlocks.count(P)) {
3892 AllPredDead = false;
3893 break;
3894 }
3895
3896 if (!AllPredDead) {
3897 // S could be proved dead later on. That is why we don't update phi
3898 // operands at this moment.
3899 DF.insert(S);
3900 } else {
3901 // While S is not dominated by D, it is dead by now. This could take
3902 // place if S already have a dead predecessor before D is declared
3903 // dead.
3904 NewDead.push_back(S);
3905 }
3906 }
3907 }
3908 }
3909
3910 // For the dead blocks' live successors, update their phi nodes by replacing
3911 // the operands corresponding to dead blocks with UndefVal.
3912 for (BasicBlock *B : DF) {
3913 if (DeadBlocks.count(B))
3914 continue;
3915
3916 // First, split the critical edges. This might also create additional blocks
3917 // to preserve LoopSimplify form and adjust edges accordingly.
3919 for (BasicBlock *P : Preds) {
3920 if (!DeadBlocks.count(P))
3921 continue;
3922
3923 if (is_contained(successors(P), B) &&
3924 isCriticalEdge(P->getTerminator(), B)) {
3925 if (BasicBlock *S = splitCriticalEdges(P, B))
3926 DeadBlocks.insert(P = S);
3927 }
3928 }
3929
3930 // Now poison the incoming values from the dead predecessors.
3931 for (BasicBlock *P : predecessors(B)) {
3932 if (!DeadBlocks.count(P))
3933 continue;
3934 for (PHINode &Phi : B->phis()) {
3935 Phi.setIncomingValueForBlock(P, PoisonValue::get(Phi.getType()));
3936 if (MD)
3937 MD->invalidateCachedPointerInfo(&Phi);
3938 }
3939 }
3940 }
3941}
3942
3943// If the given branch is recognized as a foldable branch (i.e. conditional
3944// branch with constant condition), it will perform following analyses and
3945// transformation.
3946// 1) If the dead out-coming edge is a critical-edge, split it. Let
3947// R be the target of the dead out-coming edge.
3948// 1) Identify the set of dead blocks implied by the branch's dead outcoming
3949// edge. The result of this step will be {X| X is dominated by R}
3950// 2) Identify those blocks which haves at least one dead predecessor. The
3951// result of this step will be dominance-frontier(R).
3952// 3) Update the PHIs in DF(R) by replacing the operands corresponding to
3953// dead blocks with "UndefVal" in an hope these PHIs will optimized away.
3954//
3955// Return true iff *NEW* dead code are found.
3956bool GVNPass::processFoldableCondBr(CondBrInst *BI) {
3957 // If a branch has two identical successors, we cannot declare either dead.
3958 if (BI->getSuccessor(0) == BI->getSuccessor(1))
3959 return false;
3960
3961 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
3962 if (!Cond)
3963 return false;
3964
3965 BasicBlock *DeadRoot =
3966 Cond->getZExtValue() ? BI->getSuccessor(1) : BI->getSuccessor(0);
3967 if (DeadBlocks.count(DeadRoot))
3968 return false;
3969
3970 if (!DeadRoot->getSinglePredecessor())
3971 DeadRoot = splitCriticalEdges(BI->getParent(), DeadRoot);
3972
3973 addDeadBlock(DeadRoot);
3974 return true;
3975}
3976
3977// performPRE() will trigger assert if it comes across an instruction without
3978// associated val-num. As it normally has far more live instructions than dead
3979// instructions, it makes more sense just to "fabricate" a val-number for the
3980// dead code than checking if instruction involved is dead or not.
3981void GVNPass::assignValNumForDeadCode() {
3982 for (BasicBlock *BB : DeadBlocks) {
3983 for (Instruction &Inst : *BB) {
3984 unsigned ValNum = VN.lookupOrAdd(&Inst);
3985 LeaderTable.insert(ValNum, &Inst, BB);
3986 }
3987 }
3988}
3989
3991public:
3992 static char ID; // Pass identification, replacement for typeid.
3993
3994 explicit GVNLegacyPass(bool MemDepAnalysis = GVNEnableMemDep,
3995 bool MemSSAAnalysis = GVNEnableMemorySSA,
3996 bool ScalarPRE = true)
3997 : FunctionPass(ID), Impl(GVNOptions()
3998 .setMemDep(MemDepAnalysis)
3999 .setMemorySSA(MemSSAAnalysis)
4000 .setScalarPRE(ScalarPRE)) {
4002 }
4003
4004 bool runOnFunction(Function &F) override {
4005 if (skipFunction(F))
4006 return false;
4007
4009 if (Impl.isMemorySSAEnabled() && !MSSAWP)
4011
4012 return Impl.runImpl(
4013 F, getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
4016 getAnalysis<AAResultsWrapperPass>().getAAResults(),
4017 Impl.isMemDepEnabled()
4019 : nullptr,
4020 getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
4022 MSSAWP ? &MSSAWP->getMSSA() : nullptr);
4023 }
4024
4042
4043private:
4044 GVNPass Impl;
4045};
4046
4047char GVNLegacyPass::ID = 0;
4048
4049INITIALIZE_PASS_BEGIN(GVNLegacyPass, "gvn", "Global Value Numbering", false, false)
4058INITIALIZE_PASS_END(GVNLegacyPass, "gvn", "Global Value Numbering", false, false)
4059
4060// The public interface to this file...
4063 return new GVNLegacyPass(GVNEnableMemDep, GVNEnableMemorySSA, ScalarPRE);
4064}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static RegisterPass< DebugifyFunctionPass > DF("debugify-function", "Attach debug info to a function")
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
early cse Early CSE w MemorySSA
static void reportMayClobberedLoad(LoadInst *Load, Instruction *DepInst, const DominatorTree *DT, OptimizationRemarkEmitter *ORE)
Try to locate the three instruction involved in a missed load-elimination case that is due to an inte...
Definition GVN.cpp:1274
static bool isValueFullyAvailableInBlock(BasicBlock *BB, DenseMap< BasicBlock *, AvailabilityState > &FullyAvailableBlocks)
Return true if we can prove that the value we're analyzing is fully available in the specified block.
Definition GVN.cpp:957
static Instruction * findInvariantGroupValue(LoadInst *L, DominatorTree &DT)
If a load has !invariant.group, try to find the most-dominating instruction with the same metadata an...
Definition GVN.cpp:2233
static void reportLoadElim(LoadInst *Load, Value *AvailableValue, OptimizationRemarkEmitter *ORE)
Definition GVN.cpp:2032
GVNPass::AvailableValue AvailableValue
Definition GVN.cpp:87
static cl::opt< uint32_t > MaxNumInsnsPerBlock("gvn-max-num-insns", cl::Hidden, cl::init(100), cl::desc("Max number of instructions to scan in each basic block in GVN " "(default = 100)"))
static cl::opt< bool > GVNEnableMemDep("enable-gvn-memdep", cl::init(true))
static cl::opt< bool > GVNEnableLoadInLoopPRE("enable-load-in-loop-pre", cl::init(true))
static const Instruction * findMayClobberedPtrAccess(LoadInst *Load, const DominatorTree *DT)
Definition GVN.cpp:1218
static cl::opt< uint32_t > MaxNumDeps("gvn-max-num-deps", cl::Hidden, cl::init(100), cl::desc("Max number of dependences to attempt Load PRE (default = 100)"))
static std::optional< MemoryLocation > maybeLoadStoreLocation(Instruction *I, bool AllowStores, const TargetLibraryInfo *TLI)
Return the memory location accessed by the (masked) load/store instruction I, if the instruction coul...
Definition GVN.cpp:2285
static cl::opt< bool > GVNEnableMemorySSA("enable-gvn-memoryssa", cl::init(false))
static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E, DominatorTree *DT)
There is an edge from 'Src' to 'Dst'.
Definition GVN.cpp:3064
static cl::opt< bool > GVNEnableScalarPRE("enable-scalar-pre", cl::init(true), cl::Hidden)
static Value * findDominatingValue(const MemoryLocation &Loc, Type *LoadTy, Instruction *From, AAResults *AA)
Definition GVN.cpp:1295
static bool liesBetween(const Instruction *From, Instruction *Between, const Instruction *To, const DominatorTree *DT)
Assuming To can be reached from both From and Between, does Between lie on every path from From to To...
Definition GVN.cpp:1209
static bool isLifetimeStart(const Instruction *Inst)
Definition GVN.cpp:1201
static cl::opt< bool > GVNEnableSplitBackedgeInLoadPRE("enable-split-backedge-in-load-pre", cl::init(false))
static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl)
Definition GVN.cpp:2225
static void replaceValuesPerBlockEntry(SmallVectorImpl< AvailableValueInBlock > &ValuesPerBlock, Value *OldValue, Value *NewValue)
If the specified OldValue exists in ValuesPerBlock, replace its value with NewValue.
Definition GVN.cpp:1073
static cl::opt< unsigned > ScanUsersLimit("gvn-scan-users-limit", cl::Hidden, cl::init(100), cl::desc("The number of memory accesses to scan in a block in reaching " "memory values analysis (default = 100)"))
AvailabilityState
Definition GVN.cpp:937
@ Unavailable
We know the block is not fully available. This is a fixpoint.
Definition GVN.cpp:939
@ Available
We know the block is fully available. This is a fixpoint.
Definition GVN.cpp:941
@ SpeculativelyAvailable
We do not know whether the block is fully available or not, but we are currently speculating that it ...
Definition GVN.cpp:946
static cl::opt< uint32_t > MaxNumVisitedInsts("gvn-max-num-visited-insts", cl::Hidden, cl::init(100), cl::desc("Max number of visited instructions when trying to find " "dominating value of select dependency (default = 100)"))
static cl::opt< uint32_t > MaxBBSpeculations("gvn-max-block-speculations", cl::Hidden, cl::init(600), cl::desc("Max number of blocks we're willing to speculate on (and recurse " "into) when deducing if a value is fully available or not in GVN " "(default = 600)"))
static cl::opt< bool > GVNEnableLoadPRE("enable-load-pre", cl::init(true))
GVNPass::AvailableValueInBlock AvailableValueInBlock
Definition GVN.cpp:88
static Value * constructSSAForLoadSet(LoadInst *Load, SmallVectorImpl< AvailableValueInBlock > &ValuesPerBlock, GVNPass &GVN)
Given a set of loads specified by ValuesPerBlock, construct SSA form, allowing us to eliminate Load.
Definition GVN.cpp:1092
This file provides the interface for LLVM's Global Value Numbering pass which eliminates fully redund...
#define DEBUG_TYPE
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
#define _
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
static bool lookup(const GsymReader &GR, GsymDataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
This file implements a map that provides insertion order iteration.
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.
uint64_t IntrinsicInst * II
#define P(N)
ppc ctr loops PowerPC CTR Loops Verify
#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 builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
const SmallVectorImpl< MachineOperand > & Cond
static DominatorTree getDomTree(Function &F)
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
@ MayAlias
The two locations may or may not alias.
@ NoAlias
The two locations do not alias at all.
@ PartialAlias
The two locations alias, but only due to a partial overlap.
@ MustAlias
The two locations precisely alias each other.
constexpr int32_t getOffset() const
constexpr bool hasOffset() const
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
iterator end() const
Definition ArrayRef.h:130
iterator begin() const
Definition ArrayRef.h:129
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition BasicBlock.h:704
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
Value * getArgOperand(unsigned i) const
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
Definition Constants.h:231
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:250
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:223
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
iterator end()
Definition DenseMap.h:141
Analysis pass which computes a DominatorTree.
Definition Dominators.h:270
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:306
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:151
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.
Class representing an expression and its matching format.
unsigned getNumIndices() const
iterator_range< idx_iterator > indices() const
idx_iterator idx_begin() const
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
FunctionPass(char &pid)
Definition Pass.h:316
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
Definition Pass.cpp:193
const BasicBlock & getEntryBlock() const
Definition Function.h:783
Represents calls to the gc.relocate intrinsic.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
Definition GVN.cpp:4004
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition GVN.cpp:4025
GVNLegacyPass(bool MemDepAnalysis=GVNEnableMemDep, bool MemSSAAnalysis=GVNEnableMemorySSA, bool ScalarPRE=true)
Definition GVN.cpp:3994
static char ID
Definition GVN.cpp:3992
This class holds the mapping between values and value numbers.
Definition GVN.h:158
LLVM_ABI uint32_t lookupOrAdd(MemoryAccess *MA)
Definition GVN.cpp:642
The core GVN pass object.
Definition GVN.h:123
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
Definition GVN.cpp:879
LLVM_ABI void salvageAndRemoveInstruction(Instruction *I)
This removes the specified instruction from our various maps and marks it for deletion.
Definition GVN.cpp:931
AAResults * getAliasAnalysis() const
Definition GVN.h:145
LLVM_ABI bool isLoadPREEnabled() const
Definition GVN.cpp:858
GVNPass(GVNOptions Options={})
Definition GVN.h:131
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Definition GVN.cpp:911
LLVM_ABI bool isMemorySSAEnabled() const
Definition GVN.cpp:875
DominatorTree & getDominatorTree() const
Definition GVN.h:144
LLVM_ABI bool isLoadInLoopPREEnabled() const
Definition GVN.cpp:862
LLVM_ABI bool isScalarPREEnabled() const
Definition GVN.cpp:854
LLVM_ABI bool isLoadPRESplitBackedgeEnabled() const
Definition GVN.cpp:866
friend class GVNLegacyPass
Definition GVN.h:245
LLVM_ABI bool isMemDepEnabled() const
Definition GVN.cpp:871
Legacy wrapper pass to provide the GlobalsAAResult object.
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
bool isTerminator() const
LLVM_ABI bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
LLVM_ABI void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs={})
Drop all unknown metadata except for debug locations.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
A wrapper class for inspecting calls to intrinsic functions.
An instruction for reading from memory.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:588
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:613
iterator find(const KeyT &Key)
Definition MapVector.h:156
iterator end()
Definition MapVector.h:69
size_type size() const
Definition MapVector.h:58
A memory dependence query can return one of three different answers.
bool isClobber() const
Tests if this MemDepResult represents a query that is an instruction clobber dependency.
bool isNonLocal() const
Tests if this MemDepResult represents a query that is transparent to the start of the block,...
bool isDef() const
Tests if this MemDepResult represents a query that is an instruction definition dependency.
bool isLocal() const
Tests if this MemDepResult represents a valid local query (Clobber/Def).
Instruction * getInst() const
If this is a normal dependency, returns the instruction that is depended on.
This is the common base class for memset/memcpy/memmove.
BasicBlock * getBlock() const
Definition MemorySSA.h:162
An analysis that produces MemoryDependenceResults for a function.
std::vector< NonLocalDepEntry > NonLocalDepInfo
LLVM_ABI MemDepResult getDependency(Instruction *QueryInst)
Returns the instruction on which a memory operation depends.
LLVM_ABI const NonLocalDepInfo & getNonLocalCallDependency(CallBase *QueryCall)
Perform a full dependency query for the specified call, returning the set of blocks that the value is...
A wrapper analysis pass for the legacy pass manager that exposes a MemoryDepnedenceResults instance.
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.
MemoryLocation getWithNewPtr(const Value *NewPtr) const
const Value * Ptr
The address of the start of the location.
static LLVM_ABI MemoryLocation getForArgument(const CallBase *Call, unsigned ArgIdx, const TargetLibraryInfo *TLI)
Return a location representing a particular argument of a call.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
Definition MemorySSA.h:529
BasicBlock * getIncomingBlock(unsigned I) const
Return incoming basic block number i.
Definition MemorySSA.h:542
MemoryAccess * getIncomingValue(unsigned I) const
Return incoming value number x.
Definition MemorySSA.h:532
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:922
Legacy analysis pass which computes MemorySSA.
Definition MemorySSA.h:975
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
Definition MemorySSA.h:720
LLVM_ABI bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in the same basic block, determine whether MemoryAccess A dominates MemoryA...
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
Definition MemorySSA.h:740
MemoryAccess * getDefiningAccess() const
Get the access that produces the memory state used by this Use.
Definition MemorySSA.h:260
This is an entry in the NonLocalDepInfo cache.
OptimizationRemarkEmitter legacy analysis pass.
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.
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...
LLVM_ABI Value * translateValue(BasicBlock *CurBB, BasicBlock *PredBB, const DominatorTree *DT, bool MustDominate)
translateValue - PHI translate the current address up the CFG from CurBB to Pred, updating our state ...
LLVM_ABI bool isPotentiallyPHITranslatable() const
isPotentiallyPHITranslatable - If this needs PHI translation, return true if we have some hope of doi...
bool needsPHITranslationFromBlock(BasicBlock *BB) const
needsPHITranslationFromBlock - Return true if moving from the specified BasicBlock to its predecessor...
Value * getAddr() const
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
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
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition SSAUpdater.h:39
LLVM_ABI void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
LLVM_ABI Value * GetValueInMiddleOfBlock(BasicBlock *BB)
Construct SSA form, materializing a value that is live in the middle of the specified block.
LLVM_ABI bool HasValueForBlock(BasicBlock *BB) const
Return true if the SSAUpdater already has a value for the specified block.
LLVM_ABI void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value.
std::pair< Value *, SelectAddrs > getSelectCondAndAddrs() const
Value * getAddr() const
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
bool erase(PtrType Ptr)
Remove pointer from the set.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
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)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
SmallVector & operator=(const SmallVector &RHS)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI bool isTokenLikeTy() const
Returns true if this is 'token' or a token-like target type.s.
Definition Type.cpp:1144
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:285
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
iterator_range< user_iterator > users()
Definition Value.h:426
bool hasUseList() const
Check if this Value has a use-list.
Definition Value.h:344
LLVM_ABI bool canBeFreed() const
Return true if the memory object referred to by V can by freed in the scope for which the SSA value d...
Definition Value.cpp:832
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:108
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
An efficient, type-erasing, non-owning reference to a callable.
An opaque object representing a hash code.
Definition Hashing.h:77
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
CallInst * Call
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:165
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
NoWrapTrunc_match< OpTy, TruncInst::NoUnsignedWrap > m_NUWTrunc(const OpTy &Op)
Matches trunc nuw.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_MaskedStore(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
Matches MaskedStore Intrinsic.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
LLVM_ABI int analyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr, StoreInst *DepSI, const DataLayout &DL)
This function determines whether a value for the pointer LoadPtr can be extracted from the store at D...
LLVM_ABI Value * getMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset, Type *LoadTy, Instruction *InsertPt, const DataLayout &DL)
If analyzeLoadFromClobberingMemInst returned an offset, this function can be used to actually perform...
LLVM_ABI int analyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr, LoadInst *DepLI, const DataLayout &DL)
This function determines whether a value for the pointer LoadPtr can be extracted from the load at De...
LLVM_ABI Value * getValueForLoad(Value *SrcVal, unsigned Offset, Type *LoadTy, Instruction *InsertPt, Function *F)
If analyzeLoadFromClobberingStore/Load returned an offset, this function can be used to actually perf...
LLVM_ABI int analyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr, MemIntrinsic *DepMI, const DataLayout &DL)
This function determines whether a value for the pointer LoadPtr can be extracted from the memory int...
LLVM_ABI bool canCoerceMustAliasedValueToLoad(Value *StoredVal, Type *LoadTy, Function *F)
Return true if CoerceAvailableValueToLoadType would succeed if it was called.
initializer< Ty > init(const Ty &Val)
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:391
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:392
NodeAddr< UseNode * > Use
Definition RDFGraph.h:387
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:383
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:578
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
hash_code hash_value(const FixedPointSemantics &Val)
LLVM_ABI Constant * getInitialValueOfAllocation(const Value *V, const TargetLibraryInfo *TLI, Type *Ty)
If this is a call to an allocation function that initializes memory to a fixed value,...
LLVM_ABI unsigned replaceDominatedUsesWithIf(Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Edge, function_ref< bool(const Use &U, const Value *To)> ShouldReplace)
Replace each use of 'From' with 'To' if that use is dominated by the given edge and the callback Shou...
Definition Local.cpp:3290
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
LLVM_ABI unsigned GetSuccessorNumber(const BasicBlock *BB, const BasicBlock *Succ)
Search for the specified successor of basic block BB and return its position in the terminator instru...
Definition CFG.cpp:90
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
LLVM_ABI FunctionPass * createGVNPass(bool ScalarPRE)
Create a legacy GVN pass.
Definition GVN.cpp:4062
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition Utils.cpp:1675
auto successors(const MachineBasicBlock *BB)
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ Load
The value being inserted comes from a load (InsertElement only).
constexpr from_range_t from_range
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
LLVM_ABI bool isNoAliasCall(const Value *V)
Return true if this pointer is returned by a noalias function.
LLVM_ABI bool isAssumeWithEmptyBundle(const AssumeInst &Assume)
Return true iff the operand bundles of the provided llvm.assume doesn't contain any valuable informat...
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 ...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:403
LLVM_ABI bool canReplacePointersInUseIfEqual(const Use &U, const Value *To, const DataLayout &DL)
Definition Loads.cpp:862
LLVM_ABI bool canReplacePointersIfEqual(const Value *From, const Value *To, const DataLayout &DL)
Returns true if a pointer value From can be replaced with another pointer value \To if they are deeme...
Definition Loads.cpp:882
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 void patchReplacementInstruction(Instruction *I, Value *Repl)
Patch the replacement so that it is not more restrictive than the value being replaced.
Definition Local.cpp:3190
LLVM_ABI void initializeGVNLegacyPassPass(PassRegistry &)
LLVM_ABI unsigned replaceDominatedUsesWith(Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Edge)
Replace each use of 'From' with 'To' if that use is dominated by the given edge.
Definition Local.cpp:3269
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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
@ Success
The lock was released successfully.
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
Definition Local.cpp:3118
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ NoModRef
The access neither references nor modifies the value stored in memory.
Definition ModRef.h:30
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:85
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
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 MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
LLVM_ABI FunctionPass * createGVNPass()
Definition GVN.cpp:4061
LLVM_ABI bool isPotentiallyReachable(const Instruction *From, const Instruction *To, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet=nullptr, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr, const CycleInfo *CI=nullptr)
Determine whether instruction 'To' is reachable from 'From', without passing through any blocks in Ex...
Definition CFG.cpp:335
DWARFExpression::Operation Op
LLVM_ABI BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
If this edge is a critical edge, insert a new node to split the critical edge.
LLVM_ABI bool isCriticalEdge(const Instruction *TI, unsigned SuccNum, bool AllowIdenticalEdges=false)
Return true if the specified edge is a critical edge.
Definition CFG.cpp:106
constexpr unsigned BitWidth
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
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:305
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI bool EliminateDuplicatePHINodes(BasicBlock *BB)
Check for and eliminate duplicate PHI nodes in this block.
Definition Local.cpp:1522
bool isStrongerThan(AtomicOrdering AO, AtomicOrdering Other)
Returns true if ao is stronger than other as defined by the AtomicOrdering lattice,...
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:285
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
static bool isEqual(const GVNPass::Expression &LHS, const GVNPass::Expression &RHS)
Definition GVN.cpp:188
static unsigned getHashValue(const GVNPass::Expression &E)
Definition GVN.cpp:182
An information struct used to provide DenseMap with the various necessary components for a given valu...
A set of parameters to control various transforms performed by GVN pass.
Definition GVN.h:73
Represents an AvailableValue which can be rematerialized at the end of the associated BasicBlock.
Definition GVN.cpp:294
Value * MaterializeAdjustedValue(LoadInst *Load) const
Emit code at the end of this block to adjust the value defined here to the specified type.
Definition GVN.cpp:319
static AvailableValueInBlock get(BasicBlock *BB, Value *V, unsigned Offset=0)
Definition GVN.cpp:308
AvailableValue AV
AV - The actual available value.
Definition GVN.cpp:299
static AvailableValueInBlock getUndef(BasicBlock *BB)
Definition GVN.cpp:313
BasicBlock * BB
BB - The basic block in question.
Definition GVN.cpp:296
static AvailableValueInBlock get(BasicBlock *BB, AvailableValue &&AV)
Definition GVN.cpp:301
Represents a particular available value that we know how to materialize.
Definition GVN.cpp:198
static AvailableValue getUndef()
Definition GVN.cpp:243
unsigned Offset
Offset - The byte offset in Val that is interesting for the load query.
Definition GVN.cpp:215
ValType Kind
Kind of the live-out value.
Definition GVN.cpp:212
bool isCoercedLoadValue() const
Definition GVN.cpp:262
Value * getSimpleValue() const
Definition GVN.cpp:267
LoadInst * getCoercedLoadValue() const
Definition GVN.cpp:272
bool isSelectValue() const
Definition GVN.cpp:265
Value * Val
Val - The value that is live out of the block.
Definition GVN.cpp:210
static AvailableValue getSelect(Value *Cond, Value *V1, Value *V2)
Definition GVN.cpp:251
static AvailableValue get(Value *V, unsigned Offset=0)
Definition GVN.cpp:219
static AvailableValue getMI(MemIntrinsic *MI, unsigned Offset=0)
Definition GVN.cpp:227
bool isSimpleValue() const
Definition GVN.cpp:261
bool isUndefValue() const
Definition GVN.cpp:264
Value * getSelectCondition() const
Definition GVN.cpp:282
static AvailableValue getLoad(LoadInst *Load, unsigned Offset=0)
Definition GVN.cpp:235
MemIntrinsic * getMemIntrinValue() const
Definition GVN.cpp:277
Value * MaterializeAdjustedValue(LoadInst *Load, Instruction *InsertPt) const
Emit code at the specified insertion point to adjust the value defined here to the specified type.
Definition GVN.cpp:1135
bool isMemIntrinValue() const
Definition GVN.cpp:263
Value * V1
V1, V2 - The dominating non-clobbered values of SelectVal.
Definition GVN.cpp:217
bool operator==(const Expression &Other) const
Definition GVN.cpp:160
friend hash_code hash_value(const Expression &Value)
Definition GVN.cpp:175
SmallVector< uint32_t, 4 > VarArgs
Definition GVN.cpp:154
AttributeList Attrs
Definition GVN.cpp:156
Expression(uint32_t Op=~2U)
Definition GVN.cpp:158
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition PassManager.h:89