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 if (Instruction *NV = SimplifyByFactorizing(I)) // (A*B)+(A*C) -> A*(B+C)
97 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
98 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
99 // X + (signbit) --> X ^ signbit
100 const APInt& Val = CI->getValue();
101 uint32_t BitWidth = Val.getBitWidth();
102 if (Val == APInt::getSignBit(BitWidth))
103 return BinaryOperator::CreateXor(LHS, RHS);
105 // See if SimplifyDemandedBits can simplify this. This handles stuff like
106 // (X & 254)+1 -> (X&254)|1
107 if (SimplifyDemandedInstructionBits(I))
110 // zext(bool) + C -> bool ? C + 1 : C
111 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
112 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
113 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
116 if (isa<PHINode>(LHS))
117 if (Instruction *NV = FoldOpIntoPhi(I))
120 ConstantInt *XorRHS = 0;
122 if (isa<ConstantInt>(RHSC) &&
123 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
124 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
125 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
126 unsigned ExtendAmt = 0;
127 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
128 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
129 if (XorRHS->getValue() == -RHSVal) {
130 if (RHSVal.isPowerOf2())
131 ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
132 else if (XorRHS->getValue().isPowerOf2())
133 ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
137 APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
138 if (!MaskedValueIsZero(XorLHS, Mask))
143 Constant *ShAmt = ConstantInt::get(I.getType(), ExtendAmt);
144 Value *NewShl = Builder->CreateShl(XorLHS, ShAmt, "sext");
145 return BinaryOperator::CreateAShr(NewShl, ShAmt);
150 if (I.getType()->isIntegerTy(1))
151 return BinaryOperator::CreateXor(LHS, RHS);
153 if (I.getType()->isIntegerTy()) {
156 return BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
158 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
159 if (RHSI->getOpcode() == Instruction::Sub)
160 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
161 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
163 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
164 if (LHSI->getOpcode() == Instruction::Sub)
165 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
166 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
171 // -A + -B --> -(A + B)
172 if (Value *LHSV = dyn_castNegVal(LHS)) {
173 if (LHS->getType()->isIntOrIntVectorTy()) {
174 if (Value *RHSV = dyn_castNegVal(RHS)) {
175 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
176 return BinaryOperator::CreateNeg(NewAdd);
180 return BinaryOperator::CreateSub(RHS, LHSV);
184 if (!isa<Constant>(RHS))
185 if (Value *V = dyn_castNegVal(RHS))
186 return BinaryOperator::CreateSub(LHS, V);
190 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
191 if (X == RHS) // X*C + X --> X * (C+1)
192 return BinaryOperator::CreateMul(RHS, AddOne(C2));
194 // X*C1 + X*C2 --> X * (C1+C2)
196 if (X == dyn_castFoldableMul(RHS, C1))
197 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
200 // X + X*C --> X * (C+1)
201 if (dyn_castFoldableMul(RHS, C2) == LHS)
202 return BinaryOperator::CreateMul(LHS, AddOne(C2));
204 // X + ~X --> -1 since ~X = -X-1
205 if (match(LHS, m_Not(m_Specific(RHS))) ||
206 match(RHS, m_Not(m_Specific(LHS))))
207 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
209 // A+B --> A|B iff A and B have no bits set in common.
210 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
211 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
212 APInt LHSKnownOne(IT->getBitWidth(), 0);
213 APInt LHSKnownZero(IT->getBitWidth(), 0);
214 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
215 if (LHSKnownZero != 0) {
216 APInt RHSKnownOne(IT->getBitWidth(), 0);
217 APInt RHSKnownZero(IT->getBitWidth(), 0);
218 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
220 // No bits in common -> bitwise or.
221 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
222 return BinaryOperator::CreateOr(LHS, RHS);
226 // W*X + Y*Z --> W * (X+Z) iff W == Y
227 if (I.getType()->isIntOrIntVectorTy()) {
228 Value *W, *X, *Y, *Z;
229 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
230 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
243 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
244 return BinaryOperator::CreateMul(W, NewAdd);
249 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
251 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
252 return BinaryOperator::CreateSub(SubOne(CRHS), X);
254 // (X & FF00) + xx00 -> (X+xx00) & FF00
255 if (LHS->hasOneUse() &&
256 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
257 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
259 // See if all bits from the first bit set in the Add RHS up are included
260 // in the mask. First, get the rightmost bit.
261 const APInt &AddRHSV = CRHS->getValue();
263 // Form a mask of all bits from the lowest bit added through the top.
264 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
266 // See if the and mask includes all of these bits.
267 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
269 if (AddRHSHighBits == AddRHSHighBitsAnd) {
270 // Okay, the xform is safe. Insert the new add pronto.
271 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
272 return BinaryOperator::CreateAnd(NewAdd, C2);
277 // Try to fold constant add into select arguments.
278 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
279 if (Instruction *R = FoldOpIntoSelect(I, SI))
283 // add (select X 0 (sub n A)) A --> select X A n
285 SelectInst *SI = dyn_cast<SelectInst>(LHS);
288 SI = dyn_cast<SelectInst>(RHS);
291 if (SI && SI->hasOneUse()) {
292 Value *TV = SI->getTrueValue();
293 Value *FV = SI->getFalseValue();
296 // Can we fold the add into the argument of the select?
297 // We check both true and false select arguments for a matching subtract.
298 if (match(FV, m_Zero()) &&
299 match(TV, m_Sub(m_Value(N), m_Specific(A))))
300 // Fold the add into the true select value.
301 return SelectInst::Create(SI->getCondition(), N, A);
302 if (match(TV, m_Zero()) &&
303 match(FV, m_Sub(m_Value(N), m_Specific(A))))
304 // Fold the add into the false select value.
305 return SelectInst::Create(SI->getCondition(), A, N);
309 // Check for (add (sext x), y), see if we can merge this into an
310 // integer add followed by a sext.
311 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
312 // (add (sext x), cst) --> (sext (add x, cst'))
313 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
315 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
316 if (LHSConv->hasOneUse() &&
317 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
318 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
319 // Insert the new, smaller add.
320 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
322 return new SExtInst(NewAdd, I.getType());
326 // (add (sext x), (sext y)) --> (sext (add int x, y))
327 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
328 // Only do this if x/y have the same type, if at last one of them has a
329 // single use (so we don't increase the number of sexts), and if the
330 // integer add will not overflow.
331 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
332 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
333 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
334 RHSConv->getOperand(0))) {
335 // Insert the new integer add.
336 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
337 RHSConv->getOperand(0), "addconv");
338 return new SExtInst(NewAdd, I.getType());
343 return Changed ? &I : 0;
346 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
347 bool Changed = SimplifyAssociativeOrCommutative(I);
348 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
350 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
352 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
353 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
354 (I.getType())->getValueAPF()))
355 return ReplaceInstUsesWith(I, LHS);
358 if (isa<PHINode>(LHS))
359 if (Instruction *NV = FoldOpIntoPhi(I))
364 // -A + -B --> -(A + B)
365 if (Value *LHSV = dyn_castFNegVal(LHS))
366 return BinaryOperator::CreateFSub(RHS, LHSV);
369 if (!isa<Constant>(RHS))
370 if (Value *V = dyn_castFNegVal(RHS))
371 return BinaryOperator::CreateFSub(LHS, V);
373 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
374 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
375 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
376 return ReplaceInstUsesWith(I, LHS);
378 // Check for (fadd double (sitofp x), y), see if we can merge this into an
379 // integer add followed by a promotion.
380 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
381 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
382 // ... if the constant fits in the integer value. This is useful for things
383 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
384 // requires a constant pool load, and generally allows the add to be better
386 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
388 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
389 if (LHSConv->hasOneUse() &&
390 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
391 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
392 // Insert the new integer add.
393 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
395 return new SIToFPInst(NewAdd, I.getType());
399 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
400 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
401 // Only do this if x/y have the same type, if at last one of them has a
402 // single use (so we don't increase the number of int->fp conversions),
403 // and if the integer add will not overflow.
404 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
405 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
406 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
407 RHSConv->getOperand(0))) {
408 // Insert the new integer add.
409 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
410 RHSConv->getOperand(0),"addconv");
411 return new SIToFPInst(NewAdd, I.getType());
416 return Changed ? &I : 0;
420 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
421 /// code necessary to compute the offset from the base pointer (without adding
422 /// in the base pointer). Return the result as a signed integer of intptr size.
423 Value *InstCombiner::EmitGEPOffset(User *GEP) {
424 TargetData &TD = *getTargetData();
425 gep_type_iterator GTI = gep_type_begin(GEP);
426 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
427 Value *Result = Constant::getNullValue(IntPtrTy);
429 // Build a mask for high order bits.
430 unsigned IntPtrWidth = TD.getPointerSizeInBits();
431 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
433 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
436 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
437 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
438 if (OpC->isZero()) continue;
440 // Handle a struct index, which adds its field offset to the pointer.
441 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
442 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
444 Result = Builder->CreateAdd(Result,
445 ConstantInt::get(IntPtrTy, Size),
446 GEP->getName()+".offs");
450 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
452 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
453 Scale = ConstantExpr::getMul(OC, Scale);
454 // Emit an add instruction.
455 Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
458 // Convert to correct type.
459 if (Op->getType() != IntPtrTy)
460 Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
462 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
463 // We'll let instcombine(mul) convert this to a shl if possible.
464 Op = Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
467 // Emit an add instruction.
468 Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
476 /// Optimize pointer differences into the same array into a size. Consider:
477 /// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
478 /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
480 Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
482 assert(TD && "Must have target data info for this");
484 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
486 bool Swapped = false;
487 GetElementPtrInst *GEP = 0;
488 ConstantExpr *CstGEP = 0;
490 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
491 // For now we require one side to be the base pointer "A" or a constant
492 // expression derived from it.
493 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
495 if (LHSGEP->getOperand(0) == RHS) {
498 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
499 // (gep X, ...) - (ce_gep X, ...)
500 if (CE->getOpcode() == Instruction::GetElementPtr &&
501 LHSGEP->getOperand(0) == CE->getOperand(0)) {
509 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
511 if (RHSGEP->getOperand(0) == LHS) {
514 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
515 // (ce_gep X, ...) - (gep X, ...)
516 if (CE->getOpcode() == Instruction::GetElementPtr &&
517 RHSGEP->getOperand(0) == CE->getOperand(0)) {
528 // Emit the offset of the GEP and an intptr_t.
529 Value *Result = EmitGEPOffset(GEP);
531 // If we had a constant expression GEP on the other side offsetting the
532 // pointer, subtract it from the offset we have.
534 Value *CstOffset = EmitGEPOffset(CstGEP);
535 Result = Builder->CreateSub(Result, CstOffset);
539 // If we have p - gep(p, ...) then we have to negate the result.
541 Result = Builder->CreateNeg(Result, "diff.neg");
543 return Builder->CreateIntCast(Result, Ty, true);
547 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
548 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
550 if (Op0 == Op1) // sub X, X -> 0
551 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
553 if (Instruction *NV = SimplifyByFactorizing(I)) // (A*B)-(A*C) -> A*(B-C)
556 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
557 if (Value *V = dyn_castNegVal(Op1)) {
558 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
559 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
560 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
564 if (isa<UndefValue>(Op0))
565 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
566 if (isa<UndefValue>(Op1))
567 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
568 if (I.getType()->isIntegerTy(1))
569 return BinaryOperator::CreateXor(Op0, Op1);
571 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
572 // Replace (-1 - A) with (~A).
573 if (C->isAllOnesValue())
574 return BinaryOperator::CreateNot(Op1);
576 // C - ~X == X + (1+C)
578 if (match(Op1, m_Not(m_Value(X))))
579 return BinaryOperator::CreateAdd(X, AddOne(C));
581 // -(X >>u 31) -> (X >>s 31)
582 // -(X >>s 31) -> (X >>u 31)
584 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
585 if (SI->getOpcode() == Instruction::LShr) {
586 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
587 // Check to see if we are shifting out everything but the sign bit.
588 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
589 SI->getType()->getPrimitiveSizeInBits()-1) {
590 // Ok, the transformation is safe. Insert AShr.
591 return BinaryOperator::Create(Instruction::AShr,
592 SI->getOperand(0), CU, SI->getName());
595 } else if (SI->getOpcode() == Instruction::AShr) {
596 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
597 // Check to see if we are shifting out everything but the sign bit.
598 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
599 SI->getType()->getPrimitiveSizeInBits()-1) {
600 // Ok, the transformation is safe. Insert LShr.
601 return BinaryOperator::CreateLShr(
602 SI->getOperand(0), CU, SI->getName());
609 // Try to fold constant sub into select arguments.
610 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
611 if (Instruction *R = FoldOpIntoSelect(I, SI))
614 // C - zext(bool) -> bool ? C - 1 : C
615 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
616 if (ZI->getSrcTy() == Type::getInt1Ty(I.getContext()))
617 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
620 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
621 if (Op1I->getOpcode() == Instruction::Add) {
622 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
623 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
625 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
626 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
628 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
629 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
630 // C1-(X+C2) --> (C1-C2)-X
631 return BinaryOperator::CreateSub(
632 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
636 if (Op1I->hasOneUse()) {
637 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
638 // is not used by anyone else...
640 if (Op1I->getOpcode() == Instruction::Sub) {
641 // Swap the two operands of the subexpr...
642 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
643 Op1I->setOperand(0, IIOp1);
644 Op1I->setOperand(1, IIOp0);
646 // Create the new top level add instruction...
647 return BinaryOperator::CreateAdd(Op0, Op1);
650 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
652 if (Op1I->getOpcode() == Instruction::And &&
653 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
654 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
656 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
657 return BinaryOperator::CreateAnd(Op0, NewNot);
660 // 0 - (X sdiv C) -> (X sdiv -C)
661 if (Op1I->getOpcode() == Instruction::SDiv)
662 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
664 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
665 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
666 ConstantExpr::getNeg(DivRHS));
668 // 0 - (C << X) -> (-C << X)
669 if (Op1I->getOpcode() == Instruction::Shl)
670 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
672 if (Value *ShlLHSNeg = dyn_castNegVal(Op1I->getOperand(0)))
673 return BinaryOperator::CreateShl(ShlLHSNeg, Op1I->getOperand(1));
675 // X - X*C --> X * (1-C)
677 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
679 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
681 return BinaryOperator::CreateMul(Op0, CP1);
684 // X - A*-B -> X + A*B
685 // X - -A*B -> X + A*B
687 if (match(Op1I, m_Mul(m_Value(A), m_Neg(m_Value(B)))) ||
688 match(Op1I, m_Mul(m_Neg(m_Value(A)), m_Value(B)))) {
689 Value *NewMul = Builder->CreateMul(A, B);
690 return BinaryOperator::CreateAdd(Op0, NewMul);
695 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
696 if (Op0I->getOpcode() == Instruction::Add) {
697 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
698 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
699 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
700 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
701 } else if (Op0I->getOpcode() == Instruction::Sub) {
702 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
703 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
709 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
710 if (X == Op1) // X*C - X --> X * (C-1)
711 return BinaryOperator::CreateMul(Op1, SubOne(C1));
713 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
714 if (X == dyn_castFoldableMul(Op1, C2))
715 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
718 // Optimize pointer differences into the same array into a size. Consider:
719 // &A[10] - &A[0]: we should compile this to "10".
721 Value *LHSOp, *RHSOp;
722 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
723 match(Op1, m_PtrToInt(m_Value(RHSOp))))
724 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
725 return ReplaceInstUsesWith(I, Res);
727 // trunc(p)-trunc(q) -> trunc(p-q)
728 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
729 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
730 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
731 return ReplaceInstUsesWith(I, Res);
737 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
738 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
740 // If this is a 'B = x-(-A)', change to B = x+A...
741 if (Value *V = dyn_castFNegVal(Op1))
742 return BinaryOperator::CreateFAdd(Op0, V);