1 //===- InstCombineAddSub.cpp ----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visit functions for add, fadd, sub, and fsub.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombine.h"
15 #include "llvm/Analysis/InstructionSimplify.h"
16 #include "llvm/Target/TargetData.h"
17 #include "llvm/Support/GetElementPtrTypeIterator.h"
18 #include "llvm/Support/PatternMatch.h"
20 using namespace PatternMatch;
22 /// AddOne - Add one to a ConstantInt.
23 static Constant *AddOne(Constant *C) {
24 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
26 /// SubOne - Subtract one from a ConstantInt.
27 static Constant *SubOne(ConstantInt *C) {
28 return ConstantInt::get(C->getContext(), C->getValue()-1);
32 // dyn_castFoldableMul - If this value is a multiply that can be folded into
33 // other computations (because it has a constant operand), return the
34 // non-constant operand of the multiply, and set CST to point to the multiplier.
35 // Otherwise, return null.
37 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
38 if (!V->hasOneUse() || !V->getType()->isIntegerTy())
41 Instruction *I = dyn_cast<Instruction>(V);
44 if (I->getOpcode() == Instruction::Mul)
45 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
46 return I->getOperand(0);
47 if (I->getOpcode() == Instruction::Shl)
48 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
49 // The multiplier is really 1 << CST.
50 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
51 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
52 CST = ConstantInt::get(V->getType()->getContext(),
53 APInt(BitWidth, 1).shl(CSTVal));
54 return I->getOperand(0);
60 /// WillNotOverflowSignedAdd - Return true if we can prove that:
61 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
62 /// This basically requires proving that the add in the original type would not
63 /// overflow to change the sign bit or have a carry out.
64 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
65 // There are different heuristics we can use for this. Here are some simple
68 // Add has the property that adding any two 2's complement numbers can only
69 // have one carry bit which can change a sign. As such, if LHS and RHS each
70 // have at least two sign bits, we know that the addition of the two values
71 // will sign extend fine.
72 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
76 // If one of the operands only has one non-zero bit, and if the other operand
77 // has a known-zero bit in a more significant place than it (not including the
78 // sign bit) the ripple may go up to and fill the zero, but won't change the
79 // sign. For example, (X & ~4) + 1.
86 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
87 bool Changed = SimplifyAssociativeOrCommutative(I);
88 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
90 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
91 I.hasNoUnsignedWrap(), TD))
92 return ReplaceInstUsesWith(I, V);
94 // (A*B)+(A*C) -> A*(B+C) etc
95 if (Value *V = SimplifyUsingDistributiveLaws(I))
96 return ReplaceInstUsesWith(I, V);
98 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
99 // X + (signbit) --> X ^ signbit
100 const APInt &Val = CI->getValue();
102 return BinaryOperator::CreateXor(LHS, RHS);
104 // See if SimplifyDemandedBits can simplify this. This handles stuff like
105 // (X & 254)+1 -> (X&254)|1
106 if (SimplifyDemandedInstructionBits(I))
109 // zext(bool) + C -> bool ? C + 1 : C
110 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
111 if (ZI->getSrcTy()->isIntegerTy(1))
112 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
114 Value *XorLHS = 0; ConstantInt *XorRHS = 0;
115 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
116 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
117 const APInt &RHSVal = CI->getValue();
118 unsigned ExtendAmt = 0;
119 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
120 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
121 if (XorRHS->getValue() == -RHSVal) {
122 if (RHSVal.isPowerOf2())
123 ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
124 else if (XorRHS->getValue().isPowerOf2())
125 ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
129 APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
130 if (!MaskedValueIsZero(XorLHS, Mask))
135 Constant *ShAmt = ConstantInt::get(I.getType(), ExtendAmt);
136 Value *NewShl = Builder->CreateShl(XorLHS, ShAmt, "sext");
137 return BinaryOperator::CreateAShr(NewShl, ShAmt);
140 // If this is a xor that was canonicalized from a sub, turn it back into
141 // a sub and fuse this add with it.
142 if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
143 IntegerType *IT = cast<IntegerType>(I.getType());
144 APInt LHSKnownOne(IT->getBitWidth(), 0);
145 APInt LHSKnownZero(IT->getBitWidth(), 0);
146 ComputeMaskedBits(XorLHS, LHSKnownZero, LHSKnownOne);
147 if ((XorRHS->getValue() | LHSKnownZero).isAllOnesValue())
148 return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
154 if (isa<Constant>(RHS) && isa<PHINode>(LHS))
155 if (Instruction *NV = FoldOpIntoPhi(I))
158 if (I.getType()->isIntegerTy(1))
159 return BinaryOperator::CreateXor(LHS, RHS);
163 BinaryOperator *New =
164 BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
165 New->setHasNoSignedWrap(I.hasNoSignedWrap());
166 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
171 // -A + -B --> -(A + B)
172 if (Value *LHSV = dyn_castNegVal(LHS)) {
173 if (Value *RHSV = dyn_castNegVal(RHS)) {
174 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
175 return BinaryOperator::CreateNeg(NewAdd);
178 return BinaryOperator::CreateSub(RHS, LHSV);
182 if (!isa<Constant>(RHS))
183 if (Value *V = dyn_castNegVal(RHS))
184 return BinaryOperator::CreateSub(LHS, V);
188 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
189 if (X == RHS) // X*C + X --> X * (C+1)
190 return BinaryOperator::CreateMul(RHS, AddOne(C2));
192 // X*C1 + X*C2 --> X * (C1+C2)
194 if (X == dyn_castFoldableMul(RHS, C1))
195 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
198 // X + X*C --> X * (C+1)
199 if (dyn_castFoldableMul(RHS, C2) == LHS)
200 return BinaryOperator::CreateMul(LHS, AddOne(C2));
202 // A+B --> A|B iff A and B have no bits set in common.
203 if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
204 APInt LHSKnownOne(IT->getBitWidth(), 0);
205 APInt LHSKnownZero(IT->getBitWidth(), 0);
206 ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
207 if (LHSKnownZero != 0) {
208 APInt RHSKnownOne(IT->getBitWidth(), 0);
209 APInt RHSKnownZero(IT->getBitWidth(), 0);
210 ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
212 // No bits in common -> bitwise or.
213 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
214 return BinaryOperator::CreateOr(LHS, RHS);
218 // W*X + Y*Z --> W * (X+Z) iff W == Y
220 Value *W, *X, *Y, *Z;
221 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
222 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
235 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
236 return BinaryOperator::CreateMul(W, NewAdd);
241 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
243 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
244 return BinaryOperator::CreateSub(SubOne(CRHS), X);
246 // (X & FF00) + xx00 -> (X+xx00) & FF00
247 if (LHS->hasOneUse() &&
248 match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
249 CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
250 // See if all bits from the first bit set in the Add RHS up are included
251 // in the mask. First, get the rightmost bit.
252 const APInt &AddRHSV = CRHS->getValue();
254 // Form a mask of all bits from the lowest bit added through the top.
255 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
257 // See if the and mask includes all of these bits.
258 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
260 if (AddRHSHighBits == AddRHSHighBitsAnd) {
261 // Okay, the xform is safe. Insert the new add pronto.
262 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
263 return BinaryOperator::CreateAnd(NewAdd, C2);
267 // Try to fold constant add into select arguments.
268 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
269 if (Instruction *R = FoldOpIntoSelect(I, SI))
273 // add (select X 0 (sub n A)) A --> select X A n
275 SelectInst *SI = dyn_cast<SelectInst>(LHS);
278 SI = dyn_cast<SelectInst>(RHS);
281 if (SI && SI->hasOneUse()) {
282 Value *TV = SI->getTrueValue();
283 Value *FV = SI->getFalseValue();
286 // Can we fold the add into the argument of the select?
287 // We check both true and false select arguments for a matching subtract.
288 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
289 // Fold the add into the true select value.
290 return SelectInst::Create(SI->getCondition(), N, A);
292 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
293 // Fold the add into the false select value.
294 return SelectInst::Create(SI->getCondition(), A, N);
298 // Check for (add (sext x), y), see if we can merge this into an
299 // integer add followed by a sext.
300 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
301 // (add (sext x), cst) --> (sext (add x, cst'))
302 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
304 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
305 if (LHSConv->hasOneUse() &&
306 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
307 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
308 // Insert the new, smaller add.
309 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
311 return new SExtInst(NewAdd, I.getType());
315 // (add (sext x), (sext y)) --> (sext (add int x, y))
316 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
317 // Only do this if x/y have the same type, if at last one of them has a
318 // single use (so we don't increase the number of sexts), and if the
319 // integer add will not overflow.
320 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
321 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
322 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
323 RHSConv->getOperand(0))) {
324 // Insert the new integer add.
325 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
326 RHSConv->getOperand(0), "addconv");
327 return new SExtInst(NewAdd, I.getType());
332 // Check for (x & y) + (x ^ y)
334 Value *A = 0, *B = 0;
335 if (match(RHS, m_Xor(m_Value(A), m_Value(B))) &&
336 (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
337 match(LHS, m_And(m_Specific(B), m_Specific(A)))))
338 return BinaryOperator::CreateOr(A, B);
340 if (match(LHS, m_Xor(m_Value(A), m_Value(B))) &&
341 (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
342 match(RHS, m_And(m_Specific(B), m_Specific(A)))))
343 return BinaryOperator::CreateOr(A, B);
346 return Changed ? &I : 0;
349 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
350 bool Changed = SimplifyAssociativeOrCommutative(I);
351 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
353 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
355 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
356 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
357 (I.getType())->getValueAPF()))
358 return ReplaceInstUsesWith(I, LHS);
361 if (isa<PHINode>(LHS))
362 if (Instruction *NV = FoldOpIntoPhi(I))
367 // -A + -B --> -(A + B)
368 if (Value *LHSV = dyn_castFNegVal(LHS))
369 return BinaryOperator::CreateFSub(RHS, LHSV);
372 if (!isa<Constant>(RHS))
373 if (Value *V = dyn_castFNegVal(RHS))
374 return BinaryOperator::CreateFSub(LHS, V);
376 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
377 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
378 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
379 return ReplaceInstUsesWith(I, LHS);
381 // Check for (fadd double (sitofp x), y), see if we can merge this into an
382 // integer add followed by a promotion.
383 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
384 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
385 // ... if the constant fits in the integer value. This is useful for things
386 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
387 // requires a constant pool load, and generally allows the add to be better
389 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
391 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
392 if (LHSConv->hasOneUse() &&
393 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
394 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
395 // Insert the new integer add.
396 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
398 return new SIToFPInst(NewAdd, I.getType());
402 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
403 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
404 // Only do this if x/y have the same type, if at last one of them has a
405 // single use (so we don't increase the number of int->fp conversions),
406 // and if the integer add will not overflow.
407 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
408 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
409 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
410 RHSConv->getOperand(0))) {
411 // Insert the new integer add.
412 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
413 RHSConv->getOperand(0),"addconv");
414 return new SIToFPInst(NewAdd, I.getType());
419 return Changed ? &I : 0;
423 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
424 /// code necessary to compute the offset from the base pointer (without adding
425 /// in the base pointer). Return the result as a signed integer of intptr size.
426 /// If NoNUW is true, then the NUW flag is not used.
427 Value *InstCombiner::EmitGEPOffset(User *GEP, bool NoNUW) {
428 TargetData &TD = *getTargetData();
429 gep_type_iterator GTI = gep_type_begin(GEP);
430 Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
431 Value *Result = Constant::getNullValue(IntPtrTy);
433 // If the GEP is inbounds, we know that none of the addressing operations will
434 // overflow in an unsigned sense.
435 bool isInBounds = cast<GEPOperator>(GEP)->isInBounds() && !NoNUW;
437 // Build a mask for high order bits.
438 unsigned IntPtrWidth = TD.getPointerSizeInBits();
439 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
441 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
444 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
445 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
446 if (OpC->isZero()) continue;
448 // Handle a struct index, which adds its field offset to the pointer.
449 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
450 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
453 Result = Builder->CreateAdd(Result, ConstantInt::get(IntPtrTy, Size),
454 GEP->getName()+".offs");
458 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
460 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
461 Scale = ConstantExpr::getMul(OC, Scale, isInBounds/*NUW*/);
462 // Emit an add instruction.
463 Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
466 // Convert to correct type.
467 if (Op->getType() != IntPtrTy)
468 Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
470 // We'll let instcombine(mul) convert this to a shl if possible.
471 Op = Builder->CreateMul(Op, ConstantInt::get(IntPtrTy, Size),
472 GEP->getName()+".idx", isInBounds /*NUW*/);
475 // Emit an add instruction.
476 Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
484 /// Optimize pointer differences into the same array into a size. Consider:
485 /// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
486 /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
488 Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
490 assert(TD && "Must have target data info for this");
492 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
494 bool Swapped = false;
495 GEPOperator *GEP1 = 0, *GEP2 = 0;
497 // For now we require one side to be the base pointer "A" or a constant
498 // GEP derived from it.
499 if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
501 if (LHSGEP->getOperand(0) == RHS) {
504 } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
505 // (gep X, ...) - (gep X, ...)
506 if (LHSGEP->getOperand(0)->stripPointerCasts() ==
507 RHSGEP->getOperand(0)->stripPointerCasts()) {
515 if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
517 if (RHSGEP->getOperand(0) == LHS) {
520 } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
521 // (gep X, ...) - (gep X, ...)
522 if (RHSGEP->getOperand(0)->stripPointerCasts() ==
523 LHSGEP->getOperand(0)->stripPointerCasts()) {
531 // Avoid duplicating the arithmetic if GEP2 has non-constant indices and
534 (GEP2 != 0 && !GEP2->hasAllConstantIndices() && !GEP2->hasOneUse()))
537 // Emit the offset of the GEP and an intptr_t.
538 Value *Result = EmitGEPOffset(GEP1);
540 // If we had a constant expression GEP on the other side offsetting the
541 // pointer, subtract it from the offset we have.
543 Value *Offset = EmitGEPOffset(GEP2);
544 Result = Builder->CreateSub(Result, Offset);
547 // If we have p - gep(p, ...) then we have to negate the result.
549 Result = Builder->CreateNeg(Result, "diff.neg");
551 return Builder->CreateIntCast(Result, Ty, true);
555 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
556 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
558 if (Value *V = SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(),
559 I.hasNoUnsignedWrap(), TD))
560 return ReplaceInstUsesWith(I, V);
562 // (A*B)-(A*C) -> A*(B-C) etc
563 if (Value *V = SimplifyUsingDistributiveLaws(I))
564 return ReplaceInstUsesWith(I, V);
566 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
567 if (Value *V = dyn_castNegVal(Op1)) {
568 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
569 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
570 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
574 if (I.getType()->isIntegerTy(1))
575 return BinaryOperator::CreateXor(Op0, Op1);
577 // Replace (-1 - A) with (~A).
578 if (match(Op0, m_AllOnes()))
579 return BinaryOperator::CreateNot(Op1);
581 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
582 // C - ~X == X + (1+C)
584 if (match(Op1, m_Not(m_Value(X))))
585 return BinaryOperator::CreateAdd(X, AddOne(C));
587 // -(X >>u 31) -> (X >>s 31)
588 // -(X >>s 31) -> (X >>u 31)
590 Value *X; ConstantInt *CI;
591 if (match(Op1, m_LShr(m_Value(X), m_ConstantInt(CI))) &&
592 // Verify we are shifting out everything but the sign bit.
593 CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
594 return BinaryOperator::CreateAShr(X, CI);
596 if (match(Op1, m_AShr(m_Value(X), m_ConstantInt(CI))) &&
597 // Verify we are shifting out everything but the sign bit.
598 CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
599 return BinaryOperator::CreateLShr(X, CI);
602 // Try to fold constant sub into select arguments.
603 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
604 if (Instruction *R = FoldOpIntoSelect(I, SI))
607 // C - zext(bool) -> bool ? C - 1 : C
608 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
609 if (ZI->getSrcTy()->isIntegerTy(1))
610 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
612 // C-(X+C2) --> (C-C2)-X
614 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(C2))))
615 return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
617 if (SimplifyDemandedInstructionBits(I))
623 // X-(X+Y) == -Y X-(Y+X) == -Y
624 if (match(Op1, m_Add(m_Specific(Op0), m_Value(Y))) ||
625 match(Op1, m_Add(m_Value(Y), m_Specific(Op0))))
626 return BinaryOperator::CreateNeg(Y);
629 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
630 return BinaryOperator::CreateNeg(Y);
633 if (Op1->hasOneUse()) {
634 Value *X = 0, *Y = 0, *Z = 0;
638 // (X - (Y - Z)) --> (X + (Z - Y)).
639 if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
640 return BinaryOperator::CreateAdd(Op0,
641 Builder->CreateSub(Z, Y, Op1->getName()));
643 // (X - (X & Y)) --> (X & ~Y)
645 if (match(Op1, m_And(m_Value(Y), m_Specific(Op0))) ||
646 match(Op1, m_And(m_Specific(Op0), m_Value(Y))))
647 return BinaryOperator::CreateAnd(Op0,
648 Builder->CreateNot(Y, Y->getName() + ".not"));
650 // 0 - (X sdiv C) -> (X sdiv -C)
651 if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) &&
652 match(Op0, m_Zero()))
653 return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
655 // 0 - (X << Y) -> (-X << Y) when X is freely negatable.
656 if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
657 if (Value *XNeg = dyn_castNegVal(X))
658 return BinaryOperator::CreateShl(XNeg, Y);
660 // X - X*C --> X * (1-C)
661 if (match(Op1, m_Mul(m_Specific(Op0), m_ConstantInt(CI)))) {
662 Constant *CP1 = ConstantExpr::getSub(ConstantInt::get(I.getType(),1), CI);
663 return BinaryOperator::CreateMul(Op0, CP1);
666 // X - X<<C --> X * (1-(1<<C))
667 if (match(Op1, m_Shl(m_Specific(Op0), m_ConstantInt(CI)))) {
668 Constant *One = ConstantInt::get(I.getType(), 1);
669 C = ConstantExpr::getSub(One, ConstantExpr::getShl(One, CI));
670 return BinaryOperator::CreateMul(Op0, C);
673 // X - A*-B -> X + A*B
674 // X - -A*B -> X + A*B
676 if (match(Op1, m_Mul(m_Value(A), m_Neg(m_Value(B)))) ||
677 match(Op1, m_Mul(m_Neg(m_Value(A)), m_Value(B))))
678 return BinaryOperator::CreateAdd(Op0, Builder->CreateMul(A, B));
680 // X - A*CI -> X + A*-CI
681 // X - CI*A -> X + A*-CI
682 if (match(Op1, m_Mul(m_Value(A), m_ConstantInt(CI))) ||
683 match(Op1, m_Mul(m_ConstantInt(CI), m_Value(A)))) {
684 Value *NewMul = Builder->CreateMul(A, ConstantExpr::getNeg(CI));
685 return BinaryOperator::CreateAdd(Op0, NewMul);
690 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
691 if (X == Op1) // X*C - X --> X * (C-1)
692 return BinaryOperator::CreateMul(Op1, SubOne(C1));
694 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
695 if (X == dyn_castFoldableMul(Op1, C2))
696 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
699 // Optimize pointer differences into the same array into a size. Consider:
700 // &A[10] - &A[0]: we should compile this to "10".
702 Value *LHSOp, *RHSOp;
703 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
704 match(Op1, m_PtrToInt(m_Value(RHSOp))))
705 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
706 return ReplaceInstUsesWith(I, Res);
708 // trunc(p)-trunc(q) -> trunc(p-q)
709 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
710 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
711 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
712 return ReplaceInstUsesWith(I, Res);
718 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
719 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
721 // If this is a 'B = x-(-A)', change to B = x+A...
722 if (Value *V = dyn_castFNegVal(Op1))
723 return BinaryOperator::CreateFAdd(Op0, V);