1 //===- InstCombineAndOrXor.cpp --------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visitAnd, visitOr, and visitXor functions.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombine.h"
15 #include "llvm/Intrinsics.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/Support/ConstantRange.h"
18 #include "llvm/Support/PatternMatch.h"
20 using namespace PatternMatch
;
23 /// AddOne - Add one to a ConstantInt.
24 static Constant
*AddOne(Constant
*C
) {
25 return ConstantExpr::getAdd(C
, ConstantInt::get(C
->getType(), 1));
27 /// SubOne - Subtract one from a ConstantInt.
28 static Constant
*SubOne(ConstantInt
*C
) {
29 return ConstantInt::get(C
->getContext(), C
->getValue()-1);
32 /// isFreeToInvert - Return true if the specified value is free to invert (apply
33 /// ~ to). This happens in cases where the ~ can be eliminated.
34 static inline bool isFreeToInvert(Value
*V
) {
36 if (BinaryOperator::isNot(V
))
39 // Constants can be considered to be not'ed values.
40 if (isa
<ConstantInt
>(V
))
43 // Compares can be inverted if they have a single use.
44 if (CmpInst
*CI
= dyn_cast
<CmpInst
>(V
))
45 return CI
->hasOneUse();
50 static inline Value
*dyn_castNotVal(Value
*V
) {
51 // If this is not(not(x)) don't return that this is a not: we want the two
52 // not's to be folded first.
53 if (BinaryOperator::isNot(V
)) {
54 Value
*Operand
= BinaryOperator::getNotArgument(V
);
55 if (!isFreeToInvert(Operand
))
59 // Constants can be considered to be not'ed values...
60 if (ConstantInt
*C
= dyn_cast
<ConstantInt
>(V
))
61 return ConstantInt::get(C
->getType(), ~C
->getValue());
66 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
67 /// are carefully arranged to allow folding of expressions such as:
69 /// (A < B) | (A > B) --> (A != B)
71 /// Note that this is only valid if the first and second predicates have the
72 /// same sign. Is illegal to do: (A u< B) | (A s> B)
74 /// Three bits are used to represent the condition, as follows:
79 /// <=> Value Definition
80 /// 000 0 Always false
89 static unsigned getICmpCode(const ICmpInst
*ICI
) {
90 switch (ICI
->getPredicate()) {
92 case ICmpInst::ICMP_UGT
: return 1; // 001
93 case ICmpInst::ICMP_SGT
: return 1; // 001
94 case ICmpInst::ICMP_EQ
: return 2; // 010
95 case ICmpInst::ICMP_UGE
: return 3; // 011
96 case ICmpInst::ICMP_SGE
: return 3; // 011
97 case ICmpInst::ICMP_ULT
: return 4; // 100
98 case ICmpInst::ICMP_SLT
: return 4; // 100
99 case ICmpInst::ICMP_NE
: return 5; // 101
100 case ICmpInst::ICMP_ULE
: return 6; // 110
101 case ICmpInst::ICMP_SLE
: return 6; // 110
104 llvm_unreachable("Invalid ICmp predicate!");
109 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
110 /// predicate into a three bit mask. It also returns whether it is an ordered
111 /// predicate by reference.
112 static unsigned getFCmpCode(FCmpInst::Predicate CC
, bool &isOrdered
) {
115 case FCmpInst::FCMP_ORD
: isOrdered
= true; return 0; // 000
116 case FCmpInst::FCMP_UNO
: return 0; // 000
117 case FCmpInst::FCMP_OGT
: isOrdered
= true; return 1; // 001
118 case FCmpInst::FCMP_UGT
: return 1; // 001
119 case FCmpInst::FCMP_OEQ
: isOrdered
= true; return 2; // 010
120 case FCmpInst::FCMP_UEQ
: return 2; // 010
121 case FCmpInst::FCMP_OGE
: isOrdered
= true; return 3; // 011
122 case FCmpInst::FCMP_UGE
: return 3; // 011
123 case FCmpInst::FCMP_OLT
: isOrdered
= true; return 4; // 100
124 case FCmpInst::FCMP_ULT
: return 4; // 100
125 case FCmpInst::FCMP_ONE
: isOrdered
= true; return 5; // 101
126 case FCmpInst::FCMP_UNE
: return 5; // 101
127 case FCmpInst::FCMP_OLE
: isOrdered
= true; return 6; // 110
128 case FCmpInst::FCMP_ULE
: return 6; // 110
131 // Not expecting FCMP_FALSE and FCMP_TRUE;
132 llvm_unreachable("Unexpected FCmp predicate!");
137 /// getICmpValue - This is the complement of getICmpCode, which turns an
138 /// opcode and two operands into either a constant true or false, or a brand
139 /// new ICmp instruction. The sign is passed in to determine which kind
140 /// of predicate to use in the new icmp instruction.
141 static Value
*getICmpValue(bool Sign
, unsigned Code
, Value
*LHS
, Value
*RHS
,
142 InstCombiner::BuilderTy
*Builder
) {
143 CmpInst::Predicate Pred
;
145 default: assert(0 && "Illegal ICmp code!");
147 return ConstantInt::get(CmpInst::makeCmpResultType(LHS
->getType()), 0);
148 case 1: Pred
= Sign
? ICmpInst::ICMP_SGT
: ICmpInst::ICMP_UGT
; break;
149 case 2: Pred
= ICmpInst::ICMP_EQ
; break;
150 case 3: Pred
= Sign
? ICmpInst::ICMP_SGE
: ICmpInst::ICMP_UGE
; break;
151 case 4: Pred
= Sign
? ICmpInst::ICMP_SLT
: ICmpInst::ICMP_ULT
; break;
152 case 5: Pred
= ICmpInst::ICMP_NE
; break;
153 case 6: Pred
= Sign
? ICmpInst::ICMP_SLE
: ICmpInst::ICMP_ULE
; break;
155 return ConstantInt::get(CmpInst::makeCmpResultType(LHS
->getType()), 1);
157 return Builder
->CreateICmp(Pred
, LHS
, RHS
);
160 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
161 /// opcode and two operands into either a FCmp instruction. isordered is passed
162 /// in to determine which kind of predicate to use in the new fcmp instruction.
163 static Value
*getFCmpValue(bool isordered
, unsigned code
,
164 Value
*LHS
, Value
*RHS
,
165 InstCombiner::BuilderTy
*Builder
) {
166 CmpInst::Predicate Pred
;
168 default: assert(0 && "Illegal FCmp code!");
169 case 0: Pred
= isordered
? FCmpInst::FCMP_ORD
: FCmpInst::FCMP_UNO
; break;
170 case 1: Pred
= isordered
? FCmpInst::FCMP_OGT
: FCmpInst::FCMP_UGT
; break;
171 case 2: Pred
= isordered
? FCmpInst::FCMP_OEQ
: FCmpInst::FCMP_UEQ
; break;
172 case 3: Pred
= isordered
? FCmpInst::FCMP_OGE
: FCmpInst::FCMP_UGE
; break;
173 case 4: Pred
= isordered
? FCmpInst::FCMP_OLT
: FCmpInst::FCMP_ULT
; break;
174 case 5: Pred
= isordered
? FCmpInst::FCMP_ONE
: FCmpInst::FCMP_UNE
; break;
175 case 6: Pred
= isordered
? FCmpInst::FCMP_OLE
: FCmpInst::FCMP_ULE
; break;
177 if (!isordered
) return ConstantInt::getTrue(LHS
->getContext());
178 Pred
= FCmpInst::FCMP_ORD
; break;
180 return Builder
->CreateFCmp(Pred
, LHS
, RHS
);
183 /// PredicatesFoldable - Return true if both predicates match sign or if at
184 /// least one of them is an equality comparison (which is signless).
185 static bool PredicatesFoldable(ICmpInst::Predicate p1
, ICmpInst::Predicate p2
) {
186 return (CmpInst::isSigned(p1
) == CmpInst::isSigned(p2
)) ||
187 (CmpInst::isSigned(p1
) && ICmpInst::isEquality(p2
)) ||
188 (CmpInst::isSigned(p2
) && ICmpInst::isEquality(p1
));
191 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
192 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
193 // guaranteed to be a binary operator.
194 Instruction
*InstCombiner::OptAndOp(Instruction
*Op
,
197 BinaryOperator
&TheAnd
) {
198 Value
*X
= Op
->getOperand(0);
199 Constant
*Together
= 0;
201 Together
= ConstantExpr::getAnd(AndRHS
, OpRHS
);
203 switch (Op
->getOpcode()) {
204 case Instruction::Xor
:
205 if (Op
->hasOneUse()) {
206 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
207 Value
*And
= Builder
->CreateAnd(X
, AndRHS
);
209 return BinaryOperator::CreateXor(And
, Together
);
212 case Instruction::Or
:
213 if (Op
->hasOneUse()){
214 if (Together
!= OpRHS
) {
215 // (X | C1) & C2 --> (X | (C1&C2)) & C2
216 Value
*Or
= Builder
->CreateOr(X
, Together
);
218 return BinaryOperator::CreateAnd(Or
, AndRHS
);
221 ConstantInt
*TogetherCI
= dyn_cast
<ConstantInt
>(Together
);
222 if (TogetherCI
&& !TogetherCI
->isZero()){
223 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
224 // NOTE: This reduces the number of bits set in the & mask, which
225 // can expose opportunities for store narrowing.
226 Together
= ConstantExpr::getXor(AndRHS
, Together
);
227 Value
*And
= Builder
->CreateAnd(X
, Together
);
229 return BinaryOperator::CreateOr(And
, OpRHS
);
234 case Instruction::Add
:
235 if (Op
->hasOneUse()) {
236 // Adding a one to a single bit bit-field should be turned into an XOR
237 // of the bit. First thing to check is to see if this AND is with a
238 // single bit constant.
239 const APInt
&AndRHSV
= cast
<ConstantInt
>(AndRHS
)->getValue();
241 // If there is only one bit set.
242 if (AndRHSV
.isPowerOf2()) {
243 // Ok, at this point, we know that we are masking the result of the
244 // ADD down to exactly one bit. If the constant we are adding has
245 // no bits set below this bit, then we can eliminate the ADD.
246 const APInt
& AddRHS
= cast
<ConstantInt
>(OpRHS
)->getValue();
248 // Check to see if any bits below the one bit set in AndRHSV are set.
249 if ((AddRHS
& (AndRHSV
-1)) == 0) {
250 // If not, the only thing that can effect the output of the AND is
251 // the bit specified by AndRHSV. If that bit is set, the effect of
252 // the XOR is to toggle the bit. If it is clear, then the ADD has
254 if ((AddRHS
& AndRHSV
) == 0) { // Bit is not set, noop
255 TheAnd
.setOperand(0, X
);
258 // Pull the XOR out of the AND.
259 Value
*NewAnd
= Builder
->CreateAnd(X
, AndRHS
);
260 NewAnd
->takeName(Op
);
261 return BinaryOperator::CreateXor(NewAnd
, AndRHS
);
268 case Instruction::Shl
: {
269 // We know that the AND will not produce any of the bits shifted in, so if
270 // the anded constant includes them, clear them now!
272 uint32_t BitWidth
= AndRHS
->getType()->getBitWidth();
273 uint32_t OpRHSVal
= OpRHS
->getLimitedValue(BitWidth
);
274 APInt
ShlMask(APInt::getHighBitsSet(BitWidth
, BitWidth
-OpRHSVal
));
275 ConstantInt
*CI
= ConstantInt::get(AndRHS
->getContext(),
276 AndRHS
->getValue() & ShlMask
);
278 if (CI
->getValue() == ShlMask
)
279 // Masking out bits that the shift already masks.
280 return ReplaceInstUsesWith(TheAnd
, Op
); // No need for the and.
282 if (CI
!= AndRHS
) { // Reducing bits set in and.
283 TheAnd
.setOperand(1, CI
);
288 case Instruction::LShr
: {
289 // We know that the AND will not produce any of the bits shifted in, so if
290 // the anded constant includes them, clear them now! This only applies to
291 // unsigned shifts, because a signed shr may bring in set bits!
293 uint32_t BitWidth
= AndRHS
->getType()->getBitWidth();
294 uint32_t OpRHSVal
= OpRHS
->getLimitedValue(BitWidth
);
295 APInt
ShrMask(APInt::getLowBitsSet(BitWidth
, BitWidth
- OpRHSVal
));
296 ConstantInt
*CI
= ConstantInt::get(Op
->getContext(),
297 AndRHS
->getValue() & ShrMask
);
299 if (CI
->getValue() == ShrMask
)
300 // Masking out bits that the shift already masks.
301 return ReplaceInstUsesWith(TheAnd
, Op
);
304 TheAnd
.setOperand(1, CI
); // Reduce bits set in and cst.
309 case Instruction::AShr
:
311 // See if this is shifting in some sign extension, then masking it out
313 if (Op
->hasOneUse()) {
314 uint32_t BitWidth
= AndRHS
->getType()->getBitWidth();
315 uint32_t OpRHSVal
= OpRHS
->getLimitedValue(BitWidth
);
316 APInt
ShrMask(APInt::getLowBitsSet(BitWidth
, BitWidth
- OpRHSVal
));
317 Constant
*C
= ConstantInt::get(Op
->getContext(),
318 AndRHS
->getValue() & ShrMask
);
319 if (C
== AndRHS
) { // Masking out bits shifted in.
320 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
321 // Make the argument unsigned.
322 Value
*ShVal
= Op
->getOperand(0);
323 ShVal
= Builder
->CreateLShr(ShVal
, OpRHS
, Op
->getName());
324 return BinaryOperator::CreateAnd(ShVal
, AndRHS
, TheAnd
.getName());
333 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
334 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
335 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
336 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
337 /// insert new instructions.
338 Value
*InstCombiner::InsertRangeTest(Value
*V
, Constant
*Lo
, Constant
*Hi
,
339 bool isSigned
, bool Inside
) {
340 assert(cast
<ConstantInt
>(ConstantExpr::getICmp((isSigned
?
341 ICmpInst::ICMP_SLE
:ICmpInst::ICMP_ULE
), Lo
, Hi
))->getZExtValue() &&
342 "Lo is not <= Hi in range emission code!");
345 if (Lo
== Hi
) // Trivially false.
346 return ConstantInt::getFalse(V
->getContext());
348 // V >= Min && V < Hi --> V < Hi
349 if (cast
<ConstantInt
>(Lo
)->isMinValue(isSigned
)) {
350 ICmpInst::Predicate pred
= (isSigned
?
351 ICmpInst::ICMP_SLT
: ICmpInst::ICMP_ULT
);
352 return Builder
->CreateICmp(pred
, V
, Hi
);
355 // Emit V-Lo <u Hi-Lo
356 Constant
*NegLo
= ConstantExpr::getNeg(Lo
);
357 Value
*Add
= Builder
->CreateAdd(V
, NegLo
, V
->getName()+".off");
358 Constant
*UpperBound
= ConstantExpr::getAdd(NegLo
, Hi
);
359 return Builder
->CreateICmpULT(Add
, UpperBound
);
362 if (Lo
== Hi
) // Trivially true.
363 return ConstantInt::getTrue(V
->getContext());
365 // V < Min || V >= Hi -> V > Hi-1
366 Hi
= SubOne(cast
<ConstantInt
>(Hi
));
367 if (cast
<ConstantInt
>(Lo
)->isMinValue(isSigned
)) {
368 ICmpInst::Predicate pred
= (isSigned
?
369 ICmpInst::ICMP_SGT
: ICmpInst::ICMP_UGT
);
370 return Builder
->CreateICmp(pred
, V
, Hi
);
373 // Emit V-Lo >u Hi-1-Lo
374 // Note that Hi has already had one subtracted from it, above.
375 ConstantInt
*NegLo
= cast
<ConstantInt
>(ConstantExpr::getNeg(Lo
));
376 Value
*Add
= Builder
->CreateAdd(V
, NegLo
, V
->getName()+".off");
377 Constant
*LowerBound
= ConstantExpr::getAdd(NegLo
, Hi
);
378 return Builder
->CreateICmpUGT(Add
, LowerBound
);
381 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
382 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
383 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
384 // not, since all 1s are not contiguous.
385 static bool isRunOfOnes(ConstantInt
*Val
, uint32_t &MB
, uint32_t &ME
) {
386 const APInt
& V
= Val
->getValue();
387 uint32_t BitWidth
= Val
->getType()->getBitWidth();
388 if (!APIntOps::isShiftedMask(BitWidth
, V
)) return false;
390 // look for the first zero bit after the run of ones
391 MB
= BitWidth
- ((V
- 1) ^ V
).countLeadingZeros();
392 // look for the first non-zero bit
393 ME
= V
.getActiveBits();
397 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
398 /// where isSub determines whether the operator is a sub. If we can fold one of
399 /// the following xforms:
401 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
402 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
403 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
405 /// return (A +/- B).
407 Value
*InstCombiner::FoldLogicalPlusAnd(Value
*LHS
, Value
*RHS
,
408 ConstantInt
*Mask
, bool isSub
,
410 Instruction
*LHSI
= dyn_cast
<Instruction
>(LHS
);
411 if (!LHSI
|| LHSI
->getNumOperands() != 2 ||
412 !isa
<ConstantInt
>(LHSI
->getOperand(1))) return 0;
414 ConstantInt
*N
= cast
<ConstantInt
>(LHSI
->getOperand(1));
416 switch (LHSI
->getOpcode()) {
418 case Instruction::And
:
419 if (ConstantExpr::getAnd(N
, Mask
) == Mask
) {
420 // If the AndRHS is a power of two minus one (0+1+), this is simple.
421 if ((Mask
->getValue().countLeadingZeros() +
422 Mask
->getValue().countPopulation()) ==
423 Mask
->getValue().getBitWidth())
426 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
427 // part, we don't need any explicit masks to take them out of A. If that
428 // is all N is, ignore it.
429 uint32_t MB
= 0, ME
= 0;
430 if (isRunOfOnes(Mask
, MB
, ME
)) { // begin/end bit of run, inclusive
431 uint32_t BitWidth
= cast
<IntegerType
>(RHS
->getType())->getBitWidth();
432 APInt
Mask(APInt::getLowBitsSet(BitWidth
, MB
-1));
433 if (MaskedValueIsZero(RHS
, Mask
))
438 case Instruction::Or
:
439 case Instruction::Xor
:
440 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
441 if ((Mask
->getValue().countLeadingZeros() +
442 Mask
->getValue().countPopulation()) == Mask
->getValue().getBitWidth()
443 && ConstantExpr::getAnd(N
, Mask
)->isNullValue())
449 return Builder
->CreateSub(LHSI
->getOperand(0), RHS
, "fold");
450 return Builder
->CreateAdd(LHSI
->getOperand(0), RHS
, "fold");
453 /// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
454 /// One of A and B is considered the mask, the other the value. This is
455 /// described as the "AMask" or "BMask" part of the enum. If the enum
456 /// contains only "Mask", then both A and B can be considered masks.
457 /// If A is the mask, then it was proven, that (A & C) == C. This
458 /// is trivial if C == A, or C == 0. If both A and C are constants, this
459 /// proof is also easy.
460 /// For the following explanations we assume that A is the mask.
461 /// The part "AllOnes" declares, that the comparison is true only
462 /// if (A & B) == A, or all bits of A are set in B.
463 /// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
464 /// The part "AllZeroes" declares, that the comparison is true only
465 /// if (A & B) == 0, or all bits of A are cleared in B.
466 /// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
467 /// The part "Mixed" declares, that (A & B) == C and C might or might not
468 /// contain any number of one bits and zero bits.
469 /// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
470 /// The Part "Not" means, that in above descriptions "==" should be replaced
472 /// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
473 /// If the mask A contains a single bit, then the following is equivalent:
474 /// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
475 /// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
476 enum MaskedICmpType
{
477 FoldMskICmp_AMask_AllOnes
= 1,
478 FoldMskICmp_AMask_NotAllOnes
= 2,
479 FoldMskICmp_BMask_AllOnes
= 4,
480 FoldMskICmp_BMask_NotAllOnes
= 8,
481 FoldMskICmp_Mask_AllZeroes
= 16,
482 FoldMskICmp_Mask_NotAllZeroes
= 32,
483 FoldMskICmp_AMask_Mixed
= 64,
484 FoldMskICmp_AMask_NotMixed
= 128,
485 FoldMskICmp_BMask_Mixed
= 256,
486 FoldMskICmp_BMask_NotMixed
= 512
489 /// return the set of pattern classes (from MaskedICmpType)
490 /// that (icmp SCC (A & B), C) satisfies
491 static unsigned getTypeOfMaskedICmp(Value
* A
, Value
* B
, Value
* C
,
492 ICmpInst::Predicate SCC
)
494 ConstantInt
*ACst
= dyn_cast
<ConstantInt
>(A
);
495 ConstantInt
*BCst
= dyn_cast
<ConstantInt
>(B
);
496 ConstantInt
*CCst
= dyn_cast
<ConstantInt
>(C
);
497 bool icmp_eq
= (SCC
== ICmpInst::ICMP_EQ
);
498 bool icmp_abit
= (ACst
!= 0 && !ACst
->isZero() &&
499 ACst
->getValue().isPowerOf2());
500 bool icmp_bbit
= (BCst
!= 0 && !BCst
->isZero() &&
501 BCst
->getValue().isPowerOf2());
503 if (CCst
!= 0 && CCst
->isZero()) {
504 // if C is zero, then both A and B qualify as mask
505 result
|= (icmp_eq
? (FoldMskICmp_Mask_AllZeroes
|
506 FoldMskICmp_Mask_AllZeroes
|
507 FoldMskICmp_AMask_Mixed
|
508 FoldMskICmp_BMask_Mixed
)
509 : (FoldMskICmp_Mask_NotAllZeroes
|
510 FoldMskICmp_Mask_NotAllZeroes
|
511 FoldMskICmp_AMask_NotMixed
|
512 FoldMskICmp_BMask_NotMixed
));
514 result
|= (icmp_eq
? (FoldMskICmp_AMask_NotAllOnes
|
515 FoldMskICmp_AMask_NotMixed
)
516 : (FoldMskICmp_AMask_AllOnes
|
517 FoldMskICmp_AMask_Mixed
));
519 result
|= (icmp_eq
? (FoldMskICmp_BMask_NotAllOnes
|
520 FoldMskICmp_BMask_NotMixed
)
521 : (FoldMskICmp_BMask_AllOnes
|
522 FoldMskICmp_BMask_Mixed
));
526 result
|= (icmp_eq
? (FoldMskICmp_AMask_AllOnes
|
527 FoldMskICmp_AMask_Mixed
)
528 : (FoldMskICmp_AMask_NotAllOnes
|
529 FoldMskICmp_AMask_NotMixed
));
531 result
|= (icmp_eq
? (FoldMskICmp_Mask_NotAllZeroes
|
532 FoldMskICmp_AMask_NotMixed
)
533 : (FoldMskICmp_Mask_AllZeroes
|
534 FoldMskICmp_AMask_Mixed
));
536 else if (ACst
!= 0 && CCst
!= 0 &&
537 ConstantExpr::getAnd(ACst
, CCst
) == CCst
) {
538 result
|= (icmp_eq
? FoldMskICmp_AMask_Mixed
539 : FoldMskICmp_AMask_NotMixed
);
543 result
|= (icmp_eq
? (FoldMskICmp_BMask_AllOnes
|
544 FoldMskICmp_BMask_Mixed
)
545 : (FoldMskICmp_BMask_NotAllOnes
|
546 FoldMskICmp_BMask_NotMixed
));
548 result
|= (icmp_eq
? (FoldMskICmp_Mask_NotAllZeroes
|
549 FoldMskICmp_BMask_NotMixed
)
550 : (FoldMskICmp_Mask_AllZeroes
|
551 FoldMskICmp_BMask_Mixed
));
553 else if (BCst
!= 0 && CCst
!= 0 &&
554 ConstantExpr::getAnd(BCst
, CCst
) == CCst
) {
555 result
|= (icmp_eq
? FoldMskICmp_BMask_Mixed
556 : FoldMskICmp_BMask_NotMixed
);
561 /// foldLogOpOfMaskedICmpsHelper:
562 /// handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
563 /// return the set of pattern classes (from MaskedICmpType)
564 /// that both LHS and RHS satisfy
565 static unsigned foldLogOpOfMaskedICmpsHelper(Value
*& A
,
566 Value
*& B
, Value
*& C
,
567 Value
*& D
, Value
*& E
,
568 ICmpInst
*LHS
, ICmpInst
*RHS
) {
569 ICmpInst::Predicate LHSCC
= LHS
->getPredicate(), RHSCC
= RHS
->getPredicate();
570 if (LHSCC
!= ICmpInst::ICMP_EQ
&& LHSCC
!= ICmpInst::ICMP_NE
) return 0;
571 if (RHSCC
!= ICmpInst::ICMP_EQ
&& RHSCC
!= ICmpInst::ICMP_NE
) return 0;
572 if (LHS
->getOperand(0)->getType() != RHS
->getOperand(0)->getType()) return 0;
573 // vectors are not (yet?) supported
574 if (LHS
->getOperand(0)->getType()->isVectorTy()) return 0;
576 // Here comes the tricky part:
577 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
578 // and L11 & L12 == L21 & L22. The same goes for RHS.
579 // Now we must find those components L** and R**, that are equal, so
580 // that we can extract the parameters A, B, C, D, and E for the canonical
582 Value
*L1
= LHS
->getOperand(0);
583 Value
*L2
= LHS
->getOperand(1);
584 Value
*L11
,*L12
,*L21
,*L22
;
585 if (match(L1
, m_And(m_Value(L11
), m_Value(L12
)))) {
586 if (!match(L2
, m_And(m_Value(L21
), m_Value(L22
))))
590 if (!match(L2
, m_And(m_Value(L11
), m_Value(L12
))))
596 Value
*R1
= RHS
->getOperand(0);
597 Value
*R2
= RHS
->getOperand(1);
600 if (match(R1
, m_And(m_Value(R11
), m_Value(R12
)))) {
601 if (R11
!= 0 && (R11
== L11
|| R11
== L12
|| R11
== L21
|| R11
== L22
)) {
602 A
= R11
; D
= R12
; E
= R2
; ok
= true;
605 if (R12
!= 0 && (R12
== L11
|| R12
== L12
|| R12
== L21
|| R12
== L22
)) {
606 A
= R12
; D
= R11
; E
= R2
; ok
= true;
609 if (!ok
&& match(R2
, m_And(m_Value(R11
), m_Value(R12
)))) {
610 if (R11
!= 0 && (R11
== L11
|| R11
== L12
|| R11
== L21
|| R11
== L22
)) {
611 A
= R11
; D
= R12
; E
= R1
; ok
= true;
614 if (R12
!= 0 && (R12
== L11
|| R12
== L12
|| R12
== L21
|| R12
== L22
)) {
615 A
= R12
; D
= R11
; E
= R1
; ok
= true;
636 unsigned left_type
= getTypeOfMaskedICmp(A
, B
, C
, LHSCC
);
637 unsigned right_type
= getTypeOfMaskedICmp(A
, D
, E
, RHSCC
);
638 return left_type
& right_type
;
640 /// foldLogOpOfMaskedICmps:
641 /// try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
642 /// into a single (icmp(A & X) ==/!= Y)
643 static Value
* foldLogOpOfMaskedICmps(ICmpInst
*LHS
, ICmpInst
*RHS
,
644 ICmpInst::Predicate NEWCC
,
645 llvm::InstCombiner::BuilderTy
* Builder
) {
646 Value
*A
= 0, *B
= 0, *C
= 0, *D
= 0, *E
= 0;
647 unsigned mask
= foldLogOpOfMaskedICmpsHelper(A
, B
, C
, D
, E
, LHS
, RHS
);
648 if (mask
== 0) return 0;
650 if (NEWCC
== ICmpInst::ICMP_NE
)
651 mask
>>= 1; // treat "Not"-states as normal states
653 if (mask
& FoldMskICmp_Mask_AllZeroes
) {
654 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
655 // -> (icmp eq (A & (B|D)), 0)
656 Value
* newOr
= Builder
->CreateOr(B
, D
);
657 Value
* newAnd
= Builder
->CreateAnd(A
, newOr
);
658 // we can't use C as zero, because we might actually handle
659 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
660 // with B and D, having a single bit set
661 Value
* zero
= Constant::getNullValue(A
->getType());
662 return Builder
->CreateICmp(NEWCC
, newAnd
, zero
);
664 else if (mask
& FoldMskICmp_BMask_AllOnes
) {
665 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
666 // -> (icmp eq (A & (B|D)), (B|D))
667 Value
* newOr
= Builder
->CreateOr(B
, D
);
668 Value
* newAnd
= Builder
->CreateAnd(A
, newOr
);
669 return Builder
->CreateICmp(NEWCC
, newAnd
, newOr
);
671 else if (mask
& FoldMskICmp_AMask_AllOnes
) {
672 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
673 // -> (icmp eq (A & (B&D)), A)
674 Value
* newAnd1
= Builder
->CreateAnd(B
, D
);
675 Value
* newAnd
= Builder
->CreateAnd(A
, newAnd1
);
676 return Builder
->CreateICmp(NEWCC
, newAnd
, A
);
678 else if (mask
& FoldMskICmp_BMask_Mixed
) {
679 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
680 // We already know that B & C == C && D & E == E.
681 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
682 // C and E, which are shared by both the mask B and the mask D, don't
683 // contradict, then we can transform to
684 // -> (icmp eq (A & (B|D)), (C|E))
685 // Currently, we only handle the case of B, C, D, and E being constant.
686 ConstantInt
*BCst
= dyn_cast
<ConstantInt
>(B
);
687 if (BCst
== 0) return 0;
688 ConstantInt
*DCst
= dyn_cast
<ConstantInt
>(D
);
689 if (DCst
== 0) return 0;
690 // we can't simply use C and E, because we might actually handle
691 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
692 // with B and D, having a single bit set
694 ConstantInt
*CCst
= dyn_cast
<ConstantInt
>(C
);
695 if (CCst
== 0) return 0;
696 if (LHS
->getPredicate() != NEWCC
)
697 CCst
= dyn_cast
<ConstantInt
>( ConstantExpr::getXor(BCst
, CCst
) );
698 ConstantInt
*ECst
= dyn_cast
<ConstantInt
>(E
);
699 if (ECst
== 0) return 0;
700 if (RHS
->getPredicate() != NEWCC
)
701 ECst
= dyn_cast
<ConstantInt
>( ConstantExpr::getXor(DCst
, ECst
) );
702 ConstantInt
* MCst
= dyn_cast
<ConstantInt
>(
703 ConstantExpr::getAnd(ConstantExpr::getAnd(BCst
, DCst
),
704 ConstantExpr::getXor(CCst
, ECst
)) );
705 // if there is a conflict we should actually return a false for the
709 Value
*newOr1
= Builder
->CreateOr(B
, D
);
710 Value
*newOr2
= ConstantExpr::getOr(CCst
, ECst
);
711 Value
*newAnd
= Builder
->CreateAnd(A
, newOr1
);
712 return Builder
->CreateICmp(NEWCC
, newAnd
, newOr2
);
717 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
718 Value
*InstCombiner::FoldAndOfICmps(ICmpInst
*LHS
, ICmpInst
*RHS
) {
719 ICmpInst::Predicate LHSCC
= LHS
->getPredicate(), RHSCC
= RHS
->getPredicate();
721 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
722 if (PredicatesFoldable(LHSCC
, RHSCC
)) {
723 if (LHS
->getOperand(0) == RHS
->getOperand(1) &&
724 LHS
->getOperand(1) == RHS
->getOperand(0))
726 if (LHS
->getOperand(0) == RHS
->getOperand(0) &&
727 LHS
->getOperand(1) == RHS
->getOperand(1)) {
728 Value
*Op0
= LHS
->getOperand(0), *Op1
= LHS
->getOperand(1);
729 unsigned Code
= getICmpCode(LHS
) & getICmpCode(RHS
);
730 bool isSigned
= LHS
->isSigned() || RHS
->isSigned();
731 return getICmpValue(isSigned
, Code
, Op0
, Op1
, Builder
);
735 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
736 if (Value
*V
= foldLogOpOfMaskedICmps(LHS
, RHS
, ICmpInst::ICMP_EQ
, Builder
))
739 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
740 Value
*Val
= LHS
->getOperand(0), *Val2
= RHS
->getOperand(0);
741 ConstantInt
*LHSCst
= dyn_cast
<ConstantInt
>(LHS
->getOperand(1));
742 ConstantInt
*RHSCst
= dyn_cast
<ConstantInt
>(RHS
->getOperand(1));
743 if (LHSCst
== 0 || RHSCst
== 0) return 0;
745 if (LHSCst
== RHSCst
&& LHSCC
== RHSCC
) {
746 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
747 // where C is a power of 2
748 if (LHSCC
== ICmpInst::ICMP_ULT
&&
749 LHSCst
->getValue().isPowerOf2()) {
750 Value
*NewOr
= Builder
->CreateOr(Val
, Val2
);
751 return Builder
->CreateICmp(LHSCC
, NewOr
, LHSCst
);
754 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
755 if (LHSCC
== ICmpInst::ICMP_EQ
&& LHSCst
->isZero()) {
756 Value
*NewOr
= Builder
->CreateOr(Val
, Val2
);
757 return Builder
->CreateICmp(LHSCC
, NewOr
, LHSCst
);
760 // (icmp slt A, 0) & (icmp slt B, 0) --> (icmp slt (A&B), 0)
761 if (LHSCC
== ICmpInst::ICMP_SLT
&& LHSCst
->isZero()) {
762 Value
*NewAnd
= Builder
->CreateAnd(Val
, Val2
);
763 return Builder
->CreateICmp(LHSCC
, NewAnd
, LHSCst
);
766 // (icmp sgt A, -1) & (icmp sgt B, -1) --> (icmp sgt (A|B), -1)
767 if (LHSCC
== ICmpInst::ICMP_SGT
&& LHSCst
->isAllOnesValue()) {
768 Value
*NewOr
= Builder
->CreateOr(Val
, Val2
);
769 return Builder
->CreateICmp(LHSCC
, NewOr
, LHSCst
);
773 // From here on, we only handle:
774 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
775 if (Val
!= Val2
) return 0;
777 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
778 if (LHSCC
== ICmpInst::ICMP_UGE
|| LHSCC
== ICmpInst::ICMP_ULE
||
779 RHSCC
== ICmpInst::ICMP_UGE
|| RHSCC
== ICmpInst::ICMP_ULE
||
780 LHSCC
== ICmpInst::ICMP_SGE
|| LHSCC
== ICmpInst::ICMP_SLE
||
781 RHSCC
== ICmpInst::ICMP_SGE
|| RHSCC
== ICmpInst::ICMP_SLE
)
784 // Make a constant range that's the intersection of the two icmp ranges.
785 // If the intersection is empty, we know that the result is false.
786 ConstantRange LHSRange
=
787 ConstantRange::makeICmpRegion(LHSCC
, LHSCst
->getValue());
788 ConstantRange RHSRange
=
789 ConstantRange::makeICmpRegion(RHSCC
, RHSCst
->getValue());
791 if (LHSRange
.intersectWith(RHSRange
).isEmptySet())
792 return ConstantInt::get(CmpInst::makeCmpResultType(LHS
->getType()), 0);
794 // We can't fold (ugt x, C) & (sgt x, C2).
795 if (!PredicatesFoldable(LHSCC
, RHSCC
))
798 // Ensure that the larger constant is on the RHS.
800 if (CmpInst::isSigned(LHSCC
) ||
801 (ICmpInst::isEquality(LHSCC
) &&
802 CmpInst::isSigned(RHSCC
)))
803 ShouldSwap
= LHSCst
->getValue().sgt(RHSCst
->getValue());
805 ShouldSwap
= LHSCst
->getValue().ugt(RHSCst
->getValue());
809 std::swap(LHSCst
, RHSCst
);
810 std::swap(LHSCC
, RHSCC
);
813 // At this point, we know we have two icmp instructions
814 // comparing a value against two constants and and'ing the result
815 // together. Because of the above check, we know that we only have
816 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
817 // (from the icmp folding check above), that the two constants
818 // are not equal and that the larger constant is on the RHS
819 assert(LHSCst
!= RHSCst
&& "Compares not folded above?");
822 default: llvm_unreachable("Unknown integer condition code!");
823 case ICmpInst::ICMP_EQ
:
825 default: llvm_unreachable("Unknown integer condition code!");
826 case ICmpInst::ICMP_NE
: // (X == 13 & X != 15) -> X == 13
827 case ICmpInst::ICMP_ULT
: // (X == 13 & X < 15) -> X == 13
828 case ICmpInst::ICMP_SLT
: // (X == 13 & X < 15) -> X == 13
831 case ICmpInst::ICMP_NE
:
833 default: llvm_unreachable("Unknown integer condition code!");
834 case ICmpInst::ICMP_ULT
:
835 if (LHSCst
== SubOne(RHSCst
)) // (X != 13 & X u< 14) -> X < 13
836 return Builder
->CreateICmpULT(Val
, LHSCst
);
837 break; // (X != 13 & X u< 15) -> no change
838 case ICmpInst::ICMP_SLT
:
839 if (LHSCst
== SubOne(RHSCst
)) // (X != 13 & X s< 14) -> X < 13
840 return Builder
->CreateICmpSLT(Val
, LHSCst
);
841 break; // (X != 13 & X s< 15) -> no change
842 case ICmpInst::ICMP_EQ
: // (X != 13 & X == 15) -> X == 15
843 case ICmpInst::ICMP_UGT
: // (X != 13 & X u> 15) -> X u> 15
844 case ICmpInst::ICMP_SGT
: // (X != 13 & X s> 15) -> X s> 15
846 case ICmpInst::ICMP_NE
:
847 if (LHSCst
== SubOne(RHSCst
)){// (X != 13 & X != 14) -> X-13 >u 1
848 Constant
*AddCST
= ConstantExpr::getNeg(LHSCst
);
849 Value
*Add
= Builder
->CreateAdd(Val
, AddCST
, Val
->getName()+".off");
850 return Builder
->CreateICmpUGT(Add
, ConstantInt::get(Add
->getType(), 1));
852 break; // (X != 13 & X != 15) -> no change
855 case ICmpInst::ICMP_ULT
:
857 default: llvm_unreachable("Unknown integer condition code!");
858 case ICmpInst::ICMP_EQ
: // (X u< 13 & X == 15) -> false
859 case ICmpInst::ICMP_UGT
: // (X u< 13 & X u> 15) -> false
860 return ConstantInt::get(CmpInst::makeCmpResultType(LHS
->getType()), 0);
861 case ICmpInst::ICMP_SGT
: // (X u< 13 & X s> 15) -> no change
863 case ICmpInst::ICMP_NE
: // (X u< 13 & X != 15) -> X u< 13
864 case ICmpInst::ICMP_ULT
: // (X u< 13 & X u< 15) -> X u< 13
866 case ICmpInst::ICMP_SLT
: // (X u< 13 & X s< 15) -> no change
870 case ICmpInst::ICMP_SLT
:
872 default: llvm_unreachable("Unknown integer condition code!");
873 case ICmpInst::ICMP_UGT
: // (X s< 13 & X u> 15) -> no change
875 case ICmpInst::ICMP_NE
: // (X s< 13 & X != 15) -> X < 13
876 case ICmpInst::ICMP_SLT
: // (X s< 13 & X s< 15) -> X < 13
878 case ICmpInst::ICMP_ULT
: // (X s< 13 & X u< 15) -> no change
882 case ICmpInst::ICMP_UGT
:
884 default: llvm_unreachable("Unknown integer condition code!");
885 case ICmpInst::ICMP_EQ
: // (X u> 13 & X == 15) -> X == 15
886 case ICmpInst::ICMP_UGT
: // (X u> 13 & X u> 15) -> X u> 15
888 case ICmpInst::ICMP_SGT
: // (X u> 13 & X s> 15) -> no change
890 case ICmpInst::ICMP_NE
:
891 if (RHSCst
== AddOne(LHSCst
)) // (X u> 13 & X != 14) -> X u> 14
892 return Builder
->CreateICmp(LHSCC
, Val
, RHSCst
);
893 break; // (X u> 13 & X != 15) -> no change
894 case ICmpInst::ICMP_ULT
: // (X u> 13 & X u< 15) -> (X-14) <u 1
895 return InsertRangeTest(Val
, AddOne(LHSCst
), RHSCst
, false, true);
896 case ICmpInst::ICMP_SLT
: // (X u> 13 & X s< 15) -> no change
900 case ICmpInst::ICMP_SGT
:
902 default: llvm_unreachable("Unknown integer condition code!");
903 case ICmpInst::ICMP_EQ
: // (X s> 13 & X == 15) -> X == 15
904 case ICmpInst::ICMP_SGT
: // (X s> 13 & X s> 15) -> X s> 15
906 case ICmpInst::ICMP_UGT
: // (X s> 13 & X u> 15) -> no change
908 case ICmpInst::ICMP_NE
:
909 if (RHSCst
== AddOne(LHSCst
)) // (X s> 13 & X != 14) -> X s> 14
910 return Builder
->CreateICmp(LHSCC
, Val
, RHSCst
);
911 break; // (X s> 13 & X != 15) -> no change
912 case ICmpInst::ICMP_SLT
: // (X s> 13 & X s< 15) -> (X-14) s< 1
913 return InsertRangeTest(Val
, AddOne(LHSCst
), RHSCst
, true, true);
914 case ICmpInst::ICMP_ULT
: // (X s> 13 & X u< 15) -> no change
923 /// FoldAndOfFCmps - Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of
924 /// instcombine, this returns a Value which should already be inserted into the
926 Value
*InstCombiner::FoldAndOfFCmps(FCmpInst
*LHS
, FCmpInst
*RHS
) {
927 if (LHS
->getPredicate() == FCmpInst::FCMP_ORD
&&
928 RHS
->getPredicate() == FCmpInst::FCMP_ORD
) {
929 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
930 if (ConstantFP
*LHSC
= dyn_cast
<ConstantFP
>(LHS
->getOperand(1)))
931 if (ConstantFP
*RHSC
= dyn_cast
<ConstantFP
>(RHS
->getOperand(1))) {
932 // If either of the constants are nans, then the whole thing returns
934 if (LHSC
->getValueAPF().isNaN() || RHSC
->getValueAPF().isNaN())
935 return ConstantInt::getFalse(LHS
->getContext());
936 return Builder
->CreateFCmpORD(LHS
->getOperand(0), RHS
->getOperand(0));
939 // Handle vector zeros. This occurs because the canonical form of
940 // "fcmp ord x,x" is "fcmp ord x, 0".
941 if (isa
<ConstantAggregateZero
>(LHS
->getOperand(1)) &&
942 isa
<ConstantAggregateZero
>(RHS
->getOperand(1)))
943 return Builder
->CreateFCmpORD(LHS
->getOperand(0), RHS
->getOperand(0));
947 Value
*Op0LHS
= LHS
->getOperand(0), *Op0RHS
= LHS
->getOperand(1);
948 Value
*Op1LHS
= RHS
->getOperand(0), *Op1RHS
= RHS
->getOperand(1);
949 FCmpInst::Predicate Op0CC
= LHS
->getPredicate(), Op1CC
= RHS
->getPredicate();
952 if (Op0LHS
== Op1RHS
&& Op0RHS
== Op1LHS
) {
953 // Swap RHS operands to match LHS.
954 Op1CC
= FCmpInst::getSwappedPredicate(Op1CC
);
955 std::swap(Op1LHS
, Op1RHS
);
958 if (Op0LHS
== Op1LHS
&& Op0RHS
== Op1RHS
) {
959 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
961 return Builder
->CreateFCmp((FCmpInst::Predicate
)Op0CC
, Op0LHS
, Op0RHS
);
962 if (Op0CC
== FCmpInst::FCMP_FALSE
|| Op1CC
== FCmpInst::FCMP_FALSE
)
963 return ConstantInt::get(CmpInst::makeCmpResultType(LHS
->getType()), 0);
964 if (Op0CC
== FCmpInst::FCMP_TRUE
)
966 if (Op1CC
== FCmpInst::FCMP_TRUE
)
971 unsigned Op0Pred
= getFCmpCode(Op0CC
, Op0Ordered
);
972 unsigned Op1Pred
= getFCmpCode(Op1CC
, Op1Ordered
);
975 std::swap(Op0Pred
, Op1Pred
);
976 std::swap(Op0Ordered
, Op1Ordered
);
979 // uno && ueq -> uno && (uno || eq) -> ueq
980 // ord && olt -> ord && (ord && lt) -> olt
981 if (Op0Ordered
== Op1Ordered
)
984 // uno && oeq -> uno && (ord && eq) -> false
985 // uno && ord -> false
987 return ConstantInt::get(CmpInst::makeCmpResultType(LHS
->getType()), 0);
988 // ord && ueq -> ord && (uno || eq) -> oeq
989 return getFCmpValue(true, Op1Pred
, Op0LHS
, Op0RHS
, Builder
);
997 Instruction
*InstCombiner::visitAnd(BinaryOperator
&I
) {
998 bool Changed
= SimplifyAssociativeOrCommutative(I
);
999 Value
*Op0
= I
.getOperand(0), *Op1
= I
.getOperand(1);
1001 if (Value
*V
= SimplifyAndInst(Op0
, Op1
, TD
))
1002 return ReplaceInstUsesWith(I
, V
);
1004 // (A|B)&(A|C) -> A|(B&C) etc
1005 if (Value
*V
= SimplifyUsingDistributiveLaws(I
))
1006 return ReplaceInstUsesWith(I
, V
);
1008 // See if we can simplify any instructions used by the instruction whose sole
1009 // purpose is to compute bits we don't care about.
1010 if (SimplifyDemandedInstructionBits(I
))
1013 if (ConstantInt
*AndRHS
= dyn_cast
<ConstantInt
>(Op1
)) {
1014 const APInt
&AndRHSMask
= AndRHS
->getValue();
1016 // Optimize a variety of ((val OP C1) & C2) combinations...
1017 if (BinaryOperator
*Op0I
= dyn_cast
<BinaryOperator
>(Op0
)) {
1018 Value
*Op0LHS
= Op0I
->getOperand(0);
1019 Value
*Op0RHS
= Op0I
->getOperand(1);
1020 switch (Op0I
->getOpcode()) {
1022 case Instruction::Xor
:
1023 case Instruction::Or
: {
1024 // If the mask is only needed on one incoming arm, push it up.
1025 if (!Op0I
->hasOneUse()) break;
1027 APInt
NotAndRHS(~AndRHSMask
);
1028 if (MaskedValueIsZero(Op0LHS
, NotAndRHS
)) {
1029 // Not masking anything out for the LHS, move to RHS.
1030 Value
*NewRHS
= Builder
->CreateAnd(Op0RHS
, AndRHS
,
1031 Op0RHS
->getName()+".masked");
1032 return BinaryOperator::Create(Op0I
->getOpcode(), Op0LHS
, NewRHS
);
1034 if (!isa
<Constant
>(Op0RHS
) &&
1035 MaskedValueIsZero(Op0RHS
, NotAndRHS
)) {
1036 // Not masking anything out for the RHS, move to LHS.
1037 Value
*NewLHS
= Builder
->CreateAnd(Op0LHS
, AndRHS
,
1038 Op0LHS
->getName()+".masked");
1039 return BinaryOperator::Create(Op0I
->getOpcode(), NewLHS
, Op0RHS
);
1044 case Instruction::Add
:
1045 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1046 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1047 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1048 if (Value
*V
= FoldLogicalPlusAnd(Op0LHS
, Op0RHS
, AndRHS
, false, I
))
1049 return BinaryOperator::CreateAnd(V
, AndRHS
);
1050 if (Value
*V
= FoldLogicalPlusAnd(Op0RHS
, Op0LHS
, AndRHS
, false, I
))
1051 return BinaryOperator::CreateAnd(V
, AndRHS
); // Add commutes
1054 case Instruction::Sub
:
1055 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1056 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1057 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1058 if (Value
*V
= FoldLogicalPlusAnd(Op0LHS
, Op0RHS
, AndRHS
, true, I
))
1059 return BinaryOperator::CreateAnd(V
, AndRHS
);
1061 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1062 // has 1's for all bits that the subtraction with A might affect.
1063 if (Op0I
->hasOneUse() && !match(Op0LHS
, m_Zero())) {
1064 uint32_t BitWidth
= AndRHSMask
.getBitWidth();
1065 uint32_t Zeros
= AndRHSMask
.countLeadingZeros();
1066 APInt Mask
= APInt::getLowBitsSet(BitWidth
, BitWidth
- Zeros
);
1068 if (MaskedValueIsZero(Op0LHS
, Mask
)) {
1069 Value
*NewNeg
= Builder
->CreateNeg(Op0RHS
);
1070 return BinaryOperator::CreateAnd(NewNeg
, AndRHS
);
1075 case Instruction::Shl
:
1076 case Instruction::LShr
:
1077 // (1 << x) & 1 --> zext(x == 0)
1078 // (1 >> x) & 1 --> zext(x == 0)
1079 if (AndRHSMask
== 1 && Op0LHS
== AndRHS
) {
1081 Builder
->CreateICmpEQ(Op0RHS
, Constant::getNullValue(I
.getType()));
1082 return new ZExtInst(NewICmp
, I
.getType());
1087 if (ConstantInt
*Op0CI
= dyn_cast
<ConstantInt
>(Op0I
->getOperand(1)))
1088 if (Instruction
*Res
= OptAndOp(Op0I
, Op0CI
, AndRHS
, I
))
1092 // If this is an integer truncation, and if the source is an 'and' with
1093 // immediate, transform it. This frequently occurs for bitfield accesses.
1095 Value
*X
= 0; ConstantInt
*YC
= 0;
1096 if (match(Op0
, m_Trunc(m_And(m_Value(X
), m_ConstantInt(YC
))))) {
1097 // Change: and (trunc (and X, YC) to T), C2
1098 // into : and (trunc X to T), trunc(YC) & C2
1099 // This will fold the two constants together, which may allow
1100 // other simplifications.
1101 Value
*NewCast
= Builder
->CreateTrunc(X
, I
.getType(), "and.shrunk");
1102 Constant
*C3
= ConstantExpr::getTrunc(YC
, I
.getType());
1103 C3
= ConstantExpr::getAnd(C3
, AndRHS
);
1104 return BinaryOperator::CreateAnd(NewCast
, C3
);
1108 // Try to fold constant and into select arguments.
1109 if (SelectInst
*SI
= dyn_cast
<SelectInst
>(Op0
))
1110 if (Instruction
*R
= FoldOpIntoSelect(I
, SI
))
1112 if (isa
<PHINode
>(Op0
))
1113 if (Instruction
*NV
= FoldOpIntoPhi(I
))
1118 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1119 if (Value
*Op0NotVal
= dyn_castNotVal(Op0
))
1120 if (Value
*Op1NotVal
= dyn_castNotVal(Op1
))
1121 if (Op0
->hasOneUse() && Op1
->hasOneUse()) {
1122 Value
*Or
= Builder
->CreateOr(Op0NotVal
, Op1NotVal
,
1123 I
.getName()+".demorgan");
1124 return BinaryOperator::CreateNot(Or
);
1128 Value
*A
= 0, *B
= 0, *C
= 0, *D
= 0;
1129 // (A|B) & ~(A&B) -> A^B
1130 if (match(Op0
, m_Or(m_Value(A
), m_Value(B
))) &&
1131 match(Op1
, m_Not(m_And(m_Value(C
), m_Value(D
)))) &&
1132 ((A
== C
&& B
== D
) || (A
== D
&& B
== C
)))
1133 return BinaryOperator::CreateXor(A
, B
);
1135 // ~(A&B) & (A|B) -> A^B
1136 if (match(Op1
, m_Or(m_Value(A
), m_Value(B
))) &&
1137 match(Op0
, m_Not(m_And(m_Value(C
), m_Value(D
)))) &&
1138 ((A
== C
&& B
== D
) || (A
== D
&& B
== C
)))
1139 return BinaryOperator::CreateXor(A
, B
);
1141 if (Op0
->hasOneUse() &&
1142 match(Op0
, m_Xor(m_Value(A
), m_Value(B
)))) {
1143 if (A
== Op1
) { // (A^B)&A -> A&(A^B)
1144 I
.swapOperands(); // Simplify below
1145 std::swap(Op0
, Op1
);
1146 } else if (B
== Op1
) { // (A^B)&B -> B&(B^A)
1147 cast
<BinaryOperator
>(Op0
)->swapOperands();
1148 I
.swapOperands(); // Simplify below
1149 std::swap(Op0
, Op1
);
1153 if (Op1
->hasOneUse() &&
1154 match(Op1
, m_Xor(m_Value(A
), m_Value(B
)))) {
1155 if (B
== Op0
) { // B&(A^B) -> B&(B^A)
1156 cast
<BinaryOperator
>(Op1
)->swapOperands();
1159 // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1160 // A is originally -1 (or a vector of -1 and undefs), then we enter
1161 // an endless loop. By checking that A is non-constant we ensure that
1162 // we will never get to the loop.
1163 if (A
== Op0
&& !isa
<Constant
>(A
)) // A&(A^B) -> A & ~B
1164 return BinaryOperator::CreateAnd(A
, Builder
->CreateNot(B
, "tmp"));
1167 // (A&((~A)|B)) -> A&B
1168 if (match(Op0
, m_Or(m_Not(m_Specific(Op1
)), m_Value(A
))) ||
1169 match(Op0
, m_Or(m_Value(A
), m_Not(m_Specific(Op1
)))))
1170 return BinaryOperator::CreateAnd(A
, Op1
);
1171 if (match(Op1
, m_Or(m_Not(m_Specific(Op0
)), m_Value(A
))) ||
1172 match(Op1
, m_Or(m_Value(A
), m_Not(m_Specific(Op0
)))))
1173 return BinaryOperator::CreateAnd(A
, Op0
);
1176 if (ICmpInst
*RHS
= dyn_cast
<ICmpInst
>(Op1
))
1177 if (ICmpInst
*LHS
= dyn_cast
<ICmpInst
>(Op0
))
1178 if (Value
*Res
= FoldAndOfICmps(LHS
, RHS
))
1179 return ReplaceInstUsesWith(I
, Res
);
1181 // If and'ing two fcmp, try combine them into one.
1182 if (FCmpInst
*LHS
= dyn_cast
<FCmpInst
>(I
.getOperand(0)))
1183 if (FCmpInst
*RHS
= dyn_cast
<FCmpInst
>(I
.getOperand(1)))
1184 if (Value
*Res
= FoldAndOfFCmps(LHS
, RHS
))
1185 return ReplaceInstUsesWith(I
, Res
);
1188 // fold (and (cast A), (cast B)) -> (cast (and A, B))
1189 if (CastInst
*Op0C
= dyn_cast
<CastInst
>(Op0
))
1190 if (CastInst
*Op1C
= dyn_cast
<CastInst
>(Op1
)) {
1191 const Type
*SrcTy
= Op0C
->getOperand(0)->getType();
1192 if (Op0C
->getOpcode() == Op1C
->getOpcode() && // same cast kind ?
1193 SrcTy
== Op1C
->getOperand(0)->getType() &&
1194 SrcTy
->isIntOrIntVectorTy()) {
1195 Value
*Op0COp
= Op0C
->getOperand(0), *Op1COp
= Op1C
->getOperand(0);
1197 // Only do this if the casts both really cause code to be generated.
1198 if (ShouldOptimizeCast(Op0C
->getOpcode(), Op0COp
, I
.getType()) &&
1199 ShouldOptimizeCast(Op1C
->getOpcode(), Op1COp
, I
.getType())) {
1200 Value
*NewOp
= Builder
->CreateAnd(Op0COp
, Op1COp
, I
.getName());
1201 return CastInst::Create(Op0C
->getOpcode(), NewOp
, I
.getType());
1204 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1205 // cast is otherwise not optimizable. This happens for vector sexts.
1206 if (ICmpInst
*RHS
= dyn_cast
<ICmpInst
>(Op1COp
))
1207 if (ICmpInst
*LHS
= dyn_cast
<ICmpInst
>(Op0COp
))
1208 if (Value
*Res
= FoldAndOfICmps(LHS
, RHS
))
1209 return CastInst::Create(Op0C
->getOpcode(), Res
, I
.getType());
1211 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1212 // cast is otherwise not optimizable. This happens for vector sexts.
1213 if (FCmpInst
*RHS
= dyn_cast
<FCmpInst
>(Op1COp
))
1214 if (FCmpInst
*LHS
= dyn_cast
<FCmpInst
>(Op0COp
))
1215 if (Value
*Res
= FoldAndOfFCmps(LHS
, RHS
))
1216 return CastInst::Create(Op0C
->getOpcode(), Res
, I
.getType());
1220 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
1221 if (BinaryOperator
*SI1
= dyn_cast
<BinaryOperator
>(Op1
)) {
1222 if (BinaryOperator
*SI0
= dyn_cast
<BinaryOperator
>(Op0
))
1223 if (SI0
->isShift() && SI0
->getOpcode() == SI1
->getOpcode() &&
1224 SI0
->getOperand(1) == SI1
->getOperand(1) &&
1225 (SI0
->hasOneUse() || SI1
->hasOneUse())) {
1227 Builder
->CreateAnd(SI0
->getOperand(0), SI1
->getOperand(0),
1229 return BinaryOperator::Create(SI1
->getOpcode(), NewOp
,
1230 SI1
->getOperand(1));
1234 return Changed
? &I
: 0;
1237 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
1238 /// capable of providing pieces of a bswap. The subexpression provides pieces
1239 /// of a bswap if it is proven that each of the non-zero bytes in the output of
1240 /// the expression came from the corresponding "byte swapped" byte in some other
1241 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1242 /// we know that the expression deposits the low byte of %X into the high byte
1243 /// of the bswap result and that all other bytes are zero. This expression is
1244 /// accepted, the high byte of ByteValues is set to X to indicate a correct
1247 /// This function returns true if the match was unsuccessful and false if so.
1248 /// On entry to the function the "OverallLeftShift" is a signed integer value
1249 /// indicating the number of bytes that the subexpression is later shifted. For
1250 /// example, if the expression is later right shifted by 16 bits, the
1251 /// OverallLeftShift value would be -2 on entry. This is used to specify which
1252 /// byte of ByteValues is actually being set.
1254 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1255 /// byte is masked to zero by a user. For example, in (X & 255), X will be
1256 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1257 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
1258 /// always in the local (OverallLeftShift) coordinate space.
1260 static bool CollectBSwapParts(Value
*V
, int OverallLeftShift
, uint32_t ByteMask
,
1261 SmallVector
<Value
*, 8> &ByteValues
) {
1262 if (Instruction
*I
= dyn_cast
<Instruction
>(V
)) {
1263 // If this is an or instruction, it may be an inner node of the bswap.
1264 if (I
->getOpcode() == Instruction::Or
) {
1265 return CollectBSwapParts(I
->getOperand(0), OverallLeftShift
, ByteMask
,
1267 CollectBSwapParts(I
->getOperand(1), OverallLeftShift
, ByteMask
,
1271 // If this is a logical shift by a constant multiple of 8, recurse with
1272 // OverallLeftShift and ByteMask adjusted.
1273 if (I
->isLogicalShift() && isa
<ConstantInt
>(I
->getOperand(1))) {
1275 cast
<ConstantInt
>(I
->getOperand(1))->getLimitedValue(~0U);
1276 // Ensure the shift amount is defined and of a byte value.
1277 if ((ShAmt
& 7) || (ShAmt
> 8*ByteValues
.size()))
1280 unsigned ByteShift
= ShAmt
>> 3;
1281 if (I
->getOpcode() == Instruction::Shl
) {
1282 // X << 2 -> collect(X, +2)
1283 OverallLeftShift
+= ByteShift
;
1284 ByteMask
>>= ByteShift
;
1286 // X >>u 2 -> collect(X, -2)
1287 OverallLeftShift
-= ByteShift
;
1288 ByteMask
<<= ByteShift
;
1289 ByteMask
&= (~0U >> (32-ByteValues
.size()));
1292 if (OverallLeftShift
>= (int)ByteValues
.size()) return true;
1293 if (OverallLeftShift
<= -(int)ByteValues
.size()) return true;
1295 return CollectBSwapParts(I
->getOperand(0), OverallLeftShift
, ByteMask
,
1299 // If this is a logical 'and' with a mask that clears bytes, clear the
1300 // corresponding bytes in ByteMask.
1301 if (I
->getOpcode() == Instruction::And
&&
1302 isa
<ConstantInt
>(I
->getOperand(1))) {
1303 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1304 unsigned NumBytes
= ByteValues
.size();
1305 APInt
Byte(I
->getType()->getPrimitiveSizeInBits(), 255);
1306 const APInt
&AndMask
= cast
<ConstantInt
>(I
->getOperand(1))->getValue();
1308 for (unsigned i
= 0; i
!= NumBytes
; ++i
, Byte
<<= 8) {
1309 // If this byte is masked out by a later operation, we don't care what
1311 if ((ByteMask
& (1 << i
)) == 0)
1314 // If the AndMask is all zeros for this byte, clear the bit.
1315 APInt MaskB
= AndMask
& Byte
;
1317 ByteMask
&= ~(1U << i
);
1321 // If the AndMask is not all ones for this byte, it's not a bytezap.
1325 // Otherwise, this byte is kept.
1328 return CollectBSwapParts(I
->getOperand(0), OverallLeftShift
, ByteMask
,
1333 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1334 // the input value to the bswap. Some observations: 1) if more than one byte
1335 // is demanded from this input, then it could not be successfully assembled
1336 // into a byteswap. At least one of the two bytes would not be aligned with
1337 // their ultimate destination.
1338 if (!isPowerOf2_32(ByteMask
)) return true;
1339 unsigned InputByteNo
= CountTrailingZeros_32(ByteMask
);
1341 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1342 // is demanded, it needs to go into byte 0 of the result. This means that the
1343 // byte needs to be shifted until it lands in the right byte bucket. The
1344 // shift amount depends on the position: if the byte is coming from the high
1345 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1346 // low part, it must be shifted left.
1347 unsigned DestByteNo
= InputByteNo
+ OverallLeftShift
;
1348 if (InputByteNo
< ByteValues
.size()/2) {
1349 if (ByteValues
.size()-1-DestByteNo
!= InputByteNo
)
1352 if (ByteValues
.size()-1-DestByteNo
!= InputByteNo
)
1356 // If the destination byte value is already defined, the values are or'd
1357 // together, which isn't a bswap (unless it's an or of the same bits).
1358 if (ByteValues
[DestByteNo
] && ByteValues
[DestByteNo
] != V
)
1360 ByteValues
[DestByteNo
] = V
;
1364 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1365 /// If so, insert the new bswap intrinsic and return it.
1366 Instruction
*InstCombiner::MatchBSwap(BinaryOperator
&I
) {
1367 const IntegerType
*ITy
= dyn_cast
<IntegerType
>(I
.getType());
1368 if (!ITy
|| ITy
->getBitWidth() % 16 ||
1369 // ByteMask only allows up to 32-byte values.
1370 ITy
->getBitWidth() > 32*8)
1371 return 0; // Can only bswap pairs of bytes. Can't do vectors.
1373 /// ByteValues - For each byte of the result, we keep track of which value
1374 /// defines each byte.
1375 SmallVector
<Value
*, 8> ByteValues
;
1376 ByteValues
.resize(ITy
->getBitWidth()/8);
1378 // Try to find all the pieces corresponding to the bswap.
1379 uint32_t ByteMask
= ~0U >> (32-ByteValues
.size());
1380 if (CollectBSwapParts(&I
, 0, ByteMask
, ByteValues
))
1383 // Check to see if all of the bytes come from the same value.
1384 Value
*V
= ByteValues
[0];
1385 if (V
== 0) return 0; // Didn't find a byte? Must be zero.
1387 // Check to make sure that all of the bytes come from the same value.
1388 for (unsigned i
= 1, e
= ByteValues
.size(); i
!= e
; ++i
)
1389 if (ByteValues
[i
] != V
)
1391 const Type
*Tys
[] = { ITy
};
1392 Module
*M
= I
.getParent()->getParent()->getParent();
1393 Function
*F
= Intrinsic::getDeclaration(M
, Intrinsic::bswap
, Tys
, 1);
1394 return CallInst::Create(F
, V
);
1397 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1398 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1399 /// we can simplify this expression to "cond ? C : D or B".
1400 static Instruction
*MatchSelectFromAndOr(Value
*A
, Value
*B
,
1401 Value
*C
, Value
*D
) {
1402 // If A is not a select of -1/0, this cannot match.
1404 if (!match(A
, m_SExt(m_Value(Cond
))) ||
1405 !Cond
->getType()->isIntegerTy(1))
1408 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1409 if (match(D
, m_Not(m_SExt(m_Specific(Cond
)))))
1410 return SelectInst::Create(Cond
, C
, B
);
1411 if (match(D
, m_SExt(m_Not(m_Specific(Cond
)))))
1412 return SelectInst::Create(Cond
, C
, B
);
1414 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1415 if (match(B
, m_Not(m_SExt(m_Specific(Cond
)))))
1416 return SelectInst::Create(Cond
, C
, D
);
1417 if (match(B
, m_SExt(m_Not(m_Specific(Cond
)))))
1418 return SelectInst::Create(Cond
, C
, D
);
1422 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1423 Value
*InstCombiner::FoldOrOfICmps(ICmpInst
*LHS
, ICmpInst
*RHS
) {
1424 ICmpInst::Predicate LHSCC
= LHS
->getPredicate(), RHSCC
= RHS
->getPredicate();
1426 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1427 if (PredicatesFoldable(LHSCC
, RHSCC
)) {
1428 if (LHS
->getOperand(0) == RHS
->getOperand(1) &&
1429 LHS
->getOperand(1) == RHS
->getOperand(0))
1430 LHS
->swapOperands();
1431 if (LHS
->getOperand(0) == RHS
->getOperand(0) &&
1432 LHS
->getOperand(1) == RHS
->getOperand(1)) {
1433 Value
*Op0
= LHS
->getOperand(0), *Op1
= LHS
->getOperand(1);
1434 unsigned Code
= getICmpCode(LHS
) | getICmpCode(RHS
);
1435 bool isSigned
= LHS
->isSigned() || RHS
->isSigned();
1436 return getICmpValue(isSigned
, Code
, Op0
, Op1
, Builder
);
1440 // handle (roughly):
1441 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1442 if (Value
*V
= foldLogOpOfMaskedICmps(LHS
, RHS
, ICmpInst::ICMP_NE
, Builder
))
1445 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1446 Value
*Val
= LHS
->getOperand(0), *Val2
= RHS
->getOperand(0);
1447 ConstantInt
*LHSCst
= dyn_cast
<ConstantInt
>(LHS
->getOperand(1));
1448 ConstantInt
*RHSCst
= dyn_cast
<ConstantInt
>(RHS
->getOperand(1));
1449 if (LHSCst
== 0 || RHSCst
== 0) return 0;
1451 if (LHSCst
== RHSCst
&& LHSCC
== RHSCC
) {
1452 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1453 if (LHSCC
== ICmpInst::ICMP_NE
&& LHSCst
->isZero()) {
1454 Value
*NewOr
= Builder
->CreateOr(Val
, Val2
);
1455 return Builder
->CreateICmp(LHSCC
, NewOr
, LHSCst
);
1458 // (icmp slt A, 0) | (icmp slt B, 0) --> (icmp slt (A|B), 0)
1459 if (LHSCC
== ICmpInst::ICMP_SLT
&& LHSCst
->isZero()) {
1460 Value
*NewOr
= Builder
->CreateOr(Val
, Val2
);
1461 return Builder
->CreateICmp(LHSCC
, NewOr
, LHSCst
);
1464 // (icmp sgt A, -1) | (icmp sgt B, -1) --> (icmp sgt (A&B), -1)
1465 if (LHSCC
== ICmpInst::ICMP_SGT
&& LHSCst
->isAllOnesValue()) {
1466 Value
*NewAnd
= Builder
->CreateAnd(Val
, Val2
);
1467 return Builder
->CreateICmp(LHSCC
, NewAnd
, LHSCst
);
1471 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
1472 // iff C2 + CA == C1.
1473 if (LHSCC
== ICmpInst::ICMP_ULT
&& RHSCC
== ICmpInst::ICMP_EQ
) {
1474 ConstantInt
*AddCst
;
1475 if (match(Val
, m_Add(m_Specific(Val2
), m_ConstantInt(AddCst
))))
1476 if (RHSCst
->getValue() + AddCst
->getValue() == LHSCst
->getValue())
1477 return Builder
->CreateICmpULE(Val
, LHSCst
);
1480 // From here on, we only handle:
1481 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1482 if (Val
!= Val2
) return 0;
1484 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1485 if (LHSCC
== ICmpInst::ICMP_UGE
|| LHSCC
== ICmpInst::ICMP_ULE
||
1486 RHSCC
== ICmpInst::ICMP_UGE
|| RHSCC
== ICmpInst::ICMP_ULE
||
1487 LHSCC
== ICmpInst::ICMP_SGE
|| LHSCC
== ICmpInst::ICMP_SLE
||
1488 RHSCC
== ICmpInst::ICMP_SGE
|| RHSCC
== ICmpInst::ICMP_SLE
)
1491 // We can't fold (ugt x, C) | (sgt x, C2).
1492 if (!PredicatesFoldable(LHSCC
, RHSCC
))
1495 // Ensure that the larger constant is on the RHS.
1497 if (CmpInst::isSigned(LHSCC
) ||
1498 (ICmpInst::isEquality(LHSCC
) &&
1499 CmpInst::isSigned(RHSCC
)))
1500 ShouldSwap
= LHSCst
->getValue().sgt(RHSCst
->getValue());
1502 ShouldSwap
= LHSCst
->getValue().ugt(RHSCst
->getValue());
1505 std::swap(LHS
, RHS
);
1506 std::swap(LHSCst
, RHSCst
);
1507 std::swap(LHSCC
, RHSCC
);
1510 // At this point, we know we have two icmp instructions
1511 // comparing a value against two constants and or'ing the result
1512 // together. Because of the above check, we know that we only have
1513 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1514 // icmp folding check above), that the two constants are not
1516 assert(LHSCst
!= RHSCst
&& "Compares not folded above?");
1519 default: llvm_unreachable("Unknown integer condition code!");
1520 case ICmpInst::ICMP_EQ
:
1522 default: llvm_unreachable("Unknown integer condition code!");
1523 case ICmpInst::ICMP_EQ
:
1524 if (LHSCst
== SubOne(RHSCst
)) {
1525 // (X == 13 | X == 14) -> X-13 <u 2
1526 Constant
*AddCST
= ConstantExpr::getNeg(LHSCst
);
1527 Value
*Add
= Builder
->CreateAdd(Val
, AddCST
, Val
->getName()+".off");
1528 AddCST
= ConstantExpr::getSub(AddOne(RHSCst
), LHSCst
);
1529 return Builder
->CreateICmpULT(Add
, AddCST
);
1531 break; // (X == 13 | X == 15) -> no change
1532 case ICmpInst::ICMP_UGT
: // (X == 13 | X u> 14) -> no change
1533 case ICmpInst::ICMP_SGT
: // (X == 13 | X s> 14) -> no change
1535 case ICmpInst::ICMP_NE
: // (X == 13 | X != 15) -> X != 15
1536 case ICmpInst::ICMP_ULT
: // (X == 13 | X u< 15) -> X u< 15
1537 case ICmpInst::ICMP_SLT
: // (X == 13 | X s< 15) -> X s< 15
1541 case ICmpInst::ICMP_NE
:
1543 default: llvm_unreachable("Unknown integer condition code!");
1544 case ICmpInst::ICMP_EQ
: // (X != 13 | X == 15) -> X != 13
1545 case ICmpInst::ICMP_UGT
: // (X != 13 | X u> 15) -> X != 13
1546 case ICmpInst::ICMP_SGT
: // (X != 13 | X s> 15) -> X != 13
1548 case ICmpInst::ICMP_NE
: // (X != 13 | X != 15) -> true
1549 case ICmpInst::ICMP_ULT
: // (X != 13 | X u< 15) -> true
1550 case ICmpInst::ICMP_SLT
: // (X != 13 | X s< 15) -> true
1551 return ConstantInt::getTrue(LHS
->getContext());
1554 case ICmpInst::ICMP_ULT
:
1556 default: llvm_unreachable("Unknown integer condition code!");
1557 case ICmpInst::ICMP_EQ
: // (X u< 13 | X == 14) -> no change
1559 case ICmpInst::ICMP_UGT
: // (X u< 13 | X u> 15) -> (X-13) u> 2
1560 // If RHSCst is [us]MAXINT, it is always false. Not handling
1561 // this can cause overflow.
1562 if (RHSCst
->isMaxValue(false))
1564 return InsertRangeTest(Val
, LHSCst
, AddOne(RHSCst
), false, false);
1565 case ICmpInst::ICMP_SGT
: // (X u< 13 | X s> 15) -> no change
1567 case ICmpInst::ICMP_NE
: // (X u< 13 | X != 15) -> X != 15
1568 case ICmpInst::ICMP_ULT
: // (X u< 13 | X u< 15) -> X u< 15
1570 case ICmpInst::ICMP_SLT
: // (X u< 13 | X s< 15) -> no change
1574 case ICmpInst::ICMP_SLT
:
1576 default: llvm_unreachable("Unknown integer condition code!");
1577 case ICmpInst::ICMP_EQ
: // (X s< 13 | X == 14) -> no change
1579 case ICmpInst::ICMP_SGT
: // (X s< 13 | X s> 15) -> (X-13) s> 2
1580 // If RHSCst is [us]MAXINT, it is always false. Not handling
1581 // this can cause overflow.
1582 if (RHSCst
->isMaxValue(true))
1584 return InsertRangeTest(Val
, LHSCst
, AddOne(RHSCst
), true, false);
1585 case ICmpInst::ICMP_UGT
: // (X s< 13 | X u> 15) -> no change
1587 case ICmpInst::ICMP_NE
: // (X s< 13 | X != 15) -> X != 15
1588 case ICmpInst::ICMP_SLT
: // (X s< 13 | X s< 15) -> X s< 15
1590 case ICmpInst::ICMP_ULT
: // (X s< 13 | X u< 15) -> no change
1594 case ICmpInst::ICMP_UGT
:
1596 default: llvm_unreachable("Unknown integer condition code!");
1597 case ICmpInst::ICMP_EQ
: // (X u> 13 | X == 15) -> X u> 13
1598 case ICmpInst::ICMP_UGT
: // (X u> 13 | X u> 15) -> X u> 13
1600 case ICmpInst::ICMP_SGT
: // (X u> 13 | X s> 15) -> no change
1602 case ICmpInst::ICMP_NE
: // (X u> 13 | X != 15) -> true
1603 case ICmpInst::ICMP_ULT
: // (X u> 13 | X u< 15) -> true
1604 return ConstantInt::getTrue(LHS
->getContext());
1605 case ICmpInst::ICMP_SLT
: // (X u> 13 | X s< 15) -> no change
1609 case ICmpInst::ICMP_SGT
:
1611 default: llvm_unreachable("Unknown integer condition code!");
1612 case ICmpInst::ICMP_EQ
: // (X s> 13 | X == 15) -> X > 13
1613 case ICmpInst::ICMP_SGT
: // (X s> 13 | X s> 15) -> X > 13
1615 case ICmpInst::ICMP_UGT
: // (X s> 13 | X u> 15) -> no change
1617 case ICmpInst::ICMP_NE
: // (X s> 13 | X != 15) -> true
1618 case ICmpInst::ICMP_SLT
: // (X s> 13 | X s< 15) -> true
1619 return ConstantInt::getTrue(LHS
->getContext());
1620 case ICmpInst::ICMP_ULT
: // (X s> 13 | X u< 15) -> no change
1628 /// FoldOrOfFCmps - Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of
1629 /// instcombine, this returns a Value which should already be inserted into the
1631 Value
*InstCombiner::FoldOrOfFCmps(FCmpInst
*LHS
, FCmpInst
*RHS
) {
1632 if (LHS
->getPredicate() == FCmpInst::FCMP_UNO
&&
1633 RHS
->getPredicate() == FCmpInst::FCMP_UNO
&&
1634 LHS
->getOperand(0)->getType() == RHS
->getOperand(0)->getType()) {
1635 if (ConstantFP
*LHSC
= dyn_cast
<ConstantFP
>(LHS
->getOperand(1)))
1636 if (ConstantFP
*RHSC
= dyn_cast
<ConstantFP
>(RHS
->getOperand(1))) {
1637 // If either of the constants are nans, then the whole thing returns
1639 if (LHSC
->getValueAPF().isNaN() || RHSC
->getValueAPF().isNaN())
1640 return ConstantInt::getTrue(LHS
->getContext());
1642 // Otherwise, no need to compare the two constants, compare the
1644 return Builder
->CreateFCmpUNO(LHS
->getOperand(0), RHS
->getOperand(0));
1647 // Handle vector zeros. This occurs because the canonical form of
1648 // "fcmp uno x,x" is "fcmp uno x, 0".
1649 if (isa
<ConstantAggregateZero
>(LHS
->getOperand(1)) &&
1650 isa
<ConstantAggregateZero
>(RHS
->getOperand(1)))
1651 return Builder
->CreateFCmpUNO(LHS
->getOperand(0), RHS
->getOperand(0));
1656 Value
*Op0LHS
= LHS
->getOperand(0), *Op0RHS
= LHS
->getOperand(1);
1657 Value
*Op1LHS
= RHS
->getOperand(0), *Op1RHS
= RHS
->getOperand(1);
1658 FCmpInst::Predicate Op0CC
= LHS
->getPredicate(), Op1CC
= RHS
->getPredicate();
1660 if (Op0LHS
== Op1RHS
&& Op0RHS
== Op1LHS
) {
1661 // Swap RHS operands to match LHS.
1662 Op1CC
= FCmpInst::getSwappedPredicate(Op1CC
);
1663 std::swap(Op1LHS
, Op1RHS
);
1665 if (Op0LHS
== Op1LHS
&& Op0RHS
== Op1RHS
) {
1666 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1668 return Builder
->CreateFCmp((FCmpInst::Predicate
)Op0CC
, Op0LHS
, Op0RHS
);
1669 if (Op0CC
== FCmpInst::FCMP_TRUE
|| Op1CC
== FCmpInst::FCMP_TRUE
)
1670 return ConstantInt::get(CmpInst::makeCmpResultType(LHS
->getType()), 1);
1671 if (Op0CC
== FCmpInst::FCMP_FALSE
)
1673 if (Op1CC
== FCmpInst::FCMP_FALSE
)
1677 unsigned Op0Pred
= getFCmpCode(Op0CC
, Op0Ordered
);
1678 unsigned Op1Pred
= getFCmpCode(Op1CC
, Op1Ordered
);
1679 if (Op0Ordered
== Op1Ordered
) {
1680 // If both are ordered or unordered, return a new fcmp with
1681 // or'ed predicates.
1682 return getFCmpValue(Op0Ordered
, Op0Pred
|Op1Pred
, Op0LHS
, Op0RHS
, Builder
);
1688 /// FoldOrWithConstants - This helper function folds:
1690 /// ((A | B) & C1) | (B & C2)
1696 /// when the XOR of the two constants is "all ones" (-1).
1697 Instruction
*InstCombiner::FoldOrWithConstants(BinaryOperator
&I
, Value
*Op
,
1698 Value
*A
, Value
*B
, Value
*C
) {
1699 ConstantInt
*CI1
= dyn_cast
<ConstantInt
>(C
);
1703 ConstantInt
*CI2
= 0;
1704 if (!match(Op
, m_And(m_Value(V1
), m_ConstantInt(CI2
)))) return 0;
1706 APInt Xor
= CI1
->getValue() ^ CI2
->getValue();
1707 if (!Xor
.isAllOnesValue()) return 0;
1709 if (V1
== A
|| V1
== B
) {
1710 Value
*NewOp
= Builder
->CreateAnd((V1
== A
) ? B
: A
, CI1
);
1711 return BinaryOperator::CreateOr(NewOp
, V1
);
1717 Instruction
*InstCombiner::visitOr(BinaryOperator
&I
) {
1718 bool Changed
= SimplifyAssociativeOrCommutative(I
);
1719 Value
*Op0
= I
.getOperand(0), *Op1
= I
.getOperand(1);
1721 if (Value
*V
= SimplifyOrInst(Op0
, Op1
, TD
))
1722 return ReplaceInstUsesWith(I
, V
);
1724 // (A&B)|(A&C) -> A&(B|C) etc
1725 if (Value
*V
= SimplifyUsingDistributiveLaws(I
))
1726 return ReplaceInstUsesWith(I
, V
);
1728 // See if we can simplify any instructions used by the instruction whose sole
1729 // purpose is to compute bits we don't care about.
1730 if (SimplifyDemandedInstructionBits(I
))
1733 if (ConstantInt
*RHS
= dyn_cast
<ConstantInt
>(Op1
)) {
1734 ConstantInt
*C1
= 0; Value
*X
= 0;
1735 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1736 // iff (C1 & C2) == 0.
1737 if (match(Op0
, m_And(m_Value(X
), m_ConstantInt(C1
))) &&
1738 (RHS
->getValue() & C1
->getValue()) != 0 &&
1740 Value
*Or
= Builder
->CreateOr(X
, RHS
);
1742 return BinaryOperator::CreateAnd(Or
,
1743 ConstantInt::get(I
.getContext(),
1744 RHS
->getValue() | C1
->getValue()));
1747 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1748 if (match(Op0
, m_Xor(m_Value(X
), m_ConstantInt(C1
))) &&
1750 Value
*Or
= Builder
->CreateOr(X
, RHS
);
1752 return BinaryOperator::CreateXor(Or
,
1753 ConstantInt::get(I
.getContext(),
1754 C1
->getValue() & ~RHS
->getValue()));
1757 // Try to fold constant and into select arguments.
1758 if (SelectInst
*SI
= dyn_cast
<SelectInst
>(Op0
))
1759 if (Instruction
*R
= FoldOpIntoSelect(I
, SI
))
1762 if (isa
<PHINode
>(Op0
))
1763 if (Instruction
*NV
= FoldOpIntoPhi(I
))
1767 Value
*A
= 0, *B
= 0;
1768 ConstantInt
*C1
= 0, *C2
= 0;
1770 // (A | B) | C and A | (B | C) -> bswap if possible.
1771 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1772 if (match(Op0
, m_Or(m_Value(), m_Value())) ||
1773 match(Op1
, m_Or(m_Value(), m_Value())) ||
1774 (match(Op0
, m_LogicalShift(m_Value(), m_Value())) &&
1775 match(Op1
, m_LogicalShift(m_Value(), m_Value())))) {
1776 if (Instruction
*BSwap
= MatchBSwap(I
))
1780 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1781 if (Op0
->hasOneUse() &&
1782 match(Op0
, m_Xor(m_Value(A
), m_ConstantInt(C1
))) &&
1783 MaskedValueIsZero(Op1
, C1
->getValue())) {
1784 Value
*NOr
= Builder
->CreateOr(A
, Op1
);
1786 return BinaryOperator::CreateXor(NOr
, C1
);
1789 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1790 if (Op1
->hasOneUse() &&
1791 match(Op1
, m_Xor(m_Value(A
), m_ConstantInt(C1
))) &&
1792 MaskedValueIsZero(Op0
, C1
->getValue())) {
1793 Value
*NOr
= Builder
->CreateOr(A
, Op0
);
1795 return BinaryOperator::CreateXor(NOr
, C1
);
1799 Value
*C
= 0, *D
= 0;
1800 if (match(Op0
, m_And(m_Value(A
), m_Value(C
))) &&
1801 match(Op1
, m_And(m_Value(B
), m_Value(D
)))) {
1802 Value
*V1
= 0, *V2
= 0;
1803 C1
= dyn_cast
<ConstantInt
>(C
);
1804 C2
= dyn_cast
<ConstantInt
>(D
);
1805 if (C1
&& C2
) { // (A & C1)|(B & C2)
1806 // If we have: ((V + N) & C1) | (V & C2)
1807 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1808 // replace with V+N.
1809 if (C1
->getValue() == ~C2
->getValue()) {
1810 if ((C2
->getValue() & (C2
->getValue()+1)) == 0 && // C2 == 0+1+
1811 match(A
, m_Add(m_Value(V1
), m_Value(V2
)))) {
1812 // Add commutes, try both ways.
1813 if (V1
== B
&& MaskedValueIsZero(V2
, C2
->getValue()))
1814 return ReplaceInstUsesWith(I
, A
);
1815 if (V2
== B
&& MaskedValueIsZero(V1
, C2
->getValue()))
1816 return ReplaceInstUsesWith(I
, A
);
1818 // Or commutes, try both ways.
1819 if ((C1
->getValue() & (C1
->getValue()+1)) == 0 &&
1820 match(B
, m_Add(m_Value(V1
), m_Value(V2
)))) {
1821 // Add commutes, try both ways.
1822 if (V1
== A
&& MaskedValueIsZero(V2
, C1
->getValue()))
1823 return ReplaceInstUsesWith(I
, B
);
1824 if (V2
== A
&& MaskedValueIsZero(V1
, C1
->getValue()))
1825 return ReplaceInstUsesWith(I
, B
);
1829 if ((C1
->getValue() & C2
->getValue()) == 0) {
1830 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1831 // iff (C1&C2) == 0 and (N&~C1) == 0
1832 if (match(A
, m_Or(m_Value(V1
), m_Value(V2
))) &&
1833 ((V1
== B
&& MaskedValueIsZero(V2
, ~C1
->getValue())) || // (V|N)
1834 (V2
== B
&& MaskedValueIsZero(V1
, ~C1
->getValue())))) // (N|V)
1835 return BinaryOperator::CreateAnd(A
,
1836 ConstantInt::get(A
->getContext(),
1837 C1
->getValue()|C2
->getValue()));
1838 // Or commutes, try both ways.
1839 if (match(B
, m_Or(m_Value(V1
), m_Value(V2
))) &&
1840 ((V1
== A
&& MaskedValueIsZero(V2
, ~C2
->getValue())) || // (V|N)
1841 (V2
== A
&& MaskedValueIsZero(V1
, ~C2
->getValue())))) // (N|V)
1842 return BinaryOperator::CreateAnd(B
,
1843 ConstantInt::get(B
->getContext(),
1844 C1
->getValue()|C2
->getValue()));
1846 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
1847 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
1848 ConstantInt
*C3
= 0, *C4
= 0;
1849 if (match(A
, m_Or(m_Value(V1
), m_ConstantInt(C3
))) &&
1850 (C3
->getValue() & ~C1
->getValue()) == 0 &&
1851 match(B
, m_Or(m_Specific(V1
), m_ConstantInt(C4
))) &&
1852 (C4
->getValue() & ~C2
->getValue()) == 0) {
1853 V2
= Builder
->CreateOr(V1
, ConstantExpr::getOr(C3
, C4
), "bitfield");
1854 return BinaryOperator::CreateAnd(V2
,
1855 ConstantInt::get(B
->getContext(),
1856 C1
->getValue()|C2
->getValue()));
1861 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
1862 // Don't do this for vector select idioms, the code generator doesn't handle
1864 if (!I
.getType()->isVectorTy()) {
1865 if (Instruction
*Match
= MatchSelectFromAndOr(A
, B
, C
, D
))
1867 if (Instruction
*Match
= MatchSelectFromAndOr(B
, A
, D
, C
))
1869 if (Instruction
*Match
= MatchSelectFromAndOr(C
, B
, A
, D
))
1871 if (Instruction
*Match
= MatchSelectFromAndOr(D
, A
, B
, C
))
1875 // ((A&~B)|(~A&B)) -> A^B
1876 if ((match(C
, m_Not(m_Specific(D
))) &&
1877 match(B
, m_Not(m_Specific(A
)))))
1878 return BinaryOperator::CreateXor(A
, D
);
1879 // ((~B&A)|(~A&B)) -> A^B
1880 if ((match(A
, m_Not(m_Specific(D
))) &&
1881 match(B
, m_Not(m_Specific(C
)))))
1882 return BinaryOperator::CreateXor(C
, D
);
1883 // ((A&~B)|(B&~A)) -> A^B
1884 if ((match(C
, m_Not(m_Specific(B
))) &&
1885 match(D
, m_Not(m_Specific(A
)))))
1886 return BinaryOperator::CreateXor(A
, B
);
1887 // ((~B&A)|(B&~A)) -> A^B
1888 if ((match(A
, m_Not(m_Specific(B
))) &&
1889 match(D
, m_Not(m_Specific(C
)))))
1890 return BinaryOperator::CreateXor(C
, B
);
1892 // ((A|B)&1)|(B&-2) -> (A&1) | B
1893 if (match(A
, m_Or(m_Value(V1
), m_Specific(B
))) ||
1894 match(A
, m_Or(m_Specific(B
), m_Value(V1
)))) {
1895 Instruction
*Ret
= FoldOrWithConstants(I
, Op1
, V1
, B
, C
);
1896 if (Ret
) return Ret
;
1898 // (B&-2)|((A|B)&1) -> (A&1) | B
1899 if (match(B
, m_Or(m_Specific(A
), m_Value(V1
))) ||
1900 match(B
, m_Or(m_Value(V1
), m_Specific(A
)))) {
1901 Instruction
*Ret
= FoldOrWithConstants(I
, Op0
, A
, V1
, D
);
1902 if (Ret
) return Ret
;
1906 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
1907 if (BinaryOperator
*SI1
= dyn_cast
<BinaryOperator
>(Op1
)) {
1908 if (BinaryOperator
*SI0
= dyn_cast
<BinaryOperator
>(Op0
))
1909 if (SI0
->isShift() && SI0
->getOpcode() == SI1
->getOpcode() &&
1910 SI0
->getOperand(1) == SI1
->getOperand(1) &&
1911 (SI0
->hasOneUse() || SI1
->hasOneUse())) {
1912 Value
*NewOp
= Builder
->CreateOr(SI0
->getOperand(0), SI1
->getOperand(0),
1914 return BinaryOperator::Create(SI1
->getOpcode(), NewOp
,
1915 SI1
->getOperand(1));
1919 // (~A | ~B) == (~(A & B)) - De Morgan's Law
1920 if (Value
*Op0NotVal
= dyn_castNotVal(Op0
))
1921 if (Value
*Op1NotVal
= dyn_castNotVal(Op1
))
1922 if (Op0
->hasOneUse() && Op1
->hasOneUse()) {
1923 Value
*And
= Builder
->CreateAnd(Op0NotVal
, Op1NotVal
,
1924 I
.getName()+".demorgan");
1925 return BinaryOperator::CreateNot(And
);
1928 // Canonicalize xor to the RHS.
1929 if (match(Op0
, m_Xor(m_Value(), m_Value())))
1930 std::swap(Op0
, Op1
);
1932 // A | ( A ^ B) -> A | B
1933 // A | (~A ^ B) -> A | ~B
1934 if (match(Op1
, m_Xor(m_Value(A
), m_Value(B
)))) {
1935 if (Op0
== A
|| Op0
== B
)
1936 return BinaryOperator::CreateOr(A
, B
);
1938 if (Op1
->hasOneUse() && match(A
, m_Not(m_Specific(Op0
)))) {
1939 Value
*Not
= Builder
->CreateNot(B
, B
->getName()+".not");
1940 return BinaryOperator::CreateOr(Not
, Op0
);
1942 if (Op1
->hasOneUse() && match(B
, m_Not(m_Specific(Op0
)))) {
1943 Value
*Not
= Builder
->CreateNot(A
, A
->getName()+".not");
1944 return BinaryOperator::CreateOr(Not
, Op0
);
1948 // A | ~(A | B) -> A | ~B
1949 // A | ~(A ^ B) -> A | ~B
1950 if (match(Op1
, m_Not(m_Value(A
))))
1951 if (BinaryOperator
*B
= dyn_cast
<BinaryOperator
>(A
))
1952 if ((Op0
== B
->getOperand(0) || Op0
== B
->getOperand(1)) &&
1953 Op1
->hasOneUse() && (B
->getOpcode() == Instruction::Or
||
1954 B
->getOpcode() == Instruction::Xor
)) {
1955 Value
*NotOp
= Op0
== B
->getOperand(0) ? B
->getOperand(1) :
1957 Value
*Not
= Builder
->CreateNot(NotOp
, NotOp
->getName()+".not");
1958 return BinaryOperator::CreateOr(Not
, Op0
);
1961 if (ICmpInst
*RHS
= dyn_cast
<ICmpInst
>(I
.getOperand(1)))
1962 if (ICmpInst
*LHS
= dyn_cast
<ICmpInst
>(I
.getOperand(0)))
1963 if (Value
*Res
= FoldOrOfICmps(LHS
, RHS
))
1964 return ReplaceInstUsesWith(I
, Res
);
1966 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
1967 if (FCmpInst
*LHS
= dyn_cast
<FCmpInst
>(I
.getOperand(0)))
1968 if (FCmpInst
*RHS
= dyn_cast
<FCmpInst
>(I
.getOperand(1)))
1969 if (Value
*Res
= FoldOrOfFCmps(LHS
, RHS
))
1970 return ReplaceInstUsesWith(I
, Res
);
1972 // fold (or (cast A), (cast B)) -> (cast (or A, B))
1973 if (CastInst
*Op0C
= dyn_cast
<CastInst
>(Op0
)) {
1974 CastInst
*Op1C
= dyn_cast
<CastInst
>(Op1
);
1975 if (Op1C
&& Op0C
->getOpcode() == Op1C
->getOpcode()) {// same cast kind ?
1976 const Type
*SrcTy
= Op0C
->getOperand(0)->getType();
1977 if (SrcTy
== Op1C
->getOperand(0)->getType() &&
1978 SrcTy
->isIntOrIntVectorTy()) {
1979 Value
*Op0COp
= Op0C
->getOperand(0), *Op1COp
= Op1C
->getOperand(0);
1981 if ((!isa
<ICmpInst
>(Op0COp
) || !isa
<ICmpInst
>(Op1COp
)) &&
1982 // Only do this if the casts both really cause code to be
1984 ShouldOptimizeCast(Op0C
->getOpcode(), Op0COp
, I
.getType()) &&
1985 ShouldOptimizeCast(Op1C
->getOpcode(), Op1COp
, I
.getType())) {
1986 Value
*NewOp
= Builder
->CreateOr(Op0COp
, Op1COp
, I
.getName());
1987 return CastInst::Create(Op0C
->getOpcode(), NewOp
, I
.getType());
1990 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
1991 // cast is otherwise not optimizable. This happens for vector sexts.
1992 if (ICmpInst
*RHS
= dyn_cast
<ICmpInst
>(Op1COp
))
1993 if (ICmpInst
*LHS
= dyn_cast
<ICmpInst
>(Op0COp
))
1994 if (Value
*Res
= FoldOrOfICmps(LHS
, RHS
))
1995 return CastInst::Create(Op0C
->getOpcode(), Res
, I
.getType());
1997 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
1998 // cast is otherwise not optimizable. This happens for vector sexts.
1999 if (FCmpInst
*RHS
= dyn_cast
<FCmpInst
>(Op1COp
))
2000 if (FCmpInst
*LHS
= dyn_cast
<FCmpInst
>(Op0COp
))
2001 if (Value
*Res
= FoldOrOfFCmps(LHS
, RHS
))
2002 return CastInst::Create(Op0C
->getOpcode(), Res
, I
.getType());
2007 // Note: If we've gotten to the point of visiting the outer OR, then the
2008 // inner one couldn't be simplified. If it was a constant, then it won't
2009 // be simplified by a later pass either, so we try swapping the inner/outer
2010 // ORs in the hopes that we'll be able to simplify it this way.
2011 // (X|C) | V --> (X|V) | C
2012 if (Op0
->hasOneUse() && !isa
<ConstantInt
>(Op1
) &&
2013 match(Op0
, m_Or(m_Value(A
), m_ConstantInt(C1
)))) {
2014 Value
*Inner
= Builder
->CreateOr(A
, Op1
);
2015 Inner
->takeName(Op0
);
2016 return BinaryOperator::CreateOr(Inner
, C1
);
2019 return Changed
? &I
: 0;
2022 Instruction
*InstCombiner::visitXor(BinaryOperator
&I
) {
2023 bool Changed
= SimplifyAssociativeOrCommutative(I
);
2024 Value
*Op0
= I
.getOperand(0), *Op1
= I
.getOperand(1);
2026 if (Value
*V
= SimplifyXorInst(Op0
, Op1
, TD
))
2027 return ReplaceInstUsesWith(I
, V
);
2029 // (A&B)^(A&C) -> A&(B^C) etc
2030 if (Value
*V
= SimplifyUsingDistributiveLaws(I
))
2031 return ReplaceInstUsesWith(I
, V
);
2033 // See if we can simplify any instructions used by the instruction whose sole
2034 // purpose is to compute bits we don't care about.
2035 if (SimplifyDemandedInstructionBits(I
))
2038 // Is this a ~ operation?
2039 if (Value
*NotOp
= dyn_castNotVal(&I
)) {
2040 if (BinaryOperator
*Op0I
= dyn_cast
<BinaryOperator
>(NotOp
)) {
2041 if (Op0I
->getOpcode() == Instruction::And
||
2042 Op0I
->getOpcode() == Instruction::Or
) {
2043 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2044 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2045 if (dyn_castNotVal(Op0I
->getOperand(1)))
2046 Op0I
->swapOperands();
2047 if (Value
*Op0NotVal
= dyn_castNotVal(Op0I
->getOperand(0))) {
2049 Builder
->CreateNot(Op0I
->getOperand(1),
2050 Op0I
->getOperand(1)->getName()+".not");
2051 if (Op0I
->getOpcode() == Instruction::And
)
2052 return BinaryOperator::CreateOr(Op0NotVal
, NotY
);
2053 return BinaryOperator::CreateAnd(Op0NotVal
, NotY
);
2056 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2057 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2058 if (isFreeToInvert(Op0I
->getOperand(0)) &&
2059 isFreeToInvert(Op0I
->getOperand(1))) {
2061 Builder
->CreateNot(Op0I
->getOperand(0), "notlhs");
2063 Builder
->CreateNot(Op0I
->getOperand(1), "notrhs");
2064 if (Op0I
->getOpcode() == Instruction::And
)
2065 return BinaryOperator::CreateOr(NotX
, NotY
);
2066 return BinaryOperator::CreateAnd(NotX
, NotY
);
2069 } else if (Op0I
->getOpcode() == Instruction::AShr
) {
2070 // ~(~X >>s Y) --> (X >>s Y)
2071 if (Value
*Op0NotVal
= dyn_castNotVal(Op0I
->getOperand(0)))
2072 return BinaryOperator::CreateAShr(Op0NotVal
, Op0I
->getOperand(1));
2078 if (ConstantInt
*RHS
= dyn_cast
<ConstantInt
>(Op1
)) {
2079 if (RHS
->isOne() && Op0
->hasOneUse())
2080 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2081 if (CmpInst
*CI
= dyn_cast
<CmpInst
>(Op0
))
2082 return CmpInst::Create(CI
->getOpcode(),
2083 CI
->getInversePredicate(),
2084 CI
->getOperand(0), CI
->getOperand(1));
2086 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2087 if (CastInst
*Op0C
= dyn_cast
<CastInst
>(Op0
)) {
2088 if (CmpInst
*CI
= dyn_cast
<CmpInst
>(Op0C
->getOperand(0))) {
2089 if (CI
->hasOneUse() && Op0C
->hasOneUse()) {
2090 Instruction::CastOps Opcode
= Op0C
->getOpcode();
2091 if ((Opcode
== Instruction::ZExt
|| Opcode
== Instruction::SExt
) &&
2092 (RHS
== ConstantExpr::getCast(Opcode
,
2093 ConstantInt::getTrue(I
.getContext()),
2094 Op0C
->getDestTy()))) {
2095 CI
->setPredicate(CI
->getInversePredicate());
2096 return CastInst::Create(Opcode
, CI
, Op0C
->getType());
2102 if (BinaryOperator
*Op0I
= dyn_cast
<BinaryOperator
>(Op0
)) {
2103 // ~(c-X) == X-c-1 == X+(-c-1)
2104 if (Op0I
->getOpcode() == Instruction::Sub
&& RHS
->isAllOnesValue())
2105 if (Constant
*Op0I0C
= dyn_cast
<Constant
>(Op0I
->getOperand(0))) {
2106 Constant
*NegOp0I0C
= ConstantExpr::getNeg(Op0I0C
);
2107 Constant
*ConstantRHS
= ConstantExpr::getSub(NegOp0I0C
,
2108 ConstantInt::get(I
.getType(), 1));
2109 return BinaryOperator::CreateAdd(Op0I
->getOperand(1), ConstantRHS
);
2112 if (ConstantInt
*Op0CI
= dyn_cast
<ConstantInt
>(Op0I
->getOperand(1))) {
2113 if (Op0I
->getOpcode() == Instruction::Add
) {
2114 // ~(X-c) --> (-c-1)-X
2115 if (RHS
->isAllOnesValue()) {
2116 Constant
*NegOp0CI
= ConstantExpr::getNeg(Op0CI
);
2117 return BinaryOperator::CreateSub(
2118 ConstantExpr::getSub(NegOp0CI
,
2119 ConstantInt::get(I
.getType(), 1)),
2120 Op0I
->getOperand(0));
2121 } else if (RHS
->getValue().isSignBit()) {
2122 // (X + C) ^ signbit -> (X + C + signbit)
2123 Constant
*C
= ConstantInt::get(I
.getContext(),
2124 RHS
->getValue() + Op0CI
->getValue());
2125 return BinaryOperator::CreateAdd(Op0I
->getOperand(0), C
);
2128 } else if (Op0I
->getOpcode() == Instruction::Or
) {
2129 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2130 if (MaskedValueIsZero(Op0I
->getOperand(0), Op0CI
->getValue())) {
2131 Constant
*NewRHS
= ConstantExpr::getOr(Op0CI
, RHS
);
2132 // Anything in both C1 and C2 is known to be zero, remove it from
2134 Constant
*CommonBits
= ConstantExpr::getAnd(Op0CI
, RHS
);
2135 NewRHS
= ConstantExpr::getAnd(NewRHS
,
2136 ConstantExpr::getNot(CommonBits
));
2138 I
.setOperand(0, Op0I
->getOperand(0));
2139 I
.setOperand(1, NewRHS
);
2146 // Try to fold constant and into select arguments.
2147 if (SelectInst
*SI
= dyn_cast
<SelectInst
>(Op0
))
2148 if (Instruction
*R
= FoldOpIntoSelect(I
, SI
))
2150 if (isa
<PHINode
>(Op0
))
2151 if (Instruction
*NV
= FoldOpIntoPhi(I
))
2155 BinaryOperator
*Op1I
= dyn_cast
<BinaryOperator
>(Op1
);
2158 if (match(Op1I
, m_Or(m_Value(A
), m_Value(B
)))) {
2159 if (A
== Op0
) { // B^(B|A) == (A|B)^B
2160 Op1I
->swapOperands();
2162 std::swap(Op0
, Op1
);
2163 } else if (B
== Op0
) { // B^(A|B) == (A|B)^B
2164 I
.swapOperands(); // Simplified below.
2165 std::swap(Op0
, Op1
);
2167 } else if (match(Op1I
, m_And(m_Value(A
), m_Value(B
))) &&
2169 if (A
== Op0
) { // A^(A&B) -> A^(B&A)
2170 Op1I
->swapOperands();
2173 if (B
== Op0
) { // A^(B&A) -> (B&A)^A
2174 I
.swapOperands(); // Simplified below.
2175 std::swap(Op0
, Op1
);
2180 BinaryOperator
*Op0I
= dyn_cast
<BinaryOperator
>(Op0
);
2183 if (match(Op0I
, m_Or(m_Value(A
), m_Value(B
))) &&
2184 Op0I
->hasOneUse()) {
2185 if (A
== Op1
) // (B|A)^B == (A|B)^B
2187 if (B
== Op1
) // (A|B)^B == A & ~B
2188 return BinaryOperator::CreateAnd(A
, Builder
->CreateNot(Op1
, "tmp"));
2189 } else if (match(Op0I
, m_And(m_Value(A
), m_Value(B
))) &&
2191 if (A
== Op1
) // (A&B)^A -> (B&A)^A
2193 if (B
== Op1
&& // (B&A)^A == ~B & A
2194 !isa
<ConstantInt
>(Op1
)) { // Canonical form is (B&C)^C
2195 return BinaryOperator::CreateAnd(Builder
->CreateNot(A
, "tmp"), Op1
);
2200 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
2201 if (Op0I
&& Op1I
&& Op0I
->isShift() &&
2202 Op0I
->getOpcode() == Op1I
->getOpcode() &&
2203 Op0I
->getOperand(1) == Op1I
->getOperand(1) &&
2204 (Op1I
->hasOneUse() || Op1I
->hasOneUse())) {
2206 Builder
->CreateXor(Op0I
->getOperand(0), Op1I
->getOperand(0),
2208 return BinaryOperator::Create(Op1I
->getOpcode(), NewOp
,
2209 Op1I
->getOperand(1));
2213 Value
*A
, *B
, *C
, *D
;
2214 // (A & B)^(A | B) -> A ^ B
2215 if (match(Op0I
, m_And(m_Value(A
), m_Value(B
))) &&
2216 match(Op1I
, m_Or(m_Value(C
), m_Value(D
)))) {
2217 if ((A
== C
&& B
== D
) || (A
== D
&& B
== C
))
2218 return BinaryOperator::CreateXor(A
, B
);
2220 // (A | B)^(A & B) -> A ^ B
2221 if (match(Op0I
, m_Or(m_Value(A
), m_Value(B
))) &&
2222 match(Op1I
, m_And(m_Value(C
), m_Value(D
)))) {
2223 if ((A
== C
&& B
== D
) || (A
== D
&& B
== C
))
2224 return BinaryOperator::CreateXor(A
, B
);
2228 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2229 if (ICmpInst
*RHS
= dyn_cast
<ICmpInst
>(I
.getOperand(1)))
2230 if (ICmpInst
*LHS
= dyn_cast
<ICmpInst
>(I
.getOperand(0)))
2231 if (PredicatesFoldable(LHS
->getPredicate(), RHS
->getPredicate())) {
2232 if (LHS
->getOperand(0) == RHS
->getOperand(1) &&
2233 LHS
->getOperand(1) == RHS
->getOperand(0))
2234 LHS
->swapOperands();
2235 if (LHS
->getOperand(0) == RHS
->getOperand(0) &&
2236 LHS
->getOperand(1) == RHS
->getOperand(1)) {
2237 Value
*Op0
= LHS
->getOperand(0), *Op1
= LHS
->getOperand(1);
2238 unsigned Code
= getICmpCode(LHS
) ^ getICmpCode(RHS
);
2239 bool isSigned
= LHS
->isSigned() || RHS
->isSigned();
2240 return ReplaceInstUsesWith(I
,
2241 getICmpValue(isSigned
, Code
, Op0
, Op1
, Builder
));
2245 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2246 if (CastInst
*Op0C
= dyn_cast
<CastInst
>(Op0
)) {
2247 if (CastInst
*Op1C
= dyn_cast
<CastInst
>(Op1
))
2248 if (Op0C
->getOpcode() == Op1C
->getOpcode()) { // same cast kind?
2249 const Type
*SrcTy
= Op0C
->getOperand(0)->getType();
2250 if (SrcTy
== Op1C
->getOperand(0)->getType() && SrcTy
->isIntegerTy() &&
2251 // Only do this if the casts both really cause code to be generated.
2252 ShouldOptimizeCast(Op0C
->getOpcode(), Op0C
->getOperand(0),
2254 ShouldOptimizeCast(Op1C
->getOpcode(), Op1C
->getOperand(0),
2256 Value
*NewOp
= Builder
->CreateXor(Op0C
->getOperand(0),
2257 Op1C
->getOperand(0), I
.getName());
2258 return CastInst::Create(Op0C
->getOpcode(), NewOp
, I
.getType());
2263 return Changed
? &I
: 0;