36 #define DEBUG_TYPE "instcombine"
59 using namespace llvm::PatternMatch;
61 STATISTIC(NumCombined ,
"Number of insts combined");
62 STATISTIC(NumConstProp,
"Number of constant folds");
63 STATISTIC(NumDeadInst ,
"Number of dead inst eliminated");
64 STATISTIC(NumSunkInst ,
"Number of instructions sunk");
65 STATISTIC(NumExpand,
"Number of expansions");
66 STATISTIC(NumFactor ,
"Number of factorizations");
67 STATISTIC(NumReassoc ,
"Number of reassociations");
71 cl::desc(
"Enable unsafe double to float "
72 "shrinking for math lib calls"));
85 "Combine redundant instructions",
false,
false)
103 bool InstCombiner::ShouldChangeType(
Type *From,
Type *To)
const {
107 if (!
TD)
return false;
111 bool FromLegal =
TD->isLegalInteger(FromWidth);
112 bool ToLegal =
TD->isLegalInteger(ToWidth);
116 if (FromLegal && !ToLegal)
121 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
140 if (Opcode != Instruction::Add &&
141 Opcode != Instruction::Sub) {
153 const APInt &CVal = CC->getValue();
154 bool Overflow =
false;
156 if (Opcode == Instruction::Add) {
201 bool InstCombiner::SimplifyAssociativeOrCommutative(
BinaryOperator &
I) {
203 bool Changed =
false;
247 if (Op1 && Op1->getOpcode() == Opcode) {
249 Value *B = Op1->getOperand(0);
250 Value *C = Op1->getOperand(1);
289 if (Op1 && Op1->getOpcode() == Opcode) {
291 Value *B = Op1->getOperand(0);
292 Value *C = Op1->getOperand(1);
311 Op0->
getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
313 isa<Constant>(Op1->getOperand(1)) &&
317 Value *B = Op1->getOperand(0);
318 Constant *C2 = cast<Constant>(Op1->getOperand(1));
322 InsertNewInstWith(New, I);
358 case Instruction::Mul:
363 case Instruction::Add:
364 case Instruction::Sub:
403 if (Op0 && Op1 && Op0->
getOpcode() == Op1->getOpcode()) {
407 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
417 if (A == C || (InnerCommutative && A == D)) {
425 if (!V && Op0->
hasOneUse() && Op1->hasOneUse())
426 V = Builder->CreateBinOp(TopLevelOpcode, B, D, Op1->getName());
429 V = Builder->CreateBinOp(InnerOpcode, A, V);
439 if (B == D || (InnerCommutative && B == C)) {
447 if (!V && Op0->
hasOneUse() && Op1->hasOneUse())
448 V = Builder->CreateBinOp(TopLevelOpcode, A, C, Op0->
getName());
451 V = Builder->CreateBinOp(InnerOpcode, V, B);
471 if ((L == A && R == B) ||
478 C = Builder->CreateBinOp(InnerOpcode, L, R);
487 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
496 if ((L == B && R == C) ||
503 A = Builder->CreateBinOp(InnerOpcode, L, R);
515 Value *InstCombiner::dyn_castNegVal(
Value *V)
const {
534 Value *InstCombiner::dyn_castFNegVal(
Value *V,
bool IgnoreZeroSign)
const {
551 if (
CastInst *CI = dyn_cast<CastInst>(&I)) {
556 bool ConstIsRHS = isa<Constant>(I.
getOperand(1));
559 if (
Constant *SOC = dyn_cast<Constant>(SO)) {
565 Value *Op0 = SO, *Op1 = ConstOperand;
572 if (
ICmpInst *CI = dyn_cast<ICmpInst>(&I))
575 if (
FCmpInst *CI = dyn_cast<FCmpInst>(&I))
591 if (isa<Constant>(TV) || isa<Constant>(FV)) {
597 if (
BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
602 if ((SrcTy == NULL) != (DestTy == NULL))
return 0;
612 SelectTrueVal, SelectFalseVal);
625 if (NumPHIValues == 0)
648 for (
unsigned i = 0; i != NumPHIValues; ++i) {
650 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
653 if (isa<PHINode>(InVal))
return 0;
654 if (NonConstBB)
return 0;
660 if (
InvokeInst *II = dyn_cast<InvokeInst>(InVal))
661 if (II->getParent() == NonConstBB)
675 if (NonConstBB != 0) {
682 InsertNewInstBefore(NewPN, *PN);
691 if (
SelectInst *SI = dyn_cast<SelectInst>(&I)) {
697 for (
unsigned i = 0; i != NumPHIValues; ++i) {
703 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
706 TrueVInPred, FalseVInPred,
"phitmp");
709 }
else if (
CmpInst *CI = dyn_cast<CmpInst>(&I)) {
711 for (
unsigned i = 0; i != NumPHIValues; ++i) {
715 else if (isa<ICmpInst>(CI))
725 for (
unsigned i = 0; i != NumPHIValues; ++i) {
730 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
737 for (
unsigned i = 0; i != NumPHIValues; ++i) {
742 InV = Builder->CreateCast(CI->
getOpcode(),
751 if (User == &I)
continue;
752 ReplaceInstUsesWith(*User, NewPN);
753 EraseInstFromFunction(*User);
755 return ReplaceInstUsesWith(I, NewPN);
762 Type *InstCombiner::FindElementAtOffset(
Type *PtrTy, int64_t Offset,
776 Type *IntPtrTy =
TD->getIntPtrType(PtrTy);
777 int64_t FirstIdx = 0;
778 if (int64_t TySize =
TD->getTypeAllocSize(Ty)) {
779 FirstIdx = Offset/TySize;
780 Offset -= FirstIdx*TySize;
788 assert((uint64_t)Offset < (uint64_t)TySize &&
"Out of range offset");
796 if (uint64_t(Offset*8) >=
TD->getTypeSizeInBits(Ty))
799 if (
StructType *STy = dyn_cast<StructType>(Ty)) {
802 "Offset must stay within the indexed type");
809 Ty = STy->getElementType(Elt);
810 }
else if (
ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
811 uint64_t EltSize =
TD->getTypeAllocSize(AT->getElementType());
812 assert(EltSize &&
"Cannot index into a zero-sized array");
815 Ty = AT->getElementType();
837 Value *InstCombiner::Descale(
Value *Val,
APInt Scale,
bool &NoSignedWrap) {
838 assert(isa<IntegerType>(Val->
getType()) &&
"Can only descale integers!");
840 Scale.
getBitWidth() &&
"Scale not compatible with value!");
876 std::pair<Instruction*, unsigned> Parent;
880 bool RequireNoSignedWrap =
false;
885 for (;; Op = Parent.first->getOperand(Parent.second)) {
889 APInt Quotient(Scale), Remainder(Scale);
891 if (!Remainder.isMinValue())
902 if (BO->getOpcode() == Instruction::Mul) {
904 NoSignedWrap = BO->hasNoSignedWrap();
905 if (RequireNoSignedWrap && !NoSignedWrap)
911 Value *LHS = BO->getOperand(0);
912 Value *RHS = BO->getOperand(1);
914 if (
ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
916 if (CI->getValue() == Scale) {
927 Parent = std::make_pair(BO, 1);
936 Parent = std::make_pair(BO, 0);
940 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
941 isa<ConstantInt>(BO->getOperand(1))) {
943 NoSignedWrap = BO->hasNoSignedWrap();
944 if (RequireNoSignedWrap && !NoSignedWrap)
947 Value *LHS = BO->getOperand(0);
948 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
952 if (Amt == logScale) {
958 if (Amt < logScale || !Op->hasOneUse())
963 Parent = std::make_pair(BO, 1);
972 if (
CastInst *Cast = dyn_cast<CastInst>(Op)) {
973 if (Cast->getOpcode() == Instruction::SExt) {
975 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
987 RequireNoSignedWrap =
true;
990 Parent = std::make_pair(Cast, 0);
995 if (Cast->getOpcode() == Instruction::Trunc) {
1002 if (RequireNoSignedWrap)
1006 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1007 Parent = std::make_pair(Cast, 0);
1008 Scale = Scale.
sext(LargeSize);
1009 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1030 assert(Parent.first->hasOneUse() &&
"Drilled down when more than one use!");
1031 assert(Op != Parent.first->getOperand(Parent.second) &&
1032 "Descaling was a no-op?");
1033 Parent.first->setOperand(Parent.second, Op);
1034 Worklist.Add(Parent.first);
1048 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1049 NoSignedWrap &= OpNoSignedWrap;
1050 if (NoSignedWrap != OpNoSignedWrap) {
1051 BO->setHasNoSignedWrap(NoSignedWrap);
1052 Worklist.Add(Ancestor);
1054 }
else if (Ancestor->
getOpcode() == Instruction::Trunc) {
1058 NoSignedWrap =
false;
1060 assert((Ancestor->
getOpcode() != Instruction::SExt || NoSignedWrap) &&
1061 "Failed to keep proper track of nsw flags while drilling down?");
1063 if (Ancestor == Val)
1068 assert(Ancestor->
hasOneUse() &&
"Drilled down when more than one use!");
1077 return ReplaceInstUsesWith(GEP, V);
1084 bool MadeChange =
false;
1089 I != E; ++
I, ++GTI) {
1092 if (!SeqTy)
continue;
1098 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1103 Type *IndexTy = (*I)->getType();
1104 if (IndexTy != IntPtrTy) {
1108 *I = Builder->CreateIntCast(*I, IntPtrTy,
true);
1112 if (MadeChange)
return &GEP;
1119 if (
GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1127 dyn_cast<GEPOperator>(Src->getOperand(0)))
1134 bool EndsWithSequential =
false;
1137 EndsWithSequential = !(*I)->isStructTy();
1140 if (EndsWithSequential) {
1145 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1158 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->
getName()+
".sum");
1162 if (Src->getNumOperands() == 2) {
1167 Indices.
append(Src->op_begin()+1, Src->op_end()-1);
1170 }
else if (isa<Constant>(*GEP.
idx_begin()) &&
1171 cast<Constant>(*GEP.
idx_begin())->isNullValue() &&
1172 Src->getNumOperands() != 1) {
1174 Indices.
append(Src->op_begin()+1, Src->op_end());
1178 if (!Indices.
empty())
1179 return (GEP.
isInBounds() && Src->isInBounds()) ?
1193 TD->getPointerSizeInBits(AS)) {
1195 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->
getType());
1209 if (StrippedPtr != PtrOp &&
1212 bool HasZeroPointerIndex =
false;
1214 HasZeroPointerIndex = C->isZero();
1223 if (HasZeroPointerIndex) {
1240 if (CATy->getElementType() == XATy->getElementType()) {
1259 TD->getTypeAllocSize(ResElTy)) {
1263 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.
getName()) :
1264 Builder->CreateGEP(StrippedPtr, Idx, GEP.
getName());
1276 uint64_t ResSize =
TD->getTypeAllocSize(ResElTy);
1277 uint64_t SrcSize =
TD->getTypeAllocSize(SrcElTy);
1278 if (ResSize && SrcSize % ResSize == 0) {
1281 uint64_t Scale = SrcSize / ResSize;
1286 "Index not cast to pointer width?");
1289 if (
Value *NewIdx = Descale(Idx,
APInt(BitWidth, Scale), NSW)) {
1294 Builder->CreateInBoundsGEP(StrippedPtr, NewIdx, GEP.
getName()) :
1295 Builder->CreateGEP(StrippedPtr, NewIdx, GEP.
getName());
1310 uint64_t ResSize =
TD->getTypeAllocSize(ResElTy);
1311 uint64_t ArrayEltSize
1313 if (ResSize && ArrayEltSize % ResSize == 0) {
1316 uint64_t Scale = ArrayEltSize / ResSize;
1321 "Index not cast to pointer width?");
1324 if (
Value *NewIdx = Descale(Idx,
APInt(BitWidth, Scale), NSW)) {
1334 Builder->CreateInBoundsGEP(StrippedPtr, Off, GEP.
getName()) :
1335 Builder->CreateGEP(StrippedPtr, Off, GEP.
getName());
1352 if (
BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1353 Value *Operand = BCI->getOperand(0);
1355 unsigned OffsetBits =
TD->getPointerTypeSizeInBits(OpType);
1356 APInt Offset(OffsetBits, 0);
1357 if (!isa<BitCastInst>(Operand) &&
1371 BCI->getParent()->getInstList().insert(BCI, I);
1372 ReplaceInstUsesWith(*BCI, I);
1384 if (FindElementAtOffset(OpType, Offset.
getSExtValue(), NewIndices)) {
1386 Builder->CreateInBoundsGEP(Operand, NewIndices) :
1387 Builder->CreateGEP(Operand, NewIndices);
1390 return ReplaceInstUsesWith(GEP, NGEP);
1416 case Instruction::BitCast:
1417 case Instruction::GetElementPtr:
1422 case Instruction::ICmp: {
1434 switch (II->getIntrinsicID()) {
1474 }
while (!Worklist.
empty());
1484 for (
unsigned i = 0, e = Users.
size(); i != e; ++i) {
1485 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1488 if (
ICmpInst *C = dyn_cast<ICmpInst>(I)) {
1489 ReplaceInstUsesWith(*C,
1491 C->isFalseWhenEqual()));
1492 }
else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
1494 }
else if (
IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1496 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1497 uint64_t DontKnow = CI->
isZero() ? -1ULL : 0;
1501 EraseInstFromFunction(*I);
1504 if (
InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
1506 Module *M = II->getParent()->getParent()->getParent();
1509 None,
"", II->getParent());
1511 return EraseInstFromFunction(MI);
1548 if (FreeInstrBB->
size() != 2)
1567 "Broken CFG: missing edge from predecessor to successor");
1578 if (isa<UndefValue>(Op)) {
1582 return EraseInstFromFunction(FI);
1587 if (isa<ConstantPointerNull>(Op))
1588 return EraseInstFromFunction(FI);
1611 !isa<Constant>(X)) {
1621 TrueDest, FalseDest)) &&
1637 TrueDest, FalseDest)) &&
1655 if (
Instruction *I = dyn_cast<Instruction>(Cond)) {
1665 assert(isa<ConstantInt>(NewCaseVal) &&
1666 "Result of expression should be constant");
1667 i.setValue(cast<ConstantInt>(NewCaseVal));
1681 return ReplaceInstUsesWith(EV, Agg);
1683 if (
Constant *C = dyn_cast<Constant>(Agg)) {
1686 return ReplaceInstUsesWith(EV, C2);
1696 const unsigned *exti, *exte, *insi, *inse;
1697 for (exti = EV.
idx_begin(), insi = IV->idx_begin(),
1698 exte = EV.
idx_end(), inse = IV->idx_end();
1699 exti != exte && insi != inse;
1713 if (exti == exte && insi == inse)
1718 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
1728 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
1749 if (II->hasOneUse()) {
1753 switch (II->getIntrinsicID()) {
1757 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1759 EraseInstFromFunction(*II);
1760 return BinaryOperator::CreateAdd(LHS, RHS);
1767 if (
ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
1774 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1776 EraseInstFromFunction(*II);
1777 return BinaryOperator::CreateSub(LHS, RHS);
1783 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1785 EraseInstFromFunction(*II);
1786 return BinaryOperator::CreateMul(LHS, RHS);
1794 if (
LoadInst *L = dyn_cast<LoadInst>(Agg))
1799 if (L->isSimple() && L->hasOneUse()) {
1803 Indices.
push_back(Builder->getInt32(0));
1806 Indices.
push_back(Builder->getInt32(*I));
1810 Builder->SetInsertPoint(L->getParent(), L);
1811 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
1814 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
1850 switch (Personality) {
1866 cast<ArrayType>(LHS->
getType())->getNumElements()
1868 cast<ArrayType>(RHS->
getType())->getNumElements();
1879 bool MakeNewInstruction =
false;
1885 bool isLastClause = i + 1 == e;
1893 if (AlreadyCaught.
insert(TypeInfo)) {
1898 MakeNewInstruction =
true;
1905 MakeNewInstruction =
true;
1906 CleanupFlag =
false;
1917 assert(LI.
isFilter(i) &&
"Unsupported landingpad clause!");
1919 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
1925 if (!NumTypeInfos) {
1928 MakeNewInstruction =
true;
1929 CleanupFlag =
false;
1933 bool MakeNewFilter =
false;
1935 if (isa<ConstantAggregateZero>(FilterClause)) {
1937 assert(NumTypeInfos > 0 &&
"Should have handled empty filter already!");
1943 MakeNewInstruction =
true;
1950 if (NumTypeInfos > 1)
1951 MakeNewFilter =
true;
1955 NewFilterElts.
reserve(NumTypeInfos);
1960 bool SawCatchAll =
false;
1961 for (
unsigned j = 0; j != NumTypeInfos; ++j) {
1969 if (AlreadyCaught.
count(TypeInfo))
1975 if (SeenInFilter.insert(TypeInfo))
1976 NewFilterElts.
push_back(cast<Constant>(Elt));
1981 MakeNewInstruction =
true;
1986 if (NewFilterElts.
size() < NumTypeInfos)
1987 MakeNewFilter =
true;
1989 if (MakeNewFilter) {
1991 NewFilterElts.
size());
1993 MakeNewInstruction =
true;
2002 if (MakeNewFilter && !NewFilterElts.
size()) {
2003 assert(MakeNewInstruction &&
"New filter but not a new instruction!");
2004 CleanupFlag =
false;
2015 for (
unsigned i = 0, e = NewClauses.
size(); i + 1 < e; ) {
2018 for (j = i; j != e; ++j)
2019 if (!isa<ArrayType>(NewClauses[j]->
getType()))
2025 for (
unsigned k = i; k + 1 < j; ++k)
2029 std::stable_sort(NewClauses.
begin() + i, NewClauses.
begin() + j,
2031 MakeNewInstruction =
true;
2050 for (
unsigned i = 0; i + 1 < NewClauses.
size(); ++i) {
2052 Value *Filter = NewClauses[i];
2060 for (
unsigned j = NewClauses.
size() - 1; j != i; --j) {
2061 Value *LFilter = NewClauses[j];
2072 NewClauses.
erase(J);
2073 MakeNewInstruction =
true;
2083 if (isa<ConstantAggregateZero>(LFilter)) {
2086 if (isa<ConstantAggregateZero>(Filter)) {
2087 assert(FElts <= LElts &&
"Should have handled this case earlier!");
2089 NewClauses.
erase(J);
2090 MakeNewInstruction =
true;
2096 if (isa<ConstantAggregateZero>(Filter)) {
2099 assert(FElts > 0 &&
"Should have eliminated the empty filter earlier!");
2100 for (
unsigned l = 0; l != LElts; ++l)
2103 NewClauses.
erase(J);
2104 MakeNewInstruction =
true;
2115 bool AllFound =
true;
2116 for (
unsigned f = 0; f != FElts; ++f) {
2119 for (
unsigned l = 0; l != LElts; ++l) {
2121 if (LTypeInfo == FTypeInfo) {
2131 NewClauses.
erase(J);
2132 MakeNewInstruction =
true;
2140 if (MakeNewInstruction) {
2144 for (
unsigned i = 0, e = NewClauses.
size(); i != e; ++i)
2149 if (NewClauses.
empty())
2158 assert(!CleanupFlag &&
"Adding a cleanup, not removing one?!");
2174 assert(I->
hasOneUse() &&
"Invariants didn't hold!");
2178 isa<TerminatorInst>(
I))
2182 if (isa<AllocaInst>(I) && I->
getParent() ==
2191 if (Scan->mayWriteToMemory())
2216 bool MadeIRChange =
false;
2227 if (!Visited.
insert(BB))
continue;
2235 DEBUG(
dbgs() <<
"IC: DCE: " << *Inst <<
'\n');
2243 DEBUG(
dbgs() <<
"IC: ConstFold to: " << *C <<
" from: "
2256 if (CE == 0)
continue;
2258 Constant*& FoldRes = FoldedConstants[CE];
2264 if (FoldRes != CE) {
2266 MadeIRChange =
true;
2271 InstrsForInstCombineWorklist.
push_back(Inst);
2277 if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2279 bool CondVal = cast<ConstantInt>(BI->
getCondition())->getZExtValue();
2284 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2289 if (i.getCaseValue() == Cond) {
2290 BasicBlock *ReachableBB = i.getCaseSuccessor();
2296 Worklist.
push_back(SI->getDefaultDest());
2303 }
while (!Worklist.
empty());
2311 InstrsForInstCombineWorklist.
size());
2313 return MadeIRChange;
2317 MadeIRChange =
false;
2319 DEBUG(
dbgs() <<
"\n\nINSTCOMBINE ITERATION #" << Iteration <<
" on "
2334 if (Visited.
count(BB))
continue;
2339 while (EndInst != BB->begin()) {
2345 if (isa<LandingPadInst>(Inst)) {
2349 if (!isa<DbgInfoIntrinsic>(Inst)) {
2351 MadeIRChange =
true;
2358 while (!Worklist.isEmpty()) {
2360 if (I == 0)
continue;
2364 DEBUG(
dbgs() <<
"IC: DCE: " << *I <<
'\n');
2365 EraseInstFromFunction(*I);
2367 MadeIRChange =
true;
2374 DEBUG(
dbgs() <<
"IC: ConstFold to: " << *C <<
" from: " << *I <<
'\n');
2377 ReplaceInstUsesWith(*I, C);
2379 EraseInstFromFunction(*I);
2380 MadeIRChange =
true;
2391 if (
PHINode *PN = dyn_cast<PHINode>(UserInst))
2396 if (UserParent != BB) {
2397 bool UserIsSuccessor =
false;
2400 if (*SI == UserParent) {
2401 UserIsSuccessor =
true;
2408 if (UserIsSuccessor && UserParent->getSinglePredecessor())
2416 Builder->SetCurrentDebugLocation(I->
getDebugLoc());
2422 DEBUG(
dbgs() <<
"IC: Visiting: " << OrigI <<
'\n');
2428 DEBUG(
dbgs() <<
"IC: Old = " << *I <<
'\n'
2429 <<
" New = " << *Result <<
'\n');
2437 Result->takeName(I);
2440 Worklist.Add(Result);
2441 Worklist.AddUsersToWorkList(*Result);
2449 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2454 EraseInstFromFunction(*I);
2457 DEBUG(
dbgs() <<
"IC: Mod = " << OrigI <<
'\n'
2458 <<
" New = " << *I <<
'\n');
2464 EraseInstFromFunction(*I);
2467 Worklist.AddUsersToWorkList(*I);
2470 MadeIRChange =
true;
2475 return MadeIRChange;
2498 TD = getAnalysisIfAvailable<DataLayout>();
2499 TLI = &getAnalysis<TargetLibraryInfo>();
2509 Builder = &TheBuilder;
2511 InstCombinerLibCallSimplifier TheSimplifier(
TD, TLI,
this);
2512 Simplifier = &TheSimplifier;
2514 bool EverMadeChange =
false;
2521 unsigned Iteration = 0;
2522 while (DoOneIteration(F, Iteration++))
2523 EverMadeChange =
true;
2526 return EverMadeChange;
void push_back(const T &Elt)
bool isAllocationFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates or reallocates memory (eith...
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
class_match< Value > m_Value()
m_Value() - Match an arbitrary value and ignore it.
void setHasNoSignedWrap(bool b=true)
Abstract base class of comparison instructions.
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="")
void initializeInstCombinerPass(PassRegistry &)
void setFastMathFlags(FastMathFlags FMF)
static IntegerType * getInt1Ty(LLVMContext &C)
void addIncoming(Value *V, BasicBlock *BB)
LLVMContext & getContext() const
static const Value * getFNegArgument(const Value *BinOp)
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
void LLVMInitializeInstCombine(LLVMPassRegistryRef R)
void swapSuccessors()
Swap the successors of this branch instruction.
unsigned getScalarSizeInBits()
The main container class for the LLVM Intermediate Representation.
static void ClearSubclassDataAfterReassociation(BinaryOperator &I)
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=0)
enable_if_c<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
unsigned getNumOperands() const
bool hasNoSignedWrap() const
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
INITIALIZE_PASS_BEGIN(InstCombiner,"instcombine","Combine redundant instructions", false, false) INITIALIZE_PASS_END(InstCombiner
br_match m_UnconditionalBr(BasicBlock *&Succ)
Predicate getInversePredicate() const
Return the inverse of the instruction's predicate.
Value * EmitGEPOffset(IRBuilderTy *Builder, const DataLayout &TD, User *GEP, bool NoAssumptions=false)
gep_type_iterator gep_type_end(const User *GEP)
bool mayHaveSideEffects() const
static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
bool isPtrOrPtrVectorTy() const
static bool RightDistributesOverLeft(Instruction::BinaryOps LOp, Instruction::BinaryOps ROp)
static bool isEquality(Predicate P)
FastMathFlags getFastMathFlags() const
const Function * getParent() const
Return the enclosing method, or null if none.
virtual bool runOnFunction(Function &F)
unsigned getAddressSpace() const
Return the address space of the Pointer type.
LLVMContext ** unwrap(LLVMContextRef *Tys)
FunctionType * getType(LLVMContext &Context, ID id, ArrayRef< Type * > Tys=None)
static Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
iv Induction Variable Users
bool hasAttribute(unsigned Index, Attribute::AttrKind Kind) const
Return true if the attribute exists at the given index.
StringSwitch & Case(const char(&S)[N], const T &Value)
Value * getPersonalityFn() const
static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C)
unsigned getNumIndices() const
APInt ssub_ov(const APInt &RHS, bool &Overflow) const
LoopInfoBase< BlockT, LoopT > * LI
Type * getPointerElementType() const
const CallInst * isFreeCall(const Value *I, const TargetLibraryInfo *TLI)
isFreeCall - Returns non-null if the value is a call to the builtin free()
static Constant * getNullValue(Type *Ty)
StringRef getName() const
bool match(Val *V, const Pattern &P)
bool isUnknown() const
isUnknown - Return true if this is an unknown location.
#define INITIALIZE_PASS_DEPENDENCY(depName)
static const Value * getNegArgument(const Value *BinOp)
CmpClass_match< LHS, RHS, FCmpInst, FCmpInst::Predicate > m_FCmp(FCmpInst::Predicate &Pred, const LHS &L, const RHS &R)
bool isUnconditional() const
static unsigned getComplexity(Value *V)
static unsigned getBitWidth(Type *Ty, const DataLayout *TD)
bool isIdenticalTo(const Instruction *I) const
static Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0)
Base class of casting instructions.
const APInt & getValue() const
Return the constant's value.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val()
#define llvm_unreachable(msg)
Type * getArrayElementType() const
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
InstCombiner - The -instcombine pass.
0 1 0 1 True if ordered and less than or equal
static bool shorter_filter(const Value *LHS, const Value *RHS)
Type * getPointerOperandType() const
not_match< LHS > m_Not(const LHS &L)
Interval::succ_iterator succ_begin(Interval *I)
Instruction * visitBranchInst(BranchInst &BI)
void setCleanup(bool V)
setCleanup - Indicate that this landingpad instruction is a cleanup.
bool mayReadFromMemory() const
LLVMContext & getContext() const
getContext - Return the LLVMContext in which this type was uniqued.
bool count(PtrType Ptr) const
count - Return true if the specified pointer is in the set.
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
bool isAssociative() const
Constant * ConstantFoldConstantExpression(const ConstantExpr *CE, const DataLayout *TD=0, const TargetLibraryInfo *TLI=0)
Represents a floating point comparison operator.
BasicBlock * getSuccessor(unsigned i) const
static LandingPadInst * Create(Type *RetTy, Value *PersonalityFn, unsigned NumReservedClauses, const Twine &NameStr="", Instruction *InsertBefore=0)
This class represents a no-op cast from one type to another.
Constant * ConstantFoldInstruction(Instruction *I, const DataLayout *TD=0, const TargetLibraryInfo *TLI=0)
bool isFloatingPointTy() const
TargetFolder - Create constants with target dependent folding.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
unsigned getNumClauses() const
getNumClauses - Get the number of clauses for this landing pad.
void replaceAllUsesWith(Value *V)
unsigned getNumElements() const
Return the number of elements in the Vector type.
FunctionPass * createInstructionCombiningPass()
void addClause(Value *ClauseVal)
addClause - Add a catch or filter clause to the landing pad.
Type * getElementType() const
Value * SimplifyGEPInst(ArrayRef< Value * > Ops, const DataLayout *TD=0, const TargetLibraryInfo *TLI=0, const DominatorTree *DT=0)
bool isInBounds() const
isInBounds - Determine whether the GEP has the inbounds flag.
Interval::succ_iterator succ_end(Interval *I)
unsigned getNumIncomingValues() const
uint64_t getElementOffset(unsigned Idx) const
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=0)
Construct any of the CastInst subclasses.
unsigned getNumSuccessors() const
Value * getClause(unsigned Idx) const
bool isFilter(unsigned Idx) const
isFilter - Return 'true' if the clause and index Idx is a filter clause.
static bool isCatchAll(Personality_Type Personality, Constant *TypeInfo)
isCatchAll - Return 'true' if the given typeinfo will match anything.
static Constant * getFNeg(Constant *C)
A switch()-like statement whose cases are string literals.
initializer< Ty > init(const Ty &Val)
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="")
APInt LLVM_ATTRIBUTE_UNUSED_RESULT trunc(unsigned width) const
Truncate to new width.
LLVM Basic Block Representation.
BasicBlock * getSuccessor(unsigned idx) const
LLVM Constant Representation.
static cl::opt< bool > UnsafeFPShrink("enable-double-float-shrink", cl::Hidden, cl::init(false), cl::desc("Enable unsafe double to float ""shrinking for math lib calls"))
const Value * getCondition() const
int64_t getSExtValue() const
Get sign extended value.
static bool LeftDistributesOverRight(Instruction::BinaryOps LOp, Instruction::BinaryOps ROp)
Instruction * ReplaceInstUsesWith(Instruction &I, Value *V)
APInt Or(const APInt &LHS, const APInt &RHS)
Bitwise OR function for APInt.
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=0)
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static InvokeInst * Create(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr="", Instruction *InsertBefore=0)
APInt Xor(const APInt &LHS, const APInt &RHS)
Bitwise XOR function for APInt.
Value * getRawDest() const
specificval_ty m_Specific(const Value *V)
m_Specific - Match if we have a specific specified value.
const DebugLoc & getDebugLoc() const
getDebugLoc - Return the debug location for this node as a DebugLoc.
APInt LLVM_ATTRIBUTE_UNUSED_RESULT sext(unsigned width) const
Sign extend to a new width.
brc_match< Cond_t > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=0)
BasicBlock * getIncomingBlock(unsigned i) const
const InstListType & getInstList() const
Return the underlying instruction list container.
uint64_t getNumElements() const
Represent an integer comparison operator.
iterator insert(iterator where, NodeTy *New)
unsigned getBitWidth() const
Return the number of bits in the APInt.
Value * getOperand(unsigned i) const
bool isCommutative() const
InstCombineWorklist Worklist
Worklist - All of the instructions that need to be simplified.
static Constant * getNot(Constant *C)
Constant * getAggregateElement(unsigned Elt) const
static Value * FoldOperationIntoSelectOperand(Instruction &I, Value *SO, InstCombiner *IC)
void append(in_iter in_start, in_iter in_end)
static UndefValue * get(Type *T)
iterator erase(iterator I)
LLVMContext & getContext() const
All values hold a context through their type.
bool LowerDbgDeclare(Function &F)
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
bool hasNoSignedWrap() const
hasNoSignedWrap - Determine whether the no signed wrap flag is set.
const Value * getTrueValue() const
Value * SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const DataLayout *TD=0, const TargetLibraryInfo *TLI=0, const DominatorTree *DT=0)
neg_match< LHS > m_Neg(const LHS &L)
m_Neg - Match an integer negate.
bool isConditional() const
BinaryOps getOpcode() const
static PointerType * getInt1PtrTy(LLVMContext &C, unsigned AS=0)
Class for constant integers.
struct LLVMOpaquePassRegistry * LLVMPassRegistryRef
bool DoOneIteration(Function &F, unsigned ItNum)
Value * getIncomingValue(unsigned i) const
Value * DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB)
bool hasAllZeroIndices() const
uint64_t getSizeInBytes() const
SequentialType * getType() const
Value * stripPointerCasts()
Strips off any unneeded pointer casts, all-zero GEPs and aliases from the specified value...
unsigned getElementContainingOffset(uint64_t Offset) const
Instruction * visitFree(CallInst &FI)
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
static GetElementPtrInst * Create(Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", Instruction *InsertBefore=0)
int32_t exactLogBase2() const
const BasicBlock & getEntryBlock() const
static ConstantInt * getTrue(LLVMContext &Context)
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
R Default(const T &Value) const
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs - Return a circular-buffered debug stream.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
AttributeSet getAttributes() const
Return the attribute list for this Function.
bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const
Accumulate the constant address offset of this GEP if possible.
Value * getArgOperand(unsigned i) const
static bool isNeg(const Value *V)
Class for arbitrary precision integers.
CastClass_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
m_PtrToInt
BasicBlock * getSinglePredecessor()
Return this block if it has a single predecessor block. Otherwise return a null pointer.
Instruction * visitSwitchInst(SwitchInst &SI)
static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock)
Instruction * visitExtractValueInst(ExtractValueInst &EV)
Value * getCondition() const
bool isMinValue() const
Determine if this is the smallest unsigned value.
void AddInitialGroup(Instruction *const *List, unsigned NumEntries)
APInt And(const APInt &LHS, const APInt &RHS)
Bitwise AND function for APInt.
Instruction * visitLandingPadInst(LandingPadInst &LI)
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", Instruction *InsertBefore=0)
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
Value * getCondition() const
static IntegerType * getInt32Ty(LLVMContext &C)
void setCondition(Value *V)
Combine redundant instructions
unsigned greater or equal
static bool isFNeg(const Value *V, bool IgnoreZeroSign=false)
bool isCatch(unsigned Idx) const
isCatch - Return 'true' if the clause and index Idx is a catch clause.
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
static bool AddReachableCodeToWorklist(BasicBlock *BB, SmallPtrSet< BasicBlock *, 64 > &Visited, InstCombiner &IC, const DataLayout *TD, const TargetLibraryInfo *TLI)
0 1 1 0 True if ordered and operands are unequal
static ArrayType * get(Type *ElementType, uint64_t NumElements)
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=0)
APInt sadd_ov(const APInt &RHS, bool &Overflow) const
unsigned getPrimitiveSizeInBits() const
void setCondition(Value *V)
static bool isAllocSiteRemovable(Instruction *AI, SmallVectorImpl< WeakVH > &Users, const TargetLibraryInfo *TLI)
LLVM Value Representation.
unsigned getOpcode() const
getOpcode() returns a member of one of the enums like Instruction::Add.
void clearSubclassOptionalData()
void moveBefore(Instruction *MovePos)
static Instruction * tryToMoveFreeBeforeNullTest(CallInst &FI)
Move the call to free before a NULL test.
void print(raw_ostream &O, AssemblyAnnotationWriter *AAW=0) const
Instruction * visitGetElementPtrInst(GetElementPtrInst &GEP)
const Value * getFalseValue() const
Convenience struct for specifying and reasoning about fast-math flags.
static Constant * getCompare(unsigned short pred, Constant *C1, Constant *C2)
Return an ICmp or FCmp comparison operator constant expression.
STATISTIC(NumCombined,"Number of insts combined")
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml","ocaml 3.10-compatible collector")
static GetElementPtrInst * CreateInBounds(Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", Instruction *InsertBefore=0)
iterator getFirstInsertionPt()
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src)
0 0 1 1 True if ordered and greater than or equal
static Constant * getCast(unsigned ops, Constant *C, Type *Ty)
void initializeInstCombine(PassRegistry &)
Value * getPointerOperand()
Instruction * visitAllocSite(Instruction &FI)
static RegisterPass< NVPTXAllocaHoisting > X("alloca-hoisting","Hoisting alloca instructions in non-entry ""blocks to the entry block")
const BasicBlock * getParent() const
INITIALIZE_PASS(GlobalMerge,"global-merge","Global Merge", false, false) bool GlobalMerge const DataLayout * TD
static Personality_Type RecognizePersonality(Value *Pers)
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
gep_type_iterator gep_type_begin(const User *GEP)
Function must be optimized for size first.