93#define DEBUG_TYPE "gvn"
95STATISTIC(NumGVNInstr,
"Number of instructions deleted");
97STATISTIC(NumGVNPRE,
"Number of instructions PRE'd");
99STATISTIC(NumGVNSimpl,
"Number of instructions simplified");
100STATISTIC(NumGVNEqProp,
"Number of equalities propagated");
104 "Number of loads moved to predecessor of a critical edge in PRE");
106STATISTIC(IsValueFullyAvailableInBlockNumSpeculationsMax,
107 "Number of blocks speculated as available in "
108 "IsValueFullyAvailableInBlock(), max");
110 "Number of times we we reached gvn-max-block-speculations cut-off "
111 "preventing further exploration");
134 if ((!
Attrs.isEmpty() || !
Other.Attrs.isEmpty()) &&
135 !
Attrs.intersectWith(
Ty->getContext(),
Other.Attrs).has_value())
173 struct LeaderListNode {
174 LeaderTableEntry Entry;
175 LeaderListNode *
Next;
179 DenseMap<uint32_t, LeaderListNode> NumToLeaders;
184 const LeaderListNode *Current;
195 assert(Current &&
"Dereferenced end of leader list!");
196 Current = Current->Next;
200 return Current ==
Other.Current;
203 return Current !=
Other.Current;
209 auto I = NumToLeaders.find(
N);
210 if (
I == NumToLeaders.end()) {
224 for (
auto &[
_, HeadNode] : NumToLeaders) {
225 LeaderListNode *
N = HeadNode.Next;
227 auto *
Next =
N->Next;
228 N->~LeaderListNode();
232 NumToLeaders.clear();
233 TableAllocator.Reset();
244 const ScalarOptions *Opts =
nullptr;
270 friend class ::GVNLegacyPass;
295 bool InvalidBlockRPONumbers =
true;
318 struct ReachingMemVal {
327 const Value *SelTrueAddr =
nullptr;
328 const Value *SelFalseAddr =
nullptr;
332 return {DepKind::Other, BB, Addr, Inst, -1};
335 static ReachingMemVal getDef(
const Value *Addr, Instruction *Inst) {
336 return {DepKind::Def, Inst->getParent(), Addr, Inst, -1};
339 static ReachingMemVal getClobber(
const Value *Addr, Instruction *Inst,
340 int32_t Offset = -1) {
341 return {DepKind::Clobber, Inst->getParent(), Addr, Inst, Offset};
344 static ReachingMemVal getSelect(BasicBlock *BB, SelectInst *Sel,
345 const Value *TrueAddr,
346 const Value *FalseAddr) {
347 return {DepKind::Select, BB,
nullptr,
nullptr, -1, Sel,
348 TrueAddr, FalseAddr};
352 struct DependencyBlockInfo {
353 DependencyBlockInfo() =
delete;
354 DependencyBlockInfo(
const PHITransAddr &Addr, MemoryAccess *ClobberMA)
355 : Addr(Addr), InitialClobberMA(ClobberMA), ClobberMA(ClobberMA),
358 MemoryAccess *InitialClobberMA;
359 MemoryAccess *ClobberMA;
360 std::optional<ReachingMemVal> MemVal;
361 bool ForceUnknown : 1;
365 using DependencyBlockSet = DenseMap<BasicBlock *, DependencyBlockInfo>;
367 std::optional<GVNPassImpl::ReachingMemVal> scanMemoryAccessesUsers(
368 const MemoryLocation &Loc,
bool IsInvariantLoad, BasicBlock *BB,
369 const SmallVectorImpl<MemoryAccess *> &ClobbersList,
MemorySSA &MSSA,
370 BatchAAResults &AA, LoadInst *L =
nullptr);
372 std::optional<GVNPassImpl::ReachingMemVal>
373 accessMayModifyLocation(MemoryAccess *ClobberMA,
const MemoryLocation &Loc,
374 Align LoadAlign,
bool IsInvariantLoad, BasicBlock *BB,
377 bool collectPredecessors(BasicBlock *BB,
const PHITransAddr &Addr,
378 MemoryAccess *ClobberMA, DependencyBlockSet &Blocks,
379 SmallVectorImpl<BasicBlock *> &Worklist);
381 void collectClobberList(SmallVectorImpl<MemoryAccess *> &Clobbers,
382 BasicBlock *BB,
const DependencyBlockInfo &StartInfo,
383 const DependencyBlockSet &Blocks,
MemorySSA &MSSA);
385 bool findReachingValuesForLoad(LoadInst *Inst,
386 SmallVectorImpl<ReachingMemVal> &
Values,
390 bool processLoad(LoadInst *L);
391 bool processMaskedLoad(IntrinsicInst *
I);
392 bool processNonLocalLoad(LoadInst *L);
393 bool processNonLocalLoad(LoadInst *L, SmallVectorImpl<ReachingMemVal> &Deps);
394 bool processAssumeIntrinsic(AssumeInst *
II);
398 std::optional<AvailableValue>
399 analyzeLoadAvailability(LoadInst *
Load,
const ReachingMemVal &Dep,
406 std::optional<AvailableValue>
407 analyzeSelectAvailability(LoadInst *
Load, SelectInst *Sel,
Value *TrueAddr,
408 Value *FalseAddr, Instruction *From);
413 void analyzeLoadAvailability(LoadInst *
Load,
414 SmallVectorImpl<ReachingMemVal> &Deps,
415 AvailValInBlkVect &ValuesPerBlock,
416 UnavailBlkVect &UnavailableBlocks);
420 LoadInst *findLoadToHoistIntoPred(BasicBlock *
Pred, BasicBlock *LoadBB,
423 bool performLoadPRE(LoadInst *
Load, AvailValInBlkVect &ValuesPerBlock,
424 UnavailBlkVect &UnavailableBlocks);
429 bool performLoopLoadPRE(LoadInst *
Load, AvailValInBlkVect &ValuesPerBlock,
430 UnavailBlkVect &UnavailableBlocks);
434 void eliminatePartiallyRedundantLoad(
435 LoadInst *
Load, AvailValInBlkVect &ValuesPerBlock,
436 MapVector<BasicBlock *, Value *> &AvailableLoads,
437 MapVector<BasicBlock *, LoadInst *> *CriticalEdgePredAndLoad);
440 bool processInstruction(Instruction *
I);
441 bool processBlock(BasicBlock *BB);
442 bool replaceWithEquivalentCmp(CmpInst *Cmp);
445 bool performScalarPRE(Instruction *
I);
446 bool performScalarPREInsertion(Instruction *Instr, BasicBlock *
Pred,
447 BasicBlock *Curr,
unsigned int ValNo);
448 Value *findLeader(
const BasicBlock *BB, uint32_t Num);
449 void cleanupGlobalSets();
450 void removeInstruction(Instruction *
I);
451 void verifyRemoved(
const Instruction *
I)
const;
452 bool splitCriticalEdges();
453 BasicBlock *splitCriticalEdges(BasicBlock *
Pred, BasicBlock *Succ);
456 const std::variant<BasicBlockEdge, Instruction *> &Root);
457 bool processFoldableCondBr(CondBrInst *BI);
458 void addDeadBlock(BasicBlock *BB);
459 void assignValNumForDeadCode();
494 Res.
Kind = ValType::SimpleVal;
502 Res.
Kind = ValType::MemIntrin;
510 Res.
Kind = ValType::LoadVal;
518 Res.
Kind = ValType::UndefVal;
527 Res.
Kind = ValType::SelectVal;
579 Res.
AV = std::move(
AV);
595 return AV.MaterializeAdjustedValue(
Load,
BB->getTerminator());
606 E.Opcode =
I->getOpcode();
611 E.VarArgs.push_back(
lookupOrAdd(GCR->getOperand(0)));
612 E.VarArgs.push_back(
lookupOrAdd(GCR->getBasePtr()));
613 E.VarArgs.push_back(
lookupOrAdd(GCR->getDerivedPtr()));
615 for (
Use &
Op :
I->operands())
618 if (
I->isCommutative()) {
623 assert(
I->getNumOperands() >= 2 &&
"Unsupported commutative instruction!");
624 if (
E.VarArgs[0] >
E.VarArgs[1])
626 E.Commutative =
true;
630 E.VarArgs.append(IVI->idx_begin(), IVI->idx_end());
632 ArrayRef<int> ShuffleMask = SVI->getShuffleMask();
633 E.VarArgs.append(ShuffleMask.
begin(), ShuffleMask.
end());
635 E.Attrs = CB->getAttributes();
644 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
645 "Not a comparison!");
652 if (
E.VarArgs[0] >
E.VarArgs[1]) {
656 E.Opcode = (Opcode << 8) | Predicate;
657 E.Commutative =
true;
663 assert(EI &&
"Not an ExtractValueInst?");
692 Type *PtrTy =
GEP->getType()->getScalarType();
693 const DataLayout &
DL =
GEP->getDataLayout();
694 unsigned BitWidth =
DL.getIndexTypeSizeInBits(PtrTy);
695 SmallMapVector<Value *, APInt, 4> VariableOffsets;
697 if (
GEP->collectOffset(
DL,
BitWidth, VariableOffsets, ConstantOffset)) {
701 E.Opcode =
GEP->getOpcode();
704 for (
const auto &[
V, Scale] : VariableOffsets) {
708 if (!ConstantOffset.isZero())
714 E.Opcode =
GEP->getOpcode();
715 E.Ty =
GEP->getSourceElementType();
716 for (Use &
Op :
GEP->operands())
734 ValueNumbering.insert(std::make_pair(V, Num));
736 NumberingPhi[Num] = PN;
746 assert(MSSA &&
"addMemoryStateToExp should not be called without MemorySSA");
760 if (
C->getFunction()->isPresplitCoroutine()) {
761 ValueNumbering[
C] = NextValueNumber;
762 return NextValueNumber++;
768 if (
C->isConvergent()) {
769 ValueNumbering[
C] = NextValueNumber;
770 return NextValueNumber++;
776 if (
C->hasOperandBundles()) {
777 ValueNumbering[
C] = NextValueNumber;
778 return NextValueNumber++;
781 if (AA->doesNotAccessMemory(
C)) {
783 uint32_t
E = assignExpNewValueNum(Exp).first;
784 ValueNumbering[
C] =
E;
788 if (MD && AA->onlyReadsMemory(
C)) {
790 auto [
E, IsValNumNew] = assignExpNewValueNum(Exp);
792 ValueNumbering[
C] =
E;
796 MemDepResult LocalDep = MD->getDependency(
C);
799 ValueNumbering[
C] = NextValueNumber;
800 return NextValueNumber++;
803 if (LocalDep.
isDef()) {
808 if (!LocalDepCall || LocalDepCall->
arg_size() !=
C->arg_size()) {
809 ValueNumbering[
C] = NextValueNumber;
810 return NextValueNumber++;
813 for (
unsigned I = 0,
E =
C->arg_size();
I <
E; ++
I) {
816 if (CVN != LocalDepCallVN) {
817 ValueNumbering[
C] = NextValueNumber;
818 return NextValueNumber++;
823 ValueNumbering[
C] =
V;
829 MD->getNonLocalCallDependency(
C);
831 CallInst *CDep =
nullptr;
835 for (
const NonLocalDepEntry &
I : Deps) {
836 if (
I.getResult().isNonLocal())
841 if (!
I.getResult().isDef() || CDep !=
nullptr) {
848 if (NonLocalDepCall && DT->properlyDominates(
I.getBB(),
C->getParent())) {
849 CDep = NonLocalDepCall;
858 ValueNumbering[
C] = NextValueNumber;
859 return NextValueNumber++;
863 ValueNumbering[
C] = NextValueNumber;
864 return NextValueNumber++;
866 for (
unsigned I = 0,
E =
C->arg_size();
I <
E; ++
I) {
870 ValueNumbering[
C] = NextValueNumber;
871 return NextValueNumber++;
876 ValueNumbering[
C] =
V;
880 if (MSSA && IsMSSAEnabled && AA->onlyReadsMemory(
C)) {
882 addMemoryStateToExp(
C, Exp);
883 auto [
V,
_] = assignExpNewValueNum(Exp);
884 ValueNumbering[
C] =
V;
888 ValueNumbering[
C] = NextValueNumber;
889 return NextValueNumber++;
893uint32_t GVNValueTable::computeLoadStoreVN(
Instruction *
I) {
894 if (!MSSA || !IsMSSAEnabled) {
895 ValueNumbering[
I] = NextValueNumber;
896 return NextValueNumber++;
900 Exp.Ty =
I->getType();
901 Exp.Opcode =
I->getOpcode();
902 for (Use &
Op :
I->operands())
904 addMemoryStateToExp(
I, Exp);
906 auto [
V,
_] = assignExpNewValueNum(Exp);
907 ValueNumbering[
I] =
V;
913 return ValueNumbering.contains(V);
925 auto VI = ValueNumbering.find(V);
926 if (VI != ValueNumbering.end())
931 ValueNumbering[V] = NextValueNumber;
934 return NextValueNumber++;
938 switch (
I->getOpcode()) {
939 case Instruction::Call:
941 case Instruction::FNeg:
942 case Instruction::Add:
943 case Instruction::FAdd:
944 case Instruction::Sub:
945 case Instruction::FSub:
946 case Instruction::Mul:
947 case Instruction::FMul:
948 case Instruction::UDiv:
949 case Instruction::SDiv:
950 case Instruction::FDiv:
951 case Instruction::URem:
952 case Instruction::SRem:
953 case Instruction::FRem:
954 case Instruction::Shl:
955 case Instruction::LShr:
956 case Instruction::AShr:
957 case Instruction::And:
958 case Instruction::Or:
959 case Instruction::Xor:
960 case Instruction::Trunc:
961 case Instruction::ZExt:
962 case Instruction::SExt:
963 case Instruction::FPToUI:
964 case Instruction::FPToSI:
965 case Instruction::UIToFP:
966 case Instruction::SIToFP:
967 case Instruction::FPTrunc:
968 case Instruction::FPExt:
969 case Instruction::PtrToInt:
970 case Instruction::PtrToAddr:
971 case Instruction::IntToPtr:
972 case Instruction::AddrSpaceCast:
973 case Instruction::BitCast:
974 case Instruction::Select:
975 case Instruction::Freeze:
976 case Instruction::ExtractElement:
977 case Instruction::InsertElement:
978 case Instruction::ShuffleVector:
979 case Instruction::InsertValue:
980 case Instruction::BitExtract:
981 case Instruction::BitInsert:
984 case Instruction::ICmp:
985 case Instruction::FCmp:
987 I->getOperand(0),
I->getOperand(1));
989 case Instruction::GetElementPtr:
992 case Instruction::ExtractValue:
995 case Instruction::PHI:
996 ValueNumbering[V] = NextValueNumber;
998 return NextValueNumber++;
999 case Instruction::Load:
1000 case Instruction::Store:
1001 return computeLoadStoreVN(
I);
1003 ValueNumbering[V] = NextValueNumber;
1004 return NextValueNumber++;
1007 uint32_t E = assignExpNewValueNum(Exp).first;
1008 ValueNumbering[V] = E;
1015 auto VI = ValueNumbering.find(V);
1017 assert(VI != ValueNumbering.end() &&
"Value not numbered?");
1020 return (VI != ValueNumbering.end()) ? VI->second : 0;
1030 Expression Exp = createCmpExpr(Opcode, Predicate, LHS, RHS);
1031 return assignExpNewValueNum(Exp).first;
1036 Expression Exp = createCmpExpr(Opcode, Predicate, LHS, RHS);
1037 return ExpressionNumbering.lookup(Exp);
1045 return ExpressionNumbering.lookup(Exp);
1050 ValueNumbering.clear();
1051 ExpressionNumbering.clear();
1052 NumberingPhi.clear();
1053 NumberingBB.clear();
1054 PhiTranslateTable.clear();
1055 NextValueNumber = 1;
1056 Expressions.clear();
1063 uint32_t Num = ValueNumbering.lookup(V);
1064 ValueNumbering.erase(V);
1067 NumberingPhi.erase(Num);
1069 NumberingBB.erase(Num);
1075 assert(!ValueNumbering.contains(V) &&
1076 "Inst still occurs in value numbering map!");
1085 const auto &[It, Inserted] = NumToLeaders.try_emplace(
N, V, BB,
nullptr);
1088 auto *NewSlot = TableAllocator.Allocate<LeaderListNode>();
1089 new (NewSlot) LeaderListNode(V, BB, It->second.Next);
1090 It->second.Next = NewSlot;
1097 auto It = NumToLeaders.find(
N);
1098 if (It == NumToLeaders.end())
1101 LeaderListNode *Prev =
nullptr;
1102 LeaderListNode *Curr = &It->second;
1104 while (Curr && (Curr->Entry.Val !=
I || Curr->Entry.BB != BB)) {
1114 Prev->Next = Curr->Next;
1115 Curr->~LeaderListNode();
1116 TableAllocator.Deallocate<LeaderListNode>(Curr);
1121 NumToLeaders.erase(It);
1124 LeaderListNode *
Next = Curr->Next;
1125 Curr->Entry.Val = std::move(
Next->Entry.Val);
1126 Curr->Entry.BB =
Next->Entry.BB;
1127 Curr->Next =
Next->Next;
1128 Next->~LeaderListNode();
1129 TableAllocator.Deallocate<LeaderListNode>(
Next);
1139 return Options.AllowScalarPRE.value_or(Opts->enable_scalar_pre);
1143 return Options.AllowLoadPRE.value_or(Opts->enable_load_pre);
1147 return Options.AllowLoadInLoopPRE.value_or(Opts->enable_load_in_loop_pre);
1151 return Options.AllowLoadPRESplitBackedge.value_or(
1152 Opts->enable_split_backedge_in_load_pre);
1160 return Options.AllowMemDep.value_or(
false);
1161 return Options.AllowMemDep.value_or(
valueOr(Opts->enable_gvn_memdep,
true));
1165 return Options.AllowMemorySSA.value_or(Opts->enable_gvn_memoryssa);
1187 auto *MemDep = Impl->isMemDepEnabled()
1192 if (Impl->isMemorySSAEnabled() && !MSSA) {
1194 "On-demand computation of MemSSA implies that MemDep is disabled!");
1198 bool Changed = Impl->run(
F, AC, DT,
TLI,
AA, MemDep, LI, &ORE,
1199 MSSA ? &MSSA->getMSSA() :
nullptr);
1214 removeInstruction(
I);
1220 OS, MapClassName2PassName);
1224 if (
Options.AllowScalarPRE != std::nullopt)
1225 OS << (*
Options.AllowScalarPRE ?
"" :
"no-") <<
"scalar-pre;";
1226 if (
Options.AllowLoadPRE != std::nullopt)
1227 OS << (*
Options.AllowLoadPRE ?
"" :
"no-") <<
"load-pre;";
1228 if (
Options.AllowLoadPRESplitBackedge != std::nullopt)
1229 OS << (*
Options.AllowLoadPRESplitBackedge ?
"" :
"no-")
1230 <<
"split-backedge-load-pre;";
1231 if (
Options.AllowMemDep != std::nullopt)
1232 OS << (*
Options.AllowMemDep ?
"" :
"no-") <<
"memdep;";
1233 if (
Options.AllowMemorySSA != std::nullopt)
1234 OS << (*
Options.AllowMemorySSA ?
"" :
"no-") <<
"memoryssa";
1262 std::optional<BasicBlock *> UnavailableBB;
1266 unsigned NumNewNewSpeculativelyAvailableBBs = 0;
1274 while (!Worklist.
empty()) {
1278 std::pair<DenseMap<BasicBlock *, AvailabilityState>::iterator,
bool>
IV =
1286 UnavailableBB = CurrBB;
1297 ++NumNewNewSpeculativelyAvailableBBs;
1299 NumNewNewSpeculativelyAvailableBBs > Opts.gvn_max_block_speculations;
1304 MaxBBSpeculationCutoffReachedTimes += (int)OutOfBudget;
1306 UnavailableBB = CurrBB;
1312 NewSpeculativelyAvailableBBs.
insert(CurrBB);
1318#if LLVM_ENABLE_STATS
1319 IsValueFullyAvailableInBlockNumSpeculationsMax.updateMax(
1320 NumNewNewSpeculativelyAvailableBBs);
1325 auto MarkAsFixpointAndEnqueueSuccessors =
1327 auto It = FullyAvailableBlocks.
find(BB);
1328 if (It == FullyAvailableBlocks.
end())
1335 State = FixpointState;
1338 "Found a speculatively available successor leftover?");
1346 if (UnavailableBB) {
1353 while (!Worklist.
empty())
1354 MarkAsFixpointAndEnqueueSuccessors(Worklist.
pop_back_val(),
1362 while (!Worklist.
empty())
1363 MarkAsFixpointAndEnqueueSuccessors(Worklist.
pop_back_val(),
1367 "Must have fixed all the new speculatively available blocks.");
1370 return !UnavailableBB;
1382 if (
V.AV.Val == OldValue)
1383 V.AV.Val = NewValue;
1384 if (
V.AV.isSelectValue()) {
1385 if (
V.AV.V1 == OldValue)
1387 if (
V.AV.V2 == OldValue)
1402 if (ValuesPerBlock.
size() == 1 &&
1404 assert(!ValuesPerBlock[0].AV.isUndefValue() &&
1405 "Dead BB dominate this block");
1406 return ValuesPerBlock[0].MaterializeAdjustedValue(
Load);
1417 if (AV.AV.isUndefValue())
1427 if (BB ==
Load->getParent() &&
1428 ((AV.AV.isSimpleValue() && AV.AV.getSimpleValue() ==
Load) ||
1429 (AV.AV.isCoercedLoadValue() && AV.AV.getCoercedLoadValue() ==
Load)))
1446 if (Res->
getType() != LoadTy) {
1461 Load->getFunction());
1472 if (!CoercedLoad->
hasMetadata(LLVMContext::MD_noundef))
1474 {LLVMContext::MD_dereferenceable,
1475 LLVMContext::MD_dereferenceable_or_null,
1476 LLVMContext::MD_invariant_load, LLVMContext::MD_invariant_group,
1477 LLVMContext::MD_alias_scope, LLVMContext::MD_noalias});
1493 assert(
V1 &&
V2 &&
"both value operands of the select must be present");
1507 assert(Res &&
"failed to materialize?");
1513 return II->getIntrinsicID() == Intrinsic::lifetime_start;
1530 Value *PtrOp =
Load->getPointerOperand();
1536 for (
auto *U : PtrOp->
users()) {
1557 for (
auto *U : PtrOp->
users()) {
1560 if (
I->getFunction() ==
Load->getFunction() &&
1568 OtherAccess =
nullptr;
1587 using namespace ore;
1590 R <<
"load of type " << NV(
"Type",
Load->getType()) <<
" not eliminated"
1595 R <<
" in favor of " << NV(
"OtherAccess", OtherAccess);
1597 R <<
" because it is clobbered by " << NV(
"ClobberedBy", DepInst);
1614 for (
auto *Inst = BB == FromBB ? From : BB->getTerminator();
1617 if (++NumVisitedInsts > Opts.gvn_max_num_visited_insts)
1622 if (
SI->isSimple() &&
SI->getPointerOperand() ==
Loc.Ptr &&
1623 SI->getValueOperand()->getType() == LoadTy)
1624 return SI->getValueOperand();
1628 if (LI->getPointerOperand() ==
Loc.Ptr && LI->getType() == LoadTy) {
1636std::optional<AvailableValue>
1641 "Invalid address type of true side of select dependency");
1643 "Invalid address type of false side of select dependency");
1648 bool V1IsLoad =
false, V2IsLoad =
false;
1653 return std::nullopt;
1658 return std::nullopt;
1662std::optional<AvailableValue>
1663GVNPassImpl::analyzeLoadAvailability(
LoadInst *
Load,
const ReachingMemVal &Dep,
1665 assert(
Load->isUnordered() &&
"rules below are incorrect for ordered access");
1666 assert((Dep.Kind == DepKind::Def || Dep.Kind == DepKind::Clobber) &&
1667 "expected a local dependence");
1671 const DataLayout &
DL =
Load->getDataLayout();
1672 if (Dep.Kind == DepKind::Clobber) {
1678 if (
Address &&
Load->isAtomic() <= DepSI->isAtomic()) {
1695 Load->isAtomic() <= DepLoad->isAtomic()) {
1702 DepLoad->getFunction())) {
1703 const auto ClobberOff = MD->getClobberOffset(DepLoad);
1705 Offset = (ClobberOff == std::nullopt || *ClobberOff < 0)
1711 DepLoad->getFunction()) ||
1738 dbgs() <<
" is clobbered by " << *DepInst <<
'\n';);
1742 return std::nullopt;
1744 assert(Dep.Kind == DepKind::Def &&
"follows from above");
1760 return std::nullopt;
1763 if (S->isAtomic() <
Load->isAtomic())
1764 return std::nullopt;
1775 return std::nullopt;
1778 if (
LD->isAtomic() <
Load->isAtomic())
1779 return std::nullopt;
1792 return std::nullopt;
1799 dbgs() <<
" has unknown def " << *DepInst <<
'\n';);
1800 return std::nullopt;
1803void GVNPassImpl::analyzeLoadAvailability(
LoadInst *
Load,
1805 AvailValInBlkVect &ValuesPerBlock,
1806 UnavailBlkVect &UnavailableBlocks) {
1811 for (
const auto &Dep : Deps) {
1814 if (DeadBlocks.count(DepBB)) {
1821 if (Dep.Kind == DepKind::Other) {
1822 UnavailableBlocks.push_back(DepBB);
1829 if (Dep.Kind == DepKind::Select) {
1830 if (
auto AV = analyzeSelectAvailability(
1831 Load, Dep.Sel,
const_cast<Value *
>(Dep.SelTrueAddr),
1833 ValuesPerBlock.push_back(
1836 UnavailableBlocks.push_back(DepBB);
1845 analyzeLoadAvailability(
Load, Dep,
const_cast<Value *
>(Dep.Addr))) {
1849 ValuesPerBlock.push_back(
1852 UnavailableBlocks.push_back(DepBB);
1856 assert(Deps.size() == ValuesPerBlock.size() + UnavailableBlocks.size() &&
1857 "post condition violation");
1883 auto *
Term =
Pred->getTerminator();
1884 if (
Term->getNumSuccessors() != 2 ||
Term->isSpecialTerminator())
1886 auto *SuccBB =
Term->getSuccessor(0);
1887 if (SuccBB == LoadBB)
1888 SuccBB =
Term->getSuccessor(1);
1889 if (!SuccBB->getSinglePredecessor())
1892 unsigned int NumInsts = Opts->gvn_max_num_insns;
1893 for (Instruction &Inst : *SuccBB) {
1896 if (--NumInsts == 0)
1902 bool HasLocalDep =
true;
1904 MemDepResult Dep = MD->getDependency(&Inst);
1907 auto *MSSA = MSSAU->getMemorySSA();
1909 if (
auto *MA = MSSA->getMemoryAccess(&Inst); MA &&
isa<MemoryUse>(MA)) {
1910 auto *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(MA);
1911 HasLocalDep = Clobber->getBlock() == SuccBB;
1919 if (!HasLocalDep && !ICF->isDominatedByICFIFromSameBlock(&Inst))
1930void GVNPassImpl::eliminatePartiallyRedundantLoad(
1934 for (
const auto &AvailableLoad : AvailableLoads) {
1935 BasicBlock *UnavailableBlock = AvailableLoad.first;
1936 Value *LoadPtr = AvailableLoad.second;
1939 new LoadInst(
Load->getType(), LoadPtr,
Load->getName() +
".pre",
1940 Load->getProperties(),
1942 NewLoad->setDebugLoc(
Load->getDebugLoc());
1944 auto *NewAccess = MSSAU->createMemoryAccessInBB(
1947 MSSAU->insertDef(NewDef,
true);
1953 AAMDNodes Tags =
Load->getAAMetadata();
1955 NewLoad->setAAMetadata(Tags);
1957 if (
auto *MD =
Load->getMetadata(LLVMContext::MD_invariant_load))
1958 NewLoad->setMetadata(LLVMContext::MD_invariant_load, MD);
1959 if (
auto *InvGroupMD =
Load->getMetadata(LLVMContext::MD_invariant_group))
1960 NewLoad->setMetadata(LLVMContext::MD_invariant_group, InvGroupMD);
1961 if (
auto *RangeMD =
Load->getMetadata(LLVMContext::MD_range))
1962 NewLoad->setMetadata(LLVMContext::MD_range, RangeMD);
1963 if (
auto *NoFPClassMD =
Load->getMetadata(LLVMContext::MD_nofpclass))
1964 NewLoad->setMetadata(LLVMContext::MD_nofpclass, NoFPClassMD);
1966 if (
auto *AccessMD =
Load->getMetadata(LLVMContext::MD_access_group))
1967 if (LI->getLoopFor(
Load->getParent()) == LI->getLoopFor(UnavailableBlock))
1968 NewLoad->setMetadata(LLVMContext::MD_access_group, AccessMD);
1977 ValuesPerBlock.push_back(
1980 MD->invalidateCachedPointerInfo(LoadPtr);
1985 if (CriticalEdgePredAndLoad) {
1986 auto It = CriticalEdgePredAndLoad->
find(UnavailableBlock);
1987 if (It != CriticalEdgePredAndLoad->
end()) {
1988 ++NumPRELoadMoved2CEPred;
1989 ICF->insertInstructionTo(NewLoad, UnavailableBlock);
1990 LoadInst *OldLoad = It->second;
1994 if (uint32_t ValNo = VN.lookup(OldLoad,
false))
1995 LeaderTable.erase(ValNo, OldLoad, OldLoad->
getParent());
1996 removeInstruction(OldLoad);
2004 ICF->removeUsersOf(
Load);
2005 Load->replaceAllUsesWith(
V);
2009 I->setDebugLoc(
Load->getDebugLoc());
2010 if (MD &&
V->getType()->isPtrOrPtrVectorTy())
2011 MD->invalidateCachedPointerInfo(
V);
2014 <<
"load eliminated by PRE";
2020 AvailValInBlkVect &ValuesPerBlock,
2021 UnavailBlkVect &UnavailableBlocks) {
2030 SmallPtrSet<BasicBlock *, 4> Blockers(
llvm::from_range, UnavailableBlocks);
2052 bool MustEnsureSafetyOfSpeculativeExecution =
2053 ICF->isDominatedByICFIFromSameBlock(
Load);
2057 if (TmpBB == LoadBB)
2059 if (Blockers.count(TmpBB))
2071 MustEnsureSafetyOfSpeculativeExecution =
2072 MustEnsureSafetyOfSpeculativeExecution || ICF->hasICF(TmpBB);
2080 MapVector<BasicBlock *, Value *> PredLoads;
2081 DenseMap<BasicBlock *, AvailabilityState> FullyAvailableBlocks;
2084 for (BasicBlock *UnavailableBB : UnavailableBlocks)
2092 MapVector<BasicBlock *, LoadInst *> CriticalEdgePredAndLoad;
2096 if (
Pred->getTerminator()->isEHPad()) {
2098 dbgs() <<
"COULD NOT PRE LOAD BECAUSE OF AN EH PAD PREDECESSOR '"
2099 <<
Pred->getName() <<
"': " << *
Load <<
'\n');
2107 if (
Pred->getTerminator()->getNumSuccessors() != 1) {
2110 dbgs() <<
"COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
2111 <<
Pred->getName() <<
"': " << *
Load <<
'\n');
2117 dbgs() <<
"COULD NOT PRE LOAD BECAUSE OF AN EH PAD CRITICAL EDGE '"
2118 <<
Pred->getName() <<
"': " << *
Load <<
'\n');
2124 if (DT->dominates(LoadBB,
Pred)) {
2127 <<
"COULD NOT PRE LOAD BECAUSE OF A BACKEDGE CRITICAL EDGE '"
2128 <<
Pred->getName() <<
"': " << *
Load <<
'\n');
2132 if (LoadInst *LI = findLoadToHoistIntoPred(
Pred, LoadBB,
Load))
2133 CriticalEdgePredAndLoad[
Pred] = LI;
2138 PredLoads[
Pred] =
nullptr;
2143 unsigned NumInsertPreds = PredLoads.
size() + CriticalEdgePredSplit.
size();
2144 unsigned NumUnavailablePreds = NumInsertPreds +
2145 CriticalEdgePredAndLoad.
size();
2146 assert(NumUnavailablePreds != 0 &&
2147 "Fully available value should already be eliminated!");
2148 (void)NumUnavailablePreds;
2154 if (NumInsertPreds > 1)
2159 if (MustEnsureSafetyOfSpeculativeExecution) {
2160 if (CriticalEdgePredSplit.
size())
2164 for (
auto &PL : PredLoads)
2168 for (
auto &CEP : CriticalEdgePredAndLoad)
2175 for (BasicBlock *OrigPred : CriticalEdgePredSplit) {
2176 BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
2177 assert(!PredLoads.count(OrigPred) &&
"Split edges shouldn't be in map!");
2178 PredLoads[NewPred] =
nullptr;
2179 LLVM_DEBUG(
dbgs() <<
"Split critical edge " << OrigPred->getName() <<
"->"
2180 << LoadBB->
getName() <<
'\n');
2183 for (
auto &CEP : CriticalEdgePredAndLoad)
2184 PredLoads[CEP.first] =
nullptr;
2187 bool CanDoPRE =
true;
2188 const DataLayout &
DL =
Load->getDataLayout();
2189 SmallVector<Instruction*, 8> NewInsts;
2190 for (
auto &PredLoad : PredLoads) {
2191 BasicBlock *UnavailablePred = PredLoad.first;
2201 Value *LoadPtr =
Load->getPointerOperand();
2203 while (Cur != LoadBB) {
2216 LoadPtr =
Address.translateWithInsertion(LoadBB, UnavailablePred, *DT,
2223 << *
Load->getPointerOperand() <<
"\n");
2228 PredLoad.second = LoadPtr;
2232 while (!NewInsts.
empty()) {
2242 return !CriticalEdgePredSplit.empty();
2250 <<
" INSTS: " << *NewInsts.
back()
2254 for (Instruction *
I : NewInsts) {
2258 I->updateLocationAfterHoist();
2267 eliminatePartiallyRedundantLoad(
Load, ValuesPerBlock, PredLoads,
2268 &CriticalEdgePredAndLoad);
2274 AvailValInBlkVect &ValuesPerBlock,
2275 UnavailBlkVect &UnavailableBlocks) {
2276 const Loop *
L = LI->getLoopFor(
Load->getParent());
2278 if (!L ||
L->getHeader() !=
Load->getParent())
2283 if (!Preheader || !Latch)
2286 Value *LoadPtr =
Load->getPointerOperand();
2288 if (!
L->isLoopInvariant(LoadPtr))
2294 if (ICF->isDominatedByICFIFromSameBlock(
Load))
2298 for (
auto *Blocker : UnavailableBlocks) {
2300 if (!
L->contains(Blocker))
2317 if (
const Loop *Inner = LI->getLoopFor(Blocker); Inner != L) {
2321 while (Inner->getParentLoop() != L)
2322 Inner = Inner->getParentLoop();
2328 ReloadBB = Inner->getUniqueExitBlock();
2329 if (!ReloadBB || LI->getLoopFor(ReloadBB) != L)
2338 if (DT->dominates(ReloadBB, Latch))
2345 LoopBlock = ReloadBB;
2363 MapVector<BasicBlock *, Value *> AvailableLoads;
2364 AvailableLoads[LoopBlock] = LoadPtr;
2365 AvailableLoads[Preheader] = LoadPtr;
2368 eliminatePartiallyRedundantLoad(
Load, ValuesPerBlock, AvailableLoads,
2376 using namespace ore;
2380 <<
"load of type " << NV(
"Type",
Load->getType()) <<
" eliminated"
2381 << setExtraArgs() <<
" in favor of "
2390 if (
Load->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
2391 Load->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
2396 MD->getNonLocalPointerDependency(
Load, Deps);
2401 unsigned NumDeps = Deps.size();
2402 if (NumDeps > Opts->gvn_max_num_deps)
2408 for (
const NonLocalDepResult &Dep : Deps) {
2409 const auto &
R = Dep.getResult();
2410 SelectAddr SelAddr = Dep.getAddress();
2416 ReachingMemVal::getSelect(BB, Sel, Addrs.first, Addrs.second));
2428 return processNonLocalLoad(
Load, MemVals);
2435 if (Deps.
size() == 1 && Deps[0].Kind == DepKind::Other) {
2437 dbgs() <<
" has unknown dependencies\n";);
2445 if (GetElementPtrInst *
GEP =
2447 for (Use &U :
GEP->indices())
2457 AvailValInBlkVect ValuesPerBlock;
2458 UnavailBlkVect UnavailableBlocks;
2459 analyzeLoadAvailability(
Load, Deps, ValuesPerBlock, UnavailableBlocks);
2463 if (ValuesPerBlock.empty())
2471 if (UnavailableBlocks.empty()) {
2477 ICF->removeUsersOf(
Load);
2478 Load->replaceAllUsesWith(
V);
2486 if (
Load->getDebugLoc() &&
Load->getParent() ==
I->getParent())
2487 I->setDebugLoc(
Load->getDebugLoc());
2488 if (MD &&
V->getType()->isPtrOrPtrVectorTy())
2489 MD->invalidateCachedPointerInfo(
V);
2502 if (performLoopLoadPRE(
Load, ValuesPerBlock, UnavailableBlocks) ||
2503 performLoadPRE(
Load, ValuesPerBlock, UnavailableBlocks))
2509bool GVNPassImpl::processAssumeIntrinsic(
AssumeInst *IntrinsicI) {
2513 if (
Cond->isZero()) {
2523 const MemoryUseOrDef *FirstNonDom =
nullptr;
2525 MSSAU->getMemorySSA()->getBlockAccesses(IntrinsicI->
getParent());
2532 for (
const auto &Acc : *AL) {
2534 if (!Current->getMemoryInst()->comesBefore(NewS)) {
2535 FirstNonDom = Current;
2542 FirstNonDom ? MSSAU->createMemoryAccessBefore(
2544 const_cast<MemoryUseOrDef *
>(FirstNonDom))
2545 : MSSAU->createMemoryAccessInBB(
2567 return propagateEquality(
V,
True, IntrinsicI);
2572 I->replaceAllUsesWith(Repl);
2579 Value *PointerOperand = L->getPointerOperand()->stripPointerCasts();
2591 for (
User *U : PointerOperand->
users()) {
2593 if (!
I ||
I == L || !DT.
dominates(
I, MostDominatingInstruction))
2599 if (
I->hasMetadata(LLVMContext::MD_invariant_group) &&
2601 MostDominatingInstruction =
I;
2604 return MostDominatingInstruction != L ? MostDominatingInstruction :
nullptr;
2610static std::optional<MemoryLocation>
2617 switch (
II->getIntrinsicID()) {
2618 case Intrinsic::masked_load:
2620 case Intrinsic::masked_store:
2623 return std::nullopt;
2630 return std::nullopt;
2634 return std::nullopt;
2640std::optional<GVNPassImpl::ReachingMemVal> GVNPassImpl::scanMemoryAccessesUsers(
2646 auto UpdateChoice = [&](std::optional<ReachingMemVal> &Choice,
2650 Choice = ReachingMemVal::getClobber(Loc.
Ptr, Candidate, AR.getOffset());
2652 Choice = ReachingMemVal::getDef(Loc.
Ptr, Candidate);
2660 Choice->Kind = DepKind::Clobber;
2661 Choice->Offset = AR.getOffset();
2663 Choice->Kind = DepKind::Def;
2664 Choice->Offset = -1;
2667 Choice->Inst = Candidate;
2668 Choice->Block = Candidate->getParent();
2671 std::optional<ReachingMemVal> ReachingVal;
2672 for (MemoryAccess *MA : ClobbersList) {
2674 for (User *U : MA->
users()) {
2675 if (++Scanned >= Opts->gvn_scan_users_limit)
2676 return ReachingMemVal::getUnknown(BB, Loc.
Ptr);
2679 if (!UseOrDef || UseOrDef->getBlock() != BB)
2688 AliasResult AR = AA.alias(*MaybeLoc, Loc);
2702 UpdateChoice(ReachingVal, AR, MemI);
2714std::optional<GVNPassImpl::ReachingMemVal> GVNPassImpl::accessMayModifyLocation(
2724 if (
Alloc->getParent() == BB)
2725 return ReachingMemVal::getDef(Loc.
Ptr,
const_cast<AllocaInst *
>(
Alloc));
2726 return ReachingMemVal::getUnknown(BB, Loc.
Ptr);
2730 if (IsInvariantLoad || AA.pointsToConstantMemory(Loc))
2731 return std::nullopt;
2735 return L->getOrdering();
2742 AliasResult AR = AA.alias(*MaybeLoc, Loc);
2744 return ReachingMemVal::getDef(Loc.
Ptr, ClobberI);
2755 return std::nullopt;
2756 return ReachingMemVal::getClobber(Loc.
Ptr, ClobberI);
2761 return std::nullopt;
2767 Opts->gvn_max_num_insns))
2768 return std::nullopt;
2773 return ReachingMemVal::getClobber(Loc.
Ptr, ClobberI);
2778 "Must be the superset/partial overlap case with positive offset");
2779 return ReachingMemVal::getClobber(Loc.
Ptr, ClobberI, AR.
getOffset());
2783 if (
II->getIntrinsicID() == Intrinsic::lifetime_start) {
2785 AliasResult AR = AA.alias(IIObjLoc, Loc);
2787 return ReachingMemVal::getDef(Loc.
Ptr, ClobberI);
2789 return std::nullopt;
2791 return ReachingMemVal::getClobber(Loc.
Ptr, ClobberI);
2799 if (Obj == ClobberI || AA.isMustAlias(ClobberI, Loc.
Ptr))
2800 return ReachingMemVal::getDef(Loc.
Ptr, ClobberI);
2806 return std::nullopt;
2810 ModRefInfo MR = AA.getModRefInfo(ClobberI, Loc);
2814 return std::nullopt;
2818 return ReachingMemVal::getClobber(Loc.
Ptr, ClobberI);
2826 DependencyBlockSet &Blocks,
2837 if (!DT->isReachableFromEntry(
Pred))
2844 PHITransAddr TransAddr = Addr;
2848 auto It = Blocks.find(
Pred);
2849 if (It != Blocks.end()) {
2853 if (It->second.Addr.getAddr() != TransAddr.
getAddr())
2860 Pred, DependencyBlockInfo(TransAddr,
2861 MPhi ? MPhi->getIncomingValueForBlock(
Pred)
2868 for (
auto &
P : Preds) {
2869 [[maybe_unused]]
auto It =
2870 Blocks.try_emplace(
P.first, std::move(
P.second)).first;
2884 const DependencyBlockInfo &StartInfo,
2885 const DependencyBlockSet &Blocks,
2887 MemoryAccess *MA = StartInfo.InitialClobberMA;
2888 MemoryAccess *LastMA = StartInfo.ClobberMA;
2891 while (MA != LastMA) {
2905 BB = DT->getNode(BB)->getIDom()->getBlock();
2909 auto It = Blocks.find(BB);
2910 if (It == Blocks.end())
2913 MA = It->second.InitialClobberMA;
2914 LastMA = It->second.ClobberMA;
2915 if (MA == Clobbers.
back())
2932bool GVNPassImpl::findReachingValuesForLoad(
2935 BatchAAResults AA(AAR, EA);
2937 bool IsInvariantLoad =
L->hasMetadata(LLVMContext::MD_invariant_load);
2943 if (
L->hasMetadata(LLVMContext::MD_invariant_group)) {
2956 if (
auto RMV = scanMemoryAccessesUsers(
2957 Loc, IsInvariantLoad, StartBlock,
2959 Values.emplace_back(*RMV);
2970 accessMayModifyLocation(ClobberMA, Loc,
L->getAlign(),
2971 IsInvariantLoad, StartBlock, MSSA, AA)) {
2972 Values.emplace_back(*RMV);
2982 if (
L->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
2983 L->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
2992 DependencyBlockSet Blocks;
2993 SmallVector<BasicBlock *, 16> InitialWorklist;
2994 const DataLayout &
DL =
L->getDataLayout();
2995 if (!collectPredecessors(StartBlock,
2996 PHITransAddr(
L->getPointerOperand(),
DL, AC),
2997 ClobberMA, Blocks, InitialWorklist))
3001 auto Worklist = InitialWorklist;
3002 while (!Worklist.
empty()) {
3004 if (Blocks.size() > Opts->gvn_max_num_reaching_blocks)
3007 DependencyBlockInfo &
Info = Blocks.find(BB)->second;
3010 if (!
Info.Addr.getAddr())
3020 accessMayModifyLocation(
Info.ClobberMA, BBLoc,
L->getAlign(),
3021 IsInvariantLoad, BB, MSSA, AA)) {
3026 "LiveOnEntry aliases everything");
3042 if (BB == StartBlock &&
Info.Addr.getAddr() !=
L->getPointerOperand()) {
3043 Info.ForceUnknown =
true;
3046 if (BB != StartBlock &&
3047 !collectPredecessors(BB,
Info.Addr,
Info.ClobberMA, Blocks, Worklist))
3048 Info.ForceUnknown =
true;
3058 Worklist = InitialWorklist;
3059 for (BasicBlock *BB : Worklist) {
3060 DependencyBlockInfo &
Info = Blocks.find(BB)->second;
3061 Info.Visited =
true;
3065 while (!Worklist.empty()) {
3066 auto *BB = Worklist.pop_back_val();
3067 DependencyBlockInfo &
Info = Blocks.find(BB)->second;
3071 if (!
Info.Addr.getAddr()) {
3072 Values.push_back(ReachingMemVal::getUnknown(BB,
nullptr));
3077 collectClobberList(Clobbers, BB, Info, Blocks, MSSA);
3080 IsInvariantLoad, BB, Clobbers, MSSA, AA)) {
3092 if (
Info.ForceUnknown) {
3093 Values.push_back(ReachingMemVal::getUnknown(BB,
Info.Addr.getAddr()));
3099 auto It = Blocks.find(
Pred);
3100 if (It == Blocks.end())
3102 DependencyBlockInfo &PredInfo = It->second;
3103 if (PredInfo.Visited)
3105 PredInfo.Visited =
true;
3106 Worklist.push_back(
Pred);
3115bool GVNPassImpl::processLoad(
LoadInst *L) {
3120 if (!
L->isUnordered())
3123 if (
L->getType()->isTokenLikeTy())
3126 if (
L->use_empty()) {
3131 ReachingMemVal MemVal = ReachingMemVal::getUnknown(
nullptr,
nullptr);
3134 MemDepResult Dep = MD->getDependency(L);
3138 return processNonLocalLoad(L);
3142 MemVal = ReachingMemVal::getDef(
L->getPointerOperand(), Dep.
getInst());
3145 ReachingMemVal::getClobber(
L->getPointerOperand(), Dep.
getInst());
3148 if (!findReachingValuesForLoad(L, MemVals, *MSSAU->getMemorySSA(), *AA))
3150 assert(MemVals.
size() &&
"Expected at least an unknown value");
3151 if (MemVals.
size() > 1 || MemVals[0].Block !=
L->getParent())
3152 return processNonLocalLoad(L, MemVals);
3154 MemVal = MemVals[0];
3157 if (MemVal.Kind == DepKind::Other) {
3161 dbgs() <<
"GVN: load ";
L->printAsOperand(
dbgs());
3162 dbgs() <<
" has unknown dependence\n";);
3166 auto AV = analyzeLoadAvailability(L, MemVal,
L->getPointerOperand());
3173 ICF->removeUsersOf(L);
3176 MSSAU->removeMemoryAccess(L);
3190 BatchAAResults BatchAA(*AA);
3197 MemDepResult Dep = MD->getDependency(
I);
3202 auto *MSSA = MSSAU->getMemorySSA();
3208 Def->getBlock() !=
I->getParent())
3210 DepInst = Def->getMemoryInst();
3214 Value *Passthrough =
I->getOperand(2);
3218 StoreVal->
getType() !=
I->getType())
3223 MemoryLocation StoreLoc =
3225 if (!BatchAA.isMustAlias(StoreLoc, LoadLoc))
3233 ICF->removeUsersOf(
I);
3234 I->replaceAllUsesWith(OpToForward);
3242std::pair<uint32_t, bool> GVNValueTable::assignExpNewValueNum(
Expression &Exp) {
3243 uint32_t &
E = ExpressionNumbering[
Exp];
3244 bool CreateNewValNum = !
E;
3245 if (CreateNewValNum) {
3246 Expressions.push_back(Exp);
3247 if (ExprIdx.size() < NextValueNumber + 1)
3248 ExprIdx.resize(NextValueNumber * 2);
3249 E = NextValueNumber;
3250 ExprIdx[NextValueNumber++] = NextExprNumber++;
3252 return {
E, CreateNewValNum};
3257bool GVNValueTable::areAllValsInBB(uint32_t Num,
const BasicBlock *BB,
3261 [=](
const GVNLeaderMap::LeaderTableEntry &L) { return L.BB == BB; });
3268 auto FindRes = PhiTranslateTable.find({Num, Pred});
3269 if (FindRes != PhiTranslateTable.end())
3270 return FindRes->second;
3271 uint32_t NewNum = phiTranslateImpl(Pred, PhiBlock, Num, LeaderTable);
3272 PhiTranslateTable.insert({{Num, Pred}, NewNum});
3284 for (
const auto &Entry : Leaders) {
3286 if (
Call &&
Call->getParent() == PhiBlock)
3290 if (
AA->doesNotAccessMemory(
Call))
3293 if (!MD || !
AA->onlyReadsMemory(
Call))
3305 if (
D.getResult().isNonFuncLocal())
3319 if (PHINode *PN = NumberingPhi[Num]) {
3320 if (PN->getParent() != PhiBlock)
3322 for (
unsigned I = 0;
I != PN->getNumIncomingValues(); ++
I) {
3323 if (PN->getIncomingBlock(
I) !=
Pred)
3325 if (uint32_t TransVal =
lookup(PN->getIncomingValue(
I),
false))
3331 if (BasicBlock *BB = NumberingBB[Num]) {
3332 assert(MSSA &&
"NumberingBB is non-empty only when using MemorySSA");
3338 MemoryPhi *MPhi = MSSA->getMemoryAccess(BB);
3345 if (MSSA->isLiveOnEntryDef(MA))
3350 "CFG/MemorySSA mismatch: predecessor not found among incoming blocks");
3356 if (!areAllValsInBB(Num, PhiBlock, LeaderTable))
3359 if (Num >= ExprIdx.size() || ExprIdx[Num] == 0)
3363 for (
unsigned I = 0;
I <
Exp.VarArgs.size();
I++) {
3367 if ((
I > 1 &&
Exp.Opcode == Instruction::InsertValue) ||
3368 (
I > 0 &&
Exp.Opcode == Instruction::ExtractValue) ||
3369 (
I > 1 &&
Exp.Opcode == Instruction::ShuffleVector))
3374 if (
Exp.Commutative) {
3375 assert(
Exp.VarArgs.size() >= 2 &&
"Unsupported commutative instruction!");
3376 if (
Exp.VarArgs[0] >
Exp.VarArgs[1]) {
3378 uint32_t Opcode =
Exp.Opcode >> 8;
3379 if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp)
3380 Exp.Opcode = (Opcode << 8) |
3386 if (uint32_t NewNum = ExpressionNumbering[Exp]) {
3392 if (!IsMSSAEnabled &&
Exp.Opcode == Instruction::Call && NewNum != Num)
3393 return areCallValsEqual(Num, NewNum,
Pred, PhiBlock, LeaderTable) ? NewNum
3405 PhiTranslateTable.erase({Num, Pred});
3415 if (Leaders.empty())
3418 Value *Val =
nullptr;
3419 for (
const auto &Entry : Leaders) {
3442 "No edge between these basic blocks!");
3443 return Pred !=
nullptr;
3446void GVNPassImpl::assignBlockRPONumber(
Function &
F) {
3447 BlockRPONumber.clear();
3448 uint32_t NextBlockNumber = 1;
3449 ReversePostOrderTraversal<Function *> RPOT(&
F);
3450 for (BasicBlock *BB : RPOT)
3451 BlockRPONumber[BB] = NextBlockNumber++;
3452 InvalidBlockRPONumbers =
false;
3460bool GVNPassImpl::propagateEquality(
3462 const std::variant<BasicBlockEdge, Instruction *> &Root) {
3464 SmallDenseSet<std::pair<Value *, Value *>, 4> Visited;
3468 if (
const BasicBlockEdge *
Edge = std::get_if<BasicBlockEdge>(&Root)) {
3475 for (
const auto *Node : DT->getNode(
I->getParent())->children())
3479 while (!Worklist.
empty()) {
3480 std::pair<Value*, Value*> Item = Worklist.
pop_back_val();
3481 LHS = Item.first;
RHS = Item.second;
3495 const DataLayout &
DL =
3504 uint32_t LVN = VN.lookupOrAdd(
LHS);
3509 uint32_t RVN = VN.lookupOrAdd(
RHS);
3516 if (!Visited.
insert({LHS, RHS}).second)
3529 for (
const BasicBlock *BB : DominatedBlocks)
3530 LeaderTable.insert(LVN,
RHS, BB);
3537 auto CanReplacePointersCallBack = [&
DL](
const Use &
U,
const Value *To) {
3540 unsigned NumReplacements;
3541 if (
const BasicBlockEdge *
Edge = std::get_if<BasicBlockEdge>(&Root))
3543 LHS,
RHS, *DT, *
Edge, CanReplacePointersCallBack);
3546 LHS,
RHS, *DT, std::get<Instruction *>(Root),
3547 CanReplacePointersCallBack);
3549 if (NumReplacements > 0) {
3551 NumGVNEqProp += NumReplacements;
3554 MD->invalidateCachedPointerInfo(
LHS);
3583 bool IsKnownFalse = !IsKnownTrue;
3598 Value *Op0 =
Cmp->getOperand(0), *Op1 =
Cmp->getOperand(1);
3603 if (
Cmp->isEquivalence(IsKnownFalse))
3604 Worklist.
push_back(std::make_pair(Op0, Op1));
3608 Constant *NotVal = ConstantInt::get(
Cmp->getType(), IsKnownFalse);
3612 uint32_t NextNum = VN.getNextUnusedValueNumber();
3613 uint32_t Num = VN.lookupOrAddCmp(
Cmp->getOpcode(), NotPred, Op0, Op1);
3616 if (Num < NextNum) {
3617 for (
const auto &Entry : LeaderTable.getLeaders(Num)) {
3622 if (
const BasicBlockEdge *
Edge = std::get_if<BasicBlockEdge>(&Root)) {
3623 if (!DT->dominates(
Entry.BB,
Edge->getStart()) &&
3624 !DT->dominates(
Edge->getEnd(),
Entry.BB))
3627 auto *InstBB = std::get<Instruction *>(Root)->getParent();
3628 if (!DT->dominates(
Entry.BB, InstBB) &&
3629 !DT->dominates(InstBB,
Entry.BB))
3635 unsigned NumReplacements;
3636 if (
const BasicBlockEdge *
Edge = std::get_if<BasicBlockEdge>(&Root))
3641 NotCmp, NotVal, *DT, std::get<Instruction *>(Root));
3642 Changed |= NumReplacements > 0;
3643 NumGVNEqProp += NumReplacements;
3646 MD->invalidateCachedPointerInfo(NotCmp);
3654 for (
const BasicBlock *BB : DominatedBlocks)
3655 LeaderTable.insert(Num, NotVal, BB);
3664 Worklist.
emplace_back(
A, ConstantInt::get(
A->getType(), IsKnownTrue));
3669 Worklist.
emplace_back(
A, ConstantInt::get(
A->getType(), !IsKnownTrue));
3677bool GVNPassImpl::replaceWithEquivalentCmp(
CmpInst *Cmp) {
3679 uint32_t Num = VN.lookupCmp(
Cmp->getOpcode(),
Pred,
Cmp->getOperand(0),
3680 Cmp->getOperand(1));
3682 return findLeader(
Cmp->getParent(), Num);
3687 if (
Value *Repl = FindCmpLeader(
Cmp->getInversePredicate())) {
3690 Repl, Repl->getName() +
".not",
Cmp->getIterator());
3691 Not->setDebugLoc(
Cmp->getDebugLoc());
3692 Cmp->replaceAllUsesWith(Not);
3699 if (ICmp && ICmp->hasSameSign() && !ICmp->isEquality()) {
3700 if (
Value *Repl = FindCmpLeader(
3717 const DataLayout &
DL =
I->getDataLayout();
3720 if (!
I->use_empty()) {
3723 ICF->removeUsersOf(
I);
3724 I->replaceAllUsesWith(
V);
3732 if (MD &&
V->getType()->isPtrOrPtrVectorTy())
3733 MD->invalidateCachedPointerInfo(
V);
3740 return processAssumeIntrinsic(Assume);
3743 if (processLoad(
Load))
3746 unsigned Num = VN.lookupOrAdd(
Load);
3747 LeaderTable.insert(Num,
Load,
Load->getParent());
3759 return processFoldableCondBr(BI);
3761 Value *BranchCond = BI->getCondition();
3765 if (TrueSucc == FalseSucc)
3772 BasicBlockEdge TrueE(Parent, TrueSucc);
3773 Changed |= propagateEquality(BranchCond, TrueVal, TrueE);
3776 BasicBlockEdge FalseE(Parent, FalseSucc);
3777 Changed |= propagateEquality(BranchCond, FalseVal, FalseE);
3784 Value *SwitchCond =
SI->getCondition();
3789 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
3791 ++SwitchEdges[Succ];
3793 for (
const auto &Case :
SI->cases()) {
3796 if (SwitchEdges.
lookup(Dst) == 1) {
3797 BasicBlockEdge
E(Parent, Dst);
3798 Changed |= propagateEquality(SwitchCond, Case.getCaseValue(),
E);
3806 if (
I->getType()->isVoidTy())
3809 uint32_t NextNum = VN.getNextUnusedValueNumber();
3810 unsigned Num = VN.lookupOrAdd(
I);
3815 LeaderTable.insert(Num,
I,
I->getParent());
3822 const DataLayout &
DL =
I->getDataLayout();
3823 unsigned AS = PTA->getPointerAddressSpace();
3824 if (
DL.getAddressSizeInBits(AS) ==
DL.getPointerSizeInBits(AS) &&
3825 !
DL.hasUnstableRepresentation(AS)) {
3827 VN.lookupPtrToInt(PTA->getPointerOperand(), PTA->getType());
3828 if (
Value *PTI = findLeader(
I->getParent(), PTINum)) {
3840 Value *Repl = Num < NextNum ? findLeader(
I->getParent(), Num) : nullptr;
3846 LeaderTable.insert(Num,
I,
I->getParent());
3859 MD->invalidateCachedPointerInfo(Repl);
3874 Opts->enable_gvn_memoryssa)
3876 "mutually exclusive",
3883 VN.setAliasAnalysis(&RunAA);
3885 ImplicitControlFlowTracking ImplicitCFT;
3894 InvalidBlockRPONumbers =
true;
3895 MemorySSAUpdater Updater(MSSA);
3896 MSSAU = MSSA ? &Updater :
nullptr;
3899 bool ShouldContinue =
true;
3901 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
3913 EarliestEscapeAnalysis RunEA(*DT, &LI);
3914 EA = MSSA ? &RunEA :
nullptr;
3916 unsigned Iteration = 0;
3917 while (ShouldContinue) {
3920 ShouldContinue = iterateOnFunction(
F);
3928 assignValNumForDeadCode();
3929 bool PREChanged =
true;
3930 while (PREChanged) {
3931 PREChanged = performPRE(
F);
3941 cleanupGlobalSets();
3952bool GVNPassImpl::processBlock(
BasicBlock *BB) {
3953 if (DeadBlocks.count(BB))
3956 bool ChangedFunction =
false;
3962 SmallPtrSet<PHINode *, 8> PHINodesToRemove;
3964 for (PHINode *PN : PHINodesToRemove) {
3965 removeInstruction(PN);
3968 ChangedFunction |= processInstruction(&Inst);
3969 return ChangedFunction;
3973bool GVNPassImpl::performScalarPREInsertion(
Instruction *Instr,
3975 unsigned int ValNo) {
3981 for (
unsigned I = 0,
E =
Instr->getNumOperands();
I !=
E; ++
I) {
3989 if (!VN.exists(
Op)) {
3993 uint32_t TValNo = VN.phiTranslate(
Pred, Curr, VN.lookup(
Op), LeaderTable);
4011 ICF->insertInstructionTo(Instr,
Pred);
4013 unsigned Num = VN.lookupOrAdd(Instr);
4017 LeaderTable.insert(Num, Instr,
Pred);
4021bool GVNPassImpl::performScalarPRE(
Instruction *CurInst) {
4047 if (CallB->isInlineAsm())
4051 uint32_t ValNo = VN.lookup(CurInst);
4059 unsigned NumWith = 0;
4060 unsigned NumWithout = 0;
4065 if (InvalidBlockRPONumbers)
4066 assignBlockRPONumber(*CurrentBlock->
getParent());
4072 if (!DT->isReachableFromEntry(
P)) {
4077 assert(BlockRPONumber.count(
P) && BlockRPONumber.count(CurrentBlock) &&
4078 "Invalid BlockRPONumber map.");
4079 if (BlockRPONumber[
P] >= BlockRPONumber[CurrentBlock]) {
4084 uint32_t TValNo = VN.phiTranslate(
P, CurrentBlock, ValNo, LeaderTable);
4085 Value *PredV = findLeader(
P, TValNo);
4090 }
else if (PredV == CurInst) {
4102 if (NumWithout > 1 || NumWith == 0)
4110 if (NumWithout != 0) {
4116 if (ICF->isDominatedByICFIFromSameBlock(CurInst))
4129 ToSplit.push_back(std::make_pair(PREPred->
getTerminator(), SuccNum));
4133 PREInstr = CurInst->
clone();
4134 if (!performScalarPREInsertion(PREInstr, PREPred, CurrentBlock, ValNo)) {
4137 verifyRemoved(PREInstr);
4146 assert(PREInstr !=
nullptr || NumWithout == 0);
4152 CurInst->
getName() +
".pre-phi");
4153 Phi->insertBefore(CurrentBlock->begin());
4154 for (
auto &[
V, BB] : PredMap) {
4159 Phi->addIncoming(
V, BB);
4161 Phi->addIncoming(PREInstr, PREPred);
4167 VN.eraseTranslateCacheEntry(ValNo, *CurrentBlock);
4168 LeaderTable.insert(ValNo, Phi, CurrentBlock);
4171 if (MD &&
Phi->getType()->isPtrOrPtrVectorTy())
4172 MD->invalidateCachedPointerInfo(Phi);
4173 LeaderTable.erase(ValNo, CurInst, CurrentBlock);
4176 removeInstruction(CurInst);
4183bool GVNPassImpl::performPRE(
Function &
F) {
4185 for (BasicBlock *CurrentBlock :
depth_first(&
F.getEntryBlock())) {
4187 if (CurrentBlock == &
F.getEntryBlock())
4191 if (CurrentBlock->isEHPad())
4195 BE = CurrentBlock->end();
4198 Changed |= performScalarPRE(CurInst);
4202 if (splitCriticalEdges())
4216 CriticalEdgeSplittingOptions(DT, LI, MSSAU).unsetPreserveLoopSimplify());
4219 MD->invalidateCachedPredecessors();
4220 InvalidBlockRPONumbers =
true;
4227bool GVNPassImpl::splitCriticalEdges() {
4228 if (ToSplit.empty())
4233 std::pair<Instruction *, unsigned>
Edge = ToSplit.pop_back_val();
4235 CriticalEdgeSplittingOptions(DT, LI, MSSAU)) !=
4237 }
while (!ToSplit.empty());
4240 MD->invalidateCachedPredecessors();
4241 InvalidBlockRPONumbers =
true;
4247bool GVNPassImpl::iterateOnFunction(
Function &
F) {
4248 cleanupGlobalSets();
4255 ReversePostOrderTraversal<Function *> RPOT(&
F);
4257 for (BasicBlock *BB : RPOT)
4263void GVNPassImpl::cleanupGlobalSets() {
4265 LeaderTable.clear();
4266 BlockRPONumber.clear();
4268 InvalidBlockRPONumbers =
true;
4273 if (MD) MD->removeInstruction(
I);
4275 EA->removeInstruction(
I);
4277 MSSAU->removeMemoryAccess(
I);
4281 ICF->removeInstruction(
I);
4282 I->eraseFromParent();
4288void GVNPassImpl::verifyRemoved(
const Instruction *Inst)
const {
4289 VN.verifyRemoved(Inst);
4296void GVNPassImpl::addDeadBlock(
BasicBlock *BB) {
4298 SmallSetVector<BasicBlock *, 4>
DF;
4301 while (!NewDead.
empty()) {
4303 if (DeadBlocks.count(
D))
4307 SmallVector<BasicBlock *, 8> Dom;
4308 DT->getDescendants(
D, Dom);
4309 DeadBlocks.insert_range(Dom);
4312 for (BasicBlock *
B : Dom) {
4314 if (DeadBlocks.count(S))
4317 bool AllPredDead =
true;
4319 if (!DeadBlocks.count(
P)) {
4320 AllPredDead =
false;
4340 for (BasicBlock *
B :
DF) {
4341 if (DeadBlocks.count(
B))
4347 for (BasicBlock *
P : Preds) {
4348 if (!DeadBlocks.count(
P))
4353 if (BasicBlock *S = splitCriticalEdges(
P,
B))
4354 DeadBlocks.insert(
P = S);
4360 if (!DeadBlocks.count(
P))
4362 for (PHINode &Phi :
B->phis()) {
4365 MD->invalidateCachedPointerInfo(&Phi);
4384bool GVNPassImpl::processFoldableCondBr(
CondBrInst *BI) {
4395 if (DeadBlocks.count(DeadRoot))
4399 DeadRoot = splitCriticalEdges(BI->
getParent(), DeadRoot);
4401 addDeadBlock(DeadRoot);
4409void GVNPassImpl::assignValNumForDeadCode() {
4410 for (BasicBlock *BB : DeadBlocks) {
4411 for (Instruction &Inst : *BB) {
4412 unsigned ValNum = VN.lookupOrAdd(&Inst);
4413 LeaderTable.insert(ValNum, &Inst, BB);
4444 MSSAWP ? &MSSAWP->getMSSA() :
nullptr);
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis false
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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
This file provides a data structure for mapping values and expressions to congruence class IDs.
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...
static Instruction * findInvariantGroupValue(LoadInst *L, DominatorTree &DT)
If a load has !invariant.group, try to find the most-dominating load or store with !...
static void reportLoadElim(LoadInst *Load, Value *AvailableValue, OptimizationRemarkEmitter *ORE)
static Value * findDominatingValue(const ScalarOptions &Opts, const MemoryLocation &Loc, Type *LoadTy, Instruction *From, AAResults *AA, bool &IsLoad)
static const Instruction * findMayClobberedPtrAccess(LoadInst *Load, const DominatorTree *DT)
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...
GVNPassImpl::AvailableValue AvailableValue
static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E, DominatorTree *DT)
There is an edge from 'Src' to 'Dst'.
static bool isValueFullyAvailableInBlock(const ScalarOptions &Opts, 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.
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...
static bool isLifetimeStart(const Instruction *Inst)
static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl)
static void replaceValuesPerBlockEntry(SmallVectorImpl< AvailableValueInBlock > &ValuesPerBlock, Value *OldValue, Value *NewValue)
If the specified OldValue exists in ValuesPerBlock, replace its value with NewValue.
GVNPassImpl::AvailableValueInBlock AvailableValueInBlock
@ Unavailable
We know the block is not fully available. This is a fixpoint.
@ Available
We know the block is fully available. This is a fixpoint.
@ SpeculativelyAvailable
We do not know whether the block is fully available or not, but we are currently speculating that it ...
static Value * constructSSAForLoadSet(LoadInst *Load, SmallVectorImpl< AvailableValueInBlock > &ValuesPerBlock, DominatorTree &DT)
Given a set of loads specified by ValuesPerBlock, construct SSA form, allowing us to eliminate Load.
This file provides the interface for LLVM's Global Value Numbering pass which eliminates fully redund...
This is the interface for a simple mod/ref and alias analysis over globals.
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.
SmallVector< MachineOperand, 4 > Cond
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...
uint64_t IntrinsicInst * II
ppc ctr loops PowerPC CTR Loops Verify
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
This file contains the declarations for profiling metadata utility functions.
static DominatorTree getDomTree(Function &F)
std::pair< BasicBlock *, BasicBlock * > Edge
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)
static const uint32_t IV[8]
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
GVNLegacyPass(bool ScalarPRE=true)
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
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.
Value handle that asserts if the Value is deleted.
This represents the llvm.assume intrinsic.
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
const Function * getParent() const
Return the enclosing method, or null if none.
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...
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.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
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.
static LLVM_ABI BinaryOperator * CreateNot(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Value * getArgOperand(unsigned i) const
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
This class is the base class for the comparison instructions.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Conditional Branch instruction.
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.
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.
iterator find(const_arg_type_t< KeyT > Val)
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.
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Analysis pass which computes a DominatorTree.
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.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Context-sensitive CaptureAnalysis provider, which computes and caches the earliest common dominator c...
Class representing an expression and its matching format.
FunctionPass class - This class is used to implement most global optimizations.
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
const BasicBlock & getEntryBlock() const
Represents calls to the gc.relocate intrinsic.
leader_iterator & operator++()
bool operator!=(const leader_iterator &Other) const
leader_iterator(const LeaderListNode *C)
reference operator*() const
const LeaderTableEntry value_type
std::forward_iterator_tag iterator_category
std::ptrdiff_t difference_type
bool operator==(const leader_iterator &Other) const
A mapping from value numbers to lists of Value*'s that have that value number.
LLVM_ABI void insert(uint32_t N, Value *V, const BasicBlock *BB)
Push a new Value to the LeaderTable onto the list for its value number.
LLVM_ABI void erase(uint32_t N, Instruction *I, const BasicBlock *BB)
Scan the list of values corresponding to a given value number, and remove the given instruction if en...
iterator_range< leader_iterator > getLeaders(uint32_t N)
The core GVN pass object.
bool isMemDepEnabled() const
bool isScalarPREEnabled() const
bool isLoadPRESplitBackedgeEnabled() const
MemoryDependenceResults & getMemDep() const
AAResults * getAliasAnalysis() const
void salvageAndRemoveInstruction(Instruction *I)
This removes the specified instruction from our various maps and marks it for deletion.
bool isLoadInLoopPREEnabled() const
bool isLoadPREEnabled() const
bool isMemorySSAEnabled() const
DominatorTree & getDominatorTree() const
GVNPassImpl(llvm::GVNOptions Options={})
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
LLVM_ABI GVNPass(GVNOptions Options={})
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
This class holds the mapping between values and value numbers.
LLVM_ABI uint32_t lookupOrAddCmp(unsigned Opcode, CmpInst::Predicate Pred, Value *LHS, Value *RHS)
Returns the value number of the given comparison, assigning it a new number if it did not have one be...
LLVM_ABI void erase(Value *V)
Remove a value from the value numbering.
LLVM_ABI uint32_t lookup(Value *V, bool Verify=true) const
Returns the value number of the specified value.
LLVM_ABI void add(Value *V, uint32_t Num)
add - Insert a value into the table with a specified value number.
LLVM_ABI void eraseTranslateCacheEntry(uint32_t Num, const BasicBlock &CurrBlock)
Erase stale entry from phiTranslate cache so phiTranslate can be computed again.
LLVM_ABI void verifyRemoved(const Value *) const
verifyRemoved - Verify that the value is removed from all internal data structures.
LLVM_ABI uint32_t phiTranslate(const BasicBlock *BB, const BasicBlock *PhiBlock, uint32_t Num, GVNLeaderMap &LeaderTable)
Wrap phiTranslateImpl to provide caching functionality.
LLVM_ABI uint32_t lookupCmp(unsigned Opcode, CmpInst::Predicate Pred, Value *LHS, Value *RHS)
LLVM_ABI uint32_t lookupOrAdd(MemoryAccess *MA)
LLVM_ABI void clear()
Remove all entries from the ValueTable.
LLVM_ABI bool exists(Value *V) const
Returns true if a value number exists for the specified value.
LLVM_ABI GVNValueTable & operator=(const GVNValueTable &Arg)
LLVM_ABI uint32_t lookupPtrToInt(Value *Ptr, Type *Ty)
Returns the value number of ptrtoint Ptr to \Ty.
LLVM_ABI ~GVNValueTable()
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Legacy wrapper pass to provide the GlobalsAAResult object.
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
This class allows to keep track on instructions with implicit control flow.
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.
LLVM_ABI bool mayWriteToMemory() const LLVM_READONLY
Return true if this instruction may modify memory.
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.
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.
LLVM_ABI bool isIdenticalTo(const Instruction *I) const LLVM_READONLY
Return true if the specified instruction is exactly identical to the current one.
A wrapper class for inspecting calls to intrinsic functions.
An instruction for reading from memory.
Analysis pass that exposes the LoopInfo for a function.
The legacy pass manager's analysis pass to compute loop information.
This class implements a map that also provides access to all stored values in a deterministic order.
iterator find(const KeyT &Key)
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
An analysis that produces MemoryDependenceResults for a function.
Provides a lazy, caching interface for making common memory aliasing information queries,...
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.
BasicBlock * getIncomingBlock(unsigned I) const
Return incoming basic block number i.
MemoryAccess * getIncomingValue(unsigned I) const
Return incoming value number x.
An analysis that produces MemorySSA for a function.
MemoryAccess * getClobberingMemoryAccess(const Instruction *I, BatchAAResults &AA)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
Legacy analysis pass which computes MemorySSA.
Encapsulates MemorySSA, including all data associated with memory accesses.
LLVM_ABI MemorySSAWalker * getSkipSelfWalker()
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
LLVM_ABI MemorySSAWalker * getWalker()
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
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.
MemoryAccess * getDefiningAccess() const
Get the access that produces the memory state used by this Use.
This is an entry in the NonLocalDepInfo cache.
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...
PHITransAddr - An address value which tracks and handles phi translation.
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...
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(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object 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.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Helper class for SSA formation on a set of values defined in multiple blocks.
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< SelectInst *, SelectAddrs > getSelectAndAddrs() const
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getCondition() const
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
const Value * getTrueValue() const
A vector that has set insertion semantics.
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)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
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.
LLVM_ABI bool isTokenLikeTy() const
Returns true if this is 'token' or a token-like target type.s.
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isVoidTy() const
Return true if this is 'void'.
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.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
bool hasOneUse() const
Return true if there is exactly one use of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator_range< user_iterator > users()
bool hasUseList() const
Check if this Value has a use-list.
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...
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
std::pair< iterator, bool > insert(const ValueT &V)
An efficient, type-erasing, non-owning reference to a callable.
An opaque object representing a hash code.
const ParentTy * getParent() const
self_iterator getIterator()
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
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.
@ BasicBlock
Various leaf nodes.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
AllOnesConstantMatch m_AllOnes()
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.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
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.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
Not(const Pred &P) -> Not< Pred >
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.
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
NodeAddr< InstrNode * > Instr
NodeAddr< PhiNode * > Phi
NodeAddr< UseNode * > Use
NodeAddr< NodeBase * > Node
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
hash_code hash_value(const FixedPointSemantics &Val)
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q, SmallVectorImpl< Instruction * > *DropAnnotations=nullptr)
See if we can compute a simplified version of this instruction.
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...
RelativeUniformCounterPtr Values
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...
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.
LLVM_ABI FunctionPass * createGVNPass(bool ScalarPRE)
Create a legacy GVN pass.
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...
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
LLVM_ABI bool isStorePreservingMemoryLocation(const StoreInst *SI, const MemoryLocation &MemLoc, Align MemLocAlign, BatchAAResults &AA, unsigned ScanLimit)
Check whether SI, which may alias MemLoc, can be safely skipped.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
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...
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...
const ScalarOptions & getScalarOptions(const LLVMContext &C)
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
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.
LLVM_ABI bool canReplacePointersInUseIfEqual(const Use &U, const Value *To, const DataLayout &DL)
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...
bool isModSet(const ModRefInfo MRI)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
LLVM_ABI void patchReplacementInstruction(Instruction *I, Value *Repl, bool DoesKMove=false)
Patch the replacement so that it is not more restrictive than the value being replaced.
LLVM_ABI void initializeGVNLegacyPassPass(PassRegistry &)
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
LLVM_ABI Constant * getInitialValueOfAllocation(const Value *V, Type *Ty)
If this is a call to an allocation function that initializes memory to a fixed value,...
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.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
@ 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.
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
@ Ref
The access may reference the value stored in memory.
@ NoModRef
The access neither references nor modifies the value stored in memory.
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()
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...
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.
LLVM_ABI bool willNotFreeBetween(const Instruction *Assume, const Instruction *CtxI, const DominatorTree *DT=nullptr)
Returns true, if no instruction between Assume and CtxI may free (including through synchronization).
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.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
constexpr bool valueOr(BoolOrDefault X, bool Default)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
bool pred_empty(const BasicBlock *BB)
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.
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
LLVM_ABI bool EliminateDuplicatePHINodes(BasicBlock *BB)
Check for and eliminate duplicate PHI nodes in this block.
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.
Implement std::hash so that hash_code can be used in STL containers.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Represents an AvailableValue which can be rematerialized at the end of the associated BasicBlock.
AvailableValue AV
AV - The actual available value.
BasicBlock * BB
BB - The basic block in question.
static AvailableValueInBlock get(BasicBlock *BB, Value *V, unsigned Offset=0)
Value * MaterializeAdjustedValue(LoadInst *Load) const
Emit code at the end of this block to adjust the value defined here to the specified type.
static AvailableValueInBlock getUndef(BasicBlock *BB)
static AvailableValueInBlock get(BasicBlock *BB, AvailableValue &&AV)
Represents a particular available value that we know how to materialize.
bool isMemIntrinValue() const
Value * getSimpleValue() const
SelectInst * getSelectInstr() const
static AvailableValue getUndef()
Value * Val
Val - The value that is live out of the block.
bool V1IsLoad
Whether V1/V2 is the result of a dominating load from the select's address (as opposed to a value for...
ValType Kind
Kind of the live-out value.
bool isCoercedLoadValue() const
static AvailableValue getMI(MemIntrinsic *MI, unsigned Offset=0)
unsigned Offset
Offset - The byte offset in Val that is interesting for the load query.
LoadInst * getCoercedLoadValue() const
static AvailableValue get(Value *V, unsigned Offset=0)
bool isUndefValue() const
static AvailableValue getSelect(SelectInst *Sel, Value *V1, Value *V2, bool V1IsLoad, bool V2IsLoad)
bool isSelectValue() const
Value * V1
V1, V2 - The dominating non-clobbered values of SelectVal.
static AvailableValue getLoad(LoadInst *Load, unsigned Offset=0)
Value * MaterializeAdjustedValue(LoadInst *Load, Instruction *InsertPt) const
Emit code at the specified insertion point to adjust the value defined here to the specified type.
MemIntrinsic * getMemIntrinValue() const
bool isSimpleValue() const
This struct is a compact representation of a valid (non-zero power of two) alignment.
static unsigned getHashValue(const GVNValueTable::Expression &E)
static bool isEqual(const GVNValueTable::Expression &LHS, const GVNValueTable::Expression &RHS)
An information struct used to provide DenseMap with the various necessary components for a given valu...
LeaderTableEntry(Value *V, const BasicBlock *BB)
A set of parameters to control various transforms performed by GVN pass.
Expression(uint32_t Op=~2U)
SmallVector< uint32_t, 4 > VarArgs
bool operator==(const Expression &Other) const
friend hash_code hash_value(const Expression &Value)