87 #define DEBUG_TYPE "simplifycfg" 96 "Control the amount of phi node folding to perform (default = 2)"));
100 cl::desc(
"Control the maximal total instruction cost that we are willing " 101 "to speculatively execute to fold a 2-entry PHI node into a " 102 "select (default = 4)"));
106 cl::desc(
"Duplicate return instructions into unconditional branches"));
110 cl::desc(
"Sink common instructions down to the end block"));
114 cl::desc(
"Hoist conditional stores if an unconditional store precedes"));
118 cl::desc(
"Hoist conditional stores even if an unconditional store does not " 119 "precede - hoist multiple conditional stores into a single " 120 "predicated store"));
124 cl::desc(
"When merging conditional stores, do so even if the resultant " 125 "basic blocks are unlikely to be if-converted as a result"));
129 cl::desc(
"Allow exactly one expensive instruction to be speculatively " 134 cl::desc(
"Limit maximum recursion depth when calculating costs of " 135 "speculatively executed instructions"));
137 STATISTIC(NumBitMaps,
"Number of switch instructions turned into bitmaps");
139 "Number of switch instructions turned into linear mapping");
141 "Number of switch instructions turned into lookup tables");
143 NumLookupTablesHoles,
144 "Number of switch instructions turned into lookup tables (holes checked)");
145 STATISTIC(NumTableCmpReuses,
"Number of reused switch table lookup compares");
147 "Number of common instructions sunk down to the end block");
148 STATISTIC(NumSpeculations,
"Number of speculative executed instructions");
155 using SwitchCaseResultVectorTy =
164 struct ValueEqualityComparisonCase {
169 : Value(Value), Dest(Dest) {}
171 bool operator<(ValueEqualityComparisonCase RHS)
const {
173 return Value < RHS.Value;
179 class SimplifyCFGOpt {
188 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases);
189 bool SimplifyEqualityComparisonWithOnlyPredecessor(
Instruction *TI,
192 bool FoldValueComparisonIntoPredecessors(
Instruction *TI,
206 bool tryToSimplifyUncondBranchWithICmpInIt(
ICmpInst *ICI,
213 : TTI(TTI), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {}
219 bool requestResimplify() {
244 if (SI1Succs.
count(Succ))
246 PHINode *PN = cast<PHINode>(BBI);
250 FailBlocks->insert(Succ);
277 if (!(Cond->
getOperand(0) == Ci2->getOperand(0) &&
279 !(Cond->
getOperand(0) == Ci2->getOperand(1) &&
287 if (SI1Succs.
count(Succ))
289 PHINode *PN = cast<PHINode>(BBI);
306 PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred);
308 if (
auto *MPhi = MSSAU->getMemorySSA()->getMemoryAccess(Succ))
309 MPhi->addIncoming(MPhi->getIncomingValueForBlock(ExistPred), NewPred);
319 "Instruction is not safe to speculatively execute!");
342 int &BudgetRemaining,
344 unsigned Depth = 0) {
376 if (AggressiveInsts.
count(I))
393 if (BudgetRemaining < 0 &&
404 AggressiveInsts.
insert(I);
421 if (isa<ConstantPointerNull>(V))
426 if (CE->getOpcode() == Instruction::IntToPtr)
427 if (
ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
432 return cast<ConstantInt>(
450 struct ConstantComparesGatherer {
454 Value *CompValue =
nullptr;
457 Value *Extra =
nullptr;
463 unsigned UsedICmps = 0;
470 ConstantComparesGatherer(
const ConstantComparesGatherer &) =
delete;
471 ConstantComparesGatherer &
472 operator=(
const ConstantComparesGatherer &) =
delete;
477 bool setValueOnce(
Value *NewVal) {
478 if (CompValue && CompValue != NewVal)
481 return (CompValue !=
nullptr);
495 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
552 if (!setValueOnce(RHSVal))
575 if (!setValueOnce(RHSVal))
604 CandidateVal = RHSVal;
619 if (!setValueOnce(CandidateVal))
635 void gather(
Value *V) {
636 bool isEQ = (cast<Instruction>(V)->
getOpcode() == Instruction::Or);
646 while (!DFT.
empty()) {
651 if (I->
getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
660 if (matchInstruction(I, isEQ))
686 }
else if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
687 if (BI->isConditional())
688 Cond = dyn_cast<Instruction>(BI->getCondition());
705 if (!
SI->getParent()->hasNPredecessorsOrMore(128 /
SI->getNumSuccessors()))
706 CV =
SI->getCondition();
707 }
else if (
BranchInst *BI = dyn_cast<BranchInst>(TI))
708 if (BI->isConditional() && BI->getCondition()->hasOneUse())
709 if (
ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
711 CV = ICI->getOperand(0);
717 Value *Ptr = PTII->getPointerOperand();
718 if (PTII->getType() == DL.getIntPtrType(Ptr->
getType()))
727 BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases(
728 Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
730 Cases.reserve(
SI->getNumCases());
731 for (
auto Case :
SI->cases())
732 Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
733 Case.getCaseSuccessor()));
734 return SI->getDefaultDest();
740 Cases.push_back(ValueEqualityComparisonCase(
749 std::vector<ValueEqualityComparisonCase> &Cases) {
750 Cases.erase(
std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
755 std::vector<ValueEqualityComparisonCase> &C2) {
756 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *
V2 = &C2;
759 if (V1->size() > V2->size())
764 if (V1->size() == 1) {
767 for (
unsigned i = 0,
e = V2->size(); i !=
e; ++i)
768 if (TheVal == (*V2)[i].
Value)
775 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
776 while (i1 != e1 && i2 != e2) {
779 if ((*V1)[i1].Value < (*V2)[i2].Value)
802 assert(isa<BranchInst>(I) || isa<SelectInst>(I));
806 if (TrueWeight || FalseWeight)
808 .createBranchWeights(TrueWeight, FalseWeight);
817 bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor(
823 Value *ThisVal = isValueEqualityComparison(TI);
824 assert(ThisVal &&
"This isn't a value comparison!!");
825 if (ThisVal != PredVal)
832 std::vector<ValueEqualityComparisonCase> PredCases;
834 GetValueEqualityComparisonCases(Pred->
getTerminator(), PredCases);
838 std::vector<ValueEqualityComparisonCase> ThisCases;
839 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
851 if (isa<BranchInst>(TI)) {
854 assert(ThisCases.size() == 1 &&
"Branch can only have one case!");
860 ThisCases[0].Dest->removePredecessor(TI->
getParent());
863 <<
"Through successor TI: " << *TI <<
"Leaving: " << *NI
873 for (
unsigned i = 0,
e = PredCases.size(); i !=
e; ++i)
874 DeadCases.
insert(PredCases[i].Value);
877 <<
"Through successor TI: " << *TI);
881 if (DeadCases.count(i->getCaseValue())) {
882 i->getCaseSuccessor()->removePredecessor(TI->
getParent());
894 for (
unsigned i = 0,
e = PredCases.size(); i !=
e; ++i)
895 if (PredCases[i].Dest == TIBB) {
898 TIV = PredCases[i].
Value;
900 assert(TIV &&
"No edge from pred to succ?");
905 for (
unsigned i = 0,
e = ThisCases.size(); i !=
e; ++i)
906 if (ThisCases[i].
Value == TIV) {
907 TheRealDest = ThisCases[i].Dest;
913 TheRealDest = ThisDef;
918 if (Succ != CheckEdge)
928 <<
"Through successor TI: " << *TI <<
"Leaving: " << *NI
940 struct ConstantIntOrdering {
961 return MDS->getString().equals(
"branch_weights");
981 if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
983 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
991 uint64_t Max = *std::max_element(Weights.
begin(), Weights.
end());
992 if (Max > UINT_MAX) {
994 for (uint64_t &
I : Weights)
1003 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(
Instruction *TI,
1006 Value *CV = isValueEqualityComparison(TI);
1007 assert(CV &&
"Not a comparison?");
1008 bool Changed =
false;
1011 while (!Preds.
empty()) {
1016 Value *PCV = isValueEqualityComparison(PTI);
1018 if (PCV == CV && TI != PTI) {
1021 for (
auto *Succ : FailBlocks) {
1028 std::vector<ValueEqualityComparisonCase> BBCases;
1029 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
1031 std::vector<ValueEqualityComparisonCase> PredCases;
1032 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
1044 if (PredHasWeights) {
1047 if (Weights.
size() != 1 + PredCases.size())
1048 PredHasWeights = SuccHasWeights =
false;
1049 }
else if (SuccHasWeights)
1053 Weights.
assign(1 + PredCases.size(), 1);
1056 if (SuccHasWeights) {
1059 if (SuccWeights.
size() != 1 + BBCases.size())
1060 PredHasWeights = SuccHasWeights =
false;
1061 }
else if (PredHasWeights)
1062 SuccWeights.
assign(1 + BBCases.size(), 1);
1064 if (PredDefault == BB) {
1067 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1068 for (
unsigned i = 0,
e = PredCases.size(); i !=
e; ++i)
1069 if (PredCases[i].Dest != BB)
1070 PTIHandled.insert(PredCases[i].
Value);
1073 std::swap(PredCases[i], PredCases.back());
1075 if (PredHasWeights || SuccHasWeights) {
1077 Weights[0] += Weights[i + 1];
1082 PredCases.pop_back();
1088 if (PredDefault != BBDefault) {
1090 PredDefault = BBDefault;
1094 unsigned CasesFromPred = Weights.
size();
1095 uint64_t ValidTotalSuccWeight = 0;
1096 for (
unsigned i = 0,
e = BBCases.size(); i !=
e; ++i)
1097 if (!PTIHandled.count(BBCases[i].Value) &&
1098 BBCases[i].Dest != BBDefault) {
1099 PredCases.push_back(BBCases[i]);
1100 NewSuccessors.
push_back(BBCases[i].Dest);
1101 if (SuccHasWeights || PredHasWeights) {
1105 Weights.
push_back(Weights[0] * SuccWeights[i + 1]);
1106 ValidTotalSuccWeight += SuccWeights[i + 1];
1110 if (SuccHasWeights || PredHasWeights) {
1111 ValidTotalSuccWeight += SuccWeights[0];
1113 for (
unsigned i = 1; i < CasesFromPred; ++i)
1114 Weights[i] *= ValidTotalSuccWeight;
1116 Weights[0] *= SuccWeights[0];
1122 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1123 std::map<ConstantInt *, uint64_t> WeightsForHandled;
1124 for (
unsigned i = 0,
e = PredCases.size(); i !=
e; ++i)
1125 if (PredCases[i].Dest == BB) {
1128 if (PredHasWeights || SuccHasWeights) {
1129 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1134 std::swap(PredCases[i], PredCases.back());
1135 PredCases.pop_back();
1142 for (
unsigned i = 0,
e = BBCases.size(); i !=
e; ++i)
1143 if (PTIHandled.count(BBCases[i].Value)) {
1145 if (PredHasWeights || SuccHasWeights)
1147 PredCases.push_back(BBCases[i]);
1148 NewSuccessors.
push_back(BBCases[i].Dest);
1156 if (PredHasWeights || SuccHasWeights)
1158 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
1166 for (
BasicBlock *NewSuccessor : NewSuccessors)
1180 for (ValueEqualityComparisonCase &V : PredCases)
1181 NewSI->
addCase(V.Value, V.Dest);
1183 if (PredHasWeights || SuccHasWeights) {
1200 if (!InfLoopBlock) {
1222 for (
const PHINode &PN : Succ->phis()) {
1223 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1224 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1225 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
1256 while (isa<DbgInfoIntrinsic>(I1))
1258 while (isa<DbgInfoIntrinsic>(I2))
1264 isa<CallBrInst>(I1))
1269 bool Changed =
false;
1274 goto HoistTerminator;
1284 if (C1->isMustTailCall() != C2->isMustTailCall())
1290 if (isa<DbgInfoIntrinsic>(I1) || isa<DbgInfoIntrinsic>(I2)) {
1291 assert (isa<DbgInfoIntrinsic>(I1) && isa<DbgInfoIntrinsic>(I2));
1306 if (!I2->use_empty())
1307 I2->replaceAllUsesWith(I1);
1309 unsigned KnownIDs[] = {LLVMContext::MD_tbaa,
1310 LLVMContext::MD_range,
1311 LLVMContext::MD_fpmath,
1312 LLVMContext::MD_invariant_load,
1313 LLVMContext::MD_nonnull,
1314 LLVMContext::MD_invariant_group,
1315 LLVMContext::MD_align,
1316 LLVMContext::MD_dereferenceable,
1317 LLVMContext::MD_dereferenceable_or_null,
1318 LLVMContext::MD_mem_parallel_loop_access,
1319 LLVMContext::MD_access_group,
1320 LLVMContext::MD_preserve_access_index};
1327 I2->eraseFromParent();
1337 while (isa<DbgInfoIntrinsic>(I1))
1339 while (isa<DbgInfoIntrinsic>(I2))
1353 if (isa<CallBrInst>(I1))
1357 for (
PHINode &PN : Succ->phis()) {
1358 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1359 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1381 I2->replaceAllUsesWith(NT);
1396 std::map<std::pair<Value *, Value *>,
SelectInst *> InsertedSelects;
1398 for (
PHINode &PN : Succ->phis()) {
1399 Value *BB1V = PN.getIncomingValueForBlock(BB1);
1400 Value *BB2V = PN.getIncomingValueForBlock(BB2);
1406 SelectInst *&
SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
1410 if (isa<FPMathOperator>(PN))
1413 SI = cast<SelectInst>(
1415 BB1V->
getName() +
"." + BB2V->getName(), BI));
1419 for (
unsigned i = 0,
e = PN.getNumIncomingValues(); i !=
e; ++i)
1420 if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
1421 PN.setIncomingValue(i, SI);
1435 if (
auto II = dyn_cast<IntrinsicInst>(I)) {
1436 switch (II->getIntrinsicID()) {
1439 case Intrinsic::lifetime_start:
1440 case Intrinsic::lifetime_end:
1459 for (
auto *I : Insts) {
1461 if (isa<PHINode>(I) || I->
isEHPad() || isa<AllocaInst>(
I) ||
1468 if (
const auto *
C = dyn_cast<CallBase>(I))
1480 for (
auto *I : Insts)
1492 auto *U = cast<Instruction>(*I->
user_begin());
1494 PNUse->getParent() == Succ &&
1495 PNUse->getIncomingValueForBlock(I->
getParent()) == I) ||
1523 for (
unsigned OI = 0, OE = I0->
getNumOperands(); OI != OE; ++OI) {
1532 if (!
all_of(Insts, SameAsI0)) {
1537 if (isa<CallBase>(I0) && OI == OE - 1) {
1541 for (
auto *I : Insts)
1552 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
1557 for (
auto *BB : Blocks) {
1561 }
while (isa<DbgInfoIntrinsic>(I) && I != &BB->front());
1562 if (!isa<DbgInfoIntrinsic>(I))
1574 auto *U = cast<Instruction>(*I->
user_begin());
1600 assert(!
Op->getType()->isTokenTy() &&
"Can't PHI tokens!");
1602 Op->getName() +
".sink", &BBEnd->front());
1603 for (
auto *I : Insts)
1612 I0->
moveBefore(&*BBEnd->getFirstInsertionPt());
1615 for (
auto *I : Insts)
1634 PN->replaceAllUsesWith(I0);
1635 PN->eraseFromParent();
1639 for (
auto *I : Insts)
1656 class LockstepReverseIterator {
1669 for (
auto *BB : Blocks) {
1671 for (Inst = Inst->
getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1682 bool isValid()
const {
1689 for (
auto *&Inst : Insts) {
1690 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1691 Inst = Inst->getPrevNode();
1756 auto *
T =
B->getTerminator();
1757 if (isa<BranchInst>(
T) && cast<BranchInst>(
T)->isUnconditional())
1759 else if ((isa<BranchInst>(
T) || isa<SwitchInst>(
T)) && !Cond)
1764 if (UnconditionalPreds.
size() < 2)
1767 bool Changed =
false;
1774 unsigned ScanIdx = 0;
1777 LockstepReverseIterator LRI(UnconditionalPreds);
1778 while (LRI.isValid() &&
1780 LLVM_DEBUG(
dbgs() <<
"SINK: instruction can be sunk: " << *(*LRI)[0]
1782 InstructionsToSink.
insert((*LRI).begin(), (*LRI).end());
1787 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
1788 unsigned NumPHIdValues = 0;
1789 for (
auto *I : *LRI)
1790 for (
auto *V : PHIOperands[I])
1791 if (InstructionsToSink.
count(V) == 0)
1793 LLVM_DEBUG(
dbgs() <<
"SINK: #phid values: " << NumPHIdValues <<
"\n");
1794 unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.
size();
1795 if ((NumPHIdValues % UnconditionalPreds.
size()) != 0)
1798 return NumPHIInsts <= 1;
1801 if (ScanIdx > 0 && Cond) {
1809 bool Profitable =
false;
1810 while (ProfitableToSinkInstruction(LRI) && Idx < ScanIdx) {
1842 for (
unsigned SinkIdx = 0; SinkIdx != ScanIdx; ++SinkIdx) {
1844 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
1850 if (!ProfitableToSinkInstruction(LRI)) {
1853 dbgs() <<
"SINK: stopping here, too many PHIs would be created!\n");
1904 unsigned MaxNumInstToLookAt = 9;
1906 if (!MaxNumInstToLookAt)
1908 --MaxNumInstToLookAt;
1911 if (CurI.mayHaveSideEffects() && !isa<StoreInst>(CurI))
1914 if (
auto *
SI = dyn_cast<StoreInst>(&CurI)) {
1916 if (
SI->getPointerOperand() == StorePtr)
1918 return SI->getValueOperand();
1967 if (isa<FCmpInst>(BrCond))
1975 bool Invert =
false;
1991 unsigned SpeculatedInstructions = 0;
1992 Value *SpeculatedStoreValue =
nullptr;
1995 BBE = std::prev(ThenBB->
end());
1996 BBI != BBE; ++BBI) {
1999 if (isa<DbgInfoIntrinsic>(I)) {
2006 ++SpeculatedInstructions;
2007 if (SpeculatedInstructions > 1)
2013 I, BB, ThenBB, EndBB))))
2015 if (!SpeculatedStoreValue &&
2021 if (SpeculatedStoreValue)
2022 SpeculatedStore = cast<StoreInst>(
I);
2032 ++SinkCandidateUseCounts[OpI];
2040 I = SinkCandidateUseCounts.begin(),
2041 E = SinkCandidateUseCounts.end();
2043 if (I->first->
hasNUses(I->second)) {
2044 ++SpeculatedInstructions;
2045 if (SpeculatedInstructions > 1)
2050 bool HaveRewritablePHIs =
false;
2052 Value *OrigV = PN.getIncomingValueForBlock(BB);
2053 Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
2065 HaveRewritablePHIs =
true;
2068 if (!OrigCE && !ThenCE)
2078 if (OrigCost + ThenCost > MaxCost)
2085 ++SpeculatedInstructions;
2086 if (SpeculatedInstructions > 1)
2092 if (!HaveRewritablePHIs && !(
HoistCondStores && SpeculatedStoreValue))
2096 LLVM_DEBUG(
dbgs() <<
"SPECULATIVELY EXECUTING BB" << *ThenBB <<
"\n";);
2099 if (SpeculatedStoreValue) {
2102 Value *FalseV = SpeculatedStoreValue;
2106 BrCond, TrueV, FalseV,
"spec.store.select", BI);
2114 for (
auto &I : *ThenBB)
2119 ThenBB->begin(), std::prev(ThenBB->end()));
2124 unsigned OrigI = PN.getBasicBlockIndex(BB);
2125 unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
2126 Value *OrigV = PN.getIncomingValue(OrigI);
2127 Value *ThenV = PN.getIncomingValue(ThenI);
2136 Value *TrueV = ThenV, *FalseV = OrigV;
2140 BrCond, TrueV, FalseV,
"spec.select", BI);
2141 PN.setIncomingValue(OrigI, V);
2142 PN.setIncomingValue(ThenI, V);
2168 if (UI->
getParent() != BB || isa<PHINode>(UI))
2244 if (
PHINode *PN = dyn_cast<PHINode>(BBI)) {
2251 N->
setName(BBI->getName() +
".c");
2256 if (PI != TranslateMap.
end())
2262 if (!BBI->use_empty())
2263 TranslateMap[&*BBI] = V;
2269 if (!BBI->use_empty())
2270 TranslateMap[&*BBI] = N;
2277 if (AC &&
match(N, m_Intrinsic<Intrinsic::assume>()))
2317 isa<ConstantInt>(IfCond))
2325 unsigned NumPhis = 0;
2334 int BudgetRemaining =
2338 PHINode *PN = cast<PHINode>(II++);
2346 BudgetRemaining, TTI) ||
2348 BudgetRemaining, TTI))
2360 auto CanHoistNotFromBothValues = [](
Value *V0,
Value *V1) {
2373 isa<BinaryOperator>(IfCond)) &&
2385 if (cast<BranchInst>(IfBlock1->
getTerminator())->isConditional()) {
2390 if (!AggressiveInsts.
count(&*I) && !isa<DbgInfoIntrinsic>(
I)) {
2398 if (cast<BranchInst>(IfBlock2->
getTerminator())->isConditional()) {
2403 if (!AggressiveInsts.
count(&*I) && !isa<DbgInfoIntrinsic>(
I)) {
2410 assert(DomBlock &&
"Failed to find root DomBlock");
2413 <<
" T: " << IfTrue->
getName()
2414 <<
" F: " << IfFalse->
getName() <<
"\n");
2431 if (isa<FPMathOperator>(PN))
2462 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
2468 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
2477 if (FalseRet->getNumOperands() == 0) {
2478 TrueSucc->removePredecessor(BI->
getParent());
2488 Value *FalseValue = FalseRet->getReturnValue();
2491 if (
PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
2492 if (TVPN->getParent() == TrueSucc)
2493 TrueValue = TVPN->getIncomingValueForBlock(BI->
getParent());
2494 if (
PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
2495 if (FVPN->getParent() == FalseSucc)
2496 FalseValue = FVPN->getIncomingValueForBlock(BI->
getParent());
2503 if (
ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
2506 if (
ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2512 TrueSucc->removePredecessor(BI->
getParent());
2519 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2520 }
else if (isa<UndefValue>(TrueValue)) {
2521 TrueValue = FalseValue;
2524 Builder.
CreateSelect(BrCond, TrueValue, FalseValue,
"retval", BI);
2533 LLVM_DEBUG(
dbgs() <<
"\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:" 2534 <<
"\n " << *BI <<
"NewRet = " << *RI <<
"TRUEBLOCK: " 2535 << *TrueSucc <<
"FALSEBLOCK: " << *FalseSucc);
2545 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2563 uint64_t &PredTrueWeight,
2564 uint64_t &PredFalseWeight,
2565 uint64_t &SuccTrueWeight,
2566 uint64_t &SuccFalseWeight) {
2567 bool PredHasWeights =
2569 bool SuccHasWeights =
2571 if (PredHasWeights || SuccHasWeights) {
2572 if (!PredHasWeights)
2573 PredTrueWeight = PredFalseWeight = 1;
2574 if (!SuccHasWeights)
2575 SuccTrueWeight = SuccFalseWeight = 1;
2586 unsigned BonusInstThreshold) {
2589 const unsigned PredCount =
pred_size(BB);
2600 if (
BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2601 if (PBI->isConditional() &&
2608 if (isa<CmpInst>(Curr)) {
2622 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2630 while (isa<DbgInfoIntrinsic>(CondIt))
2642 unsigned NumBonusInsts = 0;
2643 for (
auto I = BB->
begin(); Cond != &*
I; ++
I) {
2645 if (isa<DbgInfoIntrinsic>(I))
2651 if (User ==
nullptr || User->
getParent() != BB)
2659 NumBonusInsts += PredCount;
2661 if (NumBonusInsts > BonusInstThreshold)
2677 if (TrueDest == BB || FalseDest == BB)
2696 bool InvertPredCond =
false;
2700 Opc = Instruction::Or;
2702 Opc = Instruction::And;
2704 Opc = Instruction::And;
2705 InvertPredCond =
true;
2707 Opc = Instruction::Or;
2708 InvertPredCond =
true;
2717 LLVM_DEBUG(
dbgs() <<
"FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
2721 if (InvertPredCond) {
2724 if (NewCond->
hasOneUse() && isa<CmpInst>(NewCond)) {
2725 CmpInst *CI = cast<CmpInst>(NewCond);
2743 for (
auto BonusInst = BB->
begin(); Cond != &*BonusInst; ++BonusInst) {
2744 if (isa<DbgInfoIntrinsic>(BonusInst))
2749 VMap[&*BonusInst] = NewBonusInst;
2759 NewBonusInst->
takeName(&*BonusInst);
2760 BonusInst->setName(BonusInst->getName() +
".old");
2777 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2780 SuccTrueWeight, SuccFalseWeight);
2788 NewWeights.
push_back(PredTrueWeight * SuccTrueWeight);
2794 (SuccFalseWeight + SuccTrueWeight) +
2795 PredTrueWeight * SuccFalseWeight);
2807 (SuccFalseWeight + SuccTrueWeight) +
2808 PredFalseWeight * SuccTrueWeight);
2810 NewWeights.
push_back(PredFalseWeight * SuccFalseWeight);
2815 if (NewWeights.
size() == 2) {
2826 for (
unsigned i = 0,
e = PHIs.size(); i !=
e; ++i) {
2828 PHIs[i]->getIncomingValueForBlock(PBI->
getParent()));
2837 MergedCond = cast<Instruction>(
2838 Builder.
CreateBinOp(Instruction::And, NotCond, CondInPred,
2841 MergedCond = cast<Instruction>(Builder.
CreateBinOp(
2842 Instruction::Or, PBI->
getCondition(), MergedCond,
"or.cond"));
2847 MergedCond = cast<Instruction>(Builder.
CreateBinOp(
2848 Instruction::And, PBI->
getCondition(), CondInPred,
"and.cond"));
2849 if (PBI_C->
isOne()) {
2852 MergedCond = cast<Instruction>(Builder.
CreateBinOp(
2853 Instruction::Or, NotCond, MergedCond,
"or.cond"));
2857 PHIs[i]->setIncomingValueForBlock(PBI->
getParent(), MergedCond);
2881 if (isa<DbgInfoIntrinsic>(I))
2893 for (
auto *BB : {BB1, BB2}) {
2897 if (
auto *
SI = dyn_cast<StoreInst>(&I)) {
2909 Value *AlternativeV =
nullptr) {
2927 for (
auto I = Succ->
begin(); isa<PHINode>(
I); ++
I)
2928 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
2929 PHI = cast<PHINode>(
I);
2935 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
2944 if (!AlternativeV &&
2945 (!isa<Instruction>(V) || cast<Instruction>(V)->
getParent() != BB))
2960 bool InvertPCond,
bool InvertQCond,
2970 if (!PStore || !QStore)
2991 for (
auto &I : *QFB)
2995 for (
auto &I : *QTB)
3011 int BudgetRemaining =
3019 if (
auto *S = dyn_cast<StoreInst>(&I))
3023 if (!isa<BinaryOperator>(I) && !isa<GetElementPtrInst>(
I))
3028 if (BudgetRemaining < 0)
3031 assert(BudgetRemaining >= 0 &&
3032 "When we run out of budget we will eagerly return from within the " 3033 "per-instruction loop.");
3039 (!IsWorthwhile(PTB, FreeStores) || !IsWorthwhile(PFB, FreeStores) ||
3040 !IsWorthwhile(QTB, FreeStores) || !IsWorthwhile(QFB, FreeStores)))
3062 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
3068 QStore->getParent(), PPHI);
3072 Value *PPred = PStore->
getParent() == PTB ? PCond : QB.CreateNot(PCond);
3073 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
3076 PPred = QB.CreateNot(PPred);
3078 QPred = QB.CreateNot(QPred);
3079 Value *CombinedPred = QB.CreateOr(PPred, QPred);
3083 QB.SetInsertPoint(
T);
3084 StoreInst *
SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
3090 unsigned QAlignment = QStore->getAlignment();
3091 unsigned TypeAlignment =
3093 unsigned MinAlignment;
3094 unsigned MaxAlignment;
3095 std::tie(MinAlignment, MaxAlignment) = std::minmax(PAlignment, QAlignment);
3100 if (MinAlignment != 0) {
3103 }
else if (MaxAlignment != 0) {
3113 QStore->eraseFromParent();
3164 bool InvertPCond =
false, InvertQCond =
false;
3170 if (QFB == PostBB) {
3189 !HasOnePredAndOneSucc(QFB, QBI->
getParent(), PostBB))
3192 (QTB && !HasOnePredAndOneSucc(QTB, QBI->
getParent(), PostBB)))
3200 for (
auto *BB : {PTB, PFB}) {
3205 PStoreAddresses.
insert(
SI->getPointerOperand());
3207 for (
auto *BB : {QTB, QFB}) {
3212 QStoreAddresses.
insert(
SI->getPointerOperand());
3218 auto &CommonAddresses = PStoreAddresses;
3220 bool Changed =
false;
3221 for (
auto *
Address : CommonAddresses)
3223 PTB, PFB, QTB, QFB, PostBB,
Address, InvertPCond, InvertQCond, DL, TTI);
3243 if (!IfFalseBB->
phis().empty())
3285 if (BB->getSinglePredecessor()) {
3306 if ((PBI = dyn_cast<BranchInst>(P->
getTerminator())) && PBI != BI &&
3329 if (
auto *CE = dyn_cast<ConstantExpr>(BI->
getCondition()))
3344 if (&*BB->instructionsWithoutDebug().begin() != BI)
3379 unsigned NumPhis = 0;
3385 PHINode *PN = cast<PHINode>(II);
3411 if (OtherDest == BB) {
3417 OtherDest = InfLoopBlock;
3429 PBICond = Builder.
CreateNot(PBICond, PBICond->getName() +
".not");
3444 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
3445 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
3448 SuccTrueWeight, SuccFalseWeight);
3450 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3451 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3452 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3453 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3457 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
3458 PredOther * SuccCommon,
3459 PredOther * SuccOther};
3475 Value *BIV = PN.getIncomingValueForBlock(BB);
3476 unsigned PBBIdx = PN.getBasicBlockIndex(PBI->
getParent());
3477 Value *PBIV = PN.getIncomingValue(PBBIdx);
3482 PN.setIncomingValue(PBBIdx, NV);
3488 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3489 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3490 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3491 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3494 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
3495 PredOther * SuccCommon};
3526 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB :
nullptr;
3531 if (Succ == KeepEdge1)
3532 KeepEdge1 =
nullptr;
3533 else if (Succ == KeepEdge2)
3534 KeepEdge2 =
nullptr;
3544 if (!KeepEdge1 && !KeepEdge2) {
3545 if (TrueBB == FalseBB)
3553 if (TrueWeight != FalseWeight)
3556 }
else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
3584 if (!TrueVal || !FalseVal)
3593 uint32_t TrueWeight = 0, FalseWeight = 0;
3649 bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
3665 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
3668 SwitchInst *
SI = cast<SwitchInst>(Pred->getTerminator());
3677 assert(VVal &&
"Should have a unique destination value");
3685 return requestResimplify();
3701 return requestResimplify();
3708 if (PHIUse ==
nullptr || PHIUse != &SuccBlock->
front() ||
3734 NewW = ((uint64_t(*W0) + 1) >> 1);
3737 SIW.
addCase(Cst, NewBB, NewW);
3762 ConstantComparesGatherer ConstantCompare(Cond, DL);
3765 Value *CompVal = ConstantCompare.CompValue;
3766 unsigned UsedICmps = ConstantCompare.UsedICmps;
3767 Value *ExtraCase = ConstantCompare.Extra;
3777 bool TrueWhenEqual = (Cond->
getOpcode() == Instruction::Or);
3786 if (ExtraCase && Values.
size() < 2)
3806 <<
" cases into SWITCH. BB is:\n" 3830 LLVM_DEBUG(
dbgs() <<
" ** 'icmp' chain unhandled condition: " << *ExtraCase
3831 <<
"\nEXTRABB = " << *BB);
3846 for (
unsigned i = 0,
e = Values.
size(); i !=
e; ++i)
3847 New->
addCase(Values[i], EdgeBB);
3853 PHINode *PN = cast<PHINode>(BBI);
3855 for (
unsigned i = 0,
e = Values.
size() - 1; i !=
e; ++i)
3862 LLVM_DEBUG(
dbgs() <<
" ** 'icmp' chain result is:\n" << *BB <<
'\n');
3868 return SimplifyCommonResume(RI);
3872 return SimplifySingleResume(RI);
3878 bool SimplifyCFGOpt::SimplifyCommonResume(
ResumeInst *RI) {
3886 if (!isa<DbgInfoIntrinsic>(I))
3890 auto *PhiLPInst = cast<PHINode>(RI->
getValue());
3893 for (
unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
3895 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
3896 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
3900 if (IncomingBB->getUniqueSuccessor() != BB)
3905 if (IncomingValue != LandingPad)
3908 bool isTrivial =
true;
3910 I = IncomingBB->getFirstNonPHI()->getIterator();
3911 E = IncomingBB->getTerminator()->getIterator();
3913 if (!isa<DbgInfoIntrinsic>(I)) {
3919 TrivialUnwindBlocks.
insert(IncomingBB);
3923 if (TrivialUnwindBlocks.
empty())
3927 for (
auto *TrivialBB : TrivialUnwindBlocks) {
3931 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
3945 TrivialBB->getTerminator()->eraseFromParent();
3953 return !TrivialUnwindBlocks.empty();
3957 bool SimplifyCFGOpt::SimplifySingleResume(
ResumeInst *RI) {
3961 "Resume must unwind the exception that caused control to here");
3966 if (!isa<DbgInfoIntrinsic>(I))
3977 LoopHeaders->erase(BB);
4010 switch (IntrinsicID) {
4011 case Intrinsic::dbg_declare:
4012 case Intrinsic::dbg_value:
4013 case Intrinsic::dbg_label:
4014 case Intrinsic::lifetime_end:
4037 PHINode *DestPN = cast<PHINode>(
I);
4059 if (SrcPN && SrcPN->
getParent() == BB) {
4064 SrcIdx != SrcE; ++SrcIdx) {
4085 PHINode *PN = cast<PHINode>(I++);
4105 if (UnwindDest ==
nullptr) {
4133 if (!SuccessorCleanupPad)
4142 SuccessorCleanupPad->eraseFromParent();
4178 if (
BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
4179 if (BI->isUnconditional())
4188 while (!UncondBranchPreds.
empty()) {
4191 <<
"INTO UNCOND BRANCH PRED: " << *Pred);
4199 LoopHeaders->erase(BB);
4209 while (!CondBranchPreds.
empty()) {
4224 bool Changed =
false;
4234 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
4237 if (BBI->mayHaveSideEffects()) {
4238 if (
auto *
SI = dyn_cast<StoreInst>(BBI)) {
4239 if (
SI->isVolatile())
4241 }
else if (
auto *LI = dyn_cast<LoadInst>(BBI)) {
4242 if (LI->isVolatile())
4244 }
else if (
auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
4245 if (RMWI->isVolatile())
4247 }
else if (
auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
4248 if (CXI->isVolatile())
4250 }
else if (isa<CatchPadInst>(BBI)) {
4258 }
else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
4259 !isa<LandingPadInst>(BBI)) {
4269 if (!BBI->use_empty())
4271 BBI->eraseFromParent();
4277 if (&BB->
front() != UI)
4281 for (
unsigned i = 0,
e = Preds.
size(); i !=
e; ++i) {
4284 if (
auto *BI = dyn_cast<BranchInst>(TI)) {
4285 if (BI->isUnconditional()) {
4286 assert(BI->getSuccessor(0) == BB &&
"Incorrect CFG");
4291 Value* Cond = BI->getCondition();
4292 if (BI->getSuccessor(0) == BB) {
4294 Builder.
CreateBr(BI->getSuccessor(1));
4296 assert(BI->getSuccessor(1) == BB &&
"Incorrect CFG");
4298 Builder.
CreateBr(BI->getSuccessor(0));
4303 }
else if (
auto *
SI = dyn_cast<SwitchInst>(TI)) {
4306 if (i->getCaseSuccessor() != BB) {
4315 }
else if (
auto *II = dyn_cast<InvokeInst>(TI)) {
4316 if (II->getUnwindDest() == BB) {
4320 }
else if (
auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4321 if (CSI->getUnwindDest() == BB) {
4328 E = CSI->handler_end();
4331 CSI->removeHandler(I);
4337 if (CSI->getNumHandlers() == 0) {
4339 if (CSI->hasUnwindDest()) {
4353 }
else if (isa<CleanupReturnInst>(TI)) {
4364 LoopHeaders->erase(BB);
4376 for (
size_t I = 1,
E = Cases.
size(); I !=
E; ++
I) {
4377 if (Cases[I - 1]->getValue() != Cases[
I]->getValue() + 1)
4408 for (
auto Case : SI->
cases()) {
4412 if (Dest == DestA) {
4418 if (Dest == DestB) {
4426 "Single-destination switch should have been folded.");
4429 assert(!CasesB.
empty() &&
"There must be non-default cases.");
4437 ContiguousCases = &CasesA;
4438 ContiguousDest = DestA;
4441 ContiguousCases = &CasesB;
4442 ContiguousDest = DestB;
4459 if (NumCases->isNullValue() && !ContiguousCases->empty())
4470 uint64_t TrueWeight = 0;
4471 uint64_t FalseWeight = 0;
4472 for (
size_t I = 0,
E = Weights.
size(); I !=
E; ++
I) {
4474 TrueWeight += Weights[I];
4476 FalseWeight += Weights[
I];
4478 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
4487 for (
auto BBI = ContiguousDest->
begin(); isa<PHINode>(BBI); ++BBI) {
4488 unsigned PreviousEdges = ContiguousCases->size();
4491 for (
unsigned I = 0,
E = PreviousEdges - 1; I !=
E; ++
I)
4492 cast<PHINode>(BBI)->removeIncomingValue(SI->
getParent());
4494 for (
auto BBI = OtherDest->
begin(); isa<PHINode>(BBI); ++BBI) {
4495 unsigned PreviousEdges = SI->
getNumCases() - ContiguousCases->size();
4498 for (
unsigned I = 0,
E = PreviousEdges - 1; I !=
E; ++
I)
4499 cast<PHINode>(BBI)->removeIncomingValue(SI->
getParent());
4525 unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits;
4529 for (
auto &Case : SI->
cases()) {
4530 const APInt &CaseVal = Case.getCaseValue()->getValue();
4533 DeadCases.
push_back(Case.getCaseValue());
4545 const unsigned NumUnknownBits =
4547 assert(NumUnknownBits <= Bits);
4548 if (HasDefault && DeadCases.
empty() &&
4549 NumUnknownBits < 64 &&
4555 if (DeadCases.
empty())
4562 "Case was not found. Probably mistake in DeadCases forming.");
4564 CaseI->getCaseSuccessor()->removePredecessor(SI->
getParent());
4590 int Idx = PHI.getBasicBlockIndex(BB);
4591 assert(Idx >= 0 &&
"PHI has no entry for predecessor?");
4593 Value *InValue = PHI.getIncomingValue(Idx);
4594 if (InValue != CaseValue)
4610 ForwardingNodesMap ForwardingNodes;
4612 bool Changed =
false;
4613 for (
auto &Case : SI->
cases()) {
4615 BasicBlock *CaseDest = Case.getCaseSuccessor();
4634 int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
4635 if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
4636 count(Phi.blocks(), SwitchBlock) == 1) {
4645 ForwardingNodes[Phi].push_back(PhiIdx);
4648 for (
auto &ForwardingNode : ForwardingNodes) {
4649 PHINode *Phi = ForwardingNode.first;
4651 if (Indexes.
size() < 2)
4654 for (
int Index : Indexes)
4670 if (!isa<ConstantFP>(C) && !isa<ConstantInt>(
C) &&
4671 !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(
C) &&
4672 !isa<UndefValue>(C) && !isa<ConstantExpr>(
C))
4676 if (!CE->isGEPWithNoNotionalOverIndexing())
4693 if (
Constant *
C = dyn_cast<Constant>(V))
4695 return ConstantPool.
lookup(V);
4724 if (
CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
4766 if (
PHINode *Phi = dyn_cast<PHINode>(User))
4767 if (Phi->getIncomingBlock(
Use) == CaseDest)
4772 ConstantPool.
insert(std::make_pair(&I,
C));
4780 *CommonDest = CaseDest;
4782 if (CaseDest != *CommonDest)
4786 for (
PHINode &PHI : (*CommonDest)->phis()) {
4787 int Idx = PHI.getBasicBlockIndex(Pred);
4800 Res.push_back(std::make_pair(&PHI, ConstVal));
4803 return Res.size() > 0;
4809 SwitchCaseResultVectorTy &UniqueResults,
4811 for (
auto &I : UniqueResults) {
4812 if (I.first == Result) {
4813 I.second.push_back(CaseVal);
4814 return I.second.size();
4817 UniqueResults.push_back(
4828 SwitchCaseResultVectorTy &UniqueResults,
4831 uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult) {
4832 for (
auto &I : SI->
cases()) {
4842 if (Results.size() > 1)
4846 const uintptr_t NumCasesForResult =
4850 if (NumCasesForResult > MaxCasesPerResult)
4854 if (UniqueResults.size() > MaxUniqueResults)
4859 PHI = Results[0].first;
4860 else if (PHI != Results[0].
first)
4871 DefaultResults.size() == 1 ? DefaultResults.begin()->second :
nullptr;
4872 if ((!DefaultResult &&
4893 assert(ResultVector.size() == 2 &&
4894 "We should have exactly two unique results at this point");
4897 if (ResultVector[0].
second.size() == 1 &&
4898 ResultVector[1].second.size() == 1) {
4899 ConstantInt *
const FirstCase = ResultVector[0].second[0];
4900 ConstantInt *
const SecondCase = ResultVector[1].second[0];
4902 bool DefaultCanTrigger = DefaultResult;
4903 Value *SelectValue = ResultVector[1].first;
4904 if (DefaultCanTrigger) {
4905 Value *
const ValueCompare =
4906 Builder.
CreateICmpEQ(Condition, SecondCase,
"switch.selectcmp");
4908 DefaultResult,
"switch.select");
4910 Value *
const ValueCompare =
4911 Builder.
CreateICmpEQ(Condition, FirstCase,
"switch.selectcmp");
4913 SelectValue,
"switch.select");
4952 SwitchCaseResultVectorTy UniqueResults;
4958 if (UniqueResults.size() != 2)
4960 assert(PHI !=
nullptr &&
"PHI for value select not found");
4963 Value *SelectValue =
4976 class SwitchLookupTable {
4991 static bool WouldFitInRegister(
const DataLayout &DL, uint64_t TableSize,
5034 SwitchLookupTable::SwitchLookupTable(
5038 assert(Values.size() &&
"Can't build lookup table without values!");
5039 assert(TableSize >= Values.size() &&
"Can't fit values in table!");
5042 SingleValue = Values.begin()->second;
5048 for (
size_t I = 0,
E = Values.size(); I !=
E; ++
I) {
5053 uint64_t Idx = (CaseVal->
getValue() - Offset->
getValue()).getLimitedValue();
5054 TableContents[Idx] = CaseRes;
5056 if (CaseRes != SingleValue)
5057 SingleValue =
nullptr;
5061 if (Values.size() < TableSize) {
5063 "Need a default value to fill the lookup table holes.");
5065 for (uint64_t I = 0; I < TableSize; ++
I) {
5066 if (!TableContents[I])
5067 TableContents[
I] = DefaultValue;
5070 if (DefaultValue != SingleValue)
5071 SingleValue =
nullptr;
5077 Kind = SingleValueKind;
5083 if (isa<IntegerType>(ValueType)) {
5084 bool LinearMappingPossible =
true;
5087 assert(TableSize >= 2 &&
"Should be a SingleValue table.");
5089 for (uint64_t I = 0; I < TableSize; ++
I) {
5094 LinearMappingPossible =
false;
5099 APInt Dist = Val - PrevVal;
5102 }
else if (Dist != DistToPrev) {
5103 LinearMappingPossible =
false;
5109 if (LinearMappingPossible) {
5110 LinearOffset = cast<ConstantInt>(TableContents[0]);
5112 Kind = LinearMapKind;
5119 if (WouldFitInRegister(DL, TableSize, ValueType)) {
5122 for (uint64_t I = TableSize; I > 0; --
I) {
5125 if (!isa<UndefValue>(TableContents[I - 1])) {
5126 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
5127 TableInt |= Val->
getValue().
zext(TableInt.getBitWidth());
5131 BitMapElementTy =
IT;
5143 "switch.table." + FuncName);
5153 case SingleValueKind:
5155 case LinearMapKind: {
5158 false,
"switch.idx.cast");
5159 if (!LinearMultiplier->isOne())
5160 Result = Builder.
CreateMul(Result, LinearMultiplier,
"switch.idx.mult");
5161 if (!LinearOffset->isZero())
5162 Result = Builder.
CreateAdd(Result, LinearOffset,
"switch.offset");
5180 Value *DownShifted =
5181 Builder.
CreateLShr(BitMap, ShiftAmt,
"switch.downshift");
5183 return Builder.
CreateTrunc(DownShifted, BitMapElementTy,
"switch.masked");
5188 uint64_t TableSize =
5189 Array->getInitializer()->getType()->getArrayNumElements();
5190 if (TableSize > (1ULL << (IT->
getBitWidth() - 1)))
5193 "switch.tableidx.zext");
5197 GEPIndices,
"switch.gep");
5199 cast<ArrayType>(Array->getValueType())->getElementType(),
GEP,
5206 bool SwitchLookupTable::WouldFitInRegister(
const DataLayout &DL,
5208 Type *ElementType) {
5216 if (TableSize >= UINT_MAX /
IT->getBitWidth())
5230 bool AllTablesFitInRegister =
true;
5231 bool HasIllegalType =
false;
5232 for (
const auto &I : ResultTypes) {
5233 Type *Ty = I.second;
5236 HasIllegalType = HasIllegalType || !TTI.
isTypeLegal(Ty);
5239 AllTablesFitInRegister =
5240 AllTablesFitInRegister &&
5241 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
5246 if (HasIllegalType && !AllTablesFitInRegister)
5251 if (AllTablesFitInRegister)
5287 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
5307 DefaultValue, CmpOp1,
true);
5308 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
5313 for (
auto ValuePair : Values) {
5315 ValuePair.second, CmpOp1,
true);
5316 if (!CaseConst || CaseConst == DefaultConst || isa<UndefValue>(CaseConst))
5318 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
5319 "Expect true or false as compare result.");
5333 if (DefaultConst == FalseConst) {
5336 ++NumTableCmpReuses;
5339 Value *InvertedTableCmp = BinaryOperator::CreateXor(
5343 ++NumTableCmpReuses;
5359 (Fn->getFnAttribute(
"no-jump-tables").getValueAsString() ==
"true"))
5393 MinCaseVal = CaseVal;
5395 MaxCaseVal = CaseVal;
5400 if (!
GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
5405 for (
const auto &I : Results) {
5408 if (!ResultLists.
count(PHI))
5410 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
5416 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
5419 uint64_t NumResults = ResultLists[PHIs[0]].
size();
5422 bool TableHasHoles = (NumResults < TableSize);
5427 bool HasDefaultResults =
5429 DefaultResultsList, DL, TTI);
5431 bool NeedMask = (TableHasHoles && !HasDefaultResults);
5436 if (!DL.fitsInLegalInteger(TableSize))
5440 for (
const auto &I : DefaultResultsList) {
5443 DefaultResults[PHI] = Result;
5466 uint64_t MaxTableSize = CaseSize > 63 ?
UINT64_MAX : 1ULL << CaseSize;
5467 assert(MaxTableSize >= TableSize &&
5468 "It is impossible for a switch to have more entries than the max " 5469 "representable value of its input integer type's size.");
5474 const bool DefaultIsReachable =
5476 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
5479 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5497 MaskBB->
setName(
"switch.hole_check");
5504 APInt MaskInt(TableSizePowOf2, 0);
5505 APInt One(TableSizePowOf2, 1);
5507 const ResultListTy &ResultList = ResultLists[PHIs[0]];
5508 for (
size_t I = 0,
E = ResultList.size(); I !=
E; ++
I) {
5509 uint64_t Idx = (ResultList[
I].first->getValue() - MinCaseVal->
getValue())
5511 MaskInt |= One << Idx;
5521 Value *Shifted = Builder.
CreateLShr(TableMask, MaskIndex,
"switch.shifted");
5530 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5537 bool ReturnedEarly =
false;
5539 const ResultListTy &ResultList = ResultLists[PHI];
5542 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
5544 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL,
5547 Value *Result = Table.BuildLookup(TableIndex, Builder);
5551 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
5554 ReturnedEarly =
true;
5560 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
5568 PHI->addIncoming(Result, LookupBB);
5586 ++NumLookupTablesHoles;
5592 uint64_t Diff = (uint64_t)Values.
back() - (uint64_t)Values.
front();
5593 uint64_t Range = Diff + 1;
5594 uint64_t NumCases = Values.
size();
5596 uint64_t MinDensity = 40;
5598 return NumCases * 100 >= Range * MinDensity;
5613 if (CondTy->getIntegerBitWidth() > 64 ||
5626 for (
auto &
C : SI->
cases())
5627 Values.
push_back(
C.getCaseValue()->getValue().getSExtValue());
5635 int64_t
Base = Values[0];
5636 for (
auto &V : Values)
5637 V -= (uint64_t)(Base);
5652 unsigned Shift = 64;
5653 for (
auto &V : Values)
5657 for (
auto &V : Values)
5658 V = (int64_t)((uint64_t)V >> Shift);
5678 auto *LShr = Builder.
CreateLShr(Sub, ShiftC);
5679 auto *Shl = Builder.
CreateShl(Sub, Ty->getBitWidth() - Shift);
5680 auto *Rot = Builder.
CreateOr(LShr, Shl);
5683 for (
auto Case : SI->
cases()) {
5684 auto *Orig = Case.getCaseValue();
5685 auto Sub = Orig->getValue() -
APInt(Ty->getBitWidth(), Base);
5695 if (isValueEqualityComparison(SI)) {
5699 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
5700 return requestResimplify();
5705 return requestResimplify();
5710 if (FoldValueComparisonIntoPredecessors(SI, Builder))
5711 return requestResimplify();
5716 return requestResimplify();
5720 return requestResimplify();
5723 return requestResimplify();
5726 return requestResimplify();
5733 if (Options.ConvertSwitchToLookupTable &&
5735 return requestResimplify();
5738 return requestResimplify();
5745 bool Changed =
false;
5776 return requestResimplify();
5808 if (isa<PHINode>(*Succ->begin()))
5812 if (BB == OtherPred)
5818 for (++I; isa<DbgInfoIntrinsic>(
I); ++
I)
5831 "unexpected successor");
5837 for (
auto I = OtherPred->begin(),
E = OtherPred->end(); I !=
E;) {
5840 if (isa<DbgInfoIntrinsic>(Inst))
5847 Succ->removePredecessor(BB);
5858 bool SimplifyCFGOpt::SimplifyUncondBranch(
BranchInst *BI,
5870 bool NeedCanonicalLoop =
5871 Options.NeedCanonicalLoop &&
5873 (LoopHeaders->count(BB) || LoopHeaders->count(Succ)));
5881 if (
ICmpInst *ICI = dyn_cast<ICmpInst>(I))
5883 for (++I; isa<DbgInfoIntrinsic>(
I); ++
I)
5885 if (I->isTerminator() &&
5886 tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
5893 for (++I; isa<DbgInfoIntrinsic>(
I); ++
I)
5904 return requestResimplify();
5912 if (!PPred || (PredPred && PredPred != PPred))
5926 if (isValueEqualityComparison(BI)) {
5931 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
5932 return requestResimplify();
5938 if (FoldValueComparisonIntoPredecessors(BI, Builder))
5939 return requestResimplify();
5940 }
else if (&*I == cast<Instruction>(BI->
getCondition())) {
5942 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
5943 return requestResimplify();
5961 return requestResimplify();
5968 return requestResimplify();
5977 return requestResimplify();
5985 return requestResimplify();
5994 return requestResimplify();
6002 return requestResimplify();
6006 if (
BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
6009 return requestResimplify();
6014 if (
BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
6017 return requestResimplify();
6041 if (i == I->
getParent()->
end() || i->mayHaveSideEffects())
6046 if (
GEP->getPointerOperand() ==
I)
6054 if (
LoadInst *LI = dyn_cast<LoadInst>(Use))
6055 if (!LI->isVolatile())
6057 LI->getPointerAddressSpace());
6060 if (
StoreInst *SI = dyn_cast<StoreInst>(Use))
6061 if (!SI->isVolatile())
6063 SI->getPointerAddressSpace())) &&
6064 SI->getPointerOperand() ==
I;
6069 CS.getCalledValue() ==
I;
6078 for (
unsigned i = 0,
e = PHI.getNumIncomingValues(); i !=
e; ++i)
6080 Instruction *
T = PHI.getIncomingBlock(i)->getTerminator();
6082 if (
BranchInst *BI = dyn_cast<BranchInst>(T)) {
6100 bool SimplifyCFGOpt::simplifyOnce(
BasicBlock *BB) {
6101 bool Changed =
false;
6138 if (
auto *PN = dyn_cast<PHINode>(BB->
begin()))
6139 if (PN->getNumIncomingValues() == 2)
6145 if (SimplifyUncondBranch(BI, Builder))
6148 if (SimplifyCondBranch(BI, Builder))
6151 }
else if (
auto *RI = dyn_cast<ReturnInst>(BB->
getTerminator())) {
6152 if (SimplifyReturn(RI, Builder))
6154 }
else if (
auto *RI = dyn_cast<ResumeInst>(BB->
getTerminator())) {
6155 if (SimplifyResume(RI, Builder))
6157 }
else if (
auto *RI = dyn_cast<CleanupReturnInst>(BB->
getTerminator())) {
6158 if (SimplifyCleanupReturn(RI))
6160 }
else if (
auto *SI = dyn_cast<SwitchInst>(BB->
getTerminator())) {
6161 if (SimplifySwitch(SI, Builder))
6163 }
else if (
auto *UI = dyn_cast<UnreachableInst>(BB->
getTerminator())) {
6164 if (SimplifyUnreachable(UI))
6166 }
else if (
auto *IBI = dyn_cast<IndirectBrInst>(BB->
getTerminator())) {
6167 if (SimplifyIndirectBr(IBI))
6175 bool Changed =
false;
6183 Changed |= simplifyOnce(BB);
6184 }
while (Resimplify);
const T & front() const
front - Get the first element.
Value * CreateInBoundsGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
Return a value (possibly void), from a function.
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
Value * getValueOperand()
unsigned getNumCases() const
Return the number of 'cases' in this switch instruction, excluding the default case.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
A parsed version of the target data layout string in and methods for querying it. ...
static bool tryWidenCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI)
If the previous block ended with a widenable branch, determine if reusing the target block is profita...
static ConstantInt * getFalse(LLVMContext &Context)
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
bool cannotDuplicate() const
Determine if the invoke cannot be duplicated.
CaseIt case_end()
Returns a read/write iterator that points one past the last in the SwitchInst.
This class is the base class for the comparison instructions.
iterator_range< use_iterator > uses()
bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
static IntegerType * getInt1Ty(LLVMContext &C)
bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
CleanupPadInst * getCleanupPad() const
Convenience accessor.
void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
uint64_t getZExtValue() const
Get zero extended value.
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
const T & back() const
back - Get the last element.
DiagnosticInfoOptimizationBase::Argument NV
bool isSameOperationAs(const Instruction *I, unsigned flags=0) const
This function determines if the specified instruction executes the same operation as the current one...
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
This class represents lattice values for constants.
const APInt & getUpper() const
Return the upper value for this range.
void swapSuccessors()
Swap the successors of this branch instruction.
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
A Module instance is used to store all the information related to an LLVM module. ...
void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs)
Drop all unknown metadata except for debug locations.
bool isConvergent() const
Determine if the invoke is convergent.
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
Optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
static bool isProfitableToFoldUnconditional(BranchInst *SI1, BranchInst *SI2, Instruction *Cond, SmallVectorImpl< PHINode *> &PhiNodes)
Return true if it is safe and profitable to merge these two terminator instructions together...
static bool removeUndefIntroducingPredecessor(BasicBlock *BB)
If BB has an incoming value that will always trigger undefined behavior (eg.
void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
void push_back(const T &Elt)
void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
APInt zext(unsigned width) const
Zero extend to a new width.
bool slt(const APInt &RHS) const
Signed less than comparison.
This class represents a function call, abstracting a target machine's calling convention.
static bool GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest, BasicBlock **CommonDest, SmallVectorImpl< std::pair< PHINode *, Constant *>> &Res, const DataLayout &DL, const TargetTransformInfo &TTI)
Try to determine the resulting constant values in phi nodes at the common destination basic block...
bool isSizeLargerThan(uint64_t MaxSize) const
Compare set size of this range with Value.
Value * getCondition() const
static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2, Instruction *I1, Instruction *I2)
static bool mergeCleanupPad(CleanupReturnInst *RI)
const Value * getTrueValue() const
CaseIt case_begin()
Returns a read/write iterator that points to the first case in the SwitchInst.
bool mayWriteToMemory() const
Return true if this instruction may modify memory.
A wrapper class to simplify modification of SwitchInst cases along with their prof branch_weights met...
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
A cache of @llvm.assume calls within a function.
Like Internal, but omit from symbol table.
Function Alias Analysis Results
LLVMContext & getContext() const
All values hold a context through their type.
bool isTerminator() const
void deleteValue()
Delete a pointer to a generic Value.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
bool sgt(const APInt &RHS) const
Signed greater than comparison.
static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select)
const Use & getOperandUse(unsigned i) const
static bool eliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC, const DataLayout &DL)
Compute masked bits for the condition of a switch and use it to remove dead cases.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
static unsigned ComputeSpeculationCost(const Instruction *I, const TargetTransformInfo &TTI)
static StoreInst * findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2)
const MDOperand & getOperand(unsigned I) const
An instruction for reading from memory.
Value * getCondition() const
BasicBlock * getUnwindDest() const
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...
void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
static ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
This defines the Use class.
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
CaseWeightOpt getSuccessorWeight(unsigned idx)
LLVMContext & getContext() const
Get the context in which this basic block lives.
static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI)
Return true if the backend will be able to handle initializing an array of constants like C...
ConstantInt * findCaseDest(BasicBlock *BB)
Finds the unique case value for a given successor.
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI, uint64_t &PredTrueWeight, uint64_t &PredFalseWeight, uint64_t &SuccTrueWeight, uint64_t &SuccFalseWeight)
Return true if either PBI or BI has branch weight available, and store the weights in {Pred|Succ}{Tru...
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static ConstantInt * GetConstantInt(Value *V, const DataLayout &DL)
Extract ConstantInt from value, looking through IntToPtr and PointerNullValue.
static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I)
Check if passing a value to an instruction will cause undefined behavior.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Value * CreateNot(Value *V, const Twine &Name="")
iterator begin()
Instruction iterator methods.
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false)
Attempts to merge a block into its predecessor, if possible.
unsigned countTrailingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the least significant bit to the most stopping at the first 1...
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
The address of a basic block.
bool match(Val *V, const Pattern &P)
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
void hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt, BasicBlock *BB)
Hoist all of the instructions in the IfBlock to the dominant block DomBlock, by moving its instructio...
static Constant * getIntegerCast(Constant *C, Type *Ty, bool isSigned)
Create a ZExt, Bitcast or Trunc for integer -> integer casts.
const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
This class represents the LLVM 'select' instruction.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest, SwitchCaseResultVectorTy &UniqueResults, Constant *&DefaultResult, const DataLayout &DL, const TargetTransformInfo &TTI, uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult)
static void GetBranchWeights(Instruction *TI, SmallVectorImpl< uint64_t > &Weights)
Get Weights of a given terminator, the default weight is at the front of the vector.
LLVMContext & getContext() const
Get the global data context.
A Use represents the edge between a Value definition and its users.
static Optional< unsigned > getOpcode(ArrayRef< VPValue *> Values)
Returns the opcode of Values or ~0 if they do not all agree.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
static int ConstantIntSortPredicate(ConstantInt *const *P1, ConstantInt *const *P2)
ReturnInst * CreateRet(Value *V)
Create a 'ret <val>' instruction.
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...
static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI)
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
void setName(const Twine &Name)
Change the name of the value.
static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB)
Return true if we can thread a branch across this block.
static Value * isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB, BasicBlock *StoreBB, BasicBlock *EndBB)
Determine if we can hoist sink a sole store instruction out of a conditional block.
BasicBlock * getDestination(unsigned i)
Return the specified destination.
APInt operator*(APInt a, uint64_t RHS)
This file implements a class to represent arbitrary precision integral constant values and operations...
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
This class represents a cast from a pointer to an integer.
static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI, const DataLayout &DL, const TargetTransformInfo &TTI)
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...
ReturnInst * FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, BasicBlock *Pred, DomTreeUpdater *DTU=nullptr)
This method duplicates the specified return instruction into a predecessor which ends in an unconditi...
void assign(size_type NumElts, const T &Elt)
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
void setUnwindDest(BasicBlock *B)
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
A constant value that is initialized with an expression using other constant values.
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
static cl::opt< unsigned > MaxSpeculationDepth("max-speculation-depth", cl::Hidden, cl::init(10), cl::desc("Limit maximum recursion depth when calculating costs of " "speculatively executed instructions"))
static bool isSwitchDense(ArrayRef< int64_t > Values)
Type * getType() const
All values are typed, get the type of this value.
static bool SimplifyCondBranchToTwoReturns(BranchInst *BI, IRBuilder<> &Builder)
If we found a conditional branch that goes to two returning blocks, try to merge them together into o...
bool insert(const value_type &X)
Insert a new element into the SetVector.
static uintptr_t MapCaseToResult(ConstantInt *CaseVal, SwitchCaseResultVectorTy &UniqueResults, Constant *Result)
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is known to contain an unconditional branch, and contains no instructions other than PHI nodes...
unsigned getNumSuccessors() const
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
Class to represent array types.
void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction...
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
static void setBranchWeights(SwitchInst *SI, ArrayRef< uint32_t > Weights)
This class represents a no-op cast from one type to another.
static cl::opt< bool > SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true), cl::desc("Sink common instructions down to the end block"))
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
void combineMetadata(Instruction *K, const Instruction *J, ArrayRef< unsigned > KnownIDs, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
const APInt & getValue() const
Return the constant as an APInt value reference.
static Value * ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector, Constant *DefaultResult, Value *Condition, IRBuilder<> &Builder)
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
BasicBlock * getBasicBlock() const
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
static void EliminateBlockCases(BasicBlock *BB, std::vector< ValueEqualityComparisonCase > &Cases)
Given a vector of bb/value pairs, remove any entries in the list that match the specified block...
An instruction for storing to memory.
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
BasicBlock * getSuccessor(unsigned idx) const
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
bool EliminateDuplicatePHINodes(BasicBlock *BB)
Check for and eliminate duplicate PHI nodes in this block.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
void takeName(Value *V)
Transfer the name from V to this value.
static bool SinkCommonCodeFromPredecessors(BasicBlock *BB)
Check whether BB's predecessors end with unconditional branches.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Interval::succ_iterator succ_end(Interval *I)
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I)
Delegate the call to the underlying SwitchInst::removeCase() and remove correspondent branch weight...
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
static cl::opt< bool > HoistCondStores("simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true), cl::desc("Hoist conditional stores if an unconditional store precedes"))
iterator find(const_arg_type_t< KeyT > Val)
bool isVoidTy() const
Return true if this is 'void'.
bool isThreadDependent() const
Return true if the value can vary between threads.
bool FoldBranchToCommonDest(BranchInst *BI, MemorySSAUpdater *MSSAU=nullptr, unsigned BonusInstThreshold=1)
If this basic block is ONLY a setcc and a branch, and if a predecessor branches to us and one of our ...
const BasicBlock & getEntryBlock() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
void getAAMetadata(AAMDNodes &N, bool Merge=false) const
Fills the AAMDNodes structure with AA metadata from this instruction.
unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return the number of times the sign bit of the register is replicated into the other bits...
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock *> Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
initializer< Ty > init(const Ty &Val)
static bool tryCSEWithPredecessor(Instruction *Inst, BasicBlock *PB)
Return true if the given instruction is available in its predecessor block.
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder, const DataLayout &DL, const TargetTransformInfo &TTI)
If the switch is only used to initialize one or more phi nodes in a common successor block with diffe...
The landingpad instruction holds all of the information necessary to generate correct exception handl...
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
static void EraseTerminatorAndDCECond(Instruction *TI, MemorySSAUpdater *MSSAU=nullptr)
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")
bool hasNUses(unsigned N) const
Return true if this Value has exactly N users.
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
static bool sinkLastInstruction(ArrayRef< BasicBlock *> Blocks)
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
bool isIdenticalToWhenDefined(const Instruction *I) const
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags, which may specify conditions under which the instruction's result is undefined.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
static Value * ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB, Value *AlternativeV=nullptr)
void set_intersect(S1Ty &S1, const S2Ty &S2)
set_intersect(A, B) - Compute A := A ^ B Identical to set_intersection, except that it works on set<>...
void setSuccessorWeight(unsigned idx, CaseWeightOpt W)
static bool HasBranchWeights(const Instruction *I)
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
void setAAMetadata(const AAMDNodes &N)
Sets the metadata on this instruction from the AAMDNodes structure.
LLVM Basic Block Representation.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
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)
UnreachableInst * CreateUnreachable()
Conditional or Unconditional Branch instruction.
iterator_range< filter_iterator< BasicBlock::const_iterator, std::function< bool(const Instruction &)> > > instructionsWithoutDebug() const
Return a const iterator range over the instructions in the block, skipping any debug instructions...
static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder)
Turn a switch with two reachable destinations into an integer range comparison and branch...
bool ult(const APInt &RHS) const
Unsigned less than comparison.
size_t size() const
size - Get the array size.
This function has undefined behavior.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
bool isInlineAsm() const
Check if this call is an inline asm statement.
LLVM_NODISCARD bool empty() const
Resume the propagation of an exception.
bool canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx)
Given an instruction, is it legal to set operand OpIdx to a non-constant value?
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
bool isPointerTy() const
True if this is an instance of PointerType.
const Instruction & front() const
Indirect Branch Instruction.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
static cl::opt< unsigned > PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2), cl::desc("Control the amount of phi node folding to perform (default = 2)"))
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...
BasicBlock * getDefaultDest() const
bool isDLLImportDependent() const
Return true if the value is dependent on a dllimport variable.
unsigned getPrefTypeAlignment(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
bool parseWidenableBranch(const User *U, Value *&Condition, Value *&WidenableCondition, BasicBlock *&IfTrueBB, BasicBlock *&IfFalseBB)
If U is widenable branch looking like: cond = ...
static cl::opt< bool > MergeCondStoresAggressively("simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false), cl::desc("When merging conditional stores, do so even if the resultant " "basic blocks are unlikely to be if-converted as a result"))
void splice(iterator where, iplist_impl &L2)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
This instruction compares its operands according to the predicate given to the constructor.
static bool SimplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond, BasicBlock *TrueBB, BasicBlock *FalseBB, uint32_t TrueWeight, uint32_t FalseWeight)
Interval::pred_iterator pred_end(Interval *I)
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
Class to represent integer types.
static cl::opt< bool > MergeCondStores("simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true), cl::desc("Hoist conditional stores even if an unconditional store does not " "precede - hoist multiple conditional stores into a single " "predicated store"))
bool pred_empty(const BasicBlock *BB)
static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI, const DataLayout &DL)
Given a BB that starts with the specified two-entry PHI node, see if we can eliminate it...
const Function * getFunction() const
Return the function this instruction belongs to.
const Value * getCondition() const
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
If the specified value is a trivially dead instruction, delete it.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
iterator erase(const_iterator CI)
bool isExceptionalTerminator() const
Value(Type *Ty, unsigned scid)
unsigned countLeadingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the most significant bit to the least stopping at the first 1...
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W)
Delegate the call to the underlying SwitchInst::addCase() and set the specified branch weight for the...
Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldCompareInstOperands - Attempt to constant fold a compare instruction (icmp/fcmp) with the...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
void sort(IteratorTy Start, IteratorTy End)
static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL, AssumptionCache *AC)
If we have a conditional branch on a PHI node value that is defined in the same block as the branch a...
bool isEmptySet() const
Return true if this set contains no members.
static Constant * ConstantFold(Instruction *I, const DataLayout &DL, const SmallDenseMap< Value *, Constant *> &ConstantPool)
Try to fold instruction I into a constant.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
bool hasNPredecessorsOrMore(unsigned N) const
Return true if this block has N predecessors or more.
BasicBlock * getNormalDest() const
const InstListType & getInstList() const
Return the underlying instruction list container.
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
A SetVector that performs no allocations if smaller than a certain size.
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...
unsigned countPopulation(T Value)
Count the number of set bits in a value.
This is the shared class of boolean and integer constants.
static bool SafeToMergeTerminators(Instruction *SI1, Instruction *SI2, SmallSetVector< BasicBlock *, 4 > *FailBlocks=nullptr)
Return true if it is safe to merge these two terminator instructions together.
Align max(MaybeAlign Lhs, Align Rhs)
static cl::opt< bool > SpeculateOneExpensiveInst("speculate-one-expensive-inst", cl::Hidden, cl::init(true), cl::desc("Allow exactly one expensive instruction to be speculatively " "executed"))
CallInst * CreateAssumption(Value *Cond)
Create an assume intrinsic call that allows the optimizer to assume that the provided condition will ...
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder, const DataLayout &DL)
The specified branch is a conditional branch.
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.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
This class represents a range of values.
void setAlignment(MaybeAlign Alignment)
This is the common base class for debug info intrinsics.
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
Value * GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue, BasicBlock *&IfFalse)
Check whether BB is the merge point of a if-region.
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
LLVM_NODISCARD T pop_back_val()
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI, const DataLayout &DL, const TargetTransformInfo &TTI)
If we have a conditional branch as a predecessor of another block, this function tries to simplify it...
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 BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isConditional() const
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...
void applyMergedLocation(const DILocation *LocA, const DILocation *LocB)
Merge 2 debug locations and apply it to the Instruction.
pred_range predecessors(BasicBlock *BB)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch, Constant *DefaultValue, const SmallVectorImpl< std::pair< ConstantInt *, Constant *>> &Values)
Try to reuse the switch table index compare.
static bool canSinkInstructions(ArrayRef< Instruction *> Insts, DenseMap< Instruction *, SmallVector< Value *, 4 >> &PHIOperands)
CaseIt findCaseValue(const ConstantInt *C)
Search all of the case values for the specified constant.
bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
static ConstantInt * getTrue(LLVMContext &Context)
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
static bool DominatesMergePoint(Value *V, BasicBlock *BB, SmallPtrSetImpl< Instruction *> &AggressiveInsts, int &BudgetRemaining, const TargetTransformInfo &TTI, unsigned Depth=0)
If we have a merge point of an "if condition" as accepted above, return true if the specified value d...
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
The access may modify the value stored in memory.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Class for arbitrary precision integers.
static bool HoistThenElseCodeToIf(BranchInst *BI, const TargetTransformInfo &TTI)
Given a conditional branch that goes to BB1 and BB2, hoist any common code in the two blocks up into ...
void removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
Replace 'BB's terminator with one that does not have an unwind successor block.
static cl::opt< bool > DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false), cl::desc("Duplicate return instructions into unconditional branches"))
static bool isLifeTimeMarker(const Instruction *I)
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
static bool CasesAreContiguous(SmallVectorImpl< ConstantInt *> &Cases)
iterator_range< user_iterator > users()
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM...
InstListType::iterator iterator
Instruction iterators...
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
void FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
iterator insert(iterator I, T &&Elt)
const Value * getFalseValue() const
If this flag is set, the remapper ignores missing function-local entries (Argument, Instruction, BasicBlock) that are not in the value map.
SwitchInst * CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases=10, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a switch instruction with the specified value, default dest, and with a hint for the number of...
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::ZeroOrMore, cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate IT block based on arch"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow deprecated IT based on ARMv8"), clEnumValN(NoRestrictedIT, "arm-no-restrict-it", "Allow IT blocks based on ARMv7")))
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
ReturnInst * CreateRetVoid()
Create a 'ret void' instruction.
Predicate getPredicate() const
Return the predicate for this instruction.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static cl::opt< unsigned > TwoEntryPHINodeFoldingThreshold("two-entry-phi-node-folding-threshold", cl::Hidden, cl::init(4), cl::desc("Control the maximal total instruction cost that we are willing " "to speculatively execute to fold a 2-entry PHI node into a " "select (default = 4)"))
iterator insert(iterator where, pointer New)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
void registerAssumption(CallInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
unsigned getIntegerBitWidth() const
LLVM_NODISCARD bool empty() const
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value...
bool isTokenTy() const
Return true if this is 'token'.
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.
static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred, BasicBlock *ExistPred, MemorySSAUpdater *MSSAU=nullptr)
Update PHI nodes in Succ to indicate that there will now be entries in it from the 'NewPred' block...
unsigned pred_size(const BasicBlock *BB)
Get the number of predecessors of BB.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
const APInt & getLower() const
Return the lower value for this range.
Value * getValue() const
Convenience accessor.
bool empty() const
Determine if the SetVector is empty or not.
static bool removeEmptyCleanup(CleanupReturnInst *RI)
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Constant * ConstantFoldInstOperands(Instruction *I, ArrayRef< Constant *> Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands...
static bool ValuesOverlap(std::vector< ValueEqualityComparisonCase > &C1, std::vector< ValueEqualityComparisonCase > &C2)
Return true if there are any keys in C1 that exist in C2 as well.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
static void createUnreachableSwitchDefault(SwitchInst *Switch)
CaseIt case_default()
Returns an iterator that points to the default case.
bool isUnconditional() const
static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI, Value *SelectValue, IRBuilder<> &Builder)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB, const TargetTransformInfo &TTI)
Speculate a conditional basic block flattening the CFG.
unsigned getAlignment() const
Return the alignment of the access that is being performed FIXME: Remove this function once transitio...
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 * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
static bool switchToSelect(SwitchInst *SI, IRBuilder<> &Builder, const DataLayout &DL, const TargetTransformInfo &TTI)
If the switch is only used to initialize one or more phi nodes in a common successor block with only ...
void setCondition(Value *V)
static BasicBlock * allPredecessorsComeFromSameSource(BasicBlock *BB)
static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder, const DataLayout &DL, const TargetTransformInfo &TTI)
Try to transform a switch that has "holes" in it to a contiguous sequence of cases.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned getMinSignedBits() const
Get the minimum bit size for this signed APInt.
user_iterator user_begin()
LLVM_NODISCARD char front() const
front - Get the first character in the string.
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 ...
bool operator<(int64_t V1, const APSInt &V2)
BasicBlock * getUnwindDest() const
static bool ForwardSwitchConditionToPHI(SwitchInst *SI)
Try to forward the condition of a switch instruction to a phi node dominated by the switch...
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
void setDefaultDest(BasicBlock *DefaultCase)
succ_range successors(Instruction *I)
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
static const Function * getParent(const Value *V)
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB, BasicBlock *QTB, BasicBlock *QFB, BasicBlock *PostBB, Value *Address, bool InvertPCond, bool InvertQCond, const DataLayout &DL, const TargetTransformInfo &TTI)
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
cst_pred_ty< is_any_apint > m_AnyIntegralConstant()
Match an integer or vector with any integral constant.
static PHINode * FindPHIForConditionForwarding(ConstantInt *CaseValue, BasicBlock *BB, int *PhiIndex)
If BB would be eligible for simplification by TryToSimplifyUncondBranchFromEmptyBlock (i...
bool hasOneUse() const
Return true if there is exactly one user of this value.
StringRef - Represent a constant reference to a string, i.e.
const Instruction * getFirstNonPHIOrDbg() const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic...
bool fitsInLegalInteger(unsigned Width) const
Returns true if the specified type fits in a native integer type supported by the CPU...
bool simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, const SimplifyCFGOptions &Options={}, SmallPtrSetImpl< BasicBlock *> *LoopHeaders=nullptr)
This function is used to do simplification of a CFG.
A set of parameters used to control the transforms in the SimplifyCFG pass.
bool operator==(uint64_t V1, const APInt &V2)
static void FitWeights(MutableArrayRef< uint64_t > Weights)
Keep halving the weights until all can fit in uint32_t.
void setIncomingValue(unsigned i, Value *V)
unsigned getNumOperands() const
Return number of MDNode operands.
bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const
Retrieve the raw weight values of a conditional branch or select.
ConstantRange inverse() const
Return a new range that is the logical not of the current set.
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
Value * getPointerOperand()
static bool ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize, const TargetTransformInfo &TTI, const DataLayout &DL, const SmallDenseMap< PHINode *, Type *> &ResultTypes)
Determine whether a lookup table should be built for this switch, based on the number of cases...
void removeDestination(unsigned i)
This method removes the specified successor from the indirectbr instruction.
Instruction * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
void changeCondBranchToUnconditionalTo(const BranchInst *BI, const BasicBlock *To)
Conditional branch BI is changed or replaced with an unconditional branch to To.
BinaryOp_match< ValTy, cst_pred_ty< is_all_ones >, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI, BasicBlock *BB)
Given an block with only a single landing pad and a unconditional branch try to find another basic bl...
bool mayReadOrWriteMemory() const
Return true if this instruction may read or write memory.
const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
static Constant * LookupConstant(Value *V, const SmallDenseMap< Value *, Constant *> &ConstantPool)
If V is a Constant, return it.