43 #include "llvm/Config/llvm-config.h" 87 #define DEBUG_TYPE "gvn" 89 STATISTIC(NumGVNInstr,
"Number of instructions deleted");
90 STATISTIC(NumGVNLoad,
"Number of loads deleted");
91 STATISTIC(NumGVNPRE,
"Number of instructions PRE'd");
92 STATISTIC(NumGVNBlocks,
"Number of blocks merged");
93 STATISTIC(NumGVNSimpl,
"Number of instructions simplified");
94 STATISTIC(NumGVNEqProp,
"Number of equalities propagated");
95 STATISTIC(NumPRELoad,
"Number of loads PRE'd");
104 cl::desc(
"Max recurse depth (default = 1000)"));
109 bool commutative =
false;
115 if (opcode != other.
opcode)
117 if (opcode == ~0U || opcode == ~1U)
119 if (type != other.
type)
173 Res.
Val.setPointer(V);
174 Res.
Val.setInt(SimpleVal);
181 Res.
Val.setPointer(MI);
182 Res.
Val.setInt(MemIntrin);
189 Res.
Val.setPointer(LI);
190 Res.
Val.setInt(LoadVal);
197 Res.
Val.setPointer(
nullptr);
198 Res.
Val.setInt(UndefVal);
209 assert(isSimpleValue() &&
"Wrong accessor");
214 assert(isCoercedLoadValue() &&
"Wrong accessor");
219 assert(isMemIntrinValue() &&
"Wrong accessor");
241 Res.
AV = std::move(AV);
271 e.varargs.push_back(lookupOrAdd(*OI));
278 if (e.varargs[0] > e.varargs[1])
280 e.commutative =
true;
283 if (
CmpInst *
C = dyn_cast<CmpInst>(I)) {
286 if (e.varargs[0] > e.varargs[1]) {
291 e.commutative =
true;
295 e.varargs.push_back(*II);
304 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
305 "Not a comparison!");
308 e.varargs.push_back(lookupOrAdd(LHS));
309 e.varargs.push_back(lookupOrAdd(RHS));
312 if (e.varargs[0] > e.varargs[1]) {
316 e.opcode = (Opcode << 8) | Predicate;
317 e.commutative =
true;
322 assert(EI &&
"Not an ExtractValueInst?");
333 case Intrinsic::sadd_with_overflow:
334 case Intrinsic::uadd_with_overflow:
337 case Intrinsic::ssub_with_overflow:
338 case Intrinsic::usub_with_overflow:
339 e.opcode = Instruction::Sub;
341 case Intrinsic::smul_with_overflow:
342 case Intrinsic::umul_with_overflow:
343 e.opcode = Instruction::Mul;
352 "Expect two args for recognised intrinsics.");
364 e.varargs.push_back(lookupOrAdd(*OI));
368 e.varargs.push_back(*II);
384 valueNumbering.insert(std::make_pair(V, num));
385 if (
PHINode *PN = dyn_cast<PHINode>(V))
386 NumberingPhi[num] = PN;
390 if (AA->doesNotAccessMemory(C)) {
392 uint32_t e = assignExpNewValueNum(exp).first;
393 valueNumbering[
C] = e;
395 }
else if (AA->onlyReadsMemory(C)) {
397 auto ValNum = assignExpNewValueNum(exp);
399 valueNumbering[
C] = ValNum.first;
403 uint32_t e = assignExpNewValueNum(exp).first;
404 valueNumbering[
C] = e;
411 valueNumbering[
C] = nextValueNumber;
412 return nextValueNumber++;
415 if (local_dep.
isDef()) {
419 valueNumbering[
C] = nextValueNumber;
420 return nextValueNumber++;
427 valueNumbering[
C] = nextValueNumber;
428 return nextValueNumber++;
432 uint32_t v = lookupOrAdd(local_cdep);
433 valueNumbering[
C] = v;
439 MD->getNonLocalCallDependency(
CallSite(C));
445 for (
unsigned i = 0, e = deps.size(); i != e; ++i) {
459 if (NonLocalDepCall && DT->properlyDominates(I->
getBB(), C->
getParent())){
460 cdep = NonLocalDepCall;
469 valueNumbering[
C] = nextValueNumber;
470 return nextValueNumber++;
474 valueNumbering[
C] = nextValueNumber;
475 return nextValueNumber++;
481 valueNumbering[
C] = nextValueNumber;
482 return nextValueNumber++;
487 valueNumbering[
C] = v;
490 valueNumbering[
C] = nextValueNumber;
491 return nextValueNumber++;
502 if (VI != valueNumbering.end())
505 if (!isa<Instruction>(V)) {
506 valueNumbering[V] = nextValueNumber;
507 return nextValueNumber++;
514 return lookupOrAddCall(cast<CallInst>(I));
516 case Instruction::FAdd:
517 case Instruction::Sub:
518 case Instruction::FSub:
519 case Instruction::Mul:
520 case Instruction::FMul:
521 case Instruction::UDiv:
522 case Instruction::SDiv:
523 case Instruction::FDiv:
524 case Instruction::URem:
525 case Instruction::SRem:
526 case Instruction::FRem:
527 case Instruction::Shl:
528 case Instruction::LShr:
529 case Instruction::AShr:
530 case Instruction::And:
531 case Instruction::Or:
532 case Instruction::Xor:
533 case Instruction::ICmp:
534 case Instruction::FCmp:
535 case Instruction::Trunc:
536 case Instruction::ZExt:
537 case Instruction::SExt:
538 case Instruction::FPToUI:
539 case Instruction::FPToSI:
540 case Instruction::UIToFP:
541 case Instruction::SIToFP:
542 case Instruction::FPTrunc:
543 case Instruction::FPExt:
544 case Instruction::PtrToInt:
545 case Instruction::IntToPtr:
546 case Instruction::BitCast:
548 case Instruction::ExtractElement:
549 case Instruction::InsertElement:
550 case Instruction::ShuffleVector:
551 case Instruction::InsertValue:
552 case Instruction::GetElementPtr:
555 case Instruction::ExtractValue:
556 exp = createExtractvalueExpr(cast<ExtractValueInst>(I));
558 case Instruction::PHI:
559 valueNumbering[V] = nextValueNumber;
560 NumberingPhi[nextValueNumber] = cast<PHINode>(V);
561 return nextValueNumber++;
563 valueNumbering[V] = nextValueNumber;
564 return nextValueNumber++;
567 uint32_t e = assignExpNewValueNum(exp).first;
568 valueNumbering[V] = e;
577 assert(VI != valueNumbering.end() &&
"Value not numbered?");
580 return (VI != valueNumbering.end()) ? VI->second : 0;
590 Expression exp = createCmpExpr(Opcode, Predicate, LHS, RHS);
591 return assignExpNewValueNum(exp).first;
596 valueNumbering.clear();
597 expressionNumbering.clear();
598 NumberingPhi.clear();
599 PhiTranslateTable.clear();
608 uint32_t Num = valueNumbering.lookup(V);
609 valueNumbering.erase(V);
612 NumberingPhi.erase(Num);
619 I = valueNumbering.begin(),
E = valueNumbering.end(); I !=
E; ++
I) {
620 assert(I->first != V &&
"Inst still occurs in value numbering map!");
640 bool Changed =
runImpl(F, AC, DT, TLI, AA, &MemDep, LI, &ORE);
650 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 654 E = d.
end(); I !=
E; ++
I) {
655 errs() << I->first <<
"\n";
680 std::pair<DenseMap<BasicBlock*, char>::iterator,
char> IV =
681 FullyAvailableBlocks.
insert(std::make_pair(BB, 2));
687 if (IV.first->second == 2)
688 IV.first->second = 3;
689 return IV.first->second != 0;
697 goto SpeculationFailure;
699 for (; PI != PE; ++PI)
704 goto SpeculationFailure;
712 char &BBVal = FullyAvailableBlocks[BB];
730 char &EntryVal = FullyAvailableBlocks[Entry];
731 if (EntryVal == 0)
continue;
737 }
while (!BBWorklist.
empty());
750 if (ValuesPerBlock.
size() == 1 &&
753 assert(!ValuesPerBlock[0].AV.isUndefValue() &&
754 "Dead BB dominate this block");
755 return ValuesPerBlock[0].MaterializeAdjustedValue(LI, gvn);
774 ((AV.AV.isSimpleValue() && AV.AV.getSimpleValue() == LI) ||
775 (AV.AV.isCoercedLoadValue() && AV.AV.getCoercedLoadValue() == LI)))
791 if (isSimpleValue()) {
792 Res = getSimpleValue();
793 if (Res->
getType() != LoadTy) {
797 <<
" " << *getSimpleValue() <<
'\n' 801 }
else if (isCoercedLoadValue()) {
813 LLVM_DEBUG(
dbgs() <<
"GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset
814 <<
" " << *getCoercedLoadValue() <<
'\n' 818 }
else if (isMemIntrinValue()) {
822 <<
" " << *getMemIntrinValue() <<
'\n' 826 assert(isUndefValue() &&
"Should be UndefVal");
830 assert(Res &&
"failed to materialize?");
836 return II->getIntrinsicID() == Intrinsic::lifetime_start;
847 User *OtherAccess =
nullptr;
850 R <<
"load of type " <<
NV(
"Type", LI->
getType()) <<
" not eliminated" 854 if (U != LI && (isa<LoadInst>(U) || isa<StoreInst>(U)) &&
855 DT->
dominates(cast<Instruction>(U), LI)) {
860 OtherAccess =
nullptr;
866 R <<
" in favor of " <<
NV(
"OtherAccess", OtherAccess);
868 R <<
" because it is clobbered by " <<
NV(
"ClobberedBy", DepInfo.
getInst());
876 "expected a local dependence");
887 if (Address && LI->
isAtomic() <= DepSI->isAtomic()) {
905 if (DepLI != LI && Address && LI->
isAtomic() <= DepLI->isAtomic()) {
933 dbgs() <<
" is clobbered by " << *I <<
'\n';);
957 if (
StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
961 if (S->getValueOperand()->getType() != LI->
getType() &&
974 if (
LoadInst *
LD = dyn_cast<LoadInst>(DepInst)) {
994 dbgs() <<
" has unknown def " << *DepInst <<
'\n';);
998 void GVN::AnalyzeLoadAvailability(
LoadInst *LI, LoadDepVect &Deps,
999 AvailValInBlkVect &ValuesPerBlock,
1000 UnavailBlkVect &UnavailableBlocks) {
1005 unsigned NumDeps = Deps.size();
1006 for (
unsigned i = 0, e = NumDeps; i != e; ++i) {
1010 if (DeadBlocks.count(DepBB)) {
1018 UnavailableBlocks.push_back(DepBB);
1025 Value *Address = Deps[i].getAddress();
1028 if (AnalyzeLoadAvailability(LI, DepInfo, Address, AV)) {
1035 UnavailableBlocks.push_back(DepBB);
1039 assert(NumDeps == ValuesPerBlock.size() + UnavailableBlocks.size() &&
1040 "post condition violation");
1043 bool GVN::PerformLoadPRE(
LoadInst *LI, AvailValInBlkVect &ValuesPerBlock,
1044 UnavailBlkVect &UnavailableBlocks) {
1054 UnavailableBlocks.end());
1077 if (!IsSafeToSpeculativelyExecute) {
1078 auto It = FirstImplicitControlFlowInsts.find(TmpBB);
1079 if (It != FirstImplicitControlFlowInsts.end()) {
1080 assert(It->second->getParent() == TmpBB &&
1081 "Implicit control flow map broken?");
1082 if (OI->dominates(It->second, LI))
1088 if (TmpBB == LoadBB)
1090 if (Blockers.count(TmpBB))
1102 if (!IsSafeToSpeculativelyExecute &&
1103 FirstImplicitControlFlowInsts.count(TmpBB))
1115 FullyAvailableBlocks[AV.BB] =
true;
1116 for (
BasicBlock *UnavailableBB : UnavailableBlocks)
1117 FullyAvailableBlocks[UnavailableBB] =
false;
1123 if (Pred->getTerminator()->isEHPad()) {
1125 dbgs() <<
"COULD NOT PRE LOAD BECAUSE OF AN EH PAD PREDECESSOR '" 1126 << Pred->getName() <<
"': " << *LI <<
'\n');
1134 if (Pred->getTerminator()->getNumSuccessors() != 1) {
1135 if (isa<IndirectBrInst>(Pred->getTerminator())) {
1137 dbgs() <<
"COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '" 1138 << Pred->getName() <<
"': " << *LI <<
'\n');
1142 if (LoadBB->isEHPad()) {
1144 dbgs() <<
"COULD NOT PRE LOAD BECAUSE OF AN EH PAD CRITICAL EDGE '" 1145 << Pred->getName() <<
"': " << *LI <<
'\n');
1152 PredLoads[Pred] =
nullptr;
1157 unsigned NumUnavailablePreds = PredLoads.
size() + CriticalEdgePred.
size();
1158 assert(NumUnavailablePreds != 0 &&
1159 "Fully available value should already be eliminated!");
1165 if (NumUnavailablePreds != 1)
1169 for (
BasicBlock *OrigPred : CriticalEdgePred) {
1170 BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
1171 assert(!PredLoads.
count(OrigPred) &&
"Split edges shouldn't be in map!");
1172 PredLoads[NewPred] =
nullptr;
1173 LLVM_DEBUG(
dbgs() <<
"Split critical edge " << OrigPred->getName() <<
"->" 1174 << LoadBB->getName() <<
'\n');
1178 bool CanDoPRE =
true;
1181 for (
auto &PredLoad : PredLoads) {
1182 BasicBlock *UnavailablePred = PredLoad.first;
1191 Value *LoadPtr =
nullptr;
1192 LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
1204 PredLoad.second = LoadPtr;
1208 while (!NewInsts.
empty()) {
1210 markInstructionForDeletion(I);
1214 return !CriticalEdgePred.empty();
1222 <<
"INSERTED " << NewInsts.
size() <<
" INSTS: " << *NewInsts.
back()
1241 for (
const auto &PredLoad : PredLoads) {
1242 BasicBlock *UnavailablePred = PredLoad.first;
1243 Value *LoadPtr = PredLoad.second;
1255 NewLoad->setAAMetadata(Tags);
1273 MD->invalidateCachedPointerInfo(LoadPtr);
1280 if (isa<PHINode>(V))
1285 MD->invalidateCachedPointerInfo(V);
1286 markInstructionForDeletion(LI);
1289 <<
"load eliminated by PRE";
1297 using namespace ore;
1301 <<
"load of type " <<
NV(
"Type", LI->
getType()) <<
" eliminated" 1303 <<
NV(
"InfavorOfValue", AvailableValue);
1309 bool GVN::processNonLocalLoad(
LoadInst *LI) {
1312 Attribute::SanitizeAddress) ||
1314 Attribute::SanitizeHWAddress))
1319 MD->getNonLocalPointerDependency(LI, Deps);
1324 unsigned NumDeps = Deps.size();
1331 !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
1333 dbgs() <<
" has unknown dependencies\n";);
1340 OE =
GEP->idx_end();
1342 if (
Instruction *I = dyn_cast<Instruction>(OI->get()))
1343 performScalarPRE(I);
1347 AvailValInBlkVect ValuesPerBlock;
1348 UnavailBlkVect UnavailableBlocks;
1349 AnalyzeLoadAvailability(LI, Deps, ValuesPerBlock, UnavailableBlocks);
1353 if (ValuesPerBlock.empty())
1361 if (UnavailableBlocks.empty()) {
1362 LLVM_DEBUG(
dbgs() <<
"GVN REMOVING NONLOCAL LOAD: " << *LI <<
'\n');
1368 if (isa<PHINode>(V))
1377 MD->invalidateCachedPointerInfo(V);
1378 markInstructionForDeletion(LI);
1388 return PerformLoadPRE(LI, ValuesPerBlock, UnavailableBlocks);
1391 bool GVN::processAssumeIntrinsic(
IntrinsicInst *IntrinsicI) {
1393 "This function can only be called with llvm.assume intrinsic");
1396 if (
ConstantInt *Cond = dyn_cast<ConstantInt>(V)) {
1397 if (Cond->isZero()) {
1406 markInstructionForDeletion(IntrinsicI);
1408 }
else if (isa<Constant>(V)) {
1416 bool Changed =
false;
1423 Changed |= propagateEquality(V, True, Edge,
false);
1429 ReplaceWithConstMap[V] = True;
1435 if (
auto *CmpI = dyn_cast<CmpInst>(V)) {
1436 if (CmpI->getPredicate() == CmpInst::Predicate::ICMP_EQ ||
1437 CmpI->getPredicate() == CmpInst::Predicate::FCMP_OEQ ||
1438 (CmpI->getPredicate() == CmpInst::Predicate::FCMP_UEQ &&
1439 CmpI->getFastMathFlags().noNaNs())) {
1440 Value *CmpLHS = CmpI->getOperand(0);
1441 Value *CmpRHS = CmpI->getOperand(1);
1442 if (isa<Constant>(CmpLHS))
1447 if (RHSConst !=
nullptr && !isa<Constant>(CmpLHS))
1448 ReplaceWithConstMap[CmpLHS] = RHSConst;
1465 if (!isa<LoadInst>(I))
1477 static const unsigned KnownIDs[] = {
1492 bool GVN::processLoad(
LoadInst *L) {
1501 markInstructionForDeletion(L);
1510 return processNonLocalLoad(L);
1518 dbgs() <<
" has unknown dependence\n";);
1528 markInstructionForDeletion(L);
1534 MD->invalidateCachedPointerInfo(AvailableValue);
1543 std::pair<uint32_t, bool>
1544 GVN::ValueTable::assignExpNewValueNum(Expression &Exp) {
1545 uint32_t &e = expressionNumbering[Exp];
1546 bool CreateNewValNum = !e;
1547 if (CreateNewValNum) {
1549 if (ExprIdx.size() < nextValueNumber + 1)
1550 ExprIdx.resize(nextValueNumber * 2);
1551 e = nextValueNumber;
1552 ExprIdx[nextValueNumber++] = nextExprNumber++;
1554 return {e, CreateNewValNum};
1561 LeaderTableEntry *Vals = &Gvn.LeaderTable[Num];
1562 while (Vals && Vals->BB == BB)
1571 auto FindRes = PhiTranslateTable.find({Num, Pred});
1572 if (FindRes != PhiTranslateTable.end())
1573 return FindRes->second;
1574 uint32_t NewNum = phiTranslateImpl(Pred, PhiBlock, Num, Gvn);
1575 PhiTranslateTable.insert({{Num, Pred}, NewNum});
1584 if (
PHINode *PN = NumberingPhi[Num]) {
1585 for (
unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
1586 if (PN->getParent() == PhiBlock && PN->getIncomingBlock(i) == Pred)
1596 if (!areAllValsInBB(Num, PhiBlock, Gvn))
1599 if (Num >= ExprIdx.size() || ExprIdx[Num] == 0)
1603 for (
unsigned i = 0; i < Exp.
varargs.
size(); i++) {
1607 if ((i > 1 && Exp.
opcode == Instruction::InsertValue) ||
1608 (i > 0 && Exp.
opcode == Instruction::ExtractValue))
1610 Exp.
varargs[i] = phiTranslate(Pred, PhiBlock, Exp.
varargs[i], Gvn);
1618 if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp)
1619 Exp.
opcode = (Opcode << 8) |
1621 static_cast<CmpInst::Predicate>(Exp.
opcode & 255));
1625 if (
uint32_t NewNum = expressionNumbering[Exp])
1635 auto FindRes = PhiTranslateTable.find({Num, Pred});
1636 if (FindRes != PhiTranslateTable.end())
1637 PhiTranslateTable.erase(FindRes);
1647 LeaderTableEntry Vals = LeaderTable[num];
1648 if (!Vals.Val)
return nullptr;
1650 Value *Val =
nullptr;
1651 if (DT->dominates(Vals.BB, BB)) {
1653 if (isa<Constant>(Val))
return Val;
1656 LeaderTableEntry* Next = Vals.Next;
1658 if (DT->dominates(Next->BB, BB)) {
1659 if (isa<Constant>(Next->Val))
return Next->Val;
1660 if (!Val) Val = Next->Val;
1681 "No edge between these basic blocks!");
1682 return Pred !=
nullptr;
1685 void GVN::assignBlockRPONumber(
Function &
F) {
1689 BlockRPONumber[BB] = NextBlockNumber++;
1694 bool GVN::replaceOperandsWithConsts(
Instruction *Instr)
const {
1695 bool Changed =
false;
1696 for (
unsigned OpNum = 0; OpNum < Instr->
getNumOperands(); ++OpNum) {
1698 auto it = ReplaceWithConstMap.find(Operand);
1699 if (it != ReplaceWithConstMap.end()) {
1700 assert(!isa<Constant>(Operand) &&
1701 "Replacing constants with constants is invalid");
1703 << *it->second <<
" in instruction " << *Instr <<
'\n');
1717 bool DominatesByEdge) {
1719 Worklist.
push_back(std::make_pair(LHS, RHS));
1720 bool Changed =
false;
1725 while (!Worklist.
empty()) {
1726 std::pair<Value*, Value*> Item = Worklist.
pop_back_val();
1727 LHS = Item.first; RHS = Item.second;
1734 if (isa<Constant>(LHS) && isa<Constant>(RHS))
1738 if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
1740 assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) &&
"Unexpected value!");
1746 uint32_t LVN = VN.lookupOrAdd(LHS);
1747 if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
1748 (isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
1751 uint32_t RVN = VN.lookupOrAdd(RHS);
1767 if (RootDominatesEnd && !isa<Instruction>(RHS))
1768 addToLeaderTable(LVN, RHS, Root.
getEnd());
1774 unsigned NumReplacements =
1779 Changed |= NumReplacements > 0;
1780 NumGVNEqProp += NumReplacements;
1796 bool isKnownFalse = !isKnownTrue;
1803 Worklist.
push_back(std::make_pair(A, RHS));
1804 Worklist.
push_back(std::make_pair(B, RHS));
1811 if (
CmpInst *Cmp = dyn_cast<CmpInst>(LHS)) {
1812 Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
1818 Worklist.
push_back(std::make_pair(Op0, Op1));
1832 if (isa<ConstantFP>(Op1) && !cast<ConstantFP>(Op1)->
isZero())
1833 Worklist.
push_back(std::make_pair(Op0, Op1));
1842 uint32_t NextNum = VN.getNextUnusedValueNumber();
1843 uint32_t Num = VN.lookupOrAddCmp(Cmp->getOpcode(), NotPred, Op0, Op1);
1846 if (Num < NextNum) {
1848 if (NotCmp && isa<Instruction>(NotCmp)) {
1849 unsigned NumReplacements =
1854 Changed |= NumReplacements > 0;
1855 NumGVNEqProp += NumReplacements;
1862 if (RootDominatesEnd)
1863 addToLeaderTable(Num, NotVal, Root.
getEnd());
1876 if (isa<DbgInfoIntrinsic>(I))
1885 bool Changed =
false;
1891 markInstructionForDeletion(I);
1895 if (MD && V->getType()->isPtrOrPtrVectorTy())
1896 MD->invalidateCachedPointerInfo(V);
1904 return processAssumeIntrinsic(IntrinsicI);
1906 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
1907 if (processLoad(LI))
1910 unsigned Num = VN.lookupOrAdd(LI);
1911 addToLeaderTable(Num, LI, LI->
getParent());
1917 if (
BranchInst *BI = dyn_cast<BranchInst>(I)) {
1918 if (!BI->isConditional())
1921 if (isa<Constant>(BI->getCondition()))
1922 return processFoldableCondBr(BI);
1924 Value *BranchCond = BI->getCondition();
1928 if (TrueSucc == FalseSucc)
1932 bool Changed =
false;
1936 Changed |= propagateEquality(BranchCond, TrueVal, TrueE,
true);
1940 Changed |= propagateEquality(BranchCond, FalseVal, FalseE,
true);
1947 Value *SwitchCond =
SI->getCondition();
1949 bool Changed =
false;
1953 for (
unsigned i = 0, n =
SI->getNumSuccessors(); i != n; ++i)
1954 ++SwitchEdges[
SI->getSuccessor(i)];
1960 if (SwitchEdges.
lookup(Dst) == 1) {
1962 Changed |= propagateEquality(SwitchCond, i->getCaseValue(),
E,
true);
1973 uint32_t NextNum = VN.getNextUnusedValueNumber();
1974 unsigned Num = VN.lookupOrAdd(I);
1978 if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
1979 addToLeaderTable(Num, I, I->
getParent());
1986 if (Num >= NextNum) {
1987 addToLeaderTable(Num, I, I->
getParent());
1996 addToLeaderTable(Num, I, I->
getParent());
1998 }
else if (Repl == I) {
2007 MD->invalidateCachedPointerInfo(Repl);
2008 markInstructionForDeletion(I);
2021 VN.setAliasAnalysis(&RunAA);
2024 OI = &OrderedInstrs;
2028 bool Changed =
false;
2029 bool ShouldContinue =
true;
2040 Changed |= removedBlock;
2043 unsigned Iteration = 0;
2044 while (ShouldContinue) {
2046 ShouldContinue = iterateOnFunction(F);
2047 Changed |= ShouldContinue;
2054 assignValNumForDeadCode();
2055 assignBlockRPONumber(F);
2056 bool PREChanged =
true;
2057 while (PREChanged) {
2058 PREChanged = performPRE(F);
2059 Changed |= PREChanged;
2068 cleanupGlobalSets();
2079 assert(InstrsToErase.empty() &&
2080 "We expect InstrsToErase to be empty across iterations");
2081 if (DeadBlocks.count(BB))
2085 ReplaceWithConstMap.clear();
2086 bool ChangedFunction =
false;
2090 if (!ReplaceWithConstMap.empty())
2091 ChangedFunction |= replaceOperandsWithConsts(&*BI);
2092 ChangedFunction |= processInstruction(&*BI);
2094 if (InstrsToErase.empty()) {
2100 NumGVNInstr += InstrsToErase.size();
2103 bool AtStart = BI == BB->
begin();
2107 bool InvalidateImplicitCF =
false;
2108 const Instruction *MaybeFirstICF = FirstImplicitControlFlowInsts.lookup(BB);
2109 for (
auto *I : InstrsToErase) {
2110 assert(I->
getParent() == BB &&
"Removing instruction from wrong block?");
2113 if (MD) MD->removeInstruction(I);
2115 if (MaybeFirstICF == I) {
2117 InvalidateImplicitCF =
true;
2119 MaybeFirstICF =
nullptr;
2124 OI->invalidateBlock(BB);
2125 InstrsToErase.
clear();
2126 if (InvalidateImplicitCF)
2127 fillImplicitControlFlowInfo(BB);
2135 return ChangedFunction;
2148 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2154 if (!VN.exists(Op)) {
2159 VN.phiTranslate(Pred, Curr, VN.lookup(Op), *
this);
2160 if (
Value *V = findLeader(Pred, TValNo)) {
2178 unsigned Num = VN.lookupOrAdd(Instr);
2182 addToLeaderTable(Num, Instr, Pred);
2186 bool GVN::performScalarPRE(
Instruction *CurInst) {
2187 if (isa<AllocaInst>(CurInst) || isa<TerminatorInst>(CurInst) ||
2190 isa<DbgInfoIntrinsic>(CurInst))
2197 if (isa<CmpInst>(CurInst))
2201 if (
CallInst *CallI = dyn_cast<CallInst>(CurInst))
2202 if (CallI->isInlineAsm())
2205 uint32_t ValNo = VN.lookup(CurInst);
2213 unsigned NumWith = 0;
2214 unsigned NumWithout = 0;
2222 if (!DT->isReachableFromEntry(
P)) {
2229 if (BlockRPONumber[
P] >= BlockRPONumber[CurrentBlock] &&
2231 if (
auto *Inst = dyn_cast<Instruction>(U.get()))
2232 return Inst->getParent() == CurrentBlock;
2239 uint32_t TValNo = VN.phiTranslate(
P, CurrentBlock, ValNo, *
this);
2240 Value *predV = findLeader(
P, TValNo);
2242 predMap.
push_back(std::make_pair(static_cast<Value *>(
nullptr),
P));
2245 }
else if (predV == CurInst) {
2257 if (NumWithout > 1 || NumWith == 0)
2265 if (NumWithout != 0) {
2271 auto It = FirstImplicitControlFlowInsts.find(CurrentBlock);
2272 if (It != FirstImplicitControlFlowInsts.end()) {
2273 assert(It->second->getParent() == CurrentBlock &&
2274 "Implicit control flow map broken?");
2275 if (OI->dominates(It->second, CurInst))
2289 toSplit.push_back(std::make_pair(PREPred->
getTerminator(), SuccNum));
2293 PREInstr = CurInst->
clone();
2294 if (!performScalarPREInsertion(PREInstr, PREPred, CurrentBlock, ValNo)) {
2304 assert(PREInstr !=
nullptr || NumWithout == 0);
2311 CurInst->
getName() +
".pre-phi", &CurrentBlock->
front());
2312 for (
unsigned i = 0, e = predMap.
size(); i != e; ++i) {
2325 VN.eraseTranslateCacheEntry(ValNo, *CurrentBlock);
2326 addToLeaderTable(ValNo, Phi, CurrentBlock);
2330 MD->invalidateCachedPointerInfo(Phi);
2332 removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
2336 MD->removeInstruction(CurInst);
2338 bool InvalidateImplicitCF =
2339 FirstImplicitControlFlowInsts.lookup(CurInst->
getParent()) == CurInst;
2342 OI->invalidateBlock(CurrentBlock);
2344 if (InvalidateImplicitCF)
2345 fillImplicitControlFlowInfo(CurrentBlock);
2353 bool GVN::performPRE(
Function &F) {
2354 bool Changed =
false;
2361 if (CurrentBlock->isEHPad())
2365 BE = CurrentBlock->end();
2368 Changed |= performScalarPRE(CurInst);
2372 if (splitCriticalEdges())
2384 MD->invalidateCachedPredecessors();
2390 bool GVN::splitCriticalEdges() {
2391 if (toSplit.empty())
2394 std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
2397 }
while (!toSplit.empty());
2398 if (MD) MD->invalidateCachedPredecessors();
2403 bool GVN::iterateOnFunction(
Function &F) {
2404 cleanupGlobalSets();
2407 bool Changed =
false;
2414 fillImplicitControlFlowInfo(BB);
2416 Changed |= processBlock(BB);
2421 void GVN::cleanupGlobalSets() {
2423 LeaderTable.clear();
2424 BlockRPONumber.clear();
2425 TableAllocator.Reset();
2426 FirstImplicitControlFlowInsts.clear();
2430 GVN::fillImplicitControlFlowInfo(
BasicBlock *BB) {
2433 assert(InstrsToErase.empty() &&
"Filling before removed all marked insns?");
2434 auto MayNotTransferExecutionToSuccessor = [&](
const Instruction *
I) {
2449 if (isa<LoadInst>(I)) {
2451 "Non-volatile load should transfer execution to successor!");
2454 if (isa<StoreInst>(I)) {
2456 "Non-volatile store should transfer execution to successor!");
2461 FirstImplicitControlFlowInsts.erase(BB);
2464 if (MayNotTransferExecutionToSuccessor(&I)) {
2465 FirstImplicitControlFlowInsts[BB] = &
I;
2472 void GVN::verifyRemoved(
const Instruction *Inst)
const {
2473 VN.verifyRemoved(Inst);
2478 I = LeaderTable.begin(),
E = LeaderTable.end(); I !=
E; ++
I) {
2479 const LeaderTableEntry *Node = &I->second;
2480 assert(Node->Val != Inst &&
"Inst still in value numbering scope!");
2482 while (Node->Next) {
2484 assert(Node->Val != Inst &&
"Inst still in value numbering scope!");
2498 while (!NewDead.
empty()) {
2500 if (DeadBlocks.count(D))
2505 DT->getDescendants(D, Dom);
2511 if (DeadBlocks.count(S))
2514 bool AllPredDead =
true;
2516 if (!DeadBlocks.count(
P)) {
2517 AllPredDead =
false;
2540 if (DeadBlocks.count(B))
2545 if (!DeadBlocks.count(
P))
2550 DeadBlocks.insert(
P = S);
2554 PHINode &Phi = cast<PHINode>(*II);
2575 bool GVN::processFoldableCondBr(
BranchInst *BI) {
2589 if (DeadBlocks.count(DeadRoot))
2593 DeadRoot = splitCriticalEdges(BI->
getParent(), DeadRoot);
2595 addDeadBlock(DeadRoot);
2603 void GVN::assignValNumForDeadCode() {
2606 unsigned ValNum = VN.lookupOrAdd(&Inst);
2607 addToLeaderTable(ValNum, &Inst, BB);
2622 if (skipFunction(F))
2625 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
2627 return Impl.runImpl(
2628 F, getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
2629 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
2630 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
2631 getAnalysis<AAResultsWrapperPass>().getAAResults(),
2633 : &getAnalysis<MemoryDependenceWrapperPass>().getMemDep(),
2634 LIWP ? &LIWP->getLoopInfo() :
nullptr,
2635 &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE());
Legacy wrapper pass to provide the GlobalsAAResult object.
static AvailableValueInBlock get(BasicBlock *BB, AvailableValue &&AV)
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
FunctionPass * createGVNPass(bool NoLoads=false)
Create a legacy GVN pass.
static cl::opt< bool > EnableLoadPRE("enable-load-pre", cl::init(true))
void push_back(const T &Elt)
void eraseTranslateCacheEntry(uint32_t Num, const BasicBlock &CurrBlock)
Erase stale entry from phiTranslate cache so phiTranslate can be computed again.
A parsed version of the target data layout string in and methods for querying it. ...
bool isUndefValue() const
static ConstantInt * getFalse(LLVMContext &Context)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
This class is the base class for the comparison instructions.
static bool runImpl(Function &F, TargetLibraryInfo &TLI, DominatorTree &DT)
This is the entry point for all transforms.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
bool MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemoryDependenceResults *MemDep=nullptr, DeferredDominance *DDT=nullptr)
Attempts to merge a block into its predecessor, if possible.
Helper class for SSA formation on a set of values defined in multiple blocks.
Provides a lazy, caching interface for making common memory aliasing information queries, backed by LLVM's alias analysis passes.
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...
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static AvailableValue getMI(MemIntrinsic *MI, unsigned Offset=0)
unsigned Offset
Offset - The byte offset in Val that is interesting for the load query.
DiagnosticInfoOptimizationBase::Argument NV
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Compute iterated dominance frontiers using a linear time algorithm.
PointerTy getPointer() const
bool isAtomic() const
Return true if this instruction has an AtomicOrdering of unordered or higher.
This is the interface for a simple mod/ref and alias analysis over globals.
void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
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...
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value...
bool operator==(const Expression &other) const
This class represents a function call, abstracting a target machine's calling convention.
bool isNonLocal() const
Tests if this MemDepResult represents a query that is transparent to the start of the block...
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
bool salvageDebugInfo(Instruction &I)
Assuming the instruction I is going to be deleted, attempt to salvage debug users of I by writing the...
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
uint32_t phiTranslate(const BasicBlock *BB, const BasicBlock *PhiBlock, uint32_t Num, GVN &Gvn)
Wrap phiTranslateImpl to provide caching functionality.
1 1 1 0 True if unordered or not equal
void deleteValue()
Delete a pointer to a generic Value.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
This class implements a map that also provides access to all stored values in a deterministic order...
BasicBlock * getSuccessor(unsigned i) const
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
bool isCoercedLoadValue() const
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
An instruction for reading from memory.
const BasicBlock * getEnd() const
Value * getCondition() const
This defines the Use class.
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.
iterator end()
Get an iterator to the end of the SetVector.
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...
LLVMContext & getContext() const
Get the context in which this basic block lives.
gvn Early GVN Hoisting of Expressions
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
iterator begin()
Instruction iterator methods.
uint32_t lookup(Value *V, bool Verify=true) const
Returns the value number of the specified value.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
void dump() const
Support for debugging, callable in GDB: V->dump()
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool isVolatile() const
Return true if this is a load from a volatile memory location.
static cl::opt< uint32_t > MaxRecurseDepth("max-recurse-depth", cl::Hidden, cl::init(1000), cl::ZeroOrMore, cl::desc("Max recurse depth (default = 1000)"))
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
static cl::opt< bool > EnablePRE("enable-pre", cl::init(true), cl::Hidden)
bool isDef() const
Tests if this MemDepResult represents a query that is an instruction definition dependency.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
Option class for critical edge splitting.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
void clear()
Remove all entries from the ValueTable.
bool isClobber() const
Tests if this MemDepResult represents a query that is an instruction clobber dependency.
A Use represents the edge between a Value definition and its users.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
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...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
MemoryDependenceResults & getMemDep() const
bool isIntegerTy() const
True if this is an instance of IntegerType.
This file contains the simple types necessary to represent the attributes associated with functions a...
An analysis that produces MemoryDependenceResults for a function.
void setName(const Twine &Name)
Change the name of the value.
Analysis pass that exposes the LoopInfo for a function.
static const uint16_t * lookup(unsigned opcode, unsigned domain, ArrayRef< uint16_t[3]> Table)
bool isSimpleValue() const
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...
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
static void patchReplacementInstruction(Instruction *I, Value *Repl)
Type * getType() const
All values are typed, get the type of this value.
ppc ctr loops PowerPC CTR Loops Verify
bool insert(const value_type &X)
Insert a new element into the SetVector.
The core GVN pass object.
bool canCoerceMustAliasedValueToLoad(Value *StoredVal, Type *LoadTy, const DataLayout &DL)
Return true if CoerceAvailableValueToLoadType would succeed if it was called.
Expression(uint32_t o=~2U)
void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction...
iterator begin()
Get an iterator to the beginning of the SetVector.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
DiagnosticInfoOptimizationBase::setExtraArgs setExtraArgs
static AvailableValue getLoad(LoadInst *LI, unsigned Offset=0)
hash_code hash_value(const APFloat &Arg)
See friend declarations above.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LoadInst * getCoercedLoadValue() const
static GVN::Expression getEmptyKey()
An instruction for storing to memory.
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
void add(Value *V, uint32_t num)
add - Insert a value into the table with a specified value number.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void takeName(Value *V)
Transfer the name from V to this value.
static unsigned getHashValue(const GVN::Expression &e)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Value * getOperand(unsigned i) const
Interval::succ_iterator succ_end(Interval *I)
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...
void initializeGVNLegacyPassPass(PassRegistry &)
bool isVoidTy() const
Return true if this is 'void'.
const BasicBlock & getEntryBlock() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
void getAAMetadata(AAMDNodes &N, bool Merge=false) const
Fills the AAMDNodes structure with AA metadata from this instruction.
BasicBlock * SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
If this edge is a critical edge, insert a new node to split the critical edge.
initializer< Ty > init(const Ty &Val)
bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
Value * GetValueInMiddleOfBlock(BasicBlock *BB)
Construct SSA form, materializing a value that is live in the middle of the specified block...
SmallVector< uint32_t, 4 > varargs
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
A set of analyses that are preserved following a run of a transformation pass.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
LLVM Basic Block Representation.
PointerIntPair - This class implements a pair of a pointer and small integer.
PHITransAddr - An address value which tracks and handles phi translation.
The instances of the Type class are immutable: once they are created, they are never changed...
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
Conditional or Unconditional Branch instruction.
This file provides the interface for LLVM's Global Value Numbering pass which eliminates fully redund...
static GVN::Expression getTombstoneKey()
static Value * ConstructSSAForLoadSet(LoadInst *LI, SmallVectorImpl< AvailableValueInBlock > &ValuesPerBlock, GVN &gvn)
Given a set of loads specified by ValuesPerBlock, construct SSA form, allowing us to eliminate LI...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
static bool isEqual(const GVN::Expression &LHS, const GVN::Expression &RHS)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & front() const
A manager for alias analyses.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
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...
Represent the analysis usage information of a pass.
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Analysis pass providing a never-invalidated alias analysis result.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
PointerIntPair< Value *, 2, ValType > Val
V - The value that is live out of the block.
MemIntrinsic * getMemIntrinValue() const
FunctionPass class - This class is used to implement most global optimizations.
Interval::pred_iterator pred_end(Interval *I)
Value * getPointerOperand()
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...
GVNLegacyPass(bool NoLoads=false)
static void reportLoadElim(LoadInst *LI, Value *AvailableValue, OptimizationRemarkEmitter *ORE)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
A wrapper analysis pass for the legacy pass manager that exposes a MemoryDepnedenceResults instance...
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
A memory dependence query can return one of three different answers.
DominatorTree & getDominatorTree() const
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
static void reportMayClobberedLoad(LoadInst *LI, 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...
A function analysis which provides an AssumptionCache.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Value * MaterializeAdjustedValue(LoadInst *LI, GVN &gvn) const
Emit code at the end of this block to adjust the value defined here to the specified type...
A SetVector that performs no allocations if smaller than a certain size.
This is the common base class for memset/memcpy/memmove.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
const MemDepResult & getResult() const
size_type count(const KeyT &Key) const
BasicBlock * getBB() const
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
LLVM_NODISCARD T pop_back_val()
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
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 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...
pred_range predecessors(BasicBlock *BB)
Value * MaterializeAdjustedValue(LoadInst *LI, Instruction *InsertPt, GVN &gvn) const
Emit code at the specified insertion point to adjust the value defined here to the specified type...
static ConstantInt * getTrue(LLVMContext &Context)
bool isCommutative() const
Return true if the instruction is commutative:
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Represents an AvailableValue which can be rematerialized at the end of the associated BasicBlock...
iterator_range< user_iterator > users()
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
std::vector< NonLocalDepEntry > NonLocalDepInfo
An opaque object representing a hash code.
bool isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates uninitialized memory (such ...
iterator insert(iterator I, T &&Elt)
void verifyRemoved(const Value *) const
verifyRemoved - Verify that the value is removed from all internal data structures.
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
void erase(Value *v)
Remove a value from the value numbering.
static bool isLifetimeStart(const Instruction *Inst)
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
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...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
unsigned getAlignment() const
Return the alignment of the access that is being performed.
Instruction * getInst() const
If this is a normal dependency, returns the instruction that is depended on.
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...
LLVM_NODISCARD bool empty() const
unsigned getNumArgOperands() const
Return the number of call arguments.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
bool isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates zero-filled memory (such as...
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
bool mayReadFromMemory() const
Return true if this instruction may read memory.
static AvailableValue get(Value *V, unsigned Offset=0)
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
bool exists(Value *V) const
Returns true if a value number exists for the specified value.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void preserve()
Mark an analysis as preserved.
bool isUnconditional() const
friend hash_code hash_value(const Expression &Value)
uint32_t lookupOrAdd(Value *V)
lookup_or_add - Returns the value number for the specified value, assigning it a new number if it did...
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...
Value * getSimpleValue() const
Analysis pass providing the TargetLibraryInfo.
iterator_range< df_iterator< T > > depth_first(const T &G)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
const BasicBlock * getStart() const
Represents a particular available value that we know how to materialize.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
static bool IsValueFullyAvailableInBlock(BasicBlock *BB, DenseMap< BasicBlock *, char > &FullyAvailableBlocks, uint32_t RecurseDepth)
Return true if we can prove that the value we're analyzing is fully available in the specified block...
0 0 0 1 True if ordered and equal
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
succ_range successors(BasicBlock *BB)
static AvailableValueInBlock getUndef(BasicBlock *BB)
void removeInstruction(Instruction *InstToRemove)
Removes an instruction from the dependence analysis, updating the dependence of instructions that pre...
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
bool hasOneUse() const
Return true if there is exactly one user of this value.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
This is an entry in the NonLocalDepInfo cache.
A container for analyses that lazily runs them and caches their results.
BasicBlock * BB
BB - The basic block in question.
static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl)
Legacy analysis pass which computes a DominatorTree.
bool isMemIntrinValue() const
static bool isVolatile(Instruction *Inst)
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
This header defines various interfaces for pass management in LLVM.
void setIncomingValue(unsigned i, Value *V)
AvailableValue AV
AV - The actual available value.
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
static IntegerType * getInt8Ty(LLVMContext &C)
void combineMetadata(Instruction *K, const Instruction *J, ArrayRef< unsigned > KnownIDs)
Combine the metadata of two instructions so that K can replace J.
static AvailableValue getUndef()
static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E, DominatorTree *DT)
There is an edge from 'Src' to 'Dst'.
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
This instruction inserts a struct field of array element value into an aggregate value.
bool HasValueForBlock(BasicBlock *BB) const
Return true if the SSAUpdater already has a value for the specified block.
bool isCriticalEdge(const TerminatorInst *TI, unsigned SuccNum, bool AllowIdenticalEdges=false)
Return true if the specified edge is a critical edge.