blob: 91116ca27adf2e1183634a19250c952dc427302f [file] [log] [blame]
Chris Lattner53a19b72010-01-05 07:18:46 +00001//===- InstCombineAddSub.cpp ----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visit functions for add, fadd, sub, and fsub.
11//
12//===----------------------------------------------------------------------===//
13
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"
19using namespace llvm;
20using namespace PatternMatch;
21
22/// AddOne - Add one to a ConstantInt.
23static Constant *AddOne(Constant *C) {
24 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
25}
26/// SubOne - Subtract one from a ConstantInt.
27static Constant *SubOne(ConstantInt *C) {
28 return ConstantInt::get(C->getContext(), C->getValue()-1);
29}
30
31
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.
36//
37static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +000038 if (!V->hasOneUse() || !V->getType()->isIntegerTy())
Chris Lattner3168c7d2010-01-05 20:56:24 +000039 return 0;
40
41 Instruction *I = dyn_cast<Instruction>(V);
42 if (I == 0) return 0;
43
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);
Chris Lattner53a19b72010-01-05 07:18:46 +000055 }
56 return 0;
57}
58
59
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.
64bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
65 // There are different heuristics we can use for this. Here are some simple
66 // ones.
67
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)
73 return true;
74
75
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.
80
81 // TODO: Implement.
82
83 return false;
84}
85
86Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +000087 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner53a19b72010-01-05 07:18:46 +000088 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
89
90 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
91 I.hasNoUnsignedWrap(), TD))
92 return ReplaceInstUsesWith(I, V);
93
Duncan Sands37bf92b2010-12-22 13:36:08 +000094 // (A*B)+(A*C) -> A*(B+C) etc
95 if (Value *V = SimplifyUsingDistributiveLaws(I))
96 return ReplaceInstUsesWith(I, V);
97
Chris Lattnerb9b90442011-02-10 05:14:58 +000098 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
99 // X + (signbit) --> X ^ signbit
100 const APInt &Val = CI->getValue();
101 if (Val.isSignBit())
102 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattner53a19b72010-01-05 07:18:46 +0000103
Chris Lattnerb9b90442011-02-10 05:14:58 +0000104 // See if SimplifyDemandedBits can simplify this. This handles stuff like
105 // (X & 254)+1 -> (X&254)|1
106 if (SimplifyDemandedInstructionBits(I))
107 return &I;
108
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);
113
114 Value *XorLHS = 0; ConstantInt *XorRHS = 0;
115 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner53a19b72010-01-05 07:18:46 +0000116 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Chris Lattnerb9b90442011-02-10 05:14:58 +0000117 const APInt &RHSVal = CI->getValue();
Eli Friedmanbe7cfa62010-01-31 04:29:12 +0000118 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;
Chris Lattner53a19b72010-01-05 07:18:46 +0000126 }
Chris Lattnerb9b90442011-02-10 05:14:58 +0000127
Eli Friedmanbe7cfa62010-01-31 04:29:12 +0000128 if (ExtendAmt) {
129 APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
130 if (!MaskedValueIsZero(XorLHS, Mask))
131 ExtendAmt = 0;
132 }
Chris Lattnerb9b90442011-02-10 05:14:58 +0000133
Eli Friedmanbe7cfa62010-01-31 04:29:12 +0000134 if (ExtendAmt) {
135 Constant *ShAmt = ConstantInt::get(I.getType(), ExtendAmt);
136 Value *NewShl = Builder->CreateShl(XorLHS, ShAmt, "sext");
137 return BinaryOperator::CreateAShr(NewShl, ShAmt);
Chris Lattner53a19b72010-01-05 07:18:46 +0000138 }
139 }
140 }
141
Chris Lattnerb9b90442011-02-10 05:14:58 +0000142 if (isa<Constant>(RHS) && isa<PHINode>(LHS))
143 if (Instruction *NV = FoldOpIntoPhi(I))
144 return NV;
145
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000146 if (I.getType()->isIntegerTy(1))
Chris Lattner53a19b72010-01-05 07:18:46 +0000147 return BinaryOperator::CreateXor(LHS, RHS);
148
Chris Lattnerb9b90442011-02-10 05:14:58 +0000149 // X + X --> X << 1
150 if (LHS == RHS && I.getType()->isIntegerTy())
151 return BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
Chris Lattner53a19b72010-01-05 07:18:46 +0000152
153 // -A + B --> B - A
154 // -A + -B --> -(A + B)
155 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnerb9b90442011-02-10 05:14:58 +0000156 if (Value *RHSV = dyn_castNegVal(RHS)) {
157 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
158 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner53a19b72010-01-05 07:18:46 +0000159 }
160
161 return BinaryOperator::CreateSub(RHS, LHSV);
162 }
163
164 // A + -B --> A - B
165 if (!isa<Constant>(RHS))
166 if (Value *V = dyn_castNegVal(RHS))
167 return BinaryOperator::CreateSub(LHS, V);
168
169
170 ConstantInt *C2;
171 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
172 if (X == RHS) // X*C + X --> X * (C+1)
173 return BinaryOperator::CreateMul(RHS, AddOne(C2));
174
175 // X*C1 + X*C2 --> X * (C1+C2)
176 ConstantInt *C1;
177 if (X == dyn_castFoldableMul(RHS, C1))
178 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
179 }
180
181 // X + X*C --> X * (C+1)
182 if (dyn_castFoldableMul(RHS, C2) == LHS)
183 return BinaryOperator::CreateMul(LHS, AddOne(C2));
184
Chris Lattner53a19b72010-01-05 07:18:46 +0000185 // A+B --> A|B iff A and B have no bits set in common.
186 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
187 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
188 APInt LHSKnownOne(IT->getBitWidth(), 0);
189 APInt LHSKnownZero(IT->getBitWidth(), 0);
190 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
191 if (LHSKnownZero != 0) {
192 APInt RHSKnownOne(IT->getBitWidth(), 0);
193 APInt RHSKnownZero(IT->getBitWidth(), 0);
194 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
195
196 // No bits in common -> bitwise or.
197 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
198 return BinaryOperator::CreateOr(LHS, RHS);
199 }
200 }
201
202 // W*X + Y*Z --> W * (X+Z) iff W == Y
Chris Lattnerb9b90442011-02-10 05:14:58 +0000203 {
Chris Lattner53a19b72010-01-05 07:18:46 +0000204 Value *W, *X, *Y, *Z;
205 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
206 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
207 if (W != Y) {
208 if (W == Z) {
209 std::swap(Y, Z);
210 } else if (Y == X) {
211 std::swap(W, X);
212 } else if (X == Z) {
213 std::swap(Y, Z);
214 std::swap(W, X);
215 }
216 }
217
218 if (W == Y) {
219 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
220 return BinaryOperator::CreateMul(W, NewAdd);
221 }
222 }
223 }
224
225 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
226 Value *X = 0;
227 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
228 return BinaryOperator::CreateSub(SubOne(CRHS), X);
229
230 // (X & FF00) + xx00 -> (X+xx00) & FF00
231 if (LHS->hasOneUse() &&
Chris Lattnerb9b90442011-02-10 05:14:58 +0000232 match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
233 CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
234 // See if all bits from the first bit set in the Add RHS up are included
235 // in the mask. First, get the rightmost bit.
236 const APInt &AddRHSV = CRHS->getValue();
237
238 // Form a mask of all bits from the lowest bit added through the top.
239 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattner53a19b72010-01-05 07:18:46 +0000240
Chris Lattnerb9b90442011-02-10 05:14:58 +0000241 // See if the and mask includes all of these bits.
242 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Chris Lattner53a19b72010-01-05 07:18:46 +0000243
Chris Lattnerb9b90442011-02-10 05:14:58 +0000244 if (AddRHSHighBits == AddRHSHighBitsAnd) {
245 // Okay, the xform is safe. Insert the new add pronto.
246 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
247 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattner53a19b72010-01-05 07:18:46 +0000248 }
249 }
250
251 // Try to fold constant add into select arguments.
252 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
253 if (Instruction *R = FoldOpIntoSelect(I, SI))
254 return R;
255 }
256
257 // add (select X 0 (sub n A)) A --> select X A n
258 {
259 SelectInst *SI = dyn_cast<SelectInst>(LHS);
260 Value *A = RHS;
261 if (!SI) {
262 SI = dyn_cast<SelectInst>(RHS);
263 A = LHS;
264 }
265 if (SI && SI->hasOneUse()) {
266 Value *TV = SI->getTrueValue();
267 Value *FV = SI->getFalseValue();
268 Value *N;
269
270 // Can we fold the add into the argument of the select?
271 // We check both true and false select arguments for a matching subtract.
Chris Lattnerb9b90442011-02-10 05:14:58 +0000272 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner53a19b72010-01-05 07:18:46 +0000273 // Fold the add into the true select value.
274 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattnerb9b90442011-02-10 05:14:58 +0000275
276 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner53a19b72010-01-05 07:18:46 +0000277 // Fold the add into the false select value.
278 return SelectInst::Create(SI->getCondition(), A, N);
279 }
280 }
281
282 // Check for (add (sext x), y), see if we can merge this into an
283 // integer add followed by a sext.
284 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
285 // (add (sext x), cst) --> (sext (add x, cst'))
286 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
287 Constant *CI =
288 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
289 if (LHSConv->hasOneUse() &&
290 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
291 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
292 // Insert the new, smaller add.
293 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
294 CI, "addconv");
295 return new SExtInst(NewAdd, I.getType());
296 }
297 }
298
299 // (add (sext x), (sext y)) --> (sext (add int x, y))
300 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
301 // Only do this if x/y have the same type, if at last one of them has a
302 // single use (so we don't increase the number of sexts), and if the
303 // integer add will not overflow.
304 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
305 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
306 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
307 RHSConv->getOperand(0))) {
308 // Insert the new integer add.
309 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner3168c7d2010-01-05 20:56:24 +0000310 RHSConv->getOperand(0), "addconv");
Chris Lattner53a19b72010-01-05 07:18:46 +0000311 return new SExtInst(NewAdd, I.getType());
312 }
313 }
314 }
315
316 return Changed ? &I : 0;
317}
318
319Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +0000320 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner53a19b72010-01-05 07:18:46 +0000321 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
322
323 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
324 // X + 0 --> X
325 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
326 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
327 (I.getType())->getValueAPF()))
328 return ReplaceInstUsesWith(I, LHS);
329 }
330
331 if (isa<PHINode>(LHS))
332 if (Instruction *NV = FoldOpIntoPhi(I))
333 return NV;
334 }
335
336 // -A + B --> B - A
337 // -A + -B --> -(A + B)
338 if (Value *LHSV = dyn_castFNegVal(LHS))
339 return BinaryOperator::CreateFSub(RHS, LHSV);
340
341 // A + -B --> A - B
342 if (!isa<Constant>(RHS))
343 if (Value *V = dyn_castFNegVal(RHS))
344 return BinaryOperator::CreateFSub(LHS, V);
345
346 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
347 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
348 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
349 return ReplaceInstUsesWith(I, LHS);
350
Dan Gohmana9445e12010-03-02 01:11:08 +0000351 // Check for (fadd double (sitofp x), y), see if we can merge this into an
Chris Lattner53a19b72010-01-05 07:18:46 +0000352 // integer add followed by a promotion.
353 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
Dan Gohmana9445e12010-03-02 01:11:08 +0000354 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
Chris Lattner53a19b72010-01-05 07:18:46 +0000355 // ... if the constant fits in the integer value. This is useful for things
356 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
357 // requires a constant pool load, and generally allows the add to be better
358 // instcombined.
359 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
360 Constant *CI =
361 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
362 if (LHSConv->hasOneUse() &&
363 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
364 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
365 // Insert the new integer add.
366 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
367 CI, "addconv");
368 return new SIToFPInst(NewAdd, I.getType());
369 }
370 }
371
Dan Gohmana9445e12010-03-02 01:11:08 +0000372 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
Chris Lattner53a19b72010-01-05 07:18:46 +0000373 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
374 // Only do this if x/y have the same type, if at last one of them has a
375 // single use (so we don't increase the number of int->fp conversions),
376 // and if the integer add will not overflow.
377 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
378 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
379 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
380 RHSConv->getOperand(0))) {
381 // Insert the new integer add.
382 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
383 RHSConv->getOperand(0),"addconv");
384 return new SIToFPInst(NewAdd, I.getType());
385 }
386 }
387 }
388
389 return Changed ? &I : 0;
390}
391
392
393/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
394/// code necessary to compute the offset from the base pointer (without adding
395/// in the base pointer). Return the result as a signed integer of intptr size.
396Value *InstCombiner::EmitGEPOffset(User *GEP) {
397 TargetData &TD = *getTargetData();
398 gep_type_iterator GTI = gep_type_begin(GEP);
399 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
400 Value *Result = Constant::getNullValue(IntPtrTy);
401
402 // Build a mask for high order bits.
403 unsigned IntPtrWidth = TD.getPointerSizeInBits();
404 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
405
406 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
407 ++i, ++GTI) {
408 Value *Op = *i;
409 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
410 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
411 if (OpC->isZero()) continue;
412
413 // Handle a struct index, which adds its field offset to the pointer.
414 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
415 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
416
417 Result = Builder->CreateAdd(Result,
418 ConstantInt::get(IntPtrTy, Size),
419 GEP->getName()+".offs");
420 continue;
421 }
422
423 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
424 Constant *OC =
425 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
426 Scale = ConstantExpr::getMul(OC, Scale);
427 // Emit an add instruction.
428 Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
429 continue;
430 }
431 // Convert to correct type.
432 if (Op->getType() != IntPtrTy)
433 Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
434 if (Size != 1) {
435 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
436 // We'll let instcombine(mul) convert this to a shl if possible.
437 Op = Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
438 }
439
440 // Emit an add instruction.
441 Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
442 }
443 return Result;
444}
445
446
447
448
449/// Optimize pointer differences into the same array into a size. Consider:
450/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
451/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
452///
453Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
454 const Type *Ty) {
455 assert(TD && "Must have target data info for this");
456
457 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
458 // this.
459 bool Swapped = false;
460 GetElementPtrInst *GEP = 0;
461 ConstantExpr *CstGEP = 0;
462
463 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
464 // For now we require one side to be the base pointer "A" or a constant
465 // expression derived from it.
466 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
467 // (gep X, ...) - X
468 if (LHSGEP->getOperand(0) == RHS) {
469 GEP = LHSGEP;
470 Swapped = false;
471 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
472 // (gep X, ...) - (ce_gep X, ...)
473 if (CE->getOpcode() == Instruction::GetElementPtr &&
474 LHSGEP->getOperand(0) == CE->getOperand(0)) {
475 CstGEP = CE;
476 GEP = LHSGEP;
477 Swapped = false;
478 }
479 }
480 }
481
482 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
483 // X - (gep X, ...)
484 if (RHSGEP->getOperand(0) == LHS) {
485 GEP = RHSGEP;
486 Swapped = true;
487 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
488 // (ce_gep X, ...) - (gep X, ...)
489 if (CE->getOpcode() == Instruction::GetElementPtr &&
490 RHSGEP->getOperand(0) == CE->getOperand(0)) {
491 CstGEP = CE;
492 GEP = RHSGEP;
493 Swapped = true;
494 }
495 }
496 }
497
498 if (GEP == 0)
499 return 0;
500
501 // Emit the offset of the GEP and an intptr_t.
502 Value *Result = EmitGEPOffset(GEP);
503
504 // If we had a constant expression GEP on the other side offsetting the
505 // pointer, subtract it from the offset we have.
506 if (CstGEP) {
507 Value *CstOffset = EmitGEPOffset(CstGEP);
508 Result = Builder->CreateSub(Result, CstOffset);
509 }
510
511
512 // If we have p - gep(p, ...) then we have to negate the result.
513 if (Swapped)
514 Result = Builder->CreateNeg(Result, "diff.neg");
515
516 return Builder->CreateIntCast(Result, Ty, true);
517}
518
519
520Instruction *InstCombiner::visitSub(BinaryOperator &I) {
521 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
522
Duncan Sandsfea3b212010-12-15 14:07:39 +0000523 if (Value *V = SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(),
524 I.hasNoUnsignedWrap(), TD))
525 return ReplaceInstUsesWith(I, V);
Chris Lattner53a19b72010-01-05 07:18:46 +0000526
Duncan Sands37bf92b2010-12-22 13:36:08 +0000527 // (A*B)-(A*C) -> A*(B-C) etc
528 if (Value *V = SimplifyUsingDistributiveLaws(I))
529 return ReplaceInstUsesWith(I, V);
530
Chris Lattner53a19b72010-01-05 07:18:46 +0000531 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
532 if (Value *V = dyn_castNegVal(Op1)) {
533 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
534 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
535 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
536 return Res;
537 }
538
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000539 if (I.getType()->isIntegerTy(1))
Chris Lattner53a19b72010-01-05 07:18:46 +0000540 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattnerb9b90442011-02-10 05:14:58 +0000541
542 // Replace (-1 - A) with (~A).
543 if (match(Op0, m_AllOnes()))
544 return BinaryOperator::CreateNot(Op1);
Chris Lattner53a19b72010-01-05 07:18:46 +0000545
546 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner53a19b72010-01-05 07:18:46 +0000547 // C - ~X == X + (1+C)
548 Value *X = 0;
549 if (match(Op1, m_Not(m_Value(X))))
550 return BinaryOperator::CreateAdd(X, AddOne(C));
551
552 // -(X >>u 31) -> (X >>s 31)
553 // -(X >>s 31) -> (X >>u 31)
554 if (C->isZero()) {
Chris Lattnerb9b90442011-02-10 05:14:58 +0000555 Value *X; ConstantInt *CI;
556 if (match(Op1, m_LShr(m_Value(X), m_ConstantInt(CI))) &&
557 // Verify we are shifting out everything but the sign bit.
558 CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
559 return BinaryOperator::CreateAShr(X, CI);
560
561 if (match(Op1, m_AShr(m_Value(X), m_ConstantInt(CI))) &&
562 // Verify we are shifting out everything but the sign bit.
563 CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
564 return BinaryOperator::CreateLShr(X, CI);
Chris Lattner53a19b72010-01-05 07:18:46 +0000565 }
566
567 // Try to fold constant sub into select arguments.
568 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
569 if (Instruction *R = FoldOpIntoSelect(I, SI))
570 return R;
571
572 // C - zext(bool) -> bool ? C - 1 : C
573 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Chris Lattnerb9b90442011-02-10 05:14:58 +0000574 if (ZI->getSrcTy()->isIntegerTy(1))
Chris Lattner53a19b72010-01-05 07:18:46 +0000575 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerb9b90442011-02-10 05:14:58 +0000576
577 // C-(X+C2) --> (C-C2)-X
578 ConstantInt *C2;
579 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(C2))))
580 return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
Chris Lattner53a19b72010-01-05 07:18:46 +0000581 }
582
Chris Lattnerb9b90442011-02-10 05:14:58 +0000583
584 { Value *Y;
585 // X-(X+Y) == -Y X-(Y+X) == -Y
586 if (match(Op1, m_Add(m_Specific(Op0), m_Value(Y))) ||
587 match(Op1, m_Add(m_Value(Y), m_Specific(Op0))))
588 return BinaryOperator::CreateNeg(Y);
589
590 // (X-Y)-X == -Y
591 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
592 return BinaryOperator::CreateNeg(Y);
593 }
594
595 if (Op1->hasOneUse()) {
596 Value *X = 0, *Y = 0, *Z = 0;
597 Constant *C = 0;
598 ConstantInt *CI = 0;
599
600 // (X - (Y - Z)) --> (X + (Z - Y)).
601 if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
602 return BinaryOperator::CreateAdd(Op0,
603 Builder->CreateSub(Z, Y, Op1->getName()));
604
605 // (X - (X & Y)) --> (X & ~Y)
606 //
607 if (match(Op1, m_And(m_Value(Y), m_Specific(Op0))) ||
608 match(Op1, m_And(m_Specific(Op0), m_Value(Y))))
609 return BinaryOperator::CreateAnd(Op0,
610 Builder->CreateNot(Y, Y->getName() + ".not"));
611
612 // 0 - (X sdiv C) -> (X sdiv -C)
613 if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) &&
614 match(Op0, m_Zero()))
615 return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
616
617 // 0 - (X << Y) -> (-X << Y) when X is freely negatable.
618 if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
619 if (Value *XNeg = dyn_castNegVal(X))
620 return BinaryOperator::CreateShl(XNeg, Y);
621
622 // X - X*C --> X * (1-C)
623 if (match(Op1, m_Mul(m_Specific(Op0), m_ConstantInt(CI)))) {
624 Constant *CP1 = ConstantExpr::getSub(ConstantInt::get(I.getType(),1), CI);
625 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattner53a19b72010-01-05 07:18:46 +0000626 }
627
Chris Lattnerb9b90442011-02-10 05:14:58 +0000628 // X - X<<C --> X * (1-(1<<C))
629 if (match(Op1, m_Shl(m_Specific(Op0), m_ConstantInt(CI)))) {
630 Constant *One = ConstantInt::get(I.getType(), 1);
631 C = ConstantExpr::getSub(One, ConstantExpr::getShl(One, CI));
632 return BinaryOperator::CreateMul(Op0, C);
633 }
634
635 // X - A*-B -> X + A*B
636 // X - -A*B -> X + A*B
637 Value *A, *B;
638 if (match(Op1, m_Mul(m_Value(A), m_Neg(m_Value(B)))) ||
639 match(Op1, m_Mul(m_Neg(m_Value(A)), m_Value(B))))
640 return BinaryOperator::CreateAdd(Op0, Builder->CreateMul(A, B));
Chris Lattner67920322011-01-15 05:50:18 +0000641
Chris Lattnerb9b90442011-02-10 05:14:58 +0000642 // X - A*CI -> X + A*-CI
643 // X - CI*A -> X + A*-CI
644 if (match(Op1, m_Mul(m_Value(A), m_ConstantInt(CI))) ||
645 match(Op1, m_Mul(m_ConstantInt(CI), m_Value(A)))) {
646 Value *NewMul = Builder->CreateMul(A, ConstantExpr::getNeg(CI));
647 return BinaryOperator::CreateAdd(Op0, NewMul);
Chris Lattner53a19b72010-01-05 07:18:46 +0000648 }
649 }
650
651 ConstantInt *C1;
652 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
653 if (X == Op1) // X*C - X --> X * (C-1)
654 return BinaryOperator::CreateMul(Op1, SubOne(C1));
655
656 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
657 if (X == dyn_castFoldableMul(Op1, C2))
658 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
659 }
660
661 // Optimize pointer differences into the same array into a size. Consider:
662 // &A[10] - &A[0]: we should compile this to "10".
663 if (TD) {
664 Value *LHSOp, *RHSOp;
665 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
666 match(Op1, m_PtrToInt(m_Value(RHSOp))))
667 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
668 return ReplaceInstUsesWith(I, Res);
669
670 // trunc(p)-trunc(q) -> trunc(p-q)
671 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
672 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
673 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
674 return ReplaceInstUsesWith(I, Res);
675 }
676
677 return 0;
678}
679
680Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
681 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
682
683 // If this is a 'B = x-(-A)', change to B = x+A...
684 if (Value *V = dyn_castFNegVal(Op1))
685 return BinaryOperator::CreateFAdd(Op0, V);
686
Chris Lattner53a19b72010-01-05 07:18:46 +0000687 return 0;
688}