blob: 85fa7c0d4fc458f4ed4a3423852f8d9954df9053 [file] [log] [blame]
Eugene Zelenkoffec81c2015-11-04 22:32:32 +00001//===- InstCombineAddSub.cpp ------------------------------------*- C++ -*-===//
Chris Lattner82aa8882010-01-05 07:18:46 +00002//
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
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Craig Topper58713212013-07-15 04:27:47 +000015#include "llvm/ADT/STLExtras.h"
Chris Lattner82aa8882010-01-05 07:18:46 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/DataLayout.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000018#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000019#include "llvm/IR/PatternMatch.h"
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000020
Chris Lattner82aa8882010-01-05 07:18:46 +000021using namespace llvm;
22using namespace PatternMatch;
23
Chandler Carruth964daaa2014-04-22 02:55:47 +000024#define DEBUG_TYPE "instcombine"
25
Shuxin Yang37a1efe2012-12-18 23:10:12 +000026namespace {
27
28 /// Class representing coefficient of floating-point addend.
29 /// This class needs to be highly efficient, which is especially true for
30 /// the constructor. As of I write this comment, the cost of the default
Jim Grosbachbdbd7342013-04-05 21:20:12 +000031 /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
Shuxin Yang37a1efe2012-12-18 23:10:12 +000032 /// perform write-merging).
Jim Grosbachbdbd7342013-04-05 21:20:12 +000033 ///
Shuxin Yang37a1efe2012-12-18 23:10:12 +000034 class FAddendCoef {
35 public:
Suyog Sardade409fd2014-07-17 06:09:34 +000036 // The constructor has to initialize a APFloat, which is unnecessary for
Shuxin Yang37a1efe2012-12-18 23:10:12 +000037 // most addends which have coefficient either 1 or -1. So, the constructor
38 // is expensive. In order to avoid the cost of the constructor, we should
39 // reuse some instances whenever possible. The pre-created instances
40 // FAddCombine::Add[0-5] embodies this idea.
41 //
42 FAddendCoef() : IsFp(false), BufHasFpVal(false), IntVal(0) {}
43 ~FAddendCoef();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000044
Shuxin Yang37a1efe2012-12-18 23:10:12 +000045 void set(short C) {
46 assert(!insaneIntVal(C) && "Insane coefficient");
47 IsFp = false; IntVal = C;
48 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000049
Shuxin Yang37a1efe2012-12-18 23:10:12 +000050 void set(const APFloat& C);
Shuxin Yang389ed4b2013-03-25 20:43:41 +000051
Shuxin Yang37a1efe2012-12-18 23:10:12 +000052 void negate();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000053
Shuxin Yang37a1efe2012-12-18 23:10:12 +000054 bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
55 Value *getValue(Type *) const;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000056
Shuxin Yang37a1efe2012-12-18 23:10:12 +000057 // If possible, don't define operator+/operator- etc because these
58 // operators inevitably call FAddendCoef's constructor which is not cheap.
59 void operator=(const FAddendCoef &A);
60 void operator+=(const FAddendCoef &A);
Shuxin Yang37a1efe2012-12-18 23:10:12 +000061 void operator*=(const FAddendCoef &S);
Jim Grosbachbdbd7342013-04-05 21:20:12 +000062
Shuxin Yang37a1efe2012-12-18 23:10:12 +000063 bool isOne() const { return isInt() && IntVal == 1; }
64 bool isTwo() const { return isInt() && IntVal == 2; }
65 bool isMinusOne() const { return isInt() && IntVal == -1; }
66 bool isMinusTwo() const { return isInt() && IntVal == -2; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000067
Shuxin Yang37a1efe2012-12-18 23:10:12 +000068 private:
69 bool insaneIntVal(int V) { return V > 4 || V < -4; }
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000070 APFloat *getFpValPtr()
Shuxin Yang5b841c42012-12-19 01:10:17 +000071 { return reinterpret_cast<APFloat*>(&FpValBuf.buffer[0]); }
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000072 const APFloat *getFpValPtr() const
David Greene530430b2013-01-14 21:04:40 +000073 { return reinterpret_cast<const APFloat*>(&FpValBuf.buffer[0]); }
Shuxin Yang37a1efe2012-12-18 23:10:12 +000074
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000075 const APFloat &getFpVal() const {
Shuxin Yang37a1efe2012-12-18 23:10:12 +000076 assert(IsFp && BufHasFpVal && "Incorret state");
David Greene530430b2013-01-14 21:04:40 +000077 return *getFpValPtr();
Shuxin Yang37a1efe2012-12-18 23:10:12 +000078 }
79
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000080 APFloat &getFpVal() {
Jim Grosbachbdbd7342013-04-05 21:20:12 +000081 assert(IsFp && BufHasFpVal && "Incorret state");
82 return *getFpValPtr();
83 }
84
Shuxin Yang37a1efe2012-12-18 23:10:12 +000085 bool isInt() const { return !IsFp; }
86
Shuxin Yang389ed4b2013-03-25 20:43:41 +000087 // If the coefficient is represented by an integer, promote it to a
Jim Grosbachbdbd7342013-04-05 21:20:12 +000088 // floating point.
Shuxin Yang389ed4b2013-03-25 20:43:41 +000089 void convertToFpType(const fltSemantics &Sem);
90
91 // Construct an APFloat from a signed integer.
92 // TODO: We should get rid of this function when APFloat can be constructed
Jim Grosbachbdbd7342013-04-05 21:20:12 +000093 // from an *SIGNED* integer.
Shuxin Yang389ed4b2013-03-25 20:43:41 +000094 APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
Shuxin Yang5b841c42012-12-19 01:10:17 +000095
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000096 private:
Shuxin Yang37a1efe2012-12-18 23:10:12 +000097 bool IsFp;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000098
Shuxin Yang37a1efe2012-12-18 23:10:12 +000099 // True iff FpValBuf contains an instance of APFloat.
100 bool BufHasFpVal;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000101
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000102 // The integer coefficient of an individual addend is either 1 or -1,
103 // and we try to simplify at most 4 addends from neighboring at most
104 // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
105 // is overkill of this end.
106 short IntVal;
Shuxin Yang5b841c42012-12-19 01:10:17 +0000107
108 AlignedCharArrayUnion<APFloat> FpValBuf;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000109 };
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000110
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000111 /// FAddend is used to represent floating-point addend. An addend is
112 /// represented as <C, V>, where the V is a symbolic value, and C is a
113 /// constant coefficient. A constant addend is represented as <C, 0>.
114 ///
115 class FAddend {
116 public:
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000117 FAddend() : Val(nullptr) {}
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000118
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000119 Value *getSymVal() const { return Val; }
120 const FAddendCoef &getCoef() const { return Coeff; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000121
Craig Topperf40110f2014-04-25 05:29:35 +0000122 bool isConstant() const { return Val == nullptr; }
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000123 bool isZero() const { return Coeff.isZero(); }
124
Richard Trieu7a083812016-02-18 22:09:30 +0000125 void set(short Coefficient, Value *V) {
126 Coeff.set(Coefficient);
127 Val = V;
128 }
129 void set(const APFloat &Coefficient, Value *V) {
130 Coeff.set(Coefficient);
131 Val = V;
132 }
133 void set(const ConstantFP *Coefficient, Value *V) {
134 Coeff.set(Coefficient->getValueAPF());
135 Val = V;
136 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000137
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000138 void negate() { Coeff.negate(); }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000139
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000140 /// Drill down the U-D chain one step to find the definition of V, and
141 /// try to break the definition into one or two addends.
142 static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000143
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000144 /// Similar to FAddend::drillDownOneStep() except that the value being
145 /// splitted is the addend itself.
146 unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000147
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000148 void operator+=(const FAddend &T) {
149 assert((Val == T.Val) && "Symbolic-values disagree");
150 Coeff += T.Coeff;
151 }
152
153 private:
154 void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000155
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000156 // This addend has the value of "Coeff * Val".
157 Value *Val;
158 FAddendCoef Coeff;
159 };
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000160
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000161 /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
162 /// with its neighboring at most two instructions.
163 ///
164 class FAddCombine {
165 public:
Craig Topperf40110f2014-04-25 05:29:35 +0000166 FAddCombine(InstCombiner::BuilderTy *B) : Builder(B), Instr(nullptr) {}
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000167 Value *simplify(Instruction *FAdd);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000168
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000169 private:
170 typedef SmallVector<const FAddend*, 4> AddendVect;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000171
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000172 Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000173
174 Value *performFactorization(Instruction *I);
175
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000176 /// Convert given addend to a Value
177 Value *createAddendVal(const FAddend &A, bool& NeedNeg);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000178
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000179 /// Return the number of instructions needed to emit the N-ary addition.
180 unsigned calcInstrNumber(const AddendVect& Vect);
181 Value *createFSub(Value *Opnd0, Value *Opnd1);
182 Value *createFAdd(Value *Opnd0, Value *Opnd1);
183 Value *createFMul(Value *Opnd0, Value *Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000184 Value *createFDiv(Value *Opnd0, Value *Opnd1);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000185 Value *createFNeg(Value *V);
186 Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
Owen Anderson1664dc82014-01-20 07:44:53 +0000187 void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000188
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000189 InstCombiner::BuilderTy *Builder;
190 Instruction *Instr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000191
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000192 // Debugging stuff are clustered here.
193 #ifndef NDEBUG
194 unsigned CreateInstrNum;
195 void initCreateInstNum() { CreateInstrNum = 0; }
196 void incCreateInstNum() { CreateInstrNum++; }
197 #else
198 void initCreateInstNum() {}
199 void incCreateInstNum() {}
200 #endif
201 };
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000202
203} // anonymous namespace
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000204
205//===----------------------------------------------------------------------===//
206//
207// Implementation of
208// {FAddendCoef, FAddend, FAddition, FAddCombine}.
209//
210//===----------------------------------------------------------------------===//
211FAddendCoef::~FAddendCoef() {
212 if (BufHasFpVal)
213 getFpValPtr()->~APFloat();
214}
215
216void FAddendCoef::set(const APFloat& C) {
217 APFloat *P = getFpValPtr();
218
219 if (isInt()) {
220 // As the buffer is meanless byte stream, we cannot call
221 // APFloat::operator=().
222 new(P) APFloat(C);
223 } else
224 *P = C;
225
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000226 IsFp = BufHasFpVal = true;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000227}
228
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000229void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
230 if (!isInt())
231 return;
232
233 APFloat *P = getFpValPtr();
234 if (IntVal > 0)
235 new(P) APFloat(Sem, IntVal);
236 else {
237 new(P) APFloat(Sem, 0 - IntVal);
238 P->changeSign();
239 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000240 IsFp = BufHasFpVal = true;
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000241}
242
243APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
244 if (Val >= 0)
245 return APFloat(Sem, Val);
246
247 APFloat T(Sem, 0 - Val);
248 T.changeSign();
249
250 return T;
251}
252
253void FAddendCoef::operator=(const FAddendCoef &That) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000254 if (That.isInt())
255 set(That.IntVal);
256 else
257 set(That.getFpVal());
258}
259
260void FAddendCoef::operator+=(const FAddendCoef &That) {
261 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
262 if (isInt() == That.isInt()) {
263 if (isInt())
264 IntVal += That.IntVal;
265 else
266 getFpVal().add(That.getFpVal(), RndMode);
267 return;
268 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000269
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000270 if (isInt()) {
271 const APFloat &T = That.getFpVal();
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000272 convertToFpType(T.getSemantics());
273 getFpVal().add(T, RndMode);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000274 return;
275 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000276
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000277 APFloat &T = getFpVal();
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000278 T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000279}
280
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000281void FAddendCoef::operator*=(const FAddendCoef &That) {
282 if (That.isOne())
283 return;
284
285 if (That.isMinusOne()) {
286 negate();
287 return;
288 }
289
290 if (isInt() && That.isInt()) {
291 int Res = IntVal * (int)That.IntVal;
292 assert(!insaneIntVal(Res) && "Insane int value");
293 IntVal = Res;
294 return;
295 }
296
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000297 const fltSemantics &Semantic =
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000298 isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
299
300 if (isInt())
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000301 convertToFpType(Semantic);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000302 APFloat &F0 = getFpVal();
303
304 if (That.isInt())
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000305 F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
306 APFloat::rmNearestTiesToEven);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000307 else
308 F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000309}
310
311void FAddendCoef::negate() {
312 if (isInt())
313 IntVal = 0 - IntVal;
314 else
315 getFpVal().changeSign();
316}
317
318Value *FAddendCoef::getValue(Type *Ty) const {
319 return isInt() ?
320 ConstantFP::get(Ty, float(IntVal)) :
321 ConstantFP::get(Ty->getContext(), getFpVal());
322}
323
324// The definition of <Val> Addends
325// =========================================
326// A + B <1, A>, <1,B>
327// A - B <1, A>, <1,B>
328// 0 - B <-1, B>
329// C * A, <C, A>
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000330// A + C <1, A> <C, NULL>
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000331// 0 +/- 0 <0, NULL> (corner case)
332//
333// Legend: A and B are not constant, C is constant
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000334//
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000335unsigned FAddend::drillValueDownOneStep
336 (Value *Val, FAddend &Addend0, FAddend &Addend1) {
Craig Topperf40110f2014-04-25 05:29:35 +0000337 Instruction *I = nullptr;
338 if (!Val || !(I = dyn_cast<Instruction>(Val)))
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000339 return 0;
340
341 unsigned Opcode = I->getOpcode();
342
343 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
344 ConstantFP *C0, *C1;
345 Value *Opnd0 = I->getOperand(0);
346 Value *Opnd1 = I->getOperand(1);
347 if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +0000348 Opnd0 = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000349
350 if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +0000351 Opnd1 = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000352
353 if (Opnd0) {
354 if (!C0)
355 Addend0.set(1, Opnd0);
356 else
Craig Topperf40110f2014-04-25 05:29:35 +0000357 Addend0.set(C0, nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000358 }
359
360 if (Opnd1) {
361 FAddend &Addend = Opnd0 ? Addend1 : Addend0;
362 if (!C1)
363 Addend.set(1, Opnd1);
364 else
Craig Topperf40110f2014-04-25 05:29:35 +0000365 Addend.set(C1, nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000366 if (Opcode == Instruction::FSub)
367 Addend.negate();
368 }
369
370 if (Opnd0 || Opnd1)
371 return Opnd0 && Opnd1 ? 2 : 1;
372
373 // Both operands are zero. Weird!
Craig Topperf40110f2014-04-25 05:29:35 +0000374 Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000375 return 1;
376 }
377
378 if (I->getOpcode() == Instruction::FMul) {
379 Value *V0 = I->getOperand(0);
380 Value *V1 = I->getOperand(1);
381 if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
382 Addend0.set(C, V1);
383 return 1;
384 }
385
386 if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
387 Addend0.set(C, V0);
388 return 1;
389 }
390 }
391
392 return 0;
393}
394
395// Try to break *this* addend into two addends. e.g. Suppose this addend is
396// <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
397// i.e. <2.3, X> and <2.3, Y>.
398//
399unsigned FAddend::drillAddendDownOneStep
400 (FAddend &Addend0, FAddend &Addend1) const {
401 if (isConstant())
402 return 0;
403
404 unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000405 if (!BreakNum || Coeff.isOne())
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000406 return BreakNum;
407
408 Addend0.Scale(Coeff);
409
410 if (BreakNum == 2)
411 Addend1.Scale(Coeff);
412
413 return BreakNum;
414}
415
Shuxin Yang2eca6022013-03-14 18:08:26 +0000416// Try to perform following optimization on the input instruction I. Return the
417// simplified expression if was successful; otherwise, return 0.
418//
419// Instruction "I" is Simplified into
420// -------------------------------------------------------
421// (x * y) +/- (x * z) x * (y +/- z)
422// (y / x) +/- (z / x) (y +/- z) / x
423//
424Value *FAddCombine::performFactorization(Instruction *I) {
425 assert((I->getOpcode() == Instruction::FAdd ||
426 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000427
Shuxin Yang2eca6022013-03-14 18:08:26 +0000428 Instruction *I0 = dyn_cast<Instruction>(I->getOperand(0));
429 Instruction *I1 = dyn_cast<Instruction>(I->getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000430
Shuxin Yang2eca6022013-03-14 18:08:26 +0000431 if (!I0 || !I1 || I0->getOpcode() != I1->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +0000432 return nullptr;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000433
434 bool isMpy = false;
435 if (I0->getOpcode() == Instruction::FMul)
436 isMpy = true;
437 else if (I0->getOpcode() != Instruction::FDiv)
Craig Topperf40110f2014-04-25 05:29:35 +0000438 return nullptr;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000439
440 Value *Opnd0_0 = I0->getOperand(0);
441 Value *Opnd0_1 = I0->getOperand(1);
442 Value *Opnd1_0 = I1->getOperand(0);
443 Value *Opnd1_1 = I1->getOperand(1);
444
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000445 // Input Instr I Factor AddSub0 AddSub1
Shuxin Yang2eca6022013-03-14 18:08:26 +0000446 // ----------------------------------------------
447 // (x*y) +/- (x*z) x y z
448 // (y/x) +/- (z/x) x y z
449 //
Craig Topperf40110f2014-04-25 05:29:35 +0000450 Value *Factor = nullptr;
451 Value *AddSub0 = nullptr, *AddSub1 = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000452
Shuxin Yang2eca6022013-03-14 18:08:26 +0000453 if (isMpy) {
454 if (Opnd0_0 == Opnd1_0 || Opnd0_0 == Opnd1_1)
455 Factor = Opnd0_0;
456 else if (Opnd0_1 == Opnd1_0 || Opnd0_1 == Opnd1_1)
457 Factor = Opnd0_1;
458
459 if (Factor) {
460 AddSub0 = (Factor == Opnd0_0) ? Opnd0_1 : Opnd0_0;
461 AddSub1 = (Factor == Opnd1_0) ? Opnd1_1 : Opnd1_0;
462 }
463 } else if (Opnd0_1 == Opnd1_1) {
464 Factor = Opnd0_1;
465 AddSub0 = Opnd0_0;
466 AddSub1 = Opnd1_0;
467 }
468
469 if (!Factor)
Craig Topperf40110f2014-04-25 05:29:35 +0000470 return nullptr;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000471
Owen Anderson1664dc82014-01-20 07:44:53 +0000472 FastMathFlags Flags;
473 Flags.setUnsafeAlgebra();
474 if (I0) Flags &= I->getFastMathFlags();
475 if (I1) Flags &= I->getFastMathFlags();
476
Shuxin Yang2eca6022013-03-14 18:08:26 +0000477 // Create expression "NewAddSub = AddSub0 +/- AddsSub1"
478 Value *NewAddSub = (I->getOpcode() == Instruction::FAdd) ?
479 createFAdd(AddSub0, AddSub1) :
480 createFSub(AddSub0, AddSub1);
481 if (ConstantFP *CFP = dyn_cast<ConstantFP>(NewAddSub)) {
482 const APFloat &F = CFP->getValueAPF();
Michael Gottesmanc2af8d62013-06-26 23:17:31 +0000483 if (!F.isNormal())
Craig Topperf40110f2014-04-25 05:29:35 +0000484 return nullptr;
Owen Anderson1664dc82014-01-20 07:44:53 +0000485 } else if (Instruction *II = dyn_cast<Instruction>(NewAddSub))
486 II->setFastMathFlags(Flags);
487
488 if (isMpy) {
489 Value *RI = createFMul(Factor, NewAddSub);
490 if (Instruction *II = dyn_cast<Instruction>(RI))
491 II->setFastMathFlags(Flags);
492 return RI;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000493 }
494
Owen Anderson1664dc82014-01-20 07:44:53 +0000495 Value *RI = createFDiv(NewAddSub, Factor);
496 if (Instruction *II = dyn_cast<Instruction>(RI))
497 II->setFastMathFlags(Flags);
498 return RI;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000499}
500
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000501Value *FAddCombine::simplify(Instruction *I) {
502 assert(I->hasUnsafeAlgebra() && "Should be in unsafe mode");
503
504 // Currently we are not able to handle vector type.
505 if (I->getType()->isVectorTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000506 return nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000507
508 assert((I->getOpcode() == Instruction::FAdd ||
509 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
510
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000511 // Save the instruction before calling other member-functions.
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000512 Instr = I;
513
514 FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
515
516 unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
517
518 // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
519 unsigned Opnd0_ExpNum = 0;
520 unsigned Opnd1_ExpNum = 0;
521
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000522 if (!Opnd0.isConstant())
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000523 Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
524
525 // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
526 if (OpndNum == 2 && !Opnd1.isConstant())
527 Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
528
529 // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
530 if (Opnd0_ExpNum && Opnd1_ExpNum) {
531 AddendVect AllOpnds;
532 AllOpnds.push_back(&Opnd0_0);
533 AllOpnds.push_back(&Opnd1_0);
534 if (Opnd0_ExpNum == 2)
535 AllOpnds.push_back(&Opnd0_1);
536 if (Opnd1_ExpNum == 2)
537 AllOpnds.push_back(&Opnd1_1);
538
539 // Compute instruction quota. We should save at least one instruction.
540 unsigned InstQuota = 0;
541
542 Value *V0 = I->getOperand(0);
543 Value *V1 = I->getOperand(1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000544 InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000545 (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
546
547 if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
548 return R;
549 }
550
551 if (OpndNum != 2) {
552 // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
553 // splitted into two addends, say "V = X - Y", the instruction would have
554 // been optimized into "I = Y - X" in the previous steps.
555 //
556 const FAddendCoef &CE = Opnd0.getCoef();
Craig Topperf40110f2014-04-25 05:29:35 +0000557 return CE.isOne() ? Opnd0.getSymVal() : nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000558 }
559
560 // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
561 if (Opnd1_ExpNum) {
562 AddendVect AllOpnds;
563 AllOpnds.push_back(&Opnd0);
564 AllOpnds.push_back(&Opnd1_0);
565 if (Opnd1_ExpNum == 2)
566 AllOpnds.push_back(&Opnd1_1);
567
568 if (Value *R = simplifyFAdd(AllOpnds, 1))
569 return R;
570 }
571
572 // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
573 if (Opnd0_ExpNum) {
574 AddendVect AllOpnds;
575 AllOpnds.push_back(&Opnd1);
576 AllOpnds.push_back(&Opnd0_0);
577 if (Opnd0_ExpNum == 2)
578 AllOpnds.push_back(&Opnd0_1);
579
580 if (Value *R = simplifyFAdd(AllOpnds, 1))
581 return R;
582 }
583
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000584 // step 6: Try factorization as the last resort,
Shuxin Yang2eca6022013-03-14 18:08:26 +0000585 return performFactorization(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000586}
587
588Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000589 unsigned AddendNum = Addends.size();
590 assert(AddendNum <= 4 && "Too many addends");
591
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000592 // For saving intermediate results;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000593 unsigned NextTmpIdx = 0;
594 FAddend TmpResult[3];
595
596 // Points to the constant addend of the resulting simplified expression.
597 // If the resulting expr has constant-addend, this constant-addend is
598 // desirable to reside at the top of the resulting expression tree. Placing
599 // constant close to supper-expr(s) will potentially reveal some optimization
600 // opportunities in super-expr(s).
601 //
Craig Topperf40110f2014-04-25 05:29:35 +0000602 const FAddend *ConstAdd = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000603
604 // Simplified addends are placed <SimpVect>.
605 AddendVect SimpVect;
606
607 // The outer loop works on one symbolic-value at a time. Suppose the input
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000608 // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000609 // The symbolic-values will be processed in this order: x, y, z.
610 //
611 for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
612
613 const FAddend *ThisAddend = Addends[SymIdx];
614 if (!ThisAddend) {
615 // This addend was processed before.
616 continue;
617 }
618
619 Value *Val = ThisAddend->getSymVal();
620 unsigned StartIdx = SimpVect.size();
621 SimpVect.push_back(ThisAddend);
622
623 // The inner loop collects addends sharing same symbolic-value, and these
624 // addends will be later on folded into a single addend. Following above
625 // example, if the symbolic value "y" is being processed, the inner loop
626 // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
627 // be later on folded into "<b1+b2, y>".
628 //
629 for (unsigned SameSymIdx = SymIdx + 1;
630 SameSymIdx < AddendNum; SameSymIdx++) {
631 const FAddend *T = Addends[SameSymIdx];
632 if (T && T->getSymVal() == Val) {
633 // Set null such that next iteration of the outer loop will not process
634 // this addend again.
Craig Topperf40110f2014-04-25 05:29:35 +0000635 Addends[SameSymIdx] = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000636 SimpVect.push_back(T);
637 }
638 }
639
640 // If multiple addends share same symbolic value, fold them together.
641 if (StartIdx + 1 != SimpVect.size()) {
642 FAddend &R = TmpResult[NextTmpIdx ++];
643 R = *SimpVect[StartIdx];
644 for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
645 R += *SimpVect[Idx];
646
647 // Pop all addends being folded and push the resulting folded addend.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000648 SimpVect.resize(StartIdx);
Craig Topperf40110f2014-04-25 05:29:35 +0000649 if (Val) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000650 if (!R.isZero()) {
651 SimpVect.push_back(&R);
652 }
653 } else {
654 // Don't push constant addend at this time. It will be the last element
655 // of <SimpVect>.
656 ConstAdd = &R;
657 }
658 }
659 }
660
Craig Topper58713212013-07-15 04:27:47 +0000661 assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000662 "out-of-bound access");
663
664 if (ConstAdd)
665 SimpVect.push_back(ConstAdd);
666
667 Value *Result;
668 if (!SimpVect.empty())
669 Result = createNaryFAdd(SimpVect, InstrQuota);
670 else {
671 // The addition is folded to 0.0.
672 Result = ConstantFP::get(Instr->getType(), 0.0);
673 }
674
675 return Result;
676}
677
678Value *FAddCombine::createNaryFAdd
679 (const AddendVect &Opnds, unsigned InstrQuota) {
680 assert(!Opnds.empty() && "Expect at least one addend");
681
682 // Step 1: Check if the # of instructions needed exceeds the quota.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000683 //
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000684 unsigned InstrNeeded = calcInstrNumber(Opnds);
685 if (InstrNeeded > InstrQuota)
Craig Topperf40110f2014-04-25 05:29:35 +0000686 return nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000687
688 initCreateInstNum();
689
690 // step 2: Emit the N-ary addition.
691 // Note that at most three instructions are involved in Fadd-InstCombine: the
692 // addition in question, and at most two neighboring instructions.
693 // The resulting optimized addition should have at least one less instruction
694 // than the original addition expression tree. This implies that the resulting
695 // N-ary addition has at most two instructions, and we don't need to worry
696 // about tree-height when constructing the N-ary addition.
697
Craig Topperf40110f2014-04-25 05:29:35 +0000698 Value *LastVal = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000699 bool LastValNeedNeg = false;
700
701 // Iterate the addends, creating fadd/fsub using adjacent two addends.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000702 for (const FAddend *Opnd : Opnds) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000703 bool NeedNeg;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000704 Value *V = createAddendVal(*Opnd, NeedNeg);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000705 if (!LastVal) {
706 LastVal = V;
707 LastValNeedNeg = NeedNeg;
708 continue;
709 }
710
711 if (LastValNeedNeg == NeedNeg) {
712 LastVal = createFAdd(LastVal, V);
713 continue;
714 }
715
716 if (LastValNeedNeg)
717 LastVal = createFSub(V, LastVal);
718 else
719 LastVal = createFSub(LastVal, V);
720
721 LastValNeedNeg = false;
722 }
723
724 if (LastValNeedNeg) {
725 LastVal = createFNeg(LastVal);
726 }
727
728 #ifndef NDEBUG
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000729 assert(CreateInstrNum == InstrNeeded &&
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000730 "Inconsistent in instruction numbers");
731 #endif
732
733 return LastVal;
734}
735
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000736Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000737 Value *V = Builder->CreateFSub(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000738 if (Instruction *I = dyn_cast<Instruction>(V))
739 createInstPostProc(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000740 return V;
741}
742
743Value *FAddCombine::createFNeg(Value *V) {
Sanjay Patelea3c8022014-12-19 16:44:08 +0000744 Value *Zero = cast<Value>(ConstantFP::getZeroValueForNegation(V->getType()));
Owen Anderson1664dc82014-01-20 07:44:53 +0000745 Value *NewV = createFSub(Zero, V);
746 if (Instruction *I = dyn_cast<Instruction>(NewV))
747 createInstPostProc(I, true); // fneg's don't receive instruction numbers.
748 return NewV;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000749}
750
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000751Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000752 Value *V = Builder->CreateFAdd(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000753 if (Instruction *I = dyn_cast<Instruction>(V))
754 createInstPostProc(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000755 return V;
756}
757
758Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
759 Value *V = Builder->CreateFMul(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000760 if (Instruction *I = dyn_cast<Instruction>(V))
761 createInstPostProc(I);
762 return V;
763}
764
765Value *FAddCombine::createFDiv(Value *Opnd0, Value *Opnd1) {
766 Value *V = Builder->CreateFDiv(Opnd0, Opnd1);
767 if (Instruction *I = dyn_cast<Instruction>(V))
768 createInstPostProc(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000769 return V;
770}
771
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000772void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000773 NewInstr->setDebugLoc(Instr->getDebugLoc());
774
775 // Keep track of the number of instruction created.
Owen Anderson1664dc82014-01-20 07:44:53 +0000776 if (!NoNumber)
777 incCreateInstNum();
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000778
779 // Propagate fast-math flags
780 NewInstr->setFastMathFlags(Instr->getFastMathFlags());
781}
782
783// Return the number of instruction needed to emit the N-ary addition.
784// NOTE: Keep this function in sync with createAddendVal().
785unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
786 unsigned OpndNum = Opnds.size();
787 unsigned InstrNeeded = OpndNum - 1;
788
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000789 // The number of addends in the form of "(-1)*x".
790 unsigned NegOpndNum = 0;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000791
792 // Adjust the number of instructions needed to emit the N-ary add.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000793 for (const FAddend *Opnd : Opnds) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000794 if (Opnd->isConstant())
795 continue;
796
797 const FAddendCoef &CE = Opnd->getCoef();
798 if (CE.isMinusOne() || CE.isMinusTwo())
799 NegOpndNum++;
800
801 // Let the addend be "c * x". If "c == +/-1", the value of the addend
802 // is immediately available; otherwise, it needs exactly one instruction
803 // to evaluate the value.
804 if (!CE.isMinusOne() && !CE.isOne())
805 InstrNeeded++;
806 }
807 if (NegOpndNum == OpndNum)
808 InstrNeeded++;
809 return InstrNeeded;
810}
811
812// Input Addend Value NeedNeg(output)
813// ================================================================
814// Constant C C false
815// <+/-1, V> V coefficient is -1
816// <2/-2, V> "fadd V, V" coefficient is -2
817// <C, V> "fmul V, C" false
818//
819// NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000820Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000821 const FAddendCoef &Coeff = Opnd.getCoef();
822
823 if (Opnd.isConstant()) {
824 NeedNeg = false;
825 return Coeff.getValue(Instr->getType());
826 }
827
828 Value *OpndVal = Opnd.getSymVal();
829
830 if (Coeff.isMinusOne() || Coeff.isOne()) {
831 NeedNeg = Coeff.isMinusOne();
832 return OpndVal;
833 }
834
835 if (Coeff.isTwo() || Coeff.isMinusTwo()) {
836 NeedNeg = Coeff.isMinusTwo();
837 return createFAdd(OpndVal, OpndVal);
838 }
839
840 NeedNeg = false;
841 return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
842}
843
Rafael Espindola04c22582014-06-04 15:39:14 +0000844// If one of the operands only has one non-zero bit, and if the other
845// operand has a known-zero bit in a more significant place than it (not
846// including the sign bit) the ripple may go up to and fill the zero, but
847// won't change the sign. For example, (X & ~4) + 1.
848static bool checkRippleForAdd(const APInt &Op0KnownZero,
849 const APInt &Op1KnownZero) {
850 APInt Op1MaybeOne = ~Op1KnownZero;
851 // Make sure that one of the operand has at most one bit set to 1.
852 if (Op1MaybeOne.countPopulation() != 1)
853 return false;
854
855 // Find the most significant known 0 other than the sign bit.
856 int BitWidth = Op0KnownZero.getBitWidth();
857 APInt Op0KnownZeroTemp(Op0KnownZero);
858 Op0KnownZeroTemp.clearBit(BitWidth - 1);
859 int Op0ZeroPosition = BitWidth - Op0KnownZeroTemp.countLeadingZeros() - 1;
860
861 int Op1OnePosition = BitWidth - Op1MaybeOne.countLeadingZeros() - 1;
862 assert(Op1OnePosition >= 0);
863
864 // This also covers the case of no known zero, since in that case
865 // Op0ZeroPosition is -1.
866 return Op0ZeroPosition >= Op1OnePosition;
867}
Chris Lattner82aa8882010-01-05 07:18:46 +0000868
Sanjay Patel6eccf482015-09-09 15:24:36 +0000869/// Return true if we can prove that:
Chris Lattner82aa8882010-01-05 07:18:46 +0000870/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
871/// This basically requires proving that the add in the original type would not
872/// overflow to change the sign bit or have a carry out.
Hal Finkel60db0582014-09-07 18:57:58 +0000873bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000874 Instruction &CxtI) {
Chris Lattner82aa8882010-01-05 07:18:46 +0000875 // There are different heuristics we can use for this. Here are some simple
876 // ones.
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000877
Rafael Espindolad1a2c2d2014-06-02 22:01:04 +0000878 // If LHS and RHS each have at least two sign bits, the addition will look
879 // like
880 //
881 // XX..... +
882 // YY.....
883 //
884 // If the carry into the most significant position is 0, X and Y can't both
885 // be 1 and therefore the carry out of the addition is also 0.
886 //
887 // If the carry into the most significant position is 1, X and Y can't both
888 // be 0 and therefore the carry out of the addition is also 1.
889 //
890 // Since the carry into the most significant position is always equal to
891 // the carry out of the addition, there is no signed overflow.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000892 if (ComputeNumSignBits(LHS, 0, &CxtI) > 1 &&
893 ComputeNumSignBits(RHS, 0, &CxtI) > 1)
Chris Lattner82aa8882010-01-05 07:18:46 +0000894 return true;
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000895
David Majnemer54c2ca22014-12-26 09:10:14 +0000896 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
897 APInt LHSKnownZero(BitWidth, 0);
898 APInt LHSKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000899 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, 0, &CxtI);
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000900
David Majnemer54c2ca22014-12-26 09:10:14 +0000901 APInt RHSKnownZero(BitWidth, 0);
902 APInt RHSKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000903 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, 0, &CxtI);
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000904
David Majnemer54c2ca22014-12-26 09:10:14 +0000905 // Addition of two 2's compliment numbers having opposite signs will never
906 // overflow.
907 if ((LHSKnownOne[BitWidth - 1] && RHSKnownZero[BitWidth - 1]) ||
908 (LHSKnownZero[BitWidth - 1] && RHSKnownOne[BitWidth - 1]))
909 return true;
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000910
David Majnemer54c2ca22014-12-26 09:10:14 +0000911 // Check if carry bit of addition will not cause overflow.
912 if (checkRippleForAdd(LHSKnownZero, RHSKnownZero))
913 return true;
914 if (checkRippleForAdd(RHSKnownZero, LHSKnownZero))
915 return true;
916
Chris Lattner82aa8882010-01-05 07:18:46 +0000917 return false;
918}
919
David Majnemer57d5bc82014-08-19 23:36:30 +0000920/// \brief Return true if we can prove that:
921/// (sub LHS, RHS) === (sub nsw LHS, RHS)
922/// This basically requires proving that the add in the original type would not
923/// overflow to change the sign bit or have a carry out.
924/// TODO: Handle this for Vectors.
Hal Finkel60db0582014-09-07 18:57:58 +0000925bool InstCombiner::WillNotOverflowSignedSub(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000926 Instruction &CxtI) {
David Majnemer57d5bc82014-08-19 23:36:30 +0000927 // If LHS and RHS each have at least two sign bits, the subtraction
928 // cannot overflow.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000929 if (ComputeNumSignBits(LHS, 0, &CxtI) > 1 &&
930 ComputeNumSignBits(RHS, 0, &CxtI) > 1)
David Majnemer57d5bc82014-08-19 23:36:30 +0000931 return true;
932
David Majnemer54c2ca22014-12-26 09:10:14 +0000933 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
934 APInt LHSKnownZero(BitWidth, 0);
935 APInt LHSKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000936 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, 0, &CxtI);
David Majnemer57d5bc82014-08-19 23:36:30 +0000937
David Majnemer54c2ca22014-12-26 09:10:14 +0000938 APInt RHSKnownZero(BitWidth, 0);
939 APInt RHSKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000940 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, 0, &CxtI);
David Majnemer57d5bc82014-08-19 23:36:30 +0000941
David Majnemer54c2ca22014-12-26 09:10:14 +0000942 // Subtraction of two 2's compliment numbers having identical signs will
943 // never overflow.
944 if ((LHSKnownOne[BitWidth - 1] && RHSKnownOne[BitWidth - 1]) ||
945 (LHSKnownZero[BitWidth - 1] && RHSKnownZero[BitWidth - 1]))
946 return true;
David Majnemer57d5bc82014-08-19 23:36:30 +0000947
David Majnemer54c2ca22014-12-26 09:10:14 +0000948 // TODO: implement logic similar to checkRippleForAdd
David Majnemer57d5bc82014-08-19 23:36:30 +0000949 return false;
950}
951
David Majnemer42158f32014-08-20 07:17:31 +0000952/// \brief Return true if we can prove that:
953/// (sub LHS, RHS) === (sub nuw LHS, RHS)
Hal Finkel60db0582014-09-07 18:57:58 +0000954bool InstCombiner::WillNotOverflowUnsignedSub(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000955 Instruction &CxtI) {
David Majnemer42158f32014-08-20 07:17:31 +0000956 // If the LHS is negative and the RHS is non-negative, no unsigned wrap.
957 bool LHSKnownNonNegative, LHSKnownNegative;
958 bool RHSKnownNonNegative, RHSKnownNegative;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000959 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, /*Depth=*/0,
960 &CxtI);
961 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, /*Depth=*/0,
962 &CxtI);
David Majnemer42158f32014-08-20 07:17:31 +0000963 if (LHSKnownNegative && RHSKnownNonNegative)
964 return true;
965
966 return false;
967}
968
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000969// Checks if any operand is negative and we can convert add to sub.
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000970// This function checks for following negative patterns
971// ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
972// ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
973// XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000974static Value *checkForNegativeOperand(BinaryOperator &I,
975 InstCombiner::BuilderTy *Builder) {
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000976 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000977
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000978 // This function creates 2 instructions to replace ADD, we need at least one
979 // of LHS or RHS to have one use to ensure benefit in transform.
980 if (!LHS->hasOneUse() && !RHS->hasOneUse())
981 return nullptr;
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000982
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000983 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
984 const APInt *C1 = nullptr, *C2 = nullptr;
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000985
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000986 // if ONE is on other side, swap
987 if (match(RHS, m_Add(m_Value(X), m_One())))
988 std::swap(LHS, RHS);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000989
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000990 if (match(LHS, m_Add(m_Value(X), m_One()))) {
991 // if XOR on other side, swap
992 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
993 std::swap(X, RHS);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000994
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000995 if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
996 // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
997 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
998 if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
999 Value *NewAnd = Builder->CreateAnd(Z, *C1);
1000 return Builder->CreateSub(RHS, NewAnd, "sub");
1001 } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
1002 // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
1003 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
1004 Value *NewOr = Builder->CreateOr(Z, ~(*C1));
1005 return Builder->CreateSub(RHS, NewOr, "sub");
1006 }
1007 }
1008 }
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001009
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001010 // Restore LHS and RHS
1011 LHS = I.getOperand(0);
1012 RHS = I.getOperand(1);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001013
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001014 // if XOR is on other side, swap
1015 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
1016 std::swap(LHS, RHS);
1017
1018 // C2 is ODD
1019 // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
1020 // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
1021 if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
1022 if (C1->countTrailingZeros() == 0)
1023 if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
1024 Value *NewOr = Builder->CreateOr(Z, ~(*C2));
1025 return Builder->CreateSub(RHS, NewOr, "sub");
1026 }
1027 return nullptr;
1028}
1029
1030Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001031 bool Changed = SimplifyAssociativeOrCommutative(I);
1032 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Jingyue Wu33bd53d2014-06-17 00:42:07 +00001033
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001034 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001035 return replaceInstUsesWith(I, V);
Chris Lattner82aa8882010-01-05 07:18:46 +00001036
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001037 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
Justin Bogner99798402016-08-05 01:06:44 +00001038 I.hasNoUnsignedWrap(), DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001039 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001040
Dinesh Dwivedia71617352014-06-26 05:40:22 +00001041 // (A*B)+(A*C) -> A*(B+C) etc
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001042 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001043 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001044
Sanjay Patel79acd2a2016-07-16 18:29:26 +00001045 const APInt *Val;
1046 if (match(RHS, m_APInt(Val))) {
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001047 // X + (signbit) --> X ^ signbit
Sanjay Patel79acd2a2016-07-16 18:29:26 +00001048 if (Val->isSignBit())
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001049 return BinaryOperator::CreateXor(LHS, RHS);
Sanjay Patel2d477e592016-07-19 22:09:34 +00001050
1051 // Is this add the last step in a convoluted sext?
1052 Value *X;
1053 const APInt *C;
1054 if (match(LHS, m_ZExt(m_Xor(m_Value(X), m_APInt(C)))) &&
1055 C->isMinSignedValue() &&
1056 C->sext(LHS->getType()->getScalarSizeInBits()) == *Val) {
1057 // add(zext(xor i16 X, -32768), -32768) --> sext X
1058 return CastInst::Create(Instruction::SExt, X, LHS->getType());
1059 }
Sanjay Patel79acd2a2016-07-16 18:29:26 +00001060 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001061
Sanjay Patel79acd2a2016-07-16 18:29:26 +00001062 // FIXME: Use the match above instead of dyn_cast to allow these transforms
1063 // for splat vectors.
1064 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001065 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1066 // (X & 254)+1 -> (X&254)|1
1067 if (SimplifyDemandedInstructionBits(I))
1068 return &I;
1069
1070 // zext(bool) + C -> bool ? C + 1 : C
1071 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
1072 if (ZI->getSrcTy()->isIntegerTy(1))
1073 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001074
Craig Topperf40110f2014-04-25 05:29:35 +00001075 Value *XorLHS = nullptr; ConstantInt *XorRHS = nullptr;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001076 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001077 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001078 const APInt &RHSVal = CI->getValue();
Eli Friedmana2cc2872010-01-31 04:29:12 +00001079 unsigned ExtendAmt = 0;
1080 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1081 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1082 if (XorRHS->getValue() == -RHSVal) {
1083 if (RHSVal.isPowerOf2())
1084 ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
1085 else if (XorRHS->getValue().isPowerOf2())
1086 ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
Chris Lattner82aa8882010-01-05 07:18:46 +00001087 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001088
Eli Friedmana2cc2872010-01-31 04:29:12 +00001089 if (ExtendAmt) {
1090 APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
Hal Finkel60db0582014-09-07 18:57:58 +00001091 if (!MaskedValueIsZero(XorLHS, Mask, 0, &I))
Eli Friedmana2cc2872010-01-31 04:29:12 +00001092 ExtendAmt = 0;
1093 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001094
Eli Friedmana2cc2872010-01-31 04:29:12 +00001095 if (ExtendAmt) {
1096 Constant *ShAmt = ConstantInt::get(I.getType(), ExtendAmt);
1097 Value *NewShl = Builder->CreateShl(XorLHS, ShAmt, "sext");
1098 return BinaryOperator::CreateAShr(NewShl, ShAmt);
Chris Lattner82aa8882010-01-05 07:18:46 +00001099 }
Benjamin Kramerb16bd772011-12-24 17:31:53 +00001100
1101 // If this is a xor that was canonicalized from a sub, turn it back into
1102 // a sub and fuse this add with it.
1103 if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
1104 IntegerType *IT = cast<IntegerType>(I.getType());
Benjamin Kramerb16bd772011-12-24 17:31:53 +00001105 APInt LHSKnownOne(IT->getBitWidth(), 0);
1106 APInt LHSKnownZero(IT->getBitWidth(), 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001107 computeKnownBits(XorLHS, LHSKnownZero, LHSKnownOne, 0, &I);
Benjamin Kramerb16bd772011-12-24 17:31:53 +00001108 if ((XorRHS->getValue() | LHSKnownZero).isAllOnesValue())
1109 return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
1110 XorLHS);
1111 }
David Majnemer70f286d2013-05-06 21:21:31 +00001112 // (X + signbit) + C could have gotten canonicalized to (X ^ signbit) + C,
1113 // transform them into (X + (signbit ^ C))
1114 if (XorRHS->getValue().isSignBit())
Craig Toppereafbd572015-12-21 01:02:28 +00001115 return BinaryOperator::CreateAdd(XorLHS,
1116 ConstantExpr::getXor(XorRHS, CI));
Chris Lattner82aa8882010-01-05 07:18:46 +00001117 }
1118 }
1119
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001120 if (isa<Constant>(RHS) && isa<PHINode>(LHS))
1121 if (Instruction *NV = FoldOpIntoPhi(I))
1122 return NV;
1123
Benjamin Kramer72196f32014-01-19 15:24:22 +00001124 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattner82aa8882010-01-05 07:18:46 +00001125 return BinaryOperator::CreateXor(LHS, RHS);
1126
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001127 // X + X --> X << 1
Chris Lattnerd4067642011-02-17 20:55:29 +00001128 if (LHS == RHS) {
Chris Lattner55920712011-02-17 02:23:02 +00001129 BinaryOperator *New =
1130 BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
1131 New->setHasNoSignedWrap(I.hasNoSignedWrap());
1132 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1133 return New;
1134 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001135
1136 // -A + B --> B - A
1137 // -A + -B --> -(A + B)
1138 if (Value *LHSV = dyn_castNegVal(LHS)) {
Nuno Lopes2710f1b2012-06-08 22:30:05 +00001139 if (!isa<Constant>(RHS))
1140 if (Value *RHSV = dyn_castNegVal(RHS)) {
1141 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
1142 return BinaryOperator::CreateNeg(NewAdd);
1143 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001144
Chris Lattner82aa8882010-01-05 07:18:46 +00001145 return BinaryOperator::CreateSub(RHS, LHSV);
1146 }
1147
1148 // A + -B --> A - B
1149 if (!isa<Constant>(RHS))
1150 if (Value *V = dyn_castNegVal(RHS))
1151 return BinaryOperator::CreateSub(LHS, V);
1152
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001153 if (Value *V = checkForNegativeOperand(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001154 return replaceInstUsesWith(I, V);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001155
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001156 // A+B --> A|B iff A and B have no bits set in common.
Justin Bogner99798402016-08-05 01:06:44 +00001157 if (haveNoCommonBitsSet(LHS, RHS, DL, &AC, &I, &DT))
Jingyue Wuca321902015-05-14 23:53:19 +00001158 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner82aa8882010-01-05 07:18:46 +00001159
Benjamin Kramer72196f32014-01-19 15:24:22 +00001160 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1161 Value *X;
1162 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Chris Lattner82aa8882010-01-05 07:18:46 +00001163 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Benjamin Kramer72196f32014-01-19 15:24:22 +00001164 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001165
Sanjay Patel79acd2a2016-07-16 18:29:26 +00001166 // FIXME: We already did a check for ConstantInt RHS above this.
1167 // FIXME: Is this pattern covered by another fold? No regression tests fail on
1168 // removal.
Benjamin Kramer72196f32014-01-19 15:24:22 +00001169 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001170 // (X & FF00) + xx00 -> (X+xx00) & FF00
Benjamin Kramer72196f32014-01-19 15:24:22 +00001171 Value *X;
1172 ConstantInt *C2;
Chris Lattner82aa8882010-01-05 07:18:46 +00001173 if (LHS->hasOneUse() &&
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001174 match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
1175 CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
1176 // See if all bits from the first bit set in the Add RHS up are included
1177 // in the mask. First, get the rightmost bit.
1178 const APInt &AddRHSV = CRHS->getValue();
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001179
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001180 // Form a mask of all bits from the lowest bit added through the top.
1181 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattner82aa8882010-01-05 07:18:46 +00001182
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001183 // See if the and mask includes all of these bits.
1184 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Chris Lattner82aa8882010-01-05 07:18:46 +00001185
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001186 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1187 // Okay, the xform is safe. Insert the new add pronto.
1188 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
1189 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattner82aa8882010-01-05 07:18:46 +00001190 }
1191 }
1192
1193 // Try to fold constant add into select arguments.
1194 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1195 if (Instruction *R = FoldOpIntoSelect(I, SI))
1196 return R;
1197 }
1198
1199 // add (select X 0 (sub n A)) A --> select X A n
1200 {
1201 SelectInst *SI = dyn_cast<SelectInst>(LHS);
1202 Value *A = RHS;
1203 if (!SI) {
1204 SI = dyn_cast<SelectInst>(RHS);
1205 A = LHS;
1206 }
1207 if (SI && SI->hasOneUse()) {
1208 Value *TV = SI->getTrueValue();
1209 Value *FV = SI->getFalseValue();
1210 Value *N;
1211
1212 // Can we fold the add into the argument of the select?
1213 // We check both true and false select arguments for a matching subtract.
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001214 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner82aa8882010-01-05 07:18:46 +00001215 // Fold the add into the true select value.
1216 return SelectInst::Create(SI->getCondition(), N, A);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001217
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001218 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner82aa8882010-01-05 07:18:46 +00001219 // Fold the add into the false select value.
1220 return SelectInst::Create(SI->getCondition(), A, N);
1221 }
1222 }
1223
1224 // Check for (add (sext x), y), see if we can merge this into an
1225 // integer add followed by a sext.
1226 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
1227 // (add (sext x), cst) --> (sext (add x, cst'))
1228 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001229 Constant *CI =
Chris Lattner82aa8882010-01-05 07:18:46 +00001230 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
1231 if (LHSConv->hasOneUse() &&
1232 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001233 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI, I)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001234 // Insert the new, smaller add.
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001235 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner82aa8882010-01-05 07:18:46 +00001236 CI, "addconv");
1237 return new SExtInst(NewAdd, I.getType());
1238 }
1239 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001240
Chris Lattner82aa8882010-01-05 07:18:46 +00001241 // (add (sext x), (sext y)) --> (sext (add int x, y))
1242 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
1243 // Only do this if x/y have the same type, if at last one of them has a
1244 // single use (so we don't increase the number of sexts), and if the
1245 // integer add will not overflow.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001246 if (LHSConv->getOperand(0)->getType() ==
1247 RHSConv->getOperand(0)->getType() &&
Chris Lattner82aa8882010-01-05 07:18:46 +00001248 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1249 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001250 RHSConv->getOperand(0), I)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001251 // Insert the new integer add.
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001252 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattnerdec68472010-01-05 20:56:24 +00001253 RHSConv->getOperand(0), "addconv");
Chris Lattner82aa8882010-01-05 07:18:46 +00001254 return new SExtInst(NewAdd, I.getType());
1255 }
1256 }
1257 }
1258
David Majnemerab07f002014-08-11 22:32:02 +00001259 // (add (xor A, B) (and A, B)) --> (or A, B)
Chad Rosier7813dce2012-04-26 23:29:14 +00001260 {
Craig Topperf40110f2014-04-25 05:29:35 +00001261 Value *A = nullptr, *B = nullptr;
Chad Rosier7813dce2012-04-26 23:29:14 +00001262 if (match(RHS, m_Xor(m_Value(A), m_Value(B))) &&
1263 (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
1264 match(LHS, m_And(m_Specific(B), m_Specific(A)))))
1265 return BinaryOperator::CreateOr(A, B);
1266
1267 if (match(LHS, m_Xor(m_Value(A), m_Value(B))) &&
1268 (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
1269 match(RHS, m_And(m_Specific(B), m_Specific(A)))))
1270 return BinaryOperator::CreateOr(A, B);
1271 }
1272
David Majnemerab07f002014-08-11 22:32:02 +00001273 // (add (or A, B) (and A, B)) --> (add A, B)
1274 {
1275 Value *A = nullptr, *B = nullptr;
1276 if (match(RHS, m_Or(m_Value(A), m_Value(B))) &&
1277 (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
1278 match(LHS, m_And(m_Specific(B), m_Specific(A))))) {
1279 auto *New = BinaryOperator::CreateAdd(A, B);
1280 New->setHasNoSignedWrap(I.hasNoSignedWrap());
1281 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1282 return New;
1283 }
1284
1285 if (match(LHS, m_Or(m_Value(A), m_Value(B))) &&
1286 (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
1287 match(RHS, m_And(m_Specific(B), m_Specific(A))))) {
1288 auto *New = BinaryOperator::CreateAdd(A, B);
1289 New->setHasNoSignedWrap(I.hasNoSignedWrap());
1290 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1291 return New;
1292 }
1293 }
1294
Jingyue Wu33bd53d2014-06-17 00:42:07 +00001295 // TODO(jingyue): Consider WillNotOverflowSignedAdd and
1296 // WillNotOverflowUnsignedAdd to reduce the number of invocations of
1297 // computeKnownBits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001298 if (!I.hasNoSignedWrap() && WillNotOverflowSignedAdd(LHS, RHS, I)) {
Rafael Espindolad1a2c2d2014-06-02 22:01:04 +00001299 Changed = true;
1300 I.setHasNoSignedWrap(true);
1301 }
David Majnemer5310c1e2015-01-07 00:39:50 +00001302 if (!I.hasNoUnsignedWrap() &&
1303 computeOverflowForUnsignedAdd(LHS, RHS, &I) ==
1304 OverflowResult::NeverOverflows) {
Jingyue Wu33bd53d2014-06-17 00:42:07 +00001305 Changed = true;
1306 I.setHasNoUnsignedWrap(true);
1307 }
Rafael Espindolad1a2c2d2014-06-02 22:01:04 +00001308
Craig Topperf40110f2014-04-25 05:29:35 +00001309 return Changed ? &I : nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001310}
1311
1312Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001313 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner82aa8882010-01-05 07:18:46 +00001314 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1315
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001316 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001317 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001318
Chandler Carruth66b31302015-01-04 12:03:27 +00001319 if (Value *V =
Justin Bogner99798402016-08-05 01:06:44 +00001320 SimplifyFAddInst(LHS, RHS, I.getFastMathFlags(), DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001321 return replaceInstUsesWith(I, V);
Chris Lattner82aa8882010-01-05 07:18:46 +00001322
Stephen Lina9b57f62013-07-20 07:13:13 +00001323 if (isa<Constant>(RHS)) {
1324 if (isa<PHINode>(LHS))
1325 if (Instruction *NV = FoldOpIntoPhi(I))
1326 return NV;
1327
1328 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1329 if (Instruction *NV = FoldOpIntoSelect(I, SI))
1330 return NV;
1331 }
Michael Ilsemane2754dc2012-12-14 22:08:26 +00001332
Chris Lattner82aa8882010-01-05 07:18:46 +00001333 // -A + B --> B - A
1334 // -A + -B --> -(A + B)
Owen Andersone7321662014-01-16 21:26:02 +00001335 if (Value *LHSV = dyn_castFNegVal(LHS)) {
1336 Instruction *RI = BinaryOperator::CreateFSub(RHS, LHSV);
1337 RI->copyFastMathFlags(&I);
1338 return RI;
1339 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001340
1341 // A + -B --> A - B
1342 if (!isa<Constant>(RHS))
Owen Andersone7321662014-01-16 21:26:02 +00001343 if (Value *V = dyn_castFNegVal(RHS)) {
1344 Instruction *RI = BinaryOperator::CreateFSub(LHS, V);
1345 RI->copyFastMathFlags(&I);
1346 return RI;
1347 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001348
Dan Gohman6f34abd2010-03-02 01:11:08 +00001349 // Check for (fadd double (sitofp x), y), see if we can merge this into an
Chris Lattner82aa8882010-01-05 07:18:46 +00001350 // integer add followed by a promotion.
1351 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
Dan Gohman6f34abd2010-03-02 01:11:08 +00001352 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
Chris Lattner82aa8882010-01-05 07:18:46 +00001353 // ... if the constant fits in the integer value. This is useful for things
1354 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1355 // requires a constant pool load, and generally allows the add to be better
1356 // instcombined.
1357 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001358 Constant *CI =
Chris Lattner82aa8882010-01-05 07:18:46 +00001359 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
1360 if (LHSConv->hasOneUse() &&
1361 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001362 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI, I)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001363 // Insert the new integer add.
1364 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1365 CI, "addconv");
1366 return new SIToFPInst(NewAdd, I.getType());
1367 }
1368 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001369
Dan Gohman6f34abd2010-03-02 01:11:08 +00001370 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
Chris Lattner82aa8882010-01-05 07:18:46 +00001371 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1372 // Only do this if x/y have the same type, if at last one of them has a
1373 // single use (so we don't increase the number of int->fp conversions),
1374 // and if the integer add will not overflow.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001375 if (LHSConv->getOperand(0)->getType() ==
1376 RHSConv->getOperand(0)->getType() &&
Chris Lattner82aa8882010-01-05 07:18:46 +00001377 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1378 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001379 RHSConv->getOperand(0), I)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001380 // Insert the new integer add.
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001381 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner82aa8882010-01-05 07:18:46 +00001382 RHSConv->getOperand(0),"addconv");
1383 return new SIToFPInst(NewAdd, I.getType());
1384 }
1385 }
1386 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001387
Jean-Luc Duprat3e4fc3e2013-05-06 16:55:50 +00001388 // select C, 0, B + select C, A, 0 -> select C, A, B
1389 {
1390 Value *A1, *B1, *C1, *A2, *B2, *C2;
1391 if (match(LHS, m_Select(m_Value(C1), m_Value(A1), m_Value(B1))) &&
1392 match(RHS, m_Select(m_Value(C2), m_Value(A2), m_Value(B2)))) {
1393 if (C1 == C2) {
Craig Topperf40110f2014-04-25 05:29:35 +00001394 Constant *Z1=nullptr, *Z2=nullptr;
Jean-Luc Duprat3e4fc3e2013-05-06 16:55:50 +00001395 Value *A, *B, *C=C1;
1396 if (match(A1, m_AnyZero()) && match(B2, m_AnyZero())) {
1397 Z1 = dyn_cast<Constant>(A1); A = A2;
1398 Z2 = dyn_cast<Constant>(B2); B = B1;
1399 } else if (match(B1, m_AnyZero()) && match(A2, m_AnyZero())) {
1400 Z1 = dyn_cast<Constant>(B1); B = B2;
David Majnemer72a643d2014-11-03 05:53:55 +00001401 Z2 = dyn_cast<Constant>(A2); A = A1;
Jean-Luc Duprat3e4fc3e2013-05-06 16:55:50 +00001402 }
David Majnemer72a643d2014-11-03 05:53:55 +00001403
1404 if (Z1 && Z2 &&
1405 (I.hasNoSignedZeros() ||
Jean-Luc Duprat3e4fc3e2013-05-06 16:55:50 +00001406 (Z1->isNegativeZeroValue() && Z2->isNegativeZeroValue()))) {
1407 return SelectInst::Create(C, A, B);
1408 }
1409 }
1410 }
1411 }
1412
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001413 if (I.hasUnsafeAlgebra()) {
1414 if (Value *V = FAddCombine(Builder).simplify(&I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001415 return replaceInstUsesWith(I, V);
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001416 }
1417
Craig Topperf40110f2014-04-25 05:29:35 +00001418 return Changed ? &I : nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001419}
1420
Chris Lattner82aa8882010-01-05 07:18:46 +00001421/// Optimize pointer differences into the same array into a size. Consider:
1422/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1423/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1424///
1425Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
Chris Lattner229907c2011-07-18 04:54:35 +00001426 Type *Ty) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001427 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1428 // this.
1429 bool Swapped = false;
Craig Topperf40110f2014-04-25 05:29:35 +00001430 GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001431
Chris Lattner82aa8882010-01-05 07:18:46 +00001432 // For now we require one side to be the base pointer "A" or a constant
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001433 // GEP derived from it.
1434 if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001435 // (gep X, ...) - X
1436 if (LHSGEP->getOperand(0) == RHS) {
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001437 GEP1 = LHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001438 Swapped = false;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001439 } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1440 // (gep X, ...) - (gep X, ...)
1441 if (LHSGEP->getOperand(0)->stripPointerCasts() ==
1442 RHSGEP->getOperand(0)->stripPointerCasts()) {
1443 GEP2 = RHSGEP;
1444 GEP1 = LHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001445 Swapped = false;
1446 }
1447 }
1448 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001449
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001450 if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001451 // X - (gep X, ...)
1452 if (RHSGEP->getOperand(0) == LHS) {
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001453 GEP1 = RHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001454 Swapped = true;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001455 } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1456 // (gep X, ...) - (gep X, ...)
1457 if (RHSGEP->getOperand(0)->stripPointerCasts() ==
1458 LHSGEP->getOperand(0)->stripPointerCasts()) {
1459 GEP2 = LHSGEP;
1460 GEP1 = RHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001461 Swapped = true;
1462 }
1463 }
1464 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001465
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001466 // Avoid duplicating the arithmetic if GEP2 has non-constant indices and
1467 // multiple users.
Craig Topperf40110f2014-04-25 05:29:35 +00001468 if (!GEP1 ||
1469 (GEP2 && !GEP2->hasAllConstantIndices() && !GEP2->hasOneUse()))
1470 return nullptr;
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001471
Chris Lattner82aa8882010-01-05 07:18:46 +00001472 // Emit the offset of the GEP and an intptr_t.
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001473 Value *Result = EmitGEPOffset(GEP1);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001474
Chris Lattner82aa8882010-01-05 07:18:46 +00001475 // If we had a constant expression GEP on the other side offsetting the
1476 // pointer, subtract it from the offset we have.
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001477 if (GEP2) {
1478 Value *Offset = EmitGEPOffset(GEP2);
1479 Result = Builder->CreateSub(Result, Offset);
Chris Lattner82aa8882010-01-05 07:18:46 +00001480 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001481
1482 // If we have p - gep(p, ...) then we have to negate the result.
1483 if (Swapped)
1484 Result = Builder->CreateNeg(Result, "diff.neg");
1485
1486 return Builder->CreateIntCast(Result, Ty, true);
1487}
1488
Chris Lattner82aa8882010-01-05 07:18:46 +00001489Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1490 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1491
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001492 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001493 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001494
Duncan Sands0a2c41682010-12-15 14:07:39 +00001495 if (Value *V = SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(),
Justin Bogner99798402016-08-05 01:06:44 +00001496 I.hasNoUnsignedWrap(), DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001497 return replaceInstUsesWith(I, V);
Chris Lattner82aa8882010-01-05 07:18:46 +00001498
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001499 // (A*B)-(A*C) -> A*(B-C) etc
1500 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001501 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001502
David Majnemera92687d2014-07-31 04:49:29 +00001503 // If this is a 'B = x-(-A)', change to B = x+A.
Chris Lattner82aa8882010-01-05 07:18:46 +00001504 if (Value *V = dyn_castNegVal(Op1)) {
1505 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
David Majnemera92687d2014-07-31 04:49:29 +00001506
1507 if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
1508 assert(BO->getOpcode() == Instruction::Sub &&
1509 "Expected a subtraction operator!");
1510 if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
1511 Res->setHasNoSignedWrap(true);
David Majnemer0e6c9862014-08-22 16:41:23 +00001512 } else {
1513 if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
1514 Res->setHasNoSignedWrap(true);
David Majnemera92687d2014-07-31 04:49:29 +00001515 }
1516
Chris Lattner82aa8882010-01-05 07:18:46 +00001517 return Res;
1518 }
1519
Duncan Sands9dff9be2010-02-15 16:12:20 +00001520 if (I.getType()->isIntegerTy(1))
Chris Lattner82aa8882010-01-05 07:18:46 +00001521 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001522
1523 // Replace (-1 - A) with (~A).
1524 if (match(Op0, m_AllOnes()))
1525 return BinaryOperator::CreateNot(Op1);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001526
Benjamin Kramer72196f32014-01-19 15:24:22 +00001527 if (Constant *C = dyn_cast<Constant>(Op0)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001528 // C - ~X == X + (1+C)
Craig Topperf40110f2014-04-25 05:29:35 +00001529 Value *X = nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001530 if (match(Op1, m_Not(m_Value(X))))
1531 return BinaryOperator::CreateAdd(X, AddOne(C));
1532
Benjamin Kramer72196f32014-01-19 15:24:22 +00001533 // Try to fold constant sub into select arguments.
1534 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1535 if (Instruction *R = FoldOpIntoSelect(I, SI))
1536 return R;
1537
1538 // C-(X+C2) --> (C-C2)-X
1539 Constant *C2;
1540 if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
1541 return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
1542
1543 if (SimplifyDemandedInstructionBits(I))
1544 return &I;
1545
1546 // Fold (sub 0, (zext bool to B)) --> (sext bool to B)
1547 if (C->isNullValue() && match(Op1, m_ZExt(m_Value(X))))
1548 if (X->getType()->getScalarType()->isIntegerTy(1))
1549 return CastInst::CreateSExtOrBitCast(X, Op1->getType());
1550
1551 // Fold (sub 0, (sext bool to B)) --> (zext bool to B)
1552 if (C->isNullValue() && match(Op1, m_SExt(m_Value(X))))
1553 if (X->getType()->getScalarType()->isIntegerTy(1))
1554 return CastInst::CreateZExtOrBitCast(X, Op1->getType());
1555 }
1556
1557 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001558 // -(X >>u 31) -> (X >>s 31)
1559 // -(X >>s 31) -> (X >>u 31)
1560 if (C->isZero()) {
David Majnemer72a643d2014-11-03 05:53:55 +00001561 Value *X;
Suyog Sardacba4b1d2014-10-08 08:37:49 +00001562 ConstantInt *CI;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001563 if (match(Op1, m_LShr(m_Value(X), m_ConstantInt(CI))) &&
1564 // Verify we are shifting out everything but the sign bit.
Suyog Sardacba4b1d2014-10-08 08:37:49 +00001565 CI->getValue() == I.getType()->getPrimitiveSizeInBits() - 1)
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001566 return BinaryOperator::CreateAShr(X, CI);
1567
1568 if (match(Op1, m_AShr(m_Value(X), m_ConstantInt(CI))) &&
1569 // Verify we are shifting out everything but the sign bit.
Suyog Sardacba4b1d2014-10-08 08:37:49 +00001570 CI->getValue() == I.getType()->getPrimitiveSizeInBits() - 1)
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001571 return BinaryOperator::CreateLShr(X, CI);
Chris Lattner82aa8882010-01-05 07:18:46 +00001572 }
Matthias Braunec683342015-04-30 22:04:26 +00001573
1574 // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
1575 // zero.
1576 APInt IntVal = C->getValue();
1577 if ((IntVal + 1).isPowerOf2()) {
1578 unsigned BitWidth = I.getType()->getScalarSizeInBits();
1579 APInt KnownZero(BitWidth, 0);
1580 APInt KnownOne(BitWidth, 0);
1581 computeKnownBits(&I, KnownZero, KnownOne, 0, &I);
1582 if ((IntVal | KnownZero).isAllOnesValue()) {
1583 return BinaryOperator::CreateXor(Op1, C);
1584 }
1585 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001586 }
1587
David Majnemer72a643d2014-11-03 05:53:55 +00001588 {
Suyog Sardacba4b1d2014-10-08 08:37:49 +00001589 Value *Y;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001590 // X-(X+Y) == -Y X-(Y+X) == -Y
1591 if (match(Op1, m_Add(m_Specific(Op0), m_Value(Y))) ||
1592 match(Op1, m_Add(m_Value(Y), m_Specific(Op0))))
1593 return BinaryOperator::CreateNeg(Y);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001594
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001595 // (X-Y)-X == -Y
1596 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
1597 return BinaryOperator::CreateNeg(Y);
1598 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001599
David Majnemer312c3e52014-10-19 08:32:32 +00001600 // (sub (or A, B) (xor A, B)) --> (and A, B)
1601 {
1602 Value *A = nullptr, *B = nullptr;
1603 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
1604 (match(Op0, m_Or(m_Specific(A), m_Specific(B))) ||
1605 match(Op0, m_Or(m_Specific(B), m_Specific(A)))))
1606 return BinaryOperator::CreateAnd(A, B);
1607 }
1608
David Majnemer72a643d2014-11-03 05:53:55 +00001609 if (Op0->hasOneUse()) {
1610 Value *Y = nullptr;
1611 // ((X | Y) - X) --> (~X & Y)
1612 if (match(Op0, m_Or(m_Value(Y), m_Specific(Op1))) ||
1613 match(Op0, m_Or(m_Specific(Op1), m_Value(Y))))
1614 return BinaryOperator::CreateAnd(
1615 Y, Builder->CreateNot(Op1, Op1->getName() + ".not"));
1616 }
1617
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001618 if (Op1->hasOneUse()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001619 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
1620 Constant *C = nullptr;
1621 Constant *CI = nullptr;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001622
1623 // (X - (Y - Z)) --> (X + (Z - Y)).
1624 if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
1625 return BinaryOperator::CreateAdd(Op0,
1626 Builder->CreateSub(Z, Y, Op1->getName()));
1627
1628 // (X - (X & Y)) --> (X & ~Y)
1629 //
1630 if (match(Op1, m_And(m_Value(Y), m_Specific(Op0))) ||
1631 match(Op1, m_And(m_Specific(Op0), m_Value(Y))))
1632 return BinaryOperator::CreateAnd(Op0,
1633 Builder->CreateNot(Y, Y->getName() + ".not"));
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001634
David Majnemerbdeef602014-07-02 06:07:09 +00001635 // 0 - (X sdiv C) -> (X sdiv -C) provided the negation doesn't overflow.
1636 if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) && match(Op0, m_Zero()) &&
David Majnemer0e6c9862014-08-22 16:41:23 +00001637 C->isNotMinSignedValue() && !C->isOneValue())
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001638 return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
1639
1640 // 0 - (X << Y) -> (-X << Y) when X is freely negatable.
1641 if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
1642 if (Value *XNeg = dyn_castNegVal(X))
1643 return BinaryOperator::CreateShl(XNeg, Y);
1644
Sanjay Patelc6c59652016-10-14 15:24:31 +00001645 // Subtracting -1/0 is the same as adding 1/0:
1646 // sub [nsw] Op0, sext(bool Y) -> add [nsw] Op0, zext(bool Y)
1647 // 'nuw' is dropped in favor of the canonical form.
1648 if (match(Op1, m_SExt(m_Value(Y))) &&
1649 Y->getType()->getScalarSizeInBits() == 1) {
1650 Value *Zext = Builder->CreateZExt(Y, I.getType());
1651 BinaryOperator *Add = BinaryOperator::CreateAdd(Op0, Zext);
1652 Add->setHasNoSignedWrap(I.hasNoSignedWrap());
1653 return Add;
1654 }
1655
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001656 // X - A*-B -> X + A*B
1657 // X - -A*B -> X + A*B
1658 Value *A, *B;
1659 if (match(Op1, m_Mul(m_Value(A), m_Neg(m_Value(B)))) ||
1660 match(Op1, m_Mul(m_Neg(m_Value(A)), m_Value(B))))
1661 return BinaryOperator::CreateAdd(Op0, Builder->CreateMul(A, B));
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001662
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001663 // X - A*CI -> X + A*-CI
1664 // X - CI*A -> X + A*-CI
Benjamin Kramer72196f32014-01-19 15:24:22 +00001665 if (match(Op1, m_Mul(m_Value(A), m_Constant(CI))) ||
1666 match(Op1, m_Mul(m_Constant(CI), m_Value(A)))) {
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001667 Value *NewMul = Builder->CreateMul(A, ConstantExpr::getNeg(CI));
1668 return BinaryOperator::CreateAdd(Op0, NewMul);
Chris Lattner82aa8882010-01-05 07:18:46 +00001669 }
1670 }
1671
Chris Lattner82aa8882010-01-05 07:18:46 +00001672 // Optimize pointer differences into the same array into a size. Consider:
1673 // &A[10] - &A[0]: we should compile this to "10".
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001674 Value *LHSOp, *RHSOp;
1675 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1676 match(Op1, m_PtrToInt(m_Value(RHSOp))))
1677 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001678 return replaceInstUsesWith(I, Res);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001679
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001680 // trunc(p)-trunc(q) -> trunc(p-q)
1681 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1682 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1683 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001684 return replaceInstUsesWith(I, Res);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001685
David Majnemer57d5bc82014-08-19 23:36:30 +00001686 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001687 if (!I.hasNoSignedWrap() && WillNotOverflowSignedSub(Op0, Op1, I)) {
David Majnemer57d5bc82014-08-19 23:36:30 +00001688 Changed = true;
1689 I.setHasNoSignedWrap(true);
1690 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001691 if (!I.hasNoUnsignedWrap() && WillNotOverflowUnsignedSub(Op0, Op1, I)) {
David Majnemer42158f32014-08-20 07:17:31 +00001692 Changed = true;
1693 I.setHasNoUnsignedWrap(true);
1694 }
David Majnemer57d5bc82014-08-19 23:36:30 +00001695
1696 return Changed ? &I : nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001697}
1698
1699Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1700 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1701
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001702 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001703 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001704
Chandler Carruth66b31302015-01-04 12:03:27 +00001705 if (Value *V =
Justin Bogner99798402016-08-05 01:06:44 +00001706 SimplifyFSubInst(Op0, Op1, I.getFastMathFlags(), DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001707 return replaceInstUsesWith(I, V);
Michael Ilsemand5787be2012-12-12 00:28:32 +00001708
Sanjay Patele68f7152014-12-31 22:14:05 +00001709 // fsub nsz 0, X ==> fsub nsz -0.0, X
1710 if (I.getFastMathFlags().noSignedZeros() && match(Op0, m_Zero())) {
1711 // Subtraction from -0.0 is the canonical form of fneg.
1712 Instruction *NewI = BinaryOperator::CreateFNeg(Op1);
1713 NewI->copyFastMathFlags(&I);
1714 return NewI;
1715 }
1716
Stephen Lina9b57f62013-07-20 07:13:13 +00001717 if (isa<Constant>(Op0))
1718 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1719 if (Instruction *NV = FoldOpIntoSelect(I, SI))
1720 return NV;
1721
Owen Andersone37c2e42013-07-26 21:40:29 +00001722 // If this is a 'B = x-(-A)', change to B = x+A, potentially looking
1723 // through FP extensions/truncations along the way.
Owen Andersonc7be5192013-07-30 23:53:17 +00001724 if (Value *V = dyn_castFNegVal(Op1)) {
1725 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, V);
1726 NewI->copyFastMathFlags(&I);
1727 return NewI;
1728 }
Owen Andersone37c2e42013-07-26 21:40:29 +00001729 if (FPTruncInst *FPTI = dyn_cast<FPTruncInst>(Op1)) {
1730 if (Value *V = dyn_castFNegVal(FPTI->getOperand(0))) {
1731 Value *NewTrunc = Builder->CreateFPTrunc(V, I.getType());
Owen Andersonc7be5192013-07-30 23:53:17 +00001732 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewTrunc);
1733 NewI->copyFastMathFlags(&I);
1734 return NewI;
Owen Andersone37c2e42013-07-26 21:40:29 +00001735 }
1736 } else if (FPExtInst *FPEI = dyn_cast<FPExtInst>(Op1)) {
1737 if (Value *V = dyn_castFNegVal(FPEI->getOperand(0))) {
Owen Andersond6d4da02013-07-26 22:06:21 +00001738 Value *NewExt = Builder->CreateFPExt(V, I.getType());
Owen Andersonc7be5192013-07-30 23:53:17 +00001739 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewExt);
1740 NewI->copyFastMathFlags(&I);
1741 return NewI;
Owen Andersone37c2e42013-07-26 21:40:29 +00001742 }
1743 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001744
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001745 if (I.hasUnsafeAlgebra()) {
1746 if (Value *V = FAddCombine(Builder).simplify(&I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001747 return replaceInstUsesWith(I, V);
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001748 }
1749
Craig Topperf40110f2014-04-25 05:29:35 +00001750 return nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001751}