64 #define DEBUG_TYPE "sccp" 66 STATISTIC(NumInstRemoved,
"Number of instructions removed");
67 STATISTIC(NumDeadBlocks ,
"Number of basic blocks unreachable");
69 STATISTIC(IPNumInstRemoved,
"Number of instructions removed by IPSCCP");
70 STATISTIC(IPNumArgsElimed ,
"Number of arguments constant propagated by IPSCCP");
71 STATISTIC(IPNumGlobalConst,
"Number of globals found to be constant by IPSCCP");
101 LatticeValueTy getLatticeValue()
const {
106 LatticeVal() : Val(nullptr, unknown) {}
108 bool isUnknown()
const {
return getLatticeValue() == unknown; }
111 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
114 bool isOverdefined()
const {
return getLatticeValue() == overdefined; }
122 bool markOverdefined() {
132 if (getLatticeValue() == constant) {
139 assert(V &&
"Marking constant with NULL");
142 assert(getLatticeValue() == forcedconstant &&
143 "Cannot move from overdefined to constant!");
171 void markForcedConstant(
Constant *V) {
172 assert(isUnknown() &&
"Can't force a defined value!");
173 Val.
setInt(forcedconstant);
191 class SCCPSolver :
public InstVisitor<SCCPSolver> {
246 using Edge = std::pair<BasicBlock *, BasicBlock *>;
251 : DL(DL), TLI(tli) {}
258 if (!BBExecutable.
insert(BB).second)
272 LatticeVal &IV = TrackedGlobals[GV];
284 MRVFunctionsTracked.
insert(F);
285 for (
unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
286 TrackedMultipleRetVals.
insert(std::make_pair(std::make_pair(F, i),
289 TrackedRetVals.
insert(std::make_pair(F, LatticeVal()));
294 void AddMustTailCallee(
Function *F) {
295 MustTailCallees.
insert(F);
300 bool isMustTailCallee(
Function *F) {
301 return MustTailCallees.
count(F);
304 void AddArgumentTrackedFunction(
Function *F) {
305 TrackingIncomingArguments.
insert(F);
310 bool isArgumentTrackedFunction(
Function *F) {
311 return TrackingIncomingArguments.
count(F);
324 bool isBlockExecutable(
BasicBlock *BB)
const {
325 return BBExecutable.
count(BB);
332 std::vector<LatticeVal> getStructLatticeValueFor(
Value *V)
const {
333 std::vector<LatticeVal> StructValues;
335 assert(STy &&
"getStructLatticeValueFor() can be called only on structs");
336 for (
unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
337 auto I = StructValueState.
find(std::make_pair(V, i));
338 assert(
I != StructValueState.
end() &&
"Value not in valuemap!");
339 StructValues.push_back(
I->second);
344 const LatticeVal &getLatticeValueFor(
Value *V)
const {
346 "Should use getStructLatticeValueFor");
349 "V not found in ValueState nor Paramstate map!");
355 return TrackedRetVals;
361 return TrackedGlobals;
367 return MRVFunctionsTracked;
373 return MustTailCallees;
378 void markOverdefined(
Value *V) {
379 if (
auto *STy = dyn_cast<StructType>(V->
getType()))
380 for (
unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
381 markOverdefined(getStructValueState(V, i), V);
383 markOverdefined(ValueState[V], V);
391 const auto &It = TrackedMultipleRetVals.
find(std::make_pair(F, i));
392 assert(It != TrackedMultipleRetVals.
end());
393 LatticeVal LV = It->second;
394 if (LV.isOverdefined())
402 void pushToWorkList(LatticeVal &IV,
Value *V) {
403 if (IV.isOverdefined())
404 return OverdefinedInstWorkList.
push_back(V);
412 if (!IV.markConstant(C))
return false;
413 LLVM_DEBUG(
dbgs() <<
"markConstant: " << *C <<
": " << *V <<
'\n');
414 pushToWorkList(IV, V);
420 return markConstant(ValueState[V], V, C);
425 LatticeVal &IV = ValueState[V];
426 IV.markForcedConstant(C);
427 LLVM_DEBUG(
dbgs() <<
"markForcedConstant: " << *C <<
": " << *V <<
'\n');
428 pushToWorkList(IV, V);
434 bool markOverdefined(LatticeVal &IV,
Value *V) {
435 if (!IV.markOverdefined())
return false;
438 if (
auto *F = dyn_cast<Function>(V))
dbgs()
439 <<
"Function '" << F->
getName() <<
"'\n";
440 else dbgs() << *V <<
'\n');
442 pushToWorkList(IV, V);
446 bool mergeInValue(LatticeVal &IV,
Value *V, LatticeVal MergeWithV) {
447 if (IV.isOverdefined() || MergeWithV.isUnknown())
449 if (MergeWithV.isOverdefined())
450 return markOverdefined(IV, V);
452 return markConstant(IV, V, MergeWithV.getConstant());
453 if (IV.getConstant() != MergeWithV.getConstant())
454 return markOverdefined(IV, V);
458 bool mergeInValue(
Value *V, LatticeVal MergeWithV) {
460 "non-structs should use markConstant");
461 return mergeInValue(ValueState[V], V, MergeWithV);
467 LatticeVal &getValueState(
Value *V) {
470 std::pair<DenseMap<Value*, LatticeVal>::iterator,
bool> I =
471 ValueState.
insert(std::make_pair(V, LatticeVal()));
472 LatticeVal &LV = I.first->second;
477 if (
auto *C = dyn_cast<Constant>(V)) {
479 if (!isa<UndefValue>(V))
490 std::pair<DenseMap<Value*, ValueLatticeElement>::iterator,
bool>
494 LV = getValueState(V).toValueLattice();
502 LatticeVal &getStructValueState(
Value *V,
unsigned i) {
504 assert(i < cast<StructType>(V->
getType())->getNumElements() &&
505 "Invalid element #");
507 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
508 bool> I = StructValueState.
insert(
509 std::make_pair(std::make_pair(V, i), LatticeVal()));
510 LatticeVal &LV = I.first->second;
515 if (
auto *C = dyn_cast<Constant>(V)) {
519 LV.markOverdefined();
520 else if (isa<UndefValue>(Elt))
523 LV.markConstant(Elt);
533 if (!KnownFeasibleEdges.
insert(Edge(Source, Dest)).second)
536 if (!MarkBlockExecutable(Dest)) {
541 <<
" -> " << Dest->
getName() <<
'\n');
582 markOverdefined(&CPI);
583 visitTerminatorInst(CPI);
598 visitTerminatorInst(II);
609 LLVM_DEBUG(
dbgs() <<
"SCCP: Don't know how to handle: " << I <<
'\n');
621 if (
auto *BI = dyn_cast<BranchInst>(&TI)) {
622 if (BI->isUnconditional()) {
627 LatticeVal BCValue = getValueState(BI->getCondition());
632 if (!BCValue.isUnknown())
633 Succs[0] = Succs[1] =
true;
638 Succs[CI->isZero()] =
true;
648 if (
auto *
SI = dyn_cast<SwitchInst>(&TI)) {
649 if (!
SI->getNumCases()) {
653 LatticeVal SCValue = getValueState(
SI->getCondition());
658 if (!SCValue.isUnknown())
663 Succs[
SI->findCaseValue(CI)->getSuccessorIndex()] =
true;
669 if (
auto *IBR = dyn_cast<IndirectBrInst>(&TI)) {
671 LatticeVal IBRValue = getValueState(IBR->getAddress());
675 if (!IBRValue.isUnknown())
682 "Block address of a different function ?");
683 for (
unsigned i = 0; i < IBR->getNumSuccessors(); ++i) {
685 if (IBR->getDestination(i) ==
T) {
696 LLVM_DEBUG(
dbgs() <<
"Unknown terminator instruction: " << TI <<
'\n');
706 return KnownFeasibleEdges.
count(Edge(From, To));
726 void SCCPSolver::visitPHINode(
PHINode &PN) {
730 return (
void)markOverdefined(&PN);
732 if (getValueState(&PN).isOverdefined())
738 return (
void)markOverdefined(&PN);
748 if (IV.isUnknown())
continue;
753 if (IV.isOverdefined())
754 return (
void)markOverdefined(&PN);
757 OperandVal = IV.getConstant();
767 if (IV.getConstant() != OperandVal)
768 return (
void)markOverdefined(&PN);
776 markConstant(&PN, OperandVal);
779 void SCCPSolver::visitReturnInst(
ReturnInst &I) {
788 TrackedRetVals.
find(F);
789 if (TFRVI != TrackedRetVals.
end()) {
790 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
796 if (!TrackedMultipleRetVals.
empty()) {
797 if (
auto *STy = dyn_cast<StructType>(ResultOp->
getType()))
798 if (MRVFunctionsTracked.
count(F))
800 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)],
F,
801 getStructValueState(ResultOp, i));
807 getFeasibleSuccessors(TI, SuccFeasible);
812 for (
unsigned i = 0, e = SuccFeasible.
size(); i != e; ++i)
817 void SCCPSolver::visitCastInst(
CastInst &I) {
818 LatticeVal OpSt = getValueState(I.
getOperand(0));
819 if (OpSt.isOverdefined())
821 else if (OpSt.isConstant()) {
825 if (isa<UndefValue>(C))
836 return (
void)markOverdefined(&EVI);
840 return (
void)markOverdefined(&EVI);
845 LatticeVal EltVal = getStructValueState(AggVal, i);
846 mergeInValue(getValueState(&EVI), &EVI, EltVal);
849 return (
void)markOverdefined(&EVI);
856 return (
void)markOverdefined(&IVI);
861 return (
void)markOverdefined(&IVI);
870 LatticeVal EltVal = getStructValueState(Aggr, i);
871 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
878 markOverdefined(getStructValueState(&IVI, i), &IVI);
880 LatticeVal InVal = getValueState(Val);
881 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
886 void SCCPSolver::visitSelectInst(
SelectInst &I) {
890 return (
void)markOverdefined(&I);
893 if (CondValue.isUnknown())
896 if (
ConstantInt *CondCB = CondValue.getConstantInt()) {
898 mergeInValue(&I, getValueState(OpVal));
909 if (TVal.isConstant() && FVal.isConstant() &&
910 TVal.getConstant() == FVal.getConstant())
911 return (
void)markConstant(&I, FVal.getConstant());
913 if (TVal.isUnknown())
914 return (
void)mergeInValue(&I, FVal);
915 if (FVal.isUnknown())
916 return (
void)mergeInValue(&I, TVal);
921 void SCCPSolver::visitBinaryOperator(
Instruction &I) {
922 LatticeVal V1State = getValueState(I.
getOperand(0));
923 LatticeVal V2State = getValueState(I.
getOperand(1));
925 LatticeVal &IV = ValueState[&
I];
926 if (IV.isOverdefined())
return;
928 if (V1State.isConstant() && V2State.isConstant()) {
930 V2State.getConstant());
932 if (isa<UndefValue>(C))
934 return (
void)markConstant(IV, &I, C);
938 if (!V1State.isOverdefined() && !V2State.isOverdefined())
946 if (V1State.isConstant() && V1State.getConstant()->isNullValue())
947 return (
void)markConstant(IV, &I, V1State.getConstant());
955 LatticeVal *NonOverdefVal =
nullptr;
956 if (!V1State.isOverdefined())
957 NonOverdefVal = &V1State;
958 else if (!V2State.isOverdefined())
959 NonOverdefVal = &V2State;
962 if (NonOverdefVal->isUnknown())
969 if (NonOverdefVal->getConstant()->isNullValue())
970 return (
void)markConstant(IV, &I, NonOverdefVal->getConstant());
973 if (
ConstantInt *CI = NonOverdefVal->getConstantInt())
974 if (CI->isMinusOne())
975 return (
void)markConstant(IV, &I, NonOverdefVal->getConstant());
984 void SCCPSolver::visitCmpInst(
CmpInst &I) {
985 LatticeVal &IV = ValueState[&
I];
986 if (IV.isOverdefined())
return;
993 auto V1Param = ParamState.
find(Op1);
996 : getValueState(Op1).toValueLattice();
998 auto V2Param = ParamState.
find(Op2);
1001 : getValueState(Op2).toValueLattice();
1005 if (isa<UndefValue>(C))
1009 mergeInValue(&I, CV);
1017 markOverdefined(&I);
1023 if (ValueState[&I].isOverdefined())
return;
1029 LatticeVal State = getValueState(I.
getOperand(i));
1030 if (State.isUnknown())
1033 if (State.isOverdefined())
1034 return (
void)markOverdefined(&I);
1036 assert(State.isConstant() &&
"Unknown state!");
1037 Operands.
push_back(State.getConstant());
1044 if (isa<UndefValue>(C))
1046 markConstant(&I, C);
1059 if (I == TrackedGlobals.
end() || I->second.isOverdefined())
return;
1062 mergeInValue(I->second, GV, getValueState(SI.
getOperand(0)));
1063 if (I->second.isOverdefined())
1064 TrackedGlobals.
erase(I);
1069 void SCCPSolver::visitLoadInst(
LoadInst &I) {
1072 return (
void)markOverdefined(&I);
1074 LatticeVal PtrVal = getValueState(I.
getOperand(0));
1075 if (PtrVal.isUnknown())
return;
1077 LatticeVal &IV = ValueState[&
I];
1078 if (IV.isOverdefined())
return;
1081 return (
void)markOverdefined(IV, &I);
1083 Constant *Ptr = PtrVal.getConstant();
1086 if (isa<ConstantPointerNull>(Ptr)) {
1088 return (
void)markOverdefined(IV, &I);
1094 if (
auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
1095 if (!TrackedGlobals.
empty()) {
1098 TrackedGlobals.
find(GV);
1099 if (It != TrackedGlobals.
end()) {
1100 mergeInValue(IV, &I, It->second);
1108 if (isa<UndefValue>(C))
1110 return (
void)markConstant(IV, &I, C);
1115 markOverdefined(IV, &I);
1118 void SCCPSolver::visitCallSite(
CallSite CS) {
1137 LatticeVal State = getValueState(*AI);
1139 if (State.isUnknown())
1141 if (State.isOverdefined())
1142 return (
void)markOverdefined(I);
1143 assert(State.isConstant() &&
"Unknown state!");
1144 Operands.
push_back(State.getConstant());
1147 if (getValueState(I).isOverdefined())
1154 if (isa<UndefValue>(C))
1156 return (
void)markConstant(I, C);
1161 return (
void)markOverdefined(I);
1167 if (!TrackingIncomingArguments.
empty() && TrackingIncomingArguments.
count(F)){
1168 MarkBlockExecutable(&F->
front());
1173 AI !=
E; ++AI, ++CAI) {
1177 markOverdefined(&*AI);
1181 if (
auto *STy = dyn_cast<StructType>(AI->getType())) {
1183 LatticeVal
CallArg = getStructValueState(*CAI, i);
1184 mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
1189 LatticeVal ConcreteArgument = getValueState(*CAI);
1191 getParamState(&*AI).mergeIn(ConcreteArgument.toValueLattice(), DL);
1192 bool ValueChanged = mergeInValue(&*AI, ConcreteArgument);
1197 if (!ValueChanged && ParamChanged)
1198 pushToWorkList(ValueState[&*AI], &*AI);
1205 if (!MRVFunctionsTracked.
count(F))
1206 goto CallOverdefined;
1211 mergeInValue(getStructValueState(I, i),
I,
1212 TrackedMultipleRetVals[std::make_pair(F, i)]);
1215 if (TFRVI == TrackedRetVals.
end())
1216 goto CallOverdefined;
1219 mergeInValue(I, TFRVI->second);
1223 void SCCPSolver::Solve() {
1225 while (!BBWorkList.
empty() || !InstWorkList.
empty() ||
1226 !OverdefinedInstWorkList.
empty()) {
1229 while (!OverdefinedInstWorkList.
empty()) {
1242 if (
auto *UI = dyn_cast<Instruction>(U))
1243 OperandChangedState(UI);
1247 while (!InstWorkList.
empty()) {
1261 if (
auto *UI = dyn_cast<Instruction>(U))
1262 OperandChangedState(UI);
1266 while (!BBWorkList.
empty()) {
1297 bool SCCPSolver::ResolvedUndefsIn(
Function &F) {
1299 if (!BBExecutable.
count(&BB))
1306 if (
auto *STy = dyn_cast<StructType>(I.
getType())) {
1312 if (MRVFunctionsTracked.
count(F))
1317 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(
I))
1323 LatticeVal &LV = getStructValueState(&I, i);
1325 markOverdefined(LV, &I);
1330 LatticeVal &LV = getValueState(&I);
1331 if (!LV.isUnknown())
continue;
1334 if (isa<ExtractValueInst>(I))
1341 markOverdefined(&I);
1344 LatticeVal Op0LV = getValueState(I.getOperand(0));
1346 if (I.getNumOperands() == 2) {
1348 markOverdefined(&I);
1352 Op1LV = getValueState(I.getOperand(1));
1357 switch (I.getOpcode()) {
1359 case Instruction::Sub:
1360 case Instruction::Trunc:
1361 case Instruction::FPTrunc:
1362 case Instruction::BitCast:
1364 case Instruction::FSub:
1365 case Instruction::FAdd:
1366 case Instruction::FMul:
1367 case Instruction::FDiv:
1368 case Instruction::FRem:
1370 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1373 markOverdefined(&I);
1375 case Instruction::ZExt:
1376 case Instruction::SExt:
1377 case Instruction::FPToUI:
1378 case Instruction::FPToSI:
1379 case Instruction::FPExt:
1380 case Instruction::PtrToInt:
1381 case Instruction::IntToPtr:
1382 case Instruction::SIToFP:
1383 case Instruction::UIToFP:
1387 case Instruction::Mul:
1388 case Instruction::And:
1390 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1396 case Instruction::Or:
1398 if (Op0LV.isUnknown() && Op1LV.isUnknown())
1403 case Instruction::Xor:
1407 if (Op0LV.isUnknown() && Op1LV.isUnknown()) {
1413 case Instruction::SDiv:
1414 case Instruction::UDiv:
1415 case Instruction::SRem:
1416 case Instruction::URem:
1419 if (Op1LV.isUnknown())
break;
1423 if (Op1LV.isConstant() && Op1LV.getConstant()->isZeroValue())
1430 case Instruction::AShr:
1432 if (Op1LV.isUnknown())
break;
1435 if (Op1LV.isConstant()) {
1436 if (
auto *ShiftAmt = Op1LV.getConstantInt())
1437 if (ShiftAmt->getLimitedValue() >=
1438 ShiftAmt->getType()->getScalarSizeInBits())
1445 case Instruction::LShr:
1446 case Instruction::Shl:
1449 if (Op1LV.isUnknown())
break;
1452 if (Op1LV.isConstant()) {
1453 if (
auto *ShiftAmt = Op1LV.getConstantInt())
1454 if (ShiftAmt->getLimitedValue() >=
1455 ShiftAmt->getType()->getScalarSizeInBits())
1464 Op1LV = getValueState(I.getOperand(1));
1466 if (Op0LV.isUnknown()) {
1467 if (!Op1LV.isConstant())
1468 Op1LV = getValueState(I.getOperand(2));
1469 }
else if (Op1LV.isUnknown()) {
1471 Op1LV = getValueState(I.getOperand(2));
1472 if (Op1LV.isUnknown())
1479 if (Op1LV.isConstant())
1480 markForcedConstant(&I, Op1LV.getConstant());
1482 markOverdefined(&I);
1489 case Instruction::ICmp:
1491 Op0LV = getValueState(I.getOperand(0));
1492 Op1LV = getValueState(I.getOperand(1));
1494 if ((Op0LV.isUnknown() || Op1LV.isUnknown()) &&
1495 cast<ICmpInst>(&I)->isEquality())
1497 markOverdefined(&I);
1500 case Instruction::Invoke:
1507 if (TrackedRetVals.
count(F))
1512 markOverdefined(&I);
1517 markOverdefined(&I);
1526 if (
auto *BI = dyn_cast<BranchInst>(TI)) {
1527 if (!BI->isConditional())
continue;
1528 if (!getValueState(BI->getCondition()).isUnknown())
1533 if (isa<UndefValue>(BI->getCondition())) {
1544 if (markEdgeExecutable(&BB, DefaultSuccessor))
1550 if (
auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
1553 if (IBR->getNumSuccessors() < 1)
1556 if (!getValueState(IBR->getAddress()).isUnknown())
1561 if (isa<UndefValue>(IBR->getAddress())) {
1563 markEdgeExecutable(&BB, IBR->getSuccessor(0));
1572 BasicBlock *DefaultSuccessor = IBR->getSuccessor(0);
1573 if (markEdgeExecutable(&BB, DefaultSuccessor))
1579 if (
auto *SI = dyn_cast<SwitchInst>(TI)) {
1580 if (!SI->getNumCases() || !getValueState(SI->getCondition()).isUnknown())
1585 if (isa<UndefValue>(SI->getCondition())) {
1586 SI->setCondition(SI->case_begin()->getCaseValue());
1587 markEdgeExecutable(&BB, SI->case_begin()->getCaseSuccessor());
1595 BasicBlock *DefaultSuccessor = SI->case_begin()->getCaseSuccessor();
1596 if (markEdgeExecutable(&BB, DefaultSuccessor))
1609 std::vector<LatticeVal> IVs = Solver.getStructLatticeValueFor(V);
1611 [](
const LatticeVal &LV) {
return LV.isOverdefined(); }))
1613 std::vector<Constant *> ConstVals;
1615 for (
unsigned i = 0, e =
ST->getNumElements(); i != e; ++i) {
1616 LatticeVal V = IVs[i];
1617 ConstVals.push_back(V.isConstant()
1623 const LatticeVal &IV = Solver.getLatticeValueFor(V);
1624 if (IV.isOverdefined())
1629 assert(Const &&
"Constant is nullptr here!");
1640 Solver.AddMustTailCallee(F);
1642 LLVM_DEBUG(
dbgs() <<
" Can\'t treat the result of musttail call : " << *CI
1643 <<
" as a constant\n");
1647 LLVM_DEBUG(
dbgs() <<
" Constant: " << *Const <<
" = " << *V <<
'\n');
1659 SCCPSolver Solver(DL, TLI);
1662 Solver.MarkBlockExecutable(&F.
front());
1666 Solver.markOverdefined(&AI);
1669 bool ResolvedUndefs =
true;
1670 while (ResolvedUndefs) {
1673 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1676 bool MadeChanges =
false;
1683 if (!Solver.isBlockExecutable(&BB)) {
1750 if (skipFunction(F))
1754 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1764 "Sparse Conditional Constant Propagation",
false,
false)
1774 SCCPSolver &Solver) {
1776 if (!Solver.isArgumentTrackedFunction(&F))
1781 if (Solver.isMustTailCallee(&F)) {
1783 <<
" due to present musttail call of it\n");
1788 if (
CallInst *CI = BB.getTerminatingMustTailCall()) {
1789 LLVM_DEBUG(
dbgs() <<
"Can't zap return of the block due to present " 1790 <<
"musttail call : " << *CI <<
"\n");
1795 if (
auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1796 if (!isa<UndefValue>(RI->getOperand(0)))
1803 SCCPSolver Solver(DL, TLI);
1808 if (F.isDeclaration())
1814 Solver.AddTrackedFunction(&F);
1819 Solver.AddArgumentTrackedFunction(&F);
1824 Solver.MarkBlockExecutable(&F.front());
1828 Solver.markOverdefined(&AI);
1835 G.removeDeadConstantUsers();
1837 Solver.TrackValueOfGlobalVariable(&
G);
1841 bool ResolvedUndefs =
true;
1843 while (ResolvedUndefs) {
1845 ResolvedUndefs =
false;
1847 if (Solver.ResolvedUndefsIn(F)) {
1851 ResolvedUndefs =
true;
1855 bool MadeChanges =
false;
1862 if (F.isDeclaration())
1865 if (Solver.isBlockExecutable(&F.front()))
1875 if (!Solver.isBlockExecutable(&*BB)) {
1881 if (&*BB != &F.front())
1907 if (!Solver.isBlockExecutable(&F.front()))
1914 for (
unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1923 do { ++UI; }
while (UI != UE && *UI == I);
1935 if (
SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1936 Dest = SI->case_begin()->getCaseSuccessor();
1937 C = SI->case_begin()->getCaseValue();
1938 }
else if (
BranchInst *BI = dyn_cast<BranchInst>(I)) {
1939 Dest = BI->getSuccessor(1);
1942 Dest = IBR->getSuccessor(0);
1947 assert(Solver.isEdgeFeasible(I->getParent(), Dest) &&
1948 "Didn't find feasible edge?");
1951 I->setOperand(0, C);
1955 "Expect TermInst on constantint or blockaddress to be folded");
1960 F.getBasicBlockList().erase(DeadBB);
1962 BlocksToErase.clear();
1978 for (
const auto &I : RV) {
1985 for (
const auto &F : Solver.getMRVFunctionsTracked()) {
1986 assert(F->getReturnType()->isStructTy() &&
1987 "The return type should be a struct");
1988 StructType *STy = cast<StructType>(F->getReturnType());
1989 if (Solver.isStructLatticeConstant(F, STy))
1994 for (
unsigned i = 0, e = ReturnsToZap.
size(); i != e; ++i) {
1995 Function *F = ReturnsToZap[i]->getParent()->getParent();
2003 E = TG.
end(); I !=
E; ++
I) {
2005 assert(!I->second.isOverdefined() &&
2006 "Overdefined values should have been taken out of the map!");
2008 <<
"' is constant!\n");
2013 M.getGlobalList().
erase(GV);
Legacy wrapper pass to provide the GlobalsAAResult object.
Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
bool onlyReadsMemory() const
Determine if the function does not access or only reads memory.
Return a value (possibly void), from a function.
User::op_iterator arg_iterator
The type of iterator to use when looping over actual arguments at this call site. ...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
static ConstantInt * getFalse(LLVMContext &Context)
This class is the base class for the comparison instructions.
void setInt(IntType IntVal)
bool runIPSCCP(Module &M, const DataLayout &DL, const TargetLibraryInfo *TLI)
static bool isConstant(const MachineInstr &MI)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This class represents an incoming formal argument to a Function.
Base class for instruction visitors.
Value * getAggregateOperand()
Interprocedural Sparse Conditional Constant Propagation
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
iterator erase(iterator where)
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
Compute iterated dominance frontiers using a linear time algorithm.
PointerTy getPointer() const
This is the interface for a simple mod/ref and alias analysis over globals.
unsigned getNumIndices() const
A Module instance is used to store all the information related to an LLVM module. ...
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
An instruction for ordering other memory operations.
bool canTrackArgumentsInterprocedurally(Function *F)
Determine if the values of the given function's arguments can be tracked interprocedurally.
Implements a dense probed hash-table based set.
unsigned getNumElements() const
Random access to the elements.
bool isSafeToRemove() const
Return true if the instruction can be removed if the result is unused.
static ValueLatticeElement get(Constant *C)
This class represents a function call, abstracting a target machine's calling convention.
const Value * getTrueValue() const
STATISTIC(NumFunctions, "Total number of functions")
An instruction for reading from memory.
void reserve(size_type N)
bool isMustTailCall() const
static void findReturnsToZap(Function &F, SmallVector< ReturnInst *, 8 > &ReturnsToZap, SCCPSolver &Solver)
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
The address of a basic block.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
void setPointer(PointerTy PtrVal)
bool isVolatile() const
Return true if this is a load from a volatile memory location.
This class represents the LLVM 'select' instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
This is the base class for all instructions that perform data casts.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Class to represent struct types.
void initializeSCCPLegacyPassPass(PassRegistry &)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
InstrTy * getInstruction() const
FunctionPass * createSCCPPass()
Type * getSourceElementType() const
static int64_t getConstant(const MachineInstr *MI)
void assign(size_type NumElts, const T &Elt)
static Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible. ...
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Type * getType() const
All values are typed, get the type of this value.
Value * getInsertedValueOperand()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool isOverdefined() const
Value * getOperand(unsigned i) const
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
iterator find(const_arg_type_t< KeyT > Val)
bool canTrackReturnsInterprocedurally(Function *F)
Determine if the values of the given function's returns can be tracked interprocedurally.
bool isVoidTy() const
Return true if this is 'void'.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
static bool runOnFunction(Function &F, bool PostInlining)
bool erase(const KeyT &Val)
Type * getReturnType() const
Returns the type of the ret val.
Subclasses of this class are all able to terminate a basic block.
A set of analyses that are preserved following a run of a transformation pass.
LLVM Basic Block Representation.
PointerIntPair - This class implements a pair of a pointer and small integer.
The instances of the Type class are immutable: once they are created, they are never changed...
Conditional or Unconditional Branch instruction.
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_NODISCARD bool empty() const
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Indirect Branch Instruction.
std::pair< iterator, bool > insert(const ValueT &V)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
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.
FunctionPass class - This class is used to implement most global optimizations.
static Constant * get(StructType *T, ArrayRef< Constant *> V)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
const Function * getFunction() const
Return the function this instruction belongs to.
static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V)
Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, const DataLayout &DL)
ConstantFoldLoadFromConstPtr - Return the value that a load from C would produce if it is constant an...
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DeferredDominance *DDT=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
const Value * getCondition() const
static Constant * getAllOnesValue(Type *Ty)
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.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
idx_iterator idx_begin() const
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.
INITIALIZE_PASS_BEGIN(IPSCCPLegacyPass, "ipsccp", "Interprocedural Sparse Conditional Constant Propagation", false, false) INITIALIZE_PASS_END(IPSCCPLegacyPass
Constant * getCompare(CmpInst::Predicate Pred, Type *Ty, const ValueLatticeElement &Other) const
Compares this symbolic value with Other using Pred and returns either true, false or undef constants...
bool isExceptional() const
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
bool canTrackGlobalVariableInterprocedurally(GlobalVariable *GV)
Determine if the value maintained in the given global variable can be tracked interprocedurally.
LLVM_NODISCARD T pop_back_val()
void setPreservesCFG()
This function should be called by the pass, iff they do not:
unsigned removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB)
Remove all instructions from a basic block other than it's terminator and any present EH pad instruct...
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static const Function * getCalledFunction(const Value *V, bool LookThroughBitCast, bool &IsNoBuiltin)
bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
iterator_range< user_iterator > users()
Represents analyses that only rely on functions' control flow.
const Value * getFalseValue() const
Predicate getPredicate() const
Return the predicate for this instruction.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
LLVM_NODISCARD bool empty() const
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
user_iterator_impl< User > user_iterator
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Type * getValueType() const
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
unsigned changeToUnreachable(Instruction *I, bool UseLLVMTrap, bool PreserveLCSSA=false, DeferredDominance *DDT=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
LLVM_NODISCARD bool empty() const
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it's an indirect...
Analysis pass providing the TargetLibraryInfo.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
const BasicBlock & front() const
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
Module * getParent()
Get the module that this global value is contained inside of...
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.
bool canConstantFoldCallTo(ImmutableCallSite CS, const Function *F)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function...
static ValueLatticeElement getOverdefined()
A container for analyses that lazily runs them and caches their results.
This header defines various interfaces for pass management in LLVM.
Constant * ConstantFoldCall(ImmutableCallSite CS, Function *F, ArrayRef< Constant *> Operands, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldCall - Attempt to constant fold a call to the specified function with the specified argum...
static bool runSCCP(Function &F, const DataLayout &DL, const TargetLibraryInfo *TLI)
iterator_range< arg_iterator > args()
bool isStructTy() const
True if this is an instance of StructType.
const BasicBlock * getParent() const
This instruction inserts a struct field of array element value into an aggregate value.