blob: 2e2116c60e67afa83cc0c36a01cecabe35f647a6 [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"
Craig Topperb45eabc2017-04-26 16:39:58 +000020#include "llvm/Support/KnownBits.h"
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000021
Chris Lattner82aa8882010-01-05 07:18:46 +000022using namespace llvm;
23using namespace PatternMatch;
24
Chandler Carruth964daaa2014-04-22 02:55:47 +000025#define DEBUG_TYPE "instcombine"
26
Shuxin Yang37a1efe2012-12-18 23:10:12 +000027namespace {
28
29 /// Class representing coefficient of floating-point addend.
30 /// This class needs to be highly efficient, which is especially true for
31 /// the constructor. As of I write this comment, the cost of the default
Jim Grosbachbdbd7342013-04-05 21:20:12 +000032 /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
Shuxin Yang37a1efe2012-12-18 23:10:12 +000033 /// perform write-merging).
Jim Grosbachbdbd7342013-04-05 21:20:12 +000034 ///
Shuxin Yang37a1efe2012-12-18 23:10:12 +000035 class FAddendCoef {
36 public:
Suyog Sardade409fd2014-07-17 06:09:34 +000037 // The constructor has to initialize a APFloat, which is unnecessary for
Shuxin Yang37a1efe2012-12-18 23:10:12 +000038 // most addends which have coefficient either 1 or -1. So, the constructor
39 // is expensive. In order to avoid the cost of the constructor, we should
40 // reuse some instances whenever possible. The pre-created instances
41 // FAddCombine::Add[0-5] embodies this idea.
42 //
43 FAddendCoef() : IsFp(false), BufHasFpVal(false), IntVal(0) {}
44 ~FAddendCoef();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000045
Shuxin Yang37a1efe2012-12-18 23:10:12 +000046 void set(short C) {
47 assert(!insaneIntVal(C) && "Insane coefficient");
48 IsFp = false; IntVal = C;
49 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000050
Shuxin Yang37a1efe2012-12-18 23:10:12 +000051 void set(const APFloat& C);
Shuxin Yang389ed4b2013-03-25 20:43:41 +000052
Shuxin Yang37a1efe2012-12-18 23:10:12 +000053 void negate();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000054
Shuxin Yang37a1efe2012-12-18 23:10:12 +000055 bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
56 Value *getValue(Type *) const;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000057
Shuxin Yang37a1efe2012-12-18 23:10:12 +000058 // If possible, don't define operator+/operator- etc because these
59 // operators inevitably call FAddendCoef's constructor which is not cheap.
60 void operator=(const FAddendCoef &A);
61 void operator+=(const FAddendCoef &A);
Shuxin Yang37a1efe2012-12-18 23:10:12 +000062 void operator*=(const FAddendCoef &S);
Jim Grosbachbdbd7342013-04-05 21:20:12 +000063
Shuxin Yang37a1efe2012-12-18 23:10:12 +000064 bool isOne() const { return isInt() && IntVal == 1; }
65 bool isTwo() const { return isInt() && IntVal == 2; }
66 bool isMinusOne() const { return isInt() && IntVal == -1; }
67 bool isMinusTwo() const { return isInt() && IntVal == -2; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000068
Shuxin Yang37a1efe2012-12-18 23:10:12 +000069 private:
70 bool insaneIntVal(int V) { return V > 4 || V < -4; }
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000071 APFloat *getFpValPtr()
Shuxin Yang5b841c42012-12-19 01:10:17 +000072 { return reinterpret_cast<APFloat*>(&FpValBuf.buffer[0]); }
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000073 const APFloat *getFpValPtr() const
David Greene530430b2013-01-14 21:04:40 +000074 { return reinterpret_cast<const APFloat*>(&FpValBuf.buffer[0]); }
Shuxin Yang37a1efe2012-12-18 23:10:12 +000075
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000076 const APFloat &getFpVal() const {
Shuxin Yang37a1efe2012-12-18 23:10:12 +000077 assert(IsFp && BufHasFpVal && "Incorret state");
David Greene530430b2013-01-14 21:04:40 +000078 return *getFpValPtr();
Shuxin Yang37a1efe2012-12-18 23:10:12 +000079 }
80
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000081 APFloat &getFpVal() {
Jim Grosbachbdbd7342013-04-05 21:20:12 +000082 assert(IsFp && BufHasFpVal && "Incorret state");
83 return *getFpValPtr();
84 }
85
Shuxin Yang37a1efe2012-12-18 23:10:12 +000086 bool isInt() const { return !IsFp; }
87
Shuxin Yang389ed4b2013-03-25 20:43:41 +000088 // If the coefficient is represented by an integer, promote it to a
Jim Grosbachbdbd7342013-04-05 21:20:12 +000089 // floating point.
Shuxin Yang389ed4b2013-03-25 20:43:41 +000090 void convertToFpType(const fltSemantics &Sem);
91
92 // Construct an APFloat from a signed integer.
93 // TODO: We should get rid of this function when APFloat can be constructed
Jim Grosbachbdbd7342013-04-05 21:20:12 +000094 // from an *SIGNED* integer.
Shuxin Yang389ed4b2013-03-25 20:43:41 +000095 APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
Shuxin Yang5b841c42012-12-19 01:10:17 +000096
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000097 private:
Shuxin Yang37a1efe2012-12-18 23:10:12 +000098 bool IsFp;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000099
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000100 // True iff FpValBuf contains an instance of APFloat.
101 bool BufHasFpVal;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000102
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000103 // The integer coefficient of an individual addend is either 1 or -1,
104 // and we try to simplify at most 4 addends from neighboring at most
105 // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
106 // is overkill of this end.
107 short IntVal;
Shuxin Yang5b841c42012-12-19 01:10:17 +0000108
109 AlignedCharArrayUnion<APFloat> FpValBuf;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000110 };
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000111
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000112 /// FAddend is used to represent floating-point addend. An addend is
113 /// represented as <C, V>, where the V is a symbolic value, and C is a
114 /// constant coefficient. A constant addend is represented as <C, 0>.
115 ///
116 class FAddend {
117 public:
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000118 FAddend() : Val(nullptr) {}
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000119
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000120 Value *getSymVal() const { return Val; }
121 const FAddendCoef &getCoef() const { return Coeff; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000122
Craig Topperf40110f2014-04-25 05:29:35 +0000123 bool isConstant() const { return Val == nullptr; }
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000124 bool isZero() const { return Coeff.isZero(); }
125
Richard Trieu7a083812016-02-18 22:09:30 +0000126 void set(short Coefficient, Value *V) {
127 Coeff.set(Coefficient);
128 Val = V;
129 }
130 void set(const APFloat &Coefficient, Value *V) {
131 Coeff.set(Coefficient);
132 Val = V;
133 }
134 void set(const ConstantFP *Coefficient, Value *V) {
135 Coeff.set(Coefficient->getValueAPF());
136 Val = V;
137 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000138
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000139 void negate() { Coeff.negate(); }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000140
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000141 /// Drill down the U-D chain one step to find the definition of V, and
142 /// try to break the definition into one or two addends.
143 static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000144
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000145 /// Similar to FAddend::drillDownOneStep() except that the value being
146 /// splitted is the addend itself.
147 unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000148
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000149 void operator+=(const FAddend &T) {
150 assert((Val == T.Val) && "Symbolic-values disagree");
151 Coeff += T.Coeff;
152 }
153
154 private:
155 void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000156
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000157 // This addend has the value of "Coeff * Val".
158 Value *Val;
159 FAddendCoef Coeff;
160 };
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000161
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000162 /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
163 /// with its neighboring at most two instructions.
164 ///
165 class FAddCombine {
166 public:
Craig Topperf40110f2014-04-25 05:29:35 +0000167 FAddCombine(InstCombiner::BuilderTy *B) : Builder(B), Instr(nullptr) {}
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000168 Value *simplify(Instruction *FAdd);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000169
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000170 private:
171 typedef SmallVector<const FAddend*, 4> AddendVect;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000172
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000173 Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000174
175 Value *performFactorization(Instruction *I);
176
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000177 /// Convert given addend to a Value
178 Value *createAddendVal(const FAddend &A, bool& NeedNeg);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000179
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000180 /// Return the number of instructions needed to emit the N-ary addition.
181 unsigned calcInstrNumber(const AddendVect& Vect);
182 Value *createFSub(Value *Opnd0, Value *Opnd1);
183 Value *createFAdd(Value *Opnd0, Value *Opnd1);
184 Value *createFMul(Value *Opnd0, Value *Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000185 Value *createFDiv(Value *Opnd0, Value *Opnd1);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000186 Value *createFNeg(Value *V);
187 Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
Owen Anderson1664dc82014-01-20 07:44:53 +0000188 void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000189
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000190 InstCombiner::BuilderTy *Builder;
191 Instruction *Instr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000192
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000193 // Debugging stuff are clustered here.
194 #ifndef NDEBUG
195 unsigned CreateInstrNum;
196 void initCreateInstNum() { CreateInstrNum = 0; }
197 void incCreateInstNum() { CreateInstrNum++; }
198 #else
199 void initCreateInstNum() {}
200 void incCreateInstNum() {}
201 #endif
202 };
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000203
204} // anonymous namespace
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000205
206//===----------------------------------------------------------------------===//
207//
208// Implementation of
209// {FAddendCoef, FAddend, FAddition, FAddCombine}.
210//
211//===----------------------------------------------------------------------===//
212FAddendCoef::~FAddendCoef() {
213 if (BufHasFpVal)
214 getFpValPtr()->~APFloat();
215}
216
217void FAddendCoef::set(const APFloat& C) {
218 APFloat *P = getFpValPtr();
219
220 if (isInt()) {
221 // As the buffer is meanless byte stream, we cannot call
222 // APFloat::operator=().
223 new(P) APFloat(C);
224 } else
225 *P = C;
226
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000227 IsFp = BufHasFpVal = true;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000228}
229
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000230void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
231 if (!isInt())
232 return;
233
234 APFloat *P = getFpValPtr();
235 if (IntVal > 0)
236 new(P) APFloat(Sem, IntVal);
237 else {
238 new(P) APFloat(Sem, 0 - IntVal);
239 P->changeSign();
240 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000241 IsFp = BufHasFpVal = true;
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000242}
243
244APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
245 if (Val >= 0)
246 return APFloat(Sem, Val);
247
248 APFloat T(Sem, 0 - Val);
249 T.changeSign();
250
251 return T;
252}
253
254void FAddendCoef::operator=(const FAddendCoef &That) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000255 if (That.isInt())
256 set(That.IntVal);
257 else
258 set(That.getFpVal());
259}
260
261void FAddendCoef::operator+=(const FAddendCoef &That) {
262 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
263 if (isInt() == That.isInt()) {
264 if (isInt())
265 IntVal += That.IntVal;
266 else
267 getFpVal().add(That.getFpVal(), RndMode);
268 return;
269 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000270
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000271 if (isInt()) {
272 const APFloat &T = That.getFpVal();
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000273 convertToFpType(T.getSemantics());
274 getFpVal().add(T, RndMode);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000275 return;
276 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000277
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000278 APFloat &T = getFpVal();
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000279 T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000280}
281
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000282void FAddendCoef::operator*=(const FAddendCoef &That) {
283 if (That.isOne())
284 return;
285
286 if (That.isMinusOne()) {
287 negate();
288 return;
289 }
290
291 if (isInt() && That.isInt()) {
292 int Res = IntVal * (int)That.IntVal;
293 assert(!insaneIntVal(Res) && "Insane int value");
294 IntVal = Res;
295 return;
296 }
297
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000298 const fltSemantics &Semantic =
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000299 isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
300
301 if (isInt())
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000302 convertToFpType(Semantic);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000303 APFloat &F0 = getFpVal();
304
305 if (That.isInt())
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000306 F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
307 APFloat::rmNearestTiesToEven);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000308 else
309 F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000310}
311
312void FAddendCoef::negate() {
313 if (isInt())
314 IntVal = 0 - IntVal;
315 else
316 getFpVal().changeSign();
317}
318
319Value *FAddendCoef::getValue(Type *Ty) const {
320 return isInt() ?
321 ConstantFP::get(Ty, float(IntVal)) :
322 ConstantFP::get(Ty->getContext(), getFpVal());
323}
324
325// The definition of <Val> Addends
326// =========================================
327// A + B <1, A>, <1,B>
328// A - B <1, A>, <1,B>
329// 0 - B <-1, B>
330// C * A, <C, A>
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000331// A + C <1, A> <C, NULL>
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000332// 0 +/- 0 <0, NULL> (corner case)
333//
334// Legend: A and B are not constant, C is constant
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000335//
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000336unsigned FAddend::drillValueDownOneStep
337 (Value *Val, FAddend &Addend0, FAddend &Addend1) {
Craig Topperf40110f2014-04-25 05:29:35 +0000338 Instruction *I = nullptr;
339 if (!Val || !(I = dyn_cast<Instruction>(Val)))
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000340 return 0;
341
342 unsigned Opcode = I->getOpcode();
343
344 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
345 ConstantFP *C0, *C1;
346 Value *Opnd0 = I->getOperand(0);
347 Value *Opnd1 = I->getOperand(1);
348 if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +0000349 Opnd0 = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000350
351 if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +0000352 Opnd1 = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000353
354 if (Opnd0) {
355 if (!C0)
356 Addend0.set(1, Opnd0);
357 else
Craig Topperf40110f2014-04-25 05:29:35 +0000358 Addend0.set(C0, nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000359 }
360
361 if (Opnd1) {
362 FAddend &Addend = Opnd0 ? Addend1 : Addend0;
363 if (!C1)
364 Addend.set(1, Opnd1);
365 else
Craig Topperf40110f2014-04-25 05:29:35 +0000366 Addend.set(C1, nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000367 if (Opcode == Instruction::FSub)
368 Addend.negate();
369 }
370
371 if (Opnd0 || Opnd1)
372 return Opnd0 && Opnd1 ? 2 : 1;
373
374 // Both operands are zero. Weird!
Craig Topperf40110f2014-04-25 05:29:35 +0000375 Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000376 return 1;
377 }
378
379 if (I->getOpcode() == Instruction::FMul) {
380 Value *V0 = I->getOperand(0);
381 Value *V1 = I->getOperand(1);
382 if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
383 Addend0.set(C, V1);
384 return 1;
385 }
386
387 if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
388 Addend0.set(C, V0);
389 return 1;
390 }
391 }
392
393 return 0;
394}
395
396// Try to break *this* addend into two addends. e.g. Suppose this addend is
397// <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
398// i.e. <2.3, X> and <2.3, Y>.
399//
400unsigned FAddend::drillAddendDownOneStep
401 (FAddend &Addend0, FAddend &Addend1) const {
402 if (isConstant())
403 return 0;
404
405 unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000406 if (!BreakNum || Coeff.isOne())
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000407 return BreakNum;
408
409 Addend0.Scale(Coeff);
410
411 if (BreakNum == 2)
412 Addend1.Scale(Coeff);
413
414 return BreakNum;
415}
416
Shuxin Yang2eca6022013-03-14 18:08:26 +0000417// Try to perform following optimization on the input instruction I. Return the
418// simplified expression if was successful; otherwise, return 0.
419//
420// Instruction "I" is Simplified into
421// -------------------------------------------------------
422// (x * y) +/- (x * z) x * (y +/- z)
423// (y / x) +/- (z / x) (y +/- z) / x
424//
425Value *FAddCombine::performFactorization(Instruction *I) {
426 assert((I->getOpcode() == Instruction::FAdd ||
427 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000428
Shuxin Yang2eca6022013-03-14 18:08:26 +0000429 Instruction *I0 = dyn_cast<Instruction>(I->getOperand(0));
430 Instruction *I1 = dyn_cast<Instruction>(I->getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000431
Shuxin Yang2eca6022013-03-14 18:08:26 +0000432 if (!I0 || !I1 || I0->getOpcode() != I1->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +0000433 return nullptr;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000434
435 bool isMpy = false;
436 if (I0->getOpcode() == Instruction::FMul)
437 isMpy = true;
438 else if (I0->getOpcode() != Instruction::FDiv)
Craig Topperf40110f2014-04-25 05:29:35 +0000439 return nullptr;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000440
441 Value *Opnd0_0 = I0->getOperand(0);
442 Value *Opnd0_1 = I0->getOperand(1);
443 Value *Opnd1_0 = I1->getOperand(0);
444 Value *Opnd1_1 = I1->getOperand(1);
445
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000446 // Input Instr I Factor AddSub0 AddSub1
Shuxin Yang2eca6022013-03-14 18:08:26 +0000447 // ----------------------------------------------
448 // (x*y) +/- (x*z) x y z
449 // (y/x) +/- (z/x) x y z
450 //
Craig Topperf40110f2014-04-25 05:29:35 +0000451 Value *Factor = nullptr;
452 Value *AddSub0 = nullptr, *AddSub1 = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000453
Shuxin Yang2eca6022013-03-14 18:08:26 +0000454 if (isMpy) {
455 if (Opnd0_0 == Opnd1_0 || Opnd0_0 == Opnd1_1)
456 Factor = Opnd0_0;
457 else if (Opnd0_1 == Opnd1_0 || Opnd0_1 == Opnd1_1)
458 Factor = Opnd0_1;
459
460 if (Factor) {
461 AddSub0 = (Factor == Opnd0_0) ? Opnd0_1 : Opnd0_0;
462 AddSub1 = (Factor == Opnd1_0) ? Opnd1_1 : Opnd1_0;
463 }
464 } else if (Opnd0_1 == Opnd1_1) {
465 Factor = Opnd0_1;
466 AddSub0 = Opnd0_0;
467 AddSub1 = Opnd1_0;
468 }
469
470 if (!Factor)
Craig Topperf40110f2014-04-25 05:29:35 +0000471 return nullptr;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000472
Owen Anderson1664dc82014-01-20 07:44:53 +0000473 FastMathFlags Flags;
474 Flags.setUnsafeAlgebra();
475 if (I0) Flags &= I->getFastMathFlags();
476 if (I1) Flags &= I->getFastMathFlags();
477
Shuxin Yang2eca6022013-03-14 18:08:26 +0000478 // Create expression "NewAddSub = AddSub0 +/- AddsSub1"
479 Value *NewAddSub = (I->getOpcode() == Instruction::FAdd) ?
480 createFAdd(AddSub0, AddSub1) :
481 createFSub(AddSub0, AddSub1);
482 if (ConstantFP *CFP = dyn_cast<ConstantFP>(NewAddSub)) {
483 const APFloat &F = CFP->getValueAPF();
Michael Gottesmanc2af8d62013-06-26 23:17:31 +0000484 if (!F.isNormal())
Craig Topperf40110f2014-04-25 05:29:35 +0000485 return nullptr;
Owen Anderson1664dc82014-01-20 07:44:53 +0000486 } else if (Instruction *II = dyn_cast<Instruction>(NewAddSub))
487 II->setFastMathFlags(Flags);
488
489 if (isMpy) {
490 Value *RI = createFMul(Factor, NewAddSub);
491 if (Instruction *II = dyn_cast<Instruction>(RI))
492 II->setFastMathFlags(Flags);
493 return RI;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000494 }
495
Owen Anderson1664dc82014-01-20 07:44:53 +0000496 Value *RI = createFDiv(NewAddSub, Factor);
497 if (Instruction *II = dyn_cast<Instruction>(RI))
498 II->setFastMathFlags(Flags);
499 return RI;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000500}
501
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000502Value *FAddCombine::simplify(Instruction *I) {
503 assert(I->hasUnsafeAlgebra() && "Should be in unsafe mode");
504
505 // Currently we are not able to handle vector type.
506 if (I->getType()->isVectorTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000507 return nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000508
509 assert((I->getOpcode() == Instruction::FAdd ||
510 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
511
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000512 // Save the instruction before calling other member-functions.
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000513 Instr = I;
514
515 FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
516
517 unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
518
519 // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
520 unsigned Opnd0_ExpNum = 0;
521 unsigned Opnd1_ExpNum = 0;
522
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000523 if (!Opnd0.isConstant())
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000524 Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
525
526 // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
527 if (OpndNum == 2 && !Opnd1.isConstant())
528 Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
529
530 // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
531 if (Opnd0_ExpNum && Opnd1_ExpNum) {
532 AddendVect AllOpnds;
533 AllOpnds.push_back(&Opnd0_0);
534 AllOpnds.push_back(&Opnd1_0);
535 if (Opnd0_ExpNum == 2)
536 AllOpnds.push_back(&Opnd0_1);
537 if (Opnd1_ExpNum == 2)
538 AllOpnds.push_back(&Opnd1_1);
539
540 // Compute instruction quota. We should save at least one instruction.
541 unsigned InstQuota = 0;
542
543 Value *V0 = I->getOperand(0);
544 Value *V1 = I->getOperand(1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000545 InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000546 (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
547
548 if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
549 return R;
550 }
551
552 if (OpndNum != 2) {
553 // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
554 // splitted into two addends, say "V = X - Y", the instruction would have
555 // been optimized into "I = Y - X" in the previous steps.
556 //
557 const FAddendCoef &CE = Opnd0.getCoef();
Craig Topperf40110f2014-04-25 05:29:35 +0000558 return CE.isOne() ? Opnd0.getSymVal() : nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000559 }
560
561 // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
562 if (Opnd1_ExpNum) {
563 AddendVect AllOpnds;
564 AllOpnds.push_back(&Opnd0);
565 AllOpnds.push_back(&Opnd1_0);
566 if (Opnd1_ExpNum == 2)
567 AllOpnds.push_back(&Opnd1_1);
568
569 if (Value *R = simplifyFAdd(AllOpnds, 1))
570 return R;
571 }
572
573 // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
574 if (Opnd0_ExpNum) {
575 AddendVect AllOpnds;
576 AllOpnds.push_back(&Opnd1);
577 AllOpnds.push_back(&Opnd0_0);
578 if (Opnd0_ExpNum == 2)
579 AllOpnds.push_back(&Opnd0_1);
580
581 if (Value *R = simplifyFAdd(AllOpnds, 1))
582 return R;
583 }
584
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000585 // step 6: Try factorization as the last resort,
Shuxin Yang2eca6022013-03-14 18:08:26 +0000586 return performFactorization(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000587}
588
589Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000590 unsigned AddendNum = Addends.size();
591 assert(AddendNum <= 4 && "Too many addends");
592
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000593 // For saving intermediate results;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000594 unsigned NextTmpIdx = 0;
595 FAddend TmpResult[3];
596
597 // Points to the constant addend of the resulting simplified expression.
598 // If the resulting expr has constant-addend, this constant-addend is
599 // desirable to reside at the top of the resulting expression tree. Placing
600 // constant close to supper-expr(s) will potentially reveal some optimization
601 // opportunities in super-expr(s).
602 //
Craig Topperf40110f2014-04-25 05:29:35 +0000603 const FAddend *ConstAdd = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000604
605 // Simplified addends are placed <SimpVect>.
606 AddendVect SimpVect;
607
608 // The outer loop works on one symbolic-value at a time. Suppose the input
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000609 // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000610 // The symbolic-values will be processed in this order: x, y, z.
611 //
612 for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
613
614 const FAddend *ThisAddend = Addends[SymIdx];
615 if (!ThisAddend) {
616 // This addend was processed before.
617 continue;
618 }
619
620 Value *Val = ThisAddend->getSymVal();
621 unsigned StartIdx = SimpVect.size();
622 SimpVect.push_back(ThisAddend);
623
624 // The inner loop collects addends sharing same symbolic-value, and these
625 // addends will be later on folded into a single addend. Following above
626 // example, if the symbolic value "y" is being processed, the inner loop
627 // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
628 // be later on folded into "<b1+b2, y>".
629 //
630 for (unsigned SameSymIdx = SymIdx + 1;
631 SameSymIdx < AddendNum; SameSymIdx++) {
632 const FAddend *T = Addends[SameSymIdx];
633 if (T && T->getSymVal() == Val) {
634 // Set null such that next iteration of the outer loop will not process
635 // this addend again.
Craig Topperf40110f2014-04-25 05:29:35 +0000636 Addends[SameSymIdx] = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000637 SimpVect.push_back(T);
638 }
639 }
640
641 // If multiple addends share same symbolic value, fold them together.
642 if (StartIdx + 1 != SimpVect.size()) {
643 FAddend &R = TmpResult[NextTmpIdx ++];
644 R = *SimpVect[StartIdx];
645 for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
646 R += *SimpVect[Idx];
647
648 // Pop all addends being folded and push the resulting folded addend.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000649 SimpVect.resize(StartIdx);
Craig Topperf40110f2014-04-25 05:29:35 +0000650 if (Val) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000651 if (!R.isZero()) {
652 SimpVect.push_back(&R);
653 }
654 } else {
655 // Don't push constant addend at this time. It will be the last element
656 // of <SimpVect>.
657 ConstAdd = &R;
658 }
659 }
660 }
661
Craig Topper58713212013-07-15 04:27:47 +0000662 assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000663 "out-of-bound access");
664
665 if (ConstAdd)
666 SimpVect.push_back(ConstAdd);
667
668 Value *Result;
669 if (!SimpVect.empty())
670 Result = createNaryFAdd(SimpVect, InstrQuota);
671 else {
672 // The addition is folded to 0.0.
673 Result = ConstantFP::get(Instr->getType(), 0.0);
674 }
675
676 return Result;
677}
678
679Value *FAddCombine::createNaryFAdd
680 (const AddendVect &Opnds, unsigned InstrQuota) {
681 assert(!Opnds.empty() && "Expect at least one addend");
682
683 // Step 1: Check if the # of instructions needed exceeds the quota.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000684 //
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000685 unsigned InstrNeeded = calcInstrNumber(Opnds);
686 if (InstrNeeded > InstrQuota)
Craig Topperf40110f2014-04-25 05:29:35 +0000687 return nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000688
689 initCreateInstNum();
690
691 // step 2: Emit the N-ary addition.
692 // Note that at most three instructions are involved in Fadd-InstCombine: the
693 // addition in question, and at most two neighboring instructions.
694 // The resulting optimized addition should have at least one less instruction
695 // than the original addition expression tree. This implies that the resulting
696 // N-ary addition has at most two instructions, and we don't need to worry
697 // about tree-height when constructing the N-ary addition.
698
Craig Topperf40110f2014-04-25 05:29:35 +0000699 Value *LastVal = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000700 bool LastValNeedNeg = false;
701
702 // Iterate the addends, creating fadd/fsub using adjacent two addends.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000703 for (const FAddend *Opnd : Opnds) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000704 bool NeedNeg;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000705 Value *V = createAddendVal(*Opnd, NeedNeg);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000706 if (!LastVal) {
707 LastVal = V;
708 LastValNeedNeg = NeedNeg;
709 continue;
710 }
711
712 if (LastValNeedNeg == NeedNeg) {
713 LastVal = createFAdd(LastVal, V);
714 continue;
715 }
716
717 if (LastValNeedNeg)
718 LastVal = createFSub(V, LastVal);
719 else
720 LastVal = createFSub(LastVal, V);
721
722 LastValNeedNeg = false;
723 }
724
725 if (LastValNeedNeg) {
726 LastVal = createFNeg(LastVal);
727 }
728
729 #ifndef NDEBUG
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000730 assert(CreateInstrNum == InstrNeeded &&
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000731 "Inconsistent in instruction numbers");
732 #endif
733
734 return LastVal;
735}
736
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000737Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000738 Value *V = Builder->CreateFSub(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000739 if (Instruction *I = dyn_cast<Instruction>(V))
740 createInstPostProc(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000741 return V;
742}
743
744Value *FAddCombine::createFNeg(Value *V) {
Sanjay Patelea3c8022014-12-19 16:44:08 +0000745 Value *Zero = cast<Value>(ConstantFP::getZeroValueForNegation(V->getType()));
Owen Anderson1664dc82014-01-20 07:44:53 +0000746 Value *NewV = createFSub(Zero, V);
747 if (Instruction *I = dyn_cast<Instruction>(NewV))
748 createInstPostProc(I, true); // fneg's don't receive instruction numbers.
749 return NewV;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000750}
751
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000752Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000753 Value *V = Builder->CreateFAdd(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000754 if (Instruction *I = dyn_cast<Instruction>(V))
755 createInstPostProc(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000756 return V;
757}
758
759Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
760 Value *V = Builder->CreateFMul(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000761 if (Instruction *I = dyn_cast<Instruction>(V))
762 createInstPostProc(I);
763 return V;
764}
765
766Value *FAddCombine::createFDiv(Value *Opnd0, Value *Opnd1) {
767 Value *V = Builder->CreateFDiv(Opnd0, Opnd1);
768 if (Instruction *I = dyn_cast<Instruction>(V))
769 createInstPostProc(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000770 return V;
771}
772
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000773void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000774 NewInstr->setDebugLoc(Instr->getDebugLoc());
775
776 // Keep track of the number of instruction created.
Owen Anderson1664dc82014-01-20 07:44:53 +0000777 if (!NoNumber)
778 incCreateInstNum();
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000779
780 // Propagate fast-math flags
781 NewInstr->setFastMathFlags(Instr->getFastMathFlags());
782}
783
784// Return the number of instruction needed to emit the N-ary addition.
785// NOTE: Keep this function in sync with createAddendVal().
786unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
787 unsigned OpndNum = Opnds.size();
788 unsigned InstrNeeded = OpndNum - 1;
789
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000790 // The number of addends in the form of "(-1)*x".
791 unsigned NegOpndNum = 0;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000792
793 // Adjust the number of instructions needed to emit the N-ary add.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000794 for (const FAddend *Opnd : Opnds) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000795 if (Opnd->isConstant())
796 continue;
797
Matt Arsenault02907f32017-04-24 17:24:37 +0000798 // The constant check above is really for a few special constant
799 // coefficients.
800 if (isa<UndefValue>(Opnd->getSymVal()))
801 continue;
802
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000803 const FAddendCoef &CE = Opnd->getCoef();
804 if (CE.isMinusOne() || CE.isMinusTwo())
805 NegOpndNum++;
806
807 // Let the addend be "c * x". If "c == +/-1", the value of the addend
808 // is immediately available; otherwise, it needs exactly one instruction
809 // to evaluate the value.
810 if (!CE.isMinusOne() && !CE.isOne())
811 InstrNeeded++;
812 }
813 if (NegOpndNum == OpndNum)
814 InstrNeeded++;
815 return InstrNeeded;
816}
817
818// Input Addend Value NeedNeg(output)
819// ================================================================
820// Constant C C false
821// <+/-1, V> V coefficient is -1
822// <2/-2, V> "fadd V, V" coefficient is -2
823// <C, V> "fmul V, C" false
824//
825// NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000826Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000827 const FAddendCoef &Coeff = Opnd.getCoef();
828
829 if (Opnd.isConstant()) {
830 NeedNeg = false;
831 return Coeff.getValue(Instr->getType());
832 }
833
834 Value *OpndVal = Opnd.getSymVal();
835
836 if (Coeff.isMinusOne() || Coeff.isOne()) {
837 NeedNeg = Coeff.isMinusOne();
838 return OpndVal;
839 }
840
841 if (Coeff.isTwo() || Coeff.isMinusTwo()) {
842 NeedNeg = Coeff.isMinusTwo();
843 return createFAdd(OpndVal, OpndVal);
844 }
845
846 NeedNeg = false;
847 return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
848}
849
Rafael Espindola04c22582014-06-04 15:39:14 +0000850// If one of the operands only has one non-zero bit, and if the other
851// operand has a known-zero bit in a more significant place than it (not
852// including the sign bit) the ripple may go up to and fill the zero, but
853// won't change the sign. For example, (X & ~4) + 1.
854static bool checkRippleForAdd(const APInt &Op0KnownZero,
855 const APInt &Op1KnownZero) {
856 APInt Op1MaybeOne = ~Op1KnownZero;
857 // Make sure that one of the operand has at most one bit set to 1.
858 if (Op1MaybeOne.countPopulation() != 1)
859 return false;
860
861 // Find the most significant known 0 other than the sign bit.
862 int BitWidth = Op0KnownZero.getBitWidth();
863 APInt Op0KnownZeroTemp(Op0KnownZero);
864 Op0KnownZeroTemp.clearBit(BitWidth - 1);
865 int Op0ZeroPosition = BitWidth - Op0KnownZeroTemp.countLeadingZeros() - 1;
866
867 int Op1OnePosition = BitWidth - Op1MaybeOne.countLeadingZeros() - 1;
868 assert(Op1OnePosition >= 0);
869
870 // This also covers the case of no known zero, since in that case
871 // Op0ZeroPosition is -1.
872 return Op0ZeroPosition >= Op1OnePosition;
873}
Chris Lattner82aa8882010-01-05 07:18:46 +0000874
Sanjay Patel6eccf482015-09-09 15:24:36 +0000875/// Return true if we can prove that:
Chris Lattner82aa8882010-01-05 07:18:46 +0000876/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
877/// This basically requires proving that the add in the original type would not
878/// overflow to change the sign bit or have a carry out.
Hal Finkel60db0582014-09-07 18:57:58 +0000879bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000880 Instruction &CxtI) {
Chris Lattner82aa8882010-01-05 07:18:46 +0000881 // There are different heuristics we can use for this. Here are some simple
882 // ones.
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000883
Rafael Espindolad1a2c2d2014-06-02 22:01:04 +0000884 // If LHS and RHS each have at least two sign bits, the addition will look
885 // like
886 //
887 // XX..... +
888 // YY.....
889 //
890 // If the carry into the most significant position is 0, X and Y can't both
891 // be 1 and therefore the carry out of the addition is also 0.
892 //
893 // If the carry into the most significant position is 1, X and Y can't both
894 // be 0 and therefore the carry out of the addition is also 1.
895 //
896 // Since the carry into the most significant position is always equal to
897 // the carry out of the addition, there is no signed overflow.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000898 if (ComputeNumSignBits(LHS, 0, &CxtI) > 1 &&
899 ComputeNumSignBits(RHS, 0, &CxtI) > 1)
Chris Lattner82aa8882010-01-05 07:18:46 +0000900 return true;
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000901
David Majnemer54c2ca22014-12-26 09:10:14 +0000902 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +0000903 KnownBits LHSKnown(BitWidth);
904 computeKnownBits(LHS, LHSKnown, 0, &CxtI);
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000905
Craig Topperb45eabc2017-04-26 16:39:58 +0000906 KnownBits RHSKnown(BitWidth);
907 computeKnownBits(RHS, RHSKnown, 0, &CxtI);
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000908
Craig Topper957a94c2017-04-11 18:47:58 +0000909 // Addition of two 2's complement numbers having opposite signs will never
David Majnemer54c2ca22014-12-26 09:10:14 +0000910 // overflow.
Craig Topperb45eabc2017-04-26 16:39:58 +0000911 if ((LHSKnown.One[BitWidth - 1] && RHSKnown.Zero[BitWidth - 1]) ||
912 (LHSKnown.Zero[BitWidth - 1] && RHSKnown.One[BitWidth - 1]))
David Majnemer54c2ca22014-12-26 09:10:14 +0000913 return true;
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000914
David Majnemer54c2ca22014-12-26 09:10:14 +0000915 // Check if carry bit of addition will not cause overflow.
Craig Topperb45eabc2017-04-26 16:39:58 +0000916 if (checkRippleForAdd(LHSKnown.Zero, RHSKnown.Zero))
David Majnemer54c2ca22014-12-26 09:10:14 +0000917 return true;
Craig Topperb45eabc2017-04-26 16:39:58 +0000918 if (checkRippleForAdd(RHSKnown.Zero, LHSKnown.Zero))
David Majnemer54c2ca22014-12-26 09:10:14 +0000919 return true;
920
Chris Lattner82aa8882010-01-05 07:18:46 +0000921 return false;
922}
923
David Majnemer57d5bc82014-08-19 23:36:30 +0000924/// \brief Return true if we can prove that:
925/// (sub LHS, RHS) === (sub nsw LHS, RHS)
926/// This basically requires proving that the add in the original type would not
927/// overflow to change the sign bit or have a carry out.
928/// TODO: Handle this for Vectors.
Hal Finkel60db0582014-09-07 18:57:58 +0000929bool InstCombiner::WillNotOverflowSignedSub(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000930 Instruction &CxtI) {
David Majnemer57d5bc82014-08-19 23:36:30 +0000931 // If LHS and RHS each have at least two sign bits, the subtraction
932 // cannot overflow.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000933 if (ComputeNumSignBits(LHS, 0, &CxtI) > 1 &&
934 ComputeNumSignBits(RHS, 0, &CxtI) > 1)
David Majnemer57d5bc82014-08-19 23:36:30 +0000935 return true;
936
David Majnemer54c2ca22014-12-26 09:10:14 +0000937 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +0000938 KnownBits LHSKnown(BitWidth);
939 computeKnownBits(LHS, LHSKnown, 0, &CxtI);
David Majnemer57d5bc82014-08-19 23:36:30 +0000940
Craig Topperb45eabc2017-04-26 16:39:58 +0000941 KnownBits RHSKnown(BitWidth);
942 computeKnownBits(RHS, RHSKnown, 0, &CxtI);
David Majnemer57d5bc82014-08-19 23:36:30 +0000943
Craig Topper957a94c2017-04-11 18:47:58 +0000944 // Subtraction of two 2's complement numbers having identical signs will
David Majnemer54c2ca22014-12-26 09:10:14 +0000945 // never overflow.
Craig Topperb45eabc2017-04-26 16:39:58 +0000946 if ((LHSKnown.One[BitWidth - 1] && RHSKnown.One[BitWidth - 1]) ||
947 (LHSKnown.Zero[BitWidth - 1] && RHSKnown.Zero[BitWidth - 1]))
David Majnemer54c2ca22014-12-26 09:10:14 +0000948 return true;
David Majnemer57d5bc82014-08-19 23:36:30 +0000949
David Majnemer54c2ca22014-12-26 09:10:14 +0000950 // TODO: implement logic similar to checkRippleForAdd
David Majnemer57d5bc82014-08-19 23:36:30 +0000951 return false;
952}
953
David Majnemer42158f32014-08-20 07:17:31 +0000954/// \brief Return true if we can prove that:
955/// (sub LHS, RHS) === (sub nuw LHS, RHS)
Hal Finkel60db0582014-09-07 18:57:58 +0000956bool InstCombiner::WillNotOverflowUnsignedSub(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000957 Instruction &CxtI) {
David Majnemer42158f32014-08-20 07:17:31 +0000958 // If the LHS is negative and the RHS is non-negative, no unsigned wrap.
959 bool LHSKnownNonNegative, LHSKnownNegative;
960 bool RHSKnownNonNegative, RHSKnownNegative;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000961 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, /*Depth=*/0,
962 &CxtI);
963 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, /*Depth=*/0,
964 &CxtI);
David Majnemer42158f32014-08-20 07:17:31 +0000965 if (LHSKnownNegative && RHSKnownNonNegative)
966 return true;
967
968 return false;
969}
970
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000971// Checks if any operand is negative and we can convert add to sub.
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000972// This function checks for following negative patterns
973// ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
974// ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
975// XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000976static Value *checkForNegativeOperand(BinaryOperator &I,
977 InstCombiner::BuilderTy *Builder) {
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000978 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000979
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000980 // This function creates 2 instructions to replace ADD, we need at least one
981 // of LHS or RHS to have one use to ensure benefit in transform.
982 if (!LHS->hasOneUse() && !RHS->hasOneUse())
983 return nullptr;
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000984
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000985 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
986 const APInt *C1 = nullptr, *C2 = nullptr;
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000987
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000988 // if ONE is on other side, swap
989 if (match(RHS, m_Add(m_Value(X), m_One())))
990 std::swap(LHS, RHS);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000991
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000992 if (match(LHS, m_Add(m_Value(X), m_One()))) {
993 // if XOR on other side, swap
994 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
995 std::swap(X, RHS);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000996
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000997 if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
998 // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
999 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
1000 if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
1001 Value *NewAnd = Builder->CreateAnd(Z, *C1);
1002 return Builder->CreateSub(RHS, NewAnd, "sub");
1003 } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
1004 // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
1005 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
1006 Value *NewOr = Builder->CreateOr(Z, ~(*C1));
1007 return Builder->CreateSub(RHS, NewOr, "sub");
1008 }
1009 }
1010 }
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001011
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001012 // Restore LHS and RHS
1013 LHS = I.getOperand(0);
1014 RHS = I.getOperand(1);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001015
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001016 // if XOR is on other side, swap
1017 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
1018 std::swap(LHS, RHS);
1019
1020 // C2 is ODD
1021 // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
1022 // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
1023 if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
1024 if (C1->countTrailingZeros() == 0)
1025 if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
1026 Value *NewOr = Builder->CreateOr(Z, ~(*C2));
1027 return Builder->CreateSub(RHS, NewOr, "sub");
1028 }
1029 return nullptr;
1030}
1031
1032Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001033 bool Changed = SimplifyAssociativeOrCommutative(I);
1034 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Jingyue Wu33bd53d2014-06-17 00:42:07 +00001035
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001036 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001037 return replaceInstUsesWith(I, V);
Chris Lattner82aa8882010-01-05 07:18:46 +00001038
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001039 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
Daniel Berlin2c75c632017-04-26 20:56:07 +00001040 I.hasNoUnsignedWrap(), SQ))
Sanjay Patel4b198802016-02-01 22:23:39 +00001041 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001042
Dinesh Dwivedia71617352014-06-26 05:40:22 +00001043 // (A*B)+(A*C) -> A*(B+C) etc
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001044 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001045 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001046
Sanjay Patel0bf0abe2017-04-04 22:06:03 +00001047 const APInt *RHSC;
1048 if (match(RHS, m_APInt(RHSC))) {
Craig Topperbcfd2d12017-04-20 16:56:25 +00001049 if (RHSC->isSignMask()) {
Sanjay Patel53c5c3d2017-02-18 22:20:09 +00001050 // If wrapping is not allowed, then the addition must set the sign bit:
Craig Topperbcfd2d12017-04-20 16:56:25 +00001051 // X + (signmask) --> X | signmask
Sanjay Patel53c5c3d2017-02-18 22:20:09 +00001052 if (I.hasNoSignedWrap() || I.hasNoUnsignedWrap())
1053 return BinaryOperator::CreateOr(LHS, RHS);
1054
1055 // If wrapping is allowed, then the addition flips the sign bit of LHS:
Craig Topperbcfd2d12017-04-20 16:56:25 +00001056 // X + (signmask) --> X ^ signmask
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001057 return BinaryOperator::CreateXor(LHS, RHS);
Sanjay Patel53c5c3d2017-02-18 22:20:09 +00001058 }
Sanjay Patel2d477e592016-07-19 22:09:34 +00001059
1060 // Is this add the last step in a convoluted sext?
1061 Value *X;
1062 const APInt *C;
1063 if (match(LHS, m_ZExt(m_Xor(m_Value(X), m_APInt(C)))) &&
1064 C->isMinSignedValue() &&
Sanjay Patel0bf0abe2017-04-04 22:06:03 +00001065 C->sext(LHS->getType()->getScalarSizeInBits()) == *RHSC) {
Sanjay Patel2d477e592016-07-19 22:09:34 +00001066 // add(zext(xor i16 X, -32768), -32768) --> sext X
1067 return CastInst::Create(Instruction::SExt, X, LHS->getType());
1068 }
David Majnemer022d2a52017-01-04 02:21:31 +00001069
Sanjay Patel0bf0abe2017-04-04 22:06:03 +00001070 if (RHSC->isNegative() &&
David Majnemer022d2a52017-01-04 02:21:31 +00001071 match(LHS, m_ZExt(m_NUWAdd(m_Value(X), m_APInt(C)))) &&
Sanjay Patel0bf0abe2017-04-04 22:06:03 +00001072 RHSC->sge(-C->sext(RHSC->getBitWidth()))) {
David Majnemer022d2a52017-01-04 02:21:31 +00001073 // (add (zext (add nuw X, C)), Val) -> (zext (add nuw X, C+Val))
Sanjay Patel845ea962017-02-15 21:31:34 +00001074 Constant *NewC =
Sanjay Patel0bf0abe2017-04-04 22:06:03 +00001075 ConstantInt::get(X->getType(), *C + RHSC->trunc(C->getBitWidth()));
Sanjay Patel845ea962017-02-15 21:31:34 +00001076 return new ZExtInst(Builder->CreateNUWAdd(X, NewC), I.getType());
David Majnemer022d2a52017-01-04 02:21:31 +00001077 }
Sanjay Patel79acd2a2016-07-16 18:29:26 +00001078 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001079
Sanjay Patel79acd2a2016-07-16 18:29:26 +00001080 // FIXME: Use the match above instead of dyn_cast to allow these transforms
1081 // for splat vectors.
1082 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001083 // zext(bool) + C -> bool ? C + 1 : C
1084 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
1085 if (ZI->getSrcTy()->isIntegerTy(1))
1086 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001087
Craig Topperf40110f2014-04-25 05:29:35 +00001088 Value *XorLHS = nullptr; ConstantInt *XorRHS = nullptr;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001089 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001090 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001091 const APInt &RHSVal = CI->getValue();
Eli Friedmana2cc2872010-01-31 04:29:12 +00001092 unsigned ExtendAmt = 0;
1093 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1094 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1095 if (XorRHS->getValue() == -RHSVal) {
1096 if (RHSVal.isPowerOf2())
1097 ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
1098 else if (XorRHS->getValue().isPowerOf2())
1099 ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
Chris Lattner82aa8882010-01-05 07:18:46 +00001100 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001101
Eli Friedmana2cc2872010-01-31 04:29:12 +00001102 if (ExtendAmt) {
1103 APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
Hal Finkel60db0582014-09-07 18:57:58 +00001104 if (!MaskedValueIsZero(XorLHS, Mask, 0, &I))
Eli Friedmana2cc2872010-01-31 04:29:12 +00001105 ExtendAmt = 0;
1106 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001107
Eli Friedmana2cc2872010-01-31 04:29:12 +00001108 if (ExtendAmt) {
1109 Constant *ShAmt = ConstantInt::get(I.getType(), ExtendAmt);
1110 Value *NewShl = Builder->CreateShl(XorLHS, ShAmt, "sext");
1111 return BinaryOperator::CreateAShr(NewShl, ShAmt);
Chris Lattner82aa8882010-01-05 07:18:46 +00001112 }
Benjamin Kramerb16bd772011-12-24 17:31:53 +00001113
1114 // If this is a xor that was canonicalized from a sub, turn it back into
1115 // a sub and fuse this add with it.
1116 if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
1117 IntegerType *IT = cast<IntegerType>(I.getType());
Craig Topperb45eabc2017-04-26 16:39:58 +00001118 KnownBits LHSKnown(IT->getBitWidth());
1119 computeKnownBits(XorLHS, LHSKnown, 0, &I);
1120 if ((XorRHS->getValue() | LHSKnown.Zero).isAllOnesValue())
Benjamin Kramerb16bd772011-12-24 17:31:53 +00001121 return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
1122 XorLHS);
1123 }
Craig Topperbcfd2d12017-04-20 16:56:25 +00001124 // (X + signmask) + C could have gotten canonicalized to (X^signmask) + C,
1125 // transform them into (X + (signmask ^ C))
1126 if (XorRHS->getValue().isSignMask())
Craig Toppereafbd572015-12-21 01:02:28 +00001127 return BinaryOperator::CreateAdd(XorLHS,
1128 ConstantExpr::getXor(XorRHS, CI));
Chris Lattner82aa8882010-01-05 07:18:46 +00001129 }
1130 }
1131
Craig Topper3eec73e2017-04-10 16:40:00 +00001132 if (isa<Constant>(RHS))
1133 if (Instruction *NV = foldOpWithConstantIntoOperand(I))
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001134 return NV;
1135
Benjamin Kramer72196f32014-01-19 15:24:22 +00001136 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattner82aa8882010-01-05 07:18:46 +00001137 return BinaryOperator::CreateXor(LHS, RHS);
1138
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001139 // X + X --> X << 1
Chris Lattnerd4067642011-02-17 20:55:29 +00001140 if (LHS == RHS) {
Chris Lattner55920712011-02-17 02:23:02 +00001141 BinaryOperator *New =
1142 BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
1143 New->setHasNoSignedWrap(I.hasNoSignedWrap());
1144 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1145 return New;
1146 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001147
1148 // -A + B --> B - A
1149 // -A + -B --> -(A + B)
1150 if (Value *LHSV = dyn_castNegVal(LHS)) {
Nuno Lopes2710f1b2012-06-08 22:30:05 +00001151 if (!isa<Constant>(RHS))
1152 if (Value *RHSV = dyn_castNegVal(RHS)) {
1153 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
1154 return BinaryOperator::CreateNeg(NewAdd);
1155 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001156
Chris Lattner82aa8882010-01-05 07:18:46 +00001157 return BinaryOperator::CreateSub(RHS, LHSV);
1158 }
1159
1160 // A + -B --> A - B
1161 if (!isa<Constant>(RHS))
1162 if (Value *V = dyn_castNegVal(RHS))
1163 return BinaryOperator::CreateSub(LHS, V);
1164
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001165 if (Value *V = checkForNegativeOperand(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001166 return replaceInstUsesWith(I, V);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001167
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001168 // A+B --> A|B iff A and B have no bits set in common.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001169 if (haveNoCommonBitsSet(LHS, RHS, DL, &AC, &I, &DT))
Jingyue Wuca321902015-05-14 23:53:19 +00001170 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner82aa8882010-01-05 07:18:46 +00001171
Benjamin Kramer72196f32014-01-19 15:24:22 +00001172 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1173 Value *X;
1174 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Chris Lattner82aa8882010-01-05 07:18:46 +00001175 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Benjamin Kramer72196f32014-01-19 15:24:22 +00001176 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001177
Sanjay Patel79acd2a2016-07-16 18:29:26 +00001178 // FIXME: We already did a check for ConstantInt RHS above this.
1179 // FIXME: Is this pattern covered by another fold? No regression tests fail on
1180 // removal.
Benjamin Kramer72196f32014-01-19 15:24:22 +00001181 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001182 // (X & FF00) + xx00 -> (X+xx00) & FF00
Benjamin Kramer72196f32014-01-19 15:24:22 +00001183 Value *X;
1184 ConstantInt *C2;
Chris Lattner82aa8882010-01-05 07:18:46 +00001185 if (LHS->hasOneUse() &&
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001186 match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
1187 CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
1188 // See if all bits from the first bit set in the Add RHS up are included
1189 // in the mask. First, get the rightmost bit.
1190 const APInt &AddRHSV = CRHS->getValue();
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001191
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001192 // Form a mask of all bits from the lowest bit added through the top.
1193 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattner82aa8882010-01-05 07:18:46 +00001194
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001195 // See if the and mask includes all of these bits.
1196 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Chris Lattner82aa8882010-01-05 07:18:46 +00001197
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001198 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1199 // Okay, the xform is safe. Insert the new add pronto.
1200 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
1201 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattner82aa8882010-01-05 07:18:46 +00001202 }
1203 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001204 }
1205
1206 // add (select X 0 (sub n A)) A --> select X A n
1207 {
1208 SelectInst *SI = dyn_cast<SelectInst>(LHS);
1209 Value *A = RHS;
1210 if (!SI) {
1211 SI = dyn_cast<SelectInst>(RHS);
1212 A = LHS;
1213 }
1214 if (SI && SI->hasOneUse()) {
1215 Value *TV = SI->getTrueValue();
1216 Value *FV = SI->getFalseValue();
1217 Value *N;
1218
1219 // Can we fold the add into the argument of the select?
1220 // We check both true and false select arguments for a matching subtract.
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001221 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner82aa8882010-01-05 07:18:46 +00001222 // Fold the add into the true select value.
1223 return SelectInst::Create(SI->getCondition(), N, A);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001224
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001225 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner82aa8882010-01-05 07:18:46 +00001226 // Fold the add into the false select value.
1227 return SelectInst::Create(SI->getCondition(), A, N);
1228 }
1229 }
1230
1231 // Check for (add (sext x), y), see if we can merge this into an
1232 // integer add followed by a sext.
1233 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
1234 // (add (sext x), cst) --> (sext (add x, cst'))
1235 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +00001236 if (LHSConv->hasOneUse()) {
1237 Constant *CI =
1238 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
1239 if (ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
1240 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI, I)) {
1241 // Insert the new, smaller add.
1242 Value *NewAdd =
1243 Builder->CreateNSWAdd(LHSConv->getOperand(0), CI, "addconv");
1244 return new SExtInst(NewAdd, I.getType());
1245 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001246 }
1247 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001248
Chris Lattner82aa8882010-01-05 07:18:46 +00001249 // (add (sext x), (sext y)) --> (sext (add int x, y))
1250 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
Craig Topper79e5bc52017-03-30 22:28:55 +00001251 // Only do this if x/y have the same type, if at least one of them has a
Chris Lattner82aa8882010-01-05 07:18:46 +00001252 // single use (so we don't increase the number of sexts), and if the
1253 // integer add will not overflow.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001254 if (LHSConv->getOperand(0)->getType() ==
1255 RHSConv->getOperand(0)->getType() &&
Chris Lattner82aa8882010-01-05 07:18:46 +00001256 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1257 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001258 RHSConv->getOperand(0), I)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001259 // Insert the new integer add.
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001260 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattnerdec68472010-01-05 20:56:24 +00001261 RHSConv->getOperand(0), "addconv");
Chris Lattner82aa8882010-01-05 07:18:46 +00001262 return new SExtInst(NewAdd, I.getType());
1263 }
1264 }
1265 }
1266
David Majnemera1cfd7c2016-12-30 00:28:58 +00001267 // Check for (add (zext x), y), see if we can merge this into an
1268 // integer add followed by a zext.
1269 if (auto *LHSConv = dyn_cast<ZExtInst>(LHS)) {
1270 // (add (zext x), cst) --> (zext (add x, cst'))
1271 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
1272 if (LHSConv->hasOneUse()) {
1273 Constant *CI =
1274 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
1275 if (ConstantExpr::getZExt(CI, I.getType()) == RHSC &&
David Majnemer5ec5f272016-12-30 03:36:17 +00001276 computeOverflowForUnsignedAdd(LHSConv->getOperand(0), CI, &I) ==
1277 OverflowResult::NeverOverflows) {
David Majnemera1cfd7c2016-12-30 00:28:58 +00001278 // Insert the new, smaller add.
1279 Value *NewAdd =
1280 Builder->CreateNUWAdd(LHSConv->getOperand(0), CI, "addconv");
1281 return new ZExtInst(NewAdd, I.getType());
1282 }
1283 }
1284 }
1285
1286 // (add (zext x), (zext y)) --> (zext (add int x, y))
1287 if (auto *RHSConv = dyn_cast<ZExtInst>(RHS)) {
Craig Topper79e5bc52017-03-30 22:28:55 +00001288 // Only do this if x/y have the same type, if at least one of them has a
David Majnemera1cfd7c2016-12-30 00:28:58 +00001289 // single use (so we don't increase the number of zexts), and if the
1290 // integer add will not overflow.
1291 if (LHSConv->getOperand(0)->getType() ==
1292 RHSConv->getOperand(0)->getType() &&
1293 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1294 computeOverflowForUnsignedAdd(LHSConv->getOperand(0),
1295 RHSConv->getOperand(0),
1296 &I) == OverflowResult::NeverOverflows) {
1297 // Insert the new integer add.
1298 Value *NewAdd = Builder->CreateNUWAdd(
1299 LHSConv->getOperand(0), RHSConv->getOperand(0), "addconv");
1300 return new ZExtInst(NewAdd, I.getType());
1301 }
1302 }
1303 }
1304
David Majnemerab07f002014-08-11 22:32:02 +00001305 // (add (xor A, B) (and A, B)) --> (or A, B)
Chad Rosier7813dce2012-04-26 23:29:14 +00001306 {
Craig Topperf40110f2014-04-25 05:29:35 +00001307 Value *A = nullptr, *B = nullptr;
Chad Rosier7813dce2012-04-26 23:29:14 +00001308 if (match(RHS, m_Xor(m_Value(A), m_Value(B))) &&
Craig Topper31cc1432017-04-10 07:13:40 +00001309 match(LHS, m_c_And(m_Specific(A), m_Specific(B))))
Chad Rosier7813dce2012-04-26 23:29:14 +00001310 return BinaryOperator::CreateOr(A, B);
1311
1312 if (match(LHS, m_Xor(m_Value(A), m_Value(B))) &&
Craig Topper31cc1432017-04-10 07:13:40 +00001313 match(RHS, m_c_And(m_Specific(A), m_Specific(B))))
Chad Rosier7813dce2012-04-26 23:29:14 +00001314 return BinaryOperator::CreateOr(A, B);
1315 }
1316
David Majnemerab07f002014-08-11 22:32:02 +00001317 // (add (or A, B) (and A, B)) --> (add A, B)
1318 {
1319 Value *A = nullptr, *B = nullptr;
1320 if (match(RHS, m_Or(m_Value(A), m_Value(B))) &&
Craig Topper31cc1432017-04-10 07:13:40 +00001321 match(LHS, m_c_And(m_Specific(A), m_Specific(B)))) {
David Majnemerab07f002014-08-11 22:32:02 +00001322 auto *New = BinaryOperator::CreateAdd(A, B);
1323 New->setHasNoSignedWrap(I.hasNoSignedWrap());
1324 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1325 return New;
1326 }
1327
1328 if (match(LHS, m_Or(m_Value(A), m_Value(B))) &&
Craig Topper31cc1432017-04-10 07:13:40 +00001329 match(RHS, m_c_And(m_Specific(A), m_Specific(B)))) {
David Majnemerab07f002014-08-11 22:32:02 +00001330 auto *New = BinaryOperator::CreateAdd(A, B);
1331 New->setHasNoSignedWrap(I.hasNoSignedWrap());
1332 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1333 return New;
1334 }
1335 }
1336
Jingyue Wu33bd53d2014-06-17 00:42:07 +00001337 // TODO(jingyue): Consider WillNotOverflowSignedAdd and
1338 // WillNotOverflowUnsignedAdd to reduce the number of invocations of
1339 // computeKnownBits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001340 if (!I.hasNoSignedWrap() && WillNotOverflowSignedAdd(LHS, RHS, I)) {
Rafael Espindolad1a2c2d2014-06-02 22:01:04 +00001341 Changed = true;
1342 I.setHasNoSignedWrap(true);
1343 }
David Majnemer5310c1e2015-01-07 00:39:50 +00001344 if (!I.hasNoUnsignedWrap() &&
1345 computeOverflowForUnsignedAdd(LHS, RHS, &I) ==
1346 OverflowResult::NeverOverflows) {
Jingyue Wu33bd53d2014-06-17 00:42:07 +00001347 Changed = true;
1348 I.setHasNoUnsignedWrap(true);
1349 }
Rafael Espindolad1a2c2d2014-06-02 22:01:04 +00001350
Craig Topperf40110f2014-04-25 05:29:35 +00001351 return Changed ? &I : nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001352}
1353
1354Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001355 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner82aa8882010-01-05 07:18:46 +00001356 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1357
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001358 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001359 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001360
Daniel Berlin2c75c632017-04-26 20:56:07 +00001361 if (Value *V = SimplifyFAddInst(LHS, RHS, I.getFastMathFlags(), SQ))
Sanjay Patel4b198802016-02-01 22:23:39 +00001362 return replaceInstUsesWith(I, V);
Chris Lattner82aa8882010-01-05 07:18:46 +00001363
Sanjay Pateldb0938f2017-01-10 23:49:07 +00001364 if (isa<Constant>(RHS))
1365 if (Instruction *FoldedFAdd = foldOpWithConstantIntoOperand(I))
1366 return FoldedFAdd;
Michael Ilsemane2754dc2012-12-14 22:08:26 +00001367
Chris Lattner82aa8882010-01-05 07:18:46 +00001368 // -A + B --> B - A
1369 // -A + -B --> -(A + B)
Owen Andersone7321662014-01-16 21:26:02 +00001370 if (Value *LHSV = dyn_castFNegVal(LHS)) {
1371 Instruction *RI = BinaryOperator::CreateFSub(RHS, LHSV);
1372 RI->copyFastMathFlags(&I);
1373 return RI;
1374 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001375
1376 // A + -B --> A - B
1377 if (!isa<Constant>(RHS))
Owen Andersone7321662014-01-16 21:26:02 +00001378 if (Value *V = dyn_castFNegVal(RHS)) {
1379 Instruction *RI = BinaryOperator::CreateFSub(LHS, V);
1380 RI->copyFastMathFlags(&I);
1381 return RI;
1382 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001383
Dan Gohman6f34abd2010-03-02 01:11:08 +00001384 // Check for (fadd double (sitofp x), y), see if we can merge this into an
Chris Lattner82aa8882010-01-05 07:18:46 +00001385 // integer add followed by a promotion.
1386 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
Artur Pilipenko4cc61302017-03-21 11:32:15 +00001387 Value *LHSIntVal = LHSConv->getOperand(0);
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001388 Type *FPType = LHSConv->getType();
1389
1390 // TODO: This check is overly conservative. In many cases known bits
1391 // analysis can tell us that the result of the addition has less significant
1392 // bits than the integer type can hold.
1393 auto IsValidPromotion = [](Type *FTy, Type *ITy) {
Artur Pilipenko0632bdc2017-04-22 07:24:52 +00001394 Type *FScalarTy = FTy->getScalarType();
1395 Type *IScalarTy = ITy->getScalarType();
1396
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001397 // Do we have enough bits in the significand to represent the result of
1398 // the integer addition?
1399 unsigned MaxRepresentableBits =
Artur Pilipenko0632bdc2017-04-22 07:24:52 +00001400 APFloat::semanticsPrecision(FScalarTy->getFltSemantics());
1401 return IScalarTy->getIntegerBitWidth() <= MaxRepresentableBits;
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001402 };
Artur Pilipenko4cc61302017-03-21 11:32:15 +00001403
Dan Gohman6f34abd2010-03-02 01:11:08 +00001404 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
Chris Lattner82aa8882010-01-05 07:18:46 +00001405 // ... if the constant fits in the integer value. This is useful for things
1406 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1407 // requires a constant pool load, and generally allows the add to be better
1408 // instcombined.
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001409 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
1410 if (IsValidPromotion(FPType, LHSIntVal->getType())) {
1411 Constant *CI =
1412 ConstantExpr::getFPToSI(CFP, LHSIntVal->getType());
1413 if (LHSConv->hasOneUse() &&
1414 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
1415 WillNotOverflowSignedAdd(LHSIntVal, CI, I)) {
1416 // Insert the new integer add.
1417 Value *NewAdd = Builder->CreateNSWAdd(LHSIntVal,
1418 CI, "addconv");
1419 return new SIToFPInst(NewAdd, I.getType());
1420 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001421 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001422
Dan Gohman6f34abd2010-03-02 01:11:08 +00001423 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
Chris Lattner82aa8882010-01-05 07:18:46 +00001424 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
Artur Pilipenko4cc61302017-03-21 11:32:15 +00001425 Value *RHSIntVal = RHSConv->getOperand(0);
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001426 // It's enough to check LHS types only because we require int types to
1427 // be the same for this transform.
1428 if (IsValidPromotion(FPType, LHSIntVal->getType())) {
1429 // Only do this if x/y have the same type, if at least one of them has a
1430 // single use (so we don't increase the number of int->fp conversions),
1431 // and if the integer add will not overflow.
1432 if (LHSIntVal->getType() == RHSIntVal->getType() &&
1433 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1434 WillNotOverflowSignedAdd(LHSIntVal, RHSIntVal, I)) {
1435 // Insert the new integer add.
1436 Value *NewAdd = Builder->CreateNSWAdd(LHSIntVal,
1437 RHSIntVal, "addconv");
1438 return new SIToFPInst(NewAdd, I.getType());
1439 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001440 }
1441 }
1442 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001443
Jean-Luc Duprat3e4fc3e2013-05-06 16:55:50 +00001444 // select C, 0, B + select C, A, 0 -> select C, A, B
1445 {
1446 Value *A1, *B1, *C1, *A2, *B2, *C2;
1447 if (match(LHS, m_Select(m_Value(C1), m_Value(A1), m_Value(B1))) &&
1448 match(RHS, m_Select(m_Value(C2), m_Value(A2), m_Value(B2)))) {
1449 if (C1 == C2) {
Craig Topperf40110f2014-04-25 05:29:35 +00001450 Constant *Z1=nullptr, *Z2=nullptr;
Jean-Luc Duprat3e4fc3e2013-05-06 16:55:50 +00001451 Value *A, *B, *C=C1;
1452 if (match(A1, m_AnyZero()) && match(B2, m_AnyZero())) {
1453 Z1 = dyn_cast<Constant>(A1); A = A2;
1454 Z2 = dyn_cast<Constant>(B2); B = B1;
1455 } else if (match(B1, m_AnyZero()) && match(A2, m_AnyZero())) {
1456 Z1 = dyn_cast<Constant>(B1); B = B2;
David Majnemer72a643d2014-11-03 05:53:55 +00001457 Z2 = dyn_cast<Constant>(A2); A = A1;
Jean-Luc Duprat3e4fc3e2013-05-06 16:55:50 +00001458 }
David Majnemer72a643d2014-11-03 05:53:55 +00001459
1460 if (Z1 && Z2 &&
1461 (I.hasNoSignedZeros() ||
Jean-Luc Duprat3e4fc3e2013-05-06 16:55:50 +00001462 (Z1->isNegativeZeroValue() && Z2->isNegativeZeroValue()))) {
1463 return SelectInst::Create(C, A, B);
1464 }
1465 }
1466 }
1467 }
1468
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001469 if (I.hasUnsafeAlgebra()) {
1470 if (Value *V = FAddCombine(Builder).simplify(&I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001471 return replaceInstUsesWith(I, V);
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001472 }
1473
Craig Topperf40110f2014-04-25 05:29:35 +00001474 return Changed ? &I : nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001475}
1476
Chris Lattner82aa8882010-01-05 07:18:46 +00001477/// Optimize pointer differences into the same array into a size. Consider:
1478/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1479/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1480///
1481Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
Chris Lattner229907c2011-07-18 04:54:35 +00001482 Type *Ty) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001483 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1484 // this.
1485 bool Swapped = false;
Craig Topperf40110f2014-04-25 05:29:35 +00001486 GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001487
Chris Lattner82aa8882010-01-05 07:18:46 +00001488 // For now we require one side to be the base pointer "A" or a constant
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001489 // GEP derived from it.
1490 if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001491 // (gep X, ...) - X
1492 if (LHSGEP->getOperand(0) == RHS) {
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001493 GEP1 = LHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001494 Swapped = false;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001495 } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1496 // (gep X, ...) - (gep X, ...)
1497 if (LHSGEP->getOperand(0)->stripPointerCasts() ==
1498 RHSGEP->getOperand(0)->stripPointerCasts()) {
1499 GEP2 = RHSGEP;
1500 GEP1 = LHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001501 Swapped = false;
1502 }
1503 }
1504 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001505
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001506 if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001507 // X - (gep X, ...)
1508 if (RHSGEP->getOperand(0) == LHS) {
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001509 GEP1 = RHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001510 Swapped = true;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001511 } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1512 // (gep X, ...) - (gep X, ...)
1513 if (RHSGEP->getOperand(0)->stripPointerCasts() ==
1514 LHSGEP->getOperand(0)->stripPointerCasts()) {
1515 GEP2 = LHSGEP;
1516 GEP1 = RHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001517 Swapped = true;
1518 }
1519 }
1520 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001521
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001522 // Avoid duplicating the arithmetic if GEP2 has non-constant indices and
1523 // multiple users.
Craig Topperf40110f2014-04-25 05:29:35 +00001524 if (!GEP1 ||
1525 (GEP2 && !GEP2->hasAllConstantIndices() && !GEP2->hasOneUse()))
1526 return nullptr;
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001527
Chris Lattner82aa8882010-01-05 07:18:46 +00001528 // Emit the offset of the GEP and an intptr_t.
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001529 Value *Result = EmitGEPOffset(GEP1);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001530
Chris Lattner82aa8882010-01-05 07:18:46 +00001531 // If we had a constant expression GEP on the other side offsetting the
1532 // pointer, subtract it from the offset we have.
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001533 if (GEP2) {
1534 Value *Offset = EmitGEPOffset(GEP2);
1535 Result = Builder->CreateSub(Result, Offset);
Chris Lattner82aa8882010-01-05 07:18:46 +00001536 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001537
1538 // If we have p - gep(p, ...) then we have to negate the result.
1539 if (Swapped)
1540 Result = Builder->CreateNeg(Result, "diff.neg");
1541
1542 return Builder->CreateIntCast(Result, Ty, true);
1543}
1544
Chris Lattner82aa8882010-01-05 07:18:46 +00001545Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1546 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1547
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001548 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001549 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001550
Duncan Sands0a2c41682010-12-15 14:07:39 +00001551 if (Value *V = SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(),
Daniel Berlin2c75c632017-04-26 20:56:07 +00001552 I.hasNoUnsignedWrap(), SQ))
Sanjay Patel4b198802016-02-01 22:23:39 +00001553 return replaceInstUsesWith(I, V);
Chris Lattner82aa8882010-01-05 07:18:46 +00001554
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001555 // (A*B)-(A*C) -> A*(B-C) etc
1556 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001557 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001558
David Majnemera92687d2014-07-31 04:49:29 +00001559 // If this is a 'B = x-(-A)', change to B = x+A.
Chris Lattner82aa8882010-01-05 07:18:46 +00001560 if (Value *V = dyn_castNegVal(Op1)) {
1561 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
David Majnemera92687d2014-07-31 04:49:29 +00001562
1563 if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
1564 assert(BO->getOpcode() == Instruction::Sub &&
1565 "Expected a subtraction operator!");
1566 if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
1567 Res->setHasNoSignedWrap(true);
David Majnemer0e6c9862014-08-22 16:41:23 +00001568 } else {
1569 if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
1570 Res->setHasNoSignedWrap(true);
David Majnemera92687d2014-07-31 04:49:29 +00001571 }
1572
Chris Lattner82aa8882010-01-05 07:18:46 +00001573 return Res;
1574 }
1575
Craig Topperc745b6a2017-04-04 21:44:56 +00001576 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattner82aa8882010-01-05 07:18:46 +00001577 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001578
1579 // Replace (-1 - A) with (~A).
1580 if (match(Op0, m_AllOnes()))
1581 return BinaryOperator::CreateNot(Op1);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001582
Benjamin Kramer72196f32014-01-19 15:24:22 +00001583 if (Constant *C = dyn_cast<Constant>(Op0)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001584 // C - ~X == X + (1+C)
Craig Topperf40110f2014-04-25 05:29:35 +00001585 Value *X = nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001586 if (match(Op1, m_Not(m_Value(X))))
1587 return BinaryOperator::CreateAdd(X, AddOne(C));
1588
Benjamin Kramer72196f32014-01-19 15:24:22 +00001589 // Try to fold constant sub into select arguments.
1590 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1591 if (Instruction *R = FoldOpIntoSelect(I, SI))
1592 return R;
1593
Craig Topperfb71b7d2017-04-14 19:20:12 +00001594 // Try to fold constant sub into PHI values.
1595 if (PHINode *PN = dyn_cast<PHINode>(Op1))
1596 if (Instruction *R = foldOpIntoPhi(I, PN))
1597 return R;
1598
Benjamin Kramer72196f32014-01-19 15:24:22 +00001599 // C-(X+C2) --> (C-C2)-X
1600 Constant *C2;
1601 if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
1602 return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
1603
Benjamin Kramer72196f32014-01-19 15:24:22 +00001604 // Fold (sub 0, (zext bool to B)) --> (sext bool to B)
1605 if (C->isNullValue() && match(Op1, m_ZExt(m_Value(X))))
1606 if (X->getType()->getScalarType()->isIntegerTy(1))
1607 return CastInst::CreateSExtOrBitCast(X, Op1->getType());
1608
1609 // Fold (sub 0, (sext bool to B)) --> (zext bool to B)
1610 if (C->isNullValue() && match(Op1, m_SExt(m_Value(X))))
1611 if (X->getType()->getScalarType()->isIntegerTy(1))
1612 return CastInst::CreateZExtOrBitCast(X, Op1->getType());
1613 }
1614
Sanjay Patel6d6eca52016-10-14 16:31:54 +00001615 const APInt *Op0C;
1616 if (match(Op0, m_APInt(Op0C))) {
1617 unsigned BitWidth = I.getType()->getScalarSizeInBits();
1618
Chris Lattner82aa8882010-01-05 07:18:46 +00001619 // -(X >>u 31) -> (X >>s 31)
1620 // -(X >>s 31) -> (X >>u 31)
Sanjay Patel6d6eca52016-10-14 16:31:54 +00001621 if (*Op0C == 0) {
David Majnemer72a643d2014-11-03 05:53:55 +00001622 Value *X;
Sanjay Patel6d6eca52016-10-14 16:31:54 +00001623 const APInt *ShAmt;
1624 if (match(Op1, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
1625 *ShAmt == BitWidth - 1) {
1626 Value *ShAmtOp = cast<Instruction>(Op1)->getOperand(1);
1627 return BinaryOperator::CreateAShr(X, ShAmtOp);
1628 }
1629 if (match(Op1, m_AShr(m_Value(X), m_APInt(ShAmt))) &&
1630 *ShAmt == BitWidth - 1) {
1631 Value *ShAmtOp = cast<Instruction>(Op1)->getOperand(1);
1632 return BinaryOperator::CreateLShr(X, ShAmtOp);
1633 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001634 }
Matthias Braunec683342015-04-30 22:04:26 +00001635
1636 // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
1637 // zero.
Craig Topperb4da6842017-04-06 21:06:03 +00001638 if (Op0C->isMask()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001639 KnownBits RHSKnown(BitWidth);
1640 computeKnownBits(Op1, RHSKnown, 0, &I);
1641 if ((*Op0C | RHSKnown.Zero).isAllOnesValue())
Sanjay Patel6d6eca52016-10-14 16:31:54 +00001642 return BinaryOperator::CreateXor(Op1, Op0);
Matthias Braunec683342015-04-30 22:04:26 +00001643 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001644 }
1645
David Majnemer72a643d2014-11-03 05:53:55 +00001646 {
Suyog Sardacba4b1d2014-10-08 08:37:49 +00001647 Value *Y;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001648 // X-(X+Y) == -Y X-(Y+X) == -Y
Craig Topper98851ad2017-04-10 16:59:40 +00001649 if (match(Op1, m_c_Add(m_Specific(Op0), m_Value(Y))))
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001650 return BinaryOperator::CreateNeg(Y);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001651
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001652 // (X-Y)-X == -Y
1653 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
1654 return BinaryOperator::CreateNeg(Y);
1655 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001656
David Majnemer312c3e52014-10-19 08:32:32 +00001657 // (sub (or A, B) (xor A, B)) --> (and A, B)
1658 {
Craig Topper0d830ff2017-04-10 18:09:25 +00001659 Value *A, *B;
David Majnemer312c3e52014-10-19 08:32:32 +00001660 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Craig Topper0d830ff2017-04-10 18:09:25 +00001661 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
David Majnemer312c3e52014-10-19 08:32:32 +00001662 return BinaryOperator::CreateAnd(A, B);
1663 }
1664
Craig Topper0d830ff2017-04-10 18:09:25 +00001665 {
1666 Value *Y;
David Majnemer72a643d2014-11-03 05:53:55 +00001667 // ((X | Y) - X) --> (~X & Y)
Craig Topper0d830ff2017-04-10 18:09:25 +00001668 if (match(Op0, m_OneUse(m_c_Or(m_Value(Y), m_Specific(Op1)))))
David Majnemer72a643d2014-11-03 05:53:55 +00001669 return BinaryOperator::CreateAnd(
1670 Y, Builder->CreateNot(Op1, Op1->getName() + ".not"));
1671 }
1672
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001673 if (Op1->hasOneUse()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001674 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
1675 Constant *C = nullptr;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001676
1677 // (X - (Y - Z)) --> (X + (Z - Y)).
1678 if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
1679 return BinaryOperator::CreateAdd(Op0,
1680 Builder->CreateSub(Z, Y, Op1->getName()));
1681
1682 // (X - (X & Y)) --> (X & ~Y)
1683 //
Craig Topper0d830ff2017-04-10 18:09:25 +00001684 if (match(Op1, m_c_And(m_Value(Y), m_Specific(Op0))))
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001685 return BinaryOperator::CreateAnd(Op0,
1686 Builder->CreateNot(Y, Y->getName() + ".not"));
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001687
David Majnemerbdeef602014-07-02 06:07:09 +00001688 // 0 - (X sdiv C) -> (X sdiv -C) provided the negation doesn't overflow.
1689 if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) && match(Op0, m_Zero()) &&
David Majnemer0e6c9862014-08-22 16:41:23 +00001690 C->isNotMinSignedValue() && !C->isOneValue())
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001691 return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
1692
1693 // 0 - (X << Y) -> (-X << Y) when X is freely negatable.
1694 if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
1695 if (Value *XNeg = dyn_castNegVal(X))
1696 return BinaryOperator::CreateShl(XNeg, Y);
1697
Sanjay Patelc6c59652016-10-14 15:24:31 +00001698 // Subtracting -1/0 is the same as adding 1/0:
1699 // sub [nsw] Op0, sext(bool Y) -> add [nsw] Op0, zext(bool Y)
1700 // 'nuw' is dropped in favor of the canonical form.
1701 if (match(Op1, m_SExt(m_Value(Y))) &&
1702 Y->getType()->getScalarSizeInBits() == 1) {
1703 Value *Zext = Builder->CreateZExt(Y, I.getType());
1704 BinaryOperator *Add = BinaryOperator::CreateAdd(Op0, Zext);
1705 Add->setHasNoSignedWrap(I.hasNoSignedWrap());
1706 return Add;
1707 }
1708
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001709 // X - A*-B -> X + A*B
1710 // X - -A*B -> X + A*B
1711 Value *A, *B;
Craig Topper0d830ff2017-04-10 18:09:25 +00001712 Constant *CI;
1713 if (match(Op1, m_c_Mul(m_Value(A), m_Neg(m_Value(B)))))
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001714 return BinaryOperator::CreateAdd(Op0, Builder->CreateMul(A, B));
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001715
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001716 // X - A*CI -> X + A*-CI
Craig Topper0d830ff2017-04-10 18:09:25 +00001717 // No need to handle commuted multiply because multiply handling will
1718 // ensure constant will be move to the right hand side.
1719 if (match(Op1, m_Mul(m_Value(A), m_Constant(CI)))) {
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001720 Value *NewMul = Builder->CreateMul(A, ConstantExpr::getNeg(CI));
1721 return BinaryOperator::CreateAdd(Op0, NewMul);
Chris Lattner82aa8882010-01-05 07:18:46 +00001722 }
1723 }
1724
Chris Lattner82aa8882010-01-05 07:18:46 +00001725 // Optimize pointer differences into the same array into a size. Consider:
1726 // &A[10] - &A[0]: we should compile this to "10".
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001727 Value *LHSOp, *RHSOp;
1728 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1729 match(Op1, m_PtrToInt(m_Value(RHSOp))))
1730 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001731 return replaceInstUsesWith(I, Res);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001732
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001733 // trunc(p)-trunc(q) -> trunc(p-q)
1734 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1735 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1736 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001737 return replaceInstUsesWith(I, Res);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001738
David Majnemer57d5bc82014-08-19 23:36:30 +00001739 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001740 if (!I.hasNoSignedWrap() && WillNotOverflowSignedSub(Op0, Op1, I)) {
David Majnemer57d5bc82014-08-19 23:36:30 +00001741 Changed = true;
1742 I.setHasNoSignedWrap(true);
1743 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001744 if (!I.hasNoUnsignedWrap() && WillNotOverflowUnsignedSub(Op0, Op1, I)) {
David Majnemer42158f32014-08-20 07:17:31 +00001745 Changed = true;
1746 I.setHasNoUnsignedWrap(true);
1747 }
David Majnemer57d5bc82014-08-19 23:36:30 +00001748
1749 return Changed ? &I : nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001750}
1751
1752Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1753 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1754
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001755 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001756 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001757
Daniel Berlin2c75c632017-04-26 20:56:07 +00001758 if (Value *V = SimplifyFSubInst(Op0, Op1, I.getFastMathFlags(), SQ))
Sanjay Patel4b198802016-02-01 22:23:39 +00001759 return replaceInstUsesWith(I, V);
Michael Ilsemand5787be2012-12-12 00:28:32 +00001760
Sanjay Patele68f7152014-12-31 22:14:05 +00001761 // fsub nsz 0, X ==> fsub nsz -0.0, X
1762 if (I.getFastMathFlags().noSignedZeros() && match(Op0, m_Zero())) {
1763 // Subtraction from -0.0 is the canonical form of fneg.
1764 Instruction *NewI = BinaryOperator::CreateFNeg(Op1);
1765 NewI->copyFastMathFlags(&I);
1766 return NewI;
1767 }
1768
Stephen Lina9b57f62013-07-20 07:13:13 +00001769 if (isa<Constant>(Op0))
1770 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1771 if (Instruction *NV = FoldOpIntoSelect(I, SI))
1772 return NV;
1773
Owen Andersone37c2e42013-07-26 21:40:29 +00001774 // If this is a 'B = x-(-A)', change to B = x+A, potentially looking
1775 // through FP extensions/truncations along the way.
Owen Andersonc7be5192013-07-30 23:53:17 +00001776 if (Value *V = dyn_castFNegVal(Op1)) {
1777 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, V);
1778 NewI->copyFastMathFlags(&I);
1779 return NewI;
1780 }
Owen Andersone37c2e42013-07-26 21:40:29 +00001781 if (FPTruncInst *FPTI = dyn_cast<FPTruncInst>(Op1)) {
1782 if (Value *V = dyn_castFNegVal(FPTI->getOperand(0))) {
1783 Value *NewTrunc = Builder->CreateFPTrunc(V, I.getType());
Owen Andersonc7be5192013-07-30 23:53:17 +00001784 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewTrunc);
1785 NewI->copyFastMathFlags(&I);
1786 return NewI;
Owen Andersone37c2e42013-07-26 21:40:29 +00001787 }
1788 } else if (FPExtInst *FPEI = dyn_cast<FPExtInst>(Op1)) {
1789 if (Value *V = dyn_castFNegVal(FPEI->getOperand(0))) {
Owen Andersond6d4da02013-07-26 22:06:21 +00001790 Value *NewExt = Builder->CreateFPExt(V, I.getType());
Owen Andersonc7be5192013-07-30 23:53:17 +00001791 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewExt);
1792 NewI->copyFastMathFlags(&I);
1793 return NewI;
Owen Andersone37c2e42013-07-26 21:40:29 +00001794 }
1795 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001796
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001797 if (I.hasUnsafeAlgebra()) {
1798 if (Value *V = FAddCombine(Builder).simplify(&I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001799 return replaceInstUsesWith(I, V);
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001800 }
1801
Craig Topperf40110f2014-04-25 05:29:35 +00001802 return nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001803}