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 if (C->isOne() && Op0->hasOneUse()) {
987 // add (sext i1 X), 1 --> zext (not X)
988 // TODO: The smallest IR representation is (select X, 0, 1), and that would
989 // not require the one-use check. But we need to remove a transform in
990 // visitSelect and make sure that IR value tracking for select is equal or
991 // better than for these ops.
992 if (match(Op0, m_SExt(m_Value(X))) &&
993 X->getType()->getScalarSizeInBits() == 1)
994 return new ZExtInst(Builder.CreateNot(X), Ty);
995
996 // Shifts and add used to flip and mask off the low bit:
997 // add (ashr (shl i32 X, 31), 31), 1 --> and (not X), 1
998 const APInt *C3;
999 if (match(Op0, m_AShr(m_Shl(m_Value(X), m_APInt(C2)), m_APInt(C3))) &&
1000 C2 == C3 && *C2 == Ty->getScalarSizeInBits() - 1) {
1001 Value *NotX = Builder.CreateNot(X);
1002 return BinaryOperator::CreateAnd(NotX, ConstantInt::get(Ty, 1));
1003 }
1004 }
1005
1006 // umax(X, C) + -C --> usub.sat(X, C)
1007 if (match(Op0, m_OneUse(m_UMax(m_Value(X), m_SpecificInt(-*C)))))
1008 return replaceInstUsesWith(
1009 Add, Builder.CreateBinaryIntrinsic(
1010 Intrinsic::usub_sat, X, ConstantInt::get(Add.getType(), -*C)));
1011 // uadd.sat(X, C) + -C --> umin(X, ~C)
1012 // The saturating add gives X + C or UMAX, so subtracting C leaves X or
1013 // UMAX - C. Note UMAX - C == ~C.
1014 {
1015 APInt SatC = -*C;
1017 m_Value(X), m_SpecificInt(SatC)))))
1018 return replaceInstUsesWith(
1019 Add, Builder.CreateBinaryIntrinsic(Intrinsic::umin, X,
1020 ConstantInt::get(Ty, ~SatC)));
1021 }
1022 // Fold (add (zext (add X, -C)), C) -> (zext X) if X u>= C.
1023 // Truncate C to the narrow type to avoid mismatched width comparisons.
1024 {
1025 const APInt *InnerC;
1026 if (match(Op0, m_ZExt(m_Add(m_Value(X), m_APIntAllowPoison(InnerC))))) {
1027 unsigned NarrowBW = InnerC->getBitWidth();
1028 if (C->isIntN(NarrowBW)) {
1029 APInt NarrowC = C->trunc(NarrowBW);
1030 const SimplifyQuery Q = SQ.getWithInstruction(&Add);
1031 if (*InnerC == -NarrowC &&
1032 (NarrowC.isOne()
1034 : computeKnownBits(X, &Add).getMinValue().uge(NarrowC)))
1035 return new ZExtInst(X, Ty);
1036 }
1037 }
1038 }
1039
1040 return nullptr;
1041}
1042
1043// match variations of a^2 + 2*a*b + b^2
1044//
1045// to reuse the code between the FP and Int versions, the instruction OpCodes
1046// and constant types have been turned into template parameters.
1047//
1048// Mul2Rhs: The constant to perform the multiplicative equivalent of X*2 with;
1049// should be `m_SpecificFP(2.0)` for FP and `m_SpecificInt(1)` for Int
1050// (we're matching `X<<1` instead of `X*2` for Int)
1051template <bool FP, typename Mul2Rhs>
1052static bool matchesSquareSum(BinaryOperator &I, Mul2Rhs M2Rhs, Value *&A,
1053 Value *&B) {
1054 constexpr unsigned MulOp = FP ? Instruction::FMul : Instruction::Mul;
1055 constexpr unsigned AddOp = FP ? Instruction::FAdd : Instruction::Add;
1056 constexpr unsigned Mul2Op = FP ? Instruction::FMul : Instruction::Shl;
1057
1058 // (a * a) + (((a * 2) + b) * b)
1059 if (match(&I, m_c_BinOp(
1060 AddOp, m_BinOp(MulOp, m_Value(A), m_Deferred(A)),
1062 MulOp,
1063 m_c_BinOp(AddOp, m_BinOp(Mul2Op, m_Deferred(A), M2Rhs),
1064 m_Value(B)),
1065 m_Deferred(B))))))
1066 return true;
1067
1068 // ((a * b) * 2) or ((a * 2) * b)
1069 // +
1070 // (a * a + b * b) or (b * b + a * a)
1071 return match(
1072 &I, m_c_BinOp(
1073 AddOp,
1076 Mul2Op, m_BinOp(MulOp, m_Value(A), m_Value(B)), M2Rhs)),
1077 m_OneUse(m_c_BinOp(MulOp, m_BinOp(Mul2Op, m_Value(A), M2Rhs),
1078 m_Value(B)))),
1079 m_OneUse(
1080 m_c_BinOp(AddOp, m_BinOp(MulOp, m_Deferred(A), m_Deferred(A)),
1081 m_BinOp(MulOp, m_Deferred(B), m_Deferred(B))))));
1082}
1083
1084// Fold integer variations of a^2 + 2*a*b + b^2 -> (a + b)^2
1086 Value *A, *B;
1088 Value *AB = Builder.CreateAdd(A, B);
1089 return BinaryOperator::CreateMul(AB, AB);
1090 }
1091 return nullptr;
1092}
1093
1094// Fold floating point variations of a^2 + 2*a*b + b^2 -> (a + b)^2
1095// Requires `nsz` and `reassoc`.
1097 assert(I.hasAllowReassoc() && I.hasNoSignedZeros() && "Assumption mismatch");
1098 Value *A, *B;
1100 Value *AB = Builder.CreateFAddFMF(A, B, &I);
1101 return BinaryOperator::CreateFMulFMF(AB, AB, &I);
1102 }
1103 return nullptr;
1104}
1105
1106// Matches multiplication expression Op * C where C is a constant. Returns the
1107// constant value in C and the other operand in Op. Returns true if such a
1108// match is found.
1109static bool MatchMul(Value *E, Value *&Op, APInt &C) {
1110 const APInt *AI;
1111 if (match(E, m_Mul(m_Value(Op), m_APInt(AI)))) {
1112 C = *AI;
1113 return true;
1114 }
1115 if (match(E, m_Shl(m_Value(Op), m_APInt(AI)))) {
1116 C = APInt(AI->getBitWidth(), 1);
1117 C <<= *AI;
1118 return true;
1119 }
1120 return false;
1121}
1122
1123// Matches remainder expression Op % C where C is a constant. Returns the
1124// constant value in C and the other operand in Op. Returns the signedness of
1125// the remainder operation in IsSigned. Returns true if such a match is
1126// found.
1127static bool MatchRem(Value *E, Value *&Op, APInt &C, bool &IsSigned) {
1128 const APInt *AI;
1129 IsSigned = false;
1130 if (match(E, m_SRem(m_Value(Op), m_APInt(AI)))) {
1131 IsSigned = true;
1132 C = *AI;
1133 return true;
1134 }
1135 if (match(E, m_URem(m_Value(Op), m_APInt(AI)))) {
1136 C = *AI;
1137 return true;
1138 }
1139 if (match(E, m_And(m_Value(Op), m_APInt(AI))) && (*AI + 1).isPowerOf2()) {
1140 C = *AI + 1;
1141 return true;
1142 }
1143 return false;
1144}
1145
1146// Matches division expression Op / C with the given signedness as indicated
1147// by IsSigned, where C is a constant. Returns the constant value in C and the
1148// other operand in Op. Returns true if such a match is found.
1149static bool MatchDiv(Value *E, Value *&Op, APInt &C, bool IsSigned) {
1150 const APInt *AI;
1151 if (IsSigned && match(E, m_SDiv(m_Value(Op), m_APInt(AI)))) {
1152 C = *AI;
1153 return true;
1154 }
1155 if (!IsSigned) {
1156 if (match(E, m_UDiv(m_Value(Op), m_APInt(AI)))) {
1157 C = *AI;
1158 return true;
1159 }
1160 if (match(E, m_LShr(m_Value(Op), m_APInt(AI)))) {
1161 C = APInt(AI->getBitWidth(), 1);
1162 C <<= *AI;
1163 return true;
1164 }
1165 }
1166 return false;
1167}
1168
1169// Returns whether C0 * C1 with the given signedness overflows.
1170static bool MulWillOverflow(APInt &C0, APInt &C1, bool IsSigned) {
1171 bool overflow;
1172 if (IsSigned)
1173 (void)C0.smul_ov(C1, overflow);
1174 else
1175 (void)C0.umul_ov(C1, overflow);
1176 return overflow;
1177}
1178
1179// Simplifies X % C0 + (( X / C0 ) % C1) * C0 to X % (C0 * C1), where (C0 * C1)
1180// does not overflow.
1181// Simplifies (X / C0) * C1 + (X % C0) * C2 to
1182// (X / C0) * (C1 - C2 * C0) + X * C2
1184 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1185 Value *X, *MulOpV;
1186 APInt C0, MulOpC;
1187 bool IsSigned;
1188 // Match I = X % C0 + MulOpV * C0
1189 if (((MatchRem(LHS, X, C0, IsSigned) && MatchMul(RHS, MulOpV, MulOpC)) ||
1190 (MatchRem(RHS, X, C0, IsSigned) && MatchMul(LHS, MulOpV, MulOpC))) &&
1191 C0 == MulOpC) {
1192 Value *RemOpV;
1193 APInt C1;
1194 bool Rem2IsSigned;
1195 // Match MulOpC = RemOpV % C1
1196 if (MatchRem(MulOpV, RemOpV, C1, Rem2IsSigned) &&
1197 IsSigned == Rem2IsSigned) {
1198 Value *DivOpV;
1199 APInt DivOpC;
1200 // Match RemOpV = X / C0
1201 if (MatchDiv(RemOpV, DivOpV, DivOpC, IsSigned) && X == DivOpV &&
1202 C0 == DivOpC && !MulWillOverflow(C0, C1, IsSigned)) {
1203 Value *NewDivisor = ConstantInt::get(X->getType(), C0 * C1);
1204 return IsSigned ? Builder.CreateSRem(X, NewDivisor, "srem")
1205 : Builder.CreateURem(X, NewDivisor, "urem");
1206 }
1207 }
1208 }
1209
1210 // Match I = (X / C0) * C1 + (X % C0) * C2.
1211 auto FoldDivRem = [&](Value *DivSide, Value *RemSide) -> Value * {
1212 Value *Div, *Rem;
1213 APInt C1, C2;
1214 if (!DivSide->hasOneUse() || !MatchMul(DivSide, Div, C1))
1215 Div = DivSide, C1 = APInt(I.getType()->getScalarSizeInBits(), 1);
1216 if (!RemSide->hasOneUse() || !MatchMul(RemSide, Rem, C2))
1217 Rem = RemSide, C2 = APInt(I.getType()->getScalarSizeInBits(), 1);
1218 Value *DivOpV;
1219 APInt DivOpC;
1220 if (MatchRem(Rem, X, C0, IsSigned) &&
1221 MatchDiv(Div, DivOpV, DivOpC, IsSigned) && X == DivOpV &&
1222 C0 == DivOpC &&
1223 // Avoid unprofitable replacement of and with mul.
1224 !(C1.isOne() && !IsSigned && DivOpC.isPowerOf2() && DivOpC != 2)) {
1225 APInt NewC = C1 - C2 * C0;
1226 if (!NewC.isZero() && !Rem->hasOneUse())
1227 return nullptr;
1228 if (!isGuaranteedNotToBeUndef(X, &AC, &I, &DT))
1229 return nullptr;
1230 Value *MulXC2 = Builder.CreateMul(X, ConstantInt::get(X->getType(), C2));
1231 if (NewC.isZero())
1232 return MulXC2;
1233 return Builder.CreateAdd(
1234 Builder.CreateMul(Div, ConstantInt::get(X->getType(), NewC)), MulXC2);
1235 }
1236 return nullptr;
1237 };
1238 if (Value *V = FoldDivRem(LHS, RHS))
1239 return V;
1240 if (Value *V = FoldDivRem(RHS, LHS))
1241 return V;
1242
1243 return nullptr;
1244}
1245
1246/// Fold
1247/// (1 << NBits) - 1
1248/// Into:
1249/// ~(-(1 << NBits))
1250/// Because a 'not' is better for bit-tracking analysis and other transforms
1251/// than an 'add'. The new shl is always nsw, and is nuw if old `and` was.
1253 InstCombiner::BuilderTy &Builder) {
1254 Value *NBits;
1255 if (!match(&I, m_Add(m_OneUse(m_Shl(m_One(), m_Value(NBits))), m_AllOnes())))
1256 return nullptr;
1257
1258 Constant *MinusOne = Constant::getAllOnesValue(NBits->getType());
1259 Value *NotMask = Builder.CreateShl(MinusOne, NBits, "notmask");
1260 // Be wary of constant folding.
1261 if (auto *BOp = dyn_cast<BinaryOperator>(NotMask)) {
1262 // Always NSW. But NUW propagates from `add`.
1263 BOp->setHasNoSignedWrap();
1264 BOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1265 }
1266
1267 return BinaryOperator::CreateNot(NotMask, I.getName());
1268}
1269
1271 assert(I.getOpcode() == Instruction::Add && "Expecting add instruction");
1272 Type *Ty = I.getType();
1273 auto getUAddSat = [&]() {
1274 return Intrinsic::getOrInsertDeclaration(I.getModule(), Intrinsic::uadd_sat,
1275 Ty);
1276 };
1277
1278 // add (umin X, ~Y), Y --> uaddsat X, Y
1279 Value *X, *Y;
1281 m_Deferred(Y))))
1282 return CallInst::Create(getUAddSat(), { X, Y });
1283
1284 // add (umin X, ~C), C --> uaddsat X, C
1285 const APInt *C, *NotC;
1286 if (match(&I, m_Add(m_UMin(m_Value(X), m_APInt(NotC)), m_APInt(C))) &&
1287 *C == ~*NotC)
1288 return CallInst::Create(getUAddSat(), { X, ConstantInt::get(Ty, *C) });
1289
1290 return nullptr;
1291}
1292
1293// Transform:
1294// (add A, (shl (neg B), Y))
1295// -> (sub A, (shl B, Y))
1297 const BinaryOperator &I) {
1298 Value *A, *B, *Cnt;
1299 if (match(&I,
1301 m_Value(A)))) {
1302 Value *NewShl = Builder.CreateShl(B, Cnt);
1303 return BinaryOperator::CreateSub(A, NewShl);
1304 }
1305 return nullptr;
1306}
1307
1308/// Try to reduce signed division by power-of-2 to an arithmetic shift right.
1310 // Division must be by power-of-2, but not the minimum signed value.
1311 Value *X;
1312 const APInt *DivC;
1313 if (!match(Add.getOperand(0), m_SDiv(m_Value(X), m_Power2(DivC))) ||
1314 DivC->isNegative())
1315 return nullptr;
1316
1317 // Rounding is done by adding -1 if the dividend (X) is negative and has any
1318 // low bits set. It recognizes two canonical patterns:
1319 // 1. For an 'ugt' cmp with the signed minimum value (SMIN), the
1320 // pattern is: sext (icmp ugt (X & (DivC - 1)), SMIN).
1321 // 2. For an 'eq' cmp, the pattern's: sext (icmp eq X & (SMIN + 1), SMIN + 1).
1322 // Note that, by the time we end up here, if possible, ugt has been
1323 // canonicalized into eq.
1324 const APInt *MaskC, *MaskCCmp;
1325 CmpPredicate Pred;
1326 if (!match(Add.getOperand(1),
1327 m_SExt(m_ICmp(Pred, m_And(m_Specific(X), m_APInt(MaskC)),
1328 m_APInt(MaskCCmp)))))
1329 return nullptr;
1330
1331 if ((Pred != ICmpInst::ICMP_UGT || !MaskCCmp->isSignMask()) &&
1332 (Pred != ICmpInst::ICMP_EQ || *MaskCCmp != *MaskC))
1333 return nullptr;
1334
1335 APInt SMin = APInt::getSignedMinValue(Add.getType()->getScalarSizeInBits());
1336 bool IsMaskValid = Pred == ICmpInst::ICMP_UGT
1337 ? (*MaskC == (SMin | (*DivC - 1)))
1338 : (*DivC == 2 && *MaskC == SMin + 1);
1339 if (!IsMaskValid)
1340 return nullptr;
1341
1342 // (X / DivC) + sext ((X & (SMin | (DivC - 1)) >u SMin) --> X >>s log2(DivC)
1343 return BinaryOperator::CreateAShr(
1344 X, ConstantInt::get(Add.getType(), DivC->exactLogBase2()));
1345}
1346
1348 bool NSW, bool NUW) {
1349 Value *A, *B, *C;
1350 if (match(LHS, m_Sub(m_Value(A), m_Value(B))) &&
1351 match(RHS, m_Sub(m_Value(C), m_Specific(A)))) {
1352 Instruction *R = BinaryOperator::CreateSub(C, B);
1353 bool NSWOut = NSW && match(LHS, m_NSWSub(m_Value(), m_Value())) &&
1354 match(RHS, m_NSWSub(m_Value(), m_Value()));
1355
1356 bool NUWOut = match(LHS, m_NUWSub(m_Value(), m_Value())) &&
1357 match(RHS, m_NUWSub(m_Value(), m_Value()));
1358 R->setHasNoSignedWrap(NSWOut);
1359 R->setHasNoUnsignedWrap(NUWOut);
1360 return R;
1361 }
1362
1363 // ((X s/ C1) << C2) + X => X s% -C1 where -C1 is 1 << C2
1364 const APInt *C1, *C2;
1365 if (match(LHS, m_Shl(m_SDiv(m_Specific(RHS), m_APInt(C1)), m_APInt(C2)))) {
1366 APInt One(C2->getBitWidth(), 1);
1367 APInt MinusC1 = -(*C1);
1368 if (MinusC1 == (One << *C2)) {
1369 Constant *NewRHS = ConstantInt::get(RHS->getType(), MinusC1);
1370 return BinaryOperator::CreateSRem(RHS, NewRHS);
1371 }
1372 }
1373
1374 // (A + C) + (B & ~C) == A + (B | C)
1375 if (match(LHS, m_c_Add(m_Value(A), m_APInt(C1))) &&
1376 match(RHS, m_c_And(m_Value(B), m_SpecificInt(~*C1)))) {
1377 // Replacing one add with {or, add}. Avoid growth if both sides are shared.
1378 if (!LHS->hasOneUse() && !RHS->hasOneUse())
1379 return nullptr;
1380
1381 bool NSWOut = NSW && match(LHS, m_NSWAdd(m_Value(), m_Value()));
1382 bool NUWOut = NUW && match(LHS, m_NUWAdd(m_Value(), m_Value()));
1383 Value *NewOr =
1384 Builder.CreateOr(B, Constant::getIntegerValue(LHS->getType(), *C1));
1385 Instruction *NewAdd = BinaryOperator::CreateAdd(A, NewOr);
1386 NewAdd->setHasNoSignedWrap(NSWOut);
1387 NewAdd->setHasNoUnsignedWrap(NUWOut);
1388 return NewAdd;
1389 }
1390
1391 return nullptr;
1392}
1393
1396 BinaryOperator &I) {
1397 assert((I.getOpcode() == Instruction::Add ||
1398 I.getOpcode() == Instruction::Or ||
1399 I.getOpcode() == Instruction::Sub) &&
1400 "Expecting add/or/sub instruction");
1401
1402 // We have a subtraction/addition between a (potentially truncated) *logical*
1403 // right-shift of X and a "select".
1404 Value *X, *Select;
1405 Instruction *LowBitsToSkip, *Extract;
1407 Extract, m_LShr(m_Value(X),
1408 m_Instruction(LowBitsToSkip)))),
1409 m_Value(Select))))
1410 return nullptr;
1411
1412 // `add`/`or` is commutative; but for `sub`, "select" *must* be on RHS.
1413 if (I.getOpcode() == Instruction::Sub && I.getOperand(1) != Select)
1414 return nullptr;
1415
1416 Type *XTy = X->getType();
1417 bool HadTrunc = I.getType() != XTy;
1418
1419 // If there was a truncation of extracted value, then we'll need to produce
1420 // one extra instruction, so we need to ensure one instruction will go away.
1421 if (HadTrunc && !match(&I, m_c_BinOp(m_OneUse(m_Value()), m_Value())))
1422 return nullptr;
1423
1424 // Extraction should extract high NBits bits, with shift amount calculated as:
1425 // low bits to skip = shift bitwidth - high bits to extract
1426 // The shift amount itself may be extended, and we need to look past zero-ext
1427 // when matching NBits, that will matter for matching later.
1428 Value *NBits;
1429 if (!match(LowBitsToSkip,
1431 m_ZExtOrSelf(m_Value(NBits))))))
1432 return nullptr;
1433
1434 // Sign-extending value can be zero-extended if we `sub`tract it,
1435 // or sign-extended otherwise.
1436 auto SkipExtInMagic = [&I](Value *&V) {
1437 if (I.getOpcode() == Instruction::Sub)
1438 match(V, m_ZExtOrSelf(m_Value(V)));
1439 else
1440 match(V, m_SExtOrSelf(m_Value(V)));
1441 };
1442
1443 // Now, finally validate the sign-extending magic.
1444 // `select` itself may be appropriately extended, look past that.
1445 SkipExtInMagic(Select);
1446
1447 CmpPredicate Pred;
1448 const APInt *Thr;
1449 Value *SignExtendingValue, *Zero;
1450 bool ShouldSignext;
1451 // It must be a select between two values we will later establish to be a
1452 // sign-extending value and a zero constant. The condition guarding the
1453 // sign-extension must be based on a sign bit of the same X we had in `lshr`.
1454 if (!match(Select, m_Select(m_ICmp(Pred, m_Specific(X), m_APInt(Thr)),
1455 m_Value(SignExtendingValue), m_Value(Zero))) ||
1456 !isSignBitCheck(Pred, *Thr, ShouldSignext))
1457 return nullptr;
1458
1459 // icmp-select pair is commutative.
1460 if (!ShouldSignext)
1461 std::swap(SignExtendingValue, Zero);
1462
1463 // If we should not perform sign-extension then we must add/or/subtract zero.
1464 if (!match(Zero, m_Zero()))
1465 return nullptr;
1466 // Otherwise, it should be some constant, left-shifted by the same NBits we
1467 // had in `lshr`. Said left-shift can also be appropriately extended.
1468 // Again, we must look past zero-ext when looking for NBits.
1469 SkipExtInMagic(SignExtendingValue);
1470 Constant *SignExtendingValueBaseConstant;
1471 if (!match(SignExtendingValue,
1472 m_Shl(m_Constant(SignExtendingValueBaseConstant),
1473 m_ZExtOrSelf(m_Specific(NBits)))))
1474 return nullptr;
1475 // If we `sub`, then the constant should be one, else it should be all-ones.
1476 if (I.getOpcode() == Instruction::Sub
1477 ? !match(SignExtendingValueBaseConstant, m_One())
1478 : !match(SignExtendingValueBaseConstant, m_AllOnes()))
1479 return nullptr;
1480
1481 auto *NewAShr = BinaryOperator::CreateAShr(X, LowBitsToSkip,
1482 Extract->getName() + ".sext");
1483 NewAShr->copyIRFlags(Extract); // Preserve `exact`-ness.
1484 if (!HadTrunc)
1485 return NewAShr;
1486
1487 Builder.Insert(NewAShr);
1488 return TruncInst::CreateTruncOrBitCast(NewAShr, I.getType());
1489}
1490
1491/// This is a specialization of a more general transform from
1492/// foldUsingDistributiveLaws. If that code can be made to work optimally
1493/// for multi-use cases or propagating nsw/nuw, then we would not need this.
1495 InstCombiner::BuilderTy &Builder) {
1496 // TODO: Also handle mul by doubling the shift amount?
1497 assert((I.getOpcode() == Instruction::Add ||
1498 I.getOpcode() == Instruction::Sub) &&
1499 "Expected add/sub");
1500 auto *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
1501 auto *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
1502 if (!Op0 || !Op1 || !(Op0->hasOneUse() || Op1->hasOneUse()))
1503 return nullptr;
1504
1505 Value *X, *Y, *ShAmt;
1506 if (!match(Op0, m_Shl(m_Value(X), m_Value(ShAmt))) ||
1507 !match(Op1, m_Shl(m_Value(Y), m_Specific(ShAmt))))
1508 return nullptr;
1509
1510 // No-wrap propagates only when all ops have no-wrap.
1511 bool HasNSW = I.hasNoSignedWrap() && Op0->hasNoSignedWrap() &&
1512 Op1->hasNoSignedWrap();
1513 bool HasNUW = I.hasNoUnsignedWrap() && Op0->hasNoUnsignedWrap() &&
1514 Op1->hasNoUnsignedWrap();
1515
1516 // add/sub (X << ShAmt), (Y << ShAmt) --> (add/sub X, Y) << ShAmt
1517 Value *NewMath = Builder.CreateBinOp(I.getOpcode(), X, Y);
1518 if (auto *NewI = dyn_cast<BinaryOperator>(NewMath)) {
1519 NewI->setHasNoSignedWrap(HasNSW);
1520 NewI->setHasNoUnsignedWrap(HasNUW);
1521 }
1522 auto *NewShl = BinaryOperator::CreateShl(NewMath, ShAmt);
1523 NewShl->setHasNoSignedWrap(HasNSW);
1524 NewShl->setHasNoUnsignedWrap(HasNUW);
1525 return NewShl;
1526}
1527
1528/// Reduce a sequence of masked half-width multiplies to a single multiply.
1529/// ((XLow * YHigh) + (YLow * XHigh)) << HalfBits) + (XLow * YLow) --> X * Y
1531 unsigned BitWidth = I.getType()->getScalarSizeInBits();
1532 // Skip the odd bitwidth types.
1533 if ((BitWidth & 0x1))
1534 return nullptr;
1535
1536 unsigned HalfBits = BitWidth >> 1;
1537 APInt HalfMask = APInt::getMaxValue(HalfBits);
1538
1539 // ResLo = (CrossSum << HalfBits) + (YLo * XLo)
1540 Value *XLo, *YLo;
1541 Value *CrossSum;
1542 // Require one-use on the multiply to avoid increasing the number of
1543 // multiplications.
1544 if (!match(&I, m_c_Add(m_Shl(m_Value(CrossSum), m_SpecificInt(HalfBits)),
1545 m_OneUse(m_Mul(m_Value(YLo), m_Value(XLo))))))
1546 return nullptr;
1547
1548 // XLo = X & HalfMask
1549 // YLo = Y & HalfMask
1550 // TODO: Refactor with SimplifyDemandedBits or KnownBits known leading zeros
1551 // to enhance robustness
1552 Value *X, *Y;
1553 if (!match(XLo, m_And(m_Value(X), m_SpecificInt(HalfMask))) ||
1554 !match(YLo, m_And(m_Value(Y), m_SpecificInt(HalfMask))))
1555 return nullptr;
1556
1557 // CrossSum = (X' * (Y >> Halfbits)) + (Y' * (X >> HalfBits))
1558 // X' can be either X or XLo in the pattern (and the same for Y')
1559 if (match(CrossSum,
1564 return BinaryOperator::CreateMul(X, Y);
1565
1566 return nullptr;
1567}
1568
1569/// Return true if X + (Y-1) is provably non-wrapping in X's type
1570static bool checkDivCeilNUW(Value *X, Value *Y, const SimplifyQuery &SQ) {
1571 ConstantRange CRX = computeConstantRange(X, /*ForSigned=*/false, SQ);
1572 ConstantRange CRY = computeConstantRange(Y, /*ForSigned=*/false, SQ);
1573 APInt MinY = CRY.getUnsignedMin();
1574 APInt MaxX = CRX.getUnsignedMax();
1575 APInt MaxY = CRY.getUnsignedMax();
1576
1577 return !MinY.isZero() && !MaxX.ugt(-MaxY);
1578}
1579
1580/// Fold the div_ceil idiom in both forms:
1581/// add(udiv(X, Y), zext(icmp ne(urem(X, Y), 0)))
1582/// -> udiv(add nuw(X, Y - 1), Y)
1583/// add(zext(udiv(X, Y)), zext(icmp ne(urem(X, Y), 0)))
1584/// -> zext(udiv(add nuw(X, Y - 1), Y))
1585/// The zext form applies when udiv/urem operate in a narrower type than the
1586/// add.
1588 Value *X, *Y;
1589
1590 auto UDivPat = m_OneUse(m_UDiv(m_Value(X), m_Value(Y)));
1591 auto URemPat = m_OneUse(m_URem(m_Deferred(X), m_Deferred(Y)));
1592 auto ICmpPat = m_OneUse(m_SpecificICmp(ICmpInst::ICMP_NE, URemPat, m_Zero()));
1593 auto DivPat = m_OneUse(m_ZExtOrSelf(UDivPat));
1594 auto ZExtCmpPat = m_OneUse(m_ZExt(ICmpPat));
1595
1596 if (!match(&I, m_c_Add(DivPat, ZExtCmpPat)) ||
1597 !checkDivCeilNUW(X, Y, SQ.getWithInstruction(&I)))
1598 return nullptr;
1599
1600 Value *YMinusOne =
1601 Builder.CreateAdd(Y, ConstantInt::getAllOnesValue(Y->getType()));
1602 Value *NUWAdd = Builder.CreateNUWAdd(X, YMinusOne);
1603 if (X->getType() != I.getType()) {
1604 Value *Div = Builder.CreateUDiv(NUWAdd, Y);
1605 return new ZExtInst(Div, I.getType());
1606 }
1607 return BinaryOperator::CreateUDiv(NUWAdd, Y);
1608}
1609
1611 if (Value *V = simplifyAddInst(I.getOperand(0), I.getOperand(1),
1612 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
1613 SQ.getWithInstruction(&I)))
1614 return replaceInstUsesWith(I, V);
1615
1617 return &I;
1618
1620 return X;
1621
1623 return Phi;
1624
1625 // (A*B)+(A*C) -> A*(B+C) etc
1627 return replaceInstUsesWith(I, V);
1628
1629 if (Instruction *R = foldBoxMultiply(I))
1630 return R;
1631
1633 return R;
1634
1636 return X;
1637
1639 return X;
1640
1642 return R;
1643
1645 return R;
1646
1647 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1648 if (Instruction *R = foldAddLikeCommutative(LHS, RHS, I.hasNoSignedWrap(),
1649 I.hasNoUnsignedWrap()))
1650 return R;
1651 if (Instruction *R = foldAddLikeCommutative(RHS, LHS, I.hasNoSignedWrap(),
1652 I.hasNoUnsignedWrap()))
1653 return R;
1654 Type *Ty = I.getType();
1655 if (Ty->isIntOrIntVectorTy(1))
1656 return BinaryOperator::CreateXor(LHS, RHS);
1657
1658 // X + X --> X << 1
1659 if (LHS == RHS) {
1660 auto *Shl = BinaryOperator::CreateShl(LHS, ConstantInt::get(Ty, 1));
1661 Shl->setHasNoSignedWrap(I.hasNoSignedWrap());
1662 Shl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1663 return Shl;
1664 }
1665
1666 Value *A, *B;
1667 if (match(LHS, m_Neg(m_Value(A)))) {
1668 // -A + -B --> -(A + B)
1669 if (match(RHS, m_Neg(m_Value(B))))
1670 return BinaryOperator::CreateNeg(Builder.CreateAdd(A, B));
1671
1672 // -A + B --> B - A
1673 auto *Sub = BinaryOperator::CreateSub(RHS, A);
1674 auto *OB0 = cast<OverflowingBinaryOperator>(LHS);
1675 Sub->setHasNoSignedWrap(I.hasNoSignedWrap() && OB0->hasNoSignedWrap());
1676
1677 return Sub;
1678 }
1679
1680 // A + -B --> A - B
1681 if (match(RHS, m_Neg(m_Value(B)))) {
1682 auto *Sub = BinaryOperator::CreateSub(LHS, B);
1683 auto *OBO = cast<OverflowingBinaryOperator>(RHS);
1684 Sub->setHasNoSignedWrap(I.hasNoSignedWrap() && OBO->hasNoSignedWrap());
1685 return Sub;
1686 }
1687
1689 return replaceInstUsesWith(I, V);
1690
1691 // (A + 1) + ~B --> A - B
1692 // ~B + (A + 1) --> A - B
1693 // (~B + A) + 1 --> A - B
1694 // (A + ~B) + 1 --> A - B
1695 // This relies on the ~B == -1-B identity.
1696 if (match(&I, m_c_BinOp(m_Add(m_Value(A), m_One()), m_Not(m_Value(B)))) ||
1698 return BinaryOperator::CreateSub(A, B);
1699
1700 {
1701 // (A + C) + ~B --> A - B + (C-1)
1702 // ~B + (A + C) --> A - B + (C-1)
1703 // (~B + A) + C --> A - B + (C-1)
1704 // (A + ~B) + C --> A - B + (C-1)
1705 // With constant C, subtraction of one is free, so we replace three ops
1706 // (two adds and a bitwise-not) with two (sub and add).
1707 const APInt *C;
1709 m_Not(m_Value(B)))) ||
1711 m_APIntAllowPoison(C)))) {
1712 Value *Sub = Builder.CreateSub(A, B);
1713 return BinaryOperator::CreateAdd(Sub, ConstantInt::get(Ty, *C - 1));
1714 }
1715 }
1716
1717 // (A + RHS) + RHS --> A + (RHS << 1)
1718 if (match(LHS, m_OneUse(m_c_Add(m_Value(A), m_Specific(RHS)))))
1719 return BinaryOperator::CreateAdd(A, Builder.CreateShl(RHS, 1, "reass.add"));
1720
1721 // LHS + (A + LHS) --> A + (LHS << 1)
1722 if (match(RHS, m_OneUse(m_c_Add(m_Value(A), m_Specific(LHS)))))
1723 return BinaryOperator::CreateAdd(A, Builder.CreateShl(LHS, 1, "reass.add"));
1724
1725 {
1726 // (A + C1) + (C2 - B) --> (A - B) + (C1 + C2)
1727 Constant *C1, *C2;
1728 if (match(&I, m_c_Add(m_Add(m_Value(A), m_ImmConstant(C1)),
1729 m_Sub(m_ImmConstant(C2), m_Value(B)))) &&
1730 (LHS->hasOneUse() || RHS->hasOneUse())) {
1731 Value *Sub = Builder.CreateSub(A, B);
1732 return BinaryOperator::CreateAdd(Sub, ConstantExpr::getAdd(C1, C2));
1733 }
1734
1735 // Canonicalize a constant sub operand as an add operand for better folding:
1736 // (C1 - A) + B --> (B - A) + C1
1738 m_Value(B)))) {
1739 Value *Sub = Builder.CreateSub(B, A, "reass.sub");
1740 return BinaryOperator::CreateAdd(Sub, C1);
1741 }
1742 }
1743
1744 // X % C0 + (( X / C0 ) % C1) * C0 => X % (C0 * C1)
1746
1747 const APInt *C1;
1748 // (A & 2^C1) + A => A & (2^C1 - 1) iff bit C1 in A is a sign bit
1749 if (match(&I, m_c_Add(m_And(m_Value(A), m_APInt(C1)), m_Deferred(A))) &&
1750 C1->isPowerOf2() && (ComputeNumSignBits(A) > C1->countl_zero())) {
1751 Constant *NewMask = ConstantInt::get(RHS->getType(), *C1 - 1);
1752 return BinaryOperator::CreateAnd(A, NewMask);
1753 }
1754
1755 // ZExt (B - A) + ZExt(A) --> ZExt(B)
1756 if ((match(RHS, m_ZExt(m_Value(A))) &&
1757 match(LHS, m_ZExt(m_NUWSub(m_Value(B), m_Specific(A))))) ||
1758 (match(LHS, m_ZExt(m_Value(A))) &&
1760 return new ZExtInst(B, LHS->getType());
1761
1762 // zext(A) + sext(A) --> 0 if A is i1
1764 A->getType()->isIntOrIntVectorTy(1))
1765 return replaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1766
1767 // sext(A < B) + zext(A > B) => ucmp/scmp(A, B)
1768 CmpPredicate LTPred, GTPred;
1769 if (match(&I,
1770 m_c_Add(m_SExt(m_c_ICmp(LTPred, m_Value(A), m_Value(B))),
1771 m_ZExt(m_c_ICmp(GTPred, m_Deferred(A), m_Deferred(B))))) &&
1772 A->getType()->isIntOrIntVectorTy()) {
1773 if (ICmpInst::isGT(LTPred)) {
1774 std::swap(LTPred, GTPred);
1775 std::swap(A, B);
1776 }
1777
1778 if (ICmpInst::isLT(LTPred) && ICmpInst::isGT(GTPred) &&
1779 ICmpInst::isSigned(LTPred) == ICmpInst::isSigned(GTPred))
1780 return replaceInstUsesWith(
1781 I, Builder.CreateIntrinsic(
1782 Ty,
1783 ICmpInst::isSigned(LTPred) ? Intrinsic::scmp : Intrinsic::ucmp,
1784 {A, B}));
1785 }
1786
1787 // A+B --> A|B iff A and B have no bits set in common.
1788 WithCache<const Value *> LHSCache(LHS), RHSCache(RHS);
1789 switch (
1790 getNoCommonBitsSetResult(LHSCache, RHSCache, SQ.getWithInstruction(&I))) {
1792 return BinaryOperator::CreateDisjointOr(LHS, RHS);
1794 return BinaryOperator::CreateOr(LHS, RHS);
1796 break;
1797 }
1798
1799 if (Instruction *Ext = narrowMathIfNoOverflow(I))
1800 return Ext;
1801
1802 // (add (xor A, B) (and A, B)) --> (or A, B)
1803 // (add (and A, B) (xor A, B)) --> (or A, B)
1804 if (match(&I, m_c_BinOp(m_Xor(m_Value(A), m_Value(B)),
1806 return BinaryOperator::CreateOr(A, B);
1807
1808 // (add (or A, B) (and A, B)) --> (add A, B)
1809 // (add (and A, B) (or A, B)) --> (add A, B)
1810 if (match(&I, m_c_BinOp(m_Or(m_Value(A), m_Value(B)),
1812 // Replacing operands in-place to preserve nuw/nsw flags.
1813 replaceOperand(I, 0, A);
1814 replaceOperand(I, 1, B);
1815 return &I;
1816 }
1817
1818 // (add A (or A, -A)) --> (and (add A, -1) A)
1819 // (add A (or -A, A)) --> (and (add A, -1) A)
1820 // (add (or A, -A) A) --> (and (add A, -1) A)
1821 // (add (or -A, A) A) --> (and (add A, -1) A)
1823 m_Deferred(A)))))) {
1824 Value *Add =
1825 Builder.CreateAdd(A, Constant::getAllOnesValue(A->getType()), "",
1826 I.hasNoUnsignedWrap(), I.hasNoSignedWrap());
1827 return BinaryOperator::CreateAnd(Add, A);
1828 }
1829
1830 // Align-up idiom:
1831 // X + ((-X) & (C - 1)) --> (X + C - 1) & -C
1832 // ((X - 1) | (C - 1)) + 1 -> (X + C - 1) & -C
1833 // For a power-of-two C. Note -C == ~(C - 1), so the mask is simply the
1834 // inverted low-bit mask.
1835 {
1836 const APInt *LowMask;
1837 if (match(&I,
1839 m_Deferred(A))) ||
1841 m_LowBitMask(LowMask))),
1842 m_One()))
1843
1844 ) {
1845 Value *NewAdd = Builder.CreateAdd(A, ConstantInt::get(Ty, *LowMask));
1846 return BinaryOperator::CreateAnd(NewAdd, ConstantInt::get(Ty, ~*LowMask));
1847 }
1848 }
1849
1850 // Canonicalize ((A & -A) - 1) --> ((A - 1) & ~A)
1851 // Forms all commutable operations, and simplifies ctpop -> cttz folds.
1852 if (match(&I,
1854 m_AllOnes()))) {
1856 Value *Dec = Builder.CreateAdd(A, AllOnes);
1857 Value *Not = Builder.CreateXor(A, AllOnes);
1858 return BinaryOperator::CreateAnd(Dec, Not);
1859 }
1860
1861 // Disguised reassociation/factorization:
1862 // ~(A * C1) + A
1863 // ((A * -C1) - 1) + A
1864 // ((A * -C1) + A) - 1
1865 // (A * (1 - C1)) - 1
1866 if (match(&I,
1868 m_Deferred(A)))) {
1869 Type *Ty = I.getType();
1870 Constant *NewMulC = ConstantInt::get(Ty, 1 - *C1);
1871 Value *NewMul = Builder.CreateMul(A, NewMulC);
1872 return BinaryOperator::CreateAdd(NewMul, ConstantInt::getAllOnesValue(Ty));
1873 }
1874
1875 // (A * -2**C) + B --> B - (A << C)
1876 const APInt *NegPow2C;
1877 if (match(&I, m_c_Add(m_OneUse(m_Mul(m_Value(A), m_NegatedPower2(NegPow2C))),
1878 m_Value(B)))) {
1879 Constant *ShiftAmtC = ConstantInt::get(Ty, NegPow2C->countr_zero());
1880 Value *Shl = Builder.CreateShl(A, ShiftAmtC);
1881 return BinaryOperator::CreateSub(B, Shl);
1882 }
1883
1884 // Canonicalize signum variant that ends in add:
1885 // (A s>> (BW - 1)) + (zext (A s> 0)) --> (A s>> (BW - 1)) | (zext (A != 0))
1886 uint64_t BitWidth = Ty->getScalarSizeInBits();
1890 Value *NotZero = Builder.CreateIsNotNull(A, "isnotnull");
1891 Value *Zext = Builder.CreateZExt(NotZero, Ty, "isnotnull.zext");
1892 return BinaryOperator::CreateOr(LHS, Zext);
1893 }
1894
1895 {
1896 Value *Cond, *Ext;
1897 Constant *C;
1898 // (add X, (sext/zext (icmp eq X, C)))
1899 // -> (select (icmp eq X, C), (add C, (sext/zext 1)), X)
1900 auto CondMatcher =
1902 m_ImmConstant(C)));
1903
1904 if (match(&I,
1905 m_c_Add(m_Value(A), m_Value(Ext, m_ZExtOrSExt(CondMatcher)))) &&
1906 Ext->hasOneUse()) {
1909 return replaceInstUsesWith(I, Builder.CreateSelect(Cond, Add, A));
1910 }
1911 }
1912
1913 // (add (add A, 1), (sext (icmp ne A, 0))) => call umax(A, 1)
1914 if (match(LHS, m_Add(m_Value(A), m_One())) &&
1917 Value *OneConst = ConstantInt::get(A->getType(), 1);
1918 Value *UMax = Builder.CreateBinaryIntrinsic(Intrinsic::umax, A, OneConst);
1919 return replaceInstUsesWith(I, UMax);
1920 }
1921
1922 if (Instruction *Ashr = foldAddToAshr(I))
1923 return Ashr;
1924
1925 // Ceiling division by power-of-2:
1926 // (X >> log2(N)) + zext(X & (N-1) != 0) --> (X + (N-1)) >> log2(N)
1927 // This is valid when adding (N-1) to X doesn't overflow.
1928 {
1929 Value *X;
1930 const APInt *ShiftAmt, *Mask;
1931 CmpPredicate Pred;
1932
1933 // Match: (X >> C) + zext((X & Mask) != 0)
1934 // or: zext((X & Mask) != 0) + (X >> C)
1935 if (match(&I,
1938 m_And(m_Value(X), m_LowBitMask(Mask)), m_ZeroInt())),
1940 m_LShr(m_Deferred(X), m_APInt(ShiftAmt))))))) &&
1941 Mask->popcount() == *ShiftAmt) {
1942
1943 // Check if X + Mask doesn't overflow
1944 unsigned Xbits = X->getType()->getScalarSizeInBits();
1945 unsigned Ibits = Ty->getScalarSizeInBits();
1946 bool NeedZext = Ibits > Xbits;
1947 Constant *MaskC = ConstantInt::get(Ty, Mask->zext(Ibits));
1948 if (NeedZext || willNotOverflowUnsignedAdd(X, MaskC, I)) {
1949 if (NeedZext)
1950 X = Builder.CreateZExt(X, Ty);
1951 // (X + Mask) >> ShiftAmt
1952 Value *Add = Builder.CreateNUWAdd(X, MaskC);
1953 return BinaryOperator::CreateLShr(
1954 Add, ConstantInt::get(Ty, ShiftAmt->zext(Ibits)));
1955 }
1956 }
1957 }
1958
1959 // (~X) + (~Y) --> -2 - (X + Y)
1960 {
1961 // To ensure we can save instructions we need to ensure that we consume both
1962 // LHS/RHS (i.e they have a `not`).
1963 bool ConsumesLHS, ConsumesRHS;
1964 if (isFreeToInvert(LHS, LHS->hasOneUse(), ConsumesLHS) && ConsumesLHS &&
1965 isFreeToInvert(RHS, RHS->hasOneUse(), ConsumesRHS) && ConsumesRHS) {
1966 Value *NotLHS = getFreelyInverted(LHS, LHS->hasOneUse(), &Builder);
1967 Value *NotRHS = getFreelyInverted(RHS, RHS->hasOneUse(), &Builder);
1968 assert(NotLHS != nullptr && NotRHS != nullptr &&
1969 "isFreeToInvert desynced with getFreelyInverted");
1970 Value *LHSPlusRHS = Builder.CreateAdd(NotLHS, NotRHS);
1971 return BinaryOperator::CreateSub(
1972 ConstantInt::getSigned(RHS->getType(), -2), LHSPlusRHS);
1973 }
1974 }
1975
1977 return R;
1978
1979 // TODO(jingyue): Consider willNotOverflowSignedAdd and
1980 // willNotOverflowUnsignedAdd to reduce the number of invocations of
1981 // computeKnownBits.
1982 bool Changed = false;
1983 if (!I.hasNoSignedWrap() && willNotOverflowSignedAdd(LHSCache, RHSCache, I)) {
1984 Changed = true;
1985 I.setHasNoSignedWrap(true);
1986 }
1987 if (!I.hasNoUnsignedWrap() &&
1988 willNotOverflowUnsignedAdd(LHSCache, RHSCache, I)) {
1989 Changed = true;
1990 I.setHasNoUnsignedWrap(true);
1991 }
1992
1994 return V;
1995
1996 if (Instruction *V =
1998 return V;
1999
2001 return SatAdd;
2002
2003 // usub.sat(A, B) + B => umax(A, B)
2004 if (match(&I, m_c_BinOp(
2006 m_Deferred(B)))) {
2007 return replaceInstUsesWith(I,
2008 Builder.CreateIntrinsic(Intrinsic::umax, {I.getType()}, {A, B}));
2009 }
2010
2011 // ctpop(A) + ctpop(B) => ctpop(A | B) if A and B have no bits set in common.
2012 if (match(LHS, m_OneUse(m_Ctpop(m_Value(A)))) &&
2013 match(RHS, m_OneUse(m_Ctpop(m_Value(B)))) &&
2014 haveNoCommonBitsSet(A, B, SQ.getWithInstruction(&I)))
2015 return replaceInstUsesWith(
2016 I, Builder.CreateIntrinsic(Intrinsic::ctpop, {I.getType()},
2017 {Builder.CreateDisjointOr(A, B)}));
2018
2019 // Fold the log2_ceil idiom:
2020 // zext(ctpop(A) >u/!= 1) + (ctlz(A, true) ^ (BW - 1))
2021 // -->
2022 // BW - ctlz(A - 1, false)
2023 const APInt *XorC;
2024 CmpPredicate Pred;
2025 if (match(&I, m_c_Add(m_ZExt(m_ICmp(Pred, m_Ctpop(m_Value(A)), m_One())),
2028 m_Ctlz(m_Deferred(A), m_One())))),
2029 m_APInt(XorC))))))) &&
2030 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_NE) &&
2031 *XorC == A->getType()->getScalarSizeInBits() - 1) {
2032 Value *Sub = Builder.CreateAdd(A, Constant::getAllOnesValue(A->getType()));
2033 Value *Ctlz = Builder.CreateIntrinsic(Intrinsic::ctlz, {A->getType()},
2034 {Sub, Builder.getFalse()});
2035 Value *Ret = Builder.CreateSub(
2036 ConstantInt::get(A->getType(), A->getType()->getScalarSizeInBits()),
2037 Ctlz, "", /*HasNUW=*/true, /*HasNSW=*/true);
2038 return replaceInstUsesWith(I, Builder.CreateZExtOrTrunc(Ret, I.getType()));
2039 }
2040
2041 if (Instruction *Res = foldSquareSumInt(I))
2042 return Res;
2043
2044 if (Instruction *Res = foldBinOpOfDisplacedShifts(I))
2045 return Res;
2046
2048 return Res;
2049
2050 if (Instruction *Res = foldDivCeil(I))
2051 return Res;
2052
2053 // (A | -2) + A -> (A - 1) & -2
2054 APInt NegTwo(Ty->getScalarSizeInBits(), -2, /*isSigned=*/true);
2055 if (match(&I, m_c_BinOp(m_OneUse(m_Or(m_Value(A), m_SpecificInt(NegTwo))),
2056 m_Deferred(A)))) {
2057 Value *Ret = Builder.CreateAdd(
2058 A, ConstantInt::get(
2059 Ty, APInt(Ty->getScalarSizeInBits(), -1, /*isSigned=*/true)));
2060 return BinaryOperator::CreateAnd(Ret, ConstantInt::get(Ty, NegTwo));
2061 }
2062
2063 // Re-enqueue users of the induction variable of add recurrence if we infer
2064 // new nuw/nsw flags.
2065 if (Changed) {
2066 PHINode *PHI;
2067 Value *Start, *Step;
2068 if (matchSimpleRecurrence(&I, PHI, Start, Step))
2069 Worklist.pushUsersToWorkList(*PHI);
2070 }
2071
2072 return Changed ? &I : nullptr;
2073}
2074
2075/// Eliminate an op from a linear interpolation (lerp) pattern.
2077 InstCombiner::BuilderTy &Builder) {
2078 Value *X, *Y, *Z;
2081 m_Value(Z))))),
2083 return nullptr;
2084
2085 // (Y * (1.0 - Z)) + (X * Z) --> Y + Z * (X - Y) [8 commuted variants]
2086 Value *XY = Builder.CreateFSubFMF(X, Y, &I);
2087 Value *MulZ = Builder.CreateFMulFMF(Z, XY, &I);
2088 return BinaryOperator::CreateFAddFMF(Y, MulZ, &I);
2089}
2090
2091/// Factor a common operand out of fadd/fsub of fmul/fdiv.
2093 InstCombiner::BuilderTy &Builder) {
2094 assert((I.getOpcode() == Instruction::FAdd ||
2095 I.getOpcode() == Instruction::FSub) && "Expecting fadd/fsub");
2096 assert(I.hasAllowReassoc() && I.hasNoSignedZeros() &&
2097 "FP factorization requires FMF");
2098
2099 if (Instruction *Lerp = factorizeLerp(I, Builder))
2100 return Lerp;
2101
2102 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2103 if (!Op0->hasOneUse() || !Op1->hasOneUse())
2104 return nullptr;
2105
2106 Value *X, *Y, *Z;
2107 bool IsFMul;
2108 if ((match(Op0, m_FMul(m_Value(X), m_Value(Z))) &&
2109 match(Op1, m_c_FMul(m_Value(Y), m_Specific(Z)))) ||
2110 (match(Op0, m_FMul(m_Value(Z), m_Value(X))) &&
2111 match(Op1, m_c_FMul(m_Value(Y), m_Specific(Z)))))
2112 IsFMul = true;
2113 else if (match(Op0, m_FDiv(m_Value(X), m_Value(Z))) &&
2114 match(Op1, m_FDiv(m_Value(Y), m_Specific(Z))))
2115 IsFMul = false;
2116 else
2117 return nullptr;
2118
2119 // (X * Z) + (Y * Z) --> (X + Y) * Z
2120 // (X * Z) - (Y * Z) --> (X - Y) * Z
2121 // (X / Z) + (Y / Z) --> (X + Y) / Z
2122 // (X / Z) - (Y / Z) --> (X - Y) / Z
2123 bool IsFAdd = I.getOpcode() == Instruction::FAdd;
2124 Value *XY = IsFAdd ? Builder.CreateFAddFMF(X, Y, &I)
2125 : Builder.CreateFSubFMF(X, Y, &I);
2126
2127 // Bail out if we just created a denormal constant.
2128 // TODO: This is copied from a previous implementation. Is it necessary?
2129 const APFloat *C;
2130 if (match(XY, m_APFloat(C)) && !C->isNormal())
2131 return nullptr;
2132
2133 return IsFMul ? BinaryOperator::CreateFMulFMF(XY, Z, &I)
2135}
2136
2138 if (Value *V = simplifyFAddInst(I.getOperand(0), I.getOperand(1),
2139 I.getFastMathFlags(),
2140 SQ.getWithInstruction(&I)))
2141 return replaceInstUsesWith(I, V);
2142
2144 return &I;
2145
2147 return X;
2148
2150 return Phi;
2151
2152 if (Instruction *FoldedFAdd = foldBinOpIntoSelectOrPhi(I))
2153 return FoldedFAdd;
2154
2155 // B = fadd A, 0.0
2156 // Z = Op B
2157 // can be transformed into
2158 // Z = Op A
2159 // Where Op is such that we can ignore sign of 0 in fadd
2160 Value *A;
2161 if (match(&I, m_OneUse(m_FAdd(m_Value(A), m_AnyZeroFP()))) &&
2162 canIgnoreSignBitOfZero(*I.use_begin()))
2163 return replaceInstUsesWith(I, A);
2164
2165 // (-X) + Y --> Y - X
2166 Value *X, *Y;
2167 if (match(&I, m_c_FAdd(m_FNeg(m_Value(X)), m_Value(Y))))
2169
2170 // Similar to above, but look through fmul/fdiv for the negated term.
2171 // (-X * Y) + Z --> Z - (X * Y) [4 commuted variants]
2172 Value *Z;
2174 m_Value(Z)))) {
2175 Value *XY = Builder.CreateFMulFMF(X, Y, &I);
2176 return BinaryOperator::CreateFSubFMF(Z, XY, &I);
2177 }
2178 // (-X / Y) + Z --> Z - (X / Y) [2 commuted variants]
2179 // (X / -Y) + Z --> Z - (X / Y) [2 commuted variants]
2181 m_Value(Z))) ||
2183 m_Value(Z)))) {
2184 Value *XY = Builder.CreateFDivFMF(X, Y, &I);
2185 return BinaryOperator::CreateFSubFMF(Z, XY, &I);
2186 }
2187
2188 // Check for (fadd double (sitofp x), y), see if we can merge this into an
2189 // integer add followed by a promotion.
2190 if (Instruction *R = foldFBinOpOfIntCasts(I))
2191 return R;
2192
2193 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2194 // Handle specials cases for FAdd with selects feeding the operation
2195 if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS, RHS))
2196 return replaceInstUsesWith(I, V);
2197
2198 if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
2200 return F;
2201
2203 return F;
2204
2205 // Try to fold fadd into start value of reduction intrinsic.
2207 m_AnyZeroFP(), m_Value(X))),
2208 m_Value(Y)))) {
2209 // fadd (rdx 0.0, X), Y --> rdx Y, X
2210 return replaceInstUsesWith(
2211 I, Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
2212 {X->getType()}, {Y, X}, &I));
2213 }
2214 const APFloat *StartC, *C;
2216 m_APFloat(StartC), m_Value(X)))) &&
2217 match(RHS, m_APFloat(C))) {
2218 // fadd (rdx StartC, X), C --> rdx (C + StartC), X
2219 Constant *NewStartC = ConstantFP::get(I.getType(), *C + *StartC);
2220 return replaceInstUsesWith(
2221 I, Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
2222 {X->getType()}, {NewStartC, X}, &I));
2223 }
2224
2225 // (X * MulC) + X --> X * (MulC + 1.0)
2226 Constant *MulC;
2227 if (match(&I, m_c_FAdd(m_FMul(m_Value(X), m_ImmConstant(MulC)),
2228 m_Deferred(X)))) {
2230 Instruction::FAdd, MulC, ConstantFP::get(I.getType(), 1.0), DL))
2231 return BinaryOperator::CreateFMulFMF(X, NewMulC, &I);
2232 }
2233
2234 // (-X - Y) + (X + Z) --> Z - Y
2236 m_c_FAdd(m_Deferred(X), m_Value(Z)))))
2237 return BinaryOperator::CreateFSubFMF(Z, Y, &I);
2238
2239 if (Value *V = FAddCombine(Builder).simplify(&I))
2240 return replaceInstUsesWith(I, V);
2241 }
2242
2243 // minumum(X, Y) + maximum(X, Y) => X + Y.
2244 if (match(&I,
2247 m_Deferred(Y))))) {
2249 // We cannot preserve ninf if nnan flag is not set.
2250 // If X is NaN and Y is Inf then in original program we had NaN + NaN,
2251 // while in optimized version NaN + Inf and this is a poison with ninf flag.
2252 if (!Result->hasNoNaNs())
2253 Result->setHasNoInfs(false);
2254 return Result;
2255 }
2256
2257 return nullptr;
2258}
2259
2262
2263 if (LHS->getType() != RHS->getType())
2264 return Base;
2265
2266 // Collect all base pointers of LHS.
2268 Value *Ptr = LHS;
2269 while (true) {
2270 Ptrs.insert(Ptr);
2271 if (auto *GEP = dyn_cast<GEPOperator>(Ptr))
2272 Ptr = GEP->getPointerOperand();
2273 else
2274 break;
2275 }
2276
2277 // Find common base and collect RHS GEPs.
2278 bool First = true;
2279 while (true) {
2280 if (Ptrs.contains(RHS)) {
2281 Base.Ptr = RHS;
2282 break;
2283 }
2284
2285 if (auto *GEP = dyn_cast<GEPOperator>(RHS)) {
2286 Base.RHSGEPs.push_back(GEP);
2287 if (First) {
2288 First = false;
2289 Base.RHSNW = GEP->getNoWrapFlags();
2290 } else {
2291 Base.RHSNW = Base.RHSNW.intersectForOffsetAdd(GEP->getNoWrapFlags());
2292 }
2293 RHS = GEP->getPointerOperand();
2294 } else {
2295 // No common base.
2296 return Base;
2297 }
2298 }
2299
2300 // Collect LHS GEPs.
2301 First = true;
2302 while (true) {
2303 if (LHS == Base.Ptr)
2304 break;
2305
2306 auto *GEP = cast<GEPOperator>(LHS);
2307 Base.LHSGEPs.push_back(GEP);
2308 if (First) {
2309 First = false;
2310 Base.LHSNW = GEP->getNoWrapFlags();
2311 } else {
2312 Base.LHSNW = Base.LHSNW.intersectForOffsetAdd(GEP->getNoWrapFlags());
2313 }
2314 LHS = GEP->getPointerOperand();
2315 }
2316
2317 return Base;
2318}
2319
2321 unsigned NumGEPs = 0;
2322 auto ProcessGEPs = [&NumGEPs](ArrayRef<GEPOperator *> GEPs) {
2323 bool SeenMultiUse = false;
2324 for (GEPOperator *GEP : GEPs) {
2325 // Only count multi-use GEPs, excluding the first one. For the first one,
2326 // we will directly reuse the offset. For one-use GEPs, their offset will
2327 // be folded into a multi-use GEP.
2328 if (!GEP->hasOneUse()) {
2329 if (SeenMultiUse)
2330 ++NumGEPs;
2331 SeenMultiUse = true;
2332 }
2333 }
2334 };
2335 ProcessGEPs(LHSGEPs);
2336 ProcessGEPs(RHSGEPs);
2337 return NumGEPs > 2;
2338}
2339
2340/// Optimize pointer differences into the same array into a size. Consider:
2341/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2342/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2344 Type *Ty, bool IsNUW) {
2346 if (!Base.Ptr || Base.isExpensive())
2347 return nullptr;
2348
2349 // To avoid duplicating the offset arithmetic, rewrite the GEP to use the
2350 // computed offset.
2351 // TODO: We should probably do this even if there is only one GEP.
2352 bool RewriteGEPs = !Base.LHSGEPs.empty() && !Base.RHSGEPs.empty();
2353
2354 Type *IdxTy = DL.getIndexType(LHS->getType());
2355 Value *Result = EmitGEPOffsets(Base.LHSGEPs, Base.LHSNW, IdxTy, RewriteGEPs);
2356 Value *Offset2 = EmitGEPOffsets(Base.RHSGEPs, Base.RHSNW, IdxTy, RewriteGEPs);
2357
2358 // If this is a single inbounds GEP and the original sub was nuw,
2359 // then the final multiplication is also nuw.
2360 if (auto *I = dyn_cast<OverflowingBinaryOperator>(Result))
2361 if (IsNUW && match(Offset2, m_Zero()) && Base.LHSNW.isInBounds() &&
2362 (I->use_empty() || I->hasOneUse()) && I->hasNoSignedWrap() &&
2363 !I->hasNoUnsignedWrap() &&
2364 ((I->getOpcode() == Instruction::Mul &&
2365 match(I->getOperand(1), m_NonNegative())) ||
2366 I->getOpcode() == Instruction::Shl))
2367 cast<Instruction>(I)->setHasNoUnsignedWrap();
2368
2369 // If we have a 2nd GEP of the same base pointer, subtract the offsets.
2370 // If both GEPs are inbounds, then the subtract does not have signed overflow.
2371 // If both GEPs are nuw and the original sub is nuw, the new sub is also nuw.
2372 if (!match(Offset2, m_Zero())) {
2373 Result =
2374 Builder.CreateSub(Result, Offset2, "gepdiff",
2375 IsNUW && Base.LHSNW.hasNoUnsignedWrap() &&
2376 Base.RHSNW.hasNoUnsignedWrap(),
2377 Base.LHSNW.isInBounds() && Base.RHSNW.isInBounds());
2378 }
2379
2380 return Builder.CreateIntCast(Result, Ty, true);
2381}
2382
2384 InstCombiner::BuilderTy &Builder) {
2385 Value *Op0 = I.getOperand(0);
2386 Value *Op1 = I.getOperand(1);
2387 Type *Ty = I.getType();
2388 auto *MinMax = dyn_cast<MinMaxIntrinsic>(Op1);
2389 if (!MinMax)
2390 return nullptr;
2391
2392 // sub(add(X,Y), s/umin(X,Y)) --> s/umax(X,Y)
2393 // sub(add(X,Y), s/umax(X,Y)) --> s/umin(X,Y)
2394 Value *X = MinMax->getLHS();
2395 Value *Y = MinMax->getRHS();
2396 if (match(Op0, m_c_Add(m_Specific(X), m_Specific(Y))) &&
2397 (Op0->hasOneUse() || Op1->hasOneUse())) {
2398 Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMax->getIntrinsicID());
2399 Function *F = Intrinsic::getOrInsertDeclaration(I.getModule(), InvID, Ty);
2400 return CallInst::Create(F, {X, Y});
2401 }
2402
2403 // sub(add(X,Y),umin(Y,Z)) --> add(X,usub.sat(Y,Z))
2404 // sub(add(X,Z),umin(Y,Z)) --> add(X,usub.sat(Z,Y))
2405 Value *Z;
2406 if (match(Op1, m_OneUse(m_UMin(m_Value(Y), m_Value(Z))))) {
2407 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Y), m_Value(X))))) {
2408 Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, Ty, {Y, Z});
2409 return BinaryOperator::CreateAdd(X, USub);
2410 }
2411 if (match(Op0, m_OneUse(m_c_Add(m_Specific(Z), m_Value(X))))) {
2412 Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, Ty, {Z, Y});
2413 return BinaryOperator::CreateAdd(X, USub);
2414 }
2415 }
2416
2417 // sub Op0, smin((sub nsw Op0, Z), 0) --> smax Op0, Z
2418 // sub Op0, smax((sub nsw Op0, Z), 0) --> smin Op0, Z
2419 if (MinMax->isSigned() && match(Y, m_ZeroInt()) &&
2420 match(X, m_NSWSub(m_Specific(Op0), m_Value(Z)))) {
2421 Intrinsic::ID InvID = getInverseMinMaxIntrinsic(MinMax->getIntrinsicID());
2422 Function *F = Intrinsic::getOrInsertDeclaration(I.getModule(), InvID, Ty);
2423 return CallInst::Create(F, {Op0, Z});
2424 }
2425
2426 return nullptr;
2427}
2428
2430 if (Value *V = simplifySubInst(I.getOperand(0), I.getOperand(1),
2431 I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
2432 SQ.getWithInstruction(&I)))
2433 return replaceInstUsesWith(I, V);
2434
2436 return X;
2437
2439 return Phi;
2440
2441 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2442
2443 // If this is a 'B = x-(-A)', change to B = x+A.
2444 // We deal with this without involving Negator to preserve NSW flag.
2445 if (Value *V = dyn_castNegVal(Op1)) {
2446 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
2447
2448 if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
2449 assert(BO->getOpcode() == Instruction::Sub &&
2450 "Expected a subtraction operator!");
2451 if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
2452 Res->setHasNoSignedWrap(true);
2453 } else {
2454 if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
2455 Res->setHasNoSignedWrap(true);
2456 }
2457
2458 return Res;
2459 }
2460
2461 // Try this before Negator to preserve NSW flag.
2463 return R;
2464
2465 Constant *C;
2466 if (match(Op0, m_ImmConstant(C))) {
2467 Value *X;
2468 Constant *C2;
2469
2470 // C-(X+C2) --> (C-C2)-X
2471 if (match(Op1, m_AddLike(m_Value(X), m_ImmConstant(C2)))) {
2472 // C-C2 never overflow, and C-(X+C2), (X+C2) has NSW/NUW
2473 // => (C-C2)-X can have NSW/NUW
2474 bool WillNotSOV = willNotOverflowSignedSub(C, C2, I);
2475 BinaryOperator *Res =
2476 BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
2477
2478 // or disjoint is equivalent to add nuw nsw.
2479 bool Op1NSW = true;
2480 bool Op1NUW = true;
2481
2482 if (auto *OBO1 = dyn_cast<OverflowingBinaryOperator>(Op1)) {
2483 Op1NSW = OBO1->hasNoSignedWrap();
2484 Op1NUW = OBO1->hasNoUnsignedWrap();
2485 }
2486
2487 Res->setHasNoSignedWrap(I.hasNoSignedWrap() && Op1NSW && WillNotSOV);
2488 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap() && Op1NUW);
2489 return Res;
2490 }
2491 }
2492
2493 auto TryToNarrowDeduceFlags = [this, &I, &Op0, &Op1]() -> Instruction * {
2494 if (Instruction *Ext = narrowMathIfNoOverflow(I))
2495 return Ext;
2496
2497 bool Changed = false;
2498 if (!I.hasNoSignedWrap() && willNotOverflowSignedSub(Op0, Op1, I)) {
2499 Changed = true;
2500 I.setHasNoSignedWrap(true);
2501 }
2502 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedSub(Op0, Op1, I)) {
2503 Changed = true;
2504 I.setHasNoUnsignedWrap(true);
2505 }
2506
2507 return Changed ? &I : nullptr;
2508 };
2509
2510 // First, let's try to interpret `sub a, b` as `add a, (sub 0, b)`,
2511 // and let's try to sink `(sub 0, b)` into `b` itself. But only if this isn't
2512 // a pure negation used by a select that looks like abs/nabs.
2513 bool IsNegation = match(Op0, m_ZeroInt());
2514 if (!IsNegation || none_of(I.users(), match_fn(m_c_Select(m_Specific(Op1),
2515 m_Specific(&I))))) {
2516 if (Value *NegOp1 = Negator::Negate(IsNegation, /* IsNSW */ IsNegation &&
2517 I.hasNoSignedWrap(),
2518 Op1, *this))
2519 return BinaryOperator::CreateAdd(NegOp1, Op0);
2520 }
2521 if (IsNegation)
2522 return TryToNarrowDeduceFlags(); // Should have been handled in Negator!
2523
2524 // (A*B)-(A*C) -> A*(B-C) etc
2526 return replaceInstUsesWith(I, V);
2527
2528 if (I.getType()->isIntOrIntVectorTy(1))
2529 return BinaryOperator::CreateXor(Op0, Op1);
2530
2531 // Replace (-1 - A) with (~A).
2532 if (match(Op0, m_AllOnes()))
2533 return BinaryOperator::CreateNot(Op1);
2534
2535 // (X + -1) - Y --> ~Y + X
2536 Value *X, *Y;
2537 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_AllOnes()))))
2538 return BinaryOperator::CreateAdd(Builder.CreateNot(Op1), X);
2539
2540 // if (C1 & C2) == C2 then (X & C1) - (X & C2) -> X & (C1 ^ C2)
2541 Constant *C1, *C2;
2542 if (match(Op0, m_And(m_Value(X), m_ImmConstant(C1))) &&
2543 match(Op1, m_And(m_Specific(X), m_ImmConstant(C2)))) {
2544 Value *AndC = ConstantFoldBinaryInstruction(Instruction::And, C1, C2);
2545 if (C2->isElementWiseEqual(AndC))
2546 return BinaryOperator::CreateAnd(
2547 X, ConstantFoldBinaryInstruction(Instruction::Xor, C1, C2));
2548 }
2549
2550 // Reassociate sub/add sequences to create more add instructions and
2551 // reduce dependency chains:
2552 // ((X - Y) + Z) - Op1 --> (X + Z) - (Y + Op1)
2553 Value *Z;
2555 m_Value(Z))))) {
2556 Value *XZ = Builder.CreateAdd(X, Z);
2557 Value *YW = Builder.CreateAdd(Y, Op1);
2558 return BinaryOperator::CreateSub(XZ, YW);
2559 }
2560
2561 // ((X - Y) - Op1) --> X - (Y + Op1)
2562 if (match(Op0, m_OneUse(m_Sub(m_Value(X), m_Value(Y))))) {
2564 bool HasNUW = I.hasNoUnsignedWrap() && LHSSub->hasNoUnsignedWrap();
2565 bool HasNSW = HasNUW && I.hasNoSignedWrap() && LHSSub->hasNoSignedWrap();
2566 Value *Add = Builder.CreateAdd(Y, Op1, "", /*HasNUW=*/HasNUW,
2567 /*HasNSW=*/HasNSW);
2568 BinaryOperator *Sub = BinaryOperator::CreateSub(X, Add);
2569 Sub->setHasNoUnsignedWrap(HasNUW);
2570 Sub->setHasNoSignedWrap(HasNSW);
2571 return Sub;
2572 }
2573
2574 // (X + C0) - (Y + C1) --> (X - Y) + (C0 - C1)
2575 {
2576 Constant *CX, *CY;
2577 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_ImmConstant(CX)))) &&
2578 match(Op1, m_OneUse(m_Add(m_Value(Y), m_ImmConstant(CY))))) {
2579 Value *OpsSub = Builder.CreateSub(X, Y);
2580 Constant *ConstsSub = ConstantExpr::getSub(CX, CY);
2581 return BinaryOperator::CreateAdd(OpsSub, ConstsSub);
2582 }
2583 }
2584
2585 // (X + Z) - (Y + Z) --> (X - Y)
2586 {
2587 Value *W, *Z;
2588 if (match(Op0, m_AddLike(m_Value(W), m_Value(X))) &&
2589 match(Op1, m_AddLike(m_Value(Y), m_Value(Z)))) {
2590 Instruction *R = nullptr;
2591 if (W == Y)
2592 R = BinaryOperator::CreateSub(X, Z);
2593 else if (W == Z)
2594 R = BinaryOperator::CreateSub(X, Y);
2595 else if (X == Y)
2596 R = BinaryOperator::CreateSub(W, Z);
2597 else if (X == Z)
2598 R = BinaryOperator::CreateSub(W, Y);
2599 if (R) {
2600 bool NSW = I.hasNoSignedWrap() &&
2601 match(Op0, m_NSWAddLike(m_Value(), m_Value())) &&
2602 match(Op1, m_NSWAddLike(m_Value(), m_Value()));
2603
2604 bool NUW = I.hasNoUnsignedWrap() &&
2605 match(Op1, m_NUWAddLike(m_Value(), m_Value()));
2606 R->setHasNoSignedWrap(NSW);
2607 R->setHasNoUnsignedWrap(NUW);
2608 return R;
2609 }
2610 }
2611 }
2612
2613 // (~X) - (~Y) --> Y - X
2614 {
2615 // Need to ensure we can consume at least one of the `not` instructions,
2616 // otherwise this can inf loop.
2617 bool ConsumesOp0, ConsumesOp1;
2618 if (isFreeToInvert(Op0, Op0->hasOneUse(), ConsumesOp0) &&
2619 isFreeToInvert(Op1, Op1->hasOneUse(), ConsumesOp1) &&
2620 (ConsumesOp0 || ConsumesOp1)) {
2621 Value *NotOp0 = getFreelyInverted(Op0, Op0->hasOneUse(), &Builder);
2622 Value *NotOp1 = getFreelyInverted(Op1, Op1->hasOneUse(), &Builder);
2623 assert(NotOp0 != nullptr && NotOp1 != nullptr &&
2624 "isFreeToInvert desynced with getFreelyInverted");
2625 return BinaryOperator::CreateSub(NotOp1, NotOp0);
2626 }
2627 }
2628
2629 auto m_AddRdx = [](Value *&Vec) {
2631 };
2632 Value *V0, *V1;
2633 if (match(Op0, m_AddRdx(V0)) && match(Op1, m_AddRdx(V1)) &&
2634 V0->getType() == V1->getType()) {
2635 // Difference of sums is sum of differences:
2636 // add_rdx(V0) - add_rdx(V1) --> add_rdx(V0 - V1)
2637 Value *Sub = Builder.CreateSub(V0, V1);
2638 Value *Rdx = Builder.CreateIntrinsic(Intrinsic::vector_reduce_add,
2639 {Sub->getType()}, {Sub});
2640 return replaceInstUsesWith(I, Rdx);
2641 }
2642
2643 if (Constant *C = dyn_cast<Constant>(Op0)) {
2644 Value *X;
2645 if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
2646 // C - (zext bool) --> bool ? C - 1 : C
2648 // We know nothing about the distribution of the condition, so mark the
2649 // branch weights as unknown.
2651 return SI;
2652 }
2653 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
2654 // C - (sext bool) --> bool ? C + 1 : C
2656 // We know nothing about the distribution of the condition, so mark the
2657 // branch weights as unknown.
2659 return SI;
2660 }
2661
2662 // C - ~X == X + (1+C)
2663 if (match(Op1, m_Not(m_Value(X))))
2664 return BinaryOperator::CreateAdd(X, InstCombiner::AddOne(C));
2665
2666 // Try to fold constant sub into select arguments.
2668 if (Instruction *R = FoldOpIntoSelect(I, SI))
2669 return R;
2670
2671 // Try to fold constant sub into PHI values.
2672 if (PHINode *PN = dyn_cast<PHINode>(Op1))
2673 if (Instruction *R = foldOpIntoPhi(I, PN))
2674 return R;
2675
2676 Constant *C2;
2677
2678 // C-(C2-X) --> X+(C-C2)
2679 if (match(Op1, m_Sub(m_ImmConstant(C2), m_Value(X))))
2680 return BinaryOperator::CreateAdd(X, ConstantExpr::getSub(C, C2));
2681 }
2682
2683 const APInt *Op0C;
2684 if (match(Op0, m_APInt(Op0C))) {
2685 if (Op0C->isMask()) {
2686 // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
2687 // zero. We don't use information from dominating conditions so this
2688 // transform is easier to reverse if necessary.
2690 Op1, SQ.getWithInstruction(&I).getWithoutDomCondCache());
2691 if ((*Op0C | RHSKnown.Zero).isAllOnes())
2692 return BinaryOperator::CreateXor(Op1, Op0);
2693 }
2694
2695 // C - ((C3 -nuw X) & C2) --> (C - (C2 & C3)) + (X & C2) when:
2696 // (C3 - ((C2 & C3) - 1)) is pow2
2697 // ((C2 + C3) & ((C2 & C3) - 1)) == ((C2 & C3) - 1)
2698 // C2 is negative pow2 || sub nuw
2699 const APInt *C2, *C3;
2700 BinaryOperator *InnerSub;
2701 if (match(Op1, m_OneUse(m_And(m_BinOp(InnerSub), m_APInt(C2)))) &&
2702 match(InnerSub, m_Sub(m_APInt(C3), m_Value(X))) &&
2703 (InnerSub->hasNoUnsignedWrap() || C2->isNegatedPowerOf2())) {
2704 APInt C2AndC3 = *C2 & *C3;
2705 APInt C2AndC3Minus1 = C2AndC3 - 1;
2706 APInt C2AddC3 = *C2 + *C3;
2707 if ((*C3 - C2AndC3Minus1).isPowerOf2() &&
2708 C2AndC3Minus1.isSubsetOf(C2AddC3)) {
2709 Value *And = Builder.CreateAnd(X, ConstantInt::get(I.getType(), *C2));
2710 return BinaryOperator::CreateAdd(
2711 And, ConstantInt::get(I.getType(), *Op0C - C2AndC3));
2712 }
2713 }
2714 }
2715
2716 {
2717 Value *Y;
2718 // X-(X+Y) == -Y X-(Y+X) == -Y
2719 if (match(Op1, m_c_Add(m_Specific(Op0), m_Value(Y))))
2721
2722 // (X-Y)-X == -Y
2723 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
2725 }
2726
2727 // (sub (or A, B) (and A, B)) --> (xor A, B)
2728 {
2729 Value *A, *B;
2730 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
2731 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
2732 return BinaryOperator::CreateXor(A, B);
2733 }
2734
2735 // (sub (add A, B) (or A, B)) --> (and A, B)
2736 {
2737 Value *A, *B;
2738 if (match(Op0, m_Add(m_Value(A), m_Value(B))) &&
2739 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
2740 return BinaryOperator::CreateAnd(A, B);
2741 }
2742
2743 // (sub (add A, B) (and A, B)) --> (or A, B)
2744 {
2745 Value *A, *B;
2746 if (match(Op0, m_Add(m_Value(A), m_Value(B))) &&
2748 return BinaryOperator::CreateOr(A, B);
2749 }
2750
2751 // (sub (and A, B) (or A, B)) --> neg (xor A, B)
2752 {
2753 Value *A, *B;
2754 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2755 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
2756 (Op0->hasOneUse() || Op1->hasOneUse()))
2757 return BinaryOperator::CreateNeg(Builder.CreateXor(A, B));
2758 }
2759
2760 // (sub (or A, B), (xor A, B)) --> (and A, B)
2761 {
2762 Value *A, *B;
2763 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2764 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
2765 return BinaryOperator::CreateAnd(A, B);
2766 }
2767
2768 // (sub (xor A, B) (or A, B)) --> neg (and A, B)
2769 {
2770 Value *A, *B;
2771 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2772 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))) &&
2773 (Op0->hasOneUse() || Op1->hasOneUse()))
2774 return BinaryOperator::CreateNeg(Builder.CreateAnd(A, B));
2775 }
2776
2777 {
2778 Value *Y;
2779 // ((X | Y) - X) --> (~X & Y)
2780 if (match(Op0, m_OneUse(m_c_Or(m_Value(Y), m_Specific(Op1)))))
2781 return BinaryOperator::CreateAnd(
2782 Y, Builder.CreateNot(Op1, Op1->getName() + ".not"));
2783 }
2784
2785 {
2786 // (sub (and Op1, (neg X)), Op1) --> neg (and Op1, (add X, -1))
2787 Value *X;
2788 if (match(Op0, m_OneUse(m_c_And(m_Specific(Op1),
2789 m_OneUse(m_Neg(m_Value(X))))))) {
2790 return BinaryOperator::CreateNeg(Builder.CreateAnd(
2791 Op1, Builder.CreateAdd(X, Constant::getAllOnesValue(I.getType()))));
2792 }
2793 }
2794
2795 {
2796 // (sub (and Op1, C), Op1) --> neg (and Op1, ~C)
2797 Constant *C;
2798 if (match(Op0, m_OneUse(m_And(m_Specific(Op1), m_Constant(C))))) {
2800 Builder.CreateAnd(Op1, Builder.CreateNot(C)));
2801 }
2802 }
2803
2804 {
2805 // (sub (xor X, (sext C)), (sext C)) => (select C, (neg X), X)
2806 // (sub (sext C), (xor X, (sext C))) => (select C, X, (neg X))
2807 Value *C, *X;
2808 auto m_SubXorCmp = [&C, &X](Value *LHS, Value *RHS) {
2809 return match(LHS, m_OneUse(m_c_Xor(m_Value(X), m_Specific(RHS)))) &&
2810 match(RHS, m_SExt(m_Value(C))) &&
2811 (C->getType()->getScalarSizeInBits() == 1);
2812 };
2813 if (m_SubXorCmp(Op0, Op1))
2814 return createSelectInstWithUnknownProfile(C, Builder.CreateNeg(X), X);
2815 if (m_SubXorCmp(Op1, Op0))
2816 return createSelectInstWithUnknownProfile(C, X, Builder.CreateNeg(X));
2817 }
2818
2820 return R;
2821
2823 return R;
2824
2825 {
2826 // If we have a subtraction between some value and a select between
2827 // said value and something else, sink subtraction into select hands, i.e.:
2828 // sub (select %Cond, %TrueVal, %FalseVal), %Op1
2829 // ->
2830 // select %Cond, (sub %TrueVal, %Op1), (sub %FalseVal, %Op1)
2831 // or
2832 // sub %Op0, (select %Cond, %TrueVal, %FalseVal)
2833 // ->
2834 // select %Cond, (sub %Op0, %TrueVal), (sub %Op0, %FalseVal)
2835 // This will result in select between new subtraction and 0.
2836 auto SinkSubIntoSelect =
2837 [Ty = I.getType()](Value *Select, Value *OtherHandOfSub,
2838 auto SubBuilder) -> Instruction * {
2839 Value *Cond, *TrueVal, *FalseVal;
2840 if (!match(Select, m_OneUse(m_Select(m_Value(Cond), m_Value(TrueVal),
2841 m_Value(FalseVal)))))
2842 return nullptr;
2843 if (OtherHandOfSub != TrueVal && OtherHandOfSub != FalseVal)
2844 return nullptr;
2845 // While it is really tempting to just create two subtractions and let
2846 // InstCombine fold one of those to 0, it isn't possible to do so
2847 // because of worklist visitation order. So ugly it is.
2848 bool OtherHandOfSubIsTrueVal = OtherHandOfSub == TrueVal;
2849 Value *NewSub = SubBuilder(OtherHandOfSubIsTrueVal ? FalseVal : TrueVal);
2850 Constant *Zero = Constant::getNullValue(Ty);
2851 SelectInst *NewSel =
2852 SelectInst::Create(Cond, OtherHandOfSubIsTrueVal ? Zero : NewSub,
2853 OtherHandOfSubIsTrueVal ? NewSub : Zero);
2854 // Preserve prof metadata if any.
2856 return NewSel;
2857 };
2858 if (Instruction *NewSel = SinkSubIntoSelect(
2859 /*Select=*/Op0, /*OtherHandOfSub=*/Op1,
2860 [Builder = &Builder, Op1](Value *OtherHandOfSelect) {
2861 return Builder->CreateSub(OtherHandOfSelect,
2862 /*OtherHandOfSub=*/Op1);
2863 }))
2864 return NewSel;
2865 if (Instruction *NewSel = SinkSubIntoSelect(
2866 /*Select=*/Op1, /*OtherHandOfSub=*/Op0,
2867 [Builder = &Builder, Op0](Value *OtherHandOfSelect) {
2868 return Builder->CreateSub(/*OtherHandOfSub=*/Op0,
2869 OtherHandOfSelect);
2870 }))
2871 return NewSel;
2872 }
2873
2874 // (X - (X & Y)) --> (X & ~Y)
2875 if (match(Op1, m_c_And(m_Specific(Op0), m_Value(Y))) &&
2876 (Op1->hasOneUse() || isa<Constant>(Y)))
2877 return BinaryOperator::CreateAnd(
2878 Op0, Builder.CreateNot(Y, Y->getName() + ".not"));
2879
2880 // ~X - Min/Max(~X, Y) -> ~Min/Max(X, ~Y) - X
2881 // ~X - Min/Max(Y, ~X) -> ~Min/Max(X, ~Y) - X
2882 // Min/Max(~X, Y) - ~X -> X - ~Min/Max(X, ~Y)
2883 // Min/Max(Y, ~X) - ~X -> X - ~Min/Max(X, ~Y)
2884 // As long as Y is freely invertible, this will be neutral or a win.
2885 // Note: We don't generate the inverse max/min, just create the 'not' of
2886 // it and let other folds do the rest.
2887 if (match(Op0, m_Not(m_Value(X))) &&
2888 match(Op1, m_c_MaxOrMin(m_Specific(Op0), m_Value(Y))) &&
2889 !Op0->hasNUsesOrMore(3) && isFreeToInvert(Y, Y->hasOneUse())) {
2890 Value *Not = Builder.CreateNot(Op1);
2891 return BinaryOperator::CreateSub(Not, X);
2892 }
2893 if (match(Op1, m_Not(m_Value(X))) &&
2894 match(Op0, m_c_MaxOrMin(m_Specific(Op1), m_Value(Y))) &&
2895 !Op1->hasNUsesOrMore(3) && isFreeToInvert(Y, Y->hasOneUse())) {
2896 Value *Not = Builder.CreateNot(Op0);
2897 return BinaryOperator::CreateSub(X, Not);
2898 }
2899
2900 // min(X+1, Y) - min(X, Y) --> zext X < Y
2901 // Replacing a sub and at least one min with an icmp
2902 // and a zext is a potential improvement.
2903 if (match(Op0, m_c_SMin(m_NSWAddLike(m_Value(X), m_One()), m_Value(Y))) &&
2904 match(Op1, m_c_SMin(m_Specific(X), m_Specific(Y))) &&
2905 I.getType()->getScalarSizeInBits() != 1 &&
2906 (Op0->hasOneUse() || Op1->hasOneUse())) {
2907 Value *Cond = Builder.CreateICmpSLT(X, Y);
2908 return new ZExtInst(Cond, I.getType());
2909 }
2910 if (match(Op0, m_c_UMin(m_NUWAddLike(m_Value(X), m_One()), m_Value(Y))) &&
2911 match(Op1, m_c_UMin(m_Specific(X), m_Specific(Y))) &&
2912 I.getType()->getScalarSizeInBits() != 1 &&
2913 (Op0->hasOneUse() || Op1->hasOneUse())) {
2914 Value *Cond = Builder.CreateICmpULT(X, Y);
2915 return new ZExtInst(Cond, I.getType());
2916 }
2917
2918 // Optimize pointer differences into the same array into a size. Consider:
2919 // &A[10] - &A[0]: we should compile this to "10".
2920 Value *LHSOp, *RHSOp;
2921 if (match(Op0, m_PtrToIntOrAddr(m_Value(LHSOp))) &&
2922 match(Op1, m_PtrToIntOrAddr(m_Value(RHSOp))))
2923 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType(),
2924 I.hasNoUnsignedWrap()))
2925 return replaceInstUsesWith(I, Res);
2926
2927 // trunc(p)-trunc(q) -> trunc(p-q)
2928 if (match(Op0, m_Trunc(m_PtrToIntOrAddr(m_Value(LHSOp)))) &&
2929 match(Op1, m_Trunc(m_PtrToIntOrAddr(m_Value(RHSOp)))))
2930 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType(),
2931 /* IsNUW */ false))
2932 return replaceInstUsesWith(I, Res);
2933
2934 auto MatchSubOfZExtOfPtrToIntOrAddr = [&]() {
2935 if (match(Op0, m_ZExt(m_PtrToIntSameSize(DL, m_Value(LHSOp)))) &&
2936 match(Op1, m_ZExt(m_PtrToIntSameSize(DL, m_Value(RHSOp)))))
2937 return true;
2938 if (match(Op0, m_ZExt(m_PtrToAddr(m_Value(LHSOp)))) &&
2939 match(Op1, m_ZExt(m_PtrToAddr(m_Value(RHSOp)))))
2940 return true;
2941 // Special case for non-canonical ptrtoint in constant expression,
2942 // where the zext has been folded into the ptrtoint.
2943 if (match(Op0, m_ZExt(m_PtrToIntSameSize(DL, m_Value(LHSOp)))) &&
2944 match(Op1, m_PtrToInt(m_Value(RHSOp))))
2945 return true;
2946 return false;
2947 };
2948 if (MatchSubOfZExtOfPtrToIntOrAddr()) {
2949 if (auto *GEP = dyn_cast<GEPOperator>(LHSOp)) {
2950 if (GEP->getPointerOperand() == RHSOp) {
2951 if (GEP->hasNoUnsignedWrap() || GEP->hasNoUnsignedSignedWrap()) {
2952 Value *Offset = EmitGEPOffset(GEP);
2953 Value *Res = GEP->hasNoUnsignedWrap()
2954 ? Builder.CreateZExt(
2955 Offset, I.getType(), "",
2956 /*IsNonNeg=*/GEP->hasNoUnsignedSignedWrap())
2957 : Builder.CreateSExt(Offset, I.getType());
2958 return replaceInstUsesWith(I, Res);
2959 }
2960 }
2961 }
2962 }
2963
2964 // Canonicalize a shifty way to code absolute value to the common pattern.
2965 // There are 2 potential commuted variants.
2966 // We're relying on the fact that we only do this transform when the shift has
2967 // exactly 2 uses and the xor has exactly 1 use (otherwise, we might increase
2968 // instructions).
2969 Value *A;
2970 const APInt *ShAmt;
2971 Type *Ty = I.getType();
2972 unsigned BitWidth = Ty->getScalarSizeInBits();
2973 if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) &&
2974 Op1->hasNUses(2) && *ShAmt == BitWidth - 1 &&
2975 match(Op0, m_OneUse(m_c_Xor(m_Specific(A), m_Specific(Op1))))) {
2976 // B = ashr i32 A, 31 ; smear the sign bit
2977 // sub (xor A, B), B ; flip bits if negative and subtract -1 (add 1)
2978 // --> (A < 0) ? -A : A
2979 Value *IsNeg = Builder.CreateIsNeg(A);
2980 // Copy the nsw flags from the sub to the negate.
2981 Value *NegA = I.hasNoUnsignedWrap()
2982 ? Constant::getNullValue(A->getType())
2983 : Builder.CreateNeg(A, "", I.hasNoSignedWrap());
2984 return SelectInst::Create(IsNeg, NegA, A);
2985 }
2986
2987 // If we are subtracting a low-bit masked subset of some value from an add
2988 // of that same value with no low bits changed, that is clearing some low bits
2989 // of the sum:
2990 // sub (X + AddC), (X & AndC) --> and (X + AddC), ~AndC
2991 const APInt *AddC, *AndC;
2992 if (match(Op0, m_Add(m_Value(X), m_APInt(AddC))) &&
2993 match(Op1, m_And(m_Specific(X), m_APInt(AndC)))) {
2994 unsigned Cttz = AddC->countr_zero();
2995 APInt HighMask(APInt::getHighBitsSet(BitWidth, BitWidth - Cttz));
2996 if ((HighMask & *AndC).isZero())
2997 return BinaryOperator::CreateAnd(Op0, ConstantInt::get(Ty, ~(*AndC)));
2998 }
2999
3000 if (Instruction *V =
3002 return V;
3003
3004 // X - usub.sat(X, Y) => umin(X, Y)
3006 m_Value(Y)))))
3007 return replaceInstUsesWith(
3008 I, Builder.CreateIntrinsic(Intrinsic::umin, {I.getType()}, {Op0, Y}));
3009
3010 // umax(X, Op1) - Op1 --> usub.sat(X, Op1)
3011 // TODO: The one-use restriction is not strictly necessary, but it may
3012 // require improving other pattern matching and/or codegen.
3013 if (match(Op0, m_OneUse(m_c_UMax(m_Value(X), m_Specific(Op1)))))
3014 return replaceInstUsesWith(
3015 I, Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {X, Op1}));
3016
3017 // Op0 - umin(X, Op0) --> usub.sat(Op0, X)
3018 if (match(Op1, m_OneUse(m_c_UMin(m_Value(X), m_Specific(Op0)))))
3019 return replaceInstUsesWith(
3020 I, Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {Op0, X}));
3021
3022 // Op0 - umax(X, Op0) --> 0 - usub.sat(X, Op0)
3023 if (match(Op1, m_OneUse(m_c_UMax(m_Value(X), m_Specific(Op0))))) {
3024 Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {X, Op0});
3025 return BinaryOperator::CreateNeg(USub);
3026 }
3027
3028 // umin(X, Op1) - Op1 --> 0 - usub.sat(Op1, X)
3029 if (match(Op0, m_OneUse(m_c_UMin(m_Value(X), m_Specific(Op1))))) {
3030 Value *USub = Builder.CreateIntrinsic(Intrinsic::usub_sat, {Ty}, {Op1, X});
3031 return BinaryOperator::CreateNeg(USub);
3032 }
3033
3034 // C - ctpop(X) => ctpop(~X) if C is bitwidth
3035 if (match(Op0, m_SpecificInt(BitWidth)) &&
3036 match(Op1, m_OneUse(m_Ctpop(m_Value(X)))))
3037 return replaceInstUsesWith(
3038 I, Builder.CreateIntrinsic(Intrinsic::ctpop, {I.getType()},
3039 {Builder.CreateNot(X)}));
3040
3041 // Reduce multiplies for difference-of-squares by factoring:
3042 // (X * X) - (Y * Y) --> (X + Y) * (X - Y)
3043 if (match(Op0, m_OneUse(m_Mul(m_Value(X), m_Deferred(X)))) &&
3044 match(Op1, m_OneUse(m_Mul(m_Value(Y), m_Deferred(Y))))) {
3045 auto *OBO0 = cast<OverflowingBinaryOperator>(Op0);
3046 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3047 bool PropagateNSW = I.hasNoSignedWrap() && OBO0->hasNoSignedWrap() &&
3048 OBO1->hasNoSignedWrap() && BitWidth > 2;
3049 bool PropagateNUW = I.hasNoUnsignedWrap() && OBO0->hasNoUnsignedWrap() &&
3050 OBO1->hasNoUnsignedWrap() && BitWidth > 1;
3051 Value *Add = Builder.CreateAdd(X, Y, "add", PropagateNUW, PropagateNSW);
3052 Value *Sub = Builder.CreateSub(X, Y, "sub", PropagateNUW, PropagateNSW);
3053 Value *Mul = Builder.CreateMul(Add, Sub, "", PropagateNUW, PropagateNSW);
3054 return replaceInstUsesWith(I, Mul);
3055 }
3056
3057 // max(X,Y) nsw/nuw - min(X,Y) --> abs(X nsw - Y)
3058 if (match(Op0, m_OneUse(m_c_SMax(m_Value(X), m_Value(Y)))) &&
3060 if (I.hasNoUnsignedWrap() || I.hasNoSignedWrap()) {
3061 Value *Sub =
3062 Builder.CreateSub(X, Y, "sub", /*HasNUW=*/false, /*HasNSW=*/true);
3063 Value *Call =
3064 Builder.CreateBinaryIntrinsic(Intrinsic::abs, Sub, Builder.getTrue());
3065 return replaceInstUsesWith(I, Call);
3066 }
3067 }
3068
3070 return Res;
3071
3072 // (sub (sext (add nsw (X, Y)), sext (X))) --> (sext (Y))
3073 if (match(Op1, m_SExtLike(m_Value(X))) &&
3075 Value *SExtY = Builder.CreateSExt(Y, I.getType());
3076 return replaceInstUsesWith(I, SExtY);
3077 }
3078
3079 // (sub[ nsw] (sext (add nsw (X, Y)), sext (add nsw (X, Z)))) -->
3080 // --> (sub[ nsw] (sext (Y), sext (Z)))
3081 {
3082 Value *Z, *Add0, *Add1;
3083 if (match(Op0, m_SExtLike(m_Value(Add0))) &&
3084 match(Op1, m_SExtLike(m_Value(Add1))) &&
3085 ((match(Add0, m_NSWAdd(m_Value(X), m_Value(Y))) &&
3086 match(Add1, m_c_NSWAdd(m_Specific(X), m_Value(Z)))) ||
3087 (match(Add0, m_NSWAdd(m_Value(Y), m_Value(X))) &&
3088 match(Add1, m_c_NSWAdd(m_Specific(X), m_Value(Z)))))) {
3089 unsigned NumOfNewInstrs = 0;
3090 // Non-constant Y, Z require new SExt.
3091 NumOfNewInstrs += !isa<Constant>(Y) ? 1 : 0;
3092 NumOfNewInstrs += !isa<Constant>(Z) ? 1 : 0;
3093 // Check if we can trade some of the old instructions for the new ones.
3094 unsigned NumOfDeadInstrs = 0;
3095 if (Op0->hasOneUse()) {
3096 // If Op0 (sext) has multiple uses, then we keep it
3097 // and the add that it uses, otherwise, we can remove
3098 // the sext and probably the add (depending on the number of its uses).
3099 ++NumOfDeadInstrs;
3100 NumOfDeadInstrs += Add0->hasOneUse() ? 1 : 0;
3101 }
3102 if (Op1->hasOneUse()) {
3103 ++NumOfDeadInstrs;
3104 NumOfDeadInstrs += Add1->hasOneUse() ? 1 : 0;
3105 }
3106 if (NumOfDeadInstrs >= NumOfNewInstrs) {
3107 Value *SExtY = Builder.CreateSExt(Y, I.getType());
3108 Value *SExtZ = Builder.CreateSExt(Z, I.getType());
3109 Value *Sub = Builder.CreateSub(SExtY, SExtZ, "",
3110 /*HasNUW=*/false,
3111 /*HasNSW=*/I.hasNoSignedWrap());
3112 return replaceInstUsesWith(I, Sub);
3113 }
3114 }
3115 }
3116
3117 // ((X + C) & ~C) - X -> X & C where C is a power of 2.
3118 if (match(Op0,
3119 m_And(m_Add(m_Specific(Op1), m_Power2(AddC)), m_APInt(AndC))) &&
3120 *AddC == ~*AndC) {
3121 return BinaryOperator::CreateAnd(Op1, ConstantInt::get(Ty, *AddC));
3122 }
3123
3124 return TryToNarrowDeduceFlags();
3125}
3126
3127/// This eliminates floating-point negation in either 'fneg(X)' or
3128/// 'fsub(-0.0, X)' form by combining into a constant operand.
3130 // This is limited with one-use because fneg is assumed better for
3131 // reassociation and cheaper in codegen than fmul/fdiv.
3132 // TODO: Should the m_OneUse restriction be removed?
3133 Instruction *FNegOp;
3134 if (!match(&I, m_FNeg(m_OneUse(m_Instruction(FNegOp)))))
3135 return nullptr;
3136
3137 Value *X;
3138 Constant *C;
3139
3140 // Fold negation into constant operand.
3141 // -(X * C) --> X * (-C)
3142 if (match(FNegOp, m_FMul(m_Value(X), m_Constant(C))))
3143 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL)) {
3144 FastMathFlags FNegF = I.getFastMathFlags();
3145 FastMathFlags OpF = FNegOp->getFastMathFlags();
3146 FastMathFlags FMF = FastMathFlags::unionValue(FNegF, OpF) |
3148 FMF.setNoInfs(FNegF.noInfs() && OpF.noInfs());
3149 return BinaryOperator::CreateFMulFMF(X, NegC, FMF);
3150 }
3151 // -(X / C) --> X / (-C)
3152 if (match(FNegOp, m_FDiv(m_Value(X), m_Constant(C)))) {
3153 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL)) {
3155
3156 // Intersect 'nsz' and 'ninf' because those special value exceptions may
3157 // not apply to the fdiv. Everything else propagates from the fneg.
3158 FastMathFlags FMF = I.getFastMathFlags();
3159 FastMathFlags OpFMF = FNegOp->getFastMathFlags();
3160 FDiv->setHasNoSignedZeros(FMF.noSignedZeros() && OpFMF.noSignedZeros());
3161 FDiv->setHasNoInfs(FMF.noInfs() && OpFMF.noInfs());
3162 FDiv->copyMetadata(*FNegOp);
3163 return FDiv;
3164 }
3165 }
3166 // -(C / X) --> (-C) / X
3167 if (match(FNegOp, m_FDiv(m_Constant(C), m_Value(X))))
3168 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL)) {
3170
3171 // Intersect 'nsz' and 'ninf' because those special value exceptions may
3172 // not apply to the fdiv. Everything else propagates from the fneg.
3173 // TODO: We could propagate nsz/ninf from fdiv alone?
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 // With NSZ [ counter-example with -0.0: -(-0.0 + 0.0) != 0.0 + -0.0 ]:
3182 // -(X + C) --> -X + -C --> -C - X
3183 if (I.hasNoSignedZeros() && match(FNegOp, m_FAdd(m_Value(X), m_Constant(C))))
3184 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
3185 return BinaryOperator::CreateFSubFMF(NegC, X, &I);
3186
3187 return nullptr;
3188}
3189
3190Instruction *InstCombinerImpl::hoistFNegAboveFMulFDiv(Value *FNegOp,
3191 Instruction &FMFSource) {
3192 Value *X, *Y;
3193 if (match(FNegOp, m_FMul(m_Value(X), m_Value(Y)))) {
3194 // Push into RHS which is more likely to simplify (const or another fneg).
3195 // FIXME: It would be better to invert the transform.
3196 return cast<Instruction>(Builder.CreateFMulFMF(
3197 X, Builder.CreateFNegFMF(Y, &FMFSource), &FMFSource));
3198 }
3199
3200 if (match(FNegOp, m_FDiv(m_Value(X), m_Value(Y)))) {
3201 auto *FDiv = cast<Instruction>(Builder.CreateFDivFMF(
3202 Builder.CreateFNegFMF(X, &FMFSource), Y, &FMFSource));
3203 FDiv->copyMetadata(*cast<Instruction>(FNegOp));
3204 return FDiv;
3205 }
3206
3207 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(FNegOp)) {
3208 // Make sure to preserve flags and metadata on the call.
3209 if (II->getIntrinsicID() == Intrinsic::ldexp) {
3210 FastMathFlags FMF = FMFSource.getFastMathFlags() | II->getFastMathFlags();
3211 CallInst *New =
3212 Builder.CreateCall(II->getCalledFunction(),
3213 {Builder.CreateFNegFMF(II->getArgOperand(0), FMF),
3214 II->getArgOperand(1)});
3215 New->setFastMathFlags(FMF);
3216 New->copyMetadata(*II);
3217 return New;
3218 }
3219 }
3220
3221 return nullptr;
3222}
3223
3225 Value *Op = I.getOperand(0);
3226
3227 if (Value *V = simplifyFNegInst(Op, I.getFastMathFlags(),
3228 getSimplifyQuery().getWithInstruction(&I)))
3229 return replaceInstUsesWith(I, V);
3230
3232 return X;
3233
3234 Value *X, *Y;
3235
3236 // If we can ignore the sign of zeros: -(X - Y) --> (Y - X)
3237 if (I.hasNoSignedZeros() &&
3240
3241 Value *OneUse;
3242 if (!match(Op, m_OneUse(m_Value(OneUse))))
3243 return nullptr;
3244
3245 if (Instruction *R = hoistFNegAboveFMulFDiv(OneUse, I))
3246 return replaceInstUsesWith(I, R);
3247
3248 // Try to eliminate fneg if at least 1 arm of the select is negated.
3249 Value *Cond;
3250 if (match(OneUse, m_Select(m_Value(Cond), m_Value(X), m_Value(Y)))) {
3251 // Unlike most transforms, this one is not safe to propagate nsz unless
3252 // it is present on the original select. We union the flags from the select
3253 // and fneg and then remove nsz if needed.
3254 auto propagateSelectFMF = [&](SelectInst *S, bool CommonOperand) {
3255 S->copyFastMathFlags(&I);
3256 if (auto *OldSel = dyn_cast<SelectInst>(Op)) {
3257 FastMathFlags FMF = I.getFastMathFlags() | OldSel->getFastMathFlags();
3258 S->setFastMathFlags(FMF);
3259 if (!OldSel->hasNoSignedZeros() && !CommonOperand &&
3260 !isGuaranteedNotToBeUndefOrPoison(OldSel->getCondition()))
3261 S->setHasNoSignedZeros(false);
3262 }
3263 };
3264 // -(Cond ? -P : Y) --> Cond ? P : -Y
3265 Value *P;
3266 if (match(X, m_FNeg(m_Value(P)))) {
3267 Value *NegY = Builder.CreateFNegFMF(Y, &I, Y->getName() + ".neg");
3269 Cond, P, NegY, "", nullptr,
3271 propagateSelectFMF(NewSel, P == Y);
3272 return NewSel;
3273 }
3274 // -(Cond ? X : -P) --> Cond ? -X : P
3275 if (match(Y, m_FNeg(m_Value(P)))) {
3276 Value *NegX = Builder.CreateFNegFMF(X, &I, X->getName() + ".neg");
3278 Cond, NegX, P, "", nullptr,
3280 propagateSelectFMF(NewSel, P == X);
3281 return NewSel;
3282 }
3283
3284 // -(Cond ? X : C) --> Cond ? -X : -C
3285 // -(Cond ? C : Y) --> Cond ? -C : -Y
3286 if (match(X, m_ImmConstant()) || match(Y, m_ImmConstant())) {
3287 Value *NegX = Builder.CreateFNegFMF(X, &I, X->getName() + ".neg");
3288 Value *NegY = Builder.CreateFNegFMF(Y, &I, Y->getName() + ".neg");
3290 Cond, NegX, NegY, "", nullptr,
3292 propagateSelectFMF(NewSel, /*CommonOperand=*/true);
3293 return NewSel;
3294 }
3295 }
3296
3297 // fneg (copysign x, y) -> copysign x, (fneg y)
3298 if (match(OneUse, m_CopySign(m_Value(X), m_Value(Y)))) {
3299 // The source copysign has an additional value input, so we can't propagate
3300 // flags the copysign doesn't also have.
3301 FastMathFlags FMF = I.getFastMathFlags();
3302 FMF &= cast<FPMathOperator>(OneUse)->getFastMathFlags();
3303 Value *NegY = Builder.CreateFNegFMF(Y, FMF);
3304 Value *NewCopySign = Builder.CreateCopySign(X, NegY, FMF);
3305 return replaceInstUsesWith(I, NewCopySign);
3306 }
3307
3308 // fneg (shuffle x, Mask) --> shuffle (fneg x), Mask
3309 ArrayRef<int> Mask;
3310 if (match(OneUse, m_Shuffle(m_Value(X), m_Poison(), m_Mask(Mask))))
3311 return new ShuffleVectorInst(Builder.CreateFNegFMF(X, &I), Mask);
3312
3313 // fneg (reverse x) --> reverse (fneg x)
3314 if (match(OneUse, m_VecReverse(m_Value(X)))) {
3315 Value *Reverse = Builder.CreateVectorReverse(Builder.CreateFNegFMF(X, &I));
3316 return replaceInstUsesWith(I, Reverse);
3317 }
3318
3319 return nullptr;
3320}
3321
3323 if (Value *V = simplifyFSubInst(I.getOperand(0), I.getOperand(1),
3324 I.getFastMathFlags(),
3325 getSimplifyQuery().getWithInstruction(&I)))
3326 return replaceInstUsesWith(I, V);
3327
3329 return X;
3330
3332 return Phi;
3333
3334 // Subtraction from -0.0 is the canonical form of fneg.
3335 // fsub -0.0, X ==> fneg X
3336 // fsub nsz 0.0, X ==> fneg nsz X
3337 //
3338 // FIXME This matcher does not respect FTZ or DAZ yet:
3339 // fsub -0.0, Denorm ==> +-0
3340 // fneg Denorm ==> -Denorm
3341 Value *Op;
3342 if (match(&I, m_FNeg(m_Value(Op))))
3344
3346 return X;
3347
3348 if (Instruction *R = foldFBinOpOfIntCasts(I))
3349 return R;
3350
3351 Value *X, *Y;
3352 Constant *C;
3353
3354 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3355 // If Op0 is not -0.0 or we can ignore -0.0: Z - (X - Y) --> Z + (Y - X)
3356 // Canonicalize to fadd to make analysis easier.
3357 // This can also help codegen because fadd is commutative.
3358 // Note that if this fsub was really an fneg, the fadd with -0.0 will get
3359 // killed later. We still limit that particular transform with 'hasOneUse'
3360 // because an fneg is assumed better/cheaper than a generic fsub.
3361 if (I.hasNoSignedZeros() ||
3362 cannotBeNegativeZero(Op0, getSimplifyQuery().getWithInstruction(&I))) {
3363 if (match(Op1, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
3364 Value *NewSub = Builder.CreateFSubFMF(Y, X, &I);
3365 return BinaryOperator::CreateFAddFMF(Op0, NewSub, &I);
3366 }
3367 }
3368
3369 // (-X) - Op1 --> -(X + Op1)
3370 if (I.hasNoSignedZeros() && !isa<ConstantExpr>(Op0) &&
3371 match(Op0, m_OneUse(m_FNeg(m_Value(X))))) {
3372 Value *FAdd = Builder.CreateFAddFMF(X, Op1, &I);
3374 }
3375
3376 if (isa<Constant>(Op0))
3378 if (Instruction *NV = FoldOpIntoSelect(I, SI))
3379 return NV;
3380
3381 // X - C --> X + (-C)
3382 // But don't transform constant expressions because there's an inverse fold
3383 // for X + (-Y) --> X - Y.
3384 if (match(Op1, m_ImmConstant(C)))
3385 if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
3386 return BinaryOperator::CreateFAddFMF(Op0, NegC, &I);
3387
3388 // X - (-Y) --> X + Y
3389 if (match(Op1, m_FNeg(m_Value(Y))))
3390 return BinaryOperator::CreateFAddFMF(Op0, Y, &I);
3391
3392 // Similar to above, but look through a cast of the negated value:
3393 // X - (fptrunc(-Y)) --> X + fptrunc(Y)
3394 Type *Ty = I.getType();
3395 if (match(Op1, m_OneUse(m_FPTrunc(m_FNeg(m_Value(Y))))))
3396 return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPTrunc(Y, Ty), &I);
3397
3398 // X - (fpext(-Y)) --> X + fpext(Y)
3399 if (match(Op1, m_OneUse(m_FPExt(m_FNeg(m_Value(Y))))))
3400 return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPExt(Y, Ty), &I);
3401
3402 // Similar to above, but look through fmul/fdiv of the negated value:
3403 // Op0 - (-X * Y) --> Op0 + (X * Y)
3404 // Op0 - (Y * -X) --> Op0 + (X * Y)
3405 if (match(Op1, m_OneUse(m_c_FMul(m_FNeg(m_Value(X)), m_Value(Y))))) {
3406 Value *FMul = Builder.CreateFMulFMF(X, Y, &I);
3407 return BinaryOperator::CreateFAddFMF(Op0, FMul, &I);
3408 }
3409 // Op0 - (-X / Y) --> Op0 + (X / Y)
3410 // Op0 - (X / -Y) --> Op0 + (X / Y)
3411 if (match(Op1, m_OneUse(m_FDiv(m_FNeg(m_Value(X)), m_Value(Y)))) ||
3412 match(Op1, m_OneUse(m_FDiv(m_Value(X), m_FNeg(m_Value(Y)))))) {
3413 Value *FDiv = Builder.CreateFDivFMF(X, Y, &I);
3414 return BinaryOperator::CreateFAddFMF(Op0, FDiv, &I);
3415 }
3416
3417 // Handle special cases for FSub with selects feeding the operation
3418 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
3419 return replaceInstUsesWith(I, V);
3420
3421 if (I.hasAllowReassoc() && I.hasNoSignedZeros()) {
3422 // (Y - X) - Y --> -X
3423 if (match(Op0, m_FSub(m_Specific(Op1), m_Value(X))))
3425
3426 // Y - (X + Y) --> -X
3427 // Y - (Y + X) --> -X
3428 if (match(Op1, m_c_FAdd(m_Specific(Op0), m_Value(X))))
3430
3431 // (X * C) - X --> X * (C - 1.0)
3432 if (match(Op0, m_FMul(m_Specific(Op1), m_Constant(C)))) {
3434 Instruction::FSub, C, ConstantFP::get(Ty, 1.0), DL))
3435 return BinaryOperator::CreateFMulFMF(Op1, CSubOne, &I);
3436 }
3437 // X - (X * C) --> X * (1.0 - C)
3438 if (match(Op1, m_FMul(m_Specific(Op0), m_Constant(C)))) {
3440 Instruction::FSub, ConstantFP::get(Ty, 1.0), C, DL))
3441 return BinaryOperator::CreateFMulFMF(Op0, OneSubC, &I);
3442 }
3443
3444 // Reassociate fsub/fadd sequences to create more fadd instructions and
3445 // reduce dependency chains:
3446 // ((X - Y) + Z) - Op1 --> (X + Z) - (Y + Op1)
3447 Value *Z;
3449 m_Value(Z))))) {
3450 Value *XZ = Builder.CreateFAddFMF(X, Z, &I);
3451 Value *YW = Builder.CreateFAddFMF(Y, Op1, &I);
3452 return BinaryOperator::CreateFSubFMF(XZ, YW, &I);
3453 }
3454
3455 auto m_FaddRdx = [](Value *&Sum, Value *&Vec) {
3457 m_Value(Vec)));
3458 };
3459 Value *A0, *A1, *V0, *V1;
3460 if (match(Op0, m_FaddRdx(A0, V0)) && match(Op1, m_FaddRdx(A1, V1)) &&
3461 V0->getType() == V1->getType()) {
3462 // Difference of sums is sum of differences:
3463 // add_rdx(A0, V0) - add_rdx(A1, V1) --> add_rdx(A0, V0 - V1) - A1
3464 Value *Sub = Builder.CreateFSubFMF(V0, V1, &I);
3465 Value *Rdx = Builder.CreateIntrinsic(Intrinsic::vector_reduce_fadd,
3466 {Sub->getType()}, {A0, Sub}, &I);
3467 return BinaryOperator::CreateFSubFMF(Rdx, A1, &I);
3468 }
3469
3471 return F;
3472
3473 // TODO: This performs reassociative folds for FP ops. Some fraction of the
3474 // functionality has been subsumed by simple pattern matching here and in
3475 // InstSimplify. We should let a dedicated reassociation pass handle more
3476 // complex pattern matching and remove this from InstCombine.
3477 if (Value *V = FAddCombine(Builder).simplify(&I))
3478 return replaceInstUsesWith(I, V);
3479
3480 // (X - Y) - Op1 --> X - (Y + Op1)
3481 if (match(Op0, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) {
3482 Value *FAdd = Builder.CreateFAddFMF(Y, Op1, &I);
3484 }
3485 }
3486
3487 return nullptr;
3488}
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:857
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 * 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.
const SmallVectorImpl< MachineOperand > & Cond
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
const fltSemantics & getSemantics() const
Definition APFloat.h:1591
opStatus multiply(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1303
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2009
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
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
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
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
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
LLVM_ABI APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1998
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 sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
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
bool isZero() const
Return true if the value is positive or negative zero.
Definition Constants.h:467
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:43
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:155
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
This class represents zero extension of integer types.
CallInst * Call
Changed
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)
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)
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)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
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.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
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:60
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.
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.