blob: 233e0c7b5de72d94f6044f1eae0bdc2870a1c303 [file] [log] [blame]
Eugene Zelenkoffec81c2015-11-04 22:32:32 +00001//===- InstCombineAddSub.cpp ------------------------------------*- C++ -*-===//
Chris Lattner82aa8882010-01-05 07:18:46 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner82aa8882010-01-05 07:18:46 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the visit functions for add, fadd, sub, and fsub.
10//
11//===----------------------------------------------------------------------===//
12
Chandler Carrutha9174582015-01-22 05:25:13 +000013#include "InstCombineInternal.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000014#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/APInt.h"
Craig Topper58713212013-07-15 04:27:47 +000016#include "llvm/ADT/STLExtras.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000017#include "llvm/ADT/SmallVector.h"
Chris Lattner82aa8882010-01-05 07:18:46 +000018#include "llvm/Analysis/InstructionSimplify.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000019#include "llvm/Analysis/ValueTracking.h"
20#include "llvm/IR/Constant.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/InstrTypes.h"
23#include "llvm/IR/Instruction.h"
24#include "llvm/IR/Instructions.h"
25#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000026#include "llvm/IR/PatternMatch.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000027#include "llvm/IR/Type.h"
28#include "llvm/IR/Value.h"
29#include "llvm/Support/AlignOf.h"
30#include "llvm/Support/Casting.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000031#include "llvm/Support/KnownBits.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000032#include <cassert>
33#include <utility>
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000034
Chris Lattner82aa8882010-01-05 07:18:46 +000035using namespace llvm;
36using namespace PatternMatch;
37
Chandler Carruth964daaa2014-04-22 02:55:47 +000038#define DEBUG_TYPE "instcombine"
39
Shuxin Yang37a1efe2012-12-18 23:10:12 +000040namespace {
41
42 /// Class representing coefficient of floating-point addend.
43 /// This class needs to be highly efficient, which is especially true for
44 /// the constructor. As of I write this comment, the cost of the default
Jim Grosbachbdbd7342013-04-05 21:20:12 +000045 /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
Shuxin Yang37a1efe2012-12-18 23:10:12 +000046 /// perform write-merging).
Jim Grosbachbdbd7342013-04-05 21:20:12 +000047 ///
Shuxin Yang37a1efe2012-12-18 23:10:12 +000048 class FAddendCoef {
49 public:
Suyog Sardade409fd2014-07-17 06:09:34 +000050 // The constructor has to initialize a APFloat, which is unnecessary for
Shuxin Yang37a1efe2012-12-18 23:10:12 +000051 // most addends which have coefficient either 1 or -1. So, the constructor
52 // is expensive. In order to avoid the cost of the constructor, we should
53 // reuse some instances whenever possible. The pre-created instances
54 // FAddCombine::Add[0-5] embodies this idea.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000055 FAddendCoef() = default;
Shuxin Yang37a1efe2012-12-18 23:10:12 +000056 ~FAddendCoef();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000057
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +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);
62 void operator*=(const FAddendCoef &S);
63
Shuxin Yang37a1efe2012-12-18 23:10:12 +000064 void set(short C) {
65 assert(!insaneIntVal(C) && "Insane coefficient");
66 IsFp = false; IntVal = C;
67 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000068
Shuxin Yang37a1efe2012-12-18 23:10:12 +000069 void set(const APFloat& C);
Shuxin Yang389ed4b2013-03-25 20:43:41 +000070
Shuxin Yang37a1efe2012-12-18 23:10:12 +000071 void negate();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000072
Shuxin Yang37a1efe2012-12-18 23:10:12 +000073 bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
74 Value *getValue(Type *) const;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000075
Shuxin Yang37a1efe2012-12-18 23:10:12 +000076 bool isOne() const { return isInt() && IntVal == 1; }
77 bool isTwo() const { return isInt() && IntVal == 2; }
78 bool isMinusOne() const { return isInt() && IntVal == -1; }
79 bool isMinusTwo() const { return isInt() && IntVal == -2; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000080
Shuxin Yang37a1efe2012-12-18 23:10:12 +000081 private:
82 bool insaneIntVal(int V) { return V > 4 || V < -4; }
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000083
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000084 APFloat *getFpValPtr()
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000085 { return reinterpret_cast<APFloat *>(&FpValBuf.buffer[0]); }
86
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000087 const APFloat *getFpValPtr() const
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000088 { return reinterpret_cast<const APFloat *>(&FpValBuf.buffer[0]); }
Shuxin Yang37a1efe2012-12-18 23:10:12 +000089
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000090 const APFloat &getFpVal() const {
Shuxin Yang37a1efe2012-12-18 23:10:12 +000091 assert(IsFp && BufHasFpVal && "Incorret state");
David Greene530430b2013-01-14 21:04:40 +000092 return *getFpValPtr();
Shuxin Yang37a1efe2012-12-18 23:10:12 +000093 }
94
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000095 APFloat &getFpVal() {
Jim Grosbachbdbd7342013-04-05 21:20:12 +000096 assert(IsFp && BufHasFpVal && "Incorret state");
97 return *getFpValPtr();
98 }
99
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000100 bool isInt() const { return !IsFp; }
101
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000102 // If the coefficient is represented by an integer, promote it to a
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000103 // floating point.
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000104 void convertToFpType(const fltSemantics &Sem);
105
106 // Construct an APFloat from a signed integer.
107 // TODO: We should get rid of this function when APFloat can be constructed
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000108 // from an *SIGNED* integer.
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000109 APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
Shuxin Yang5b841c42012-12-19 01:10:17 +0000110
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000111 bool IsFp = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000112
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000113 // True iff FpValBuf contains an instance of APFloat.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000114 bool BufHasFpVal = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000115
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000116 // The integer coefficient of an individual addend is either 1 or -1,
117 // and we try to simplify at most 4 addends from neighboring at most
118 // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
119 // is overkill of this end.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000120 short IntVal = 0;
Shuxin Yang5b841c42012-12-19 01:10:17 +0000121
122 AlignedCharArrayUnion<APFloat> FpValBuf;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000123 };
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000124
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000125 /// FAddend is used to represent floating-point addend. An addend is
126 /// represented as <C, V>, where the V is a symbolic value, and C is a
127 /// constant coefficient. A constant addend is represented as <C, 0>.
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000128 class FAddend {
129 public:
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000130 FAddend() = default;
131
132 void operator+=(const FAddend &T) {
133 assert((Val == T.Val) && "Symbolic-values disagree");
134 Coeff += T.Coeff;
135 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000136
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000137 Value *getSymVal() const { return Val; }
138 const FAddendCoef &getCoef() const { return Coeff; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000139
Craig Topperf40110f2014-04-25 05:29:35 +0000140 bool isConstant() const { return Val == nullptr; }
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000141 bool isZero() const { return Coeff.isZero(); }
142
Richard Trieu7a083812016-02-18 22:09:30 +0000143 void set(short Coefficient, Value *V) {
144 Coeff.set(Coefficient);
145 Val = V;
146 }
147 void set(const APFloat &Coefficient, Value *V) {
148 Coeff.set(Coefficient);
149 Val = V;
150 }
151 void set(const ConstantFP *Coefficient, Value *V) {
152 Coeff.set(Coefficient->getValueAPF());
153 Val = V;
154 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000155
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000156 void negate() { Coeff.negate(); }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000157
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000158 /// Drill down the U-D chain one step to find the definition of V, and
159 /// try to break the definition into one or two addends.
160 static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000161
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000162 /// Similar to FAddend::drillDownOneStep() except that the value being
163 /// splitted is the addend itself.
164 unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000165
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000166 private:
167 void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000168
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000169 // This addend has the value of "Coeff * Val".
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000170 Value *Val = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000171 FAddendCoef Coeff;
172 };
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000173
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000174 /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
175 /// with its neighboring at most two instructions.
176 ///
177 class FAddCombine {
178 public:
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000179 FAddCombine(InstCombiner::BuilderTy &B) : Builder(B) {}
180
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000181 Value *simplify(Instruction *FAdd);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000182
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000183 private:
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000184 using AddendVect = SmallVector<const FAddend *, 4>;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000185
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000186 Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000187
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000188 /// Convert given addend to a Value
189 Value *createAddendVal(const FAddend &A, bool& NeedNeg);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000190
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000191 /// Return the number of instructions needed to emit the N-ary addition.
192 unsigned calcInstrNumber(const AddendVect& Vect);
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000193
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000194 Value *createFSub(Value *Opnd0, Value *Opnd1);
195 Value *createFAdd(Value *Opnd0, Value *Opnd1);
196 Value *createFMul(Value *Opnd0, Value *Opnd1);
197 Value *createFNeg(Value *V);
198 Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
Owen Anderson1664dc82014-01-20 07:44:53 +0000199 void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000200
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000201 // Debugging stuff are clustered here.
202 #ifndef NDEBUG
203 unsigned CreateInstrNum;
204 void initCreateInstNum() { CreateInstrNum = 0; }
205 void incCreateInstNum() { CreateInstrNum++; }
206 #else
207 void initCreateInstNum() {}
208 void incCreateInstNum() {}
209 #endif
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000210
211 InstCombiner::BuilderTy &Builder;
212 Instruction *Instr = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000213 };
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000214
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000215} // end anonymous namespace
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000216
217//===----------------------------------------------------------------------===//
218//
219// Implementation of
220// {FAddendCoef, FAddend, FAddition, FAddCombine}.
221//
222//===----------------------------------------------------------------------===//
223FAddendCoef::~FAddendCoef() {
224 if (BufHasFpVal)
225 getFpValPtr()->~APFloat();
226}
227
228void FAddendCoef::set(const APFloat& C) {
229 APFloat *P = getFpValPtr();
230
231 if (isInt()) {
232 // As the buffer is meanless byte stream, we cannot call
233 // APFloat::operator=().
234 new(P) APFloat(C);
235 } else
236 *P = C;
237
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000238 IsFp = BufHasFpVal = true;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000239}
240
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000241void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
242 if (!isInt())
243 return;
244
245 APFloat *P = getFpValPtr();
246 if (IntVal > 0)
247 new(P) APFloat(Sem, IntVal);
248 else {
249 new(P) APFloat(Sem, 0 - IntVal);
250 P->changeSign();
251 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000252 IsFp = BufHasFpVal = true;
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000253}
254
255APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
256 if (Val >= 0)
257 return APFloat(Sem, Val);
258
259 APFloat T(Sem, 0 - Val);
260 T.changeSign();
261
262 return T;
263}
264
265void FAddendCoef::operator=(const FAddendCoef &That) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000266 if (That.isInt())
267 set(That.IntVal);
268 else
269 set(That.getFpVal());
270}
271
272void FAddendCoef::operator+=(const FAddendCoef &That) {
Serge Pavlovc7ff5b32020-03-26 14:51:09 +0700273 RoundingMode RndMode = RoundingMode::NearestTiesToEven;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000274 if (isInt() == That.isInt()) {
275 if (isInt())
276 IntVal += That.IntVal;
277 else
278 getFpVal().add(That.getFpVal(), RndMode);
279 return;
280 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000281
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000282 if (isInt()) {
283 const APFloat &T = That.getFpVal();
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000284 convertToFpType(T.getSemantics());
285 getFpVal().add(T, RndMode);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000286 return;
287 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000288
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000289 APFloat &T = getFpVal();
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000290 T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000291}
292
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000293void FAddendCoef::operator*=(const FAddendCoef &That) {
294 if (That.isOne())
295 return;
296
297 if (That.isMinusOne()) {
298 negate();
299 return;
300 }
301
302 if (isInt() && That.isInt()) {
303 int Res = IntVal * (int)That.IntVal;
304 assert(!insaneIntVal(Res) && "Insane int value");
305 IntVal = Res;
306 return;
307 }
308
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000309 const fltSemantics &Semantic =
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000310 isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
311
312 if (isInt())
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000313 convertToFpType(Semantic);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000314 APFloat &F0 = getFpVal();
315
316 if (That.isInt())
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000317 F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
318 APFloat::rmNearestTiesToEven);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000319 else
320 F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000321}
322
323void FAddendCoef::negate() {
324 if (isInt())
325 IntVal = 0 - IntVal;
326 else
327 getFpVal().changeSign();
328}
329
330Value *FAddendCoef::getValue(Type *Ty) const {
331 return isInt() ?
332 ConstantFP::get(Ty, float(IntVal)) :
333 ConstantFP::get(Ty->getContext(), getFpVal());
334}
335
336// The definition of <Val> Addends
337// =========================================
338// A + B <1, A>, <1,B>
339// A - B <1, A>, <1,B>
340// 0 - B <-1, B>
341// C * A, <C, A>
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000342// A + C <1, A> <C, NULL>
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000343// 0 +/- 0 <0, NULL> (corner case)
344//
345// Legend: A and B are not constant, C is constant
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000346unsigned FAddend::drillValueDownOneStep
347 (Value *Val, FAddend &Addend0, FAddend &Addend1) {
Craig Topperf40110f2014-04-25 05:29:35 +0000348 Instruction *I = nullptr;
349 if (!Val || !(I = dyn_cast<Instruction>(Val)))
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000350 return 0;
351
352 unsigned Opcode = I->getOpcode();
353
354 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
355 ConstantFP *C0, *C1;
356 Value *Opnd0 = I->getOperand(0);
357 Value *Opnd1 = I->getOperand(1);
358 if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +0000359 Opnd0 = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000360
361 if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +0000362 Opnd1 = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000363
364 if (Opnd0) {
365 if (!C0)
366 Addend0.set(1, Opnd0);
367 else
Craig Topperf40110f2014-04-25 05:29:35 +0000368 Addend0.set(C0, nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000369 }
370
371 if (Opnd1) {
372 FAddend &Addend = Opnd0 ? Addend1 : Addend0;
373 if (!C1)
374 Addend.set(1, Opnd1);
375 else
Craig Topperf40110f2014-04-25 05:29:35 +0000376 Addend.set(C1, nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000377 if (Opcode == Instruction::FSub)
378 Addend.negate();
379 }
380
381 if (Opnd0 || Opnd1)
382 return Opnd0 && Opnd1 ? 2 : 1;
383
384 // Both operands are zero. Weird!
Craig Topperf40110f2014-04-25 05:29:35 +0000385 Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000386 return 1;
387 }
388
389 if (I->getOpcode() == Instruction::FMul) {
390 Value *V0 = I->getOperand(0);
391 Value *V1 = I->getOperand(1);
392 if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
393 Addend0.set(C, V1);
394 return 1;
395 }
396
397 if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
398 Addend0.set(C, V0);
399 return 1;
400 }
401 }
402
403 return 0;
404}
405
406// Try to break *this* addend into two addends. e.g. Suppose this addend is
407// <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
408// i.e. <2.3, X> and <2.3, Y>.
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000409unsigned FAddend::drillAddendDownOneStep
410 (FAddend &Addend0, FAddend &Addend1) const {
411 if (isConstant())
412 return 0;
413
414 unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000415 if (!BreakNum || Coeff.isOne())
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000416 return BreakNum;
417
418 Addend0.Scale(Coeff);
419
420 if (BreakNum == 2)
421 Addend1.Scale(Coeff);
422
423 return BreakNum;
424}
425
426Value *FAddCombine::simplify(Instruction *I) {
Warren Ristow8b2f27c2018-04-14 19:18:28 +0000427 assert(I->hasAllowReassoc() && I->hasNoSignedZeros() &&
428 "Expected 'reassoc'+'nsz' instruction");
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000429
430 // Currently we are not able to handle vector type.
431 if (I->getType()->isVectorTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000432 return nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000433
434 assert((I->getOpcode() == Instruction::FAdd ||
435 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
436
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000437 // Save the instruction before calling other member-functions.
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000438 Instr = I;
439
440 FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
441
442 unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
443
444 // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
445 unsigned Opnd0_ExpNum = 0;
446 unsigned Opnd1_ExpNum = 0;
447
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000448 if (!Opnd0.isConstant())
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000449 Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
450
451 // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
452 if (OpndNum == 2 && !Opnd1.isConstant())
453 Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
454
455 // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
456 if (Opnd0_ExpNum && Opnd1_ExpNum) {
457 AddendVect AllOpnds;
458 AllOpnds.push_back(&Opnd0_0);
459 AllOpnds.push_back(&Opnd1_0);
460 if (Opnd0_ExpNum == 2)
461 AllOpnds.push_back(&Opnd0_1);
462 if (Opnd1_ExpNum == 2)
463 AllOpnds.push_back(&Opnd1_1);
464
465 // Compute instruction quota. We should save at least one instruction.
466 unsigned InstQuota = 0;
467
468 Value *V0 = I->getOperand(0);
469 Value *V1 = I->getOperand(1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000470 InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000471 (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
472
473 if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
474 return R;
475 }
476
477 if (OpndNum != 2) {
478 // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
479 // splitted into two addends, say "V = X - Y", the instruction would have
480 // been optimized into "I = Y - X" in the previous steps.
481 //
482 const FAddendCoef &CE = Opnd0.getCoef();
Craig Topperf40110f2014-04-25 05:29:35 +0000483 return CE.isOne() ? Opnd0.getSymVal() : nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000484 }
485
486 // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
487 if (Opnd1_ExpNum) {
488 AddendVect AllOpnds;
489 AllOpnds.push_back(&Opnd0);
490 AllOpnds.push_back(&Opnd1_0);
491 if (Opnd1_ExpNum == 2)
492 AllOpnds.push_back(&Opnd1_1);
493
494 if (Value *R = simplifyFAdd(AllOpnds, 1))
495 return R;
496 }
497
498 // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
499 if (Opnd0_ExpNum) {
500 AddendVect AllOpnds;
501 AllOpnds.push_back(&Opnd1);
502 AllOpnds.push_back(&Opnd0_0);
503 if (Opnd0_ExpNum == 2)
504 AllOpnds.push_back(&Opnd0_1);
505
506 if (Value *R = simplifyFAdd(AllOpnds, 1))
507 return R;
508 }
509
Sanjay Pateldc185ee2018-08-12 15:48:26 +0000510 return nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000511}
512
513Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000514 unsigned AddendNum = Addends.size();
515 assert(AddendNum <= 4 && "Too many addends");
516
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000517 // For saving intermediate results;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000518 unsigned NextTmpIdx = 0;
519 FAddend TmpResult[3];
520
521 // Points to the constant addend of the resulting simplified expression.
522 // If the resulting expr has constant-addend, this constant-addend is
523 // desirable to reside at the top of the resulting expression tree. Placing
524 // constant close to supper-expr(s) will potentially reveal some optimization
525 // opportunities in super-expr(s).
Craig Topperf40110f2014-04-25 05:29:35 +0000526 const FAddend *ConstAdd = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000527
528 // Simplified addends are placed <SimpVect>.
529 AddendVect SimpVect;
530
531 // The outer loop works on one symbolic-value at a time. Suppose the input
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000532 // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000533 // The symbolic-values will be processed in this order: x, y, z.
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000534 for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
535
536 const FAddend *ThisAddend = Addends[SymIdx];
537 if (!ThisAddend) {
538 // This addend was processed before.
539 continue;
540 }
541
542 Value *Val = ThisAddend->getSymVal();
543 unsigned StartIdx = SimpVect.size();
544 SimpVect.push_back(ThisAddend);
545
546 // The inner loop collects addends sharing same symbolic-value, and these
547 // addends will be later on folded into a single addend. Following above
548 // example, if the symbolic value "y" is being processed, the inner loop
549 // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
550 // be later on folded into "<b1+b2, y>".
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000551 for (unsigned SameSymIdx = SymIdx + 1;
552 SameSymIdx < AddendNum; SameSymIdx++) {
553 const FAddend *T = Addends[SameSymIdx];
554 if (T && T->getSymVal() == Val) {
555 // Set null such that next iteration of the outer loop will not process
556 // this addend again.
Craig Topperf40110f2014-04-25 05:29:35 +0000557 Addends[SameSymIdx] = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000558 SimpVect.push_back(T);
559 }
560 }
561
562 // If multiple addends share same symbolic value, fold them together.
563 if (StartIdx + 1 != SimpVect.size()) {
564 FAddend &R = TmpResult[NextTmpIdx ++];
565 R = *SimpVect[StartIdx];
566 for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
567 R += *SimpVect[Idx];
568
569 // Pop all addends being folded and push the resulting folded addend.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000570 SimpVect.resize(StartIdx);
Craig Topperf40110f2014-04-25 05:29:35 +0000571 if (Val) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000572 if (!R.isZero()) {
573 SimpVect.push_back(&R);
574 }
575 } else {
576 // Don't push constant addend at this time. It will be the last element
577 // of <SimpVect>.
578 ConstAdd = &R;
579 }
580 }
581 }
582
Craig Topper58713212013-07-15 04:27:47 +0000583 assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000584 "out-of-bound access");
585
586 if (ConstAdd)
587 SimpVect.push_back(ConstAdd);
588
589 Value *Result;
590 if (!SimpVect.empty())
591 Result = createNaryFAdd(SimpVect, InstrQuota);
592 else {
593 // The addition is folded to 0.0.
594 Result = ConstantFP::get(Instr->getType(), 0.0);
595 }
596
597 return Result;
598}
599
600Value *FAddCombine::createNaryFAdd
601 (const AddendVect &Opnds, unsigned InstrQuota) {
602 assert(!Opnds.empty() && "Expect at least one addend");
603
604 // Step 1: Check if the # of instructions needed exceeds the quota.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000605
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000606 unsigned InstrNeeded = calcInstrNumber(Opnds);
607 if (InstrNeeded > InstrQuota)
Craig Topperf40110f2014-04-25 05:29:35 +0000608 return nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000609
610 initCreateInstNum();
611
612 // step 2: Emit the N-ary addition.
613 // Note that at most three instructions are involved in Fadd-InstCombine: the
614 // addition in question, and at most two neighboring instructions.
615 // The resulting optimized addition should have at least one less instruction
616 // than the original addition expression tree. This implies that the resulting
617 // N-ary addition has at most two instructions, and we don't need to worry
618 // about tree-height when constructing the N-ary addition.
619
Craig Topperf40110f2014-04-25 05:29:35 +0000620 Value *LastVal = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000621 bool LastValNeedNeg = false;
622
623 // Iterate the addends, creating fadd/fsub using adjacent two addends.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000624 for (const FAddend *Opnd : Opnds) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000625 bool NeedNeg;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000626 Value *V = createAddendVal(*Opnd, NeedNeg);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000627 if (!LastVal) {
628 LastVal = V;
629 LastValNeedNeg = NeedNeg;
630 continue;
631 }
632
633 if (LastValNeedNeg == NeedNeg) {
634 LastVal = createFAdd(LastVal, V);
635 continue;
636 }
637
638 if (LastValNeedNeg)
639 LastVal = createFSub(V, LastVal);
640 else
641 LastVal = createFSub(LastVal, V);
642
643 LastValNeedNeg = false;
644 }
645
646 if (LastValNeedNeg) {
647 LastVal = createFNeg(LastVal);
648 }
649
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000650#ifndef NDEBUG
651 assert(CreateInstrNum == InstrNeeded &&
652 "Inconsistent in instruction numbers");
653#endif
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000654
655 return LastVal;
656}
657
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000658Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000659 Value *V = Builder.CreateFSub(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000660 if (Instruction *I = dyn_cast<Instruction>(V))
661 createInstPostProc(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000662 return V;
663}
664
665Value *FAddCombine::createFNeg(Value *V) {
Simon Molld871ef42020-03-10 16:05:31 +0100666 Value *NewV = Builder.CreateFNeg(V);
Owen Anderson1664dc82014-01-20 07:44:53 +0000667 if (Instruction *I = dyn_cast<Instruction>(NewV))
668 createInstPostProc(I, true); // fneg's don't receive instruction numbers.
669 return NewV;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000670}
671
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000672Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000673 Value *V = Builder.CreateFAdd(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000674 if (Instruction *I = dyn_cast<Instruction>(V))
675 createInstPostProc(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000676 return V;
677}
678
679Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000680 Value *V = Builder.CreateFMul(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000681 if (Instruction *I = dyn_cast<Instruction>(V))
682 createInstPostProc(I);
683 return V;
684}
685
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000686void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000687 NewInstr->setDebugLoc(Instr->getDebugLoc());
688
689 // Keep track of the number of instruction created.
Owen Anderson1664dc82014-01-20 07:44:53 +0000690 if (!NoNumber)
691 incCreateInstNum();
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000692
693 // Propagate fast-math flags
694 NewInstr->setFastMathFlags(Instr->getFastMathFlags());
695}
696
697// Return the number of instruction needed to emit the N-ary addition.
698// NOTE: Keep this function in sync with createAddendVal().
699unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
700 unsigned OpndNum = Opnds.size();
701 unsigned InstrNeeded = OpndNum - 1;
702
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000703 // The number of addends in the form of "(-1)*x".
704 unsigned NegOpndNum = 0;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000705
706 // Adjust the number of instructions needed to emit the N-ary add.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000707 for (const FAddend *Opnd : Opnds) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000708 if (Opnd->isConstant())
709 continue;
710
Matt Arsenault02907f32017-04-24 17:24:37 +0000711 // The constant check above is really for a few special constant
712 // coefficients.
713 if (isa<UndefValue>(Opnd->getSymVal()))
714 continue;
715
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000716 const FAddendCoef &CE = Opnd->getCoef();
717 if (CE.isMinusOne() || CE.isMinusTwo())
718 NegOpndNum++;
719
720 // Let the addend be "c * x". If "c == +/-1", the value of the addend
721 // is immediately available; otherwise, it needs exactly one instruction
722 // to evaluate the value.
723 if (!CE.isMinusOne() && !CE.isOne())
724 InstrNeeded++;
725 }
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000726 return InstrNeeded;
727}
728
729// Input Addend Value NeedNeg(output)
730// ================================================================
731// Constant C C false
732// <+/-1, V> V coefficient is -1
733// <2/-2, V> "fadd V, V" coefficient is -2
734// <C, V> "fmul V, C" false
735//
736// NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000737Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000738 const FAddendCoef &Coeff = Opnd.getCoef();
739
740 if (Opnd.isConstant()) {
741 NeedNeg = false;
742 return Coeff.getValue(Instr->getType());
743 }
744
745 Value *OpndVal = Opnd.getSymVal();
746
747 if (Coeff.isMinusOne() || Coeff.isOne()) {
748 NeedNeg = Coeff.isMinusOne();
749 return OpndVal;
750 }
751
752 if (Coeff.isTwo() || Coeff.isMinusTwo()) {
753 NeedNeg = Coeff.isMinusTwo();
754 return createFAdd(OpndVal, OpndVal);
755 }
756
757 NeedNeg = false;
758 return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
759}
760
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000761// Checks if any operand is negative and we can convert add to sub.
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000762// This function checks for following negative patterns
763// ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
764// ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
765// XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000766static Value *checkForNegativeOperand(BinaryOperator &I,
Craig Topperbb4069e2017-07-07 23:16:26 +0000767 InstCombiner::BuilderTy &Builder) {
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000768 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000769
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000770 // This function creates 2 instructions to replace ADD, we need at least one
771 // of LHS or RHS to have one use to ensure benefit in transform.
772 if (!LHS->hasOneUse() && !RHS->hasOneUse())
773 return nullptr;
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000774
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000775 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
776 const APInt *C1 = nullptr, *C2 = nullptr;
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000777
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000778 // if ONE is on other side, swap
779 if (match(RHS, m_Add(m_Value(X), m_One())))
780 std::swap(LHS, RHS);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000781
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000782 if (match(LHS, m_Add(m_Value(X), m_One()))) {
783 // if XOR on other side, swap
784 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
785 std::swap(X, RHS);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000786
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000787 if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
788 // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
789 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
790 if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000791 Value *NewAnd = Builder.CreateAnd(Z, *C1);
792 return Builder.CreateSub(RHS, NewAnd, "sub");
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000793 } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
794 // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
795 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
Craig Topperbb4069e2017-07-07 23:16:26 +0000796 Value *NewOr = Builder.CreateOr(Z, ~(*C1));
797 return Builder.CreateSub(RHS, NewOr, "sub");
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000798 }
799 }
800 }
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000801
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000802 // Restore LHS and RHS
803 LHS = I.getOperand(0);
804 RHS = I.getOperand(1);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000805
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000806 // if XOR is on other side, swap
807 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
808 std::swap(LHS, RHS);
809
810 // C2 is ODD
811 // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
812 // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
813 if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
814 if (C1->countTrailingZeros() == 0)
815 if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000816 Value *NewOr = Builder.CreateOr(Z, ~(*C2));
817 return Builder.CreateSub(RHS, NewOr, "sub");
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000818 }
819 return nullptr;
820}
821
Sanjay Patel4a47f5f2019-02-28 19:05:26 +0000822/// Wrapping flags may allow combining constants separated by an extend.
823static Instruction *foldNoWrapAdd(BinaryOperator &Add,
824 InstCombiner::BuilderTy &Builder) {
825 Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
826 Type *Ty = Add.getType();
827 Constant *Op1C;
828 if (!match(Op1, m_Constant(Op1C)))
829 return nullptr;
830
831 // Try this match first because it results in an add in the narrow type.
832 // (zext (X +nuw C2)) + C1 --> zext (X + (C2 + trunc(C1)))
833 Value *X;
834 const APInt *C1, *C2;
835 if (match(Op1, m_APInt(C1)) &&
836 match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_APInt(C2))))) &&
837 C1->isNegative() && C1->sge(-C2->sext(C1->getBitWidth()))) {
838 Constant *NewC =
839 ConstantInt::get(X->getType(), *C2 + C1->trunc(C2->getBitWidth()));
840 return new ZExtInst(Builder.CreateNUWAdd(X, NewC), Ty);
841 }
842
843 // More general combining of constants in the wide type.
844 // (sext (X +nsw NarrowC)) + C --> (sext X) + (sext(NarrowC) + C)
845 Constant *NarrowC;
846 if (match(Op0, m_OneUse(m_SExt(m_NSWAdd(m_Value(X), m_Constant(NarrowC)))))) {
847 Constant *WideC = ConstantExpr::getSExt(NarrowC, Ty);
848 Constant *NewC = ConstantExpr::getAdd(WideC, Op1C);
849 Value *WideX = Builder.CreateSExt(X, Ty);
850 return BinaryOperator::CreateAdd(WideX, NewC);
851 }
852 // (zext (X +nuw NarrowC)) + C --> (zext X) + (zext(NarrowC) + C)
853 if (match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_Constant(NarrowC)))))) {
854 Constant *WideC = ConstantExpr::getZExt(NarrowC, Ty);
855 Constant *NewC = ConstantExpr::getAdd(WideC, Op1C);
856 Value *WideX = Builder.CreateZExt(X, Ty);
857 return BinaryOperator::CreateAdd(WideX, NewC);
858 }
859
860 return nullptr;
861}
862
Sanjay Patel8d810fe2017-10-13 16:43:58 +0000863Instruction *InstCombiner::foldAddWithConstant(BinaryOperator &Add) {
Sanjay Patel4133d4a2017-05-10 00:07:16 +0000864 Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
Sanjay Patel21506512017-10-13 16:29:38 +0000865 Constant *Op1C;
866 if (!match(Op1, m_Constant(Op1C)))
867 return nullptr;
868
Sanjay Patel8fdd87f2018-02-28 16:36:24 +0000869 if (Instruction *NV = foldBinOpIntoSelectOrPhi(Add))
Sanjay Patel8d810fe2017-10-13 16:43:58 +0000870 return NV;
871
Roman Lebedev886c4ef2019-05-31 09:47:04 +0000872 Value *X;
873 Constant *Op00C;
874
875 // add (sub C1, X), C2 --> sub (add C1, C2), X
876 if (match(Op0, m_Sub(m_Constant(Op00C), m_Value(X))))
877 return BinaryOperator::CreateSub(ConstantExpr::getAdd(Op00C, Op1C), X);
878
879 Value *Y;
Sanjay Patel818b2532018-07-28 16:48:44 +0000880
881 // add (sub X, Y), -1 --> add (not Y), X
882 if (match(Op0, m_OneUse(m_Sub(m_Value(X), m_Value(Y)))) &&
883 match(Op1, m_AllOnes()))
884 return BinaryOperator::CreateAdd(Builder.CreateNot(Y), X);
885
Sanjay Patelf0242de2017-10-13 20:29:11 +0000886 // zext(bool) + C -> bool ? C + 1 : C
887 if (match(Op0, m_ZExt(m_Value(X))) &&
888 X->getType()->getScalarSizeInBits() == 1)
Sanjay Patel76ed9ea2017-10-13 17:00:47 +0000889 return SelectInst::Create(X, AddOne(Op1C), Op1);
Roman Lebedev796fa662019-12-05 20:44:22 +0300890 // sext(bool) + C -> bool ? C - 1 : C
891 if (match(Op0, m_SExt(m_Value(X))) &&
892 X->getType()->getScalarSizeInBits() == 1)
893 return SelectInst::Create(X, SubOne(Op1C), Op1);
Sanjay Patel21506512017-10-13 16:29:38 +0000894
Sanjay Patelf0242de2017-10-13 20:29:11 +0000895 // ~X + C --> (C-1) - X
896 if (match(Op0, m_Not(m_Value(X))))
897 return BinaryOperator::CreateSub(SubOne(Op1C), X);
898
Sanjay Patel4133d4a2017-05-10 00:07:16 +0000899 const APInt *C;
900 if (!match(Op1, m_APInt(C)))
901 return nullptr;
902
Robert Lougher8681ef82019-05-07 19:36:41 +0000903 // (X | C2) + C --> (X | C2) ^ C2 iff (C2 == -C)
904 const APInt *C2;
905 if (match(Op0, m_Or(m_Value(), m_APInt(C2))) && *C2 == -*C)
906 return BinaryOperator::CreateXor(Op0, ConstantInt::get(Add.getType(), *C2));
907
Sanjay Patel4133d4a2017-05-10 00:07:16 +0000908 if (C->isSignMask()) {
909 // If wrapping is not allowed, then the addition must set the sign bit:
910 // X + (signmask) --> X | signmask
911 if (Add.hasNoSignedWrap() || Add.hasNoUnsignedWrap())
912 return BinaryOperator::CreateOr(Op0, Op1);
913
914 // If wrapping is allowed, then the addition flips the sign bit of LHS:
915 // X + (signmask) --> X ^ signmask
916 return BinaryOperator::CreateXor(Op0, Op1);
917 }
918
Sanjay Patel4133d4a2017-05-10 00:07:16 +0000919 // Is this add the last step in a convoluted sext?
920 // add(zext(xor i16 X, -32768), -32768) --> sext X
Sanjay Patel76ed9ea2017-10-13 17:00:47 +0000921 Type *Ty = Add.getType();
Sanjay Patel4133d4a2017-05-10 00:07:16 +0000922 if (match(Op0, m_ZExt(m_Xor(m_Value(X), m_APInt(C2)))) &&
923 C2->isMinSignedValue() && C2->sext(Ty->getScalarSizeInBits()) == *C)
924 return CastInst::Create(Instruction::SExt, X, Ty);
925
Sanjay Patel2f3ead72017-06-25 14:15:28 +0000926 if (C->isOneValue() && Op0->hasOneUse()) {
927 // add (sext i1 X), 1 --> zext (not X)
928 // TODO: The smallest IR representation is (select X, 0, 1), and that would
929 // not require the one-use check. But we need to remove a transform in
930 // visitSelect and make sure that IR value tracking for select is equal or
931 // better than for these ops.
932 if (match(Op0, m_SExt(m_Value(X))) &&
933 X->getType()->getScalarSizeInBits() == 1)
934 return new ZExtInst(Builder.CreateNot(X), Ty);
935
936 // Shifts and add used to flip and mask off the low bit:
937 // add (ashr (shl i32 X, 31), 31), 1 --> and (not X), 1
938 const APInt *C3;
939 if (match(Op0, m_AShr(m_Shl(m_Value(X), m_APInt(C2)), m_APInt(C3))) &&
940 C2 == C3 && *C2 == Ty->getScalarSizeInBits() - 1) {
941 Value *NotX = Builder.CreateNot(X);
942 return BinaryOperator::CreateAnd(NotX, ConstantInt::get(Ty, 1));
943 }
Sanjay Patel2e069f22017-05-10 13:56:52 +0000944 }
945
Sanjay Patel4133d4a2017-05-10 00:07:16 +0000946 return nullptr;
947}
948
Sanjoy Das6f1937b2018-04-26 20:52:28 +0000949// Matches multiplication expression Op * C where C is a constant. Returns the
950// constant value in C and the other operand in Op. Returns true if such a
951// match is found.
952static bool MatchMul(Value *E, Value *&Op, APInt &C) {
953 const APInt *AI;
954 if (match(E, m_Mul(m_Value(Op), m_APInt(AI)))) {
955 C = *AI;
956 return true;
957 }
958 if (match(E, m_Shl(m_Value(Op), m_APInt(AI)))) {
959 C = APInt(AI->getBitWidth(), 1);
960 C <<= *AI;
961 return true;
962 }
963 return false;
964}
965
966// Matches remainder expression Op % C where C is a constant. Returns the
967// constant value in C and the other operand in Op. Returns the signedness of
968// the remainder operation in IsSigned. Returns true if such a match is
969// found.
970static bool MatchRem(Value *E, Value *&Op, APInt &C, bool &IsSigned) {
971 const APInt *AI;
972 IsSigned = false;
973 if (match(E, m_SRem(m_Value(Op), m_APInt(AI)))) {
974 IsSigned = true;
975 C = *AI;
976 return true;
977 }
978 if (match(E, m_URem(m_Value(Op), m_APInt(AI)))) {
979 C = *AI;
980 return true;
981 }
982 if (match(E, m_And(m_Value(Op), m_APInt(AI))) && (*AI + 1).isPowerOf2()) {
983 C = *AI + 1;
984 return true;
985 }
986 return false;
987}
988
989// Matches division expression Op / C with the given signedness as indicated
990// by IsSigned, where C is a constant. Returns the constant value in C and the
991// other operand in Op. Returns true if such a match is found.
992static bool MatchDiv(Value *E, Value *&Op, APInt &C, bool IsSigned) {
993 const APInt *AI;
994 if (IsSigned && match(E, m_SDiv(m_Value(Op), m_APInt(AI)))) {
995 C = *AI;
996 return true;
997 }
998 if (!IsSigned) {
999 if (match(E, m_UDiv(m_Value(Op), m_APInt(AI)))) {
1000 C = *AI;
1001 return true;
1002 }
1003 if (match(E, m_LShr(m_Value(Op), m_APInt(AI)))) {
1004 C = APInt(AI->getBitWidth(), 1);
1005 C <<= *AI;
1006 return true;
1007 }
1008 }
1009 return false;
1010}
1011
1012// Returns whether C0 * C1 with the given signedness overflows.
1013static bool MulWillOverflow(APInt &C0, APInt &C1, bool IsSigned) {
1014 bool overflow;
1015 if (IsSigned)
1016 (void)C0.smul_ov(C1, overflow);
1017 else
1018 (void)C0.umul_ov(C1, overflow);
1019 return overflow;
1020}
1021
1022// Simplifies X % C0 + (( X / C0 ) % C1) * C0 to X % (C0 * C1), where (C0 * C1)
1023// does not overflow.
1024Value *InstCombiner::SimplifyAddWithRemainder(BinaryOperator &I) {
1025 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1026 Value *X, *MulOpV;
1027 APInt C0, MulOpC;
1028 bool IsSigned;
1029 // Match I = X % C0 + MulOpV * C0
1030 if (((MatchRem(LHS, X, C0, IsSigned) && MatchMul(RHS, MulOpV, MulOpC)) ||
1031 (MatchRem(RHS, X, C0, IsSigned) && MatchMul(LHS, MulOpV, MulOpC))) &&
1032 C0 == MulOpC) {
1033 Value *RemOpV;
1034 APInt C1;
1035 bool Rem2IsSigned;
1036 // Match MulOpC = RemOpV % C1
1037 if (MatchRem(MulOpV, RemOpV, C1, Rem2IsSigned) &&
1038 IsSigned == Rem2IsSigned) {
1039 Value *DivOpV;
1040 APInt DivOpC;
1041 // Match RemOpV = X / C0
1042 if (MatchDiv(RemOpV, DivOpV, DivOpC, IsSigned) && X == DivOpV &&
1043 C0 == DivOpC && !MulWillOverflow(C0, C1, IsSigned)) {
Florian Hahnc8c14d92020-03-10 14:22:19 +00001044 Value *NewDivisor = ConstantInt::get(X->getType(), C0 * C1);
Sanjoy Das6f1937b2018-04-26 20:52:28 +00001045 return IsSigned ? Builder.CreateSRem(X, NewDivisor, "srem")
1046 : Builder.CreateURem(X, NewDivisor, "urem");
1047 }
1048 }
1049 }
1050
1051 return nullptr;
1052}
1053
Roman Lebedevcbf84462018-06-06 19:38:27 +00001054/// Fold
1055/// (1 << NBits) - 1
1056/// Into:
1057/// ~(-(1 << NBits))
1058/// Because a 'not' is better for bit-tracking analysis and other transforms
1059/// than an 'add'. The new shl is always nsw, and is nuw if old `and` was.
1060static Instruction *canonicalizeLowbitMask(BinaryOperator &I,
1061 InstCombiner::BuilderTy &Builder) {
1062 Value *NBits;
1063 if (!match(&I, m_Add(m_OneUse(m_Shl(m_One(), m_Value(NBits))), m_AllOnes())))
1064 return nullptr;
1065
1066 Constant *MinusOne = Constant::getAllOnesValue(NBits->getType());
1067 Value *NotMask = Builder.CreateShl(MinusOne, NBits, "notmask");
1068 // Be wary of constant folding.
1069 if (auto *BOp = dyn_cast<BinaryOperator>(NotMask)) {
1070 // Always NSW. But NUW propagates from `add`.
1071 BOp->setHasNoSignedWrap();
1072 BOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1073 }
1074
1075 return BinaryOperator::CreateNot(NotMask, I.getName());
1076}
1077
Sanjay Patel81e8d762019-03-26 17:50:08 +00001078static Instruction *foldToUnsignedSaturatedAdd(BinaryOperator &I) {
1079 assert(I.getOpcode() == Instruction::Add && "Expecting add instruction");
1080 Type *Ty = I.getType();
1081 auto getUAddSat = [&]() {
1082 return Intrinsic::getDeclaration(I.getModule(), Intrinsic::uadd_sat, Ty);
1083 };
1084
1085 // add (umin X, ~Y), Y --> uaddsat X, Y
1086 Value *X, *Y;
1087 if (match(&I, m_c_Add(m_c_UMin(m_Value(X), m_Not(m_Value(Y))),
1088 m_Deferred(Y))))
1089 return CallInst::Create(getUAddSat(), { X, Y });
1090
1091 // add (umin X, ~C), C --> uaddsat X, C
1092 const APInt *C, *NotC;
1093 if (match(&I, m_Add(m_UMin(m_Value(X), m_APInt(NotC)), m_APInt(C))) &&
1094 *C == ~*NotC)
1095 return CallInst::Create(getUAddSat(), { X, ConstantInt::get(Ty, *C) });
1096
1097 return nullptr;
1098}
1099
Roman Lebedev7015a5c2019-10-20 20:52:06 +00001100Instruction *
1101InstCombiner::canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(
1102 BinaryOperator &I) {
Roman Lebedev7cdeac42019-10-07 20:53:27 +00001103 assert((I.getOpcode() == Instruction::Add ||
Roman Lebedev7015a5c2019-10-20 20:52:06 +00001104 I.getOpcode() == Instruction::Or ||
Roman Lebedev7cdeac42019-10-07 20:53:27 +00001105 I.getOpcode() == Instruction::Sub) &&
Roman Lebedev9948fac2019-10-21 08:21:54 +00001106 "Expecting add/or/sub instruction");
Roman Lebedev7cdeac42019-10-07 20:53:27 +00001107
1108 // We have a subtraction/addition between a (potentially truncated) *logical*
1109 // right-shift of X and a "select".
1110 Value *X, *Select;
1111 Instruction *LowBitsToSkip, *Extract;
1112 if (!match(&I, m_c_BinOp(m_TruncOrSelf(m_CombineAnd(
1113 m_LShr(m_Value(X), m_Instruction(LowBitsToSkip)),
1114 m_Instruction(Extract))),
1115 m_Value(Select))))
1116 return nullptr;
1117
Roman Lebedev7015a5c2019-10-20 20:52:06 +00001118 // `add`/`or` is commutative; but for `sub`, "select" *must* be on RHS.
Roman Lebedev7cdeac42019-10-07 20:53:27 +00001119 if (I.getOpcode() == Instruction::Sub && I.getOperand(1) != Select)
1120 return nullptr;
1121
1122 Type *XTy = X->getType();
1123 bool HadTrunc = I.getType() != XTy;
1124
1125 // If there was a truncation of extracted value, then we'll need to produce
1126 // one extra instruction, so we need to ensure one instruction will go away.
1127 if (HadTrunc && !match(&I, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
1128 return nullptr;
1129
1130 // Extraction should extract high NBits bits, with shift amount calculated as:
1131 // low bits to skip = shift bitwidth - high bits to extract
1132 // The shift amount itself may be extended, and we need to look past zero-ext
1133 // when matching NBits, that will matter for matching later.
1134 Constant *C;
1135 Value *NBits;
1136 if (!match(
1137 LowBitsToSkip,
1138 m_ZExtOrSelf(m_Sub(m_Constant(C), m_ZExtOrSelf(m_Value(NBits))))) ||
1139 !match(C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
1140 APInt(C->getType()->getScalarSizeInBits(),
1141 X->getType()->getScalarSizeInBits()))))
1142 return nullptr;
1143
Roman Lebedev7015a5c2019-10-20 20:52:06 +00001144 // Sign-extending value can be zero-extended if we `sub`tract it,
1145 // or sign-extended otherwise.
Roman Lebedev7cdeac42019-10-07 20:53:27 +00001146 auto SkipExtInMagic = [&I](Value *&V) {
Roman Lebedev7015a5c2019-10-20 20:52:06 +00001147 if (I.getOpcode() == Instruction::Sub)
Roman Lebedev7cdeac42019-10-07 20:53:27 +00001148 match(V, m_ZExtOrSelf(m_Value(V)));
Roman Lebedev7015a5c2019-10-20 20:52:06 +00001149 else
1150 match(V, m_SExtOrSelf(m_Value(V)));
Roman Lebedev7cdeac42019-10-07 20:53:27 +00001151 };
1152
1153 // Now, finally validate the sign-extending magic.
1154 // `select` itself may be appropriately extended, look past that.
1155 SkipExtInMagic(Select);
1156
1157 ICmpInst::Predicate Pred;
1158 const APInt *Thr;
1159 Value *SignExtendingValue, *Zero;
1160 bool ShouldSignext;
Roman Lebedev9948fac2019-10-21 08:21:54 +00001161 // It must be a select between two values we will later establish to be a
Roman Lebedev7cdeac42019-10-07 20:53:27 +00001162 // sign-extending value and a zero constant. The condition guarding the
1163 // sign-extension must be based on a sign bit of the same X we had in `lshr`.
1164 if (!match(Select, m_Select(m_ICmp(Pred, m_Specific(X), m_APInt(Thr)),
1165 m_Value(SignExtendingValue), m_Value(Zero))) ||
1166 !isSignBitCheck(Pred, *Thr, ShouldSignext))
1167 return nullptr;
1168
1169 // icmp-select pair is commutative.
1170 if (!ShouldSignext)
1171 std::swap(SignExtendingValue, Zero);
1172
Roman Lebedev7015a5c2019-10-20 20:52:06 +00001173 // If we should not perform sign-extension then we must add/or/subtract zero.
Roman Lebedev7cdeac42019-10-07 20:53:27 +00001174 if (!match(Zero, m_Zero()))
1175 return nullptr;
1176 // Otherwise, it should be some constant, left-shifted by the same NBits we
1177 // had in `lshr`. Said left-shift can also be appropriately extended.
1178 // Again, we must look past zero-ext when looking for NBits.
1179 SkipExtInMagic(SignExtendingValue);
1180 Constant *SignExtendingValueBaseConstant;
1181 if (!match(SignExtendingValue,
1182 m_Shl(m_Constant(SignExtendingValueBaseConstant),
1183 m_ZExtOrSelf(m_Specific(NBits)))))
1184 return nullptr;
Roman Lebedev7015a5c2019-10-20 20:52:06 +00001185 // If we `sub`, then the constant should be one, else it should be all-ones.
1186 if (I.getOpcode() == Instruction::Sub
1187 ? !match(SignExtendingValueBaseConstant, m_One())
1188 : !match(SignExtendingValueBaseConstant, m_AllOnes()))
Roman Lebedev7cdeac42019-10-07 20:53:27 +00001189 return nullptr;
1190
1191 auto *NewAShr = BinaryOperator::CreateAShr(X, LowBitsToSkip,
1192 Extract->getName() + ".sext");
1193 NewAShr->copyIRFlags(Extract); // Preserve `exact`-ness.
1194 if (!HadTrunc)
1195 return NewAShr;
1196
1197 Builder.Insert(NewAShr);
1198 return TruncInst::CreateTruncOrBitCast(NewAShr, I.getType());
1199}
1200
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001201Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001202 if (Value *V = SimplifyAddInst(I.getOperand(0), I.getOperand(1),
1203 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
1204 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001205 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001206
Sanjay Patel70043b72018-07-13 01:18:07 +00001207 if (SimplifyAssociativeOrCommutative(I))
1208 return &I;
1209
Sanjay Patel79dceb22018-10-03 15:20:58 +00001210 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +00001211 return X;
1212
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001213 // (A*B)+(A*C) -> A*(B+C) etc
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001214 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001215 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001216
Sanjay Patel8d810fe2017-10-13 16:43:58 +00001217 if (Instruction *X = foldAddWithConstant(I))
Sanjay Patel4133d4a2017-05-10 00:07:16 +00001218 return X;
Sanjay Patel53c5c3d2017-02-18 22:20:09 +00001219
Sanjay Patel4a47f5f2019-02-28 19:05:26 +00001220 if (Instruction *X = foldNoWrapAdd(I, Builder))
1221 return X;
1222
Sanjay Patel4133d4a2017-05-10 00:07:16 +00001223 // FIXME: This should be moved into the above helper function to allow these
Sanjay Patel21506512017-10-13 16:29:38 +00001224 // transforms for general constant or constant splat vectors.
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001225 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Sanjay Patel21189522017-10-13 18:32:53 +00001226 Type *Ty = I.getType();
Sanjay Patel79acd2a2016-07-16 18:29:26 +00001227 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001228 Value *XorLHS = nullptr; ConstantInt *XorRHS = nullptr;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001229 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Sanjay Patel21189522017-10-13 18:32:53 +00001230 unsigned TySizeBits = Ty->getScalarSizeInBits();
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001231 const APInt &RHSVal = CI->getValue();
Eli Friedmana2cc2872010-01-31 04:29:12 +00001232 unsigned ExtendAmt = 0;
1233 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1234 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1235 if (XorRHS->getValue() == -RHSVal) {
1236 if (RHSVal.isPowerOf2())
1237 ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
1238 else if (XorRHS->getValue().isPowerOf2())
1239 ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
Chris Lattner82aa8882010-01-05 07:18:46 +00001240 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001241
Eli Friedmana2cc2872010-01-31 04:29:12 +00001242 if (ExtendAmt) {
1243 APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
Hal Finkel60db0582014-09-07 18:57:58 +00001244 if (!MaskedValueIsZero(XorLHS, Mask, 0, &I))
Eli Friedmana2cc2872010-01-31 04:29:12 +00001245 ExtendAmt = 0;
1246 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001247
Eli Friedmana2cc2872010-01-31 04:29:12 +00001248 if (ExtendAmt) {
Sanjay Patel21189522017-10-13 18:32:53 +00001249 Constant *ShAmt = ConstantInt::get(Ty, ExtendAmt);
Craig Topperbb4069e2017-07-07 23:16:26 +00001250 Value *NewShl = Builder.CreateShl(XorLHS, ShAmt, "sext");
Eli Friedmana2cc2872010-01-31 04:29:12 +00001251 return BinaryOperator::CreateAShr(NewShl, ShAmt);
Chris Lattner82aa8882010-01-05 07:18:46 +00001252 }
Benjamin Kramerb16bd772011-12-24 17:31:53 +00001253
1254 // If this is a xor that was canonicalized from a sub, turn it back into
1255 // a sub and fuse this add with it.
1256 if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
Craig Topper8205a1a2017-05-24 16:53:07 +00001257 KnownBits LHSKnown = computeKnownBits(XorLHS, 0, &I);
Craig Topperb45eabc2017-04-26 16:39:58 +00001258 if ((XorRHS->getValue() | LHSKnown.Zero).isAllOnesValue())
Benjamin Kramerb16bd772011-12-24 17:31:53 +00001259 return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
1260 XorLHS);
1261 }
Craig Topperbcfd2d12017-04-20 16:56:25 +00001262 // (X + signmask) + C could have gotten canonicalized to (X^signmask) + C,
1263 // transform them into (X + (signmask ^ C))
1264 if (XorRHS->getValue().isSignMask())
Craig Toppereafbd572015-12-21 01:02:28 +00001265 return BinaryOperator::CreateAdd(XorLHS,
1266 ConstantExpr::getXor(XorRHS, CI));
Chris Lattner82aa8882010-01-05 07:18:46 +00001267 }
1268 }
1269
Sanjay Patel21189522017-10-13 18:32:53 +00001270 if (Ty->isIntOrIntVectorTy(1))
Chris Lattner82aa8882010-01-05 07:18:46 +00001271 return BinaryOperator::CreateXor(LHS, RHS);
1272
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001273 // X + X --> X << 1
Chris Lattnerd4067642011-02-17 20:55:29 +00001274 if (LHS == RHS) {
Sanjay Patel21189522017-10-13 18:32:53 +00001275 auto *Shl = BinaryOperator::CreateShl(LHS, ConstantInt::get(Ty, 1));
1276 Shl->setHasNoSignedWrap(I.hasNoSignedWrap());
1277 Shl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1278 return Shl;
Chris Lattner55920712011-02-17 02:23:02 +00001279 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001280
Sanjay Patelb869f762017-10-13 21:28:50 +00001281 Value *A, *B;
1282 if (match(LHS, m_Neg(m_Value(A)))) {
1283 // -A + -B --> -(A + B)
1284 if (match(RHS, m_Neg(m_Value(B))))
1285 return BinaryOperator::CreateNeg(Builder.CreateAdd(A, B));
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001286
Sanjay Patelb869f762017-10-13 21:28:50 +00001287 // -A + B --> B - A
1288 return BinaryOperator::CreateSub(RHS, A);
Chris Lattner82aa8882010-01-05 07:18:46 +00001289 }
1290
1291 // A + -B --> A - B
Sanjay Patelb869f762017-10-13 21:28:50 +00001292 if (match(RHS, m_Neg(m_Value(B))))
1293 return BinaryOperator::CreateSub(LHS, B);
Chris Lattner82aa8882010-01-05 07:18:46 +00001294
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001295 if (Value *V = checkForNegativeOperand(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001296 return replaceInstUsesWith(I, V);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001297
Gil Rapaportda2e2ca2018-06-26 05:31:18 +00001298 // (A + 1) + ~B --> A - B
1299 // ~B + (A + 1) --> A - B
Roman Lebedev04d3d3b2019-07-01 15:55:24 +00001300 // (~B + A) + 1 --> A - B
1301 // (A + ~B) + 1 --> A - B
1302 if (match(&I, m_c_BinOp(m_Add(m_Value(A), m_One()), m_Not(m_Value(B)))) ||
1303 match(&I, m_BinOp(m_c_Add(m_Not(m_Value(B)), m_Value(A)), m_One())))
Gil Rapaportda2e2ca2018-06-26 05:31:18 +00001304 return BinaryOperator::CreateSub(A, B);
1305
Sanjay Patel2f7c24f2020-05-22 11:37:58 -04001306 // (A + RHS) + RHS --> A + (RHS << 1)
1307 if (match(LHS, m_OneUse(m_c_Add(m_Value(A), m_Specific(RHS)))))
1308 return BinaryOperator::CreateAdd(A, Builder.CreateShl(RHS, 1, "reass.add"));
1309
1310 // LHS + (A + LHS) --> A + (LHS << 1)
1311 if (match(RHS, m_OneUse(m_c_Add(m_Value(A), m_Specific(LHS)))))
1312 return BinaryOperator::CreateAdd(A, Builder.CreateShl(LHS, 1, "reass.add"));
1313
Sanjoy Das6f1937b2018-04-26 20:52:28 +00001314 // X % C0 + (( X / C0 ) % C1) * C0 => X % (C0 * C1)
1315 if (Value *V = SimplifyAddWithRemainder(I)) return replaceInstUsesWith(I, V);
1316
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001317 // A+B --> A|B iff A and B have no bits set in common.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001318 if (haveNoCommonBitsSet(LHS, RHS, DL, &AC, &I, &DT))
Jingyue Wuca321902015-05-14 23:53:19 +00001319 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner82aa8882010-01-05 07:18:46 +00001320
Sanjay Patel79acd2a2016-07-16 18:29:26 +00001321 // FIXME: We already did a check for ConstantInt RHS above this.
1322 // FIXME: Is this pattern covered by another fold? No regression tests fail on
1323 // removal.
Benjamin Kramer72196f32014-01-19 15:24:22 +00001324 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001325 // (X & FF00) + xx00 -> (X+xx00) & FF00
Benjamin Kramer72196f32014-01-19 15:24:22 +00001326 Value *X;
1327 ConstantInt *C2;
Chris Lattner82aa8882010-01-05 07:18:46 +00001328 if (LHS->hasOneUse() &&
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001329 match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
1330 CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
1331 // See if all bits from the first bit set in the Add RHS up are included
1332 // in the mask. First, get the rightmost bit.
1333 const APInt &AddRHSV = CRHS->getValue();
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001334
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001335 // Form a mask of all bits from the lowest bit added through the top.
1336 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattner82aa8882010-01-05 07:18:46 +00001337
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001338 // See if the and mask includes all of these bits.
1339 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Chris Lattner82aa8882010-01-05 07:18:46 +00001340
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001341 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1342 // Okay, the xform is safe. Insert the new add pronto.
Craig Topperbb4069e2017-07-07 23:16:26 +00001343 Value *NewAdd = Builder.CreateAdd(X, CRHS, LHS->getName());
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001344 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattner82aa8882010-01-05 07:18:46 +00001345 }
1346 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001347 }
1348
1349 // add (select X 0 (sub n A)) A --> select X A n
1350 {
1351 SelectInst *SI = dyn_cast<SelectInst>(LHS);
1352 Value *A = RHS;
1353 if (!SI) {
1354 SI = dyn_cast<SelectInst>(RHS);
1355 A = LHS;
1356 }
1357 if (SI && SI->hasOneUse()) {
1358 Value *TV = SI->getTrueValue();
1359 Value *FV = SI->getFalseValue();
1360 Value *N;
1361
1362 // Can we fold the add into the argument of the select?
1363 // We check both true and false select arguments for a matching subtract.
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001364 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner82aa8882010-01-05 07:18:46 +00001365 // Fold the add into the true select value.
1366 return SelectInst::Create(SI->getCondition(), N, A);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001367
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001368 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner82aa8882010-01-05 07:18:46 +00001369 // Fold the add into the false select value.
1370 return SelectInst::Create(SI->getCondition(), A, N);
1371 }
1372 }
1373
Sanjay Patel90a36342018-09-14 22:23:35 +00001374 if (Instruction *Ext = narrowMathIfNoOverflow(I))
Sanjay Patel2426eb42018-09-14 20:40:46 +00001375 return Ext;
David Majnemera1cfd7c2016-12-30 00:28:58 +00001376
David Majnemerab07f002014-08-11 22:32:02 +00001377 // (add (xor A, B) (and A, B)) --> (or A, B)
Sanjay Patel28b3aa32017-10-13 20:12:21 +00001378 // (add (and A, B) (xor A, B)) --> (or A, B)
Roman Lebedev6959b8e2018-04-27 21:23:20 +00001379 if (match(&I, m_c_BinOp(m_Xor(m_Value(A), m_Value(B)),
1380 m_c_And(m_Deferred(A), m_Deferred(B)))))
Sanjay Patel28b3aa32017-10-13 20:12:21 +00001381 return BinaryOperator::CreateOr(A, B);
Chad Rosier7813dce2012-04-26 23:29:14 +00001382
David Majnemerab07f002014-08-11 22:32:02 +00001383 // (add (or A, B) (and A, B)) --> (add A, B)
Sanjay Patel28b3aa32017-10-13 20:12:21 +00001384 // (add (and A, B) (or A, B)) --> (add A, B)
Roman Lebedev6959b8e2018-04-27 21:23:20 +00001385 if (match(&I, m_c_BinOp(m_Or(m_Value(A), m_Value(B)),
1386 m_c_And(m_Deferred(A), m_Deferred(B))))) {
Nikita Popov5a8819b2020-02-03 21:17:36 +01001387 // Replacing operands in-place to preserve nuw/nsw flags.
1388 replaceOperand(I, 0, A);
1389 replaceOperand(I, 1, B);
Sanjay Patel28b3aa32017-10-13 20:12:21 +00001390 return &I;
David Majnemerab07f002014-08-11 22:32:02 +00001391 }
1392
Craig Topper2b1fc322017-05-22 06:25:31 +00001393 // TODO(jingyue): Consider willNotOverflowSignedAdd and
Craig Topperbb973722017-05-15 02:44:08 +00001394 // willNotOverflowUnsignedAdd to reduce the number of invocations of
Jingyue Wu33bd53d2014-06-17 00:42:07 +00001395 // computeKnownBits.
Sanjay Patel70043b72018-07-13 01:18:07 +00001396 bool Changed = false;
Craig Topper2b1fc322017-05-22 06:25:31 +00001397 if (!I.hasNoSignedWrap() && willNotOverflowSignedAdd(LHS, RHS, I)) {
Rafael Espindolad1a2c2d2014-06-02 22:01:04 +00001398 Changed = true;
1399 I.setHasNoSignedWrap(true);
1400 }
Craig Topperbb973722017-05-15 02:44:08 +00001401 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedAdd(LHS, RHS, I)) {
Jingyue Wu33bd53d2014-06-17 00:42:07 +00001402 Changed = true;
1403 I.setHasNoUnsignedWrap(true);
1404 }
Rafael Espindolad1a2c2d2014-06-02 22:01:04 +00001405
Roman Lebedevcbf84462018-06-06 19:38:27 +00001406 if (Instruction *V = canonicalizeLowbitMask(I, Builder))
1407 return V;
1408
Roman Lebedev7cdeac42019-10-07 20:53:27 +00001409 if (Instruction *V =
Roman Lebedev7015a5c2019-10-20 20:52:06 +00001410 canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
Roman Lebedev7cdeac42019-10-07 20:53:27 +00001411 return V;
1412
Sanjay Patel81e8d762019-03-26 17:50:08 +00001413 if (Instruction *SatAdd = foldToUnsignedSaturatedAdd(I))
1414 return SatAdd;
1415
Craig Topperf40110f2014-04-25 05:29:35 +00001416 return Changed ? &I : nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001417}
1418
Sanjay Patelc229cfe2019-07-26 11:19:18 +00001419/// Eliminate an op from a linear interpolation (lerp) pattern.
1420static Instruction *factorizeLerp(BinaryOperator &I,
1421 InstCombiner::BuilderTy &Builder) {
1422 Value *X, *Y, *Z;
1423 if (!match(&I, m_c_FAdd(m_OneUse(m_c_FMul(m_Value(Y),
1424 m_OneUse(m_FSub(m_FPOne(),
1425 m_Value(Z))))),
1426 m_OneUse(m_c_FMul(m_Value(X), m_Deferred(Z))))))
1427 return nullptr;
1428
1429 // (Y * (1.0 - Z)) + (X * Z) --> Y + Z * (X - Y) [8 commuted variants]
1430 Value *XY = Builder.CreateFSubFMF(X, Y, &I);
1431 Value *MulZ = Builder.CreateFMulFMF(Z, XY, &I);
1432 return BinaryOperator::CreateFAddFMF(Y, MulZ, &I);
1433}
1434
Sanjay Pateldc185ee2018-08-12 15:48:26 +00001435/// Factor a common operand out of fadd/fsub of fmul/fdiv.
1436static Instruction *factorizeFAddFSub(BinaryOperator &I,
1437 InstCombiner::BuilderTy &Builder) {
1438 assert((I.getOpcode() == Instruction::FAdd ||
1439 I.getOpcode() == Instruction::FSub) && "Expecting fadd/fsub");
1440 assert(I.hasAllowReassoc() && I.hasNoSignedZeros() &&
1441 "FP factorization requires FMF");
Sanjay Patelc229cfe2019-07-26 11:19:18 +00001442
1443 if (Instruction *Lerp = factorizeLerp(I, Builder))
1444 return Lerp;
1445
Sanjay Pateldc185ee2018-08-12 15:48:26 +00001446 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1447 Value *X, *Y, *Z;
1448 bool IsFMul;
1449 if ((match(Op0, m_OneUse(m_FMul(m_Value(X), m_Value(Z)))) &&
1450 match(Op1, m_OneUse(m_c_FMul(m_Value(Y), m_Specific(Z))))) ||
1451 (match(Op0, m_OneUse(m_FMul(m_Value(Z), m_Value(X)))) &&
1452 match(Op1, m_OneUse(m_c_FMul(m_Value(Y), m_Specific(Z))))))
1453 IsFMul = true;
1454 else if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Z)))) &&
1455 match(Op1, m_OneUse(m_FDiv(m_Value(Y), m_Specific(Z)))))
1456 IsFMul = false;
1457 else
1458 return nullptr;
1459
1460 // (X * Z) + (Y * Z) --> (X + Y) * Z
1461 // (X * Z) - (Y * Z) --> (X - Y) * Z
1462 // (X / Z) + (Y / Z) --> (X + Y) / Z
1463 // (X / Z) - (Y / Z) --> (X - Y) / Z
1464 bool IsFAdd = I.getOpcode() == Instruction::FAdd;
1465 Value *XY = IsFAdd ? Builder.CreateFAddFMF(X, Y, &I)
1466 : Builder.CreateFSubFMF(X, Y, &I);
1467
1468 // Bail out if we just created a denormal constant.
1469 // TODO: This is copied from a previous implementation. Is it necessary?
1470 const APFloat *C;
1471 if (match(XY, m_APFloat(C)) && !C->isNormal())
1472 return nullptr;
1473
1474 return IsFMul ? BinaryOperator::CreateFMulFMF(XY, Z, &I)
1475 : BinaryOperator::CreateFDivFMF(XY, Z, &I);
1476}
1477
Chris Lattner82aa8882010-01-05 07:18:46 +00001478Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001479 if (Value *V = SimplifyFAddInst(I.getOperand(0), I.getOperand(1),
1480 I.getFastMathFlags(),
Craig Toppera4205622017-06-09 03:21:29 +00001481 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001482 return replaceInstUsesWith(I, V);
Chris Lattner82aa8882010-01-05 07:18:46 +00001483
Sanjay Patel70043b72018-07-13 01:18:07 +00001484 if (SimplifyAssociativeOrCommutative(I))
1485 return &I;
1486
Sanjay Patel79dceb22018-10-03 15:20:58 +00001487 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +00001488 return X;
1489
Sanjay Patel8fdd87f2018-02-28 16:36:24 +00001490 if (Instruction *FoldedFAdd = foldBinOpIntoSelectOrPhi(I))
1491 return FoldedFAdd;
Michael Ilsemane2754dc2012-12-14 22:08:26 +00001492
Sanjay Patel1170daa2018-04-16 14:13:57 +00001493 // (-X) + Y --> Y - X
Sanjay Patel5483f422019-07-29 13:20:46 +00001494 Value *X, *Y;
1495 if (match(&I, m_c_FAdd(m_FNeg(m_Value(X)), m_Value(Y))))
1496 return BinaryOperator::CreateFSubFMF(Y, X, &I);
Chris Lattner82aa8882010-01-05 07:18:46 +00001497
Sanjay Patele9ee7b42019-07-29 13:50:25 +00001498 // Similar to above, but look through fmul/fdiv for the negated term.
1499 // (-X * Y) + Z --> Z - (X * Y) [4 commuted variants]
1500 Value *Z;
1501 if (match(&I, m_c_FAdd(m_OneUse(m_c_FMul(m_FNeg(m_Value(X)), m_Value(Y))),
1502 m_Value(Z)))) {
1503 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
1504 return BinaryOperator::CreateFSubFMF(Z, XY, &I);
1505 }
1506 // (-X / Y) + Z --> Z - (X / Y) [2 commuted variants]
1507 // (X / -Y) + Z --> Z - (X / Y) [2 commuted variants]
1508 if (match(&I, m_c_FAdd(m_OneUse(m_FDiv(m_FNeg(m_Value(X)), m_Value(Y))),
1509 m_Value(Z))) ||
1510 match(&I, m_c_FAdd(m_OneUse(m_FDiv(m_Value(X), m_FNeg(m_Value(Y)))),
1511 m_Value(Z)))) {
1512 Value *XY = Builder.CreateFDivFMF(X, Y, &I);
1513 return BinaryOperator::CreateFSubFMF(Z, XY, &I);
1514 }
1515
Dan Gohman6f34abd2010-03-02 01:11:08 +00001516 // Check for (fadd double (sitofp x), y), see if we can merge this into an
Chris Lattner82aa8882010-01-05 07:18:46 +00001517 // integer add followed by a promotion.
Sanjay Patel5483f422019-07-29 13:20:46 +00001518 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner82aa8882010-01-05 07:18:46 +00001519 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
Artur Pilipenko4cc61302017-03-21 11:32:15 +00001520 Value *LHSIntVal = LHSConv->getOperand(0);
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001521 Type *FPType = LHSConv->getType();
1522
1523 // TODO: This check is overly conservative. In many cases known bits
1524 // analysis can tell us that the result of the addition has less significant
1525 // bits than the integer type can hold.
1526 auto IsValidPromotion = [](Type *FTy, Type *ITy) {
Artur Pilipenko0632bdc2017-04-22 07:24:52 +00001527 Type *FScalarTy = FTy->getScalarType();
1528 Type *IScalarTy = ITy->getScalarType();
1529
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001530 // Do we have enough bits in the significand to represent the result of
1531 // the integer addition?
1532 unsigned MaxRepresentableBits =
Artur Pilipenko0632bdc2017-04-22 07:24:52 +00001533 APFloat::semanticsPrecision(FScalarTy->getFltSemantics());
1534 return IScalarTy->getIntegerBitWidth() <= MaxRepresentableBits;
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001535 };
Artur Pilipenko4cc61302017-03-21 11:32:15 +00001536
Dan Gohman6f34abd2010-03-02 01:11:08 +00001537 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
Chris Lattner82aa8882010-01-05 07:18:46 +00001538 // ... if the constant fits in the integer value. This is useful for things
1539 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1540 // requires a constant pool load, and generally allows the add to be better
1541 // instcombined.
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001542 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
1543 if (IsValidPromotion(FPType, LHSIntVal->getType())) {
1544 Constant *CI =
1545 ConstantExpr::getFPToSI(CFP, LHSIntVal->getType());
1546 if (LHSConv->hasOneUse() &&
1547 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Craig Topper2b1fc322017-05-22 06:25:31 +00001548 willNotOverflowSignedAdd(LHSIntVal, CI, I)) {
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001549 // Insert the new integer add.
Craig Topperbb4069e2017-07-07 23:16:26 +00001550 Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, CI, "addconv");
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001551 return new SIToFPInst(NewAdd, I.getType());
1552 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001553 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001554
Dan Gohman6f34abd2010-03-02 01:11:08 +00001555 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
Chris Lattner82aa8882010-01-05 07:18:46 +00001556 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
Artur Pilipenko4cc61302017-03-21 11:32:15 +00001557 Value *RHSIntVal = RHSConv->getOperand(0);
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001558 // It's enough to check LHS types only because we require int types to
1559 // be the same for this transform.
1560 if (IsValidPromotion(FPType, LHSIntVal->getType())) {
1561 // Only do this if x/y have the same type, if at least one of them has a
1562 // single use (so we don't increase the number of int->fp conversions),
1563 // and if the integer add will not overflow.
1564 if (LHSIntVal->getType() == RHSIntVal->getType() &&
1565 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
Craig Topper2b1fc322017-05-22 06:25:31 +00001566 willNotOverflowSignedAdd(LHSIntVal, RHSIntVal, I)) {
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001567 // Insert the new integer add.
Craig Topperbb4069e2017-07-07 23:16:26 +00001568 Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, RHSIntVal, "addconv");
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001569 return new SIToFPInst(NewAdd, I.getType());
1570 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001571 }
1572 }
1573 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001574
Quentin Colombetaa103b32017-09-20 17:32:16 +00001575 // Handle specials cases for FAdd with selects feeding the operation
1576 if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS, RHS))
1577 return replaceInstUsesWith(I, V);
Jean-Luc Duprat3e4fc3e2013-05-06 16:55:50 +00001578
Warren Ristow8b2f27c2018-04-14 19:18:28 +00001579 if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
Sanjay Pateldc185ee2018-08-12 15:48:26 +00001580 if (Instruction *F = factorizeFAddFSub(I, Builder))
1581 return F;
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001582 if (Value *V = FAddCombine(Builder).simplify(&I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001583 return replaceInstUsesWith(I, V);
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001584 }
1585
Sanjay Patel70043b72018-07-13 01:18:07 +00001586 return nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001587}
1588
Chris Lattner82aa8882010-01-05 07:18:46 +00001589/// Optimize pointer differences into the same array into a size. Consider:
1590/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1591/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
Chris Lattner82aa8882010-01-05 07:18:46 +00001592Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
Nikita Popov0e322c82020-01-01 11:11:05 +01001593 Type *Ty, bool IsNUW) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001594 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1595 // this.
1596 bool Swapped = false;
Craig Topperf40110f2014-04-25 05:29:35 +00001597 GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001598
Chris Lattner82aa8882010-01-05 07:18:46 +00001599 // For now we require one side to be the base pointer "A" or a constant
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001600 // GEP derived from it.
1601 if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001602 // (gep X, ...) - X
1603 if (LHSGEP->getOperand(0) == RHS) {
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001604 GEP1 = LHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001605 Swapped = false;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001606 } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1607 // (gep X, ...) - (gep X, ...)
1608 if (LHSGEP->getOperand(0)->stripPointerCasts() ==
1609 RHSGEP->getOperand(0)->stripPointerCasts()) {
1610 GEP2 = RHSGEP;
1611 GEP1 = LHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001612 Swapped = false;
1613 }
1614 }
1615 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001616
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001617 if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001618 // X - (gep X, ...)
1619 if (RHSGEP->getOperand(0) == LHS) {
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001620 GEP1 = RHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001621 Swapped = true;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001622 } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1623 // (gep X, ...) - (gep X, ...)
1624 if (RHSGEP->getOperand(0)->stripPointerCasts() ==
1625 LHSGEP->getOperand(0)->stripPointerCasts()) {
1626 GEP2 = LHSGEP;
1627 GEP1 = RHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001628 Swapped = true;
1629 }
1630 }
1631 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001632
Hiroshi Yamauchi60855212017-07-27 18:27:11 +00001633 if (!GEP1)
1634 // No GEP found.
Craig Topperf40110f2014-04-25 05:29:35 +00001635 return nullptr;
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001636
Hiroshi Yamauchi60855212017-07-27 18:27:11 +00001637 if (GEP2) {
1638 // (gep X, ...) - (gep X, ...)
1639 //
1640 // Avoid duplicating the arithmetic if there are more than one non-constant
1641 // indices between the two GEPs and either GEP has a non-constant index and
1642 // multiple users. If zero non-constant index, the result is a constant and
1643 // there is no duplication. If one non-constant index, the result is an add
1644 // or sub with a constant, which is no larger than the original code, and
1645 // there's no duplicated arithmetic, even if either GEP has multiple
1646 // users. If more than one non-constant indices combined, as long as the GEP
1647 // with at least one non-constant index doesn't have multiple users, there
1648 // is no duplication.
1649 unsigned NumNonConstantIndices1 = GEP1->countNonConstantIndices();
1650 unsigned NumNonConstantIndices2 = GEP2->countNonConstantIndices();
1651 if (NumNonConstantIndices1 + NumNonConstantIndices2 > 1 &&
1652 ((NumNonConstantIndices1 > 0 && !GEP1->hasOneUse()) ||
1653 (NumNonConstantIndices2 > 0 && !GEP2->hasOneUse()))) {
1654 return nullptr;
1655 }
1656 }
1657
Chris Lattner82aa8882010-01-05 07:18:46 +00001658 // Emit the offset of the GEP and an intptr_t.
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001659 Value *Result = EmitGEPOffset(GEP1);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001660
Nikita Popov0e322c82020-01-01 11:11:05 +01001661 // If this is a single inbounds GEP and the original sub was nuw,
1662 // then the final multiplication is also nuw. We match an extra add zero
1663 // here, because that's what EmitGEPOffset() generates.
1664 Instruction *I;
1665 if (IsNUW && !GEP2 && !Swapped && GEP1->isInBounds() &&
1666 match(Result, m_Add(m_Instruction(I), m_Zero())) &&
1667 I->getOpcode() == Instruction::Mul)
1668 I->setHasNoUnsignedWrap();
1669
Chris Lattner82aa8882010-01-05 07:18:46 +00001670 // If we had a constant expression GEP on the other side offsetting the
1671 // pointer, subtract it from the offset we have.
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001672 if (GEP2) {
1673 Value *Offset = EmitGEPOffset(GEP2);
Craig Topperbb4069e2017-07-07 23:16:26 +00001674 Result = Builder.CreateSub(Result, Offset);
Chris Lattner82aa8882010-01-05 07:18:46 +00001675 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001676
1677 // If we have p - gep(p, ...) then we have to negate the result.
1678 if (Swapped)
Craig Topperbb4069e2017-07-07 23:16:26 +00001679 Result = Builder.CreateNeg(Result, "diff.neg");
Chris Lattner82aa8882010-01-05 07:18:46 +00001680
Craig Topperbb4069e2017-07-07 23:16:26 +00001681 return Builder.CreateIntCast(Result, Ty, true);
Chris Lattner82aa8882010-01-05 07:18:46 +00001682}
1683
Chris Lattner82aa8882010-01-05 07:18:46 +00001684Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00001685 if (Value *V = SimplifySubInst(I.getOperand(0), I.getOperand(1),
1686 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
1687 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001688 return replaceInstUsesWith(I, V);
Chris Lattner82aa8882010-01-05 07:18:46 +00001689
Sanjay Patel79dceb22018-10-03 15:20:58 +00001690 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +00001691 return X;
1692
Roman Lebedev352fef32020-04-21 21:24:36 +03001693 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001694
David Majnemera92687d2014-07-31 04:49:29 +00001695 // If this is a 'B = x-(-A)', change to B = x+A.
Roman Lebedev352fef32020-04-21 21:24:36 +03001696 // We deal with this without involving Negator to preserve NSW flag.
Chris Lattner82aa8882010-01-05 07:18:46 +00001697 if (Value *V = dyn_castNegVal(Op1)) {
1698 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
David Majnemera92687d2014-07-31 04:49:29 +00001699
1700 if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
1701 assert(BO->getOpcode() == Instruction::Sub &&
1702 "Expected a subtraction operator!");
1703 if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
1704 Res->setHasNoSignedWrap(true);
David Majnemer0e6c9862014-08-22 16:41:23 +00001705 } else {
1706 if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
1707 Res->setHasNoSignedWrap(true);
David Majnemera92687d2014-07-31 04:49:29 +00001708 }
1709
Chris Lattner82aa8882010-01-05 07:18:46 +00001710 return Res;
1711 }
1712
Roman Lebedev352fef32020-04-21 21:24:36 +03001713 auto TryToNarrowDeduceFlags = [this, &I, &Op0, &Op1]() -> Instruction * {
1714 if (Instruction *Ext = narrowMathIfNoOverflow(I))
1715 return Ext;
1716
1717 bool Changed = false;
1718 if (!I.hasNoSignedWrap() && willNotOverflowSignedSub(Op0, Op1, I)) {
1719 Changed = true;
1720 I.setHasNoSignedWrap(true);
1721 }
1722 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedSub(Op0, Op1, I)) {
1723 Changed = true;
1724 I.setHasNoUnsignedWrap(true);
1725 }
1726
1727 return Changed ? &I : nullptr;
1728 };
1729
1730 // First, let's try to interpret `sub a, b` as `add a, (sub 0, b)`,
1731 // and let's try to sink `(sub 0, b)` into `b` itself. But only if this isn't
1732 // a pure negation used by a select that looks like abs/nabs.
1733 bool IsNegation = match(Op0, m_ZeroInt());
1734 if (!IsNegation || none_of(I.users(), [&I, Op1](const User *U) {
1735 const Instruction *UI = dyn_cast<Instruction>(U);
1736 if (!UI)
1737 return false;
1738 return match(UI,
1739 m_Select(m_Value(), m_Specific(Op1), m_Specific(&I))) ||
1740 match(UI, m_Select(m_Value(), m_Specific(&I), m_Specific(Op1)));
1741 })) {
1742 if (Value *NegOp1 = Negator::Negate(IsNegation, Op1, *this))
1743 return BinaryOperator::CreateAdd(NegOp1, Op0);
1744 }
1745 if (IsNegation)
1746 return TryToNarrowDeduceFlags(); // Should have been handled in Negator!
1747
1748 // (A*B)-(A*C) -> A*(B-C) etc
1749 if (Value *V = SimplifyUsingDistributiveLaws(I))
1750 return replaceInstUsesWith(I, V);
1751
Craig Topperfde47232017-07-09 07:04:03 +00001752 if (I.getType()->isIntOrIntVectorTy(1))
Chris Lattner82aa8882010-01-05 07:18:46 +00001753 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001754
1755 // Replace (-1 - A) with (~A).
1756 if (match(Op0, m_AllOnes()))
1757 return BinaryOperator::CreateNot(Op1);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001758
Sanjay Patel1a8d5c32018-03-03 17:53:25 +00001759 // (~X) - (~Y) --> Y - X
1760 Value *X, *Y;
1761 if (match(Op0, m_Not(m_Value(X))) && match(Op1, m_Not(m_Value(Y))))
1762 return BinaryOperator::CreateSub(Y, X);
1763
Sanjay Patel577c7052018-07-29 18:13:16 +00001764 // (X + -1) - Y --> ~Y + X
1765 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_AllOnes()))))
1766 return BinaryOperator::CreateAdd(Builder.CreateNot(Op1), X);
1767
Benjamin Kramer72196f32014-01-19 15:24:22 +00001768 if (Constant *C = dyn_cast<Constant>(Op0)) {
Sanjay Patelb6404a82017-12-06 21:22:57 +00001769 Value *X;
Nikita Popovbcfa0f52020-01-23 21:13:57 +01001770 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
Sanjay Patel3bd957b2018-06-03 16:35:26 +00001771 // C - (zext bool) --> bool ? C - 1 : C
Sanjay Patelb6404a82017-12-06 21:22:57 +00001772 return SelectInst::Create(X, SubOne(C), C);
Nikita Popovbcfa0f52020-01-23 21:13:57 +01001773 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
Sanjay Patel3bd957b2018-06-03 16:35:26 +00001774 // C - (sext bool) --> bool ? C + 1 : C
Sanjay Patel3bd957b2018-06-03 16:35:26 +00001775 return SelectInst::Create(X, AddOne(C), C);
Sanjay Patelb6404a82017-12-06 21:22:57 +00001776
Chris Lattner82aa8882010-01-05 07:18:46 +00001777 // C - ~X == X + (1+C)
Chris Lattner82aa8882010-01-05 07:18:46 +00001778 if (match(Op1, m_Not(m_Value(X))))
1779 return BinaryOperator::CreateAdd(X, AddOne(C));
1780
Benjamin Kramer72196f32014-01-19 15:24:22 +00001781 // Try to fold constant sub into select arguments.
1782 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1783 if (Instruction *R = FoldOpIntoSelect(I, SI))
1784 return R;
1785
Craig Topperfb71b7d2017-04-14 19:20:12 +00001786 // Try to fold constant sub into PHI values.
1787 if (PHINode *PN = dyn_cast<PHINode>(Op1))
1788 if (Instruction *R = foldOpIntoPhi(I, PN))
1789 return R;
1790
Benjamin Kramer72196f32014-01-19 15:24:22 +00001791 Constant *C2;
Roman Lebedev39390d82019-05-31 09:47:16 +00001792
1793 // C-(C2-X) --> X+(C-C2)
Sanjay Patel01bcc3e2020-04-15 09:11:44 -04001794 if (match(Op1, m_Sub(m_Constant(C2), m_Value(X))) && !isa<ConstantExpr>(C2))
Roman Lebedev39390d82019-05-31 09:47:16 +00001795 return BinaryOperator::CreateAdd(X, ConstantExpr::getSub(C, C2));
1796
1797 // C-(X+C2) --> (C-C2)-X
Benjamin Kramer72196f32014-01-19 15:24:22 +00001798 if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
1799 return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
Benjamin Kramer72196f32014-01-19 15:24:22 +00001800 }
1801
Sanjay Patel6d6eca52016-10-14 16:31:54 +00001802 const APInt *Op0C;
Roman Lebedev352fef32020-04-21 21:24:36 +03001803 if (match(Op0, m_APInt(Op0C)) && Op0C->isMask()) {
Matthias Braunec683342015-04-30 22:04:26 +00001804 // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
1805 // zero.
Roman Lebedev352fef32020-04-21 21:24:36 +03001806 KnownBits RHSKnown = computeKnownBits(Op1, 0, &I);
1807 if ((*Op0C | RHSKnown.Zero).isAllOnesValue())
1808 return BinaryOperator::CreateXor(Op1, Op0);
Chris Lattner82aa8882010-01-05 07:18:46 +00001809 }
1810
David Majnemer72a643d2014-11-03 05:53:55 +00001811 {
Suyog Sardacba4b1d2014-10-08 08:37:49 +00001812 Value *Y;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001813 // X-(X+Y) == -Y X-(Y+X) == -Y
Craig Topper98851ad2017-04-10 16:59:40 +00001814 if (match(Op1, m_c_Add(m_Specific(Op0), m_Value(Y))))
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001815 return BinaryOperator::CreateNeg(Y);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001816
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001817 // (X-Y)-X == -Y
1818 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
1819 return BinaryOperator::CreateNeg(Y);
1820 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001821
David Bolvansky358b80b2019-09-04 12:00:33 +00001822 // (sub (or A, B) (and A, B)) --> (xor A, B)
1823 {
1824 Value *A, *B;
1825 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1826 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
1827 return BinaryOperator::CreateXor(A, B);
1828 }
1829
David Bolvansky0e072482019-09-04 17:30:53 +00001830 // (sub (and A, B) (or A, B)) --> neg (xor A, B)
1831 {
1832 Value *A, *B;
1833 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1834 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
1835 (Op0->hasOneUse() || Op1->hasOneUse()))
1836 return BinaryOperator::CreateNeg(Builder.CreateXor(A, B));
1837 }
1838
Hiroshi Yamauchi0445e312017-07-26 21:54:43 +00001839 // (sub (or A, B), (xor A, B)) --> (and A, B)
David Majnemer312c3e52014-10-19 08:32:32 +00001840 {
Craig Topper0d830ff2017-04-10 18:09:25 +00001841 Value *A, *B;
David Majnemer312c3e52014-10-19 08:32:32 +00001842 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Craig Topper0d830ff2017-04-10 18:09:25 +00001843 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
David Majnemer312c3e52014-10-19 08:32:32 +00001844 return BinaryOperator::CreateAnd(A, B);
1845 }
1846
David Bolvansky420cbb62019-09-04 18:03:21 +00001847 // (sub (xor A, B) (or A, B)) --> neg (and A, B)
1848 {
1849 Value *A, *B;
1850 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
1851 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
1852 (Op0->hasOneUse() || Op1->hasOneUse()))
1853 return BinaryOperator::CreateNeg(Builder.CreateAnd(A, B));
1854 }
1855
Craig Topper0d830ff2017-04-10 18:09:25 +00001856 {
1857 Value *Y;
David Majnemer72a643d2014-11-03 05:53:55 +00001858 // ((X | Y) - X) --> (~X & Y)
Craig Topper0d830ff2017-04-10 18:09:25 +00001859 if (match(Op0, m_OneUse(m_c_Or(m_Value(Y), m_Specific(Op1)))))
David Majnemer72a643d2014-11-03 05:53:55 +00001860 return BinaryOperator::CreateAnd(
Craig Topperbb4069e2017-07-07 23:16:26 +00001861 Y, Builder.CreateNot(Op1, Op1->getName() + ".not"));
David Majnemer72a643d2014-11-03 05:53:55 +00001862 }
1863
Roman Lebedevcc0216b2020-01-03 19:53:29 +03001864 {
1865 // (sub (and Op1, (neg X)), Op1) --> neg (and Op1, (add X, -1))
1866 Value *X;
1867 if (match(Op0, m_OneUse(m_c_And(m_Specific(Op1),
1868 m_OneUse(m_Neg(m_Value(X))))))) {
1869 return BinaryOperator::CreateNeg(Builder.CreateAnd(
1870 Op1, Builder.CreateAdd(X, Constant::getAllOnesValue(I.getType()))));
1871 }
1872 }
1873
Roman Lebedev7973aa02020-01-03 21:10:51 +03001874 {
1875 // (sub (and Op1, C), Op1) --> neg (and Op1, ~C)
1876 Constant *C;
1877 if (match(Op0, m_OneUse(m_And(m_Specific(Op1), m_Constant(C))))) {
1878 return BinaryOperator::CreateNeg(
1879 Builder.CreateAnd(Op1, Builder.CreateNot(C)));
1880 }
1881 }
1882
Roman Lebedev4d8e47c2020-01-04 16:31:18 +03001883 {
Roman Lebedev6d05bc22020-01-04 17:24:20 +03001884 // If we have a subtraction between some value and a select between
1885 // said value and something else, sink subtraction into select hands, i.e.:
1886 // sub (select %Cond, %TrueVal, %FalseVal), %Op1
1887 // ->
1888 // select %Cond, (sub %TrueVal, %Op1), (sub %FalseVal, %Op1)
1889 // or
Roman Lebedev772ede32020-01-04 16:50:53 +03001890 // sub %Op0, (select %Cond, %TrueVal, %FalseVal)
1891 // ->
1892 // select %Cond, (sub %Op0, %TrueVal), (sub %Op0, %FalseVal)
1893 // This will result in select between new subtraction and 0.
Roman Lebedev6d05bc22020-01-04 17:24:20 +03001894 auto SinkSubIntoSelect =
1895 [Ty = I.getType()](Value *Select, Value *OtherHandOfSub,
1896 auto SubBuilder) -> Instruction * {
1897 Value *Cond, *TrueVal, *FalseVal;
1898 if (!match(Select, m_OneUse(m_Select(m_Value(Cond), m_Value(TrueVal),
1899 m_Value(FalseVal)))))
1900 return nullptr;
1901 if (OtherHandOfSub != TrueVal && OtherHandOfSub != FalseVal)
1902 return nullptr;
Roman Lebedev772ede32020-01-04 16:50:53 +03001903 // While it is really tempting to just create two subtractions and let
1904 // InstCombine fold one of those to 0, it isn't possible to do so
1905 // because of worklist visitation order. So ugly it is.
Roman Lebedev6d05bc22020-01-04 17:24:20 +03001906 bool OtherHandOfSubIsTrueVal = OtherHandOfSub == TrueVal;
1907 Value *NewSub = SubBuilder(OtherHandOfSubIsTrueVal ? FalseVal : TrueVal);
1908 Constant *Zero = Constant::getNullValue(Ty);
Roman Lebedev772ede32020-01-04 16:50:53 +03001909 SelectInst *NewSel =
Roman Lebedev6d05bc22020-01-04 17:24:20 +03001910 SelectInst::Create(Cond, OtherHandOfSubIsTrueVal ? Zero : NewSub,
1911 OtherHandOfSubIsTrueVal ? NewSub : Zero);
Roman Lebedev772ede32020-01-04 16:50:53 +03001912 // Preserve prof metadata if any.
Roman Lebedev6d05bc22020-01-04 17:24:20 +03001913 NewSel->copyMetadata(cast<Instruction>(*Select));
Roman Lebedev772ede32020-01-04 16:50:53 +03001914 return NewSel;
Roman Lebedev6d05bc22020-01-04 17:24:20 +03001915 };
1916 if (Instruction *NewSel = SinkSubIntoSelect(
1917 /*Select=*/Op0, /*OtherHandOfSub=*/Op1,
1918 [Builder = &Builder, Op1](Value *OtherHandOfSelect) {
1919 return Builder->CreateSub(OtherHandOfSelect,
1920 /*OtherHandOfSub=*/Op1);
1921 }))
Roman Lebedev4d8e47c2020-01-04 16:31:18 +03001922 return NewSel;
Roman Lebedev6d05bc22020-01-04 17:24:20 +03001923 if (Instruction *NewSel = SinkSubIntoSelect(
1924 /*Select=*/Op1, /*OtherHandOfSub=*/Op0,
1925 [Builder = &Builder, Op0](Value *OtherHandOfSelect) {
1926 return Builder->CreateSub(/*OtherHandOfSub=*/Op0,
1927 OtherHandOfSelect);
1928 }))
1929 return NewSel;
Roman Lebedev4d8e47c2020-01-04 16:31:18 +03001930 }
1931
Roman Lebedev1badf7c2020-03-06 21:39:07 +03001932 // (X - (X & Y)) --> (X & ~Y)
1933 if (match(Op1, m_c_And(m_Specific(Op0), m_Value(Y))) &&
1934 (Op1->hasOneUse() || isa<Constant>(Y)))
1935 return BinaryOperator::CreateAnd(
1936 Op0, Builder.CreateNot(Y, Y->getName() + ".not"));
1937
David Green1e44c3b2018-10-02 09:48:34 +00001938 {
1939 // ~A - Min/Max(~A, O) -> Max/Min(A, ~O) - A
1940 // ~A - Min/Max(O, ~A) -> Max/Min(A, ~O) - A
1941 // Min/Max(~A, O) - ~A -> A - Max/Min(A, ~O)
1942 // Min/Max(O, ~A) - ~A -> A - Max/Min(A, ~O)
1943 // So long as O here is freely invertible, this will be neutral or a win.
1944 Value *LHS, *RHS, *A;
1945 Value *NotA = Op0, *MinMax = Op1;
1946 SelectPatternFlavor SPF = matchSelectPattern(MinMax, LHS, RHS).Flavor;
1947 if (!SelectPatternResult::isMinOrMax(SPF)) {
1948 NotA = Op1;
1949 MinMax = Op0;
1950 SPF = matchSelectPattern(MinMax, LHS, RHS).Flavor;
1951 }
1952 if (SelectPatternResult::isMinOrMax(SPF) &&
1953 match(NotA, m_Not(m_Value(A))) && (NotA == LHS || NotA == RHS)) {
1954 if (NotA == LHS)
1955 std::swap(LHS, RHS);
1956 // LHS is now O above and expected to have at least 2 uses (the min/max)
1957 // NotA is epected to have 2 uses from the min/max and 1 from the sub.
Roman Lebedev04104892019-08-13 12:49:16 +00001958 if (isFreeToInvert(LHS, !LHS->hasNUsesOrMore(3)) &&
David Green1e44c3b2018-10-02 09:48:34 +00001959 !NotA->hasNUsesOrMore(4)) {
1960 // Note: We don't generate the inverse max/min, just create the not of
1961 // it and let other folds do the rest.
1962 Value *Not = Builder.CreateNot(MinMax);
1963 if (NotA == Op0)
1964 return BinaryOperator::CreateSub(Not, A);
1965 else
1966 return BinaryOperator::CreateSub(A, Not);
1967 }
1968 }
1969 }
1970
Chris Lattner82aa8882010-01-05 07:18:46 +00001971 // Optimize pointer differences into the same array into a size. Consider:
1972 // &A[10] - &A[0]: we should compile this to "10".
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001973 Value *LHSOp, *RHSOp;
1974 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1975 match(Op1, m_PtrToInt(m_Value(RHSOp))))
Nikita Popov0e322c82020-01-01 11:11:05 +01001976 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType(),
1977 I.hasNoUnsignedWrap()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001978 return replaceInstUsesWith(I, Res);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001979
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001980 // trunc(p)-trunc(q) -> trunc(p-q)
1981 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1982 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
Nikita Popov0e322c82020-01-01 11:11:05 +01001983 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType(),
1984 /* IsNUW */ false))
Sanjay Patel4b198802016-02-01 22:23:39 +00001985 return replaceInstUsesWith(I, Res);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001986
Sanjay Patel3cd1aa82018-06-06 21:58:12 +00001987 // Canonicalize a shifty way to code absolute value to the common pattern.
1988 // There are 2 potential commuted variants.
1989 // We're relying on the fact that we only do this transform when the shift has
1990 // exactly 2 uses and the xor has exactly 1 use (otherwise, we might increase
1991 // instructions).
1992 Value *A;
1993 const APInt *ShAmt;
1994 Type *Ty = I.getType();
1995 if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
1996 Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 &&
1997 match(Op0, m_OneUse(m_c_Xor(m_Specific(A), m_Specific(Op1))))) {
1998 // B = ashr i32 A, 31 ; smear the sign bit
1999 // sub (xor A, B), B ; flip bits if negative and subtract -1 (add 1)
2000 // --> (A < 0) ? -A : A
2001 Value *Cmp = Builder.CreateICmpSLT(A, ConstantInt::getNullValue(Ty));
2002 // Copy the nuw/nsw flags from the sub to the negate.
2003 Value *Neg = Builder.CreateNeg(A, "", I.hasNoUnsignedWrap(),
2004 I.hasNoSignedWrap());
2005 return SelectInst::Create(Cmp, Neg, A);
2006 }
2007
Roman Lebedev7cdeac42019-10-07 20:53:27 +00002008 if (Instruction *V =
Roman Lebedev7015a5c2019-10-20 20:52:06 +00002009 canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I))
Roman Lebedev7cdeac42019-10-07 20:53:27 +00002010 return V;
2011
Roman Lebedev352fef32020-04-21 21:24:36 +03002012 return TryToNarrowDeduceFlags();
Chris Lattner82aa8882010-01-05 07:18:46 +00002013}
2014
Cameron McInally2557ca22019-05-20 19:10:30 +00002015/// This eliminates floating-point negation in either 'fneg(X)' or
2016/// 'fsub(-0.0, X)' form by combining into a constant operand.
2017static Instruction *foldFNegIntoConstant(Instruction &I) {
2018 Value *X;
2019 Constant *C;
2020
2021 // Fold negation into constant operand. This is limited with one-use because
2022 // fneg is assumed better for analysis and cheaper in codegen than fmul/fdiv.
2023 // -(X * C) --> X * (-C)
Cameron McInally8bec58d2019-05-20 21:00:42 +00002024 // FIXME: It's arguable whether these should be m_OneUse or not. The current
2025 // belief is that the FNeg allows for better reassociation opportunities.
Cameron McInally2557ca22019-05-20 19:10:30 +00002026 if (match(&I, m_FNeg(m_OneUse(m_FMul(m_Value(X), m_Constant(C))))))
2027 return BinaryOperator::CreateFMulFMF(X, ConstantExpr::getFNeg(C), &I);
2028 // -(X / C) --> X / (-C)
2029 if (match(&I, m_FNeg(m_OneUse(m_FDiv(m_Value(X), m_Constant(C))))))
2030 return BinaryOperator::CreateFDivFMF(X, ConstantExpr::getFNeg(C), &I);
2031 // -(C / X) --> (-C) / X
2032 if (match(&I, m_FNeg(m_OneUse(m_FDiv(m_Constant(C), m_Value(X))))))
2033 return BinaryOperator::CreateFDivFMF(ConstantExpr::getFNeg(C), X, &I);
2034
Sanjay Patel0ade2ab2020-01-22 09:29:19 -05002035 // With NSZ [ counter-example with -0.0: -(-0.0 + 0.0) != 0.0 + -0.0 ]:
2036 // -(X + C) --> -X + -C --> -C - X
2037 if (I.hasNoSignedZeros() &&
2038 match(&I, m_FNeg(m_OneUse(m_FAdd(m_Value(X), m_Constant(C))))))
2039 return BinaryOperator::CreateFSubFMF(ConstantExpr::getFNeg(C), X, &I);
2040
Cameron McInally2557ca22019-05-20 19:10:30 +00002041 return nullptr;
2042}
2043
Sanjay Patel435cdec2019-07-31 16:53:22 +00002044static Instruction *hoistFNegAboveFMulFDiv(Instruction &I,
2045 InstCombiner::BuilderTy &Builder) {
2046 Value *FNeg;
2047 if (!match(&I, m_FNeg(m_Value(FNeg))))
2048 return nullptr;
2049
2050 Value *X, *Y;
2051 if (match(FNeg, m_OneUse(m_FMul(m_Value(X), m_Value(Y)))))
2052 return BinaryOperator::CreateFMulFMF(Builder.CreateFNegFMF(X, &I), Y, &I);
2053
2054 if (match(FNeg, m_OneUse(m_FDiv(m_Value(X), m_Value(Y)))))
2055 return BinaryOperator::CreateFDivFMF(Builder.CreateFNegFMF(X, &I), Y, &I);
2056
2057 return nullptr;
2058}
2059
Cameron McInallye75412a2019-05-10 20:01:04 +00002060Instruction *InstCombiner::visitFNeg(UnaryOperator &I) {
Cameron McInally08200d62019-06-11 16:21:21 +00002061 Value *Op = I.getOperand(0);
2062
2063 if (Value *V = SimplifyFNegInst(Op, I.getFastMathFlags(),
Cameron McInallye75412a2019-05-10 20:01:04 +00002064 SQ.getWithInstruction(&I)))
2065 return replaceInstUsesWith(I, V);
2066
Cameron McInally2557ca22019-05-20 19:10:30 +00002067 if (Instruction *X = foldFNegIntoConstant(I))
2068 return X;
2069
Cameron McInally08200d62019-06-11 16:21:21 +00002070 Value *X, *Y;
2071
2072 // If we can ignore the sign of zeros: -(X - Y) --> (Y - X)
2073 if (I.hasNoSignedZeros() &&
2074 match(Op, m_OneUse(m_FSub(m_Value(X), m_Value(Y)))))
2075 return BinaryOperator::CreateFSubFMF(Y, X, &I);
2076
Sanjay Patel435cdec2019-07-31 16:53:22 +00002077 if (Instruction *R = hoistFNegAboveFMulFDiv(I, Builder))
2078 return R;
2079
Cameron McInallye75412a2019-05-10 20:01:04 +00002080 return nullptr;
2081}
2082
Chris Lattner82aa8882010-01-05 07:18:46 +00002083Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
Sanjay Patel7b0fc752018-06-21 17:06:36 +00002084 if (Value *V = SimplifyFSubInst(I.getOperand(0), I.getOperand(1),
2085 I.getFastMathFlags(),
Craig Toppera4205622017-06-09 03:21:29 +00002086 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002087 return replaceInstUsesWith(I, V);
Michael Ilsemand5787be2012-12-12 00:28:32 +00002088
Sanjay Patel79dceb22018-10-03 15:20:58 +00002089 if (Instruction *X = foldVectorBinop(I))
Sanjay Patelbbc6d602018-06-02 16:27:44 +00002090 return X;
2091
Sanjay Patela9ca7092018-04-06 17:24:08 +00002092 // Subtraction from -0.0 is the canonical form of fneg.
Simon Molld871ef42020-03-10 16:05:31 +01002093 // fsub -0.0, X ==> fneg X
2094 // fsub nsz 0.0, X ==> fneg nsz X
2095 //
2096 // FIXME This matcher does not respect FTZ or DAZ yet:
2097 // fsub -0.0, Denorm ==> +-0
2098 // fneg Denorm ==> -Denorm
2099 Value *Op;
2100 if (match(&I, m_FNeg(m_Value(Op))))
2101 return UnaryOperator::CreateFNegFMF(Op, &I);
Sanjay Patel03e25262018-04-05 21:37:17 +00002102
Cameron McInally2557ca22019-05-20 19:10:30 +00002103 if (Instruction *X = foldFNegIntoConstant(I))
2104 return X;
2105
Sanjay Patel435cdec2019-07-31 16:53:22 +00002106 if (Instruction *R = hoistFNegAboveFMulFDiv(I, Builder))
2107 return R;
2108
Sanjay Patela194b2d2018-08-08 14:29:08 +00002109 Value *X, *Y;
2110 Constant *C;
2111
Simon Molld871ef42020-03-10 16:05:31 +01002112 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Sanjay Patela9ca7092018-04-06 17:24:08 +00002113 // If Op0 is not -0.0 or we can ignore -0.0: Z - (X - Y) --> Z + (Y - X)
Sanjay Patel04683de2018-04-05 23:21:15 +00002114 // Canonicalize to fadd to make analysis easier.
2115 // This can also help codegen because fadd is commutative.
Sanjay Patela9ca7092018-04-06 17:24:08 +00002116 // Note that if this fsub was really an fneg, the fadd with -0.0 will get
2117 // killed later. We still limit that particular transform with 'hasOneUse'
2118 // because an fneg is assumed better/cheaper than a generic fsub.
Sanjay Patel04683de2018-04-05 23:21:15 +00002119 if (I.hasNoSignedZeros() || CannotBeNegativeZero(Op0, SQ.TLI)) {
2120 if (match(Op1, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
2121 Value *NewSub = Builder.CreateFSubFMF(Y, X, &I);
2122 return BinaryOperator::CreateFAddFMF(Op0, NewSub, &I);
2123 }
2124 }
2125
Sanjay Patel242fed92020-01-27 14:40:43 -05002126 // (-X) - Op1 --> -(X + Op1)
2127 if (I.hasNoSignedZeros() && !isa<ConstantExpr>(Op0) &&
2128 match(Op0, m_OneUse(m_FNeg(m_Value(X))))) {
2129 Value *FAdd = Builder.CreateFAddFMF(X, Op1, &I);
2130 return UnaryOperator::CreateFNegFMF(FAdd, &I);
2131 }
2132
Stephen Lina9b57f62013-07-20 07:13:13 +00002133 if (isa<Constant>(Op0))
2134 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2135 if (Instruction *NV = FoldOpIntoSelect(I, SI))
2136 return NV;
2137
Sanjay Pateldeaf4f32018-04-05 17:06:45 +00002138 // X - C --> X + (-C)
Sanjay Patelceb595b2018-05-30 23:55:12 +00002139 // But don't transform constant expressions because there's an inverse fold
2140 // for X + (-Y) --> X - Y.
Sanjay Patelceb595b2018-05-30 23:55:12 +00002141 if (match(Op1, m_Constant(C)) && !isa<ConstantExpr>(Op1))
Sanjay Pateldeaf4f32018-04-05 17:06:45 +00002142 return BinaryOperator::CreateFAddFMF(Op0, ConstantExpr::getFNeg(C), &I);
Fangrui Songf78650a2018-07-30 19:41:25 +00002143
Sanjay Pateldeaf4f32018-04-05 17:06:45 +00002144 // X - (-Y) --> X + Y
Sanjay Pateldeaf4f32018-04-05 17:06:45 +00002145 if (match(Op1, m_FNeg(m_Value(Y))))
2146 return BinaryOperator::CreateFAddFMF(Op0, Y, &I);
Sanjay Patel4a9116e2018-02-23 17:07:29 +00002147
Sanjay Patelff986822018-04-11 15:57:18 +00002148 // Similar to above, but look through a cast of the negated value:
2149 // X - (fptrunc(-Y)) --> X + fptrunc(Y)
Sanjay Patelebec4202018-08-09 15:07:13 +00002150 Type *Ty = I.getType();
2151 if (match(Op1, m_OneUse(m_FPTrunc(m_FNeg(m_Value(Y))))))
2152 return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPTrunc(Y, Ty), &I);
Chris Lattner82aa8882010-01-05 07:18:46 +00002153
Sanjay Patelebec4202018-08-09 15:07:13 +00002154 // X - (fpext(-Y)) --> X + fpext(Y)
2155 if (match(Op1, m_OneUse(m_FPExt(m_FNeg(m_Value(Y))))))
2156 return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPExt(Y, Ty), &I);
2157
Sanjay Patel99c57c62019-07-28 17:10:06 +00002158 // Similar to above, but look through fmul/fdiv of the negated value:
2159 // Op0 - (-X * Y) --> Op0 + (X * Y)
2160 // Op0 - (Y * -X) --> Op0 + (X * Y)
2161 if (match(Op1, m_OneUse(m_c_FMul(m_FNeg(m_Value(X)), m_Value(Y))))) {
2162 Value *FMul = Builder.CreateFMulFMF(X, Y, &I);
2163 return BinaryOperator::CreateFAddFMF(Op0, FMul, &I);
2164 }
2165 // Op0 - (-X / Y) --> Op0 + (X / Y)
2166 // Op0 - (X / -Y) --> Op0 + (X / Y)
2167 if (match(Op1, m_OneUse(m_FDiv(m_FNeg(m_Value(X)), m_Value(Y)))) ||
2168 match(Op1, m_OneUse(m_FDiv(m_Value(X), m_FNeg(m_Value(Y)))))) {
2169 Value *FDiv = Builder.CreateFDivFMF(X, Y, &I);
2170 return BinaryOperator::CreateFAddFMF(Op0, FDiv, &I);
2171 }
2172
Sanjay Patelebec4202018-08-09 15:07:13 +00002173 // Handle special cases for FSub with selects feeding the operation
Quentin Colombetaa103b32017-09-20 17:32:16 +00002174 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
2175 return replaceInstUsesWith(I, V);
2176
Warren Ristow8b2f27c2018-04-14 19:18:28 +00002177 if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
Sanjay Patel2054dd72018-08-08 16:04:48 +00002178 // (Y - X) - Y --> -X
2179 if (match(Op0, m_FSub(m_Specific(Op1), m_Value(X))))
Simon Mollddd11272020-02-27 09:05:54 -08002180 return UnaryOperator::CreateFNegFMF(X, &I);
Sanjay Patel2054dd72018-08-08 16:04:48 +00002181
Sanjay Patelfe839692018-08-08 16:19:22 +00002182 // Y - (X + Y) --> -X
2183 // Y - (Y + X) --> -X
2184 if (match(Op1, m_c_FAdd(m_Specific(Op0), m_Value(X))))
Simon Mollddd11272020-02-27 09:05:54 -08002185 return UnaryOperator::CreateFNegFMF(X, &I);
Sanjay Patelfe839692018-08-08 16:19:22 +00002186
Sanjay Patel55accd72018-08-09 18:42:12 +00002187 // (X * C) - X --> X * (C - 1.0)
2188 if (match(Op0, m_FMul(m_Specific(Op1), m_Constant(C)))) {
2189 Constant *CSubOne = ConstantExpr::getFSub(C, ConstantFP::get(Ty, 1.0));
2190 return BinaryOperator::CreateFMulFMF(Op1, CSubOne, &I);
2191 }
2192 // X - (X * C) --> X * (1.0 - C)
2193 if (match(Op1, m_FMul(m_Specific(Op0), m_Constant(C)))) {
2194 Constant *OneSubC = ConstantExpr::getFSub(ConstantFP::get(Ty, 1.0), C);
2195 return BinaryOperator::CreateFMulFMF(Op0, OneSubC, &I);
2196 }
2197
Sanjay Patela0ce2332020-05-26 12:48:22 -04002198 // Reassociate fsub/fadd sequences to create more fadd instructions and
2199 // reduce dependency chains:
2200 // ((X - Y) + Z) - Op1 --> (X + Z) - (Y + Op1)
2201 Value *Z;
2202 if (match(Op0, m_OneUse(m_c_FAdd(m_OneUse(m_FSub(m_Value(X), m_Value(Y))),
2203 m_Value(Z))))) {
2204 Value *XZ = Builder.CreateFAddFMF(X, Z, &I);
2205 Value *YW = Builder.CreateFAddFMF(Y, Op1, &I);
2206 return BinaryOperator::CreateFSubFMF(XZ, YW, &I);
2207 }
2208
Sanjay Pateldc185ee2018-08-12 15:48:26 +00002209 if (Instruction *F = factorizeFAddFSub(I, Builder))
2210 return F;
2211
Sanjay Patel2054dd72018-08-08 16:04:48 +00002212 // TODO: This performs reassociative folds for FP ops. Some fraction of the
2213 // functionality has been subsumed by simple pattern matching here and in
2214 // InstSimplify. We should let a dedicated reassociation pass handle more
2215 // complex pattern matching and remove this from InstCombine.
Shuxin Yang37a1efe2012-12-18 23:10:12 +00002216 if (Value *V = FAddCombine(Builder).simplify(&I))
Sanjay Patel4b198802016-02-01 22:23:39 +00002217 return replaceInstUsesWith(I, V);
Sanjay Patel3180af432020-01-15 08:23:46 -05002218
2219 // (X - Y) - Op1 --> X - (Y + Op1)
2220 if (match(Op0, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
2221 Value *FAdd = Builder.CreateFAddFMF(Y, Op1, &I);
2222 return BinaryOperator::CreateFSubFMF(X, FAdd, &I);
2223 }
Shuxin Yang37a1efe2012-12-18 23:10:12 +00002224 }
2225
Craig Topperf40110f2014-04-25 05:29:35 +00002226 return nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00002227}