83using namespace llvm::gvn;
85using namespace PatternMatch;
87#define DEBUG_TYPE "gvn"
89STATISTIC(NumGVNInstr,
"Number of instructions deleted");
91STATISTIC(NumGVNPRE,
"Number of instructions PRE'd");
93STATISTIC(NumGVNSimpl,
"Number of instructions simplified");
94STATISTIC(NumGVNEqProp,
"Number of equalities propagated");
96STATISTIC(NumPRELoopLoad,
"Number of loop loads PRE'd");
98STATISTIC(IsValueFullyAvailableInBlockNumSpeculationsMax,
99 "Number of blocks speculated as available in "
100 "IsValueFullyAvailableInBlock(), max");
102 "Number of times we we reached gvn-max-block-speculations cut-off "
103 "preventing further exploration");
116 cl::desc(
"Max number of dependences to attempt Load PRE (default = 100)"));
121 cl::desc(
"Max number of blocks we're willing to speculate on (and recurse "
122 "into) when deducing if a value is fully available or not in GVN "
127 cl::desc(
"Max number of visited instructions when trying to find "
128 "dominating value of select dependency (default = 100)"));
259 return cast<LoadInst>(
Val);
264 return cast<MemIntrinsic>(
Val);
269 return cast<SelectInst>(
Val);
290 Res.
AV = std::move(
AV);
321 e.type =
I->getType();
322 e.opcode =
I->getOpcode();
327 e.varargs.push_back(
lookupOrAdd(GCR->getOperand(0)));
328 e.varargs.push_back(
lookupOrAdd(GCR->getBasePtr()));
329 e.varargs.push_back(
lookupOrAdd(GCR->getDerivedPtr()));
331 for (
Use &Op :
I->operands())
334 if (
I->isCommutative()) {
339 assert(
I->getNumOperands() >= 2 &&
"Unsupported commutative instruction!");
340 if (
e.varargs[0] >
e.varargs[1])
342 e.commutative =
true;
345 if (
auto *
C = dyn_cast<CmpInst>(
I)) {
348 if (
e.varargs[0] >
e.varargs[1]) {
352 e.opcode = (
C->getOpcode() << 8) | Predicate;
353 e.commutative =
true;
354 }
else if (
auto *
E = dyn_cast<InsertValueInst>(
I)) {
355 e.varargs.append(
E->idx_begin(),
E->idx_end());
356 }
else if (
auto *SVI = dyn_cast<ShuffleVectorInst>(
I)) {
358 e.varargs.append(ShuffleMask.
begin(), ShuffleMask.
end());
366 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
367 "Not a comparison!");
370 e.varargs.push_back(lookupOrAdd(LHS));
371 e.varargs.push_back(lookupOrAdd(RHS));
374 if (
e.varargs[0] >
e.varargs[1]) {
378 e.opcode = (Opcode << 8) | Predicate;
379 e.commutative =
true;
385 assert(EI &&
"Not an ExtractValueInst?");
396 e.varargs.push_back(lookupOrAdd(WO->
getLHS()));
397 e.varargs.push_back(lookupOrAdd(WO->
getRHS()));
405 e.varargs.push_back(lookupOrAdd(Op));
414 Type *PtrTy =
GEP->getType()->getScalarType();
416 unsigned BitWidth =
DL.getIndexTypeSizeInBits(PtrTy);
420 GEP->collectOffset(
DL,
BitWidth, VariableOffsets, ConstantOffset)) {
424 E.opcode =
GEP->getOpcode();
426 E.varargs.push_back(lookupOrAdd(
GEP->getPointerOperand()));
427 for (
const auto &Pair : VariableOffsets) {
428 E.varargs.push_back(lookupOrAdd(Pair.first));
431 if (!ConstantOffset.isZero())
437 E.opcode =
GEP->getOpcode();
438 E.type =
GEP->getSourceElementType();
439 for (
Use &Op :
GEP->operands())
440 E.varargs.push_back(lookupOrAdd(Op));
449GVNPass::ValueTable::ValueTable() =
default;
450GVNPass::ValueTable::ValueTable(
const ValueTable &) =
default;
451GVNPass::ValueTable::ValueTable(
ValueTable &&) =
default;
452GVNPass::ValueTable::~ValueTable() =
default;
458 valueNumbering.insert(std::make_pair(V, num));
459 if (
PHINode *PN = dyn_cast<PHINode>(V))
460 NumberingPhi[num] = PN;
464 if (AA->doesNotAccessMemory(
C) &&
472 !
C->getFunction()->isPresplitCoroutine()) {
474 uint32_t e = assignExpNewValueNum(exp).first;
475 valueNumbering[
C] = e;
477 }
else if (MD && AA->onlyReadsMemory(
C) &&
485 !
C->getFunction()->isPresplitCoroutine()) {
487 auto ValNum = assignExpNewValueNum(exp);
489 valueNumbering[
C] = ValNum.first;
496 valueNumbering[
C] = nextValueNumber;
497 return nextValueNumber++;
500 if (local_dep.
isDef()) {
505 if (!local_cdep || local_cdep->
arg_size() !=
C->arg_size()) {
506 valueNumbering[
C] = nextValueNumber;
507 return nextValueNumber++;
510 for (
unsigned i = 0, e =
C->arg_size(); i < e; ++i) {
511 uint32_t c_vn = lookupOrAdd(
C->getArgOperand(i));
514 valueNumbering[
C] = nextValueNumber;
515 return nextValueNumber++;
520 valueNumbering[
C] =
v;
533 if (
I.getResult().isNonLocal())
538 if (!
I.getResult().isDef() || cdep !=
nullptr) {
543 CallInst *NonLocalDepCall = dyn_cast<CallInst>(
I.getResult().getInst());
546 cdep = NonLocalDepCall;
555 valueNumbering[
C] = nextValueNumber;
556 return nextValueNumber++;
560 valueNumbering[
C] = nextValueNumber;
561 return nextValueNumber++;
563 for (
unsigned i = 0, e =
C->arg_size(); i < e; ++i) {
564 uint32_t c_vn = lookupOrAdd(
C->getArgOperand(i));
567 valueNumbering[
C] = nextValueNumber;
568 return nextValueNumber++;
573 valueNumbering[
C] =
v;
576 valueNumbering[
C] = nextValueNumber;
577 return nextValueNumber++;
582bool GVNPass::ValueTable::exists(
Value *V)
const {
583 return valueNumbering.count(V) != 0;
590 if (
VI != valueNumbering.end())
593 auto *
I = dyn_cast<Instruction>(V);
595 valueNumbering[V] = nextValueNumber;
596 return nextValueNumber++;
600 switch (
I->getOpcode()) {
601 case Instruction::Call:
602 return lookupOrAddCall(cast<CallInst>(
I));
603 case Instruction::FNeg:
604 case Instruction::Add:
605 case Instruction::FAdd:
606 case Instruction::Sub:
607 case Instruction::FSub:
608 case Instruction::Mul:
609 case Instruction::FMul:
610 case Instruction::UDiv:
611 case Instruction::SDiv:
612 case Instruction::FDiv:
613 case Instruction::URem:
614 case Instruction::SRem:
615 case Instruction::FRem:
616 case Instruction::Shl:
617 case Instruction::LShr:
618 case Instruction::AShr:
619 case Instruction::And:
620 case Instruction::Or:
621 case Instruction::Xor:
622 case Instruction::ICmp:
623 case Instruction::FCmp:
624 case Instruction::Trunc:
625 case Instruction::ZExt:
626 case Instruction::SExt:
627 case Instruction::FPToUI:
628 case Instruction::FPToSI:
629 case Instruction::UIToFP:
630 case Instruction::SIToFP:
631 case Instruction::FPTrunc:
632 case Instruction::FPExt:
633 case Instruction::PtrToInt:
634 case Instruction::IntToPtr:
635 case Instruction::AddrSpaceCast:
636 case Instruction::BitCast:
637 case Instruction::Select:
638 case Instruction::Freeze:
639 case Instruction::ExtractElement:
640 case Instruction::InsertElement:
641 case Instruction::ShuffleVector:
642 case Instruction::InsertValue:
645 case Instruction::GetElementPtr:
646 exp = createGEPExpr(cast<GetElementPtrInst>(
I));
648 case Instruction::ExtractValue:
649 exp = createExtractvalueExpr(cast<ExtractValueInst>(
I));
651 case Instruction::PHI:
652 valueNumbering[V] = nextValueNumber;
653 NumberingPhi[nextValueNumber] = cast<PHINode>(V);
654 return nextValueNumber++;
656 valueNumbering[V] = nextValueNumber;
657 return nextValueNumber++;
660 uint32_t e = assignExpNewValueNum(exp).first;
661 valueNumbering[V] = e;
670 assert(
VI != valueNumbering.end() &&
"Value not numbered?");
673 return (
VI != valueNumbering.end()) ?
VI->second : 0;
680uint32_t GVNPass::ValueTable::lookupOrAddCmp(
unsigned Opcode,
684 return assignExpNewValueNum(exp).first;
688void GVNPass::ValueTable::clear() {
689 valueNumbering.clear();
690 expressionNumbering.clear();
691 NumberingPhi.clear();
692 PhiTranslateTable.clear();
700void GVNPass::ValueTable::erase(
Value *V) {
701 uint32_t Num = valueNumbering.lookup(V);
702 valueNumbering.erase(V);
705 NumberingPhi.erase(Num);
710void GVNPass::ValueTable::verifyRemoved(
const Value *V)
const {
712 I = valueNumbering.begin(),
E = valueNumbering.end();
I !=
E; ++
I) {
713 assert(
I->first != V &&
"Inst still occurs in value numbering map!");
756 bool Changed = runImpl(
F, AC, DT, TLI, AA, MemDep, LI, &ORE,
757 MSSA ? &MSSA->getMSSA() :
nullptr);
773 OS, MapClassName2PassName);
776 if (Options.
AllowPRE != std::nullopt)
777 OS << (*Options.
AllowPRE ?
"" :
"no-") <<
"pre;";
782 <<
"split-backedge-load-pre;";
788#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
792 errs() <<
I.first <<
"\n";
823 std::optional<BasicBlock *> UnavailableBB;
827 unsigned NumNewNewSpeculativelyAvailableBBs = 0;
835 while (!Worklist.
empty()) {
839 std::pair<DenseMap<BasicBlock *, AvailabilityState>::iterator,
bool>
IV =
841 CurrBB, AvailabilityState::SpeculativelyAvailable);
846 if (State == AvailabilityState::Unavailable) {
847 UnavailableBB = CurrBB;
858 ++NumNewNewSpeculativelyAvailableBBs;
864 MaxBBSpeculationCutoffReachedTimes += (int)OutOfBudget;
865 State = AvailabilityState::Unavailable;
866 UnavailableBB = CurrBB;
872 NewSpeculativelyAvailableBBs.
insert(CurrBB);
879 IsValueFullyAvailableInBlockNumSpeculationsMax.updateMax(
880 NumNewNewSpeculativelyAvailableBBs);
885 auto MarkAsFixpointAndEnqueueSuccessors =
887 auto It = FullyAvailableBlocks.
find(BB);
888 if (It == FullyAvailableBlocks.
end())
891 case AvailabilityState::Unavailable:
892 case AvailabilityState::Available:
894 case AvailabilityState::SpeculativelyAvailable:
895 State = FixpointState;
898 "Found a speculatively available successor leftover?");
913 while (!Worklist.
empty())
914 MarkAsFixpointAndEnqueueSuccessors(Worklist.
pop_back_val(),
915 AvailabilityState::Unavailable);
922 while (!Worklist.
empty())
923 MarkAsFixpointAndEnqueueSuccessors(Worklist.
pop_back_val(),
924 AvailabilityState::Available);
927 "Must have fixed all the new speculatively available blocks.");
930 return !UnavailableBB;
942 if (ValuesPerBlock.
size() == 1 &&
944 Load->getParent())) {
945 assert(!ValuesPerBlock[0].AV.isUndefValue() &&
946 "Dead BB dominate this block");
947 return ValuesPerBlock[0].MaterializeAdjustedValue(Load, gvn);
953 SSAUpdate.
Initialize(Load->getType(), Load->getName());
958 if (AV.AV.isUndefValue())
968 if (BB == Load->getParent() &&
969 ((AV.AV.isSimpleValue() && AV.AV.getSimpleValue() == Load) ||
970 (AV.AV.isCoercedLoadValue() && AV.AV.getCoercedLoadValue() == Load)))
984 Type *LoadTy = Load->getType();
985 const DataLayout &
DL = Load->getModule()->getDataLayout();
986 if (isSimpleValue()) {
987 Res = getSimpleValue();
988 if (Res->
getType() != LoadTy) {
992 <<
" " << *getSimpleValue() <<
'\n'
996 }
else if (isCoercedLoadValue()) {
997 LoadInst *CoercedLoad = getCoercedLoadValue();
1009 <<
" " << *getCoercedLoadValue() <<
'\n'
1013 }
else if (isMemIntrinValue()) {
1017 <<
" " << *getMemIntrinValue() <<
'\n'
1020 }
else if (isSelectValue()) {
1023 assert(V1 && V2 &&
"both value operands of the select must be present");
1028 assert(Res &&
"failed to materialize?");
1033 if (
const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
1034 return II->getIntrinsicID() == Intrinsic::lifetime_start;
1054 using namespace ore;
1059 R <<
"load of type " << NV(
"Type", Load->getType()) <<
" not eliminated"
1062 for (
auto *U : Load->getPointerOperand()->users()) {
1063 if (U != Load && (isa<LoadInst>(U) || isa<StoreInst>(U))) {
1064 auto *
I = cast<Instruction>(U);
1065 if (
I->getFunction() == Load->getFunction() && DT->
dominates(
I, Load)) {
1081 for (
auto *U : Load->getPointerOperand()->users()) {
1082 if (U != Load && (isa<LoadInst>(U) || isa<StoreInst>(U))) {
1083 auto *
I = cast<Instruction>(U);
1084 if (
I->getFunction() == Load->getFunction() &&
1092 OtherAccess =
nullptr;
1104 R <<
" in favor of " << NV(
"OtherAccess", OtherAccess);
1106 R <<
" because it is clobbered by " << NV(
"ClobberedBy", DepInfo.
getInst());
1119 for (
auto I = BB == FromBB ?
From->getReverseIterator() : BB->rbegin(),
1128 if (
auto *LI = dyn_cast<LoadInst>(Inst))
1129 if (LI->getPointerOperand() == Loc.
Ptr && LI->getType() == LoadTy)
1135std::optional<AvailableValue>
1138 assert(
Load->isUnordered() &&
"rules below are incorrect for ordered access");
1148 if (
StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
1150 if (
Address &&
Load->isAtomic() <= DepSI->isAtomic()) {
1162 if (
LoadInst *DepLoad = dyn_cast<LoadInst>(DepInst)) {
1166 if (DepLoad != Load &&
Address &&
1167 Load->isAtomic() <= DepLoad->isAtomic()) {
1176 Offset = (ClobberOff == std::nullopt || *ClobberOff < 0)
1190 if (
MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
1203 dbgs() <<
" is clobbered by " << *DepInst <<
'\n';);
1207 return std::nullopt;
1220 if (
StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
1226 return std::nullopt;
1229 if (S->isAtomic() <
Load->isAtomic())
1230 return std::nullopt;
1235 if (
LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
1240 return std::nullopt;
1243 if (
LD->isAtomic() <
Load->isAtomic())
1244 return std::nullopt;
1252 if (
auto *Sel = dyn_cast<SelectInst>(DepInst)) {
1253 assert(Sel->getType() ==
Load->getPointerOperandType());
1259 return std::nullopt;
1264 return std::nullopt;
1272 dbgs() <<
" has unknown def " << *DepInst <<
'\n';);
1273 return std::nullopt;
1276void GVNPass::AnalyzeLoadAvailability(
LoadInst *Load, LoadDepVect &Deps,
1277 AvailValInBlkVect &ValuesPerBlock,
1278 UnavailBlkVect &UnavailableBlocks) {
1283 for (
const auto &Dep : Deps) {
1287 if (DeadBlocks.count(DepBB)) {
1295 UnavailableBlocks.push_back(DepBB);
1302 if (
auto AV = AnalyzeLoadAvailability(Load, DepInfo, Dep.getAddress())) {
1306 ValuesPerBlock.push_back(
1309 UnavailableBlocks.push_back(DepBB);
1313 assert(Deps.size() == ValuesPerBlock.size() + UnavailableBlocks.size() &&
1314 "post condition violation");
1317void GVNPass::eliminatePartiallyRedundantLoad(
1318 LoadInst *Load, AvailValInBlkVect &ValuesPerBlock,
1320 for (
const auto &AvailableLoad : AvailableLoads) {
1321 BasicBlock *UnavailableBlock = AvailableLoad.first;
1322 Value *LoadPtr = AvailableLoad.second;
1326 Load->isVolatile(),
Load->getAlign(),
Load->getOrdering(),
1328 NewLoad->setDebugLoc(
Load->getDebugLoc());
1338 NewLoad, DefiningAcc, NewLoad->getParent(),
1340 if (
auto *NewDef = dyn_cast<MemoryDef>(NewAccess))
1343 MSSAU->
insertUse(cast<MemoryUse>(NewAccess),
true);
1349 NewLoad->setAAMetadata(Tags);
1351 if (
auto *MD =
Load->getMetadata(LLVMContext::MD_invariant_load))
1352 NewLoad->setMetadata(LLVMContext::MD_invariant_load, MD);
1353 if (
auto *InvGroupMD =
Load->getMetadata(LLVMContext::MD_invariant_group))
1354 NewLoad->setMetadata(LLVMContext::MD_invariant_group, InvGroupMD);
1355 if (
auto *RangeMD =
Load->getMetadata(LLVMContext::MD_range))
1356 NewLoad->setMetadata(LLVMContext::MD_range, RangeMD);
1357 if (
auto *AccessMD =
Load->getMetadata(LLVMContext::MD_access_group))
1360 NewLoad->setMetadata(LLVMContext::MD_access_group, AccessMD);
1369 ValuesPerBlock.push_back(
1377 Load->replaceAllUsesWith(V);
1378 if (isa<PHINode>(V))
1381 I->setDebugLoc(
Load->getDebugLoc());
1382 if (
V->getType()->isPtrOrPtrVectorTy())
1387 <<
"load eliminated by PRE";
1391bool GVNPass::PerformLoadPRE(
LoadInst *Load, AvailValInBlkVect &ValuesPerBlock,
1392 UnavailBlkVect &UnavailableBlocks) {
1402 UnavailableBlocks.end());
1424 bool MustEnsureSafetyOfSpeculativeExecution =
1429 if (TmpBB == LoadBB)
1431 if (Blockers.count(TmpBB))
1443 MustEnsureSafetyOfSpeculativeExecution =
1444 MustEnsureSafetyOfSpeculativeExecution || ICF->
hasICF(TmpBB);
1455 FullyAvailableBlocks[AV.BB] = AvailabilityState::Available;
1456 for (
BasicBlock *UnavailableBB : UnavailableBlocks)
1457 FullyAvailableBlocks[UnavailableBB] = AvailabilityState::Unavailable;
1463 if (Pred->getTerminator()->isEHPad()) {
1465 dbgs() <<
"COULD NOT PRE LOAD BECAUSE OF AN EH PAD PREDECESSOR '"
1466 << Pred->getName() <<
"': " << *Load <<
'\n');
1474 if (Pred->getTerminator()->getNumSuccessors() != 1) {
1475 if (isa<IndirectBrInst>(Pred->getTerminator())) {
1477 dbgs() <<
"COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
1478 << Pred->getName() <<
"': " << *Load <<
'\n');
1484 dbgs() <<
"COULD NOT PRE LOAD BECAUSE OF AN EH PAD CRITICAL EDGE '"
1485 << Pred->getName() <<
"': " << *Load <<
'\n');
1494 <<
"COULD NOT PRE LOAD BECAUSE OF A BACKEDGE CRITICAL EDGE '"
1495 << Pred->getName() <<
"': " << *Load <<
'\n');
1502 PredLoads[Pred] =
nullptr;
1507 unsigned NumUnavailablePreds = PredLoads.
size() + CriticalEdgePred.
size();
1508 assert(NumUnavailablePreds != 0 &&
1509 "Fully available value should already be eliminated!");
1510 (void)NumUnavailablePreds;
1516 if (NumUnavailablePreds != 1)
1521 if (MustEnsureSafetyOfSpeculativeExecution) {
1522 if (CriticalEdgePred.
size())
1525 for (
auto &PL : PredLoads)
1532 for (
BasicBlock *OrigPred : CriticalEdgePred) {
1533 BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
1534 assert(!PredLoads.count(OrigPred) &&
"Split edges shouldn't be in map!");
1535 PredLoads[NewPred] =
nullptr;
1536 LLVM_DEBUG(
dbgs() <<
"Split critical edge " << OrigPred->getName() <<
"->"
1537 << LoadBB->
getName() <<
'\n');
1541 bool CanDoPRE =
true;
1544 for (
auto &PredLoad : PredLoads) {
1545 BasicBlock *UnavailablePred = PredLoad.first;
1555 Value *LoadPtr =
Load->getPointerOperand();
1557 while (Cur != LoadBB) {
1570 LoadPtr =
Address.translateWithInsertion(LoadBB, UnavailablePred, *DT,
1577 << *
Load->getPointerOperand() <<
"\n");
1582 PredLoad.second = LoadPtr;
1586 while (!NewInsts.
empty()) {
1596 return !CriticalEdgePred.empty();
1602 LLVM_DEBUG(
dbgs() <<
"GVN REMOVING PRE LOAD: " << *Load <<
'\n');
1604 <<
" INSTS: " << *NewInsts.
back()
1612 I->updateLocationAfterHoist();
1621 eliminatePartiallyRedundantLoad(Load, ValuesPerBlock, PredLoads);
1626bool GVNPass::performLoopLoadPRE(
LoadInst *Load,
1627 AvailValInBlkVect &ValuesPerBlock,
1628 UnavailBlkVect &UnavailableBlocks) {
1634 if (!L ||
L->getHeader() !=
Load->getParent())
1639 if (!Preheader || !Latch)
1642 Value *LoadPtr =
Load->getPointerOperand();
1644 if (!
L->isLoopInvariant(LoadPtr))
1654 for (
auto *Blocker : UnavailableBlocks) {
1656 if (!
L->contains(Blocker))
1680 if (Blocker->getTerminator()->mayWriteToMemory())
1683 LoopBlock = Blocker;
1696 AvailableLoads[LoopBlock] = LoadPtr;
1697 AvailableLoads[Preheader] = LoadPtr;
1699 LLVM_DEBUG(
dbgs() <<
"GVN REMOVING PRE LOOP LOAD: " << *Load <<
'\n');
1700 eliminatePartiallyRedundantLoad(Load, ValuesPerBlock, AvailableLoads);
1707 using namespace ore;
1711 <<
"load of type " << NV(
"Type", Load->getType()) <<
" eliminated"
1712 << setExtraArgs() <<
" in favor of "
1719bool GVNPass::processNonLocalLoad(
LoadInst *Load) {
1721 if (
Load->getParent()->getParent()->hasFnAttribute(
1722 Attribute::SanitizeAddress) ||
1723 Load->getParent()->getParent()->hasFnAttribute(
1724 Attribute::SanitizeHWAddress))
1734 unsigned NumDeps = Deps.size();
1741 !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
1743 dbgs() <<
" has unknown dependencies\n";);
1747 bool Changed =
false;
1750 dyn_cast<GetElementPtrInst>(
Load->getOperand(0))) {
1751 for (
Use &U :
GEP->indices())
1753 Changed |= performScalarPRE(
I);
1757 AvailValInBlkVect ValuesPerBlock;
1758 UnavailBlkVect UnavailableBlocks;
1759 AnalyzeLoadAvailability(Load, Deps, ValuesPerBlock, UnavailableBlocks);
1763 if (ValuesPerBlock.empty())
1771 if (UnavailableBlocks.empty()) {
1772 LLVM_DEBUG(
dbgs() <<
"GVN REMOVING NONLOCAL LOAD: " << *Load <<
'\n');
1776 Load->replaceAllUsesWith(V);
1778 if (isa<PHINode>(V))
1784 if (
Load->getDebugLoc() &&
Load->getParent() ==
I->getParent())
1785 I->setDebugLoc(
Load->getDebugLoc());
1786 if (
V->getType()->isPtrOrPtrVectorTy())
1800 if (performLoopLoadPRE(Load, ValuesPerBlock, UnavailableBlocks) ||
1801 PerformLoadPRE(Load, ValuesPerBlock, UnavailableBlocks))
1816 Cmp->getFastMathFlags().noNaNs())) {
1824 if (isa<ConstantFP>(
LHS) && !cast<ConstantFP>(
LHS)->
isZero())
1826 if (isa<ConstantFP>(
RHS) && !cast<ConstantFP>(
RHS)->
isZero())
1841 Cmp->getFastMathFlags().noNaNs()) ||
1850 if (isa<ConstantFP>(
LHS) && !cast<ConstantFP>(
LHS)->
isZero())
1852 if (isa<ConstantFP>(
RHS) && !cast<ConstantFP>(
RHS)->
isZero())
1862 auto *I = dyn_cast<Instruction>(U);
1863 return I && I->getParent() == BB;
1867bool GVNPass::processAssumeIntrinsic(
AssumeInst *IntrinsicI) {
1871 if (
Cond->isZero()) {
1889 for (
const auto &Acc : *AL) {
1890 if (
auto *Current = dyn_cast<MemoryUseOrDef>(&Acc))
1891 if (!Current->getMemoryInst()->comesBefore(NewS)) {
1892 FirstNonDom = Current;
1908 MSSAU->
insertDef(cast<MemoryDef>(NewDef),
false);
1914 }
else if (isa<Constant>(V)) {
1922 bool Changed =
false;
1929 Changed |= propagateEquality(V, True, Edge,
false);
1935 ReplaceOperandsWithMap[
V] = True;
1957 if (
auto *CmpI = dyn_cast<CmpInst>(V)) {
1959 Value *CmpLHS = CmpI->getOperand(0);
1960 Value *CmpRHS = CmpI->getOperand(1);
1966 if (isa<Constant>(CmpLHS) && !isa<Constant>(CmpRHS))
1968 if (!isa<Instruction>(CmpLHS) && isa<Instruction>(CmpRHS))
1970 if ((isa<Argument>(CmpLHS) && isa<Argument>(CmpRHS)) ||
1971 (isa<Instruction>(CmpLHS) && isa<Instruction>(CmpRHS))) {
1982 if (isa<Constant>(CmpLHS) && isa<Constant>(CmpRHS))
1986 << *CmpLHS <<
" with "
1987 << *CmpRHS <<
" in block "
1993 ReplaceOperandsWithMap[CmpLHS] = CmpRHS;
2006 I->replaceAllUsesWith(Repl);
2011bool GVNPass::processLoad(
LoadInst *L) {
2016 if (!
L->isUnordered())
2019 if (
L->use_empty()) {
2029 return processNonLocalLoad(L);
2036 dbgs() <<
"GVN: load ";
L->printAsOperand(
dbgs());
2037 dbgs() <<
" has unknown dependence\n";);
2041 auto AV = AnalyzeLoadAvailability(L, Dep,
L->getPointerOperand());
2063std::pair<uint32_t, bool>
2064GVNPass::ValueTable::assignExpNewValueNum(
Expression &Exp) {
2066 bool CreateNewValNum = !
e;
2067 if (CreateNewValNum) {
2068 Expressions.push_back(Exp);
2069 if (ExprIdx.size() < nextValueNumber + 1)
2070 ExprIdx.resize(nextValueNumber * 2);
2071 e = nextValueNumber;
2072 ExprIdx[nextValueNumber++] = nextExprNumber++;
2074 return {
e, CreateNewValNum};
2081 LeaderTableEntry *Vals = &Gvn.LeaderTable[Num];
2082 while (Vals && Vals->BB == BB)
2091 auto FindRes = PhiTranslateTable.find({Num, Pred});
2092 if (FindRes != PhiTranslateTable.end())
2093 return FindRes->second;
2094 uint32_t NewNum = phiTranslateImpl(Pred, PhiBlock, Num, Gvn);
2095 PhiTranslateTable.insert({{Num, Pred}, NewNum});
2106 LeaderTableEntry *Vals = &Gvn.LeaderTable[Num];
2108 Call = dyn_cast<CallInst>(Vals->Val);
2109 if (Call && Call->getParent() == PhiBlock)
2114 if (AA->doesNotAccessMemory(Call))
2117 if (!MD || !AA->onlyReadsMemory(Call))
2129 if (
D.getResult().isNonFuncLocal())
2140 if (
PHINode *PN = NumberingPhi[Num]) {
2141 for (
unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
2142 if (PN->getParent() == PhiBlock && PN->getIncomingBlock(i) == Pred)
2152 if (!areAllValsInBB(Num, PhiBlock, Gvn))
2155 if (Num >= ExprIdx.size() || ExprIdx[Num] == 0)
2159 for (
unsigned i = 0; i <
Exp.varargs.size(); i++) {
2163 if ((i > 1 &&
Exp.opcode == Instruction::InsertValue) ||
2164 (i > 0 &&
Exp.opcode == Instruction::ExtractValue) ||
2165 (i > 1 &&
Exp.opcode == Instruction::ShuffleVector))
2167 Exp.varargs[i] = phiTranslate(Pred, PhiBlock,
Exp.varargs[i], Gvn);
2170 if (
Exp.commutative) {
2171 assert(
Exp.varargs.size() >= 2 &&
"Unsupported commutative instruction!");
2172 if (
Exp.varargs[0] >
Exp.varargs[1]) {
2175 if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp)
2176 Exp.opcode = (Opcode << 8) |
2182 if (
uint32_t NewNum = expressionNumbering[Exp]) {
2183 if (
Exp.opcode == Instruction::Call && NewNum != Num)
2184 return areCallValsEqual(Num, NewNum, Pred, PhiBlock, Gvn) ? NewNum : Num;
2192void GVNPass::ValueTable::eraseTranslateCacheEntry(
2195 PhiTranslateTable.erase({Num, Pred});
2204 LeaderTableEntry Vals = LeaderTable[num];
2205 if (!Vals.Val)
return nullptr;
2207 Value *Val =
nullptr;
2210 if (isa<Constant>(Val))
return Val;
2213 LeaderTableEntry* Next = Vals.Next;
2216 if (isa<Constant>(Next->Val))
return Next->Val;
2217 if (!Val) Val = Next->Val;
2236 const BasicBlock *Pred =
E.getEnd()->getSinglePredecessor();
2237 assert((!Pred || Pred ==
E.getStart()) &&
2238 "No edge between these basic blocks!");
2239 return Pred !=
nullptr;
2242void GVNPass::assignBlockRPONumber(
Function &
F) {
2243 BlockRPONumber.clear();
2247 BlockRPONumber[BB] = NextBlockNumber++;
2248 InvalidBlockRPONumbers =
false;
2251bool GVNPass::replaceOperandsForInBlockEquality(
Instruction *Instr)
const {
2252 bool Changed =
false;
2253 for (
unsigned OpNum = 0; OpNum < Instr->
getNumOperands(); ++OpNum) {
2255 auto it = ReplaceOperandsWithMap.find(Operand);
2256 if (it != ReplaceOperandsWithMap.end()) {
2258 << *it->second <<
" in instruction " << *Instr <<
'\n');
2271bool GVNPass::propagateEquality(
Value *LHS,
Value *RHS,
2273 bool DominatesByEdge) {
2275 Worklist.
push_back(std::make_pair(LHS, RHS));
2276 bool Changed =
false;
2281 while (!Worklist.
empty()) {
2282 std::pair<Value*, Value*> Item = Worklist.
pop_back_val();
2283 LHS = Item.first;
RHS = Item.second;
2290 if (isa<Constant>(LHS) && isa<Constant>(RHS))
2294 if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
2296 assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) &&
"Unexpected value!");
2303 if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
2304 (isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
2323 if (RootDominatesEnd && !isa<Instruction>(RHS))
2324 addToLeaderTable(LVN, RHS, Root.
getEnd());
2330 unsigned NumReplacements =
2335 Changed |= NumReplacements > 0;
2336 NumGVNEqProp += NumReplacements;
2355 bool isKnownFalse = !isKnownTrue;
2370 if (
CmpInst *Cmp = dyn_cast<CmpInst>(LHS)) {
2371 Value *Op0 =
Cmp->getOperand(0), *Op1 =
Cmp->getOperand(1);
2378 Worklist.
push_back(std::make_pair(Op0, Op1));
2390 if (Num < NextNum) {
2392 if (NotCmp && isa<Instruction>(NotCmp)) {
2393 unsigned NumReplacements =
2398 Changed |= NumReplacements > 0;
2399 NumGVNEqProp += NumReplacements;
2409 if (RootDominatesEnd)
2410 addToLeaderTable(Num, NotVal, Root.
getEnd());
2423 if (isa<DbgInfoIntrinsic>(
I))
2432 bool Changed =
false;
2433 if (!
I->use_empty()) {
2437 I->replaceAllUsesWith(V);
2445 if (MD &&
V->getType()->isPtrOrPtrVectorTy())
2452 if (
auto *Assume = dyn_cast<AssumeInst>(
I))
2453 return processAssumeIntrinsic(Assume);
2455 if (
LoadInst *Load = dyn_cast<LoadInst>(
I)) {
2456 if (processLoad(Load))
2460 addToLeaderTable(Num, Load,
Load->getParent());
2467 if (!BI->isConditional())
2470 if (isa<Constant>(BI->getCondition()))
2471 return processFoldableCondBr(BI);
2473 Value *BranchCond = BI->getCondition();
2477 if (TrueSucc == FalseSucc)
2481 bool Changed =
false;
2485 Changed |= propagateEquality(BranchCond, TrueVal, TrueE,
true);
2489 Changed |= propagateEquality(BranchCond, FalseVal, FalseE,
true);
2496 Value *SwitchCond =
SI->getCondition();
2498 bool Changed =
false;
2502 for (
unsigned i = 0, n =
SI->getNumSuccessors(); i != n; ++i)
2503 ++SwitchEdges[
SI->getSuccessor(i)];
2509 if (SwitchEdges.
lookup(Dst) == 1) {
2511 Changed |= propagateEquality(SwitchCond, i->getCaseValue(),
E,
true);
2519 if (
I->getType()->isVoidTy())
2527 if (isa<AllocaInst>(
I) ||
I->isTerminator() || isa<PHINode>(
I)) {
2528 addToLeaderTable(Num,
I,
I->getParent());
2535 if (Num >= NextNum) {
2536 addToLeaderTable(Num,
I,
I->getParent());
2542 Value *Repl = findLeader(
I->getParent(), Num);
2545 addToLeaderTable(Num,
I,
I->getParent());
2547 }
else if (Repl ==
I) {
2577 InvalidBlockRPONumbers =
true;
2579 MSSAU = MSSA ? &Updater :
nullptr;
2581 bool Changed =
false;
2582 bool ShouldContinue =
true;
2592 Changed |= removedBlock;
2595 unsigned Iteration = 0;
2596 while (ShouldContinue) {
2599 ShouldContinue = iterateOnFunction(
F);
2600 Changed |= ShouldContinue;
2607 assignValNumForDeadCode();
2608 bool PREChanged =
true;
2609 while (PREChanged) {
2610 PREChanged = performPRE(
F);
2611 Changed |= PREChanged;
2620 cleanupGlobalSets();
2635 "We expect InstrsToErase to be empty across iterations");
2636 if (DeadBlocks.count(BB))
2640 ReplaceOperandsWithMap.clear();
2641 bool ChangedFunction =
false;
2651 if (!ReplaceOperandsWithMap.empty())
2652 ChangedFunction |= replaceOperandsForInBlockEquality(&*BI);
2653 ChangedFunction |= processInstruction(&*BI);
2655 if (InstrsToErase.
empty()) {
2661 NumGVNInstr += InstrsToErase.
size();
2664 bool AtStart = BI == BB->
begin();
2668 for (
auto *
I : InstrsToErase) {
2669 assert(
I->getParent() == BB &&
"Removing instruction from wrong block?");
2678 I->eraseFromParent();
2680 InstrsToErase.clear();
2688 return ChangedFunction;
2701 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2713 if (
Value *V = findLeader(Pred, TValNo)) {
2737 addToLeaderTable(Num, Instr, Pred);
2741bool GVNPass::performScalarPRE(
Instruction *CurInst) {
2742 if (isa<AllocaInst>(CurInst) || CurInst->
isTerminator() ||
2745 isa<DbgInfoIntrinsic>(CurInst))
2752 if (isa<CmpInst>(CurInst))
2762 if (isa<GetElementPtrInst>(CurInst))
2765 if (
auto *CallB = dyn_cast<CallBase>(CurInst)) {
2767 if (CallB->isInlineAsm())
2770 if (CallB->isConvergent())
2782 unsigned NumWith = 0;
2783 unsigned NumWithout = 0;
2788 if (InvalidBlockRPONumbers)
2789 assignBlockRPONumber(*CurrentBlock->
getParent());
2800 assert(BlockRPONumber.count(
P) && BlockRPONumber.count(CurrentBlock) &&
2801 "Invalid BlockRPONumber map.");
2802 if (BlockRPONumber[
P] >= BlockRPONumber[CurrentBlock]) {
2808 Value *predV = findLeader(
P, TValNo);
2813 }
else if (predV == CurInst) {
2825 if (NumWithout > 1 || NumWith == 0)
2833 if (NumWithout != 0) {
2852 toSplit.push_back(std::make_pair(PREPred->
getTerminator(), SuccNum));
2856 PREInstr = CurInst->
clone();
2857 if (!performScalarPREInsertion(PREInstr, PREPred, CurrentBlock, ValNo)) {
2867 assert(PREInstr !=
nullptr || NumWithout == 0);
2874 CurInst->
getName() +
".pre-phi", &CurrentBlock->
front());
2875 for (
unsigned i = 0, e = predMap.
size(); i != e; ++i) {
2876 if (
Value *V = predMap[i].first) {
2889 addToLeaderTable(ValNo, Phi, CurrentBlock);
2895 removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
2915 bool Changed =
false;
2918 if (CurrentBlock == &
F.getEntryBlock())
2922 if (CurrentBlock->isEHPad())
2926 BE = CurrentBlock->end();
2929 Changed |= performScalarPRE(CurInst);
2933 if (splitCriticalEdges())
2950 InvalidBlockRPONumbers =
true;
2957bool GVNPass::splitCriticalEdges() {
2958 if (toSplit.empty())
2961 bool Changed =
false;
2963 std::pair<Instruction *, unsigned> Edge = toSplit.pop_back_val();
2967 }
while (!toSplit.empty());
2971 InvalidBlockRPONumbers =
true;
2977bool GVNPass::iterateOnFunction(
Function &
F) {
2978 cleanupGlobalSets();
2981 bool Changed =
false;
2988 Changed |= processBlock(BB);
2993void GVNPass::cleanupGlobalSets() {
2995 LeaderTable.
clear();
2996 BlockRPONumber.clear();
2997 TableAllocator.
Reset();
2999 InvalidBlockRPONumbers =
true;
3004void GVNPass::verifyRemoved(
const Instruction *Inst)
const {
3009 for (
const auto &
I : LeaderTable) {
3010 const LeaderTableEntry *
Node = &
I.second;
3011 assert(
Node->Val != Inst &&
"Inst still in value numbering scope!");
3013 while (
Node->Next) {
3015 assert(
Node->Val != Inst &&
"Inst still in value numbering scope!");
3029 while (!NewDead.
empty()) {
3031 if (DeadBlocks.count(
D))
3037 DeadBlocks.insert(Dom.
begin(), Dom.
end());
3042 if (DeadBlocks.count(S))
3045 bool AllPredDead =
true;
3047 if (!DeadBlocks.count(
P)) {
3048 AllPredDead =
false;
3069 if (DeadBlocks.count(
B))
3076 if (!DeadBlocks.count(
P))
3082 DeadBlocks.insert(
P = S);
3088 if (!DeadBlocks.count(
P))
3112bool GVNPass::processFoldableCondBr(
BranchInst *BI) {
3126 if (DeadBlocks.count(DeadRoot))
3130 DeadRoot = splitCriticalEdges(BI->
getParent(), DeadRoot);
3132 addDeadBlock(DeadRoot);
3140void GVNPass::assignValNumForDeadCode() {
3144 addToLeaderTable(ValNum, &Inst, BB);
3159 if (skipFunction(
F))
3162 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3164 auto *MSSAWP = getAnalysisIfAvailable<MemorySSAWrapperPass>();
3165 return Impl.runImpl(
3166 F, getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
F),
3167 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
3168 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
F),
3169 getAnalysis<AAResultsWrapperPass>().getAAResults(),
3170 Impl.isMemDepEnabled()
3171 ? &getAnalysis<MemoryDependenceWrapperPass>().getMemDep()
3173 LIWP ? &LIWP->getLoopInfo() :
nullptr,
3174 &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(),
3175 MSSAWP ? &MSSAWP->getMSSA() :
nullptr);
3183 if (Impl.isMemDepEnabled())
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
This file contains the simple types necessary to represent the attributes associated with functions a...
SmallVector< MachineOperand, 4 > Cond
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
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")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
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.
static bool hasUsersIn(Value *V, BasicBlock *BB)
static void reportMayClobberedLoad(LoadInst *Load, MemDepResult DepInfo, DominatorTree *DT, OptimizationRemarkEmitter *ORE)
Try to locate the three instruction involved in a missed load-elimination case that is due to an inte...
static void reportLoadElim(LoadInst *Load, Value *AvailableValue, OptimizationRemarkEmitter *ORE)
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 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 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.
static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E, DominatorTree *DT)
There is an edge from 'Src' to 'Dst'.
static bool impliesEquivalanceIfFalse(CmpInst *Cmp)
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.
static Value * findDominatingValue(const MemoryLocation &Loc, Type *LoadTy, Instruction *From, AAResults *AA)
static bool isLifetimeStart(const Instruction *Inst)
static cl::opt< bool > GVNEnableSplitBackedgeInLoadPRE("enable-split-backedge-in-load-pre", cl::init(false))
static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl)
static bool impliesEquivalanceIfTrue(CmpInst *Cmp)
@ 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 cl::opt< bool > GVNEnablePRE("enable-pre", cl::init(true), cl::Hidden)
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 bool liesBetween(const Instruction *From, Instruction *Between, const Instruction *To, DominatorTree *DT)
Assuming To can be reached from both From and Between, does Between lie on every path from From to To...
static cl::opt< bool > GVNEnableLoadPRE("enable-load-pre", cl::init(true))
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.
static bool lookup(const GsymReader &GR, DataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
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...
Module.h This file contains the declarations for the Module class.
ppc ctr loops PowerPC CTR Loops Verify
This header defines various interfaces for pass management in LLVM.
#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.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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)
This defines the Use class.
static const uint32_t IV[8]
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
Class for arbitrary precision integers.
A container for analyses that lazily runs them and caches their results.
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.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
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.
const BasicBlock * getEnd() const
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Function * getParent() const
Return the enclosing method, or null if none.
InstListType::iterator iterator
Instruction iterators...
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 if the block is well formed or null if the block is not well forme...
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)
Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
Conditional or Unconditional Branch instruction.
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
Value * getCondition() const
void Reset()
Deallocate all but the current slab and reset the current pointer to the beginning of it,...
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.
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
This is the shared class of boolean and integer constants.
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
static ConstantInt * getTrue(LLVMContext &Context)
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static ConstantInt * getFalse(LLVMContext &Context)
This is an important base class in LLVM.
static 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.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&... Args)
Analysis pass which computes a DominatorTree.
void getDescendants(NodeT *R, SmallVectorImpl< NodeT * > &Result) const
Get all nodes dominated by R, including R itself.
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.
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
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.
FunctionPass class - This class is used to implement most global optimizations.
Represents calls to the gc.relocate intrinsic.
This class holds the mapping between values and value numbers.
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...
uint32_t getNextUnusedValueNumber()
uint32_t lookupOrAdd(Value *V)
lookup_or_add - Returns the value number for the specified value, assigning it a new number if it did...
uint32_t lookup(Value *V, bool Verify=true) const
Returns the value number of the specified value.
void setAliasAnalysis(AAResults *A)
void clear()
Remove all entries from the ValueTable.
bool exists(Value *V) const
Returns true if a value number exists for the specified value.
uint32_t phiTranslate(const BasicBlock *BB, const BasicBlock *PhiBlock, uint32_t Num, GVNPass &Gvn)
Wrap phiTranslateImpl to provide caching functionality.
void setMemDep(MemoryDependenceResults *M)
void erase(Value *v)
Remove a value from the value numbering.
void add(Value *V, uint32_t num)
add - Insert a value into the table with a specified value number.
void setDomTree(DominatorTree *D)
void eraseTranslateCacheEntry(uint32_t Num, const BasicBlock &CurrBlock)
Erase stale entry from phiTranslate cache so phiTranslate can be computed again.
void verifyRemoved(const Value *) const
verifyRemoved - Verify that the value is removed from all internal data structures.
The core GVN pass object.
friend class gvn::GVNLegacyPass
bool isPREEnabled() const
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
AAResults * getAliasAnalysis() const
bool isLoadPREEnabled() const
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
DominatorTree & getDominatorTree() const
bool isLoadInLoopPREEnabled() const
bool isLoadPRESplitBackedgeEnabled() const
void markInstructionForDeletion(Instruction *I)
This removes the specified instruction from our various maps and marks it for deletion.
bool isMemDepEnabled() const
MemoryDependenceResults & getMemDep() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Legacy wrapper pass to provide the GlobalsAAResult object.
This class allows to keep track on instructions with implicit control flow.
bool isDominatedByICFIFromSameBlock(const Instruction *Insn)
Returns true if the first ICFI of Insn's block exists and dominates Insn.
bool hasICF(const BasicBlock *BB)
Returns true if at least one instruction from the given basic block has implicit control flow.
void clear()
Invalidates all information from this tracking.
void removeUsersOf(const Instruction *Inst)
Notifies this tracking that we are going to replace all uses of Inst.
void insertInstructionTo(const Instruction *Inst, const BasicBlock *BB)
Notifies this tracking that we are going to insert a new instruction Inst to the basic block BB.
void removeInstruction(const Instruction *Inst)
Notifies this tracking that we are going to remove the instruction Inst It makes all necessary update...
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
const BasicBlock * getParent() const
bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
bool isTerminator() const
bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
An instruction for reading from memory.
Analysis pass that exposes the LoopInfo for a function.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Represents a single loop in the control flow graph.
This class implements a map that also provides access to all stored values in a deterministic order.
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.
An analysis that produces MemoryDependenceResults for a function.
Provides a lazy, caching interface for making common memory aliasing information queries,...
std::vector< NonLocalDepEntry > NonLocalDepInfo
void invalidateCachedPredecessors()
Clears the PredIteratorCache info.
void invalidateCachedPointerInfo(Value *Ptr)
Invalidates cached information about the specified pointer, because it may be too conservative in mem...
std::optional< int32_t > getClobberOffset(LoadInst *DepInst) const
Return the clobber offset to dependent instruction.
void removeInstruction(Instruction *InstToRemove)
Removes an instruction from the dependence analysis, updating the dependence of instructions that pre...
MemDepResult getDependency(Instruction *QueryInst)
Returns the instruction on which a memory operation depends.
const NonLocalDepInfo & getNonLocalCallDependency(CallBase *QueryCall)
Perform a full dependency query for the specified call, returning the set of blocks that the value is...
void getNonLocalPointerDependency(Instruction *QueryInst, SmallVectorImpl< NonLocalDepResult > &Result)
Perform a full dependency query for an access to the QueryInst's specified memory location,...
A wrapper analysis pass for the legacy pass manager that exposes a MemoryDepnedenceResults instance.
Representation for a specific memory location.
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
const Value * Ptr
The address of the start of the location.
An analysis that produces MemorySSA for a function.
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
MemoryUseOrDef * createMemoryAccessBefore(Instruction *I, MemoryAccess *Definition, MemoryUseOrDef *InsertPt)
Create a MemoryAccess in MemorySSA before or after an existing MemoryAccess.
void insertDef(MemoryDef *Def, bool RenameUses=false)
Insert a definition into the MemorySSA IR.
MemoryAccess * createMemoryAccessInBB(Instruction *I, MemoryAccess *Definition, const BasicBlock *BB, MemorySSA::InsertionPlace Point)
Create a MemoryAccess in MemorySSA at a specified point in a block, with a specified clobbering defin...
void insertUse(MemoryUse *Use, bool RenameUses=false)
void removeMemoryAccess(MemoryAccess *, bool OptimizePhis=false)
Remove a MemoryAccess from MemorySSA, including updating all definitions and uses.
Legacy analysis pass which computes MemorySSA.
Encapsulates MemorySSA, including all data associated with memory accesses.
const AccessList * getBlockAccesses(const BasicBlock *BB) const
Return the list of MemoryAccess's for a given basic block.
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.
MemoryAccess * getLiveOnEntryDef() const
Class that has the common methods + fields of memory uses/defs.
MemoryAccess * getDefiningAccess() const
Get the access that produces the memory state used by this Use.
This is an entry in the NonLocalDepInfo cache.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
void setIncomingValueForBlock(const BasicBlock *BB, Value *V)
Set every incoming value(s) for block BB to V.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *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.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static 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.
void preserve()
Mark an analysis as preserved.
Helper class for SSA formation on a set of values defined in multiple blocks.
void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
Value * GetValueInMiddleOfBlock(BasicBlock *BB)
Construct SSA form, materializing a value that is live in the middle of the specified block.
bool HasValueForBlock(BasicBlock *BB) const
Return true if the SSAUpdater already has a value for the specified block.
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value.
This class represents the LLVM 'select' instruction.
const Value * getCondition() const
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
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.
An instruction for storing to memory.
StringRef - Represent a constant reference to a string, i.e.
char front() const
front - Get the first character in the string.
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.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
static 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 isOpaquePointerTy() const
True if this is an instance of an opaque PointerType.
bool isVoidTy() const
Return true if this is 'void'.
static 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.
void setOperand(unsigned i, Value *Val)
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
void setName(const Twine &Name)
Change the name of the value.
bool hasOneUse() const
Return true if there is exactly one use of this value.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
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...
void deleteValue()
Delete a pointer to a generic Value.
StringRef getName() const
Return a constant reference to the value's name.
Represents an op.with.overflow intrinsic.
An efficient, type-erasing, non-owning reference to a callable.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
GVNLegacyPass(bool NoMemDepAnalysis=!GVNEnableMemDep)
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
An opaque object representing a hash code.
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.
std::unique_ptr< ValueIDNum[]> ValueTable
Type for a table of values in a block.
@ C
The default llvm calling convention, compatible with C.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
bool match(Val *V, const Pattern &P)
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
BinaryOp_match< cst_pred_ty< is_all_ones >, ValTy, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
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...
Value * getLoadValueForLoad(LoadInst *SrcVal, unsigned Offset, Type *LoadTy, Instruction *InsertPt, const DataLayout &DL)
If analyzeLoadFromClobberingLoad returned an offset, this function can be used to actually perform th...
Value * getStoreValueForLoad(Value *SrcVal, unsigned Offset, Type *LoadTy, Instruction *InsertPt, const DataLayout &DL)
If analyzeLoadFromClobberingStore returned an offset, this function can be used to actually perform t...
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...
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...
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...
bool canCoerceMustAliasedValueToLoad(Value *StoredVal, Type *LoadTy, const DataLayout &DL)
Return true if CoerceAvailableValueToLoadType would succeed if it was called.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
Interval::succ_iterator succ_end(Interval *I)
hash_code hash_value(const FixedPointSemantics &Val)
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,...
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...
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)
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
void append_range(Container &C, Range &&R)
Wrapper function to append a range to a container.
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...
void initializeGVNLegacyPassPass(PassRegistry &)
Interval::pred_iterator pred_end(Interval *I)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
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.
bool isModSet(const ModRefInfo MRI)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
void patchReplacementInstruction(Instruction *I, Value *Repl)
Patch the replacement so that it is not more restrictive than the value being replaced.
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.
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Global
Append to llvm.global_dtors.
bool VerifyMemorySSA
Enables verification of MemorySSA.
bool salvageKnowledge(Instruction *I, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr)
Calls BuildAssumeFromInst and if the resulting llvm.assume is valid insert if before I.
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.
Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
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.
FunctionPass * createGVNPass(bool NoMemDepAnalysis=false)
Create a legacy GVN pass.
bool isCriticalEdge(const Instruction *TI, unsigned SuccNum, bool AllowIdenticalEdges=false)
Return true if the specified edge is a critical edge.
bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
constexpr unsigned BitWidth
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
bool pred_empty(const BasicBlock *BB)
iterator_range< df_iterator< T > > depth_first(const T &G)
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
bool EliminateDuplicatePHINodes(BasicBlock *BB)
Check for and eliminate duplicate PHI nodes in this block.
bool isAssumeWithEmptyBundle(AssumeInst &Assume)
Return true iff the operand bundles of the provided llvm.assume doesn't contain any valuable informat...
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
bool isPotentiallyReachable(const Instruction *From, const Instruction *To, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet=nullptr, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr)
Determine whether instruction 'To' is reachable from 'From', without passing through any blocks in Ex...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Option class for critical edge splitting.
static GVNPass::Expression getTombstoneKey()
static bool isEqual(const GVNPass::Expression &LHS, const GVNPass::Expression &RHS)
static unsigned getHashValue(const GVNPass::Expression &e)
static GVNPass::Expression getEmptyKey()
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.
std::optional< bool > AllowLoadPRESplitBackedge
std::optional< bool > AllowPRE
std::optional< bool > AllowLoadInLoopPRE
std::optional< bool > AllowMemDep
std::optional< bool > AllowLoadPRE
SmallVector< uint32_t, 4 > varargs
bool operator==(const Expression &other) const
friend hash_code hash_value(const Expression &Value)
Expression(uint32_t o=~2U)
A CRTP mix-in to automatically provide informational APIs needed for passes.
Represents an AvailableValue which can be rematerialized at the end of the associated BasicBlock.
static AvailableValueInBlock get(BasicBlock *BB, Value *V, unsigned Offset=0)
static AvailableValueInBlock getUndef(BasicBlock *BB)
static AvailableValueInBlock get(BasicBlock *BB, AvailableValue &&AV)
Value * MaterializeAdjustedValue(LoadInst *Load, GVNPass &gvn) const
Emit code at the end of this block to adjust the value defined here to the specified type.
AvailableValue AV
AV - The actual available value.
static AvailableValueInBlock getSelect(BasicBlock *BB, SelectInst *Sel, Value *V1, Value *V2)
BasicBlock * BB
BB - The basic block in question.
Represents a particular available value that we know how to materialize.
unsigned Offset
Offset - The byte offset in Val that is interesting for the load query.
bool isSimpleValue() const
static AvailableValue getSelect(SelectInst *Sel, Value *V1, Value *V2)
bool isCoercedLoadValue() const
static AvailableValue get(Value *V, unsigned Offset=0)
ValType Kind
Kind of the live-out value.
LoadInst * getCoercedLoadValue() const
static AvailableValue getLoad(LoadInst *Load, unsigned Offset=0)
static AvailableValue getMI(MemIntrinsic *MI, unsigned Offset=0)
bool isUndefValue() const
bool isSelectValue() const
Value * Val
Val - The value that is live out of the block.
Value * V1
V1, V2 - The dominating non-clobbered values of SelectVal.
Value * MaterializeAdjustedValue(LoadInst *Load, Instruction *InsertPt, GVNPass &gvn) const
Emit code at the specified insertion point to adjust the value defined here to the specified type.
static AvailableValue getUndef()
SelectInst * getSelectValue() const
Value * getSimpleValue() const
bool isMemIntrinValue() const
MemIntrinsic * getMemIntrinValue() const