LLVM 24.0.0git
InstCombineAddSub.cpp
Go to the documentation of this file.
1//===- InstCombineAddSub.cpp ------------------------------------*- C++ -*-===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the visit functions for add, fadd, sub, and fsub.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
14#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/STLExtras.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"
25#include "llvm/IR/Operator.h"
28#include "llvm/IR/Type.h"
29#include "llvm/IR/Value.h"
34#include <cassert>
35#include <utility>
36
37using namespace llvm;
38using namespace PatternMatch;
39
40#define DEBUG_TYPE "instcombine"
41
42namespace llvm {
44}
45
46namespace {
47
48 /// Class representing coefficient of floating-point addend.
49 /// This class needs to be highly efficient, which is especially true for
50 /// the constructor. As of I write this comment, the cost of the default
51 /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
52 /// perform write-merging).
53 ///
54 class FAddendCoef {
55 public:
56 // The constructor has to initialize a APFloat, which is unnecessary for
57 // most addends which have coefficient either 1 or -1. So, the constructor
58 // is expensive. In order to avoid the cost of the constructor, we should
59 // reuse some instances whenever possible. The pre-created instances
60 // FAddCombine::Add[0-5] embodies this idea.
61 FAddendCoef() = default;
62 ~FAddendCoef();
63
64 // If possible, don't define operator+/operator- etc because these
65 // operators inevitably call FAddendCoef's constructor which is not cheap.
66 void operator=(const FAddendCoef &A);
67 void operator+=(const FAddendCoef &A);
68 void operator*=(const FAddendCoef &S);
69
70 void set(short C) {
71 assert(!insaneIntVal(C) && "Insane coefficient");
72 IsFp = false; IntVal = C;
73 }
74
75 void set(const APFloat& C);
76
77 void negate();
78
79 bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
80 Value *getValue(Type *) const;
81
82 bool isOne() const { return isInt() && IntVal == 1; }
83 bool isTwo() const { return isInt() && IntVal == 2; }
84 bool isMinusOne() const { return isInt() && IntVal == -1; }
85 bool isMinusTwo() const { return isInt() && IntVal == -2; }
86
87 private:
88 bool insaneIntVal(int V) { return V > 4 || V < -4; }
89
90 APFloat *getFpValPtr() { return reinterpret_cast<APFloat *>(&FpValBuf); }
91
92 const APFloat *getFpValPtr() const {
93 return reinterpret_cast<const APFloat *>(&FpValBuf);
94 }
95
96 const APFloat &getFpVal() const {
97 assert(IsFp && BufHasFpVal && "Incorrect state");
98 return *getFpValPtr();
99 }
100
101 APFloat &getFpVal() {
102 assert(IsFp && BufHasFpVal && "Incorrect state");
103 return *getFpValPtr();
104 }
105
106 bool isInt() const { return !IsFp; }
107
108 // If the coefficient is represented by an integer, promote it to a
109 // floating point.
110 void convertToFpType(const fltSemantics &Sem);
111
112 // Construct an APFloat from a signed integer.
113 // TODO: We should get rid of this function when APFloat can be constructed
114 // from an *SIGNED* integer.
115 APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
116
117 bool IsFp = false;
118
119 // True iff FpValBuf contains an instance of APFloat.
120 bool BufHasFpVal = false;
121
122 // The integer coefficient of an individual addend is either 1 or -1,
123 // and we try to simplify at most 4 addends from neighboring at most
124 // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
125 // is overkill of this end.
126 short IntVal = 0;
127
128 AlignedCharArrayUnion<APFloat> FpValBuf;
129 };
130
131 /// FAddend is used to represent floating-point addend. An addend is
132 /// represented as <C, V>, where the V is a symbolic value, and C is a
133 /// constant coefficient. A constant addend is represented as <C, 0>.
134 class FAddend {
135 public:
136 FAddend() = default;
137
138 void operator+=(const FAddend &T) {
139 assert((Val == T.Val) && "Symbolic-values disagree");
140 Coeff += T.Coeff;
141 }
142
143 Value *getSymVal() const { return Val; }
144 const FAddendCoef &getCoef() const { return Coeff; }
145
146 bool isConstant() const { return Val == nullptr; }
147 bool isZero() const { return Coeff.isZero(); }
148
149 void set(short Coefficient, Value *V) {
150 Coeff.set(Coefficient);
151 Val = V;
152 }
153 void set(const APFloat &Coefficient, Value *V) {
154 Coeff.set(Coefficient);
155 Val = V;
156 }
157 void set(const ConstantFP *Coefficient, Value *V) {
158 Coeff.set(Coefficient->getValueAPF());
159 Val = V;
160 }
161
162 void negate() { Coeff.negate(); }
163
164 /// Drill down the U-D chain one step to find the definition of V, and
165 /// try to break the definition into one or two addends.
166 static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
167
168 /// Similar to FAddend::drillDownOneStep() except that the value being
169 /// splitted is the addend itself.
170 unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
171
172 private:
173 void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
174
175 // This addend has the value of "Coeff * Val".
176 Value *Val = nullptr;
177 FAddendCoef Coeff;
178 };
179
180 /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
181 /// with its neighboring at most two instructions.
182 ///
183 class FAddCombine {
184 public:
185 FAddCombine(InstCombiner::BuilderTy &B) : Builder(B) {}
186
187 Value *simplify(Instruction *FAdd);
188
189 private:
190 using AddendVect = SmallVector<const FAddend *, 4>;
191
192 Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
193
194 /// Convert given addend to a Value
195 Value *createAddendVal(const FAddend &A, bool& NeedNeg);
196
197 /// Return the number of instructions needed to emit the N-ary addition.
198 unsigned calcInstrNumber(const AddendVect& Vect);
199
200 Value *createFSub(Value *Opnd0, Value *Opnd1);
201 Value *createFAdd(Value *Opnd0, Value *Opnd1);
202 Value *createFMul(Value *Opnd0, Value *Opnd1);
203 Value *createFNeg(Value *V);
204 Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
205 void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
206
207 // Debugging stuff are clustered here.
208 #ifndef NDEBUG
209 unsigned CreateInstrNum;
210 void initCreateInstNum() { CreateInstrNum = 0; }
211 void incCreateInstNum() { CreateInstrNum++; }
212 #else
213 void initCreateInstNum() {}
214 void incCreateInstNum() {}
215 #endif
216
217 InstCombiner::BuilderTy &Builder;
218 Instruction *Instr = nullptr;
219 };
220
221} // end anonymous namespace
222
223//===----------------------------------------------------------------------===//
224//
225// Implementation of
226// {FAddendCoef, FAddend, FAddition, FAddCombine}.
227//
228//===----------------------------------------------------------------------===//
229FAddendCoef::~FAddendCoef() {
230 if (BufHasFpVal)
231 getFpValPtr()->~APFloat();
232}
233
234void FAddendCoef::set(const APFloat& C) {
235 APFloat *P = getFpValPtr();
236
237 if (isInt()) {
238 // As the buffer is meanless byte stream, we cannot call
239 // APFloat::operator=().
240 new(P) APFloat(C);
241 } else
242 *P = C;
243
244 IsFp = BufHasFpVal = true;
245}
246
247void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
248 if (!isInt())
249 return;
250
251 APFloat *P = getFpValPtr();
252 if (IntVal > 0)
253 new(P) APFloat(Sem, IntVal);
254 else {
255 new(P) APFloat(Sem, 0 - IntVal);
256 P->changeSign();
257 }
258 IsFp = BufHasFpVal = true;
259}
260
261APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
262 if (Val >= 0)
263 return APFloat(Sem, Val);
264
265 APFloat T(Sem, 0 - Val);
266 T.changeSign();
267
268 return T;
269}
270
271void FAddendCoef::operator=(const FAddendCoef &That) {
272 if (That.isInt())
273 set(That.IntVal);
274 else
275 set(That.getFpVal());
276}
277
278void FAddendCoef::operator+=(const FAddendCoef &That) {
279 RoundingMode RndMode = RoundingMode::NearestTiesToEven;
280 if (isInt() == That.isInt()) {
281 if (isInt())
282 IntVal += That.IntVal;
283 else
284 getFpVal().add(That.getFpVal(), RndMode);
285 return;
286 }
287
288 if (isInt()) {
289 const APFloat &T = That.getFpVal();
290 convertToFpType(T.getSemantics());
291 getFpVal().add(T, RndMode);
292 return;
293 }
294
295 APFloat &T = getFpVal();
296 T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
297}
298
299void FAddendCoef::operator*=(const FAddendCoef &That) {
300 if (That.isOne())
301 return;
302
303 if (That.isMinusOne()) {
304 negate();
305 return;
306 }
307
308 if (isInt() && That.isInt()) {
309 int Res = IntVal * (int)That.IntVal;
310 assert(!insaneIntVal(Res) && "Insane int value");
311 IntVal = Res;
312 return;
313 }
314
315 const fltSemantics &Semantic =
316 isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
317
318 if (isInt())
319 convertToFpType(Semantic);
320 APFloat &F0 = getFpVal();
321
322 if (That.isInt())
323 F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
324 APFloat::rmNearestTiesToEven);
325 else
326 F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
327}
328
329void FAddendCoef::negate() {
330 if (isInt())
331 IntVal = 0 - IntVal;
332 else
333 getFpVal().changeSign();
334}
335
336Value *FAddendCoef::getValue(Type *Ty) const {
337 return isInt() ?
338 ConstantFP::get(Ty, float(IntVal)) :
339 ConstantFP::get(Ty->getContext(), getFpVal());
340}
341
342// The definition of <Val> Addends
343// =========================================
344// A + B <1, A>, <1,B>
345// A - B <1, A>, <1,B>
346// 0 - B <-1, B>
347// C * A, <C, A>
348// A + C <1, A> <C, NULL>
349// 0 +/- 0 <0, NULL> (corner case)
350//
351// Legend: A and B are not constant, C is constant
352unsigned FAddend::drillValueDownOneStep
353 (Value *Val, FAddend &Addend0, FAddend &Addend1) {
354 Instruction *I = nullptr;
355 if (!Val || !(I = dyn_cast<Instruction>(Val)))
356 return 0;
357
358 unsigned Opcode = I->getOpcode();
359
360 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
361 ConstantFP *C0, *C1;
362 Value *Opnd0 = I->getOperand(0);
363 Value *Opnd1 = I->getOperand(1);
364 if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
365 Opnd0 = nullptr;
366
367 if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
368 Opnd1 = nullptr;
369
370 if (Opnd0) {
371 if (!C0)
372 Addend0.set(1, Opnd0);
373 else
374 Addend0.set(C0, nullptr);
375 }
376
377 if (Opnd1) {
378 FAddend &Addend = Opnd0 ? Addend1 : Addend0;
379 if (!C1)
380 Addend.set(1, Opnd1);
381 else
382 Addend.set(C1, nullptr);
383 if (Opcode == Instruction::FSub)
384 Addend.negate();
385 }
386
387 if (Opnd0 || Opnd1)
388 return Opnd0 && Opnd1 ? 2 : 1;
389
390 // Both operands are zero. Weird!
391 Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
392 return 1;
393 }
394
395 if (I->getOpcode() == Instruction::FMul) {
396 Value *V0 = I->getOperand(0);
397 Value *V1 = I->getOperand(1);
398 if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
399 Addend0.set(C, V1);
400 return 1;
401 }
402
403 if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
404 Addend0.set(C, V0);
405 return 1;
406 }
407 }
408
409 return 0;
410}
411
412// Try to break *this* addend into two addends. e.g. Suppose this addend is
413// <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
414// i.e. <2.3, X> and <2.3, Y>.
415unsigned FAddend::drillAddendDownOneStep
416 (FAddend &Addend0, FAddend &Addend1) const {
417 if (isConstant())
418 return 0;
419
420 unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
421 if (!BreakNum || Coeff.isOne())
422 return BreakNum;
423
424 Addend0.Scale(Coeff);
425
426 if (BreakNum == 2)
427 Addend1.Scale(Coeff);
428
429 return BreakNum;
430}
431
432Value *FAddCombine::simplify(Instruction *I) {
433 assert(I->hasAllowReassoc() && I->hasNoSignedZeros() &&
434 "Expected 'reassoc'+'nsz' instruction");
435
436 // Currently we are not able to handle vector type.
437 if (I->getType()->isVectorTy())
438 return nullptr;
439
440 assert((I->getOpcode() == Instruction::FAdd ||
441 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
442
443 // Save the instruction before calling other member-functions.
444 Instr = I;
445
446 FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
447
448 unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
449
450 // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
451 unsigned Opnd0_ExpNum = 0;
452 unsigned Opnd1_ExpNum = 0;
453
454 if (!Opnd0.isConstant())
455 Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
456
457 // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
458 if (OpndNum == 2 && !Opnd1.isConstant())
459 Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
460
461 // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
462 if (Opnd0_ExpNum && Opnd1_ExpNum) {
463 AddendVect AllOpnds;
464 AllOpnds.push_back(&Opnd0_0);
465 AllOpnds.push_back(&Opnd1_0);
466 if (Opnd0_ExpNum == 2)
467 AllOpnds.push_back(&Opnd0_1);
468 if (Opnd1_ExpNum == 2)
469 AllOpnds.push_back(&Opnd1_1);
470
471 // Compute instruction quota. We should save at least one instruction.
472 unsigned InstQuota = 0;
473
474 Value *V0 = I->getOperand(0);
475 Value *V1 = I->getOperand(1);
476 InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
477 (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
478
479 if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
480 return R;
481 }
482
483 if (OpndNum != 2) {
484 // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
485 // splitted into two addends, say "V = X - Y", the instruction would have
486 // been optimized into "I = Y - X" in the previous steps.
487 //
488 const FAddendCoef &CE = Opnd0.getCoef();
489 return CE.isOne() ? Opnd0.getSymVal() : nullptr;
490 }
491
492 // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
493 if (Opnd1_ExpNum) {
494 AddendVect AllOpnds;
495 AllOpnds.push_back(&Opnd0);
496 AllOpnds.push_back(&Opnd1_0);
497 if (Opnd1_ExpNum == 2)
498 AllOpnds.push_back(&Opnd1_1);
499
500 if (Value *R = simplifyFAdd(AllOpnds, 1))
501 return R;
502 }
503
504 // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
505 if (Opnd0_ExpNum) {
506 AddendVect AllOpnds;
507 AllOpnds.push_back(&Opnd1);
508 AllOpnds.push_back(&Opnd0_0);
509 if (Opnd0_ExpNum == 2)
510 AllOpnds.push_back(&Opnd0_1);
511
512 if (Value *R = simplifyFAdd(AllOpnds, 1))
513 return R;
514 }
515
516 return nullptr;
517}
518
519Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
520 unsigned AddendNum = Addends.size();
521 assert(AddendNum <= 4 && "Too many addends");
522
523 // For saving intermediate results;
524 unsigned NextTmpIdx = 0;
525 FAddend TmpResult[3];
526
527 // Simplified addends are placed <SimpVect>.
528 AddendVect SimpVect;
529
530 // The outer loop works on one symbolic-value at a time. Suppose the input
531 // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
532 // The symbolic-values will be processed in this order: x, y, z.
533 for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
534
535 const FAddend *ThisAddend = Addends[SymIdx];
536 if (!ThisAddend) {
537 // This addend was processed before.
538 continue;
539 }
540
541 Value *Val = ThisAddend->getSymVal();
542
543 // If the resulting expr has constant-addend, this constant-addend is
544 // desirable to reside at the top of the resulting expression tree. Placing
545 // constant close to super-expr(s) will potentially reveal some
546 // optimization opportunities in super-expr(s). Here we do not implement
547 // this logic intentionally and rely on SimplifyAssociativeOrCommutative
548 // call later.
549
550 unsigned StartIdx = SimpVect.size();
551 SimpVect.push_back(ThisAddend);
552
553 // The inner loop collects addends sharing same symbolic-value, and these
554 // addends will be later on folded into a single addend. Following above
555 // example, if the symbolic value "y" is being processed, the inner loop
556 // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
557 // be later on folded into "<b1+b2, y>".
558 for (unsigned SameSymIdx = SymIdx + 1;
559 SameSymIdx < AddendNum; SameSymIdx++) {
560 const FAddend *T = Addends[SameSymIdx];
561 if (T && T->getSymVal() == Val) {
562 // Set null such that next iteration of the outer loop will not process
563 // this addend again.
564 Addends[SameSymIdx] = nullptr;
565 SimpVect.push_back(T);
566 }
567 }
568
569 // If multiple addends share same symbolic value, fold them together.
570 if (StartIdx + 1 != SimpVect.size()) {
571 FAddend &R = TmpResult[NextTmpIdx ++];
572 R = *SimpVect[StartIdx];
573 for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
574 R += *SimpVect[Idx];
575
576 // Pop all addends being folded and push the resulting folded addend.
577 SimpVect.resize(StartIdx);
578 if (!R.isZero()) {
579 SimpVect.push_back(&R);
580 }
581 }
582 }
583
584 assert((NextTmpIdx <= std::size(TmpResult) + 1) && "out-of-bound access");
585
586 Value *Result;
587 if (!SimpVect.empty())
588 Result = createNaryFAdd(SimpVect, InstrQuota);
589 else {
590 // The addition is folded to 0.0.
591 Result = ConstantFP::get(Instr->getType(), 0.0);
592 }
593
594 return Result;
595}
596
597Value *FAddCombine::createNaryFAdd
598 (const AddendVect &Opnds, unsigned InstrQuota) {
599 assert(!Opnds.empty() && "Expect at least one addend");
600
601 // Step 1: Check if the # of instructions needed exceeds the quota.
602
603 unsigned InstrNeeded = calcInstrNumber(Opnds);
604 if (InstrNeeded > InstrQuota)
605 return nullptr;
606
607 initCreateInstNum();
608
609 // step 2: Emit the N-ary addition.
610 // Note that at most three instructions are involved in Fadd-InstCombine: the
611 // addition in question, and at most two neighboring instructions.
612 // The resulting optimized addition should have at least one less instruction
613 // than the original addition expression tree. This implies that the resulting
614 // N-ary addition has at most two instructions, and we don't need to worry
615 // about tree-height when constructing the N-ary addition.
616
617 Value *LastVal = nullptr;
618 bool LastValNeedNeg = false;
619
620 // Iterate the addends, creating fadd/fsub using adjacent two addends.
621 for (const FAddend *Opnd : Opnds) {
622 bool NeedNeg;
623 Value *V = createAddendVal(*Opnd, NeedNeg);
624 if (!LastVal) {
625 LastVal = V;
626 LastValNeedNeg = NeedNeg;
627 continue;
628 }
629
630 if (LastValNeedNeg == NeedNeg) {
631 LastVal = createFAdd(LastVal, V);
632 continue;
633 }
634
635 if (LastValNeedNeg)
636 LastVal = createFSub(V, LastVal);
637 else
638 LastVal = createFSub(LastVal, V);
639
640 LastValNeedNeg = false;
641 }
642
643 if (LastValNeedNeg) {
644 LastVal = createFNeg(LastVal);
645 }
646
647#ifndef NDEBUG
648 assert(CreateInstrNum == InstrNeeded &&
649 "Inconsistent in instruction numbers");
650#endif
651
652 return LastVal;
653}
654
655Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
656 Value *V = Builder.CreateFSub(Opnd0, Opnd1);
657 if (Instruction *I = dyn_cast<Instruction>(V))
658 createInstPostProc(I);
659 return V;
660}
661
662Value *FAddCombine::createFNeg(Value *V) {
663 Value *NewV = Builder.CreateFNeg(V);
664 if (Instruction *I = dyn_cast<Instruction>(NewV))
665 createInstPostProc(I, true); // fneg's don't receive instruction numbers.
666 return NewV;
667}
668
669Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
670 Value *V = Builder.CreateFAdd(Opnd0, Opnd1);
671 if (Instruction *I = dyn_cast<Instruction>(V))
672 createInstPostProc(I);
673 return V;
674}
675
676Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
677 Value *V = Builder.CreateFMul(Opnd0, Opnd1);
678 if (Instruction *I = dyn_cast<Instruction>(V))
679 createInstPostProc(I);
680 return V;
681}
682
683void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
684 NewInstr->setDebugLoc(Instr->getDebugLoc());
685
686 // Keep track of the number of instruction created.
687 if (!NoNumber)
688 incCreateInstNum();
689
690 // Propagate fast-math flags
691 NewInstr->setFastMathFlags(Instr->getFastMathFlags());
692}
693
694// Return the number of instruction needed to emit the N-ary addition.
695// NOTE: Keep this function in sync with createAddendVal().
696unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
697 unsigned OpndNum = Opnds.size();
698 unsigned InstrNeeded = OpndNum - 1;
699
700 // Adjust the number of instructions needed to emit the N-ary add.
701 for (const FAddend *Opnd : Opnds) {
702 if (Opnd->isConstant())
703 continue;
704
705 // The constant check above is really for a few special constant
706 // coefficients.
707 if (isa<UndefValue>(Opnd->getSymVal()))
708 continue;
709
710 const FAddendCoef &CE = Opnd->getCoef();
711 // Let the addend be "c * x". If "c == +/-1", the value of the addend
712 // is immediately available; otherwise, it needs exactly one instruction
713 // to evaluate the value.
714 if (!CE.isMinusOne() && !CE.isOne())
715 InstrNeeded++;
716 }
717 return InstrNeeded;
718}
719
720// Input Addend Value NeedNeg(output)
721// ================================================================
722// Constant C C false
723// <+/-1, V> V coefficient is -1
724// <2/-2, V> "fadd V, V" coefficient is -2
725// <C, V> "fmul V, C" false
726//
727// NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
728Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
729 const FAddendCoef &Coeff = Opnd.getCoef();
730
731 if (Opnd.isConstant()) {
732 NeedNeg = false;
733 return Coeff.getValue(Instr->getType());
734 }
735
736 Value *OpndVal = Opnd.getSymVal();
737
738 if (Coeff.isMinusOne() || Coeff.isOne()) {
739 NeedNeg = Coeff.isMinusOne();
740 return OpndVal;
741 }
742
743 if (Coeff.isTwo() || Coeff.isMinusTwo()) {
744 NeedNeg = Coeff.isMinusTwo();
745 return createFAdd(OpndVal, OpndVal);
746 }
747
748 NeedNeg = false;
749 return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
750}
751
752// Checks if any operand is negative and we can convert add to sub.
753// This function checks for following negative patterns
754// ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
755// ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
756// XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
758 InstCombiner::BuilderTy &Builder) {
759 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
760
761 // This function creates 2 instructions to replace ADD, we need at least one
762 // of LHS or RHS to have one use to ensure benefit in transform.
763 if (!LHS->hasOneUse() && !RHS->hasOneUse())
764 return nullptr;
765
766 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
767 const APInt *C1 = nullptr, *C2 = nullptr;
768
769 // if ONE is on other side, swap
770 if (match(RHS, m_Add(m_Value(X), m_One())))
771 std::swap(LHS, RHS);
772
773 if (match(LHS, m_Add(m_Value(X), m_One()))) {
774 // if XOR on other side, swap
775 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
776 std::swap(X, RHS);
777
778 if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
779 // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
780 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
781 if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
782 Value *NewAnd = Builder.CreateAnd(Z, *C1);
783 return Builder.CreateSub(RHS, NewAnd, "sub");
784 } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
785 // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
786 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
787 Value *NewOr = Builder.CreateOr(Z, ~(*C1));
788 return Builder.CreateSub(RHS, NewOr, "sub");
789 }
790 }
791 }
792
793 // Restore LHS and RHS
794 LHS = I.getOperand(0);
795 RHS = I.getOperand(1);
796
797 // if XOR is on other side, swap
798 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
799 std::swap(LHS, RHS);
800
801 // C2 is ODD
802 // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
803 // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
804 if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
805 if (C1->countr_zero() == 0)
806 if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
807 Value *NewOr = Builder.CreateOr(Z, ~(*C2));
808 return Builder.CreateSub(RHS, NewOr, "sub");
809 }
810 return nullptr;
811}
812
813/// Wrapping flags may allow combining constants separated by an extend.
815 InstCombiner::BuilderTy &Builder) {
816 Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
817 Type *Ty = Add.getType();
818 Constant *Op1C;
819 if (!match(Op1, m_Constant(Op1C)))
820 return nullptr;
821
822 // Try this match first because it results in an add in the narrow type.
823 // (zext (X +nuw C2)) + C1 --> zext (X + (C2 + trunc(C1)))
824 Value *X;
825 const APInt *C1, *C2;
826 if (match(Op1, m_APInt(C1)) &&
827 match(Op0, m_ZExt(m_NUWAddLike(m_Value(X), m_APInt(C2)))) &&
828 C1->isNegative() && C1->sge(-C2->sext(C1->getBitWidth()))) {
829 APInt NewC = *C2 + C1->trunc(C2->getBitWidth());
830 // If the smaller add will fold to zero, we don't need to check one use.
831 if (NewC.isZero())
832 return new ZExtInst(X, Ty);
833 // Otherwise only do this if the existing zero extend will be removed.
834 if (Op0->hasOneUse())
835 return new ZExtInst(
836 Builder.CreateNUWAdd(X, ConstantInt::get(X->getType(), NewC)), Ty);
837 }
838
839 // More general combining of constants in the wide type.
840 // (sext (X +nsw NarrowC)) + C --> (sext X) + (sext(NarrowC) + C)
841 // or (zext nneg (X +nsw NarrowC)) + C --> (sext X) + (sext(NarrowC) + C)
842 Constant *NarrowC;
843 if (match(Op0, m_OneUse(m_SExtLike(
844 m_NSWAddLike(m_Value(X), m_Constant(NarrowC)))))) {
845 Value *WideC = Builder.CreateSExt(NarrowC, Ty);
846 Value *NewC = Builder.CreateAdd(WideC, Op1C);
847 Value *WideX = Builder.CreateSExt(X, Ty);
848 return BinaryOperator::CreateAdd(WideX, NewC);
849 }
850 // (zext (X +nuw NarrowC)) + C --> (zext X) + (zext(NarrowC) + C)
851 if (match(Op0,
853 Value *WideC = Builder.CreateZExt(NarrowC, Ty);
854 Value *NewC = Builder.CreateAdd(WideC, Op1C);
855 Value *WideX = Builder.CreateZExt(X, Ty);
856 return BinaryOperator::CreateAdd(WideX, NewC);
857 }
858 return nullptr;
859}
860
862 Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
863 Type *Ty = Add.getType();
864 Constant *Op1C;
865 if (!match(Op1, m_ImmConstant(Op1C)))
866 return nullptr;
867
869 return NV;
870
871 if (Instruction *FoldedLogic = foldBinOpSelectBinOp(Add))
872 return FoldedLogic;
873
874 Value *X;
875 Constant *Op00C;
876
877 // add (sub C1, X), C2 --> sub (add C1, C2), X
878 if (match(Op0, m_Sub(m_Constant(Op00C), m_Value(X))))
879 return BinaryOperator::CreateSub(ConstantExpr::getAdd(Op00C, Op1C), X);
880
881 Value *Y;
882
883 // add (sub X, Y), -1 --> add (not Y), X
884 if (match(Op0, m_OneUse(m_Sub(m_Value(X), m_Value(Y)))) &&
885 match(Op1, m_AllOnes()))
886 return BinaryOperator::CreateAdd(Builder.CreateNot(Y), X);
887
888 // zext(bool) + C -> bool ? C + 1 : C
889 if (match(Op0, m_ZExt(m_Value(X))) &&
890 X->getType()->getScalarSizeInBits() == 1)
891 return createSelectInstWithUnknownProfile(X, InstCombiner::AddOne(Op1C),
892 Op1);
893 // sext(bool) + C -> bool ? C - 1 : C
894 if (match(Op0, m_SExt(m_Value(X))) &&
895 X->getType()->getScalarSizeInBits() == 1)
896 return createSelectInstWithUnknownProfile(X, InstCombiner::SubOne(Op1C),
897 Op1);
898
899 // ~X + C --> (C-1) - X
900 if (match(Op0, m_Not(m_Value(X)))) {
901 // ~X + C has NSW and (C-1) won't oveflow => (C-1)-X can have NSW
902 auto *COne = ConstantInt::get(Op1C->getType(), 1);
903 bool WillNotSOV = willNotOverflowSignedSub(Op1C, COne, Add);
904 BinaryOperator *Res =
905 BinaryOperator::CreateSub(ConstantExpr::getSub(Op1C, COne), X);
906 Res->setHasNoSignedWrap(Add.hasNoSignedWrap() && WillNotSOV);
907 return Res;
908 }
909
910 // (iN X s>> (N - 1)) + 1 --> zext (X > -1)
911 const APInt *C;
912 unsigned BitWidth = Ty->getScalarSizeInBits();
913 if (match(Op0, m_OneUse(m_AShr(m_Value(X),
915 match(Op1, m_One()))
916 return new ZExtInst(Builder.CreateIsNotNeg(X, "isnotneg"), Ty);
917
918 if (!match(Op1, m_APInt(C)))
919 return nullptr;
920
921 // (X | Op01C) + Op1C --> X + (Op01C + Op1C) iff the `or` is actually an `add`
922 Constant *Op01C;
923 if (match(Op0, m_DisjointOr(m_Value(X), m_ImmConstant(Op01C)))) {
924 BinaryOperator *NewAdd =
925 BinaryOperator::CreateAdd(X, ConstantExpr::getAdd(Op01C, Op1C));
926 NewAdd->setHasNoSignedWrap(Add.hasNoSignedWrap() &&
927 willNotOverflowSignedAdd(Op01C, Op1C, Add));
928 NewAdd->setHasNoUnsignedWrap(Add.hasNoUnsignedWrap());
929 return NewAdd;
930 }
931
932 // (X | C2) + C --> (X | C2) ^ C2 iff (C2 == -C)
933 const APInt *C2;
934 if (match(Op0, m_Or(m_Value(), m_APInt(C2))) && *C2 == -*C)
935 return BinaryOperator::CreateXor(Op0, ConstantInt::get(Add.getType(), *C2));
936
937 if (C->isSignMask()) {
938 // If wrapping is not allowed, then the addition must set the sign bit:
939 // X + (signmask) --> X | signmask
940 if (Add.hasNoSignedWrap() || Add.hasNoUnsignedWrap())
941 return BinaryOperator::CreateDisjointOr(Op0, Op1);
942
943 // If wrapping is allowed, then the addition flips the sign bit of LHS:
944 // X + (signmask) --> X ^ signmask
945 return BinaryOperator::CreateXor(Op0, Op1);
946 }
947
948 // Is this add the last step in a convoluted sext?
949 // add(zext(xor i16 X, -32768), -32768) --> sext X
950 if (match(Op0, m_ZExt(m_Xor(m_Value(X), m_APInt(C2)))) &&
951 C2->isMinSignedValue() && C2->sext(Ty->getScalarSizeInBits()) == *C)
952 return CastInst::Create(Instruction::SExt, X, Ty);
953
954 if (match(Op0, m_Xor(m_Value(X), m_APInt(C2)))) {
955 // (X ^ signmask) + C --> (X + (signmask ^ C))
956 if (C2->isSignMask())
957 return BinaryOperator::CreateAdd(X, ConstantInt::get(Ty, *C2 ^ *C));
958
959 // If X has no bits set other than an xor mask,
960 // xor is equivalent to sub with no borrow between bits:
961 // add (xor X, C2), C --> sub (C2 + C), X
962 KnownBits LHSKnown = computeKnownBits(X, &Add);
963 if ((*C2 | LHSKnown.Zero).isAllOnes())
964 return BinaryOperator::CreateSub(ConstantInt::get(Ty, *C2 + *C), X);
965
966 // Look for a math+logic pattern that corresponds to sext-in-register of a
967 // value with cleared high bits. Convert that into a pair of shifts:
968 // add (xor X, 0x80), 0xF..F80 --> (X << ShAmtC) >>s ShAmtC
969 // add (xor X, 0xF..F80), 0x80 --> (X << ShAmtC) >>s ShAmtC
970 if (Op0->hasOneUse() && *C2 == -(*C)) {
971 unsigned BitWidth = Ty->getScalarSizeInBits();
972 unsigned ShAmt = 0;
973 if (C->isPowerOf2())
974 ShAmt = BitWidth - C->logBase2() - 1;
975 else if (C2->isPowerOf2())
976 ShAmt = BitWidth - C2->logBase2() - 1;
977 if (ShAmt &&
979 Constant *ShAmtC = ConstantInt::get(Ty, ShAmt);
980 Value *NewShl = Builder.CreateShl(X, ShAmtC, "sext");
981 return BinaryOperator::CreateAShr(NewShl, ShAmtC);
982 }
983 }
984 }
985
986 // umax(X, C) + -C --> usub.sat(X, C)
987 if (match(Op0, m_OneUse(m_UMax(m_Value(X), m_SpecificInt(-*C)))))
988 return replaceInstUsesWith(
989 Add, Builder.CreateBinaryIntrinsic(
990 Intrinsic::usub_sat, X, ConstantInt::get(Add.getType(), -*C)));
991 // uadd.sat(X, C) + -C --> umin(X, ~C)
992 // The saturating add gives X + C or UMAX, so subtracting C leaves X or
993 // UMAX - C. Note UMAX - C == ~C.
994 {
995 APInt SatC = -*C;
997 m_Value(X), m_SpecificInt(SatC)))))
998 return replaceInstUsesWith(
999 Add, Builder.CreateBinaryIntrinsic(Intrinsic::umin, X,
1000 ConstantInt::get(Ty, ~SatC)));
1001 }
1002 // Fold (add (zext (add X, -C)), C) -> (zext X) if X u>= C.
1003 // Truncate C to the narrow type to avoid mismatched width comparisons.
1004 {
1005 const APInt *InnerC;
1006 if (match(Op0, m_ZExt(m_Add(m_Value(X), m_APIntAllowPoison(InnerC))))) {
1007 unsigned NarrowBW = InnerC->getBitWidth();
1008 if (C->isIntN(NarrowBW)) {
1009 APInt NarrowC = C->trunc(NarrowBW);
1010 const SimplifyQuery Q = SQ.getWithInstruction(&Add);
1011 if (*InnerC == -NarrowC &&
1012 (NarrowC.isOne()
1014 : computeKnownBits(X, &Add).getMinValue().uge(NarrowC)))
1015 return new ZExtInst(X, Ty);
1016 }
1017 }
1018 }
1019
1020 return nullptr;
1021}
1022
1023// match variations of a^2 + 2*a*b + b^2
1024//
1025// to reuse the code between the FP and Int versions, the instruction OpCodes
1026// and constant types have been turned into template parameters.
1027//
1028// Mul2Rhs: The constant to perform the multiplicative equivalent of X*2 with;
1029// should be `m_SpecificFP(2.0)` for FP and `m_SpecificInt(1)` for Int
1030// (we're matching `X<<1` instead of `X*2` for Int)
1031template <bool FP, typename Mul2Rhs>
1032static bool matchesSquareSum(BinaryOperator &I, Mul2Rhs M2Rhs, Value *&A,
1033 Value *&B) {
1034 constexpr unsigned MulOp = FP ? Instruction::FMul : Instruction::Mul;
1035 constexpr unsigned AddOp = FP ? Instruction::FAdd : Instruction::Add;
1036 constexpr unsigned Mul2Op = FP ? Instruction::FMul : Instruction::Shl;
1037
1038 // (a * a) + (((a * 2) + b) * b)
1039 if (match(&I, m_c_BinOp(
1040 AddOp, m_BinOp(MulOp, m_Value(A), m_Deferred(A)),
1042 MulOp,
1043 m_c_BinOp(AddOp, m_BinOp(Mul2Op, m_Deferred(A), M2Rhs),
1044 m_Value(B)),
1045 m_Deferred(B))))))
1046 return true;
1047
1048 // ((a * b) * 2) or ((a * 2) * b)
1049 // +
1050 // (a * a + b * b) or (b * b + a * a)
1051 return match(
1052 &I, m_c_BinOp(
1053 AddOp,
1056 Mul2Op, m_BinOp(MulOp, m_Value(A), m_Value(B)), M2Rhs)),
1057 m_OneUse(m_c_BinOp(MulOp, m_BinOp(Mul2Op, m_Value(A), M2Rhs),
1058 m_Value(B)))),
1059 m_OneUse(
1060 m_c_BinOp(AddOp, m_BinOp(MulOp, m_Deferred(A), m_Deferred(A)),
1061 m_BinOp(MulOp, m_Deferred(B), m_Deferred(B))))));
1062}
1063
1064// Fold integer variations of a^2 + 2*a*b + b^2 -> (a + b)^2
1066 Value *A, *B;
1068 Value *AB = Builder.CreateAdd(A, B);
1069 return BinaryOperator::CreateMul(AB, AB);
1070 }
1071 return nullptr;
1072}
1073
1074// Fold floating point variations of a^2 + 2*a*b + b^2 -> (a + b)^2
1075// Requires `nsz` and `reassoc`.
1077 assert(I.hasAllowReassoc() && I.hasNoSignedZeros() && "Assumption mismatch");
1078 Value *A, *B;
1080 Value *AB = Builder.CreateFAddFMF(A, B, &I);
1081 return BinaryOperator::CreateFMulFMF(AB, AB, &I);
1082 }
1083 return nullptr;
1084}
1085
1086// Matches multiplication expression Op * C where C is a constant. Returns the
1087// constant value in C and the other operand in Op. Returns true if such a
1088// match is found.
1089static bool MatchMul(Value *E, Value *&Op, APInt &C) {
1090 const APInt *AI;
1091 if (match(E, m_Mul(m_Value(Op), m_APInt(AI)))) {
1092 C = *AI;
1093 return true;
1094 }
1095 if (match(E, m_Shl(m_Value(Op), m_APInt(AI)))) {
1096 C = APInt(AI->getBitWidth(), 1);
1097 C <<= *AI;
1098 return true;
1099 }
1100 return false;
1101}
1102
1103// Matches remainder expression Op % C where C is a constant. Returns the
1104// constant value in C and the other operand in Op. Returns the signedness of
1105// the remainder operation in IsSigned. Returns true if such a match is
1106// found.
1107static bool MatchRem(Value *E, Value *&Op, APInt &C, bool &IsSigned) {
1108 const APInt *AI;
1109 IsSigned = false;
1110 if (match(E, m_SRem(m_Value(Op), m_APInt(AI)))) {
1111 IsSigned = true;
1112 C = *AI;
1113 return true;
1114 }
1115 if (match(E, m_URem(m_Value(Op), m_APInt(AI)))) {
1116 C = *AI;
1117 return true;
1118 }
1119 if (match(E, m_And(m_Value(Op), m_APInt(AI))) && (*AI + 1).isPowerOf2()) {
1120 C = *AI + 1;
1121 return true;
1122 }
1123 return false;
1124}
1125
1126// Matches division expression Op / C with the given signedness as indicated
1127// by IsSigned, where C is a constant. Returns the constant value in C and the
1128// other operand in Op. Returns true if such a match is found.
1129static bool MatchDiv(Value *E, Value *&Op, APInt &C, bool IsSigned) {
1130 const APInt *AI;
1131 if (IsSigned && match(E, m_SDiv(m_Value(Op), m_APInt(AI)))) {
1132 C = *AI;
1133 return true;
1134 }
1135 if (!IsSigned) {
1136 if (match(E, m_UDiv(m_Value(Op), m_APInt(AI)))) {
1137 C = *AI;
1138 return true;
1139 }
1140 if (match(E, m_LShr(m_Value(Op), m_APInt(AI)))) {
1141 C = APInt(AI->getBitWidth(), 1);
1142 C <<= *AI;
1143 return true;
1144 }
1145 }
1146 return false;
1147}
1148
1149// Returns whether C0 * C1 with the given signedness overflows.
1150static bool MulWillOverflow(APInt &C0, APInt &C1, bool IsSigned) {
1151 bool overflow;
1152 if (IsSigned)
1153 (void)C0.smul_ov(C1, overflow);
1154 else
1155 (void)C0.umul_ov(C1, overflow);
1156 return overflow;
1157}
1158
1159// Simplifies X % C0 + (( X / C0 ) % C1) * C0 to X % (C0 * C1), where (C0 * C1)
1160// does not overflow.
1161// Simplifies (X / C0) * C1 + (X % C0) * C2 to
1162// (X / C0) * (C1 - C2 * C0) + X * C2
1164 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1165 Value *X, *MulOpV;
1166 APInt C0, MulOpC;
1167 bool IsSigned;
1168 // Match I = X % C0 + MulOpV * C0
1169 if (((MatchRem(LHS, X, C0, IsSigned) && MatchMul(RHS, MulOpV, MulOpC)) ||
1170 (MatchRem(RHS, X, C0, IsSigned) && MatchMul(LHS, MulOpV, MulOpC))) &&
1171 C0 == MulOpC) {
1172 Value *RemOpV;
1173 APInt C1;
1174 bool Rem2IsSigned;
1175 // Match MulOpC = RemOpV % C1
1176 if (MatchRem(MulOpV, RemOpV, C1, Rem2IsSigned) &&
1177 IsSigned == Rem2IsSigned) {
1178 Value *DivOpV;
1179 APInt DivOpC;
1180 // Match RemOpV = X / C0
1181 if (MatchDiv(RemOpV, DivOpV, DivOpC, IsSigned) && X == DivOpV &&
1182 C0 == DivOpC && !MulWillOverflow(C0, C1, IsSigned)) {
1183 Value *NewDivisor = ConstantInt::get(X->getType(), C0 * C1);
1184 return IsSigned ? Builder.CreateSRem(X, NewDivisor, "srem")
1185 : Builder.CreateURem(X, NewDivisor, "urem");
1186 }
1187 }
1188 }
1189
1190 // Match I = (X / C0) * C1 + (X % C0) * C2.
1191 auto FoldDivRem = [&](Value *DivSide, Value *RemSide) -> Value * {
1192 Value *Div, *Rem;
1193 APInt C1, C2;
1194 if (!DivSide->hasOneUse() || !MatchMul(DivSide, Div, C1))
1195 Div = DivSide, C1 = APInt(I.getType()->getScalarSizeInBits(), 1);
1196 if (!RemSide->hasOneUse() || !MatchMul(RemSide, Rem, C2))
1197 Rem = RemSide, C2 = APInt(I.getType()->getScalarSizeInBits(), 1);
1198 Value *DivOpV;
1199 APInt DivOpC;
1200 if (MatchRem(Rem, X, C0, IsSigned) &&
1201 MatchDiv(Div, DivOpV, DivOpC, IsSigned) && X == DivOpV &&
1202 C0 == DivOpC &&
1203 // Avoid unprofitable replacement of and with mul.
1204 !(C1.isOne() && !IsSigned && DivOpC.isPowerOf2() && DivOpC != 2)) {
1205 APInt NewC = C1 - C2 * C0;
1206 if (!NewC.isZero() && !Rem->hasOneUse())
1207 return nullptr;
1208 if (!isGuaranteedNotToBeUndef(X, &AC, &I, &DT))
1209 return nullptr;
1210 Value *MulXC2 = Builder.CreateMul(X, ConstantInt::get(X->getType(), C2));
1211 if (NewC.isZero())
1212 return MulXC2;
1213 return Builder.CreateAdd(
1214 Builder.CreateMul(Div, ConstantInt::get(X->getType(), NewC)), MulXC2);
1215 }
1216 return nullptr;
1217 };
1218 if (Value *V = FoldDivRem(LHS, RHS))
1219 return V;
1220 if (Value *V = FoldDivRem(RHS, LHS))
1221 return V;
1222
1223 return nullptr;
1224}
1225
1226/// Fold
1227/// (1 << NBits) - 1
1228/// Into:
1229/// ~(-(1 << NBits))
1230/// Because a 'not' is better for bit-tracking analysis and other transforms
1231/// than an 'add'. The new shl is always nsw, and is nuw if old `and` was.
1233 InstCombiner::BuilderTy &Builder) {
1234 Value *NBits;
1235 if (!match(&I, m_Add(m_OneUse(m_Shl(m_One(), m_Value(NBits))), m_AllOnes())))
1236 return nullptr;
1237
1238 Constant *MinusOne = Constant::getAllOnesValue(NBits->getType());
1239 Value *NotMask = Builder.CreateShl(MinusOne, NBits, "notmask");
1240 // Be wary of constant folding.
1241 if (auto *BOp = dyn_cast<BinaryOperator>(NotMask)) {
1242 // Always NSW. But NUW propagates from `add`.
1243 BOp->setHasNoSignedWrap();
1244 BOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1245 }
1246
1247 return BinaryOperator::CreateNot(NotMask, I.getName());
1248}
1249
1251 assert(I.getOpcode() == Instruction::Add && "Expecting add instruction");
1252 Type *Ty = I.getType();
1253 auto getUAddSat = [&]() {
1254 return Intrinsic::getOrInsertDeclaration(I.getModule(), Intrinsic::uadd_sat,
1255 Ty);
1256 };
1257
1258 // add (umin X, ~Y), Y --> uaddsat X, Y
1259 Value *X, *Y;
1261 m_Deferred(Y))))
1262 return CallInst::Create(getUAddSat(), { X, Y });
1263
1264 // add (umin X, ~C), C --> uaddsat X, C
1265 const APInt *C, *NotC;
1266 if (match(&I, m_Add(m_UMin(m_Value(X), m_APInt(NotC)), m_APInt(C))) &&
1267 *C == ~*NotC)
1268 return CallInst::Create(getUAddSat(), { X, ConstantInt::get(Ty, *C) });
1269
1270 return nullptr;
1271}
1272
1273// Transform:
1274// (add A, (shl (neg B), Y))
1275// -> (sub A, (shl B, Y))
1277 const BinaryOperator &I) {
1278 Value *A, *B, *Cnt;
1279 if (match(&I,
1281 m_Value(A)))) {
1282 Value *NewShl = Builder.CreateShl(B, Cnt);
1283 return BinaryOperator::CreateSub(A, NewShl);
1284 }
1285 return nullptr;
1286}
1287
1288/// Try to reduce signed division by power-of-2 to an arithmetic shift right.
1290 // Division must be by power-of-2, but not the minimum signed value.
1291 Value *X;
1292 const APInt *DivC;
1293 if (!match(Add.getOperand(0), m_SDiv(m_Value(X), m_Power2(DivC))) ||
1294 DivC->isNegative())
1295 return nullptr;
1296
1297 // Rounding is done by adding -1 if the dividend (X) is negative and has any
1298 // low bits set. It recognizes two canonical patterns:
1299 // 1. For an 'ugt' cmp with the signed minimum value (SMIN), the
1300 // pattern is: sext (icmp ugt (X & (DivC - 1)), SMIN).
1301 // 2. For an 'eq' cmp, the pattern's: sext (icmp eq X & (SMIN + 1), SMIN + 1).
1302 // Note that, by the time we end up here, if possible, ugt has been
1303 // canonicalized into eq.
1304 const APInt *MaskC, *MaskCCmp;
1305 CmpPredicate Pred;
1306 if (!match(Add.getOperand(1),
1307 m_SExt(m_ICmp(Pred, m_And(m_Specific(X), m_APInt(MaskC)),
1308 m_APInt(MaskCCmp)))))
1309 return nullptr;
1310
1311 if ((Pred != ICmpInst::ICMP_UGT || !MaskCCmp->isSignMask()) &&
1312 (Pred != ICmpInst::ICMP_EQ || *MaskCCmp != *MaskC))
1313 return nullptr;
1314
1315 APInt SMin = APInt::getSignedMinValue(Add.getType()->getScalarSizeInBits());
1316 bool IsMaskValid = Pred == ICmpInst::ICMP_UGT
1317 ? (*MaskC == (SMin | (*DivC - 1)))
1318 : (*DivC == 2 && *MaskC == SMin + 1);
1319 if (!IsMaskValid)
1320 return nullptr;
1321
1322 // (X / DivC) + sext ((X & (SMin | (DivC - 1)) >u SMin) --> X >>s log2(DivC)
1323 return BinaryOperator::CreateAShr(
1324 X, ConstantInt::get(Add.getType(), DivC->exactLogBase2()));
1325}
1326
1328 bool NSW, bool NUW) {
1329 Value *A, *B, *C;
1330 if (match(LHS, m_Sub(m_Value(A), m_Value(B))) &&
1331 match(RHS, m_Sub(m_Value(C), m_Specific(A)))) {
1332 Instruction *R = BinaryOperator::CreateSub(C, B);
1333 bool NSWOut = NSW && match(LHS, m_NSWSub(m_Value(), m_Value())) &&
1334 match(RHS, m_NSWSub(m_Value(), m_Value()));
1335
1336 bool NUWOut = match(LHS, m_NUWSub(m_Value(), m_Value())) &&
1337 match(RHS, m_NUWSub(m_Value(), m_Value()));
1338 R->setHasNoSignedWrap(NSWOut);
1339 R->setHasNoUnsignedWrap(NUWOut);
1340 return R;
1341 }
1342
1343 // ((X s/ C1) << C2) + X => X s% -C1 where -C1 is 1 << C2
1344 const APInt *C1, *C2;
1345 if (match(LHS, m_Shl(m_SDiv(m_Specific(RHS), m_APInt(C1)), m_APInt(C2)))) {
1346 APInt One(C2->getBitWidth(), 1);
1347 APInt MinusC1 = -(*C1);
1348 if (MinusC1 == (One << *C2)) {
1349 Constant *NewRHS = ConstantInt::get(RHS->getType(), MinusC1);
1350 return BinaryOperator::CreateSRem(RHS, NewRHS);
1351 }
1352 }
1353
1354 // (A + C) + (B & ~C) == A + (B | C)
1355 if (match(LHS, m_c_Add(m_Value(A), m_APInt(C1))) &&
1356 match(RHS, m_c_And(m_Value(B), m_SpecificInt(~*C1)))) {
1357 // Replacing one add with {or, add}. Avoid growth if both sides are shared.
1358 if (!LHS->hasOneUse() && !RHS->hasOneUse())
1359 return nullptr;
1360
1361 bool NSWOut = NSW && match(LHS, m_NSWAdd(m_Value(), m_Value()));
1362 bool NUWOut = NUW && match(LHS, m_NUWAdd(m_Value(), m_Value()));
1363 Value *NewOr =
1364 Builder.CreateOr(B, Constant::getIntegerValue(LHS->getType(), *C1));
1365 Instruction *NewAdd = BinaryOperator::CreateAdd(A, NewOr);
1366 NewAdd->setHasNoSignedWrap(NSWOut);
1367 NewAdd->setHasNoUnsignedWrap(NUWOut);
1368 return NewAdd;
1369 }
1370
1371 return nullptr;
1372}
1373
1376 BinaryOperator &I) {
1377 assert((I.getOpcode() == Instruction::Add ||
1378 I.getOpcode() == Instruction::Or ||
1379 I.getOpcode() == Instruction::Sub) &&
1380 "Expecting add/or/sub instruction");
1381
1382 // We have a subtraction/addition between a (potentially truncated) *logical*
1383 // right-shift of X and a "select".
1384 Value *X, *Select;
1385 Instruction *LowBitsToSkip, *Extract;
1387 Extract, m_LShr(m_Value(X),
1388 m_Instruction(LowBitsToSkip)))),
1389 m_Value(Select))))
1390 return nullptr;
1391
1392 // `add`/`or` is commutative; but for `sub`, "select" *must* be on RHS.
1393 if (I.getOpcode() == Instruction::Sub && I.getOperand(1) != Select)
1394 return nullptr;
1395
1396 Type *XTy = X->getType();
1397 bool HadTrunc = I.getType() != XTy;
1398
1399 // If there was a truncation of extracted value, then we'll need to produce
1400 // one extra instruction, so we need to ensure one instruction will go away.
1401 if (HadTrunc && !match(&I, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
1402 return nullptr;
1403
1404 // Extraction should extract high NBits bits, with shift amount calculated as:
1405 // low bits to skip = shift bitwidth - high bits to extract
1406 // The shift amount itself may be extended, and we need to look past zero-ext
1407 // when matching NBits, that will matter for matching later.
1408 Value *NBits;
1409 if (!match(LowBitsToSkip,
1411 m_ZExtOrSelf(m_Value(NBits))))))
1412 return nullptr;
1413
1414 // Sign-extending value can be zero-extended if we `sub`tract it,
1415 // or sign-extended otherwise.
1416 auto SkipExtInMagic = [&I](Value *&V) {
1417 if (I.getOpcode() == Instruction::Sub)
1418 match(V, m_ZExtOrSelf(m_Value(V)));
1419 else
1420 match(V, m_SExtOrSelf(m_Value(V)));
1421 };
1422
1423 // Now, finally validate the sign-extending magic.
1424 // `select` itself may be appropriately extended, look past that.
1425 SkipExtInMagic(Select);
1426
1427 CmpPredicate Pred;
1428 const APInt *Thr;
1429 Value *SignExtendingValue, *Zero;
1430 bool ShouldSignext;
1431 // It must be a select between two values we will later establish to be a
1432 // sign-extending value and a zero constant. The condition guarding the
1433 // sign-extension must be based on a sign bit of the same X we had in `lshr`.
1434 if (!match(Select, m_Select(m_ICmp(Pred, m_Specific(X), m_APInt(Thr)),
1435 m_Value(SignExtendingValue), m_Value(Zero))) ||
1436 !isSignBitCheck(Pred, *Thr, ShouldSignext))
1437 return nullptr;
1438
1439 // icmp-select pair is commutative.
1440 if (!ShouldSignext)
1441 std::swap(SignExtendingValue, Zero);
1442
1443 // If we should not perform sign-extension then we must add/or/subtract zero.
1444 if (!match(Zero, m_Zero()))
1445 return nullptr;
1446 // Otherwise, it should be some constant, left-shifted by the same NBits we
1447 // had in `lshr`. Said left-shift can also be appropriately extended.
1448 // Again, we must look past zero-ext when looking for NBits.
1449 SkipExtInMagic(SignExtendingValue);
1450 Constant *SignExtendingValueBaseConstant;
1451 if (!match(SignExtendingValue,
1452 m_Shl(m_Constant(SignExtendingValueBaseConstant),
1453 m_ZExtOrSelf(m_Specific(NBits)))))
1454 return nullptr;
1455 // If we `sub`, then the constant should be one, else it should be all-ones.
1456 if (I.getOpcode() == Instruction::Sub
1457 ? !match(SignExtendingValueBaseConstant, m_One())
1458 : !match(SignExtendingValueBaseConstant, m_AllOnes()))
1459 return nullptr;
1460
1461 auto *NewAShr = BinaryOperator::CreateAShr(X, LowBitsToSkip,
1462 Extract->getName() + ".sext");
1463 NewAShr->copyIRFlags(Extract); // Preserve `exact`-ness.
1464 if (!HadTrunc)
1465 return NewAShr;
1466
1467 Builder.Insert(NewAShr);
1468 return TruncInst::CreateTruncOrBitCast(NewAShr, I.getType());
1469}
1470
1471/// This is a specialization of a more general transform from
1472/// foldUsingDistributiveLaws. If that code can be made to work optimally
1473/// for multi-use cases or propagating nsw/nuw, then we would not need this.
1475 InstCombiner::BuilderTy &Builder) {
1476 // TODO: Also handle mul by doubling the shift amount?
1477 assert((I.getOpcode() == Instruction::Add ||
1478 I.getOpcode() == Instruction::Sub) &&
1479 "Expected add/sub");
1480 auto *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
1481 auto *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
1482 if (!Op0 || !Op1 || !(Op0->hasOneUse() || Op1->hasOneUse()))
1483 return nullptr;
1484
1485 Value *X, *Y, *ShAmt;
1486 if (!match(Op0, m_Shl(m_Value(X), m_Value(ShAmt))) ||
1487 !match(Op1, m_Shl(m_Value(Y), m_Specific(ShAmt))))
1488 return nullptr;
1489
1490 // No-wrap propagates only when all ops have no-wrap.
1491 bool HasNSW = I.hasNoSignedWrap() && Op0->hasNoSignedWrap() &&
1492 Op1->hasNoSignedWrap();
1493 bool HasNUW = I.hasNoUnsignedWrap() && Op0->hasNoUnsignedWrap() &&
1494 Op1->hasNoUnsignedWrap();
1495
1496 // add/sub (X << ShAmt), (Y << ShAmt) --> (add/sub X, Y) << ShAmt
1497 Value *NewMath = Builder.CreateBinOp(I.getOpcode(), X, Y);
1498 if (auto *NewI = dyn_cast<BinaryOperator>(NewMath)) {
1499 NewI->setHasNoSignedWrap(HasNSW);
1500 NewI->setHasNoUnsignedWrap(HasNUW);
1501 }
1502 auto *NewShl = BinaryOperator::CreateShl(NewMath, ShAmt);
1503 NewShl->setHasNoSignedWrap(HasNSW);
1504 NewShl->setHasNoUnsignedWrap(HasNUW);
1505 return NewShl;
1506}
1507
1508/// Reduce a sequence of masked half-width multiplies to a single multiply.
1509/// ((XLow * YHigh) + (YLow * XHigh)) << HalfBits) + (XLow * YLow) --> X * Y
1511 unsigned BitWidth = I.getType()->getScalarSizeInBits();
1512 // Skip the odd bitwidth types.
1513 if ((BitWidth & 0x1))
1514 return nullptr;
1515
1516 unsigned HalfBits = BitWidth >> 1;
1517 APInt HalfMask = APInt::getMaxValue(HalfBits);
1518
1519 // ResLo = (CrossSum << HalfBits) + (YLo * XLo)
1520 Value *XLo, *YLo;
1521 Value *CrossSum;
1522 // Require one-use on the multiply to avoid increasing the number of
1523 // multiplications.
1524 if (!match(&I, m_c_Add(m_Shl(m_Value(CrossSum), m_SpecificInt(HalfBits)),
1525 m_OneUse(m_Mul(m_Value(YLo), m_Value(XLo))))))
1526 return nullptr;
1527
1528 // XLo = X & HalfMask
1529 // YLo = Y & HalfMask
1530 // TODO: Refactor with SimplifyDemandedBits or KnownBits known leading zeros
1531 // to enhance robustness
1532 Value *X, *Y;
1533 if (!match(XLo, m_And(m_Value(X), m_SpecificInt(HalfMask))) ||
1534 !match(YLo, m_And(m_Value(Y), m_SpecificInt(HalfMask))))
1535 return nullptr;
1536
1537 // CrossSum = (X' * (Y >> Halfbits)) + (Y' * (X >> HalfBits))
1538 // X' can be either X or XLo in the pattern (and the same for Y')
1539 if (match(CrossSum,
1544 return BinaryOperator::CreateMul(X, Y);
1545
1546 return nullptr;
1547}
1548
1549/// Return true if X + (Y-1) is provably non-wrapping in X's type
1550static bool checkDivCeilNUW(Value *X, Value *Y, const SimplifyQuery &SQ) {
1551 ConstantRange CRX = computeConstantRange(X, /*ForSigned=*/false, SQ);
1552 ConstantRange CRY = computeConstantRange(Y, /*ForSigned=*/false, SQ);
1553 APInt MinY = CRY.getUnsignedMin();
1554 APInt MaxX = CRX.getUnsignedMax();
1555 APInt MaxY = CRY.getUnsignedMax();
1556
1557 return !MinY.isZero() && !MaxX.ugt(-MaxY);
1558}
1559
1560/// Fold the div_ceil idiom in both forms:
1561/// add(udiv(X, Y), zext(icmp ne(urem(X, Y), 0)))
1562/// -> udiv(add nuw(X, Y - 1), Y)
1563/// add(zext(udiv(X, Y)), zext(icmp ne(urem(X, Y), 0)))
1564/// -> zext(udiv(add nuw(X, Y - 1), Y))
1565/// The zext form applies when udiv/urem operate in a narrower type than the
1566/// add.
1568 Value *X, *Y;
1569
1570 auto UDivPat = m_OneUse(m_UDiv(m_Value(X), m_Value(Y)));
1571 auto URemPat = m_OneUse(m_URem(m_Deferred(X), m_Deferred(Y)));
1572 auto ICmpPat = m_OneUse(m_SpecificICmp(ICmpInst::ICMP_NE, URemPat, m_Zero()));
1573 auto DivPat = m_OneUse(m_ZExtOrSelf(UDivPat));
1574 auto ZExtCmpPat = m_OneUse(m_ZExt(ICmpPat));
1575
1576 if (!match(&I, m_c_Add(DivPat, ZExtCmpPat)) ||
1577 !checkDivCeilNUW(X, Y, SQ.getWithInstruction(&I)))
1578 return nullptr;
1579
1580 Value *YMinusOne =
1581 Builder.CreateAdd(Y, ConstantInt::getAllOnesValue(Y->getType()));
1582 Value *NUWAdd = Builder.CreateNUWAdd(X, YMinusOne);
1583 if (X->getType() != I.getType()) {
1584 Value *Div = Builder.CreateUDiv(NUWAdd, Y);
1585 return new ZExtInst(Div, I.getType());
1586 }
1587 return BinaryOperator::CreateUDiv(NUWAdd, Y);
1588}
1589
1591 if (Value *V = simplifyAddInst(I.getOperand(0), I.getOperand(1),
1592 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
1593 SQ.getWithInstruction(&I)))
1594 return replaceInstUsesWith(I, V);
1595
1597 return &I;
1598
1600 return X;
1601
1603 return Phi;
1604
1605 // (A*B)+(A*C) -> A*(B+C) etc
1607 return replaceInstUsesWith(I, V);
1608
1609 if (Instruction *R = foldBoxMultiply(I))
1610 return R;
1611
1613 return R;
1614
1616 return X;
1617
1619 return X;
1620
1622 return R;
1623
1625 return R;
1626
1627 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1628 if (Instruction *R = foldAddLikeCommutative(LHS, RHS, I.hasNoSignedWrap(),
1629 I.hasNoUnsignedWrap()))
1630 return R;
1631 if (Instruction *R = foldAddLikeCommutative(RHS, LHS, I.hasNoSignedWrap(),
1632 I.hasNoUnsignedWrap()))
1633 return R;
1634 Type *Ty = I.getType();
1635 if (Ty->isIntOrIntVectorTy(1))
1636 return BinaryOperator::CreateXor(LHS, RHS);
1637
1638 // X + X --> X << 1
1639 if (LHS == RHS) {
1640 auto *Shl = BinaryOperator::CreateShl(LHS, ConstantInt::get(Ty, 1));
1641 Shl->setHasNoSignedWrap(I.hasNoSignedWrap());
1642 Shl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1643 return Shl;
1644 }
1645
1646 Value *A, *B;
1647 if (match(LHS, m_Neg(m_Value(A)))) {
1648 // -A + -B --> -(A + B)
1649 if (match(RHS, m_Neg(m_Value(B))))
1650 return BinaryOperator::CreateNeg(Builder.CreateAdd(A, B));
1651
1652 // -A + B --> B - A
1653 auto *Sub = BinaryOperator::CreateSub(RHS, A);
1654 auto *OB0 = cast<OverflowingBinaryOperator>(LHS);
1655 Sub->setHasNoSignedWrap(I.hasNoSignedWrap() && OB0->hasNoSignedWrap());
1656
1657 return Sub;
1658 }
1659
1660 // A + -B --> A - B
1661 if (match(RHS, m_Neg(m_Value(B)))) {
1662 auto *Sub = BinaryOperator::CreateSub(LHS, B);
1663 auto *OBO = cast<OverflowingBinaryOperator>(RHS);
1664 Sub->setHasNoSignedWrap(I.hasNoSignedWrap() && OBO->hasNoSignedWrap());
1665 return Sub;
1666 }
1667
1669 return replaceInstUsesWith(I, V);
1670
1671 // (A + 1) + ~B --> A - B
1672 // ~B + (A + 1) --> A - B
1673 // (~B + A) + 1 --> A - B
1674 // (A + ~B) + 1 --> A - B
1675 // This relies on the ~B == -1-B identity.
1676 if (match(&I, m_c_BinOp(m_Add(m_Value(A), m_One()), m_Not(m_Value(B)))) ||
1678 return BinaryOperator::CreateSub(A, B);
1679
1680 {
1681 // (A + C) + ~B --> A - B + (C-1)
1682 // ~B + (A + C) --> A - B + (C-1)
1683 // (~B + A) + C --> A - B + (C-1)
1684 // (A + ~B) + C --> A - B + (C-1)
1685 // With constant C, subtraction of one is free, so we replace three ops
1686 // (two adds and a bitwise-not) with two (sub and add).
1687 const APInt *C;
1689 m_Not(m_Value(B)))) ||
1691 m_APIntAllowPoison(C)))) {
1692 Value *Sub = Builder.CreateSub(A, B);
1693 return BinaryOperator::CreateAdd(Sub, ConstantInt::get(Ty, *C - 1));
1694 }
1695 }
1696
1697 // (A + RHS) + RHS --> A + (RHS << 1)
1698 if (match(LHS, m_OneUse(m_c_Add(m_Value(A), m_Specific(RHS)))))
1699 return BinaryOperator::CreateAdd(A, Builder.CreateShl(RHS, 1, "reass.add"));
1700
1701 // LHS + (A + LHS) --> A + (LHS << 1)
1702 if (match(RHS, m_OneUse(m_c_Add(m_Value(A), m_Specific(LHS)))))
1703 return BinaryOperator::CreateAdd(A, Builder.CreateShl(LHS, 1, "reass.add"));
1704
1705 {
1706 // (A + C1) + (C2 - B) --> (A - B) + (C1 + C2)
1707 Constant *C1, *C2;
1709 m_Sub(m_ImmConstant(C2), m_Value(B)))) &&
1710 (LHS->hasOneUse() || RHS->hasOneUse())) {
1711 Value *Sub = Builder.CreateSub(A, B);
1712 return BinaryOperator::CreateAdd(Sub, ConstantExpr::getAdd(C1, C2));
1713 }
1714
1715 // Canonicalize a constant sub operand as an add operand for better folding:
1716 // (C1 - A) + B --> (B - A) + C1
1718 m_Value(B)))) {
1719 Value *Sub = Builder.CreateSub(B, A, "reass.sub");
1720 return BinaryOperator::CreateAdd(Sub, C1);
1721 }
1722 }
1723
1724 // X % C0 + (( X / C0 ) % C1) * C0 => X % (C0 * C1)
1726
1727 const APInt *C1;
1728 // (A & 2^C1) + A => A & (2^C1 - 1) iff bit C1 in A is a sign bit
1729 if (match(&I, m_c_Add(m_And(m_Value(A), m_APInt(C1)), m_Deferred(A))) &&
1730 C1->isPowerOf2() && (ComputeNumSignBits(A) > C1->countl_zero())) {
1731 Constant *NewMask = ConstantInt::get(RHS->getType(), *C1 - 1);
1732 return BinaryOperator::CreateAnd(A, NewMask);
1733 }
1734
1735 // ZExt (B - A) + ZExt(A) --> ZExt(B)
1736 if ((match(RHS, m_ZExt(m_Value(A))) &&
1737 match(LHS, m_ZExt(m_NUWSub(m_Value(B), m_Specific(A))))) ||
1738 (match(LHS, m_ZExt(m_Value(A))) &&
1740 return new ZExtInst(B, LHS->getType());
1741
1742 // zext(A) + sext(A) --> 0 if A is i1
1744 A->getType()->isIntOrIntVectorTy(1))
1745 return replaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1746
1747 // sext(A < B) + zext(A > B) => ucmp/scmp(A, B)
1748 CmpPredicate LTPred, GTPred;
1749 if (match(&I,
1750 m_c_Add(m_SExt(m_c_ICmp(LTPred, m_Value(A), m_Value(B))),
1751 m_ZExt(m_c_ICmp(GTPred, m_Deferred(A), m_Deferred(B))))) &&
1752 A->getType()->isIntOrIntVectorTy()) {
1753 if (ICmpInst::isGT(LTPred)) {
1754 std::swap(LTPred, GTPred);
1755 std::swap(A, B);
1756 }
1757
1758 if (ICmpInst::isLT(LTPred) && ICmpInst::isGT(GTPred) &&
1759 ICmpInst::isSigned(LTPred) == ICmpInst::isSigned(GTPred))
1760 return replaceInstUsesWith(
1761 I, Builder.CreateIntrinsic(
1762 Ty,
1763 ICmpInst::isSigned(LTPred) ? Intrinsic::scmp : Intrinsic::ucmp,
1764 {A, B}));
1765 }
1766
1767 // A+B --> A|B iff A and B have no bits set in common.
1768 WithCache<const Value *> LHSCache(LHS), RHSCache(RHS);
1769 switch (
1770 getNoCommonBitsSetResult(LHSCache, RHSCache, SQ.getWithInstruction(&I))) {
1772 return BinaryOperator::CreateDisjointOr(LHS, RHS);
1774 return BinaryOperator::CreateOr(LHS, RHS);
1776 break;
1777 }
1778
1779 if (Instruction *Ext = narrowMathIfNoOverflow(I))
1780 return Ext;
1781
1782 // (add (xor A, B) (and A, B)) --> (or A, B)
1783 // (add (and A, B) (xor A, B)) --> (or A, B)
1784 if (match(&I, m_c_BinOp(m_Xor(m_Value(A), m_Value(B)),
1786 return BinaryOperator::CreateOr(A, B);
1787
1788 // (add (or A, B) (and A, B)) --> (add A, B)
1789 // (add (and A, B) (or A, B)) --> (add A, B)
1790 if (match(&I, m_c_BinOp(m_Or(m_Value(A), m_Value(B)),
1792 // Replacing operands in-place to preserve nuw/nsw flags.
1793 replaceOperand(I, 0, A);
1794 replaceOperand(I, 1, B);
1795 return &I;
1796 }
1797
1798 // (add A (or A, -A)) --> (and (add A, -1) A)
1799 // (add A (or -A, A)) --> (and (add A, -1) A)
1800 // (add (or A, -A) A) --> (and (add A, -1) A)
1801 // (add (or -A, A) A) --> (and (add A, -1) A)
1803 m_Deferred(A)))))) {
1804 Value *Add =
1805 Builder.CreateAdd(A, Constant::getAllOnesValue(A->getType()), "",
1806 I.hasNoUnsignedWrap(), I.hasNoSignedWrap());
1807 return BinaryOperator::CreateAnd(Add, A);
1808 }
1809
1810 // Align-up idiom:
1811 // X + ((-X) & (C - 1)) --> (X + C - 1) & -C
1812 // ((X - 1) | (C - 1)) + 1 -> (X + C - 1) & -C
1813 // For a power-of-two C. Note -C == ~(C - 1), so the mask is simply the
1814 // inverted low-bit mask.
1815 {
1816 const APInt *LowMask;
1817 if (match(&I,
1819 m_Deferred(A))) ||
1821 m_LowBitMask(LowMask))),
1822 m_One()))
1823
1824 ) {
1825 Value *NewAdd = Builder.CreateAdd(A, ConstantInt::get(Ty, *LowMask));
1826 return BinaryOperator::CreateAnd(NewAdd, ConstantInt::get(Ty, ~*LowMask));
1827 }
1828 }
1829
1830 // Canonicalize ((A & -A) - 1) --> ((A - 1) & ~A)
1831 // Forms all commutable operations, and simplifies ctpop -> cttz folds.
1832 if (match(&I,
1834 m_AllOnes()))) {
1836 Value *Dec = Builder.CreateAdd(A, AllOnes);
1837 Value *Not = Builder.CreateXor(A, AllOnes);
1838 return BinaryOperator::CreateAnd(Dec, Not);
1839 }
1840
1841 // Disguised reassociation/factorization:
1842 // ~(A * C1) + A
1843 // ((A * -C1) - 1) + A
1844 // ((A * -C1) + A) - 1
1845 // (A * (1 - C1)) - 1
1846 if (match(&I,
1848 m_Deferred(A)))) {
1849 Type *Ty = I.getType();
1850 Constant *NewMulC = ConstantInt::get(Ty, 1 - *C1);
1851 Value *NewMul = Builder.CreateMul(A, NewMulC);
1852 return BinaryOperator::CreateAdd(NewMul, ConstantInt::getAllOnesValue(Ty));
1853 }
1854
1855 // (A * -2**C) + B --> B - (A << C)
1856 const APInt *NegPow2C;
1857 if (match(&I, m_c_Add(m_OneUse(m_Mul(m_Value(A), m_NegatedPower2(NegPow2C))),
1858 m_Value(B)))) {
1859 Constant *ShiftAmtC = ConstantInt::get(Ty, NegPow2C->countr_zero());
1860 Value *Shl = Builder.CreateShl(A, ShiftAmtC);
1861 return BinaryOperator::CreateSub(B, Shl);
1862 }
1863
1864 // Canonicalize signum variant that ends in add:
1865 // (A s>> (BW - 1)) + (zext (A s> 0)) --> (A s>> (BW - 1)) | (zext (A != 0))
1866 uint64_t BitWidth = Ty->getScalarSizeInBits();
1870 Value *NotZero = Builder.CreateIsNotNull(A, "isnotnull");
1871 Value *Zext = Builder.CreateZExt(NotZero, Ty, "isnotnull.zext");
1872 return BinaryOperator::CreateOr(LHS, Zext);
1873 }
1874
1875 {
1876 Value *Cond, *Ext;
1877 Constant *C;
1878 // (add X, (sext/zext (icmp eq X, C)))
1879 // -> (select (icmp eq X, C), (add C, (sext/zext 1)), X)
1880 auto CondMatcher =
1882 m_ImmConstant(C)));
1883
1884 if (match(&I,
1885 m_c_Add(m_Value(A), m_Value(Ext, m_ZExtOrSExt(CondMatcher)))) &&
1886 Ext->hasOneUse()) {
1889 return replaceInstUsesWith(I, Builder.CreateSelect(Cond, Add, A));
1890 }
1891 }
1892
1893 // (add (add A, 1), (sext (icmp ne A, 0))) => call umax(A, 1)
1894 if (match(LHS, m_Add(m_Value(A), m_One())) &&
1897 Value *OneConst = ConstantInt::get(A->getType(), 1);
1898 Value *UMax = Builder.CreateBinaryIntrinsic(Intrinsic::umax, A, OneConst);
1899 return replaceInstUsesWith(I, UMax);
1900 }
1901
1902 if (Instruction *Ashr = foldAddToAshr(I))
1903 return Ashr;
1904
1905 // Ceiling division by power-of-2:
1906 // (X >> log2(N)) + zext(X & (N-1) != 0) --> (X + (N-1)) >> log2(N)
1907 // This is valid when adding (N-1) to X doesn't overflow.
1908 {
1909 Value *X;
1910 const APInt *ShiftAmt, *Mask;
1911 CmpPredicate Pred;
1912
1913 // Match: (X >> C) + zext((X & Mask) != 0)
1914 // or: zext((X & Mask) != 0) + (X >> C)
1915 if (match(&I,
1918 m_And(m_Value(X), m_LowBitMask(Mask)), m_ZeroInt())),
1920 m_LShr(m_Deferred(X), m_APInt(ShiftAmt))))))) &&
1921 Mask->popcount() == *ShiftAmt) {
1922
1923 // Check if X + Mask doesn't overflow
1924 unsigned Xbits = X->getType()->getScalarSizeInBits();
1925 unsigned Ibits = Ty->getScalarSizeInBits();
1926 bool NeedZext = Ibits > Xbits;
1927 Constant *MaskC = ConstantInt::get(Ty, Mask->zext(Ibits));
1928 if (NeedZext || willNotOverflowUnsignedAdd(X, MaskC, I)) {
1929 if (NeedZext)
1930 X = Builder.CreateZExt(X, Ty);
1931 // (X + Mask) >> ShiftAmt
1932 Value *Add = Builder.CreateNUWAdd(X, MaskC);
1933 return BinaryOperator::CreateLShr(
1934 Add, ConstantInt::get(Ty, ShiftAmt->zext(Ibits)));
1935 }
1936 }
1937 }
1938
1939 // (~X) + (~Y) --> -2 - (X + Y)
1940 {
1941 // To ensure we can save instructions we need to ensure that we consume both
1942 // LHS/RHS (i.e they have a `not`).
1943 bool ConsumesLHS, ConsumesRHS;
1944 if (isFreeToInvert(LHS, LHS->hasOneUse(), ConsumesLHS) && ConsumesLHS &&
1945 isFreeToInvert(RHS, RHS->hasOneUse(), ConsumesRHS) && ConsumesRHS) {
1946 Value *NotLHS = getFreelyInverted(LHS, LHS->hasOneUse(), &Builder);
1947 Value *NotRHS = getFreelyInverted(RHS, RHS->hasOneUse(), &Builder);
1948 assert(NotLHS != nullptr && NotRHS != nullptr &&
1949 "isFreeToInvert desynced with getFreelyInverted");
1950 Value *LHSPlusRHS = Builder.CreateAdd(NotLHS, NotRHS);
1951 return BinaryOperator::CreateSub(
1952 ConstantInt::getSigned(RHS->getType(), -2), LHSPlusRHS);
1953 }
1954 }
1955
1957 return R;
1958
1959 // TODO(jingyue): Consider willNotOverflowSignedAdd and
1960 // willNotOverflowUnsignedAdd to reduce the number of invocations of
1961 // computeKnownBits.
1962 bool Changed = false;
1963 if (!I.hasNoSignedWrap() && willNotOverflowSignedAdd(LHSCache, RHSCache, I)) {
1964 Changed = true;
1965 I.setHasNoSignedWrap(true);
1966 }
1967 if (!I.hasNoUnsignedWrap() &&
1968 willNotOverflowUnsignedAdd(LHSCache, RHSCache, I)) {
1969 Changed = true;
1970 I.setHasNoUnsignedWrap(true);
1971 }
1972
1974 return V;
1975
1976 if (Instruction *V =
1978 return V;
1979
1981 return SatAdd;
1982
1983 // usub.sat(A, B) + B => umax(A, B)
1984 if (match(&I, m_c_BinOp(
1986 m_Deferred(B)))) {
1987 return replaceInstUsesWith(I,
1988 Builder.CreateIntrinsic(Intrinsic::umax, {I.getType()}, {A, B}));
1989 }
1990
1991 // ctpop(A) + ctpop(B) => ctpop(A | B) if A and B have no bits set in common.
1992 if (match(LHS, m_OneUse(m_Ctpop(m_Value(A)))) &&
1993 match(RHS, m_OneUse(m_Ctpop(m_Value(B)))) &&
1994 haveNoCommonBitsSet(A, B, SQ.getWithInstruction(&I)))
1995 return replaceInstUsesWith(
1996 I, Builder.CreateIntrinsic(Intrinsic::ctpop, {I.getType()},
1997 {Builder.CreateDisjointOr(A, B)}));
1998
1999 // Fold the log2_ceil idiom:
2000 // zext(ctpop(A) >u/!= 1) + (ctlz(A, true) ^ (BW - 1))
2001 // -->
2002 // BW - ctlz(A - 1, false)
2003 const APInt *XorC;
2004 CmpPredicate Pred;
2005 if (match(&I, m_c_Add(m_ZExt(m_ICmp(Pred, m_Ctpop(m_Value(A)), m_One())),
2008 m_Ctlz(m_Deferred(A), m_One())))),
2009 m_APInt(XorC))))))) &&
2010 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_NE) &&
2011 *XorC == A->getType()->getScalarSizeInBits() - 1 &&
2012 isPowerOf2_32(A->getType()->getScalarSizeInBits())) {
2013 Value *Sub = Builder.CreateAdd(A, Constant::getAllOnesValue(A->getType()));
2014 Value *Ctlz = Builder.CreateIntrinsic(Intrinsic::ctlz, {A->getType()},
2015 {Sub, Builder.getFalse()});
2016 Value *Ret = Builder.CreateSub(
2017 ConstantInt::get(A->getType(), A->getType()->getScalarSizeInBits()),
2018 Ctlz, "", /*HasNUW=*/true, /*HasNSW=*/true);
2019 return replaceInstUsesWith(I, Builder.CreateZExtOrTrunc(Ret, I.getType()));
2020 }
2021
2022 if (Instruction *Res = foldSquareSumInt(I))
2023 return Res;
2024
2025 if (Instruction *Res = foldBinOpOfDisplacedShifts(I))
2026 return Res;
2027
2029 return Res;
2030
2031 if (Instruction *Res = foldDivCeil(I))
2032 return Res;
2033
2034 // (A | -2) + A -> (A - 1) & -2
2035 APInt NegTwo(Ty->getScalarSizeInBits(), -2, /*isSigned=*/true);
2036 if (match(&I, m_c_BinOp(m_OneUse(m_Or(m_Value(A), m_SpecificInt(NegTwo))),
2037 m_Deferred(A)))) {
2038 Value *Ret = Builder.CreateAdd(
2039 A, ConstantInt::get(
2040 Ty, APInt(Ty->getScalarSizeInBits(), -1, /*isSigned=*/true)));
2041 return BinaryOperator::CreateAnd(Ret, ConstantInt::get(Ty, NegTwo));
2042 }
2043
2044 // Re-enqueue users of the induction variable of add recurrence if we infer
2045 // new nuw/nsw flags.
2046 if (Changed) {
2047 PHINode *PHI;
2048 Value *Start, *Step;
2049 if (matchSimpleRecurrence(&I, PHI, Start, Step))
2050 Worklist.pushUsersToWorkList(*PHI);
2051 }
2052
2053 return Changed ? &I : nullptr;
2054}
2055
2056/// Eliminate an op from a linear interpolation (lerp) pattern.
2058 InstCombiner::BuilderTy &Builder) {
2059 Value *X, *Y, *Z;
2062 m_Value(Z))))),
2064 return nullptr;
2065
2066 // (Y * (1.0 - Z)) + (X * Z) --> Y + Z * (X - Y) [8 commuted variants]
2067 Value *XY = Builder.CreateFSubFMF(X, Y, &I);
2068 Value *MulZ = Builder.CreateFMulFMF(Z, XY, &I);
2069 return BinaryOperator::CreateFAddFMF(Y, MulZ, &I);
2070}
2071
2072/// Factor a common operand out of fadd/fsub of fmul/fdiv.
2074 InstCombiner::BuilderTy &Builder) {
2075 assert((I.getOpcode() == Instruction::FAdd ||
2076 I.getOpcode() == Instruction::FSub) && "Expecting fadd/fsub");
2077 assert(I.hasAllowReassoc() && I.hasNoSignedZeros() &&
2078 "FP factorization requires FMF");
2079
2080 if (Instruction *Lerp = factorizeLerp(I, Builder))
2081 return Lerp;
2082
2083 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2084 if (!Op0->hasOneUse() || !Op1->hasOneUse())
2085 return nullptr;
2086
2087 Value *X, *Y, *Z;
2088 bool IsFMul;
2089 if ((match(Op0, m_FMul(m_Value(X), m_Value(Z))) &&
2090 match(Op1, m_c_FMul(m_Value(Y), m_Specific(Z)))) ||
2091 (match(Op0, m_FMul(m_Value(Z), m_Value(X))) &&
2092 match(Op1, m_c_FMul(m_Value(Y), m_Specific(Z)))))
2093 IsFMul = true;
2094 else if (match(Op0, m_FDiv(m_Value(X), m_Value(Z))) &&
2095 match(Op1, m_FDiv(m_Value(Y), m_Specific(Z))))
2096 IsFMul = false;
2097 else
2098 return nullptr;
2099
2100 // (X * Z) + (Y * Z) --> (X + Y) * Z
2101 // (X * Z) - (Y * Z) --> (X - Y) * Z
2102 // (X / Z) + (Y / Z) --> (X + Y) / Z
2103 // (X / Z) - (Y / Z) --> (X - Y) / Z
2104 bool IsFAdd = I.getOpcode() == Instruction::FAdd;
2105 Value *XY = IsFAdd ? Builder.CreateFAddFMF(X, Y, &I)
2106 : Builder.CreateFSubFMF(X, Y, &I);
2107
2108 // Bail out if we just created a denormal constant.
2109 // TODO: This is copied from a previous implementation. Is it necessary?
2110 const APFloat *C;
2111 if (match(XY, m_APFloat(C)) && !C->isNormal())
2112 return nullptr;
2113
2114 return IsFMul ? BinaryOperator::CreateFMulFMF(XY, Z, &I)
2116}
2117
2119 if (Value *V = simplifyFAddInst(I.getOperand(0), I.getOperand(1),
2120 I.getFastMathFlags(),
2121 SQ.getWithInstruction(&I)))
2122 return replaceInstUsesWith(I, V);
2123
2125 return &I;
2126
2128 return X;
2129
2131 return Phi;
2132
2133 if (Instruction *FoldedFAdd = foldBinOpIntoSelectOrPhi(I))
2134 return FoldedFAdd;
2135
2136 // B = fadd A, 0.0
2137 // Z = Op B
2138 // can be transformed into
2139 // Z = Op A
2140 // Where Op is such that we can ignore sign of 0 in fadd
2141 Value *A;
2142 if (match(&I, m_OneUse(m_FAdd(m_Value(A), m_AnyZeroFP()))) &&
2143 canIgnoreSignBitOfZero(*I.use_begin()))
2144 return replaceInstUsesWith(I, A);
2145
2146 // (-X) + Y --> Y - X
2147 Value *X, *Y;
2148 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
2151
2152 // Similar to above, but look through fmul/fdiv for the negated term.
2153 // (-X * Y) + Z --> Z - (X * Y) [4 commuted variants]
2154 Value *Z;
2155 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
2157 m_Value(Y))),
2158 m_Value(Z)))) {
2159 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
2160 return BinaryOperator::CreateFSubFMF(Z, XY, &I);
2161 }
2162 // (-X / Y) + Z --> Z - (X / Y) [2 commuted variants]
2163 // (X / -Y) + Z --> Z - (X / Y) [2 commuted variants]
2164 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
2166 m_Value(Y))),
2167 m_Value(Z))) ||
2170 m_Value(Z)))) {
2171 Value *XY = Builder.CreateFDivFMF(X, Y, &I);
2172 return BinaryOperator::CreateFSubFMF(Z, XY, &I);
2173 }
2174
2175 // Check for (fadd double (sitofp x), y), see if we can merge this into an
2176 // integer add followed by a promotion.
2177 if (Instruction *R = foldFBinOpOfIntCasts(I))
2178 return R;
2179
2180 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2181 // Handle specials cases for FAdd with selects feeding the operation
2182 if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS, RHS))
2183 return replaceInstUsesWith(I, V);
2184
2185 if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
2187 return F;
2188
2190 return F;
2191
2192 // Try to fold fadd into start value of reduction intrinsic.
2194 m_AnyZeroFP(), m_Value(X))),
2195 m_Value(Y)))) {
2196 // fadd (rdx 0.0, X), Y --> rdx Y, X
2197 return replaceInstUsesWith(
2198 I, Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
2199 {X->getType()}, {Y, X}, &I));
2200 }
2201 const APFloat *StartC, *C;
2203 m_APFloat(StartC), m_Value(X)))) &&
2204 match(RHS, m_APFloat(C))) {
2205 // fadd (rdx StartC, X), C --> rdx (C + StartC), X
2206 Constant *NewStartC = ConstantFP::get(I.getType(), *C + *StartC);
2207 return replaceInstUsesWith(
2208 I, Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
2209 {X->getType()}, {NewStartC, X}, &I));
2210 }
2211
2212 // (X * MulC) + X --> X * (MulC + 1.0)
2213 Constant *MulC;
2214 if (match(&I, m_c_FAdd(m_FMul(m_Value(X), m_ImmConstant(MulC)),
2215 m_Deferred(X)))) {
2217 Instruction::FAdd, MulC, ConstantFP::get(I.getType(), 1.0), DL))
2218 return BinaryOperator::CreateFMulFMF(X, NewMulC, &I);
2219 }
2220
2221 // (-X - Y) + (X + Z) --> Z - Y
2222 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
2224 m_c_FAdd(m_Deferred(X), m_Value(Z)))))
2225 return BinaryOperator::CreateFSubFMF(Z, Y, &I);
2226
2227 if (Value *V = FAddCombine(Builder).simplify(&I))
2228 return replaceInstUsesWith(I, V);
2229 }
2230
2231 // minumum(X, Y) + maximum(X, Y) => X + Y.
2232 if (match(&I,
2235 m_Deferred(Y))))) {
2237 // We cannot preserve ninf if nnan flag is not set.
2238 // If X is NaN and Y is Inf then in original program we had NaN + NaN,
2239 // while in optimized version NaN + Inf and this is a poison with ninf flag.
2240 if (!Result->hasNoNaNs())
2241 Result->setHasNoInfs(false);
2242 return Result;
2243 }
2244
2245 return nullptr;
2246}
2247
2250
2251 if (LHS->getType() != RHS->getType())
2252 return Base;
2253
2254 // Collect all base pointers of LHS.
2256 Value *Ptr = LHS;
2257 while (true) {
2258 Ptrs.insert(Ptr);
2259 if (auto *GEP = dyn_cast<GEPOperator>(Ptr))
2260 Ptr = GEP->getPointerOperand();
2261 else
2262 break;
2263 }
2264
2265 // Find common base and collect RHS GEPs.
2266 bool First = true;
2267 while (true) {
2268 if (Ptrs.contains(RHS)) {
2269 Base.Ptr = RHS;
2270 break;
2271 }
2272
2273 if (auto *GEP = dyn_cast<GEPOperator>(RHS)) {
2274 Base.RHSGEPs.push_back(GEP);
2275 if (First) {
2276 First = false;
2277 Base.RHSNW = GEP->getNoWrapFlags();
2278 } else {
2279 Base.RHSNW = Base.RHSNW.intersectForOffsetAdd(GEP->getNoWrapFlags());
2280 }
2281 RHS = GEP->getPointerOperand();
2282 } else {
2283 // No common base.
2284 return Base;
2285 }
2286 }
2287
2288 // Collect LHS GEPs.
2289 First = true;
2290 while (true) {
2291 if (LHS == Base.Ptr)
2292 break;
2293
2294 auto *GEP = cast<GEPOperator>(LHS);
2295 Base.LHSGEPs.push_back(GEP);
2296 if (First) {
2297 First = false;
2298 Base.LHSNW = GEP->getNoWrapFlags();
2299 } else {
2300 Base.LHSNW = Base.LHSNW.intersectForOffsetAdd(GEP->getNoWrapFlags());
2301 }
2302 LHS = GEP->getPointerOperand();
2303 }
2304
2305 return Base;
2306}
2307
2309 unsigned NumGEPs = 0;
2310 auto ProcessGEPs = [&NumGEPs](ArrayRef<GEPOperator *> GEPs) {
2311 bool SeenMultiUse = false;
2312 for (GEPOperator *GEP : GEPs) {
2313 // Only count multi-use GEPs, excluding the first one. For the first one,
2314 // we will directly reuse the offset. For one-use GEPs, their offset will
2315 // be folded into a multi-use GEP.
2316 if (!GEP->hasOneUse()) {
2317 if (SeenMultiUse)
2318 ++NumGEPs;
2319 SeenMultiUse = true;
2320 }
2321 }
2322 };
2323 ProcessGEPs(LHSGEPs);
2324 ProcessGEPs(RHSGEPs);
2325 return NumGEPs > 2;
2326}
2327
2328/// Optimize pointer differences into the same array into a size. Consider:
2329/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2330/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2332 Type *Ty, bool IsNUW) {
2334 if (!Base.Ptr || Base.isExpensive())
2335 return nullptr;
2336
2337 // To avoid duplicating the offset arithmetic, rewrite the GEP to use the
2338 // computed offset.
2339 // TODO: We should probably do this even if there is only one GEP.
2340 bool RewriteGEPs = !Base.LHSGEPs.empty() && !Base.RHSGEPs.empty();
2341
2342 Type *IdxTy = DL.getIndexType(LHS->getType());
2343 Value *Result = EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy, RewriteGEPs);
2344 Value *Offset2 = EmitGEPOffsets(Base.RHSGEPs, Base.RHSNW, IdxTy, RewriteGEPs);
2345
2346 // If this is a single inbounds GEP and the original sub was nuw,
2347 // then the final multiplication is also nuw.
2348 if (auto *I = dyn_cast<OverflowingBinaryOperator>(Result))
2349 if (IsNUW && match(Offset2, m_Zero()) && Base.LHSNW.isInBounds() &&
2350 (I->use_empty() || I->hasOneUse()) && I->hasNoSignedWrap() &&
2351 !I->hasNoUnsignedWrap() &&
2352 ((I->getOpcode() == Instruction::Mul &&
2353 match(I->getOperand(1), m_NonNegative())) ||
2354 I->getOpcode() == Instruction::Shl))
2355 cast<Instruction>(I)->setHasNoUnsignedWrap();
2356
2357 // If we have a 2nd GEP of the same base pointer, subtract the offsets.
2358 // If both GEPs are inbounds, then the subtract does not have signed overflow.
2359 // If both GEPs are nuw and the original sub is nuw, the new sub is also nuw.
2360 if (!match(Offset2, m_Zero())) {
2361 Result =
2362 Builder.CreateSub(Result, Offset2, "gepdiff",
2363 IsNUW && Base.LHSNW.hasNoUnsignedWrap() &&
2364 Base.RHSNW.hasNoUnsignedWrap(),
2365 Base.LHSNW.isInBounds() && Base.RHSNW.isInBounds());
2366 }
2367
2368 return Builder.CreateIntCast(Result, Ty, true);
2369}
2370
2372 InstCombiner::BuilderTy &Builder) {
2373 Value *Op0 = I.getOperand(0);
2374 Value *Op1 = I.getOperand(1);
2375 Type *Ty = I.getType();
2376 auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op1);
2377 if (!MinMax)
2378 return nullptr;
2379
2380 // sub(add(X,Y), s/umin(X,Y)) --> s/umax(X,Y)
2381 // sub(add(X,Y), s/umax(X,Y)) --> s/umin(X,Y)
2382 Value *X = MinMax->getLHS();
2383 Value *Y = MinMax->getRHS();
2384 if (match(Op0, m_c_Add(m_Specific(X), m_Specific(Y))) &&
2385 (Op0->hasOneUse() || Op1->hasOneUse())) {
2386 Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMax->getIntrinsicID());
2387 Function *F = Intrinsic::getOrInsertDeclaration(I.getModule(), InvID, Ty);
2388 return CallInst::Create(F, {X, Y});
2389 }
2390
2391 // sub(add(X,Y),umin(Y,Z)) --> add(X,usub.sat(Y,Z))
2392 // sub(add(X,Z),umin(Y,Z)) --> add(X,usub.sat(Z,Y))
2393 Value *Z;
2394 if (match(Op1, m_OneUse(m_UMin(m_Value(Y), m_Value(Z))))) {
2395 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Y), m_Value(X))))) {
2396 Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, Ty, {Y, Z});
2397 return BinaryOperator::CreateAdd(X, USub);
2398 }
2399 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Z), m_Value(X))))) {
2400 Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, Ty, {Z, Y});
2401 return BinaryOperator::CreateAdd(X, USub);
2402 }
2403 }
2404
2405 // sub Op0, smin((sub nsw Op0, Z), 0) --> smax Op0, Z
2406 // sub Op0, smax((sub nsw Op0, Z), 0) --> smin Op0, Z
2407 if (MinMax->isSigned() && match(Y, m_ZeroInt()) &&
2408 match(X, m_NSWSub(m_Specific(Op0), m_Value(Z)))) {
2409 Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMax->getIntrinsicID());
2410 Function *F = Intrinsic::getOrInsertDeclaration(I.getModule(), InvID, Ty);
2411 return CallInst::Create(F, {Op0, Z});
2412 }
2413
2414 return nullptr;
2415}
2416
2417/// sub nuw (and X, LowMask), (zext Y) --> zext (sub nuw (trunc X), Y)
2418/// sub nuw (zext Y), (and X, LowMask) --> zext (sub nuw Y, (trunc X))
2419/// where LowMask has exactly as many low bits set as Y's width, so the 'and'
2420/// is zext(trunc X) and the wide nuw implies the narrow sub does not wrap.
2422 InstCombiner::BuilderTy &Builder) {
2423 if (!I.hasNoUnsignedWrap())
2424 return nullptr;
2425
2426 Value *X, *Y;
2427 const APInt *Mask;
2428 auto MaskPat = m_OneUse(m_And(m_Value(X), m_LowBitMask(Mask)));
2429 auto ZExtPat = m_OneUse(m_ZExt(m_Value(Y)));
2430 bool MaskIsLHS = match(&I, m_Sub(MaskPat, ZExtPat));
2431 if ((!MaskIsLHS && !match(&I, m_Sub(ZExtPat, MaskPat))) ||
2432 Mask->countr_one() != Y->getType()->getScalarSizeInBits())
2433 return nullptr;
2434
2435 Value *TruncX = Builder.CreateTrunc(X, Y->getType());
2436 Value *NarrowSub = MaskIsLHS ? Builder.CreateNUWSub(TruncX, Y)
2437 : Builder.CreateNUWSub(Y, TruncX);
2438 return new ZExtInst(NarrowSub, I.getType());
2439}
2440
2442 if (Value *V = simplifySubInst(I.getOperand(0), I.getOperand(1),
2443 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
2444 SQ.getWithInstruction(&I)))
2445 return replaceInstUsesWith(I, V);
2446
2448 return X;
2449
2451 return Phi;
2452
2453 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2454
2455 // If this is a 'B = x-(-A)', change to B = x+A.
2456 // We deal with this without involving Negator to preserve NSW flag.
2457 if (Value *V = dyn_castNegVal(Op1)) {
2458 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
2459
2460 if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
2461 assert(BO->getOpcode() == Instruction::Sub &&
2462 "Expected a subtraction operator!");
2463 if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
2464 Res->setHasNoSignedWrap(true);
2465 } else {
2466 if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
2467 Res->setHasNoSignedWrap(true);
2468 }
2469
2470 return Res;
2471 }
2472
2473 // Try this before Negator to preserve NSW flag.
2475 return R;
2476
2477 Constant *C;
2478 if (match(Op0, m_ImmConstant(C))) {
2479 Value *X;
2480 Constant *C2;
2481
2482 // C-(X+C2) --> (C-C2)-X
2483 if (match(Op1, m_AddLike(m_Value(X), m_ImmConstant(C2)))) {
2484 // C-C2 never overflow, and C-(X+C2), (X+C2) has NSW/NUW
2485 // => (C-C2)-X can have NSW/NUW
2486 bool WillNotSOV = willNotOverflowSignedSub(C, C2, I);
2487 BinaryOperator *Res =
2488 BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
2489
2490 // or disjoint is equivalent to add nuw nsw.
2491 bool Op1NSW = true;
2492 bool Op1NUW = true;
2493
2494 if (auto *OBO1 = dyn_cast<OverflowingBinaryOperator>(Op1)) {
2495 Op1NSW = OBO1->hasNoSignedWrap();
2496 Op1NUW = OBO1->hasNoUnsignedWrap();
2497 }
2498
2499 Res->setHasNoSignedWrap(I.hasNoSignedWrap() && Op1NSW && WillNotSOV);
2500 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap() && Op1NUW);
2501 return Res;
2502 }
2503 }
2504
2505 auto TryToNarrowDeduceFlags = [this, &I, &Op0, &Op1]() -> Instruction * {
2506 if (Instruction *Ext = narrowMathIfNoOverflow(I))
2507 return Ext;
2508
2509 bool Changed = false;
2510 if (!I.hasNoSignedWrap() && willNotOverflowSignedSub(Op0, Op1, I)) {
2511 Changed = true;
2512 I.setHasNoSignedWrap(true);
2513 }
2514 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedSub(Op0, Op1, I)) {
2515 Changed = true;
2516 I.setHasNoUnsignedWrap(true);
2517 }
2518
2519 return Changed ? &I : nullptr;
2520 };
2521
2523 return R;
2524
2525 // First, let's try to interpret `sub a, b` as `add a, (sub 0, b)`,
2526 // and let's try to sink `(sub 0, b)` into `b` itself. But only if this isn't
2527 // a pure negation used by a select that looks like abs/nabs.
2528 bool IsNegation = match(Op0, m_ZeroInt());
2529 if (!IsNegation || none_of(I.users(), match_fn(m_c_Select(m_Specific(Op1),
2530 m_Specific(&I))))) {
2531 if (Value *NegOp1 = Negator::Negate(IsNegation, /* IsNSW */ IsNegation &&
2532 I.hasNoSignedWrap(),
2533 Op1, *this))
2534 return BinaryOperator::CreateAdd(NegOp1, Op0);
2535 }
2536 if (IsNegation)
2537 return TryToNarrowDeduceFlags(); // Should have been handled in Negator!
2538
2539 // (A*B)-(A*C) -> A*(B-C) etc
2541 return replaceInstUsesWith(I, V);
2542
2543 if (I.getType()->isIntOrIntVectorTy(1))
2544 return BinaryOperator::CreateXor(Op0, Op1);
2545
2546 // Replace (-1 - A) with (~A).
2547 if (match(Op0, m_AllOnes()))
2548 return BinaryOperator::CreateNot(Op1);
2549
2550 // (X + -1) - Y --> ~Y + X
2551 Value *X, *Y;
2552 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_AllOnes()))))
2553 return BinaryOperator::CreateAdd(Builder.CreateNot(Op1), X);
2554
2555 // if (C1 & C2) == C2 then (X & C1) - (X & C2) -> X & (C1 ^ C2)
2556 Constant *C1, *C2;
2557 if (match(Op0, m_And(m_Value(X), m_ImmConstant(C1))) &&
2558 match(Op1, m_And(m_Specific(X), m_ImmConstant(C2)))) {
2559 Value *AndC = ConstantFoldBinaryInstruction(Instruction::And, C1, C2);
2560 if (C2->isElementWiseEqual(AndC))
2561 return BinaryOperator::CreateAnd(
2562 X, ConstantFoldBinaryInstruction(Instruction::Xor, C1, C2));
2563 }
2564
2565 // Reassociate sub/add sequences to create more add instructions and
2566 // reduce dependency chains:
2567 // ((X - Y) + Z) - Op1 --> (X + Z) - (Y + Op1)
2568 Value *Z;
2570 m_Value(Z))))) {
2571 Value *XZ = Builder.CreateAdd(X, Z);
2572 Value *YW = Builder.CreateAdd(Y, Op1);
2573 return BinaryOperator::CreateSub(XZ, YW);
2574 }
2575
2576 // ((X - Y) - Op1) --> X - (Y + Op1)
2577 if (match(Op0, m_OneUse(m_Sub(m_Value(X), m_Value(Y))))) {
2579 bool HasNUW = I.hasNoUnsignedWrap() && LHSSub->hasNoUnsignedWrap();
2580 bool HasNSW = HasNUW && I.hasNoSignedWrap() && LHSSub->hasNoSignedWrap();
2581 Value *Add = Builder.CreateAdd(Y, Op1, "", /*HasNUW=*/HasNUW,
2582 /*HasNSW=*/HasNSW);
2583 BinaryOperator *Sub = BinaryOperator::CreateSub(X, Add);
2584 Sub->setHasNoUnsignedWrap(HasNUW);
2585 Sub->setHasNoSignedWrap(HasNSW);
2586 return Sub;
2587 }
2588
2589 // (X + C0) - (Y + C1) --> (X - Y) + (C0 - C1)
2590 {
2591 Constant *CX, *CY;
2592 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_ImmConstant(CX)))) &&
2593 match(Op1, m_OneUse(m_Add(m_Value(Y), m_ImmConstant(CY))))) {
2594 Value *OpsSub = Builder.CreateSub(X, Y);
2595 Constant *ConstsSub = ConstantExpr::getSub(CX, CY);
2596 return BinaryOperator::CreateAdd(OpsSub, ConstsSub);
2597 }
2598 }
2599
2600 // (X + Z) - (Y + Z) --> (X - Y)
2601 {
2602 Value *W, *Z;
2603 if (match(Op0, m_AddLike(m_Value(W), m_Value(X))) &&
2604 match(Op1, m_AddLike(m_Value(Y), m_Value(Z)))) {
2605 Instruction *R = nullptr;
2606 if (W == Y)
2607 R = BinaryOperator::CreateSub(X, Z);
2608 else if (W == Z)
2609 R = BinaryOperator::CreateSub(X, Y);
2610 else if (X == Y)
2611 R = BinaryOperator::CreateSub(W, Z);
2612 else if (X == Z)
2613 R = BinaryOperator::CreateSub(W, Y);
2614 if (R) {
2615 bool NSW = I.hasNoSignedWrap() &&
2616 match(Op0, m_NSWAddLike(m_Value(), m_Value())) &&
2617 match(Op1, m_NSWAddLike(m_Value(), m_Value()));
2618
2619 bool NUW = I.hasNoUnsignedWrap() &&
2620 match(Op1, m_NUWAddLike(m_Value(), m_Value()));
2621 R->setHasNoSignedWrap(NSW);
2622 R->setHasNoUnsignedWrap(NUW);
2623 return R;
2624 }
2625 }
2626 }
2627
2628 // (~X) - (~Y) --> Y - X
2629 {
2630 // Need to ensure we can consume at least one of the `not` instructions,
2631 // otherwise this can inf loop.
2632 bool ConsumesOp0, ConsumesOp1;
2633 if (isFreeToInvert(Op0, Op0->hasOneUse(), ConsumesOp0) &&
2634 isFreeToInvert(Op1, Op1->hasOneUse(), ConsumesOp1) &&
2635 (ConsumesOp0 || ConsumesOp1)) {
2636 Value *NotOp0 = getFreelyInverted(Op0, Op0->hasOneUse(), &Builder);
2637 Value *NotOp1 = getFreelyInverted(Op1, Op1->hasOneUse(), &Builder);
2638 assert(NotOp0 != nullptr && NotOp1 != nullptr &&
2639 "isFreeToInvert desynced with getFreelyInverted");
2640 return BinaryOperator::CreateSub(NotOp1, NotOp0);
2641 }
2642 }
2643
2644 auto m_AddRdx = [](Value *&Vec) {
2646 };
2647 Value *V0, *V1;
2648 if (match(Op0, m_AddRdx(V0)) && match(Op1, m_AddRdx(V1)) &&
2649 V0->getType() == V1->getType()) {
2650 // Difference of sums is sum of differences:
2651 // add_rdx(V0) - add_rdx(V1) --> add_rdx(V0 - V1)
2652 Value *Sub = Builder.CreateSub(V0, V1);
2653 Value *Rdx = Builder.CreateIntrinsic(Intrinsic::vector_reduce_add,
2654 {Sub->getType()}, {Sub});
2655 return replaceInstUsesWith(I, Rdx);
2656 }
2657
2658 if (Constant *C = dyn_cast<Constant>(Op0)) {
2659 Value *X;
2660 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
2661 // C - (zext bool) --> bool ? C - 1 : C
2663 // We know nothing about the distribution of the condition, so mark the
2664 // branch weights as unknown.
2666 return SI;
2667 }
2668 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
2669 // C - (sext bool) --> bool ? C + 1 : C
2671 // We know nothing about the distribution of the condition, so mark the
2672 // branch weights as unknown.
2674 return SI;
2675 }
2676
2677 // C - ~X == X + (1+C)
2678 if (match(Op1, m_Not(m_Value(X))))
2679 return BinaryOperator::CreateAdd(X, InstCombiner::AddOne(C));
2680
2681 // Try to fold constant sub into select arguments.
2683 if (Instruction *R = FoldOpIntoSelect(I, SI))
2684 return R;
2685
2686 // Try to fold constant sub into PHI values.
2687 if (PHINode *PN = dyn_cast<PHINode>(Op1))
2688 if (Instruction *R = foldOpIntoPhi(I, PN))
2689 return R;
2690
2691 Constant *C2;
2692
2693 // C-(C2-X) --> X+(C-C2)
2694 if (match(Op1, m_Sub(m_ImmConstant(C2), m_Value(X))))
2695 return BinaryOperator::CreateAdd(X, ConstantExpr::getSub(C, C2));
2696 }
2697
2698 const APInt *Op0C;
2699 if (match(Op0, m_APInt(Op0C))) {
2700 if (Op0C->isMask()) {
2701 // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
2702 // zero. We don't use information from dominating conditions so this
2703 // transform is easier to reverse if necessary.
2705 Op1, SQ.getWithInstruction(&I).getWithoutDomCondCache());
2706 if ((*Op0C | RHSKnown.Zero).isAllOnes())
2707 return BinaryOperator::CreateXor(Op1, Op0);
2708 }
2709
2710 // C - ((C3 -nuw X) & C2) --> (C - (C2 & C3)) + (X & C2) when:
2711 // (C3 - ((C2 & C3) - 1)) is pow2
2712 // ((C2 + C3) & ((C2 & C3) - 1)) == ((C2 & C3) - 1)
2713 // C2 is negative pow2 || sub nuw
2714 const APInt *C2, *C3;
2715 BinaryOperator *InnerSub;
2716 if (match(Op1, m_OneUse(m_And(m_BinOp(InnerSub), m_APInt(C2)))) &&
2717 match(InnerSub, m_Sub(m_APInt(C3), m_Value(X))) &&
2718 (InnerSub->hasNoUnsignedWrap() || C2->isNegatedPowerOf2())) {
2719 APInt C2AndC3 = *C2 & *C3;
2720 APInt C2AndC3Minus1 = C2AndC3 - 1;
2721 APInt C2AddC3 = *C2 + *C3;
2722 if ((*C3 - C2AndC3Minus1).isPowerOf2() &&
2723 C2AndC3Minus1.isSubsetOf(C2AddC3)) {
2724 Value *And = Builder.CreateAnd(X, ConstantInt::get(I.getType(), *C2));
2725 return BinaryOperator::CreateAdd(
2726 And, ConstantInt::get(I.getType(), *Op0C - C2AndC3));
2727 }
2728 }
2729 }
2730
2731 {
2732 Value *Y;
2733 // X-(X+Y) == -Y X-(Y+X) == -Y
2734 if (match(Op1, m_c_Add(m_Specific(Op0), m_Value(Y))))
2736
2737 // (X-Y)-X == -Y
2738 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
2740 }
2741
2742 // (sub (or A, B) (and A, B)) --> (xor A, B)
2743 {
2744 Value *A, *B;
2745 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
2746 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
2747 return BinaryOperator::CreateXor(A, B);
2748 }
2749
2750 // (sub (add A, B) (or A, B)) --> (and A, B)
2751 {
2752 Value *A, *B;
2753 if (match(Op0, m_Add(m_Value(A), m_Value(B))) &&
2754 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
2755 return BinaryOperator::CreateAnd(A, B);
2756 }
2757
2758 // (sub (add A, B) (and A, B)) --> (or A, B)
2759 {
2760 Value *A, *B;
2761 if (match(Op0, m_Add(m_Value(A), m_Value(B))) &&
2763 return BinaryOperator::CreateOr(A, B);
2764 }
2765
2766 // (sub (and A, B) (or A, B)) --> neg (xor A, B)
2767 {
2768 Value *A, *B;
2769 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2770 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
2771 (Op0->hasOneUse() || Op1->hasOneUse()))
2772 return BinaryOperator::CreateNeg(Builder.CreateXor(A, B));
2773 }
2774
2775 // (sub (or A, B), (xor A, B)) --> (and A, B)
2776 {
2777 Value *A, *B;
2778 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2779 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
2780 return BinaryOperator::CreateAnd(A, B);
2781 }
2782
2783 // (sub (xor A, B) (or A, B)) --> neg (and A, B)
2784 {
2785 Value *A, *B;
2786 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2787 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
2788 (Op0->hasOneUse() || Op1->hasOneUse()))
2789 return BinaryOperator::CreateNeg(Builder.CreateAnd(A, B));
2790 }
2791
2792 {
2793 Value *Y;
2794 // ((X | Y) - X) --> (~X & Y)
2795 if (match(Op0, m_OneUse(m_c_Or(m_Value(Y), m_Specific(Op1)))))
2796 return BinaryOperator::CreateAnd(
2797 Y, Builder.CreateNot(Op1, Op1->getName() + ".not"));
2798 }
2799
2800 {
2801 // (sub (and Op1, (neg X)), Op1) --> neg (and Op1, (add X, -1))
2802 Value *X;
2803 if (match(Op0, m_OneUse(m_c_And(m_Specific(Op1),
2804 m_OneUse(m_Neg(m_Value(X))))))) {
2805 return BinaryOperator::CreateNeg(Builder.CreateAnd(
2806 Op1, Builder.CreateAdd(X, Constant::getAllOnesValue(I.getType()))));
2807 }
2808 }
2809
2810 {
2811 // (sub (and Op1, C), Op1) --> neg (and Op1, ~C)
2812 Constant *C;
2813 if (match(Op0, m_OneUse(m_And(m_Specific(Op1), m_Constant(C))))) {
2815 Builder.CreateAnd(Op1, Builder.CreateNot(C)));
2816 }
2817 }
2818
2819 {
2820 // (sub (xor X, (sext C)), (sext C)) => (select C, (neg X), X)
2821 // (sub (sext C), (xor X, (sext C))) => (select C, X, (neg X))
2822 Value *C, *X;
2823 auto m_SubXorCmp = [&C, &X](Value *LHS, Value *RHS) {
2824 return match(LHS, m_OneUse(m_c_Xor(m_Value(X), m_Specific(RHS)))) &&
2825 match(RHS, m_SExt(m_Value(C))) &&
2826 (C->getType()->getScalarSizeInBits() == 1);
2827 };
2828 if (m_SubXorCmp(Op0, Op1))
2829 return createSelectInstWithUnknownProfile(C, Builder.CreateNeg(X), X);
2830 if (m_SubXorCmp(Op1, Op0))
2831 return createSelectInstWithUnknownProfile(C, X, Builder.CreateNeg(X));
2832 }
2833
2835 return R;
2836
2838 return R;
2839
2840 {
2841 // If we have a subtraction between some value and a select between
2842 // said value and something else, sink subtraction into select hands, i.e.:
2843 // sub (select %Cond, %TrueVal, %FalseVal), %Op1
2844 // ->
2845 // select %Cond, (sub %TrueVal, %Op1), (sub %FalseVal, %Op1)
2846 // or
2847 // sub %Op0, (select %Cond, %TrueVal, %FalseVal)
2848 // ->
2849 // select %Cond, (sub %Op0, %TrueVal), (sub %Op0, %FalseVal)
2850 // This will result in select between new subtraction and 0.
2851 auto SinkSubIntoSelect =
2852 [Ty = I.getType()](Value *Select, Value *OtherHandOfSub,
2853 auto SubBuilder) -> Instruction * {
2854 Value *Cond, *TrueVal, *FalseVal;
2855 if (!match(Select, m_OneUse(m_Select(m_Value(Cond), m_Value(TrueVal),
2856 m_Value(FalseVal)))))
2857 return nullptr;
2858 if (OtherHandOfSub != TrueVal && OtherHandOfSub != FalseVal)
2859 return nullptr;
2860 // While it is really tempting to just create two subtractions and let
2861 // InstCombine fold one of those to 0, it isn't possible to do so
2862 // because of worklist visitation order. So ugly it is.
2863 bool OtherHandOfSubIsTrueVal = OtherHandOfSub == TrueVal;
2864 Value *NewSub = SubBuilder(OtherHandOfSubIsTrueVal ? FalseVal : TrueVal);
2865 Constant *Zero = Constant::getNullValue(Ty);
2866 SelectInst *NewSel =
2867 SelectInst::Create(Cond, OtherHandOfSubIsTrueVal ? Zero : NewSub,
2868 OtherHandOfSubIsTrueVal ? NewSub : Zero);
2869 // Preserve prof metadata if any.
2871 return NewSel;
2872 };
2873 if (Instruction *NewSel = SinkSubIntoSelect(
2874 /*Select=*/Op0, /*OtherHandOfSub=*/Op1,
2875 [Builder = &Builder, Op1](Value *OtherHandOfSelect) {
2876 return Builder->CreateSub(OtherHandOfSelect,
2877 /*OtherHandOfSub=*/Op1);
2878 }))
2879 return NewSel;
2880 if (Instruction *NewSel = SinkSubIntoSelect(
2881 /*Select=*/Op1, /*OtherHandOfSub=*/Op0,
2882 [Builder = &Builder, Op0](Value *OtherHandOfSelect) {
2883 return Builder->CreateSub(/*OtherHandOfSub=*/Op0,
2884 OtherHandOfSelect);
2885 }))
2886 return NewSel;
2887 }
2888
2889 // (X - (X & Y)) --> (X & ~Y)
2890 if (match(Op1, m_c_And(m_Specific(Op0), m_Value(Y))) &&
2891 (Op1->hasOneUse() || isa<Constant>(Y)))
2892 return BinaryOperator::CreateAnd(
2893 Op0, Builder.CreateNot(Y, Y->getName() + ".not"));
2894
2895 // ~X - Min/Max(~X, Y) -> ~Min/Max(X, ~Y) - X
2896 // ~X - Min/Max(Y, ~X) -> ~Min/Max(X, ~Y) - X
2897 // Min/Max(~X, Y) - ~X -> X - ~Min/Max(X, ~Y)
2898 // Min/Max(Y, ~X) - ~X -> X - ~Min/Max(X, ~Y)
2899 // As long as Y is freely invertible, this will be neutral or a win.
2900 // Note: We don't generate the inverse max/min, just create the 'not' of
2901 // it and let other folds do the rest.
2902 if (match(Op0, m_Not(m_Value(X))) &&
2903 match(Op1, m_c_MaxOrMin(m_Specific(Op0), m_Value(Y))) &&
2904 !Op0->hasNUsesOrMore(3) && isFreeToInvert(Y, Y->hasOneUse())) {
2905 Value *Not = Builder.CreateNot(Op1);
2906 return BinaryOperator::CreateSub(Not, X);
2907 }
2908 if (match(Op1, m_Not(m_Value(X))) &&
2909 match(Op0, m_c_MaxOrMin(m_Specific(Op1), m_Value(Y))) &&
2910 !Op1->hasNUsesOrMore(3) && isFreeToInvert(Y, Y->hasOneUse())) {
2911 Value *Not = Builder.CreateNot(Op0);
2912 return BinaryOperator::CreateSub(X, Not);
2913 }
2914
2915 // min(X+1, Y) - min(X, Y) --> zext X < Y
2916 // Replacing a sub and at least one min with an icmp
2917 // and a zext is a potential improvement.
2918 if (match(Op0, m_c_SMin(m_NSWAddLike(m_Value(X), m_One()), m_Value(Y))) &&
2919 match(Op1, m_c_SMin(m_Specific(X), m_Specific(Y))) &&
2920 I.getType()->getScalarSizeInBits() != 1 &&
2921 (Op0->hasOneUse() || Op1->hasOneUse())) {
2922 Value *Cond = Builder.CreateICmpSLT(X, Y);
2923 return new ZExtInst(Cond, I.getType());
2924 }
2925 if (match(Op0, m_c_UMin(m_NUWAddLike(m_Value(X), m_One()), m_Value(Y))) &&
2926 match(Op1, m_c_UMin(m_Specific(X), m_Specific(Y))) &&
2927 I.getType()->getScalarSizeInBits() != 1 &&
2928 (Op0->hasOneUse() || Op1->hasOneUse())) {
2929 Value *Cond = Builder.CreateICmpULT(X, Y);
2930 return new ZExtInst(Cond, I.getType());
2931 }
2932
2933 // Optimize pointer differences into the same array into a size. Consider:
2934 // &A[10] - &A[0]: we should compile this to "10".
2935 Value *LHSOp, *RHSOp;
2936 if (match(Op0, m_PtrToIntOrAddr(m_Value(LHSOp))) &&
2937 match(Op1, m_PtrToIntOrAddr(m_Value(RHSOp))))
2938 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType(),
2939 I.hasNoUnsignedWrap()))
2940 return replaceInstUsesWith(I, Res);
2941
2942 // trunc(p)-trunc(q) -> trunc(p-q)
2943 if (match(Op0, m_Trunc(m_PtrToIntOrAddr(m_Value(LHSOp)))) &&
2944 match(Op1, m_Trunc(m_PtrToIntOrAddr(m_Value(RHSOp)))))
2945 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType(),
2946 /* IsNUW */ false))
2947 return replaceInstUsesWith(I, Res);
2948
2949 auto MatchSubOfZExtOfPtrToIntOrAddr = [&]() {
2950 if (match(Op0, m_ZExt(m_PtrToIntSameSize(DL, m_Value(LHSOp)))) &&
2951 match(Op1, m_ZExt(m_PtrToIntSameSize(DL, m_Value(RHSOp)))))
2952 return true;
2953 if (match(Op0, m_ZExt(m_PtrToAddr(m_Value(LHSOp)))) &&
2954 match(Op1, m_ZExt(m_PtrToAddr(m_Value(RHSOp)))))
2955 return true;
2956 // Special case for non-canonical ptrtoint in constant expression,
2957 // where the zext has been folded into the ptrtoint.
2958 if (match(Op0, m_ZExt(m_PtrToIntSameSize(DL, m_Value(LHSOp)))) &&
2959 match(Op1, m_PtrToInt(m_Value(RHSOp))))
2960 return true;
2961 return false;
2962 };
2963 if (MatchSubOfZExtOfPtrToIntOrAddr()) {
2964 if (auto *GEP = dyn_cast<GEPOperator>(LHSOp)) {
2965 if (GEP->getPointerOperand() == RHSOp) {
2966 if (GEP->hasNoUnsignedWrap() || GEP->hasNoUnsignedSignedWrap()) {
2967 Value *Offset = EmitGEPOffset(GEP);
2968 Value *Res = GEP->hasNoUnsignedWrap()
2969 ? Builder.CreateZExt(
2970 Offset, I.getType(), "",
2971 /*IsNonNeg=*/GEP->hasNoUnsignedSignedWrap())
2972 : Builder.CreateSExt(Offset, I.getType());
2973 return replaceInstUsesWith(I, Res);
2974 }
2975 }
2976 }
2977 }
2978
2979 // Canonicalize a shifty way to code absolute value to the common pattern.
2980 // There are 2 potential commuted variants.
2981 // We're relying on the fact that we only do this transform when the shift has
2982 // exactly 2 uses and the xor has exactly 1 use (otherwise, we might increase
2983 // instructions).
2984 Value *A;
2985 const APInt *ShAmt;
2986 Type *Ty = I.getType();
2987 unsigned BitWidth = Ty->getScalarSizeInBits();
2988 if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
2989 Op1->hasNUses(2) && *ShAmt == BitWidth - 1 &&
2990 match(Op0, m_OneUse(m_c_Xor(m_Specific(A), m_Specific(Op1))))) {
2991 // B = ashr i32 A, 31 ; smear the sign bit
2992 // sub (xor A, B), B ; flip bits if negative and subtract -1 (add 1)
2993 // --> (A < 0) ? -A : A
2994 Value *IsNeg = Builder.CreateIsNeg(A);
2995 // Copy the nsw flags from the sub to the negate.
2996 Value *NegA = I.hasNoUnsignedWrap()
2997 ? Constant::getNullValue(A->getType())
2998 : Builder.CreateNeg(A, "", I.hasNoSignedWrap());
2999 return SelectInst::Create(IsNeg, NegA, A);
3000 }
3001
3002 // If we are subtracting a low-bit masked subset of some value from an add
3003 // of that same value with no low bits changed, that is clearing some low bits
3004 // of the sum:
3005 // sub (X + AddC), (X & AndC) --> and (X + AddC), ~AndC
3006 const APInt *AddC, *AndC;
3007 if (match(Op0, m_Add(m_Value(X), m_APInt(AddC))) &&
3008 match(Op1, m_And(m_Specific(X), m_APInt(AndC)))) {
3009 unsigned Cttz = AddC->countr_zero();
3010 APInt HighMask(APInt::getHighBitsSet(BitWidth, BitWidth - Cttz));
3011 if ((HighMask & *AndC).isZero())
3012 return BinaryOperator::CreateAnd(Op0, ConstantInt::get(Ty, ~(*AndC)));
3013 }
3014
3015 if (Instruction *V =
3017 return V;
3018
3019 // X - usub.sat(X, Y) => umin(X, Y)
3021 m_Value(Y)))))
3022 return replaceInstUsesWith(
3023 I, Builder.CreateIntrinsic(Intrinsic::umin, {I.getType()}, {Op0, Y}));
3024
3025 // umax(X, Op1) - Op1 --> usub.sat(X, Op1)
3026 // TODO: The one-use restriction is not strictly necessary, but it may
3027 // require improving other pattern matching and/or codegen.
3028 if (match(Op0, m_OneUse(m_c_UMax(m_Value(X), m_Specific(Op1)))))
3029 return replaceInstUsesWith(
3030 I, Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {X, Op1}));
3031
3032 // Op0 - umin(X, Op0) --> usub.sat(Op0, X)
3033 if (match(Op1, m_OneUse(m_c_UMin(m_Value(X), m_Specific(Op0)))))
3034 return replaceInstUsesWith(
3035 I, Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {Op0, X}));
3036
3037 // Op0 - umax(X, Op0) --> 0 - usub.sat(X, Op0)
3038 if (match(Op1, m_OneUse(m_c_UMax(m_Value(X), m_Specific(Op0))))) {
3039 Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {X, Op0});
3040 return BinaryOperator::CreateNeg(USub);
3041 }
3042
3043 // umin(X, Op1) - Op1 --> 0 - usub.sat(Op1, X)
3044 if (match(Op0, m_OneUse(m_c_UMin(m_Value(X), m_Specific(Op1))))) {
3045 Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {Op1, X});
3046 return BinaryOperator::CreateNeg(USub);
3047 }
3048
3049 // C - ctpop(X) => ctpop(~X) if C is bitwidth
3050 if (match(Op0, m_SpecificInt(BitWidth)) &&
3051 match(Op1, m_OneUse(m_Ctpop(m_Value(X)))))
3052 return replaceInstUsesWith(
3053 I, Builder.CreateIntrinsic(Intrinsic::ctpop, {I.getType()},
3054 {Builder.CreateNot(X)}));
3055
3056 // Reduce multiplies for difference-of-squares by factoring:
3057 // (X * X) - (Y * Y) --> (X + Y) * (X - Y)
3058 if (match(Op0, m_OneUse(m_Mul(m_Value(X), m_Deferred(X)))) &&
3059 match(Op1, m_OneUse(m_Mul(m_Value(Y), m_Deferred(Y))))) {
3060 auto *OBO0 = cast<OverflowingBinaryOperator>(Op0);
3061 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3062 bool PropagateNSW = I.hasNoSignedWrap() && OBO0->hasNoSignedWrap() &&
3063 OBO1->hasNoSignedWrap() && BitWidth > 2;
3064 bool PropagateNUW = I.hasNoUnsignedWrap() && OBO0->hasNoUnsignedWrap() &&
3065 OBO1->hasNoUnsignedWrap() && BitWidth > 1;
3066 Value *Add = Builder.CreateAdd(X, Y, "add", PropagateNUW, PropagateNSW);
3067 Value *Sub = Builder.CreateSub(X, Y, "sub", PropagateNUW, PropagateNSW);
3068 Value *Mul = Builder.CreateMul(Add, Sub, "", PropagateNUW, PropagateNSW);
3069 return replaceInstUsesWith(I, Mul);
3070 }
3071
3072 // max(X,Y) nsw/nuw - min(X,Y) --> abs(X nsw - Y)
3073 if (match(Op0, m_OneUse(m_c_SMax(m_Value(X), m_Value(Y)))) &&
3075 if (I.hasNoUnsignedWrap() || I.hasNoSignedWrap()) {
3076 Value *Sub =
3077 Builder.CreateSub(X, Y, "sub", /*HasNUW=*/false, /*HasNSW=*/true);
3078 Value *Call =
3079 Builder.CreateBinaryIntrinsic(Intrinsic::abs, Sub, Builder.getTrue());
3080 return replaceInstUsesWith(I, Call);
3081 }
3082 }
3083
3085 return Res;
3086
3087 // (sub (sext (add nsw (X, Y)), sext (X))) --> (sext (Y))
3088 if (match(Op1, m_SExtLike(m_Value(X))) &&
3090 Value *SExtY = Builder.CreateSExt(Y, I.getType());
3091 return replaceInstUsesWith(I, SExtY);
3092 }
3093
3094 // (sub[ nsw] (sext (add nsw (X, Y)), sext (add nsw (X, Z)))) -->
3095 // --> (sub[ nsw] (sext (Y), sext (Z)))
3096 {
3097 Value *Z, *Add0, *Add1;
3098 if (match(Op0, m_SExtLike(m_Value(Add0))) &&
3099 match(Op1, m_SExtLike(m_Value(Add1))) &&
3100 ((match(Add0, m_NSWAdd(m_Value(X), m_Value(Y))) &&
3101 match(Add1, m_c_NSWAdd(m_Specific(X), m_Value(Z)))) ||
3102 (match(Add0, m_NSWAdd(m_Value(Y), m_Value(X))) &&
3103 match(Add1, m_c_NSWAdd(m_Specific(X), m_Value(Z)))))) {
3104 unsigned NumOfNewInstrs = 0;
3105 // Non-constant Y, Z require new SExt.
3106 NumOfNewInstrs += !isa<Constant>(Y) ? 1 : 0;
3107 NumOfNewInstrs += !isa<Constant>(Z) ? 1 : 0;
3108 // Check if we can trade some of the old instructions for the new ones.
3109 unsigned NumOfDeadInstrs = 0;
3110 if (Op0->hasOneUse()) {
3111 // If Op0 (sext) has multiple uses, then we keep it
3112 // and the add that it uses, otherwise, we can remove
3113 // the sext and probably the add (depending on the number of its uses).
3114 ++NumOfDeadInstrs;
3115 NumOfDeadInstrs += Add0->hasOneUse() ? 1 : 0;
3116 }
3117 if (Op1->hasOneUse()) {
3118 ++NumOfDeadInstrs;
3119 NumOfDeadInstrs += Add1->hasOneUse() ? 1 : 0;
3120 }
3121 if (NumOfDeadInstrs >= NumOfNewInstrs) {
3122 Value *SExtY = Builder.CreateSExt(Y, I.getType());
3123 Value *SExtZ = Builder.CreateSExt(Z, I.getType());
3124 Value *Sub = Builder.CreateSub(SExtY, SExtZ, "",
3125 /*HasNUW=*/false,
3126 /*HasNSW=*/I.hasNoSignedWrap());
3127 return replaceInstUsesWith(I, Sub);
3128 }
3129 }
3130 }
3131
3132 // ((X + C) & ~C) - X -> X & C where C is a power of 2.
3133 if (match(Op0,
3134 m_And(m_Add(m_Specific(Op1), m_Power2(AddC)), m_APInt(AndC))) &&
3135 *AddC == ~*AndC) {
3136 return BinaryOperator::CreateAnd(Op1, ConstantInt::get(Ty, *AddC));
3137 }
3138
3139 return TryToNarrowDeduceFlags();
3140}
3141
3142/// This eliminates floating-point negation in either 'fneg(X)' or
3143/// 'fsub(-0.0, X)' form by combining into a constant operand.
3145 // This is limited with one-use because fneg is assumed better for
3146 // reassociation and cheaper in codegen than fmul/fdiv.
3147 // TODO: Should the m_OneUse restriction be removed?
3148 Instruction *FNegOp;
3149 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3151 return nullptr;
3152
3153 Value *X;
3154 Constant *C;
3155
3156 // Fold negation into constant operand.
3157 // -(X * C) --> X * (-C)
3158 if (match(FNegOp, m_FMul(m_Value(X), m_Constant(C))))
3159 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL)) {
3160 FastMathFlags FNegF = I.getFastMathFlags();
3161 FastMathFlags OpF = FNegOp->getFastMathFlags();
3162 FastMathFlags FMF = FastMathFlags::unionValue(FNegF, OpF) |
3164 FMF.setNoInfs(FNegF.noInfs() && OpF.noInfs());
3165 return BinaryOperator::CreateFMulFMF(X, NegC, FMF);
3166 }
3167 // -(X / C) --> X / (-C)
3168 if (match(FNegOp, m_FDiv(m_Value(X), m_Constant(C)))) {
3169 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL)) {
3171
3172 // Intersect 'nsz' and 'ninf' because those special value exceptions may
3173 // not apply to the fdiv. Everything else propagates from the fneg.
3174 FastMathFlags FMF = I.getFastMathFlags();
3175 FastMathFlags OpFMF = FNegOp->getFastMathFlags();
3176 FDiv->setHasNoSignedZeros(FMF.noSignedZeros() && OpFMF.noSignedZeros());
3177 FDiv->setHasNoInfs(FMF.noInfs() && OpFMF.noInfs());
3178 FDiv->copyMetadata(*FNegOp);
3179 return FDiv;
3180 }
3181 }
3182 // -(C / X) --> (-C) / X
3183 if (match(FNegOp, m_FDiv(m_Constant(C), m_Value(X))))
3184 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL)) {
3186
3187 // Intersect 'nsz' and 'ninf' because those special value exceptions may
3188 // not apply to the fdiv. Everything else propagates from the fneg.
3189 // TODO: We could propagate nsz/ninf from fdiv alone?
3190 FastMathFlags FMF = I.getFastMathFlags();
3191 FastMathFlags OpFMF = FNegOp->getFastMathFlags();
3192 FDiv->setHasNoSignedZeros(FMF.noSignedZeros() && OpFMF.noSignedZeros());
3193 FDiv->setHasNoInfs(FMF.noInfs() && OpFMF.noInfs());
3194 FDiv->copyMetadata(*FNegOp);
3195 return FDiv;
3196 }
3197 // With NSZ [ counter-example with -0.0: -(-0.0 + 0.0) != 0.0 + -0.0 ]:
3198 // -(X + C) --> -X + -C --> -C - X
3199 if (I.hasNoSignedZeros() && match(FNegOp, m_FAdd(m_Value(X), m_Constant(C))))
3200 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
3201 return BinaryOperator::CreateFSubFMF(NegC, X, &I);
3202
3203 return nullptr;
3204}
3205
3206Instruction *InstCombinerImpl::hoistFNegAboveFMulFDiv(Value *FNegOp,
3207 Instruction &FMFSource) {
3208 Value *X, *Y;
3209 if (match(FNegOp, m_FMul(m_Value(X), m_Value(Y)))) {
3210 // Push into RHS which is more likely to simplify (const or another fneg).
3211 // FIXME: It would be better to invert the transform.
3212 return cast<Instruction>(Builder.CreateFMulFMF(
3213 X, Builder.CreateFNegFMF(Y, &FMFSource), &FMFSource));
3214 }
3215
3216 if (match(FNegOp, m_FDiv(m_Value(X), m_Value(Y)))) {
3217 auto *FDiv = cast<Instruction>(Builder.CreateFDivFMF(
3218 Builder.CreateFNegFMF(X, &FMFSource), Y, &FMFSource));
3219 FDiv->copyMetadata(*cast<Instruction>(FNegOp));
3220 return FDiv;
3221 }
3222
3223 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(FNegOp)) {
3224 // Make sure to preserve flags and metadata on the call.
3225 if (II->getIntrinsicID() == Intrinsic::ldexp) {
3226 FastMathFlags FMF = FMFSource.getFastMathFlags() | II->getFastMathFlags();
3227 CallInst *New =
3228 Builder.CreateCall(II->getCalledFunction(),
3229 {Builder.CreateFNegFMF(II->getArgOperand(0), FMF),
3230 II->getArgOperand(1)});
3231 New->setFastMathFlags(FMF);
3232 New->copyMetadata(*II);
3233 return New;
3234 }
3235 }
3236
3237 return nullptr;
3238}
3239
3241 Value *Op = I.getOperand(0);
3242
3243 if (Value *V = simplifyFNegInst(Op, I.getFastMathFlags(),
3244 getSimplifyQuery().getWithInstruction(&I)))
3245 return replaceInstUsesWith(I, V);
3246
3248 return X;
3249
3250 Value *X, *Y;
3251
3252 // If we can ignore the sign of zeros: -(X - Y) --> (Y - X)
3253 if (I.hasNoSignedZeros() &&
3256
3257 Value *OneUse;
3258 if (!match(Op, m_OneUse(m_Value(OneUse))))
3259 return nullptr;
3260
3261 if (Instruction *R = hoistFNegAboveFMulFDiv(OneUse, I))
3262 return replaceInstUsesWith(I, R);
3263
3264 // Try to eliminate fneg if at least 1 arm of the select is negated.
3265 Value *Cond;
3266 if (match(OneUse, m_Select(m_Value(Cond), m_Value(X), m_Value(Y)))) {
3267 // Unlike most transforms, this one is not safe to propagate nsz unless
3268 // it is present on the original select. We union the flags from the select
3269 // and fneg and then remove nsz if needed.
3270 auto propagateSelectFMF = [&](SelectInst *S, bool CommonOperand) {
3271 S->copyFastMathFlags(&I);
3272 if (auto *OldSel = dyn_cast<SelectInst>(Op)) {
3273 FastMathFlags FMF = I.getFastMathFlags() | OldSel->getFastMathFlags();
3274 S->setFastMathFlags(FMF);
3275 if (!OldSel->hasNoSignedZeros() && !CommonOperand &&
3276 !isGuaranteedNotToBeUndefOrPoison(OldSel->getCondition()))
3277 S->setHasNoSignedZeros(false);
3278 }
3279 };
3280 // -(Cond ? -P : Y) --> Cond ? P : -Y
3281 Value *P;
3282 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3284 Value *NegY = Builder.CreateFNegFMF(Y, &I, Y->getName() + ".neg");
3286 Cond, P, NegY, "", nullptr,
3288 propagateSelectFMF(NewSel, P == Y);
3289 return NewSel;
3290 }
3291 // -(Cond ? X : -P) --> Cond ? -X : P
3292 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3294 Value *NegX = Builder.CreateFNegFMF(X, &I, X->getName() + ".neg");
3296 Cond, NegX, P, "", nullptr,
3298 propagateSelectFMF(NewSel, P == X);
3299 return NewSel;
3300 }
3301
3302 // -(Cond ? X : C) --> Cond ? -X : -C
3303 // -(Cond ? C : Y) --> Cond ? -C : -Y
3304 if (match(X, m_ImmConstant()) || match(Y, m_ImmConstant())) {
3305 Value *NegX = Builder.CreateFNegFMF(X, &I, X->getName() + ".neg");
3306 Value *NegY = Builder.CreateFNegFMF(Y, &I, Y->getName() + ".neg");
3308 Cond, NegX, NegY, "", nullptr,
3310 propagateSelectFMF(NewSel, /*CommonOperand=*/true);
3311 return NewSel;
3312 }
3313 }
3314
3315 // fneg (copysign x, y) -> copysign x, (fneg y)
3316 if (match(OneUse, m_CopySign(m_Value(X), m_Value(Y)))) {
3317 // The source copysign has an additional value input, so we can't propagate
3318 // flags the copysign doesn't also have.
3319 FastMathFlags FMF = I.getFastMathFlags();
3320 FMF &= cast<FPMathOperator>(OneUse)->getFastMathFlags();
3321 Value *NegY = Builder.CreateFNegFMF(Y, FMF);
3322 Value *NewCopySign = Builder.CreateCopySign(X, NegY, FMF);
3323 return replaceInstUsesWith(I, NewCopySign);
3324 }
3325
3326 // fneg (shuffle x, Mask) --> shuffle (fneg x), Mask
3327 ArrayRef<int> Mask;
3328 if (match(OneUse, m_Shuffle(m_Value(X), m_Poison(), m_Mask(Mask))))
3329 return new ShuffleVectorInst(Builder.CreateFNegFMF(X, &I), Mask);
3330
3331 // fneg (reverse x) --> reverse (fneg x)
3332 if (match(OneUse, m_VecReverse(m_Value(X)))) {
3333 Value *Reverse = Builder.CreateVectorReverse(Builder.CreateFNegFMF(X, &I));
3334 return replaceInstUsesWith(I, Reverse);
3335 }
3336
3337 return nullptr;
3338}
3339
3341 if (Value *V = simplifyFSubInst(I.getOperand(0), I.getOperand(1),
3342 I.getFastMathFlags(),
3343 getSimplifyQuery().getWithInstruction(&I)))
3344 return replaceInstUsesWith(I, V);
3345
3347 return X;
3348
3350 return Phi;
3351
3352 // Subtraction from -0.0 is the canonical form of fneg.
3353 // fsub -0.0, X ==> fneg X
3354 // fsub nsz 0.0, X ==> fneg nsz X
3355 //
3356 // FIXME This matcher does not respect FTZ or DAZ yet:
3357 // fsub -0.0, Denorm ==> +-0
3358 // fneg Denorm ==> -Denorm
3359 Value *Op;
3360 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3363
3365 return X;
3366
3367 if (Instruction *R = foldFBinOpOfIntCasts(I))
3368 return R;
3369
3370 Value *X, *Y;
3371 Constant *C;
3372
3373 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3374 // If Op0 is not -0.0 or we can ignore -0.0: Z - (X - Y) --> Z + (Y - X)
3375 // Canonicalize to fadd to make analysis easier.
3376 // This can also help codegen because fadd is commutative.
3377 // Note that if this fsub was really an fneg, the fadd with -0.0 will get
3378 // killed later. We still limit that particular transform with 'hasOneUse'
3379 // because an fneg is assumed better/cheaper than a generic fsub.
3380 if (I.hasNoSignedZeros() ||
3381 cannotBeNegativeZero(Op0, getSimplifyQuery().getWithInstruction(&I))) {
3382 if (match(Op1, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
3383 Value *NewSub = Builder.CreateFSubFMF(Y, X, &I);
3384 return BinaryOperator::CreateFAddFMF(Op0, NewSub, &I);
3385 }
3386 }
3387
3388 // (-X) - Op1 --> -(X + Op1)
3389 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3390 if (I.hasNoSignedZeros() && !isa<ConstantExpr>(Op0) &&
3392 Value *FAdd = Builder.CreateFAddFMF(X, Op1, &I);
3394 }
3395
3396 if (isa<Constant>(Op0))
3398 if (Instruction *NV = FoldOpIntoSelect(I, SI))
3399 return NV;
3400
3401 // X - C --> X + (-C)
3402 // But don't transform constant expressions because there's an inverse fold
3403 // for X + (-Y) --> X - Y.
3404 if (match(Op1, m_ImmConstant(C)))
3405 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
3406 return BinaryOperator::CreateFAddFMF(Op0, NegC, &I);
3407
3408 // X - (-Y) --> X + Y
3409 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3410 if (match(Op1, m_FNegOrFSubNegZero(m_Value(Y))))
3411 return BinaryOperator::CreateFAddFMF(Op0, Y, &I);
3412
3413 // Similar to above, but look through a cast of the negated value:
3414 // X - (fptrunc(-Y)) --> X + fptrunc(Y)
3415 Type *Ty = I.getType();
3416 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3418 return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPTrunc(Y, Ty), &I);
3419
3420 // X - (fpext(-Y)) --> X + fpext(Y)
3421 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3423 return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPExt(Y, Ty), &I);
3424
3425 // Similar to above, but look through fmul/fdiv of the negated value:
3426 // Op0 - (-X * Y) --> Op0 + (X * Y)
3427 // Op0 - (Y * -X) --> Op0 + (X * Y)
3428 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3429 if (match(Op1,
3431 Value *FMul = Builder.CreateFMulFMF(X, Y, &I);
3432 return BinaryOperator::CreateFAddFMF(Op0, FMul, &I);
3433 }
3434 // Op0 - (-X / Y) --> Op0 + (X / Y)
3435 // Op0 - (X / -Y) --> Op0 + (X / Y)
3436 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
3437 if (match(Op1,
3439 match(Op1,
3441 Value *FDiv = Builder.CreateFDivFMF(X, Y, &I);
3442 return BinaryOperator::CreateFAddFMF(Op0, FDiv, &I);
3443 }
3444
3445 // Handle special cases for FSub with selects feeding the operation
3446 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
3447 return replaceInstUsesWith(I, V);
3448
3449 if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
3450 // (Y - X) - Y --> -X
3451 if (match(Op0, m_FSub(m_Specific(Op1), m_Value(X))))
3453
3454 // Y - (X + Y) --> -X
3455 // Y - (Y + X) --> -X
3456 if (match(Op1, m_c_FAdd(m_Specific(Op0), m_Value(X))))
3458
3459 // (X * C) - X --> X * (C - 1.0)
3460 if (match(Op0, m_FMul(m_Specific(Op1), m_Constant(C)))) {
3462 Instruction::FSub, C, ConstantFP::get(Ty, 1.0), DL))
3463 return BinaryOperator::CreateFMulFMF(Op1, CSubOne, &I);
3464 }
3465 // X - (X * C) --> X * (1.0 - C)
3466 if (match(Op1, m_FMul(m_Specific(Op0), m_Constant(C)))) {
3468 Instruction::FSub, ConstantFP::get(Ty, 1.0), C, DL))
3469 return BinaryOperator::CreateFMulFMF(Op0, OneSubC, &I);
3470 }
3471
3472 // Reassociate fsub/fadd sequences to create more fadd instructions and
3473 // reduce dependency chains:
3474 // ((X - Y) + Z) - Op1 --> (X + Z) - (Y + Op1)
3475 Value *Z;
3477 m_Value(Z))))) {
3478 Value *XZ = Builder.CreateFAddFMF(X, Z, &I);
3479 Value *YW = Builder.CreateFAddFMF(Y, Op1, &I);
3480 return BinaryOperator::CreateFSubFMF(XZ, YW, &I);
3481 }
3482
3483 auto m_FaddRdx = [](Value *&Sum, Value *&Vec) {
3485 m_Value(Vec)));
3486 };
3487 Value *A0, *A1, *V0, *V1;
3488 if (match(Op0, m_FaddRdx(A0, V0)) && match(Op1, m_FaddRdx(A1, V1)) &&
3489 V0->getType() == V1->getType()) {
3490 // Difference of sums is sum of differences:
3491 // add_rdx(A0, V0) - add_rdx(A1, V1) --> add_rdx(A0, V0 - V1) - A1
3492 Value *Sub = Builder.CreateFSubFMF(V0, V1, &I);
3493 Value *Rdx = Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
3494 {Sub->getType()}, {A0, Sub}, &I);
3495 return BinaryOperator::CreateFSubFMF(Rdx, A1, &I);
3496 }
3497
3499 return F;
3500
3501 // TODO: This performs reassociative folds for FP ops. Some fraction of the
3502 // functionality has been subsumed by simple pattern matching here and in
3503 // InstSimplify. We should let a dedicated reassociation pass handle more
3504 // complex pattern matching and remove this from InstCombine.
3505 if (Value *V = FAddCombine(Builder).simplify(&I))
3506 return replaceInstUsesWith(I, V);
3507
3508 // (X - Y) - Op1 --> X - (Y + Op1)
3509 if (match(Op0, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
3510 Value *FAdd = Builder.CreateFAddFMF(Y, Op1, &I);
3512 }
3513 }
3514
3515 return nullptr;
3516}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isConstant(const MachineInstr &MI)
AMDGPU Register Bank Select
Rewrite undef for PHI
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define DEBUG_TYPE
hexagon bit simplify
Hexagon Common GEP
static Instruction * factorizeFAddFSub(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
Factor a common operand out of fadd/fsub of fmul/fdiv.
static Instruction * foldAddToAshr(BinaryOperator &Add)
Try to reduce signed division by power-of-2 to an arithmetic shift right.
static bool MatchMul(Value *E, Value *&Op, APInt &C)
static bool MatchDiv(Value *E, Value *&Op, APInt &C, bool IsSigned)
static Instruction * foldFNegIntoConstant(Instruction &I, const DataLayout &DL)
This eliminates floating-point negation in either 'fneg(X)' or 'fsub(-0.0, X)' form by combining into...
static Instruction * combineAddSubWithShlAddSub(InstCombiner::BuilderTy &Builder, const BinaryOperator &I)
static Instruction * factorizeLerp(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
Eliminate an op from a linear interpolation (lerp) pattern.
static Instruction * foldSubOfMinMax(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
static Instruction * foldSubNUWOfMaskAndZExt(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
sub nuw (and X, LowMask), (zext Y) --> zext (sub nuw (trunc X), Y) sub nuw (zext Y),...
static Instruction * foldBoxMultiply(BinaryOperator &I)
Reduce a sequence of masked half-width multiplies to a single multiply.
static Value * checkForNegativeOperand(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
static bool MulWillOverflow(APInt &C0, APInt &C1, bool IsSigned)
static Instruction * foldNoWrapAdd(BinaryOperator &Add, InstCombiner::BuilderTy &Builder)
Wrapping flags may allow combining constants separated by an extend.
static bool matchesSquareSum(BinaryOperator &I, Mul2Rhs M2Rhs, Value *&A, Value *&B)
static Instruction * factorizeMathWithShlOps(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
This is a specialization of a more general transform from foldUsingDistributiveLaws.
static Instruction * canonicalizeLowbitMask(BinaryOperator &I, InstCombiner::BuilderTy &Builder)
Fold (1 << NBits) - 1 Into: ~(-(1 << NBits)) Because a 'not' is better for bit-tracking analysis and ...
static bool checkDivCeilNUW(Value *X, Value *Y, const SimplifyQuery &SQ)
Return true if X + (Y-1) is provably non-wrapping in X's type.
static Instruction * foldToUnsignedSaturatedAdd(BinaryOperator &I)
static bool MatchRem(Value *E, Value *&Op, APInt &C, bool &IsSigned)
This file provides internal interfaces used to implement the InstCombine.
This file provides the interface for the instcombine pass implementation.
static constexpr Value * getValue(Ty &ValueOrUse)
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:540
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
uint64_t IntrinsicInst * II
#define P(N)
This file contains the declarations for profiling metadata utility functions.
SmallVector< MachineOperand, 4 > Cond
int64_t C1
int64_t C0
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
static unsigned getScalarSizeInBits(Type *Ty)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Value * LHS
opStatus multiply(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1303
Class for arbitrary precision integers.
Definition APInt.h:78
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition APInt.h:445
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool isSignMask() const
Check if the APInt's value is returned by getSignMask.
Definition APInt.h:462
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
int32_t exactLogBase2() const
Definition APInt.h:1803
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
unsigned logBase2() const
Definition APInt.h:1781
bool isMask(unsigned numBits) const
Definition APInt.h:484
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
static BinaryOperator * CreateFAddFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition InstrTypes.h:271
static LLVM_ABI BinaryOperator * CreateNeg(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Helper functions to construct and inspect unary operations (NEG and NOT) via binary operators SUB and...
static LLVM_ABI BinaryOperator * CreateNot(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
static BinaryOperator * CreateFMulFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition InstrTypes.h:279
static BinaryOperator * CreateFDivFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition InstrTypes.h:283
static BinaryOperator * CreateFSubFMF(Value *V1, Value *V2, FastMathFlags FMF, const Twine &Name="")
Definition InstrTypes.h:275
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI CastInst * CreateTruncOrBitCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a Trunc or BitCast cast instruction.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_NE
not equal
Definition InstrTypes.h:762
bool isSigned() const
Definition InstrTypes.h:993
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
const APFloat & getValueAPF() const
Definition Constants.h:463
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
This class represents a range of values.
LLVM_ABI APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI bool isElementWiseEqual(Value *Y) const
Return true if this constant and a constant 'Y' are element-wise equal.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
static FastMathFlags intersectRewrite(FastMathFlags LHS, FastMathFlags RHS)
Intersect rewrite-based flags.
Definition FMF.h:116
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
static FastMathFlags unionValue(FastMathFlags LHS, FastMathFlags RHS)
Union value flags.
Definition FMF.h:124
void setNoInfs(bool B=true)
Definition FMF.h:81
static bool isLT(Predicate P)
Return true if the predicate is SLT or ULT.
static bool isGT(Predicate P)
Return true if the predicate is SGT or UGT.
Instruction * foldBinOpOfSelectAndCastOfSelectCondition(BinaryOperator &I)
Tries to simplify binops of select and cast of the select condition.
Instruction * visitAdd(BinaryOperator &I)
Instruction * canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(BinaryOperator &I)
Instruction * foldBinOpIntoSelectOrPhi(BinaryOperator &I)
This is a convenience wrapper function for the above two functions.
bool SimplifyAssociativeOrCommutative(BinaryOperator &I)
Performs a few simplifications for operators which are associative or commutative.
Value * foldUsingDistributiveLaws(BinaryOperator &I)
Tries to simplify binary operations which some other binary operation distributes over.
Instruction * foldBinOpShiftWithShift(BinaryOperator &I)
Instruction * foldSquareSumInt(BinaryOperator &I)
Instruction * foldOpIntoPhi(Instruction &I, PHINode *PN, bool AllowMultipleUses=false)
Given a binary operator, cast instruction, or select which has a PHI node as operand #0,...
Instruction * foldBinOpSelectBinOp(BinaryOperator &Op)
In some cases it is beneficial to fold a select into a binary operator.
Instruction * foldSquareSumFP(BinaryOperator &I)
Instruction * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false, bool SimplifyBothArms=false)
Given an instruction with a select as one operand and a constant as the other operand,...
Instruction * visitSub(BinaryOperator &I)
Instruction * foldDivCeil(BinaryOperator &I)
Fold both forms of the div_ceil idiom: (add (udiv X, Y), (zext (icmp ne (urem X, Y),...
Value * OptimizePointerDifference(Value *LHS, Value *RHS, Type *Ty, bool isNUW)
Optimize pointer differences into the same array into a size.
Instruction * visitFAdd(BinaryOperator &I)
Instruction * foldBinopWithPhiOperands(BinaryOperator &BO)
For a binary operator with 2 phi operands, try to hoist the binary operation before the phi.
Instruction * foldAddLikeCommutative(Value *LHS, Value *RHS, bool NSW, bool NUW)
Common transforms for add / disjoint or.
Instruction * tryFoldInstWithCtpopWithNot(Instruction *I)
Value * SimplifyAddWithRemainder(BinaryOperator &I)
Tries to simplify add operations using the definition of remainder.
Instruction * foldAddWithConstant(BinaryOperator &Add)
Instruction * foldVectorBinop(BinaryOperator &Inst)
Canonicalize the position of binops relative to shufflevector.
Value * SimplifySelectsFeedingBinaryOp(BinaryOperator &I, Value *LHS, Value *RHS)
Instruction * visitFNeg(UnaryOperator &I)
Instruction * visitFSub(BinaryOperator &I)
SimplifyQuery SQ
bool isFreeToInvert(Value *V, bool WillInvertAllUses, bool &DoesConsume)
Return true if the specified value is free to invert (apply ~ to).
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
static Constant * SubOne(Constant *C)
Subtract one from a Constant.
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
const DataLayout & DL
unsigned ComputeNumSignBits(const Value *Op, const Instruction *CtxI=nullptr, unsigned Depth=0) const
IRBuilder< TargetFolder, IRBuilderInstCombineInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
AssumptionCache & AC
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
DominatorTree & DT
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CtxI, unsigned Depth=0) const
Value * getFreelyInverted(Value *V, bool WillInvertAllUses, BuilderTy *Builder, bool &DoesConsume)
const SimplifyQuery & getSimplifyQuery() const
static Constant * AddOne(Constant *C)
Add one to a Constant.
LLVM_ABI void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI void copyFastMathFlags(FastMathFlags FMF)
Convenience function for transferring all fast-math flag values to this instruction,...
LLVM_ABI void setHasNoSignedZeros(bool B)
Set or clear the no-signed-zeros flag on this instruction, which must be an operator which supports t...
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI void setHasNoInfs(bool B)
Set or clear the no-infs flag on this instruction, which must be an operator which supports this flag...
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
static Value * Negate(bool LHSIsZero, bool IsNSW, Value *Root, InstCombinerImpl &IC)
Attempt to negate Root.
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property.
Definition Operator.h:113
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
Definition Operator.h:107
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
This instruction constructs a fixed permutation of two input vectors.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static UnaryOperator * CreateFNegFMF(Value *Op, Instruction *FMFSource, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Definition InstrTypes.h:156
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI bool hasNUsesOrMore(unsigned N) const
Return true if this value has N uses or more.
Definition Value.cpp:151
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
This class represents zero extension of integer types.
CallInst * Call
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
PtrToIntSameSize_match< OpTy > m_PtrToIntSameSize(const DataLayout &DL, const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
auto m_c_UMax(const LHS &L, const RHS &R)
Matches a UMax with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::FMul, true > m_c_FMul(const LHS &L, const RHS &R)
Matches FMul with LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
auto m_PtrToIntOrAddr(const OpTy &Op)
Matches PtrToInt or PtrToAddr.
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap, true > m_c_NSWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, TruncInst >, OpTy > m_TruncOrSelf(const OpTy &Op)
CommutativeBinaryIntrinsic_match< IntrID, T0, T1 > m_c_Intrinsic(const T0 &Op0, const T1 &Op1)
auto m_Poison()
Match an arbitrary poison constant.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
CastOperator_match< OpTy, Instruction::PtrToAddr > m_PtrToAddr(const OpTy &Op)
Matches PtrToAddr.
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
BinaryOp_match< LHS, RHS, Instruction::FMul > m_FMul(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, OpTy > m_ZExtOrSelf(const OpTy &Op)
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
DisjointOr_match< LHS, RHS > m_DisjointOr(const LHS &L, const RHS &R)
specific_intval< true > m_SpecificIntAllowPoison(const APInt &V)
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
match_combine_or< CastInst_match< OpTy, SExtInst >, OpTy > m_SExtOrSelf(const OpTy &Op)
specific_fpval m_SpecificFP(double V)
Match a specific floating point value or vector with all elements equal to the value.
auto m_CopySign(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::FAdd > m_FAdd(const LHS &L, const RHS &R)
auto m_Ctpop(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
ThreeOps_match< decltype(m_Value()), LHS, RHS, Instruction::Select, true > m_c_Select(const LHS &L, const RHS &R)
Match Select(C, LHS, RHS) or Select(C, RHS, LHS)
CastInst_match< OpTy, FPExtInst > m_FPExt(const OpTy &Op)
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
auto m_Ctlz(const Opnd0 &Op0, const Opnd1 &Op1)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
cst_pred_ty< is_negated_power2 > m_NegatedPower2()
Match a integer or vector negated power-of-2.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
specific_fpval m_FPOne()
Match a float 1.0 or vector with all elements equal to 1.0.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
match_combine_or< CastInst_match< OpTy, SExtInst >, NNegZExt_match< OpTy > > m_SExtLike(const OpTy &Op)
Match either "sext" or "zext nneg".
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
BinaryOp_match< LHS, RHS, Instruction::SDiv > m_SDiv(const LHS &L, const RHS &R)
auto m_c_MaxOrMin(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
FNeg_match< OpTy, true > m_FNegOrFSubNegZero(const OpTy &X)
Match fneg X or fsub -0.0, X.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::FAdd, true > m_c_FAdd(const LHS &L, const RHS &R)
Matches FAdd with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::FDiv > m_FDiv(const LHS &L, const RHS &R)
auto m_c_UMin(const LHS &L, const RHS &R)
Matches a UMin with LHS and RHS in either order.
auto m_c_SMax(const LHS &L, const RHS &R)
Matches an SMax with LHS and RHS in either order.
CastInst_match< OpTy, FPTruncInst > m_FPTrunc(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
auto m_VecReverse(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
auto m_c_SMin(const LHS &L, const RHS &R)
Matches an SMin with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
LLVM_ABI Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)
@ Offset
Definition DWP.cpp:577
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
Definition LoopInfo.cpp:61
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
LLVM_ABI bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit.
@ Known
Known to have no common set bits.
@ Unknown
Not known to have no common set bits.
@ OnlyIfUndefIgnored
Known to have no common set bits only if undef values are ignored.
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt & operator+=(DynamicAPInt &A, int64_t B)
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI bool canIgnoreSignBitOfZero(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is zero.
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
LLVM_ABI Value * simplifySubInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for a Sub, fold the result or return null.
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
LLVM_ABI Value * simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt & operator*=(DynamicAPInt &A, int64_t B)
LLVM_ABI Constant * ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, const DataLayout &DL)
Attempt to constant fold a unary operation with the specified operand.
LLVM_ABI NoCommonBitsSetResult getNoCommonBitsSetResult(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return how strongly LHS and RHS are known to have no common set bits.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI Value * simplifyFNegInst(Value *Op, FastMathFlags FMF, const SimplifyQuery &Q)
Given operand for an FNeg, fold the result or return null.
LLVM_ABI Value * simplifyFSubInst(Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q, fp::ExceptionBehavior ExBehavior=fp::ebIgnore, RoundingMode Rounding=RoundingMode::NearestTiesToEven)
Given operands for an FSub, fold the result or return null.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI Value * simplifyFAddInst(Value *LHS, Value *RHS, FastMathFlags FMF, const SimplifyQuery &Q, fp::ExceptionBehavior ExBehavior=fp::ebIgnore, RoundingMode Rounding=RoundingMode::NearestTiesToEven)
Given operands for an FAdd, fold the result or return null.
LLVM_ABI bool cannotBeNegativeZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is never equal to -0.0.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ Mul
Product of integers.
@ FMul
Product of floats.
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ FAdd
Sum of floats.
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
DWARFExpression::Operation Op
RoundingMode
Rounding mode.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI Constant * ConstantFoldBinaryInstruction(unsigned Opcode, Constant *V1, Constant *V2)
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
Value * Ptr
Common base pointer.
SmallVector< GEPOperator * > RHSGEPs
RHS GEPs until common base.
SmallVector< GEPOperator * > LHSGEPs
LHS GEPs until common base.
bool isExpensive() const
Whether expanding the GEP chains is expensive.
static CommonPointerBase compute(Value *LHS, Value *RHS)
Matching combinators.