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/Analysis/InstructionSimplify.h"
16 #include "llvm/IR/Intrinsics.h"
17 #include "llvm/Support/ConstantRange.h"
18 #include "llvm/Support/PatternMatch.h"
19 #include "llvm/Transforms/Utils/CmpInstAnalysis.h"
21 using namespace PatternMatch;
24 /// AddOne - Add one to a ConstantInt.
25 static Constant *AddOne(Constant *C) {
26 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
28 /// SubOne - Subtract one from a ConstantInt.
29 static Constant *SubOne(ConstantInt *C) {
30 return ConstantInt::get(C->getContext(), C->getValue()-1);
33 /// isFreeToInvert - Return true if the specified value is free to invert (apply
34 /// ~ to). This happens in cases where the ~ can be eliminated.
35 static inline bool isFreeToInvert(Value *V) {
37 if (BinaryOperator::isNot(V))
40 // Constants can be considered to be not'ed values.
41 if (isa<ConstantInt>(V))
44 // Compares can be inverted if they have a single use.
45 if (CmpInst *CI = dyn_cast<CmpInst>(V))
46 return CI->hasOneUse();
51 static inline Value *dyn_castNotVal(Value *V) {
52 // If this is not(not(x)) don't return that this is a not: we want the two
53 // not's to be folded first.
54 if (BinaryOperator::isNot(V)) {
55 Value *Operand = BinaryOperator::getNotArgument(V);
56 if (!isFreeToInvert(Operand))
60 // Constants can be considered to be not'ed values...
61 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
62 return ConstantInt::get(C->getType(), ~C->getValue());
66 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
67 /// predicate into a three bit mask. It also returns whether it is an ordered
68 /// predicate by reference.
69 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
72 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
73 case FCmpInst::FCMP_UNO: return 0; // 000
74 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
75 case FCmpInst::FCMP_UGT: return 1; // 001
76 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
77 case FCmpInst::FCMP_UEQ: return 2; // 010
78 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
79 case FCmpInst::FCMP_UGE: return 3; // 011
80 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
81 case FCmpInst::FCMP_ULT: return 4; // 100
82 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
83 case FCmpInst::FCMP_UNE: return 5; // 101
84 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
85 case FCmpInst::FCMP_ULE: return 6; // 110
88 // Not expecting FCMP_FALSE and FCMP_TRUE;
89 llvm_unreachable("Unexpected FCmp predicate!");
93 /// getNewICmpValue - This is the complement of getICmpCode, which turns an
94 /// opcode and two operands into either a constant true or false, or a brand
95 /// new ICmp instruction. The sign is passed in to determine which kind
96 /// of predicate to use in the new icmp instruction.
97 static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
98 InstCombiner::BuilderTy *Builder) {
99 ICmpInst::Predicate NewPred;
100 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
102 return Builder->CreateICmp(NewPred, LHS, RHS);
105 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
106 /// opcode and two operands into either a FCmp instruction. isordered is passed
107 /// in to determine which kind of predicate to use in the new fcmp instruction.
108 static Value *getFCmpValue(bool isordered, unsigned code,
109 Value *LHS, Value *RHS,
110 InstCombiner::BuilderTy *Builder) {
111 CmpInst::Predicate Pred;
113 default: llvm_unreachable("Illegal FCmp code!");
114 case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
115 case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
116 case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
117 case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
118 case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
119 case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
120 case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
122 if (!isordered) return ConstantInt::getTrue(LHS->getContext());
123 Pred = FCmpInst::FCMP_ORD; break;
125 return Builder->CreateFCmp(Pred, LHS, RHS);
128 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
129 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
130 // guaranteed to be a binary operator.
131 Instruction *InstCombiner::OptAndOp(Instruction *Op,
134 BinaryOperator &TheAnd) {
135 Value *X = Op->getOperand(0);
136 Constant *Together = 0;
138 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
140 switch (Op->getOpcode()) {
141 case Instruction::Xor:
142 if (Op->hasOneUse()) {
143 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
144 Value *And = Builder->CreateAnd(X, AndRHS);
146 return BinaryOperator::CreateXor(And, Together);
149 case Instruction::Or:
150 if (Op->hasOneUse()){
151 if (Together != OpRHS) {
152 // (X | C1) & C2 --> (X | (C1&C2)) & C2
153 Value *Or = Builder->CreateOr(X, Together);
155 return BinaryOperator::CreateAnd(Or, AndRHS);
158 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
159 if (TogetherCI && !TogetherCI->isZero()){
160 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
161 // NOTE: This reduces the number of bits set in the & mask, which
162 // can expose opportunities for store narrowing.
163 Together = ConstantExpr::getXor(AndRHS, Together);
164 Value *And = Builder->CreateAnd(X, Together);
166 return BinaryOperator::CreateOr(And, OpRHS);
171 case Instruction::Add:
172 if (Op->hasOneUse()) {
173 // Adding a one to a single bit bit-field should be turned into an XOR
174 // of the bit. First thing to check is to see if this AND is with a
175 // single bit constant.
176 const APInt &AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
178 // If there is only one bit set.
179 if (AndRHSV.isPowerOf2()) {
180 // Ok, at this point, we know that we are masking the result of the
181 // ADD down to exactly one bit. If the constant we are adding has
182 // no bits set below this bit, then we can eliminate the ADD.
183 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
185 // Check to see if any bits below the one bit set in AndRHSV are set.
186 if ((AddRHS & (AndRHSV-1)) == 0) {
187 // If not, the only thing that can effect the output of the AND is
188 // the bit specified by AndRHSV. If that bit is set, the effect of
189 // the XOR is to toggle the bit. If it is clear, then the ADD has
191 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
192 TheAnd.setOperand(0, X);
195 // Pull the XOR out of the AND.
196 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
197 NewAnd->takeName(Op);
198 return BinaryOperator::CreateXor(NewAnd, AndRHS);
205 case Instruction::Shl: {
206 // We know that the AND will not produce any of the bits shifted in, so if
207 // the anded constant includes them, clear them now!
209 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
210 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
211 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
212 ConstantInt *CI = ConstantInt::get(AndRHS->getContext(),
213 AndRHS->getValue() & ShlMask);
215 if (CI->getValue() == ShlMask)
216 // Masking out bits that the shift already masks.
217 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
219 if (CI != AndRHS) { // Reducing bits set in and.
220 TheAnd.setOperand(1, CI);
225 case Instruction::LShr: {
226 // We know that the AND will not produce any of the bits shifted in, so if
227 // the anded constant includes them, clear them now! This only applies to
228 // unsigned shifts, because a signed shr may bring in set bits!
230 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
231 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
232 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
233 ConstantInt *CI = ConstantInt::get(Op->getContext(),
234 AndRHS->getValue() & ShrMask);
236 if (CI->getValue() == ShrMask)
237 // Masking out bits that the shift already masks.
238 return ReplaceInstUsesWith(TheAnd, Op);
241 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
246 case Instruction::AShr:
248 // See if this is shifting in some sign extension, then masking it out
250 if (Op->hasOneUse()) {
251 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
252 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
253 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
254 Constant *C = ConstantInt::get(Op->getContext(),
255 AndRHS->getValue() & ShrMask);
256 if (C == AndRHS) { // Masking out bits shifted in.
257 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
258 // Make the argument unsigned.
259 Value *ShVal = Op->getOperand(0);
260 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
261 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
270 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
271 /// true, otherwise (V < Lo || V >= Hi). In practice, we emit the more efficient
272 /// (V-Lo) \<u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
273 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
274 /// insert new instructions.
275 Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
276 bool isSigned, bool Inside) {
277 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
278 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
279 "Lo is not <= Hi in range emission code!");
282 if (Lo == Hi) // Trivially false.
283 return ConstantInt::getFalse(V->getContext());
285 // V >= Min && V < Hi --> V < Hi
286 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
287 ICmpInst::Predicate pred = (isSigned ?
288 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
289 return Builder->CreateICmp(pred, V, Hi);
292 // Emit V-Lo <u Hi-Lo
293 Constant *NegLo = ConstantExpr::getNeg(Lo);
294 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
295 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
296 return Builder->CreateICmpULT(Add, UpperBound);
299 if (Lo == Hi) // Trivially true.
300 return ConstantInt::getTrue(V->getContext());
302 // V < Min || V >= Hi -> V > Hi-1
303 Hi = SubOne(cast<ConstantInt>(Hi));
304 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
305 ICmpInst::Predicate pred = (isSigned ?
306 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
307 return Builder->CreateICmp(pred, V, Hi);
310 // Emit V-Lo >u Hi-1-Lo
311 // Note that Hi has already had one subtracted from it, above.
312 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
313 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
314 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
315 return Builder->CreateICmpUGT(Add, LowerBound);
318 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
319 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
320 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
321 // not, since all 1s are not contiguous.
322 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
323 const APInt& V = Val->getValue();
324 uint32_t BitWidth = Val->getType()->getBitWidth();
325 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
327 // look for the first zero bit after the run of ones
328 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
329 // look for the first non-zero bit
330 ME = V.getActiveBits();
334 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
335 /// where isSub determines whether the operator is a sub. If we can fold one of
336 /// the following xforms:
338 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
339 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
340 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
342 /// return (A +/- B).
344 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
345 ConstantInt *Mask, bool isSub,
347 Instruction *LHSI = dyn_cast<Instruction>(LHS);
348 if (!LHSI || LHSI->getNumOperands() != 2 ||
349 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
351 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
353 switch (LHSI->getOpcode()) {
355 case Instruction::And:
356 if (ConstantExpr::getAnd(N, Mask) == Mask) {
357 // If the AndRHS is a power of two minus one (0+1+), this is simple.
358 if ((Mask->getValue().countLeadingZeros() +
359 Mask->getValue().countPopulation()) ==
360 Mask->getValue().getBitWidth())
363 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
364 // part, we don't need any explicit masks to take them out of A. If that
365 // is all N is, ignore it.
366 uint32_t MB = 0, ME = 0;
367 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
368 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
369 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
370 if (MaskedValueIsZero(RHS, Mask))
375 case Instruction::Or:
376 case Instruction::Xor:
377 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
378 if ((Mask->getValue().countLeadingZeros() +
379 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
380 && ConstantExpr::getAnd(N, Mask)->isNullValue())
386 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
387 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
390 /// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
391 /// One of A and B is considered the mask, the other the value. This is
392 /// described as the "AMask" or "BMask" part of the enum. If the enum
393 /// contains only "Mask", then both A and B can be considered masks.
394 /// If A is the mask, then it was proven, that (A & C) == C. This
395 /// is trivial if C == A, or C == 0. If both A and C are constants, this
396 /// proof is also easy.
397 /// For the following explanations we assume that A is the mask.
398 /// The part "AllOnes" declares, that the comparison is true only
399 /// if (A & B) == A, or all bits of A are set in B.
400 /// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
401 /// The part "AllZeroes" declares, that the comparison is true only
402 /// if (A & B) == 0, or all bits of A are cleared in B.
403 /// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
404 /// The part "Mixed" declares, that (A & B) == C and C might or might not
405 /// contain any number of one bits and zero bits.
406 /// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
407 /// The Part "Not" means, that in above descriptions "==" should be replaced
409 /// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
410 /// If the mask A contains a single bit, then the following is equivalent:
411 /// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
412 /// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
413 enum MaskedICmpType {
414 FoldMskICmp_AMask_AllOnes = 1,
415 FoldMskICmp_AMask_NotAllOnes = 2,
416 FoldMskICmp_BMask_AllOnes = 4,
417 FoldMskICmp_BMask_NotAllOnes = 8,
418 FoldMskICmp_Mask_AllZeroes = 16,
419 FoldMskICmp_Mask_NotAllZeroes = 32,
420 FoldMskICmp_AMask_Mixed = 64,
421 FoldMskICmp_AMask_NotMixed = 128,
422 FoldMskICmp_BMask_Mixed = 256,
423 FoldMskICmp_BMask_NotMixed = 512
426 /// return the set of pattern classes (from MaskedICmpType)
427 /// that (icmp SCC (A & B), C) satisfies
428 static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
429 ICmpInst::Predicate SCC)
431 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
432 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
433 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
434 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
435 bool icmp_abit = (ACst != 0 && !ACst->isZero() &&
436 ACst->getValue().isPowerOf2());
437 bool icmp_bbit = (BCst != 0 && !BCst->isZero() &&
438 BCst->getValue().isPowerOf2());
440 if (CCst != 0 && CCst->isZero()) {
441 // if C is zero, then both A and B qualify as mask
442 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
443 FoldMskICmp_Mask_AllZeroes |
444 FoldMskICmp_AMask_Mixed |
445 FoldMskICmp_BMask_Mixed)
446 : (FoldMskICmp_Mask_NotAllZeroes |
447 FoldMskICmp_Mask_NotAllZeroes |
448 FoldMskICmp_AMask_NotMixed |
449 FoldMskICmp_BMask_NotMixed));
451 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
452 FoldMskICmp_AMask_NotMixed)
453 : (FoldMskICmp_AMask_AllOnes |
454 FoldMskICmp_AMask_Mixed));
456 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
457 FoldMskICmp_BMask_NotMixed)
458 : (FoldMskICmp_BMask_AllOnes |
459 FoldMskICmp_BMask_Mixed));
463 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
464 FoldMskICmp_AMask_Mixed)
465 : (FoldMskICmp_AMask_NotAllOnes |
466 FoldMskICmp_AMask_NotMixed));
468 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
469 FoldMskICmp_AMask_NotMixed)
470 : (FoldMskICmp_Mask_AllZeroes |
471 FoldMskICmp_AMask_Mixed));
472 } else if (ACst != 0 && CCst != 0 &&
473 ConstantExpr::getAnd(ACst, CCst) == CCst) {
474 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
475 : FoldMskICmp_AMask_NotMixed);
478 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
479 FoldMskICmp_BMask_Mixed)
480 : (FoldMskICmp_BMask_NotAllOnes |
481 FoldMskICmp_BMask_NotMixed));
483 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
484 FoldMskICmp_BMask_NotMixed)
485 : (FoldMskICmp_Mask_AllZeroes |
486 FoldMskICmp_BMask_Mixed));
487 } else if (BCst != 0 && CCst != 0 &&
488 ConstantExpr::getAnd(BCst, CCst) == CCst) {
489 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
490 : FoldMskICmp_BMask_NotMixed);
495 /// decomposeBitTestICmp - Decompose an icmp into the form ((X & Y) pred Z)
496 /// if possible. The returned predicate is either == or !=. Returns false if
497 /// decomposition fails.
498 static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
499 Value *&X, Value *&Y, Value *&Z) {
500 // X < 0 is equivalent to (X & SignBit) != 0.
501 if (I->getPredicate() == ICmpInst::ICMP_SLT)
502 if (ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1)))
504 X = I->getOperand(0);
505 Y = ConstantInt::get(I->getContext(),
506 APInt::getSignBit(C->getBitWidth()));
507 Pred = ICmpInst::ICMP_NE;
512 // X > -1 is equivalent to (X & SignBit) == 0.
513 if (I->getPredicate() == ICmpInst::ICMP_SGT)
514 if (ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1)))
515 if (C->isAllOnesValue()) {
516 X = I->getOperand(0);
517 Y = ConstantInt::get(I->getContext(),
518 APInt::getSignBit(C->getBitWidth()));
519 Pred = ICmpInst::ICMP_EQ;
520 Z = ConstantInt::getNullValue(C->getType());
527 /// foldLogOpOfMaskedICmpsHelper:
528 /// handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
529 /// return the set of pattern classes (from MaskedICmpType)
530 /// that both LHS and RHS satisfy
531 static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
532 Value*& B, Value*& C,
533 Value*& D, Value*& E,
534 ICmpInst *LHS, ICmpInst *RHS,
535 ICmpInst::Predicate &LHSCC,
536 ICmpInst::Predicate &RHSCC) {
537 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
538 // vectors are not (yet?) supported
539 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
541 // Here comes the tricky part:
542 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
543 // and L11 & L12 == L21 & L22. The same goes for RHS.
544 // Now we must find those components L** and R**, that are equal, so
545 // that we can extract the parameters A, B, C, D, and E for the canonical
547 Value *L1 = LHS->getOperand(0);
548 Value *L2 = LHS->getOperand(1);
549 Value *L11,*L12,*L21,*L22;
550 // Check whether the icmp can be decomposed into a bit test.
551 if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
554 // Look for ANDs in the LHS icmp.
555 if (match(L1, m_And(m_Value(L11), m_Value(L12)))) {
556 if (!match(L2, m_And(m_Value(L21), m_Value(L22))))
559 if (!match(L2, m_And(m_Value(L11), m_Value(L12))))
566 // Bail if LHS was a icmp that can't be decomposed into an equality.
567 if (!ICmpInst::isEquality(LHSCC))
570 Value *R1 = RHS->getOperand(0);
571 Value *R2 = RHS->getOperand(1);
574 if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
575 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
577 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
582 E = R2; R1 = 0; ok = true;
583 } else if (match(R1, m_And(m_Value(R11), m_Value(R12)))) {
584 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
585 A = R11; D = R12; E = R2; ok = true;
586 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
587 A = R12; D = R11; E = R2; ok = true;
591 // Bail if RHS was a icmp that can't be decomposed into an equality.
592 if (!ICmpInst::isEquality(RHSCC))
595 // Look for ANDs in on the right side of the RHS icmp.
596 if (!ok && match(R2, m_And(m_Value(R11), m_Value(R12)))) {
597 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
598 A = R11; D = R12; E = R1; ok = true;
599 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
600 A = R12; D = R11; E = R1; ok = true;
610 } else if (L12 == A) {
612 } else if (L21 == A) {
614 } else if (L22 == A) {
618 unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
619 unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
620 return left_type & right_type;
622 /// foldLogOpOfMaskedICmps:
623 /// try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
624 /// into a single (icmp(A & X) ==/!= Y)
625 static Value* foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS,
626 ICmpInst::Predicate NEWCC,
627 llvm::InstCombiner::BuilderTy* Builder) {
628 Value *A = 0, *B = 0, *C = 0, *D = 0, *E = 0;
629 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
630 unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
632 if (mask == 0) return 0;
633 assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
634 "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
636 if (NEWCC == ICmpInst::ICMP_NE)
637 mask >>= 1; // treat "Not"-states as normal states
639 if (mask & FoldMskICmp_Mask_AllZeroes) {
640 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
641 // -> (icmp eq (A & (B|D)), 0)
642 Value* newOr = Builder->CreateOr(B, D);
643 Value* newAnd = Builder->CreateAnd(A, newOr);
644 // we can't use C as zero, because we might actually handle
645 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
646 // with B and D, having a single bit set
647 Value* zero = Constant::getNullValue(A->getType());
648 return Builder->CreateICmp(NEWCC, newAnd, zero);
650 if (mask & FoldMskICmp_BMask_AllOnes) {
651 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
652 // -> (icmp eq (A & (B|D)), (B|D))
653 Value* newOr = Builder->CreateOr(B, D);
654 Value* newAnd = Builder->CreateAnd(A, newOr);
655 return Builder->CreateICmp(NEWCC, newAnd, newOr);
657 if (mask & FoldMskICmp_AMask_AllOnes) {
658 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
659 // -> (icmp eq (A & (B&D)), A)
660 Value* newAnd1 = Builder->CreateAnd(B, D);
661 Value* newAnd = Builder->CreateAnd(A, newAnd1);
662 return Builder->CreateICmp(NEWCC, newAnd, A);
664 if (mask & FoldMskICmp_BMask_Mixed) {
665 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
666 // We already know that B & C == C && D & E == E.
667 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
668 // C and E, which are shared by both the mask B and the mask D, don't
669 // contradict, then we can transform to
670 // -> (icmp eq (A & (B|D)), (C|E))
671 // Currently, we only handle the case of B, C, D, and E being constant.
672 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
673 if (BCst == 0) return 0;
674 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
675 if (DCst == 0) return 0;
676 // we can't simply use C and E, because we might actually handle
677 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
678 // with B and D, having a single bit set
680 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
681 if (CCst == 0) return 0;
683 CCst = dyn_cast<ConstantInt>( ConstantExpr::getXor(BCst, CCst) );
684 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
685 if (ECst == 0) return 0;
687 ECst = dyn_cast<ConstantInt>( ConstantExpr::getXor(DCst, ECst) );
688 ConstantInt* MCst = dyn_cast<ConstantInt>(
689 ConstantExpr::getAnd(ConstantExpr::getAnd(BCst, DCst),
690 ConstantExpr::getXor(CCst, ECst)) );
691 // if there is a conflict we should actually return a false for the
695 Value *newOr1 = Builder->CreateOr(B, D);
696 Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
697 Value *newAnd = Builder->CreateAnd(A, newOr1);
698 return Builder->CreateICmp(NEWCC, newAnd, newOr2);
703 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
704 Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
705 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
707 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
708 if (PredicatesFoldable(LHSCC, RHSCC)) {
709 if (LHS->getOperand(0) == RHS->getOperand(1) &&
710 LHS->getOperand(1) == RHS->getOperand(0))
712 if (LHS->getOperand(0) == RHS->getOperand(0) &&
713 LHS->getOperand(1) == RHS->getOperand(1)) {
714 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
715 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
716 bool isSigned = LHS->isSigned() || RHS->isSigned();
717 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
721 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
722 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, ICmpInst::ICMP_EQ, Builder))
725 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
726 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
727 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
728 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
729 if (LHSCst == 0 || RHSCst == 0) return 0;
731 if (LHSCst == RHSCst && LHSCC == RHSCC) {
732 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
733 // where C is a power of 2
734 if (LHSCC == ICmpInst::ICMP_ULT &&
735 LHSCst->getValue().isPowerOf2()) {
736 Value *NewOr = Builder->CreateOr(Val, Val2);
737 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
740 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
741 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
742 Value *NewOr = Builder->CreateOr(Val, Val2);
743 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
747 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
748 // where CMAX is the all ones value for the truncated type,
749 // iff the lower bits of C2 and CA are zero.
750 if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
751 LHS->hasOneUse() && RHS->hasOneUse()) {
753 ConstantInt *AndCst, *SmallCst = 0, *BigCst = 0;
755 // (trunc x) == C1 & (and x, CA) == C2
756 // (and x, CA) == C2 & (trunc x) == C1
757 if (match(Val2, m_Trunc(m_Value(V))) &&
758 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
761 } else if (match(Val, m_Trunc(m_Value(V))) &&
762 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
767 if (SmallCst && BigCst) {
768 unsigned BigBitSize = BigCst->getType()->getBitWidth();
769 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
771 // Check that the low bits are zero.
772 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
773 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
774 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
775 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
776 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
777 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
782 // From here on, we only handle:
783 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
784 if (Val != Val2) return 0;
786 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
787 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
788 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
789 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
790 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
793 // Make a constant range that's the intersection of the two icmp ranges.
794 // If the intersection is empty, we know that the result is false.
795 ConstantRange LHSRange =
796 ConstantRange::makeICmpRegion(LHSCC, LHSCst->getValue());
797 ConstantRange RHSRange =
798 ConstantRange::makeICmpRegion(RHSCC, RHSCst->getValue());
800 if (LHSRange.intersectWith(RHSRange).isEmptySet())
801 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
803 // We can't fold (ugt x, C) & (sgt x, C2).
804 if (!PredicatesFoldable(LHSCC, RHSCC))
807 // Ensure that the larger constant is on the RHS.
809 if (CmpInst::isSigned(LHSCC) ||
810 (ICmpInst::isEquality(LHSCC) &&
811 CmpInst::isSigned(RHSCC)))
812 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
814 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
818 std::swap(LHSCst, RHSCst);
819 std::swap(LHSCC, RHSCC);
822 // At this point, we know we have two icmp instructions
823 // comparing a value against two constants and and'ing the result
824 // together. Because of the above check, we know that we only have
825 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
826 // (from the icmp folding check above), that the two constants
827 // are not equal and that the larger constant is on the RHS
828 assert(LHSCst != RHSCst && "Compares not folded above?");
831 default: llvm_unreachable("Unknown integer condition code!");
832 case ICmpInst::ICMP_EQ:
834 default: llvm_unreachable("Unknown integer condition code!");
835 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
836 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
837 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
840 case ICmpInst::ICMP_NE:
842 default: llvm_unreachable("Unknown integer condition code!");
843 case ICmpInst::ICMP_ULT:
844 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
845 return Builder->CreateICmpULT(Val, LHSCst);
846 break; // (X != 13 & X u< 15) -> no change
847 case ICmpInst::ICMP_SLT:
848 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
849 return Builder->CreateICmpSLT(Val, LHSCst);
850 break; // (X != 13 & X s< 15) -> no change
851 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
852 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
853 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
855 case ICmpInst::ICMP_NE:
856 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
857 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
858 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
859 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1));
861 break; // (X != 13 & X != 15) -> no change
864 case ICmpInst::ICMP_ULT:
866 default: llvm_unreachable("Unknown integer condition code!");
867 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
868 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
869 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
870 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
872 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
873 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
875 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
879 case ICmpInst::ICMP_SLT:
881 default: llvm_unreachable("Unknown integer condition code!");
882 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
884 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
885 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
887 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
891 case ICmpInst::ICMP_UGT:
893 default: llvm_unreachable("Unknown integer condition code!");
894 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
895 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
897 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
899 case ICmpInst::ICMP_NE:
900 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
901 return Builder->CreateICmp(LHSCC, Val, RHSCst);
902 break; // (X u> 13 & X != 15) -> no change
903 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
904 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
905 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
909 case ICmpInst::ICMP_SGT:
911 default: llvm_unreachable("Unknown integer condition code!");
912 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
913 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
915 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
917 case ICmpInst::ICMP_NE:
918 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
919 return Builder->CreateICmp(LHSCC, Val, RHSCst);
920 break; // (X s> 13 & X != 15) -> no change
921 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
922 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
923 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
932 /// FoldAndOfFCmps - Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of
933 /// instcombine, this returns a Value which should already be inserted into the
935 Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
936 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
937 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
938 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
939 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
940 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
941 // If either of the constants are nans, then the whole thing returns
943 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
944 return ConstantInt::getFalse(LHS->getContext());
945 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
948 // Handle vector zeros. This occurs because the canonical form of
949 // "fcmp ord x,x" is "fcmp ord x, 0".
950 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
951 isa<ConstantAggregateZero>(RHS->getOperand(1)))
952 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
956 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
957 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
958 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
961 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
962 // Swap RHS operands to match LHS.
963 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
964 std::swap(Op1LHS, Op1RHS);
967 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
968 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
970 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
971 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
972 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
973 if (Op0CC == FCmpInst::FCMP_TRUE)
975 if (Op1CC == FCmpInst::FCMP_TRUE)
980 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
981 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
982 // uno && ord -> false
983 if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
984 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
987 std::swap(Op0Pred, Op1Pred);
988 std::swap(Op0Ordered, Op1Ordered);
991 // uno && ueq -> uno && (uno || eq) -> uno
992 // ord && olt -> ord && (ord && lt) -> olt
993 if (!Op0Ordered && (Op0Ordered == Op1Ordered))
995 if (Op0Ordered && (Op0Ordered == Op1Ordered))
998 // uno && oeq -> uno && (ord && eq) -> false
1000 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1001 // ord && ueq -> ord && (uno || eq) -> oeq
1002 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
1010 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1011 bool Changed = SimplifyAssociativeOrCommutative(I);
1012 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1014 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
1015 return ReplaceInstUsesWith(I, V);
1017 // (A|B)&(A|C) -> A|(B&C) etc
1018 if (Value *V = SimplifyUsingDistributiveLaws(I))
1019 return ReplaceInstUsesWith(I, V);
1021 // See if we can simplify any instructions used by the instruction whose sole
1022 // purpose is to compute bits we don't care about.
1023 if (SimplifyDemandedInstructionBits(I))
1026 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1027 const APInt &AndRHSMask = AndRHS->getValue();
1029 // Optimize a variety of ((val OP C1) & C2) combinations...
1030 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1031 Value *Op0LHS = Op0I->getOperand(0);
1032 Value *Op0RHS = Op0I->getOperand(1);
1033 switch (Op0I->getOpcode()) {
1035 case Instruction::Xor:
1036 case Instruction::Or: {
1037 // If the mask is only needed on one incoming arm, push it up.
1038 if (!Op0I->hasOneUse()) break;
1040 APInt NotAndRHS(~AndRHSMask);
1041 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1042 // Not masking anything out for the LHS, move to RHS.
1043 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1044 Op0RHS->getName()+".masked");
1045 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1047 if (!isa<Constant>(Op0RHS) &&
1048 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1049 // Not masking anything out for the RHS, move to LHS.
1050 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1051 Op0LHS->getName()+".masked");
1052 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1057 case Instruction::Add:
1058 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1059 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1060 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1061 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1062 return BinaryOperator::CreateAnd(V, AndRHS);
1063 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1064 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1067 case Instruction::Sub:
1068 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1069 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1070 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1071 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1072 return BinaryOperator::CreateAnd(V, AndRHS);
1074 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1075 // has 1's for all bits that the subtraction with A might affect.
1076 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
1077 uint32_t BitWidth = AndRHSMask.getBitWidth();
1078 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1079 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1081 if (MaskedValueIsZero(Op0LHS, Mask)) {
1082 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1083 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1088 case Instruction::Shl:
1089 case Instruction::LShr:
1090 // (1 << x) & 1 --> zext(x == 0)
1091 // (1 >> x) & 1 --> zext(x == 0)
1092 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1094 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1095 return new ZExtInst(NewICmp, I.getType());
1100 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1101 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1105 // If this is an integer truncation, and if the source is an 'and' with
1106 // immediate, transform it. This frequently occurs for bitfield accesses.
1108 Value *X = 0; ConstantInt *YC = 0;
1109 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1110 // Change: and (trunc (and X, YC) to T), C2
1111 // into : and (trunc X to T), trunc(YC) & C2
1112 // This will fold the two constants together, which may allow
1113 // other simplifications.
1114 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1115 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1116 C3 = ConstantExpr::getAnd(C3, AndRHS);
1117 return BinaryOperator::CreateAnd(NewCast, C3);
1121 // Try to fold constant and into select arguments.
1122 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1123 if (Instruction *R = FoldOpIntoSelect(I, SI))
1125 if (isa<PHINode>(Op0))
1126 if (Instruction *NV = FoldOpIntoPhi(I))
1131 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1132 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1133 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1134 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1135 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1136 I.getName()+".demorgan");
1137 return BinaryOperator::CreateNot(Or);
1141 Value *A = 0, *B = 0, *C = 0, *D = 0;
1142 // (A|B) & ~(A&B) -> A^B
1143 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1144 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1145 ((A == C && B == D) || (A == D && B == C)))
1146 return BinaryOperator::CreateXor(A, B);
1148 // ~(A&B) & (A|B) -> A^B
1149 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1150 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1151 ((A == C && B == D) || (A == D && B == C)))
1152 return BinaryOperator::CreateXor(A, B);
1154 // A&(A^B) => A & ~B
1156 Value *tmpOp0 = Op0;
1157 Value *tmpOp1 = Op1;
1158 if (Op0->hasOneUse() &&
1159 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1160 if (A == Op1 || B == Op1 ) {
1167 if (tmpOp1->hasOneUse() &&
1168 match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
1172 // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1173 // A is originally -1 (or a vector of -1 and undefs), then we enter
1174 // an endless loop. By checking that A is non-constant we ensure that
1175 // we will never get to the loop.
1176 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
1177 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
1181 // (A&((~A)|B)) -> A&B
1182 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1183 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1184 return BinaryOperator::CreateAnd(A, Op1);
1185 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1186 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1187 return BinaryOperator::CreateAnd(A, Op0);
1190 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
1191 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
1192 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1193 return ReplaceInstUsesWith(I, Res);
1195 // If and'ing two fcmp, try combine them into one.
1196 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1197 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1198 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1199 return ReplaceInstUsesWith(I, Res);
1202 // fold (and (cast A), (cast B)) -> (cast (and A, B))
1203 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
1204 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
1205 Type *SrcTy = Op0C->getOperand(0)->getType();
1206 if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1207 SrcTy == Op1C->getOperand(0)->getType() &&
1208 SrcTy->isIntOrIntVectorTy()) {
1209 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1211 // Only do this if the casts both really cause code to be generated.
1212 if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1213 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1214 Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
1215 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1218 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1219 // cast is otherwise not optimizable. This happens for vector sexts.
1220 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1221 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1222 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1223 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1225 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1226 // cast is otherwise not optimizable. This happens for vector sexts.
1227 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1228 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1229 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1230 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1234 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
1235 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1236 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1237 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1238 SI0->getOperand(1) == SI1->getOperand(1) &&
1239 (SI0->hasOneUse() || SI1->hasOneUse())) {
1241 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1243 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1244 SI1->getOperand(1));
1250 bool OpsSwapped = false;
1251 // Canonicalize SExt or Not to the LHS
1252 if (match(Op1, m_SExt(m_Value())) ||
1253 match(Op1, m_Not(m_Value()))) {
1254 std::swap(Op0, Op1);
1258 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1259 if (match(Op0, m_SExt(m_Value(X))) &&
1260 X->getType()->getScalarType()->isIntegerTy(1)) {
1261 Value *Zero = Constant::getNullValue(Op1->getType());
1262 return SelectInst::Create(X, Op1, Zero);
1265 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1266 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1267 X->getType()->getScalarType()->isIntegerTy(1)) {
1268 Value *Zero = Constant::getNullValue(Op0->getType());
1269 return SelectInst::Create(X, Zero, Op1);
1273 std::swap(Op0, Op1);
1276 return Changed ? &I : 0;
1279 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
1280 /// capable of providing pieces of a bswap. The subexpression provides pieces
1281 /// of a bswap if it is proven that each of the non-zero bytes in the output of
1282 /// the expression came from the corresponding "byte swapped" byte in some other
1283 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1284 /// we know that the expression deposits the low byte of %X into the high byte
1285 /// of the bswap result and that all other bytes are zero. This expression is
1286 /// accepted, the high byte of ByteValues is set to X to indicate a correct
1289 /// This function returns true if the match was unsuccessful and false if so.
1290 /// On entry to the function the "OverallLeftShift" is a signed integer value
1291 /// indicating the number of bytes that the subexpression is later shifted. For
1292 /// example, if the expression is later right shifted by 16 bits, the
1293 /// OverallLeftShift value would be -2 on entry. This is used to specify which
1294 /// byte of ByteValues is actually being set.
1296 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1297 /// byte is masked to zero by a user. For example, in (X & 255), X will be
1298 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1299 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
1300 /// always in the local (OverallLeftShift) coordinate space.
1302 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1303 SmallVector<Value*, 8> &ByteValues) {
1304 if (Instruction *I = dyn_cast<Instruction>(V)) {
1305 // If this is an or instruction, it may be an inner node of the bswap.
1306 if (I->getOpcode() == Instruction::Or) {
1307 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1309 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1313 // If this is a logical shift by a constant multiple of 8, recurse with
1314 // OverallLeftShift and ByteMask adjusted.
1315 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1317 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1318 // Ensure the shift amount is defined and of a byte value.
1319 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1322 unsigned ByteShift = ShAmt >> 3;
1323 if (I->getOpcode() == Instruction::Shl) {
1324 // X << 2 -> collect(X, +2)
1325 OverallLeftShift += ByteShift;
1326 ByteMask >>= ByteShift;
1328 // X >>u 2 -> collect(X, -2)
1329 OverallLeftShift -= ByteShift;
1330 ByteMask <<= ByteShift;
1331 ByteMask &= (~0U >> (32-ByteValues.size()));
1334 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1335 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1337 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1341 // If this is a logical 'and' with a mask that clears bytes, clear the
1342 // corresponding bytes in ByteMask.
1343 if (I->getOpcode() == Instruction::And &&
1344 isa<ConstantInt>(I->getOperand(1))) {
1345 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1346 unsigned NumBytes = ByteValues.size();
1347 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1348 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1350 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1351 // If this byte is masked out by a later operation, we don't care what
1353 if ((ByteMask & (1 << i)) == 0)
1356 // If the AndMask is all zeros for this byte, clear the bit.
1357 APInt MaskB = AndMask & Byte;
1359 ByteMask &= ~(1U << i);
1363 // If the AndMask is not all ones for this byte, it's not a bytezap.
1367 // Otherwise, this byte is kept.
1370 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1375 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1376 // the input value to the bswap. Some observations: 1) if more than one byte
1377 // is demanded from this input, then it could not be successfully assembled
1378 // into a byteswap. At least one of the two bytes would not be aligned with
1379 // their ultimate destination.
1380 if (!isPowerOf2_32(ByteMask)) return true;
1381 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
1383 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1384 // is demanded, it needs to go into byte 0 of the result. This means that the
1385 // byte needs to be shifted until it lands in the right byte bucket. The
1386 // shift amount depends on the position: if the byte is coming from the high
1387 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1388 // low part, it must be shifted left.
1389 unsigned DestByteNo = InputByteNo + OverallLeftShift;
1390 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1393 // If the destination byte value is already defined, the values are or'd
1394 // together, which isn't a bswap (unless it's an or of the same bits).
1395 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1397 ByteValues[DestByteNo] = V;
1401 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1402 /// If so, insert the new bswap intrinsic and return it.
1403 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1404 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1405 if (!ITy || ITy->getBitWidth() % 16 ||
1406 // ByteMask only allows up to 32-byte values.
1407 ITy->getBitWidth() > 32*8)
1408 return 0; // Can only bswap pairs of bytes. Can't do vectors.
1410 /// ByteValues - For each byte of the result, we keep track of which value
1411 /// defines each byte.
1412 SmallVector<Value*, 8> ByteValues;
1413 ByteValues.resize(ITy->getBitWidth()/8);
1415 // Try to find all the pieces corresponding to the bswap.
1416 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1417 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1420 // Check to see if all of the bytes come from the same value.
1421 Value *V = ByteValues[0];
1422 if (V == 0) return 0; // Didn't find a byte? Must be zero.
1424 // Check to make sure that all of the bytes come from the same value.
1425 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1426 if (ByteValues[i] != V)
1428 Module *M = I.getParent()->getParent()->getParent();
1429 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
1430 return CallInst::Create(F, V);
1433 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1434 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1435 /// we can simplify this expression to "cond ? C : D or B".
1436 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1437 Value *C, Value *D) {
1438 // If A is not a select of -1/0, this cannot match.
1440 if (!match(A, m_SExt(m_Value(Cond))) ||
1441 !Cond->getType()->isIntegerTy(1))
1444 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1445 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1446 return SelectInst::Create(Cond, C, B);
1447 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
1448 return SelectInst::Create(Cond, C, B);
1450 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1451 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
1452 return SelectInst::Create(Cond, C, D);
1453 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
1454 return SelectInst::Create(Cond, C, D);
1458 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1459 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
1460 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1462 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1463 if (PredicatesFoldable(LHSCC, RHSCC)) {
1464 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1465 LHS->getOperand(1) == RHS->getOperand(0))
1466 LHS->swapOperands();
1467 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1468 LHS->getOperand(1) == RHS->getOperand(1)) {
1469 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1470 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1471 bool isSigned = LHS->isSigned() || RHS->isSigned();
1472 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
1476 // handle (roughly):
1477 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1478 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, ICmpInst::ICMP_NE, Builder))
1481 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1482 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1483 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1484 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1485 if (LHSCst == 0 || RHSCst == 0) return 0;
1487 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1488 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1489 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1490 Value *NewOr = Builder->CreateOr(Val, Val2);
1491 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1495 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
1496 // iff C2 + CA == C1.
1497 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
1498 ConstantInt *AddCst;
1499 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1500 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
1501 return Builder->CreateICmpULE(Val, LHSCst);
1504 // From here on, we only handle:
1505 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1506 if (Val != Val2) return 0;
1508 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1509 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1510 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1511 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1512 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1515 // We can't fold (ugt x, C) | (sgt x, C2).
1516 if (!PredicatesFoldable(LHSCC, RHSCC))
1519 // Ensure that the larger constant is on the RHS.
1521 if (CmpInst::isSigned(LHSCC) ||
1522 (ICmpInst::isEquality(LHSCC) &&
1523 CmpInst::isSigned(RHSCC)))
1524 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1526 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1529 std::swap(LHS, RHS);
1530 std::swap(LHSCst, RHSCst);
1531 std::swap(LHSCC, RHSCC);
1534 // At this point, we know we have two icmp instructions
1535 // comparing a value against two constants and or'ing the result
1536 // together. Because of the above check, we know that we only have
1537 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1538 // icmp folding check above), that the two constants are not
1540 assert(LHSCst != RHSCst && "Compares not folded above?");
1543 default: llvm_unreachable("Unknown integer condition code!");
1544 case ICmpInst::ICMP_EQ:
1546 default: llvm_unreachable("Unknown integer condition code!");
1547 case ICmpInst::ICMP_EQ:
1548 if (LHSCst == SubOne(RHSCst)) {
1549 // (X == 13 | X == 14) -> X-13 <u 2
1550 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1551 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1552 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1553 return Builder->CreateICmpULT(Add, AddCST);
1556 if (LHS->getOperand(0) == RHS->getOperand(0)) {
1557 // if LHSCst and RHSCst differ only by one bit:
1558 // (A == C1 || A == C2) -> (A & ~(C1 ^ C2)) == C1
1559 assert(LHSCst->getValue().ule(LHSCst->getValue()));
1561 APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1562 if (Xor.isPowerOf2()) {
1563 Value *NegCst = Builder->getInt(~Xor);
1564 Value *And = Builder->CreateAnd(LHS->getOperand(0), NegCst);
1565 return Builder->CreateICmp(ICmpInst::ICMP_EQ, And, LHSCst);
1569 break; // (X == 13 | X == 15) -> no change
1570 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1571 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1573 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1574 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1575 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
1579 case ICmpInst::ICMP_NE:
1581 default: llvm_unreachable("Unknown integer condition code!");
1582 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1583 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1584 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
1586 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1587 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1588 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
1589 return ConstantInt::getTrue(LHS->getContext());
1591 case ICmpInst::ICMP_ULT:
1593 default: llvm_unreachable("Unknown integer condition code!");
1594 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1596 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1597 // If RHSCst is [us]MAXINT, it is always false. Not handling
1598 // this can cause overflow.
1599 if (RHSCst->isMaxValue(false))
1601 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
1602 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1604 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1605 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
1607 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1611 case ICmpInst::ICMP_SLT:
1613 default: llvm_unreachable("Unknown integer condition code!");
1614 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1616 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1617 // If RHSCst is [us]MAXINT, it is always false. Not handling
1618 // this can cause overflow.
1619 if (RHSCst->isMaxValue(true))
1621 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
1622 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1624 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1625 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
1627 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1631 case ICmpInst::ICMP_UGT:
1633 default: llvm_unreachable("Unknown integer condition code!");
1634 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1635 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
1637 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1639 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1640 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
1641 return ConstantInt::getTrue(LHS->getContext());
1642 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1646 case ICmpInst::ICMP_SGT:
1648 default: llvm_unreachable("Unknown integer condition code!");
1649 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1650 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
1652 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1654 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1655 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
1656 return ConstantInt::getTrue(LHS->getContext());
1657 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1665 /// FoldOrOfFCmps - Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of
1666 /// instcombine, this returns a Value which should already be inserted into the
1668 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1669 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1670 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1671 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1672 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1673 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1674 // If either of the constants are nans, then the whole thing returns
1676 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1677 return ConstantInt::getTrue(LHS->getContext());
1679 // Otherwise, no need to compare the two constants, compare the
1681 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1684 // Handle vector zeros. This occurs because the canonical form of
1685 // "fcmp uno x,x" is "fcmp uno x, 0".
1686 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1687 isa<ConstantAggregateZero>(RHS->getOperand(1)))
1688 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1693 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1694 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1695 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1697 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1698 // Swap RHS operands to match LHS.
1699 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1700 std::swap(Op1LHS, Op1RHS);
1702 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1703 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1705 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1706 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
1707 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
1708 if (Op0CC == FCmpInst::FCMP_FALSE)
1710 if (Op1CC == FCmpInst::FCMP_FALSE)
1714 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1715 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1716 if (Op0Ordered == Op1Ordered) {
1717 // If both are ordered or unordered, return a new fcmp with
1718 // or'ed predicates.
1719 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
1725 /// FoldOrWithConstants - This helper function folds:
1727 /// ((A | B) & C1) | (B & C2)
1733 /// when the XOR of the two constants is "all ones" (-1).
1734 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1735 Value *A, Value *B, Value *C) {
1736 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1740 ConstantInt *CI2 = 0;
1741 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1743 APInt Xor = CI1->getValue() ^ CI2->getValue();
1744 if (!Xor.isAllOnesValue()) return 0;
1746 if (V1 == A || V1 == B) {
1747 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1748 return BinaryOperator::CreateOr(NewOp, V1);
1754 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1755 bool Changed = SimplifyAssociativeOrCommutative(I);
1756 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1758 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1759 return ReplaceInstUsesWith(I, V);
1761 // (A&B)|(A&C) -> A&(B|C) etc
1762 if (Value *V = SimplifyUsingDistributiveLaws(I))
1763 return ReplaceInstUsesWith(I, V);
1765 // See if we can simplify any instructions used by the instruction whose sole
1766 // purpose is to compute bits we don't care about.
1767 if (SimplifyDemandedInstructionBits(I))
1770 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1771 ConstantInt *C1 = 0; Value *X = 0;
1772 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1773 // iff (C1 & C2) == 0.
1774 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
1775 (RHS->getValue() & C1->getValue()) != 0 &&
1777 Value *Or = Builder->CreateOr(X, RHS);
1779 return BinaryOperator::CreateAnd(Or,
1780 ConstantInt::get(I.getContext(),
1781 RHS->getValue() | C1->getValue()));
1784 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1785 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1787 Value *Or = Builder->CreateOr(X, RHS);
1789 return BinaryOperator::CreateXor(Or,
1790 ConstantInt::get(I.getContext(),
1791 C1->getValue() & ~RHS->getValue()));
1794 // Try to fold constant and into select arguments.
1795 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1796 if (Instruction *R = FoldOpIntoSelect(I, SI))
1799 if (isa<PHINode>(Op0))
1800 if (Instruction *NV = FoldOpIntoPhi(I))
1804 Value *A = 0, *B = 0;
1805 ConstantInt *C1 = 0, *C2 = 0;
1807 // (A | B) | C and A | (B | C) -> bswap if possible.
1808 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1809 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1810 match(Op1, m_Or(m_Value(), m_Value())) ||
1811 (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1812 match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
1813 if (Instruction *BSwap = MatchBSwap(I))
1817 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1818 if (Op0->hasOneUse() &&
1819 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1820 MaskedValueIsZero(Op1, C1->getValue())) {
1821 Value *NOr = Builder->CreateOr(A, Op1);
1823 return BinaryOperator::CreateXor(NOr, C1);
1826 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1827 if (Op1->hasOneUse() &&
1828 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1829 MaskedValueIsZero(Op0, C1->getValue())) {
1830 Value *NOr = Builder->CreateOr(A, Op0);
1832 return BinaryOperator::CreateXor(NOr, C1);
1836 Value *C = 0, *D = 0;
1837 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1838 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1839 Value *V1 = 0, *V2 = 0;
1840 C1 = dyn_cast<ConstantInt>(C);
1841 C2 = dyn_cast<ConstantInt>(D);
1842 if (C1 && C2) { // (A & C1)|(B & C2)
1843 // If we have: ((V + N) & C1) | (V & C2)
1844 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1845 // replace with V+N.
1846 if (C1->getValue() == ~C2->getValue()) {
1847 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1848 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1849 // Add commutes, try both ways.
1850 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1851 return ReplaceInstUsesWith(I, A);
1852 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1853 return ReplaceInstUsesWith(I, A);
1855 // Or commutes, try both ways.
1856 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
1857 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1858 // Add commutes, try both ways.
1859 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1860 return ReplaceInstUsesWith(I, B);
1861 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1862 return ReplaceInstUsesWith(I, B);
1866 if ((C1->getValue() & C2->getValue()) == 0) {
1867 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1868 // iff (C1&C2) == 0 and (N&~C1) == 0
1869 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1870 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
1871 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
1872 return BinaryOperator::CreateAnd(A,
1873 ConstantInt::get(A->getContext(),
1874 C1->getValue()|C2->getValue()));
1875 // Or commutes, try both ways.
1876 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1877 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
1878 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
1879 return BinaryOperator::CreateAnd(B,
1880 ConstantInt::get(B->getContext(),
1881 C1->getValue()|C2->getValue()));
1883 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
1884 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
1885 ConstantInt *C3 = 0, *C4 = 0;
1886 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
1887 (C3->getValue() & ~C1->getValue()) == 0 &&
1888 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
1889 (C4->getValue() & ~C2->getValue()) == 0) {
1890 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
1891 return BinaryOperator::CreateAnd(V2,
1892 ConstantInt::get(B->getContext(),
1893 C1->getValue()|C2->getValue()));
1898 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
1899 // Don't do this for vector select idioms, the code generator doesn't handle
1901 if (!I.getType()->isVectorTy()) {
1902 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
1904 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
1906 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
1908 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
1912 // ((A&~B)|(~A&B)) -> A^B
1913 if ((match(C, m_Not(m_Specific(D))) &&
1914 match(B, m_Not(m_Specific(A)))))
1915 return BinaryOperator::CreateXor(A, D);
1916 // ((~B&A)|(~A&B)) -> A^B
1917 if ((match(A, m_Not(m_Specific(D))) &&
1918 match(B, m_Not(m_Specific(C)))))
1919 return BinaryOperator::CreateXor(C, D);
1920 // ((A&~B)|(B&~A)) -> A^B
1921 if ((match(C, m_Not(m_Specific(B))) &&
1922 match(D, m_Not(m_Specific(A)))))
1923 return BinaryOperator::CreateXor(A, B);
1924 // ((~B&A)|(B&~A)) -> A^B
1925 if ((match(A, m_Not(m_Specific(B))) &&
1926 match(D, m_Not(m_Specific(C)))))
1927 return BinaryOperator::CreateXor(C, B);
1929 // ((A|B)&1)|(B&-2) -> (A&1) | B
1930 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
1931 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
1932 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
1933 if (Ret) return Ret;
1935 // (B&-2)|((A|B)&1) -> (A&1) | B
1936 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
1937 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
1938 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
1939 if (Ret) return Ret;
1943 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
1944 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1945 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1946 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1947 SI0->getOperand(1) == SI1->getOperand(1) &&
1948 (SI0->hasOneUse() || SI1->hasOneUse())) {
1949 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1951 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1952 SI1->getOperand(1));
1956 // (~A | ~B) == (~(A & B)) - De Morgan's Law
1957 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1958 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1959 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1960 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
1961 I.getName()+".demorgan");
1962 return BinaryOperator::CreateNot(And);
1965 // Canonicalize xor to the RHS.
1966 bool SwappedForXor = false;
1967 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
1968 std::swap(Op0, Op1);
1969 SwappedForXor = true;
1972 // A | ( A ^ B) -> A | B
1973 // A | (~A ^ B) -> A | ~B
1974 // (A & B) | (A ^ B)
1975 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
1976 if (Op0 == A || Op0 == B)
1977 return BinaryOperator::CreateOr(A, B);
1979 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
1980 match(Op0, m_And(m_Specific(B), m_Specific(A))))
1981 return BinaryOperator::CreateOr(A, B);
1983 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
1984 Value *Not = Builder->CreateNot(B, B->getName()+".not");
1985 return BinaryOperator::CreateOr(Not, Op0);
1987 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
1988 Value *Not = Builder->CreateNot(A, A->getName()+".not");
1989 return BinaryOperator::CreateOr(Not, Op0);
1993 // A | ~(A | B) -> A | ~B
1994 // A | ~(A ^ B) -> A | ~B
1995 if (match(Op1, m_Not(m_Value(A))))
1996 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
1997 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
1998 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
1999 B->getOpcode() == Instruction::Xor)) {
2000 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2002 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2003 return BinaryOperator::CreateOr(Not, Op0);
2007 std::swap(Op0, Op1);
2009 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2010 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2011 if (Value *Res = FoldOrOfICmps(LHS, RHS))
2012 return ReplaceInstUsesWith(I, Res);
2014 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2015 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2016 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2017 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2018 return ReplaceInstUsesWith(I, Res);
2020 // fold (or (cast A), (cast B)) -> (cast (or A, B))
2021 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2022 CastInst *Op1C = dyn_cast<CastInst>(Op1);
2023 if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
2024 Type *SrcTy = Op0C->getOperand(0)->getType();
2025 if (SrcTy == Op1C->getOperand(0)->getType() &&
2026 SrcTy->isIntOrIntVectorTy()) {
2027 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
2029 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
2030 // Only do this if the casts both really cause code to be
2032 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
2033 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
2034 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
2035 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2038 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
2039 // cast is otherwise not optimizable. This happens for vector sexts.
2040 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
2041 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
2042 if (Value *Res = FoldOrOfICmps(LHS, RHS))
2043 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
2045 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
2046 // cast is otherwise not optimizable. This happens for vector sexts.
2047 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
2048 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
2049 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2050 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
2055 // or(sext(A), B) -> A ? -1 : B where A is an i1
2056 // or(A, sext(B)) -> B ? -1 : A where B is an i1
2057 if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2058 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2059 if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2060 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2062 // Note: If we've gotten to the point of visiting the outer OR, then the
2063 // inner one couldn't be simplified. If it was a constant, then it won't
2064 // be simplified by a later pass either, so we try swapping the inner/outer
2065 // ORs in the hopes that we'll be able to simplify it this way.
2066 // (X|C) | V --> (X|V) | C
2067 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2068 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2069 Value *Inner = Builder->CreateOr(A, Op1);
2070 Inner->takeName(Op0);
2071 return BinaryOperator::CreateOr(Inner, C1);
2074 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2075 // Since this OR statement hasn't been optimized further yet, we hope
2076 // that this transformation will allow the new ORs to be optimized.
2078 Value *X = 0, *Y = 0;
2079 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2080 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2081 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2082 Value *orTrue = Builder->CreateOr(A, C);
2083 Value *orFalse = Builder->CreateOr(B, D);
2084 return SelectInst::Create(X, orTrue, orFalse);
2088 return Changed ? &I : 0;
2091 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2092 bool Changed = SimplifyAssociativeOrCommutative(I);
2093 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2095 if (Value *V = SimplifyXorInst(Op0, Op1, TD))
2096 return ReplaceInstUsesWith(I, V);
2098 // (A&B)^(A&C) -> A&(B^C) etc
2099 if (Value *V = SimplifyUsingDistributiveLaws(I))
2100 return ReplaceInstUsesWith(I, V);
2102 // See if we can simplify any instructions used by the instruction whose sole
2103 // purpose is to compute bits we don't care about.
2104 if (SimplifyDemandedInstructionBits(I))
2107 // Is this a ~ operation?
2108 if (Value *NotOp = dyn_castNotVal(&I)) {
2109 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2110 if (Op0I->getOpcode() == Instruction::And ||
2111 Op0I->getOpcode() == Instruction::Or) {
2112 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2113 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2114 if (dyn_castNotVal(Op0I->getOperand(1)))
2115 Op0I->swapOperands();
2116 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2118 Builder->CreateNot(Op0I->getOperand(1),
2119 Op0I->getOperand(1)->getName()+".not");
2120 if (Op0I->getOpcode() == Instruction::And)
2121 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2122 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2125 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2126 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2127 if (isFreeToInvert(Op0I->getOperand(0)) &&
2128 isFreeToInvert(Op0I->getOperand(1))) {
2130 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2132 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2133 if (Op0I->getOpcode() == Instruction::And)
2134 return BinaryOperator::CreateOr(NotX, NotY);
2135 return BinaryOperator::CreateAnd(NotX, NotY);
2138 } else if (Op0I->getOpcode() == Instruction::AShr) {
2139 // ~(~X >>s Y) --> (X >>s Y)
2140 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2141 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
2147 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2148 if (RHS->isOne() && Op0->hasOneUse())
2149 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2150 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2151 return CmpInst::Create(CI->getOpcode(),
2152 CI->getInversePredicate(),
2153 CI->getOperand(0), CI->getOperand(1));
2155 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2156 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2157 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2158 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2159 Instruction::CastOps Opcode = Op0C->getOpcode();
2160 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2161 (RHS == ConstantExpr::getCast(Opcode,
2162 ConstantInt::getTrue(I.getContext()),
2163 Op0C->getDestTy()))) {
2164 CI->setPredicate(CI->getInversePredicate());
2165 return CastInst::Create(Opcode, CI, Op0C->getType());
2171 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2172 // ~(c-X) == X-c-1 == X+(-c-1)
2173 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2174 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2175 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2176 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2177 ConstantInt::get(I.getType(), 1));
2178 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2181 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2182 if (Op0I->getOpcode() == Instruction::Add) {
2183 // ~(X-c) --> (-c-1)-X
2184 if (RHS->isAllOnesValue()) {
2185 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2186 return BinaryOperator::CreateSub(
2187 ConstantExpr::getSub(NegOp0CI,
2188 ConstantInt::get(I.getType(), 1)),
2189 Op0I->getOperand(0));
2190 } else if (RHS->getValue().isSignBit()) {
2191 // (X + C) ^ signbit -> (X + C + signbit)
2192 Constant *C = ConstantInt::get(I.getContext(),
2193 RHS->getValue() + Op0CI->getValue());
2194 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2197 } else if (Op0I->getOpcode() == Instruction::Or) {
2198 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2199 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
2200 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2201 // Anything in both C1 and C2 is known to be zero, remove it from
2203 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2204 NewRHS = ConstantExpr::getAnd(NewRHS,
2205 ConstantExpr::getNot(CommonBits));
2207 I.setOperand(0, Op0I->getOperand(0));
2208 I.setOperand(1, NewRHS);
2211 } else if (Op0I->getOpcode() == Instruction::LShr) {
2212 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2216 if (Op0I->hasOneUse() &&
2217 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2218 E1->getOpcode() == Instruction::Xor &&
2219 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2220 // fold (C1 >> C2) ^ C3
2221 ConstantInt *C2 = Op0CI, *C3 = RHS;
2222 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2223 FoldConst ^= C3->getValue();
2224 // Prepare the two operands.
2225 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2226 Opnd0->takeName(Op0I);
2227 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2228 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2230 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2236 // Try to fold constant and into select arguments.
2237 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2238 if (Instruction *R = FoldOpIntoSelect(I, SI))
2240 if (isa<PHINode>(Op0))
2241 if (Instruction *NV = FoldOpIntoPhi(I))
2245 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2248 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2249 if (A == Op0) { // B^(B|A) == (A|B)^B
2250 Op1I->swapOperands();
2252 std::swap(Op0, Op1);
2253 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2254 I.swapOperands(); // Simplified below.
2255 std::swap(Op0, Op1);
2257 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
2259 if (A == Op0) { // A^(A&B) -> A^(B&A)
2260 Op1I->swapOperands();
2263 if (B == Op0) { // A^(B&A) -> (B&A)^A
2264 I.swapOperands(); // Simplified below.
2265 std::swap(Op0, Op1);
2270 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2273 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2274 Op0I->hasOneUse()) {
2275 if (A == Op1) // (B|A)^B == (A|B)^B
2277 if (B == Op1) // (A|B)^B == A & ~B
2278 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
2279 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2281 if (A == Op1) // (A&B)^A -> (B&A)^A
2283 if (B == Op1 && // (B&A)^A == ~B & A
2284 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
2285 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
2290 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
2291 if (Op0I && Op1I && Op0I->isShift() &&
2292 Op0I->getOpcode() == Op1I->getOpcode() &&
2293 Op0I->getOperand(1) == Op1I->getOperand(1) &&
2294 (Op0I->hasOneUse() || Op1I->hasOneUse())) {
2296 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2298 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
2299 Op1I->getOperand(1));
2303 Value *A, *B, *C, *D;
2304 // (A & B)^(A | B) -> A ^ B
2305 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2306 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
2307 if ((A == C && B == D) || (A == D && B == C))
2308 return BinaryOperator::CreateXor(A, B);
2310 // (A | B)^(A & B) -> A ^ B
2311 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2312 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2313 if ((A == C && B == D) || (A == D && B == C))
2314 return BinaryOperator::CreateXor(A, B);
2318 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2319 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2320 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2321 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2322 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2323 LHS->getOperand(1) == RHS->getOperand(0))
2324 LHS->swapOperands();
2325 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2326 LHS->getOperand(1) == RHS->getOperand(1)) {
2327 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2328 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2329 bool isSigned = LHS->isSigned() || RHS->isSigned();
2330 return ReplaceInstUsesWith(I,
2331 getNewICmpValue(isSigned, Code, Op0, Op1,
2336 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2337 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2338 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2339 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
2340 Type *SrcTy = Op0C->getOperand(0)->getType();
2341 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
2342 // Only do this if the casts both really cause code to be generated.
2343 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
2345 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
2347 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2348 Op1C->getOperand(0), I.getName());
2349 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2354 return Changed ? &I : 0;