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/PatternMatch.h"
19 using namespace PatternMatch;
22 /// AddOne - Add one to a ConstantInt.
23 static Constant *AddOne(Constant *C) {
24 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
26 /// SubOne - Subtract one from a ConstantInt.
27 static Constant *SubOne(ConstantInt *C) {
28 return ConstantInt::get(C->getContext(), C->getValue()-1);
31 /// isFreeToInvert - Return true if the specified value is free to invert (apply
32 /// ~ to). This happens in cases where the ~ can be eliminated.
33 static inline bool isFreeToInvert(Value *V) {
35 if (BinaryOperator::isNot(V))
38 // Constants can be considered to be not'ed values.
39 if (isa<ConstantInt>(V))
42 // Compares can be inverted if they have a single use.
43 if (CmpInst *CI = dyn_cast<CmpInst>(V))
44 return CI->hasOneUse();
49 static inline Value *dyn_castNotVal(Value *V) {
50 // If this is not(not(x)) don't return that this is a not: we want the two
51 // not's to be folded first.
52 if (BinaryOperator::isNot(V)) {
53 Value *Operand = BinaryOperator::getNotArgument(V);
54 if (!isFreeToInvert(Operand))
58 // Constants can be considered to be not'ed values...
59 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
60 return ConstantInt::get(C->getType(), ~C->getValue());
65 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
66 /// are carefully arranged to allow folding of expressions such as:
68 /// (A < B) | (A > B) --> (A != B)
70 /// Note that this is only valid if the first and second predicates have the
71 /// same sign. Is illegal to do: (A u< B) | (A s> B)
73 /// Three bits are used to represent the condition, as follows:
78 /// <=> Value Definition
79 /// 000 0 Always false
88 static unsigned getICmpCode(const ICmpInst *ICI) {
89 switch (ICI->getPredicate()) {
91 case ICmpInst::ICMP_UGT: return 1; // 001
92 case ICmpInst::ICMP_SGT: return 1; // 001
93 case ICmpInst::ICMP_EQ: return 2; // 010
94 case ICmpInst::ICMP_UGE: return 3; // 011
95 case ICmpInst::ICMP_SGE: return 3; // 011
96 case ICmpInst::ICMP_ULT: return 4; // 100
97 case ICmpInst::ICMP_SLT: return 4; // 100
98 case ICmpInst::ICMP_NE: return 5; // 101
99 case ICmpInst::ICMP_ULE: return 6; // 110
100 case ICmpInst::ICMP_SLE: return 6; // 110
103 llvm_unreachable("Invalid ICmp predicate!");
108 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
109 /// predicate into a three bit mask. It also returns whether it is an ordered
110 /// predicate by reference.
111 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
114 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
115 case FCmpInst::FCMP_UNO: return 0; // 000
116 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
117 case FCmpInst::FCMP_UGT: return 1; // 001
118 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
119 case FCmpInst::FCMP_UEQ: return 2; // 010
120 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
121 case FCmpInst::FCMP_UGE: return 3; // 011
122 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
123 case FCmpInst::FCMP_ULT: return 4; // 100
124 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
125 case FCmpInst::FCMP_UNE: return 5; // 101
126 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
127 case FCmpInst::FCMP_ULE: return 6; // 110
130 // Not expecting FCMP_FALSE and FCMP_TRUE;
131 llvm_unreachable("Unexpected FCmp predicate!");
136 /// getICmpValue - This is the complement of getICmpCode, which turns an
137 /// opcode and two operands into either a constant true or false, or a brand
138 /// new ICmp instruction. The sign is passed in to determine which kind
139 /// of predicate to use in the new icmp instruction.
140 static Value *getICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS) {
142 default: assert(0 && "Illegal ICmp code!");
144 return ConstantInt::getFalse(LHS->getContext());
147 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
148 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
150 return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
153 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
154 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
157 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
158 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
160 return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
163 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
164 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
166 return ConstantInt::getTrue(LHS->getContext());
170 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
171 /// opcode and two operands into either a FCmp instruction. isordered is passed
172 /// in to determine which kind of predicate to use in the new fcmp instruction.
173 static Value *getFCmpValue(bool isordered, unsigned code,
174 Value *LHS, Value *RHS) {
176 default: llvm_unreachable("Illegal FCmp code!");
179 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
181 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
184 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
186 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
189 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
191 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
194 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
196 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
199 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
201 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
204 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
206 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
209 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
211 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
212 case 7: return ConstantInt::getTrue(LHS->getContext());
216 /// PredicatesFoldable - Return true if both predicates match sign or if at
217 /// least one of them is an equality comparison (which is signless).
218 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
219 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
220 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
221 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
224 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
225 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
226 // guaranteed to be a binary operator.
227 Instruction *InstCombiner::OptAndOp(Instruction *Op,
230 BinaryOperator &TheAnd) {
231 Value *X = Op->getOperand(0);
232 Constant *Together = 0;
234 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
236 switch (Op->getOpcode()) {
237 case Instruction::Xor:
238 if (Op->hasOneUse()) {
239 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
240 Value *And = Builder->CreateAnd(X, AndRHS);
242 return BinaryOperator::CreateXor(And, Together);
245 case Instruction::Or:
246 if (Together == AndRHS) // (X | C) & C --> C
247 return ReplaceInstUsesWith(TheAnd, AndRHS);
249 if (Op->hasOneUse() && Together != OpRHS) {
250 // (X | C1) & C2 --> (X | (C1&C2)) & C2
251 Value *Or = Builder->CreateOr(X, Together);
253 return BinaryOperator::CreateAnd(Or, AndRHS);
256 case Instruction::Add:
257 if (Op->hasOneUse()) {
258 // Adding a one to a single bit bit-field should be turned into an XOR
259 // of the bit. First thing to check is to see if this AND is with a
260 // single bit constant.
261 const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
263 // If there is only one bit set.
264 if (AndRHSV.isPowerOf2()) {
265 // Ok, at this point, we know that we are masking the result of the
266 // ADD down to exactly one bit. If the constant we are adding has
267 // no bits set below this bit, then we can eliminate the ADD.
268 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
270 // Check to see if any bits below the one bit set in AndRHSV are set.
271 if ((AddRHS & (AndRHSV-1)) == 0) {
272 // If not, the only thing that can effect the output of the AND is
273 // the bit specified by AndRHSV. If that bit is set, the effect of
274 // the XOR is to toggle the bit. If it is clear, then the ADD has
276 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
277 TheAnd.setOperand(0, X);
280 // Pull the XOR out of the AND.
281 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
282 NewAnd->takeName(Op);
283 return BinaryOperator::CreateXor(NewAnd, AndRHS);
290 case Instruction::Shl: {
291 // We know that the AND will not produce any of the bits shifted in, so if
292 // the anded constant includes them, clear them now!
294 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
295 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
296 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
297 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
298 AndRHS->getValue() & ShlMask);
300 if (CI->getValue() == ShlMask) {
301 // Masking out bits that the shift already masks
302 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
303 } else if (CI != AndRHS) { // Reducing bits set in and.
304 TheAnd.setOperand(1, CI);
309 case Instruction::LShr: {
310 // We know that the AND will not produce any of the bits shifted in, so if
311 // the anded constant includes them, clear them now! This only applies to
312 // unsigned shifts, because a signed shr may bring in set bits!
314 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
315 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
316 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
317 ConstantInt *CI = ConstantInt::get(Op->getContext(),
318 AndRHS->getValue() & ShrMask);
320 if (CI->getValue() == ShrMask) {
321 // Masking out bits that the shift already masks.
322 return ReplaceInstUsesWith(TheAnd, Op);
323 } else if (CI != AndRHS) {
324 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
329 case Instruction::AShr:
331 // See if this is shifting in some sign extension, then masking it out
333 if (Op->hasOneUse()) {
334 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
335 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
336 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
337 Constant *C = ConstantInt::get(Op->getContext(),
338 AndRHS->getValue() & ShrMask);
339 if (C == AndRHS) { // Masking out bits shifted in.
340 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
341 // Make the argument unsigned.
342 Value *ShVal = Op->getOperand(0);
343 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
344 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
353 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
354 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
355 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
356 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
357 /// insert new instructions.
358 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
359 bool isSigned, bool Inside,
361 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
362 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
363 "Lo is not <= Hi in range emission code!");
366 if (Lo == Hi) // Trivially false.
367 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
369 // V >= Min && V < Hi --> V < Hi
370 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
371 ICmpInst::Predicate pred = (isSigned ?
372 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
373 return new ICmpInst(pred, V, Hi);
376 // Emit V-Lo <u Hi-Lo
377 Constant *NegLo = ConstantExpr::getNeg(Lo);
378 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
379 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
380 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
383 if (Lo == Hi) // Trivially true.
384 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
386 // V < Min || V >= Hi -> V > Hi-1
387 Hi = SubOne(cast<ConstantInt>(Hi));
388 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
389 ICmpInst::Predicate pred = (isSigned ?
390 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
391 return new ICmpInst(pred, V, Hi);
394 // Emit V-Lo >u Hi-1-Lo
395 // Note that Hi has already had one subtracted from it, above.
396 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
397 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
398 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
399 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
402 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
403 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
404 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
405 // not, since all 1s are not contiguous.
406 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
407 const APInt& V = Val->getValue();
408 uint32_t BitWidth = Val->getType()->getBitWidth();
409 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
411 // look for the first zero bit after the run of ones
412 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
413 // look for the first non-zero bit
414 ME = V.getActiveBits();
418 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
419 /// where isSub determines whether the operator is a sub. If we can fold one of
420 /// the following xforms:
422 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
423 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
424 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
426 /// return (A +/- B).
428 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
429 ConstantInt *Mask, bool isSub,
431 Instruction *LHSI = dyn_cast<Instruction>(LHS);
432 if (!LHSI || LHSI->getNumOperands() != 2 ||
433 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
435 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
437 switch (LHSI->getOpcode()) {
439 case Instruction::And:
440 if (ConstantExpr::getAnd(N, Mask) == Mask) {
441 // If the AndRHS is a power of two minus one (0+1+), this is simple.
442 if ((Mask->getValue().countLeadingZeros() +
443 Mask->getValue().countPopulation()) ==
444 Mask->getValue().getBitWidth())
447 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
448 // part, we don't need any explicit masks to take them out of A. If that
449 // is all N is, ignore it.
450 uint32_t MB = 0, ME = 0;
451 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
452 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
453 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
454 if (MaskedValueIsZero(RHS, Mask))
459 case Instruction::Or:
460 case Instruction::Xor:
461 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
462 if ((Mask->getValue().countLeadingZeros() +
463 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
464 && ConstantExpr::getAnd(N, Mask)->isNullValue())
470 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
471 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
474 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
475 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
476 ICmpInst *LHS, ICmpInst *RHS) {
477 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
479 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
480 if (PredicatesFoldable(LHSCC, RHSCC)) {
481 if (LHS->getOperand(0) == RHS->getOperand(1) &&
482 LHS->getOperand(1) == RHS->getOperand(0))
484 if (LHS->getOperand(0) == RHS->getOperand(0) &&
485 LHS->getOperand(1) == RHS->getOperand(1)) {
486 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
487 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
488 bool isSigned = LHS->isSigned() || RHS->isSigned();
489 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
490 if (Instruction *I = dyn_cast<Instruction>(RV))
492 // Otherwise, it's a constant boolean value.
493 return ReplaceInstUsesWith(I, RV);
497 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
498 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
499 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
500 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
501 if (LHSCst == 0 || RHSCst == 0) return 0;
503 if (LHSCst == RHSCst && LHSCC == RHSCC) {
504 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
505 // where C is a power of 2
506 if (LHSCC == ICmpInst::ICMP_ULT &&
507 LHSCst->getValue().isPowerOf2()) {
508 Value *NewOr = Builder->CreateOr(Val, Val2);
509 return new ICmpInst(LHSCC, NewOr, LHSCst);
512 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
513 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
514 Value *NewOr = Builder->CreateOr(Val, Val2);
515 return new ICmpInst(LHSCC, NewOr, LHSCst);
519 // From here on, we only handle:
520 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
521 if (Val != Val2) return 0;
523 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
524 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
525 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
526 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
527 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
530 // We can't fold (ugt x, C) & (sgt x, C2).
531 if (!PredicatesFoldable(LHSCC, RHSCC))
534 // Ensure that the larger constant is on the RHS.
536 if (CmpInst::isSigned(LHSCC) ||
537 (ICmpInst::isEquality(LHSCC) &&
538 CmpInst::isSigned(RHSCC)))
539 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
541 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
545 std::swap(LHSCst, RHSCst);
546 std::swap(LHSCC, RHSCC);
549 // At this point, we know we have have two icmp instructions
550 // comparing a value against two constants and and'ing the result
551 // together. Because of the above check, we know that we only have
552 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
553 // (from the icmp folding check above), that the two constants
554 // are not equal and that the larger constant is on the RHS
555 assert(LHSCst != RHSCst && "Compares not folded above?");
558 default: llvm_unreachable("Unknown integer condition code!");
559 case ICmpInst::ICMP_EQ:
561 default: llvm_unreachable("Unknown integer condition code!");
562 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
563 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
564 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
565 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
566 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
567 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
568 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
569 return ReplaceInstUsesWith(I, LHS);
571 case ICmpInst::ICMP_NE:
573 default: llvm_unreachable("Unknown integer condition code!");
574 case ICmpInst::ICMP_ULT:
575 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
576 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
577 break; // (X != 13 & X u< 15) -> no change
578 case ICmpInst::ICMP_SLT:
579 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
580 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
581 break; // (X != 13 & X s< 15) -> no change
582 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
583 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
584 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
585 return ReplaceInstUsesWith(I, RHS);
586 case ICmpInst::ICMP_NE:
587 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
588 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
589 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
590 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
591 ConstantInt::get(Add->getType(), 1));
593 break; // (X != 13 & X != 15) -> no change
596 case ICmpInst::ICMP_ULT:
598 default: llvm_unreachable("Unknown integer condition code!");
599 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
600 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
601 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
602 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
604 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
605 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
606 return ReplaceInstUsesWith(I, LHS);
607 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
611 case ICmpInst::ICMP_SLT:
613 default: llvm_unreachable("Unknown integer condition code!");
614 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
615 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
616 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
617 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
619 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
620 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
621 return ReplaceInstUsesWith(I, LHS);
622 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
626 case ICmpInst::ICMP_UGT:
628 default: llvm_unreachable("Unknown integer condition code!");
629 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
630 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
631 return ReplaceInstUsesWith(I, RHS);
632 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
634 case ICmpInst::ICMP_NE:
635 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
636 return new ICmpInst(LHSCC, Val, RHSCst);
637 break; // (X u> 13 & X != 15) -> no change
638 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
639 return InsertRangeTest(Val, AddOne(LHSCst),
640 RHSCst, false, true, I);
641 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
645 case ICmpInst::ICMP_SGT:
647 default: llvm_unreachable("Unknown integer condition code!");
648 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
649 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
650 return ReplaceInstUsesWith(I, RHS);
651 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
653 case ICmpInst::ICMP_NE:
654 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
655 return new ICmpInst(LHSCC, Val, RHSCst);
656 break; // (X s> 13 & X != 15) -> no change
657 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
658 return InsertRangeTest(Val, AddOne(LHSCst),
659 RHSCst, true, true, I);
660 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
669 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
672 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
673 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
674 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
675 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
676 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
677 // If either of the constants are nans, then the whole thing returns
679 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
680 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
681 return new FCmpInst(FCmpInst::FCMP_ORD,
682 LHS->getOperand(0), RHS->getOperand(0));
685 // Handle vector zeros. This occurs because the canonical form of
686 // "fcmp ord x,x" is "fcmp ord x, 0".
687 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
688 isa<ConstantAggregateZero>(RHS->getOperand(1)))
689 return new FCmpInst(FCmpInst::FCMP_ORD,
690 LHS->getOperand(0), RHS->getOperand(0));
694 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
695 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
696 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
699 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
700 // Swap RHS operands to match LHS.
701 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
702 std::swap(Op1LHS, Op1RHS);
705 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
706 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
708 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
710 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
711 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
712 if (Op0CC == FCmpInst::FCMP_TRUE)
713 return ReplaceInstUsesWith(I, RHS);
714 if (Op1CC == FCmpInst::FCMP_TRUE)
715 return ReplaceInstUsesWith(I, LHS);
719 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
720 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
723 std::swap(Op0Pred, Op1Pred);
724 std::swap(Op0Ordered, Op1Ordered);
727 // uno && ueq -> uno && (uno || eq) -> ueq
728 // ord && olt -> ord && (ord && lt) -> olt
729 if (Op0Ordered == Op1Ordered)
730 return ReplaceInstUsesWith(I, RHS);
732 // uno && oeq -> uno && (ord && eq) -> false
733 // uno && ord -> false
735 return ReplaceInstUsesWith(I, ConstantInt::getFalse(I.getContext()));
736 // ord && ueq -> ord && (uno || eq) -> oeq
737 return cast<Instruction>(getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS));
745 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
746 bool Changed = SimplifyCommutative(I);
747 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
749 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
750 return ReplaceInstUsesWith(I, V);
752 // See if we can simplify any instructions used by the instruction whose sole
753 // purpose is to compute bits we don't care about.
754 if (SimplifyDemandedInstructionBits(I))
757 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
758 const APInt &AndRHSMask = AndRHS->getValue();
759 APInt NotAndRHS(~AndRHSMask);
761 // Optimize a variety of ((val OP C1) & C2) combinations...
762 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
763 Value *Op0LHS = Op0I->getOperand(0);
764 Value *Op0RHS = Op0I->getOperand(1);
765 switch (Op0I->getOpcode()) {
767 case Instruction::Xor:
768 case Instruction::Or:
769 // If the mask is only needed on one incoming arm, push it up.
770 if (!Op0I->hasOneUse()) break;
772 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
773 // Not masking anything out for the LHS, move to RHS.
774 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
775 Op0RHS->getName()+".masked");
776 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
778 if (!isa<Constant>(Op0RHS) &&
779 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
780 // Not masking anything out for the RHS, move to LHS.
781 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
782 Op0LHS->getName()+".masked");
783 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
787 case Instruction::Add:
788 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
789 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
790 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
791 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
792 return BinaryOperator::CreateAnd(V, AndRHS);
793 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
794 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
797 case Instruction::Sub:
798 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
799 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
800 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
801 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
802 return BinaryOperator::CreateAnd(V, AndRHS);
804 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
805 // has 1's for all bits that the subtraction with A might affect.
806 if (Op0I->hasOneUse()) {
807 uint32_t BitWidth = AndRHSMask.getBitWidth();
808 uint32_t Zeros = AndRHSMask.countLeadingZeros();
809 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
811 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
812 if (!(A && A->isZero()) && // avoid infinite recursion.
813 MaskedValueIsZero(Op0LHS, Mask)) {
814 Value *NewNeg = Builder->CreateNeg(Op0RHS);
815 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
820 case Instruction::Shl:
821 case Instruction::LShr:
822 // (1 << x) & 1 --> zext(x == 0)
823 // (1 >> x) & 1 --> zext(x == 0)
824 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
826 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
827 return new ZExtInst(NewICmp, I.getType());
832 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
833 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
835 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
836 // If this is an integer truncation or change from signed-to-unsigned, and
837 // if the source is an and/or with immediate, transform it. This
838 // frequently occurs for bitfield accesses.
839 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
840 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
841 CastOp->getNumOperands() == 2)
842 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
843 if (CastOp->getOpcode() == Instruction::And) {
844 // Change: and (cast (and X, C1) to T), C2
845 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
846 // This will fold the two constants together, which may allow
847 // other simplifications.
848 Value *NewCast = Builder->CreateTruncOrBitCast(
849 CastOp->getOperand(0), I.getType(),
850 CastOp->getName()+".shrunk");
851 // trunc_or_bitcast(C1)&C2
852 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
853 C3 = ConstantExpr::getAnd(C3, AndRHS);
854 return BinaryOperator::CreateAnd(NewCast, C3);
855 } else if (CastOp->getOpcode() == Instruction::Or) {
856 // Change: and (cast (or X, C1) to T), C2
857 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
858 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
859 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
861 return ReplaceInstUsesWith(I, AndRHS);
867 // Try to fold constant and into select arguments.
868 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
869 if (Instruction *R = FoldOpIntoSelect(I, SI))
871 if (isa<PHINode>(Op0))
872 if (Instruction *NV = FoldOpIntoPhi(I))
877 // (~A & ~B) == (~(A | B)) - De Morgan's Law
878 if (Value *Op0NotVal = dyn_castNotVal(Op0))
879 if (Value *Op1NotVal = dyn_castNotVal(Op1))
880 if (Op0->hasOneUse() && Op1->hasOneUse()) {
881 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
882 I.getName()+".demorgan");
883 return BinaryOperator::CreateNot(Or);
887 Value *A = 0, *B = 0, *C = 0, *D = 0;
888 // (A|B) & ~(A&B) -> A^B
889 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
890 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
891 ((A == C && B == D) || (A == D && B == C)))
892 return BinaryOperator::CreateXor(A, B);
894 // ~(A&B) & (A|B) -> A^B
895 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
896 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
897 ((A == C && B == D) || (A == D && B == C)))
898 return BinaryOperator::CreateXor(A, B);
900 if (Op0->hasOneUse() &&
901 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
902 if (A == Op1) { // (A^B)&A -> A&(A^B)
903 I.swapOperands(); // Simplify below
905 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
906 cast<BinaryOperator>(Op0)->swapOperands();
907 I.swapOperands(); // Simplify below
912 if (Op1->hasOneUse() &&
913 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
914 if (B == Op0) { // B&(A^B) -> B&(B^A)
915 cast<BinaryOperator>(Op1)->swapOperands();
918 if (A == Op0) // A&(A^B) -> A & ~B
919 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
922 // (A&((~A)|B)) -> A&B
923 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
924 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
925 return BinaryOperator::CreateAnd(A, Op1);
926 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
927 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
928 return BinaryOperator::CreateAnd(A, Op0);
931 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
932 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
933 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
936 // fold (and (cast A), (cast B)) -> (cast (and A, B))
937 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
938 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
939 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
940 const Type *SrcTy = Op0C->getOperand(0)->getType();
941 if (SrcTy == Op1C->getOperand(0)->getType() &&
942 SrcTy->isIntOrIntVector() &&
943 // Only do this if the casts both really cause code to be generated.
944 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
946 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
948 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
949 Op1C->getOperand(0), I.getName());
950 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
954 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
955 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
956 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
957 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
958 SI0->getOperand(1) == SI1->getOperand(1) &&
959 (SI0->hasOneUse() || SI1->hasOneUse())) {
961 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
963 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
968 // If and'ing two fcmp, try combine them into one.
969 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
970 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
971 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
975 return Changed ? &I : 0;
978 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
979 /// capable of providing pieces of a bswap. The subexpression provides pieces
980 /// of a bswap if it is proven that each of the non-zero bytes in the output of
981 /// the expression came from the corresponding "byte swapped" byte in some other
982 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
983 /// we know that the expression deposits the low byte of %X into the high byte
984 /// of the bswap result and that all other bytes are zero. This expression is
985 /// accepted, the high byte of ByteValues is set to X to indicate a correct
988 /// This function returns true if the match was unsuccessful and false if so.
989 /// On entry to the function the "OverallLeftShift" is a signed integer value
990 /// indicating the number of bytes that the subexpression is later shifted. For
991 /// example, if the expression is later right shifted by 16 bits, the
992 /// OverallLeftShift value would be -2 on entry. This is used to specify which
993 /// byte of ByteValues is actually being set.
995 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
996 /// byte is masked to zero by a user. For example, in (X & 255), X will be
997 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
998 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
999 /// always in the local (OverallLeftShift) coordinate space.
1001 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1002 SmallVector<Value*, 8> &ByteValues) {
1003 if (Instruction *I = dyn_cast<Instruction>(V)) {
1004 // If this is an or instruction, it may be an inner node of the bswap.
1005 if (I->getOpcode() == Instruction::Or) {
1006 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1008 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1012 // If this is a logical shift by a constant multiple of 8, recurse with
1013 // OverallLeftShift and ByteMask adjusted.
1014 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1016 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1017 // Ensure the shift amount is defined and of a byte value.
1018 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1021 unsigned ByteShift = ShAmt >> 3;
1022 if (I->getOpcode() == Instruction::Shl) {
1023 // X << 2 -> collect(X, +2)
1024 OverallLeftShift += ByteShift;
1025 ByteMask >>= ByteShift;
1027 // X >>u 2 -> collect(X, -2)
1028 OverallLeftShift -= ByteShift;
1029 ByteMask <<= ByteShift;
1030 ByteMask &= (~0U >> (32-ByteValues.size()));
1033 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1034 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1036 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1040 // If this is a logical 'and' with a mask that clears bytes, clear the
1041 // corresponding bytes in ByteMask.
1042 if (I->getOpcode() == Instruction::And &&
1043 isa<ConstantInt>(I->getOperand(1))) {
1044 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1045 unsigned NumBytes = ByteValues.size();
1046 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1047 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1049 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1050 // If this byte is masked out by a later operation, we don't care what
1052 if ((ByteMask & (1 << i)) == 0)
1055 // If the AndMask is all zeros for this byte, clear the bit.
1056 APInt MaskB = AndMask & Byte;
1058 ByteMask &= ~(1U << i);
1062 // If the AndMask is not all ones for this byte, it's not a bytezap.
1066 // Otherwise, this byte is kept.
1069 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1074 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1075 // the input value to the bswap. Some observations: 1) if more than one byte
1076 // is demanded from this input, then it could not be successfully assembled
1077 // into a byteswap. At least one of the two bytes would not be aligned with
1078 // their ultimate destination.
1079 if (!isPowerOf2_32(ByteMask)) return true;
1080 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
1082 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1083 // is demanded, it needs to go into byte 0 of the result. This means that the
1084 // byte needs to be shifted until it lands in the right byte bucket. The
1085 // shift amount depends on the position: if the byte is coming from the high
1086 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1087 // low part, it must be shifted left.
1088 unsigned DestByteNo = InputByteNo + OverallLeftShift;
1089 if (InputByteNo < ByteValues.size()/2) {
1090 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1093 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1097 // If the destination byte value is already defined, the values are or'd
1098 // together, which isn't a bswap (unless it's an or of the same bits).
1099 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1101 ByteValues[DestByteNo] = V;
1105 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1106 /// If so, insert the new bswap intrinsic and return it.
1107 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1108 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1109 if (!ITy || ITy->getBitWidth() % 16 ||
1110 // ByteMask only allows up to 32-byte values.
1111 ITy->getBitWidth() > 32*8)
1112 return 0; // Can only bswap pairs of bytes. Can't do vectors.
1114 /// ByteValues - For each byte of the result, we keep track of which value
1115 /// defines each byte.
1116 SmallVector<Value*, 8> ByteValues;
1117 ByteValues.resize(ITy->getBitWidth()/8);
1119 // Try to find all the pieces corresponding to the bswap.
1120 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1121 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1124 // Check to see if all of the bytes come from the same value.
1125 Value *V = ByteValues[0];
1126 if (V == 0) return 0; // Didn't find a byte? Must be zero.
1128 // Check to make sure that all of the bytes come from the same value.
1129 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1130 if (ByteValues[i] != V)
1132 const Type *Tys[] = { ITy };
1133 Module *M = I.getParent()->getParent()->getParent();
1134 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
1135 return CallInst::Create(F, V);
1138 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1139 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1140 /// we can simplify this expression to "cond ? C : D or B".
1141 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1142 Value *C, Value *D) {
1143 // If A is not a select of -1/0, this cannot match.
1145 if (!match(A, m_SExt(m_Value(Cond))))
1148 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1149 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1150 return SelectInst::Create(Cond, C, B);
1151 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1152 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
1153 return SelectInst::Create(Cond, C, D);
1157 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1158 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
1159 ICmpInst *LHS, ICmpInst *RHS) {
1160 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1162 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1163 if (PredicatesFoldable(LHSCC, RHSCC)) {
1164 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1165 LHS->getOperand(1) == RHS->getOperand(0))
1166 LHS->swapOperands();
1167 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1168 LHS->getOperand(1) == RHS->getOperand(1)) {
1169 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1170 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1171 bool isSigned = LHS->isSigned() || RHS->isSigned();
1172 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
1173 if (Instruction *I = dyn_cast<Instruction>(RV))
1175 // Otherwise, it's a constant boolean value.
1176 return ReplaceInstUsesWith(I, RV);
1180 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1181 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1182 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1183 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1184 if (LHSCst == 0 || RHSCst == 0) return 0;
1186 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1187 if (LHSCst == RHSCst && LHSCC == RHSCC &&
1188 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1189 Value *NewOr = Builder->CreateOr(Val, Val2);
1190 return new ICmpInst(LHSCC, NewOr, LHSCst);
1193 // From here on, we only handle:
1194 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1195 if (Val != Val2) return 0;
1197 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1198 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1199 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1200 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1201 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1204 // We can't fold (ugt x, C) | (sgt x, C2).
1205 if (!PredicatesFoldable(LHSCC, RHSCC))
1208 // Ensure that the larger constant is on the RHS.
1210 if (CmpInst::isSigned(LHSCC) ||
1211 (ICmpInst::isEquality(LHSCC) &&
1212 CmpInst::isSigned(RHSCC)))
1213 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1215 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1218 std::swap(LHS, RHS);
1219 std::swap(LHSCst, RHSCst);
1220 std::swap(LHSCC, RHSCC);
1223 // At this point, we know we have have two icmp instructions
1224 // comparing a value against two constants and or'ing the result
1225 // together. Because of the above check, we know that we only have
1226 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1227 // icmp folding check above), that the two constants are not
1229 assert(LHSCst != RHSCst && "Compares not folded above?");
1232 default: llvm_unreachable("Unknown integer condition code!");
1233 case ICmpInst::ICMP_EQ:
1235 default: llvm_unreachable("Unknown integer condition code!");
1236 case ICmpInst::ICMP_EQ:
1237 if (LHSCst == SubOne(RHSCst)) {
1238 // (X == 13 | X == 14) -> X-13 <u 2
1239 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1240 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1241 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1242 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
1244 break; // (X == 13 | X == 15) -> no change
1245 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1246 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1248 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1249 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1250 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
1251 return ReplaceInstUsesWith(I, RHS);
1254 case ICmpInst::ICMP_NE:
1256 default: llvm_unreachable("Unknown integer condition code!");
1257 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1258 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1259 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
1260 return ReplaceInstUsesWith(I, LHS);
1261 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1262 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1263 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
1264 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1267 case ICmpInst::ICMP_ULT:
1269 default: llvm_unreachable("Unknown integer condition code!");
1270 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1272 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1273 // If RHSCst is [us]MAXINT, it is always false. Not handling
1274 // this can cause overflow.
1275 if (RHSCst->isMaxValue(false))
1276 return ReplaceInstUsesWith(I, LHS);
1277 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
1279 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1281 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1282 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
1283 return ReplaceInstUsesWith(I, RHS);
1284 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1288 case ICmpInst::ICMP_SLT:
1290 default: llvm_unreachable("Unknown integer condition code!");
1291 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1293 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1294 // If RHSCst is [us]MAXINT, it is always false. Not handling
1295 // this can cause overflow.
1296 if (RHSCst->isMaxValue(true))
1297 return ReplaceInstUsesWith(I, LHS);
1298 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
1300 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1302 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1303 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
1304 return ReplaceInstUsesWith(I, RHS);
1305 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1309 case ICmpInst::ICMP_UGT:
1311 default: llvm_unreachable("Unknown integer condition code!");
1312 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1313 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
1314 return ReplaceInstUsesWith(I, LHS);
1315 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1317 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1318 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
1319 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1320 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1324 case ICmpInst::ICMP_SGT:
1326 default: llvm_unreachable("Unknown integer condition code!");
1327 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1328 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
1329 return ReplaceInstUsesWith(I, LHS);
1330 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1332 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1333 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
1334 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1335 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1343 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
1345 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1346 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1347 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1348 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1349 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1350 // If either of the constants are nans, then the whole thing returns
1352 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1353 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1355 // Otherwise, no need to compare the two constants, compare the
1357 return new FCmpInst(FCmpInst::FCMP_UNO,
1358 LHS->getOperand(0), RHS->getOperand(0));
1361 // Handle vector zeros. This occurs because the canonical form of
1362 // "fcmp uno x,x" is "fcmp uno x, 0".
1363 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1364 isa<ConstantAggregateZero>(RHS->getOperand(1)))
1365 return new FCmpInst(FCmpInst::FCMP_UNO,
1366 LHS->getOperand(0), RHS->getOperand(0));
1371 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1372 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1373 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1375 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1376 // Swap RHS operands to match LHS.
1377 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1378 std::swap(Op1LHS, Op1RHS);
1380 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1381 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1383 return new FCmpInst((FCmpInst::Predicate)Op0CC,
1385 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
1386 return ReplaceInstUsesWith(I, ConstantInt::getTrue(I.getContext()));
1387 if (Op0CC == FCmpInst::FCMP_FALSE)
1388 return ReplaceInstUsesWith(I, RHS);
1389 if (Op1CC == FCmpInst::FCMP_FALSE)
1390 return ReplaceInstUsesWith(I, LHS);
1393 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1394 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1395 if (Op0Ordered == Op1Ordered) {
1396 // If both are ordered or unordered, return a new fcmp with
1397 // or'ed predicates.
1398 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS);
1399 if (Instruction *I = dyn_cast<Instruction>(RV))
1401 // Otherwise, it's a constant boolean value...
1402 return ReplaceInstUsesWith(I, RV);
1408 /// FoldOrWithConstants - This helper function folds:
1410 /// ((A | B) & C1) | (B & C2)
1416 /// when the XOR of the two constants is "all ones" (-1).
1417 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1418 Value *A, Value *B, Value *C) {
1419 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1423 ConstantInt *CI2 = 0;
1424 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1426 APInt Xor = CI1->getValue() ^ CI2->getValue();
1427 if (!Xor.isAllOnesValue()) return 0;
1429 if (V1 == A || V1 == B) {
1430 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1431 return BinaryOperator::CreateOr(NewOp, V1);
1437 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1438 bool Changed = SimplifyCommutative(I);
1439 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1441 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1442 return ReplaceInstUsesWith(I, V);
1445 // See if we can simplify any instructions used by the instruction whose sole
1446 // purpose is to compute bits we don't care about.
1447 if (SimplifyDemandedInstructionBits(I))
1450 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1451 ConstantInt *C1 = 0; Value *X = 0;
1452 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1453 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
1455 Value *Or = Builder->CreateOr(X, RHS);
1457 return BinaryOperator::CreateAnd(Or,
1458 ConstantInt::get(I.getContext(),
1459 RHS->getValue() | C1->getValue()));
1462 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1463 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1465 Value *Or = Builder->CreateOr(X, RHS);
1467 return BinaryOperator::CreateXor(Or,
1468 ConstantInt::get(I.getContext(),
1469 C1->getValue() & ~RHS->getValue()));
1472 // Try to fold constant and into select arguments.
1473 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1474 if (Instruction *R = FoldOpIntoSelect(I, SI))
1476 if (isa<PHINode>(Op0))
1477 if (Instruction *NV = FoldOpIntoPhi(I))
1481 Value *A = 0, *B = 0;
1482 ConstantInt *C1 = 0, *C2 = 0;
1484 // (A | B) | C and A | (B | C) -> bswap if possible.
1485 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1486 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1487 match(Op1, m_Or(m_Value(), m_Value())) ||
1488 (match(Op0, m_Shift(m_Value(), m_Value())) &&
1489 match(Op1, m_Shift(m_Value(), m_Value())))) {
1490 if (Instruction *BSwap = MatchBSwap(I))
1494 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1495 if (Op0->hasOneUse() &&
1496 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1497 MaskedValueIsZero(Op1, C1->getValue())) {
1498 Value *NOr = Builder->CreateOr(A, Op1);
1500 return BinaryOperator::CreateXor(NOr, C1);
1503 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1504 if (Op1->hasOneUse() &&
1505 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1506 MaskedValueIsZero(Op0, C1->getValue())) {
1507 Value *NOr = Builder->CreateOr(A, Op0);
1509 return BinaryOperator::CreateXor(NOr, C1);
1513 Value *C = 0, *D = 0;
1514 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1515 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1516 Value *V1 = 0, *V2 = 0, *V3 = 0;
1517 C1 = dyn_cast<ConstantInt>(C);
1518 C2 = dyn_cast<ConstantInt>(D);
1519 if (C1 && C2) { // (A & C1)|(B & C2)
1520 // If we have: ((V + N) & C1) | (V & C2)
1521 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1522 // replace with V+N.
1523 if (C1->getValue() == ~C2->getValue()) {
1524 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1525 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1526 // Add commutes, try both ways.
1527 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1528 return ReplaceInstUsesWith(I, A);
1529 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1530 return ReplaceInstUsesWith(I, A);
1532 // Or commutes, try both ways.
1533 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
1534 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1535 // Add commutes, try both ways.
1536 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1537 return ReplaceInstUsesWith(I, B);
1538 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1539 return ReplaceInstUsesWith(I, B);
1543 if ((C1->getValue() & C2->getValue()) == 0) {
1544 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1545 // iff (C1&C2) == 0 and (N&~C1) == 0
1546 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1547 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
1548 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
1549 return BinaryOperator::CreateAnd(A,
1550 ConstantInt::get(A->getContext(),
1551 C1->getValue()|C2->getValue()));
1552 // Or commutes, try both ways.
1553 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1554 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
1555 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
1556 return BinaryOperator::CreateAnd(B,
1557 ConstantInt::get(B->getContext(),
1558 C1->getValue()|C2->getValue()));
1560 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
1561 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
1562 ConstantInt *C3 = 0, *C4 = 0;
1563 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
1564 (C3->getValue() & ~C1->getValue()) == 0 &&
1565 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
1566 (C4->getValue() & ~C2->getValue()) == 0) {
1567 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
1568 return BinaryOperator::CreateAnd(V2,
1569 ConstantInt::get(B->getContext(),
1570 C1->getValue()|C2->getValue()));
1575 // Check to see if we have any common things being and'ed. If so, find the
1576 // terms for V1 & (V2|V3).
1577 if (Op0->hasOneUse() || Op1->hasOneUse()) {
1579 if (A == B) // (A & C)|(A & D) == A & (C|D)
1580 V1 = A, V2 = C, V3 = D;
1581 else if (A == D) // (A & C)|(B & A) == A & (B|C)
1582 V1 = A, V2 = B, V3 = C;
1583 else if (C == B) // (A & C)|(C & D) == C & (A|D)
1584 V1 = C, V2 = A, V3 = D;
1585 else if (C == D) // (A & C)|(B & C) == C & (A|B)
1586 V1 = C, V2 = A, V3 = B;
1589 Value *Or = Builder->CreateOr(V2, V3, "tmp");
1590 return BinaryOperator::CreateAnd(V1, Or);
1594 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
1595 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
1597 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
1599 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
1601 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
1604 // ((A&~B)|(~A&B)) -> A^B
1605 if ((match(C, m_Not(m_Specific(D))) &&
1606 match(B, m_Not(m_Specific(A)))))
1607 return BinaryOperator::CreateXor(A, D);
1608 // ((~B&A)|(~A&B)) -> A^B
1609 if ((match(A, m_Not(m_Specific(D))) &&
1610 match(B, m_Not(m_Specific(C)))))
1611 return BinaryOperator::CreateXor(C, D);
1612 // ((A&~B)|(B&~A)) -> A^B
1613 if ((match(C, m_Not(m_Specific(B))) &&
1614 match(D, m_Not(m_Specific(A)))))
1615 return BinaryOperator::CreateXor(A, B);
1616 // ((~B&A)|(B&~A)) -> A^B
1617 if ((match(A, m_Not(m_Specific(B))) &&
1618 match(D, m_Not(m_Specific(C)))))
1619 return BinaryOperator::CreateXor(C, B);
1622 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
1623 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1624 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1625 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1626 SI0->getOperand(1) == SI1->getOperand(1) &&
1627 (SI0->hasOneUse() || SI1->hasOneUse())) {
1628 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1630 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1631 SI1->getOperand(1));
1635 // ((A|B)&1)|(B&-2) -> (A&1) | B
1636 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
1637 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
1638 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
1639 if (Ret) return Ret;
1641 // (B&-2)|((A|B)&1) -> (A&1) | B
1642 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
1643 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
1644 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
1645 if (Ret) return Ret;
1648 // (~A | ~B) == (~(A & B)) - De Morgan's Law
1649 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1650 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1651 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1652 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
1653 I.getName()+".demorgan");
1654 return BinaryOperator::CreateNot(And);
1657 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1658 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
1659 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
1662 // fold (or (cast A), (cast B)) -> (cast (or A, B))
1663 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1664 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
1665 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
1666 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
1667 !isa<ICmpInst>(Op1C->getOperand(0))) {
1668 const Type *SrcTy = Op0C->getOperand(0)->getType();
1669 if (SrcTy == Op1C->getOperand(0)->getType() &&
1670 SrcTy->isIntOrIntVector() &&
1671 // Only do this if the casts both really cause code to be
1673 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
1675 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
1677 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
1678 Op1C->getOperand(0), I.getName());
1679 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1686 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
1687 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
1688 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1689 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
1693 return Changed ? &I : 0;
1696 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
1697 bool Changed = SimplifyCommutative(I);
1698 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1700 if (isa<UndefValue>(Op1)) {
1701 if (isa<UndefValue>(Op0))
1702 // Handle undef ^ undef -> 0 special case. This is a common
1704 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1705 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1710 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1712 // See if we can simplify any instructions used by the instruction whose sole
1713 // purpose is to compute bits we don't care about.
1714 if (SimplifyDemandedInstructionBits(I))
1716 if (isa<VectorType>(I.getType()))
1717 if (isa<ConstantAggregateZero>(Op1))
1718 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
1720 // Is this a ~ operation?
1721 if (Value *NotOp = dyn_castNotVal(&I)) {
1722 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
1723 if (Op0I->getOpcode() == Instruction::And ||
1724 Op0I->getOpcode() == Instruction::Or) {
1725 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
1726 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
1727 if (dyn_castNotVal(Op0I->getOperand(1)))
1728 Op0I->swapOperands();
1729 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1731 Builder->CreateNot(Op0I->getOperand(1),
1732 Op0I->getOperand(1)->getName()+".not");
1733 if (Op0I->getOpcode() == Instruction::And)
1734 return BinaryOperator::CreateOr(Op0NotVal, NotY);
1735 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
1738 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
1739 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
1740 if (isFreeToInvert(Op0I->getOperand(0)) &&
1741 isFreeToInvert(Op0I->getOperand(1))) {
1743 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
1745 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
1746 if (Op0I->getOpcode() == Instruction::And)
1747 return BinaryOperator::CreateOr(NotX, NotY);
1748 return BinaryOperator::CreateAnd(NotX, NotY);
1751 } else if (Op0I->getOpcode() == Instruction::AShr) {
1752 // ~(~X >>s Y) --> (X >>s Y)
1753 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
1754 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
1760 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1761 if (RHS->isOne() && Op0->hasOneUse()) {
1762 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
1763 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
1764 return new ICmpInst(ICI->getInversePredicate(),
1765 ICI->getOperand(0), ICI->getOperand(1));
1767 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
1768 return new FCmpInst(FCI->getInversePredicate(),
1769 FCI->getOperand(0), FCI->getOperand(1));
1772 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
1773 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1774 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
1775 if (CI->hasOneUse() && Op0C->hasOneUse()) {
1776 Instruction::CastOps Opcode = Op0C->getOpcode();
1777 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
1778 (RHS == ConstantExpr::getCast(Opcode,
1779 ConstantInt::getTrue(I.getContext()),
1780 Op0C->getDestTy()))) {
1781 CI->setPredicate(CI->getInversePredicate());
1782 return CastInst::Create(Opcode, CI, Op0C->getType());
1788 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1789 // ~(c-X) == X-c-1 == X+(-c-1)
1790 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1791 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
1792 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1793 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
1794 ConstantInt::get(I.getType(), 1));
1795 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
1798 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
1799 if (Op0I->getOpcode() == Instruction::Add) {
1800 // ~(X-c) --> (-c-1)-X
1801 if (RHS->isAllOnesValue()) {
1802 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1803 return BinaryOperator::CreateSub(
1804 ConstantExpr::getSub(NegOp0CI,
1805 ConstantInt::get(I.getType(), 1)),
1806 Op0I->getOperand(0));
1807 } else if (RHS->getValue().isSignBit()) {
1808 // (X + C) ^ signbit -> (X + C + signbit)
1809 Constant *C = ConstantInt::get(I.getContext(),
1810 RHS->getValue() + Op0CI->getValue());
1811 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
1814 } else if (Op0I->getOpcode() == Instruction::Or) {
1815 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
1816 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
1817 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
1818 // Anything in both C1 and C2 is known to be zero, remove it from
1820 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
1821 NewRHS = ConstantExpr::getAnd(NewRHS,
1822 ConstantExpr::getNot(CommonBits));
1824 I.setOperand(0, Op0I->getOperand(0));
1825 I.setOperand(1, NewRHS);
1832 // Try to fold constant and into select arguments.
1833 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1834 if (Instruction *R = FoldOpIntoSelect(I, SI))
1836 if (isa<PHINode>(Op0))
1837 if (Instruction *NV = FoldOpIntoPhi(I))
1841 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
1843 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
1845 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
1847 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
1850 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
1853 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
1854 if (A == Op0) { // B^(B|A) == (A|B)^B
1855 Op1I->swapOperands();
1857 std::swap(Op0, Op1);
1858 } else if (B == Op0) { // B^(A|B) == (A|B)^B
1859 I.swapOperands(); // Simplified below.
1860 std::swap(Op0, Op1);
1862 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
1863 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
1864 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
1865 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
1866 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
1868 if (A == Op0) { // A^(A&B) -> A^(B&A)
1869 Op1I->swapOperands();
1872 if (B == Op0) { // A^(B&A) -> (B&A)^A
1873 I.swapOperands(); // Simplified below.
1874 std::swap(Op0, Op1);
1879 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
1882 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
1883 Op0I->hasOneUse()) {
1884 if (A == Op1) // (B|A)^B == (A|B)^B
1886 if (B == Op1) // (A|B)^B == A & ~B
1887 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
1888 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
1889 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
1890 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
1891 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
1892 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
1894 if (A == Op1) // (A&B)^A -> (B&A)^A
1896 if (B == Op1 && // (B&A)^A == ~B & A
1897 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
1898 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
1903 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
1904 if (Op0I && Op1I && Op0I->isShift() &&
1905 Op0I->getOpcode() == Op1I->getOpcode() &&
1906 Op0I->getOperand(1) == Op1I->getOperand(1) &&
1907 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
1909 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
1911 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
1912 Op1I->getOperand(1));
1916 Value *A, *B, *C, *D;
1917 // (A & B)^(A | B) -> A ^ B
1918 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
1919 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
1920 if ((A == C && B == D) || (A == D && B == C))
1921 return BinaryOperator::CreateXor(A, B);
1923 // (A | B)^(A & B) -> A ^ B
1924 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
1925 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
1926 if ((A == C && B == D) || (A == D && B == C))
1927 return BinaryOperator::CreateXor(A, B);
1931 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
1932 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
1933 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
1934 // (X & Y)^(X & Y) -> (Y^Z) & X
1935 Value *X = 0, *Y = 0, *Z = 0;
1937 X = A, Y = B, Z = D;
1939 X = A, Y = B, Z = C;
1941 X = B, Y = A, Z = D;
1943 X = B, Y = A, Z = C;
1946 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
1947 return BinaryOperator::CreateAnd(NewOp, X);
1952 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
1953 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1954 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
1955 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
1956 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1957 LHS->getOperand(1) == RHS->getOperand(0))
1958 LHS->swapOperands();
1959 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1960 LHS->getOperand(1) == RHS->getOperand(1)) {
1961 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1962 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
1963 bool isSigned = LHS->isSigned() || RHS->isSigned();
1964 Value *RV = getICmpValue(isSigned, Code, Op0, Op1);
1965 if (Instruction *I = dyn_cast<Instruction>(RV))
1967 // Otherwise, it's a constant boolean value.
1968 return ReplaceInstUsesWith(I, RV);
1972 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
1973 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1974 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
1975 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
1976 const Type *SrcTy = Op0C->getOperand(0)->getType();
1977 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
1978 // Only do this if the casts both really cause code to be generated.
1979 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
1981 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
1983 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
1984 Op1C->getOperand(0), I.getName());
1985 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1990 return Changed ? &I : 0;