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/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));
1248 return Changed ? &I : 0;
1251 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
1252 /// capable of providing pieces of a bswap. The subexpression provides pieces
1253 /// of a bswap if it is proven that each of the non-zero bytes in the output of
1254 /// the expression came from the corresponding "byte swapped" byte in some other
1255 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1256 /// we know that the expression deposits the low byte of %X into the high byte
1257 /// of the bswap result and that all other bytes are zero. This expression is
1258 /// accepted, the high byte of ByteValues is set to X to indicate a correct
1261 /// This function returns true if the match was unsuccessful and false if so.
1262 /// On entry to the function the "OverallLeftShift" is a signed integer value
1263 /// indicating the number of bytes that the subexpression is later shifted. For
1264 /// example, if the expression is later right shifted by 16 bits, the
1265 /// OverallLeftShift value would be -2 on entry. This is used to specify which
1266 /// byte of ByteValues is actually being set.
1268 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1269 /// byte is masked to zero by a user. For example, in (X & 255), X will be
1270 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1271 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
1272 /// always in the local (OverallLeftShift) coordinate space.
1274 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1275 SmallVector<Value*, 8> &ByteValues) {
1276 if (Instruction *I = dyn_cast<Instruction>(V)) {
1277 // If this is an or instruction, it may be an inner node of the bswap.
1278 if (I->getOpcode() == Instruction::Or) {
1279 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1281 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1285 // If this is a logical shift by a constant multiple of 8, recurse with
1286 // OverallLeftShift and ByteMask adjusted.
1287 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1289 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1290 // Ensure the shift amount is defined and of a byte value.
1291 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1294 unsigned ByteShift = ShAmt >> 3;
1295 if (I->getOpcode() == Instruction::Shl) {
1296 // X << 2 -> collect(X, +2)
1297 OverallLeftShift += ByteShift;
1298 ByteMask >>= ByteShift;
1300 // X >>u 2 -> collect(X, -2)
1301 OverallLeftShift -= ByteShift;
1302 ByteMask <<= ByteShift;
1303 ByteMask &= (~0U >> (32-ByteValues.size()));
1306 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1307 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1309 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1313 // If this is a logical 'and' with a mask that clears bytes, clear the
1314 // corresponding bytes in ByteMask.
1315 if (I->getOpcode() == Instruction::And &&
1316 isa<ConstantInt>(I->getOperand(1))) {
1317 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1318 unsigned NumBytes = ByteValues.size();
1319 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1320 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1322 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1323 // If this byte is masked out by a later operation, we don't care what
1325 if ((ByteMask & (1 << i)) == 0)
1328 // If the AndMask is all zeros for this byte, clear the bit.
1329 APInt MaskB = AndMask & Byte;
1331 ByteMask &= ~(1U << i);
1335 // If the AndMask is not all ones for this byte, it's not a bytezap.
1339 // Otherwise, this byte is kept.
1342 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1347 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1348 // the input value to the bswap. Some observations: 1) if more than one byte
1349 // is demanded from this input, then it could not be successfully assembled
1350 // into a byteswap. At least one of the two bytes would not be aligned with
1351 // their ultimate destination.
1352 if (!isPowerOf2_32(ByteMask)) return true;
1353 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
1355 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1356 // is demanded, it needs to go into byte 0 of the result. This means that the
1357 // byte needs to be shifted until it lands in the right byte bucket. The
1358 // shift amount depends on the position: if the byte is coming from the high
1359 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1360 // low part, it must be shifted left.
1361 unsigned DestByteNo = InputByteNo + OverallLeftShift;
1362 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1365 // If the destination byte value is already defined, the values are or'd
1366 // together, which isn't a bswap (unless it's an or of the same bits).
1367 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1369 ByteValues[DestByteNo] = V;
1373 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1374 /// If so, insert the new bswap intrinsic and return it.
1375 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1376 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1377 if (!ITy || ITy->getBitWidth() % 16 ||
1378 // ByteMask only allows up to 32-byte values.
1379 ITy->getBitWidth() > 32*8)
1380 return 0; // Can only bswap pairs of bytes. Can't do vectors.
1382 /// ByteValues - For each byte of the result, we keep track of which value
1383 /// defines each byte.
1384 SmallVector<Value*, 8> ByteValues;
1385 ByteValues.resize(ITy->getBitWidth()/8);
1387 // Try to find all the pieces corresponding to the bswap.
1388 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1389 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1392 // Check to see if all of the bytes come from the same value.
1393 Value *V = ByteValues[0];
1394 if (V == 0) return 0; // Didn't find a byte? Must be zero.
1396 // Check to make sure that all of the bytes come from the same value.
1397 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1398 if (ByteValues[i] != V)
1400 Module *M = I.getParent()->getParent()->getParent();
1401 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
1402 return CallInst::Create(F, V);
1405 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1406 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1407 /// we can simplify this expression to "cond ? C : D or B".
1408 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1409 Value *C, Value *D) {
1410 // If A is not a select of -1/0, this cannot match.
1412 if (!match(A, m_SExt(m_Value(Cond))) ||
1413 !Cond->getType()->isIntegerTy(1))
1416 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1417 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1418 return SelectInst::Create(Cond, C, B);
1419 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
1420 return SelectInst::Create(Cond, C, B);
1422 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1423 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
1424 return SelectInst::Create(Cond, C, D);
1425 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
1426 return SelectInst::Create(Cond, C, D);
1430 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1431 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
1432 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1434 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1435 if (PredicatesFoldable(LHSCC, RHSCC)) {
1436 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1437 LHS->getOperand(1) == RHS->getOperand(0))
1438 LHS->swapOperands();
1439 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1440 LHS->getOperand(1) == RHS->getOperand(1)) {
1441 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1442 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1443 bool isSigned = LHS->isSigned() || RHS->isSigned();
1444 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
1448 // handle (roughly):
1449 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1450 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, ICmpInst::ICMP_NE, Builder))
1453 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1454 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1455 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1456 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1457 if (LHSCst == 0 || RHSCst == 0) return 0;
1459 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1460 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1461 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1462 Value *NewOr = Builder->CreateOr(Val, Val2);
1463 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1467 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
1468 // iff C2 + CA == C1.
1469 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
1470 ConstantInt *AddCst;
1471 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1472 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
1473 return Builder->CreateICmpULE(Val, LHSCst);
1476 // From here on, we only handle:
1477 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1478 if (Val != Val2) return 0;
1480 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1481 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1482 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1483 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1484 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1487 // We can't fold (ugt x, C) | (sgt x, C2).
1488 if (!PredicatesFoldable(LHSCC, RHSCC))
1491 // Ensure that the larger constant is on the RHS.
1493 if (CmpInst::isSigned(LHSCC) ||
1494 (ICmpInst::isEquality(LHSCC) &&
1495 CmpInst::isSigned(RHSCC)))
1496 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1498 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1501 std::swap(LHS, RHS);
1502 std::swap(LHSCst, RHSCst);
1503 std::swap(LHSCC, RHSCC);
1506 // At this point, we know we have two icmp instructions
1507 // comparing a value against two constants and or'ing the result
1508 // together. Because of the above check, we know that we only have
1509 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1510 // icmp folding check above), that the two constants are not
1512 assert(LHSCst != RHSCst && "Compares not folded above?");
1515 default: llvm_unreachable("Unknown integer condition code!");
1516 case ICmpInst::ICMP_EQ:
1518 default: llvm_unreachable("Unknown integer condition code!");
1519 case ICmpInst::ICMP_EQ:
1520 if (LHSCst == SubOne(RHSCst)) {
1521 // (X == 13 | X == 14) -> X-13 <u 2
1522 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1523 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1524 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1525 return Builder->CreateICmpULT(Add, AddCST);
1528 if (LHS->getOperand(0) == RHS->getOperand(0)) {
1529 // if LHSCst and RHSCst differ only by one bit:
1530 // (A == C1 || A == C2) -> (A & ~(C1 ^ C2)) == C1
1531 APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1532 if (Xor.isPowerOf2()) {
1533 Value *NegCst = Builder->getInt(~Xor);
1534 Value *And = Builder->CreateAnd(LHS->getOperand(0), NegCst);
1535 return Builder->CreateICmp(ICmpInst::ICMP_EQ, And, LHSCst);
1539 break; // (X == 13 | X == 15) -> no change
1540 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1541 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1543 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1544 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1545 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
1549 case ICmpInst::ICMP_NE:
1551 default: llvm_unreachable("Unknown integer condition code!");
1552 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1553 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1554 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
1556 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1557 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1558 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
1559 return ConstantInt::getTrue(LHS->getContext());
1561 case ICmpInst::ICMP_ULT:
1563 default: llvm_unreachable("Unknown integer condition code!");
1564 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1566 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1567 // If RHSCst is [us]MAXINT, it is always false. Not handling
1568 // this can cause overflow.
1569 if (RHSCst->isMaxValue(false))
1571 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
1572 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1574 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1575 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
1577 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1581 case ICmpInst::ICMP_SLT:
1583 default: llvm_unreachable("Unknown integer condition code!");
1584 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1586 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1587 // If RHSCst is [us]MAXINT, it is always false. Not handling
1588 // this can cause overflow.
1589 if (RHSCst->isMaxValue(true))
1591 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
1592 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1594 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1595 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
1597 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1601 case ICmpInst::ICMP_UGT:
1603 default: llvm_unreachable("Unknown integer condition code!");
1604 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1605 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
1607 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1609 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1610 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
1611 return ConstantInt::getTrue(LHS->getContext());
1612 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1616 case ICmpInst::ICMP_SGT:
1618 default: llvm_unreachable("Unknown integer condition code!");
1619 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1620 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
1622 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1624 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1625 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
1626 return ConstantInt::getTrue(LHS->getContext());
1627 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1635 /// FoldOrOfFCmps - Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of
1636 /// instcombine, this returns a Value which should already be inserted into the
1638 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1639 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1640 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1641 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1642 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1643 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1644 // If either of the constants are nans, then the whole thing returns
1646 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1647 return ConstantInt::getTrue(LHS->getContext());
1649 // Otherwise, no need to compare the two constants, compare the
1651 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1654 // Handle vector zeros. This occurs because the canonical form of
1655 // "fcmp uno x,x" is "fcmp uno x, 0".
1656 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1657 isa<ConstantAggregateZero>(RHS->getOperand(1)))
1658 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1663 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1664 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1665 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1667 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1668 // Swap RHS operands to match LHS.
1669 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1670 std::swap(Op1LHS, Op1RHS);
1672 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1673 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1675 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1676 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
1677 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
1678 if (Op0CC == FCmpInst::FCMP_FALSE)
1680 if (Op1CC == FCmpInst::FCMP_FALSE)
1684 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1685 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1686 if (Op0Ordered == Op1Ordered) {
1687 // If both are ordered or unordered, return a new fcmp with
1688 // or'ed predicates.
1689 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
1695 /// FoldOrWithConstants - This helper function folds:
1697 /// ((A | B) & C1) | (B & C2)
1703 /// when the XOR of the two constants is "all ones" (-1).
1704 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1705 Value *A, Value *B, Value *C) {
1706 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1710 ConstantInt *CI2 = 0;
1711 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
1713 APInt Xor = CI1->getValue() ^ CI2->getValue();
1714 if (!Xor.isAllOnesValue()) return 0;
1716 if (V1 == A || V1 == B) {
1717 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1718 return BinaryOperator::CreateOr(NewOp, V1);
1724 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1725 bool Changed = SimplifyAssociativeOrCommutative(I);
1726 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1728 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
1729 return ReplaceInstUsesWith(I, V);
1731 // (A&B)|(A&C) -> A&(B|C) etc
1732 if (Value *V = SimplifyUsingDistributiveLaws(I))
1733 return ReplaceInstUsesWith(I, V);
1735 // See if we can simplify any instructions used by the instruction whose sole
1736 // purpose is to compute bits we don't care about.
1737 if (SimplifyDemandedInstructionBits(I))
1740 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1741 ConstantInt *C1 = 0; Value *X = 0;
1742 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1743 // iff (C1 & C2) == 0.
1744 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
1745 (RHS->getValue() & C1->getValue()) != 0 &&
1747 Value *Or = Builder->CreateOr(X, RHS);
1749 return BinaryOperator::CreateAnd(Or,
1750 ConstantInt::get(I.getContext(),
1751 RHS->getValue() | C1->getValue()));
1754 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1755 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1757 Value *Or = Builder->CreateOr(X, RHS);
1759 return BinaryOperator::CreateXor(Or,
1760 ConstantInt::get(I.getContext(),
1761 C1->getValue() & ~RHS->getValue()));
1764 // Try to fold constant and into select arguments.
1765 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1766 if (Instruction *R = FoldOpIntoSelect(I, SI))
1769 if (isa<PHINode>(Op0))
1770 if (Instruction *NV = FoldOpIntoPhi(I))
1774 Value *A = 0, *B = 0;
1775 ConstantInt *C1 = 0, *C2 = 0;
1777 // (A | B) | C and A | (B | C) -> bswap if possible.
1778 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1779 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1780 match(Op1, m_Or(m_Value(), m_Value())) ||
1781 (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1782 match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
1783 if (Instruction *BSwap = MatchBSwap(I))
1787 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1788 if (Op0->hasOneUse() &&
1789 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1790 MaskedValueIsZero(Op1, C1->getValue())) {
1791 Value *NOr = Builder->CreateOr(A, Op1);
1793 return BinaryOperator::CreateXor(NOr, C1);
1796 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1797 if (Op1->hasOneUse() &&
1798 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1799 MaskedValueIsZero(Op0, C1->getValue())) {
1800 Value *NOr = Builder->CreateOr(A, Op0);
1802 return BinaryOperator::CreateXor(NOr, C1);
1806 Value *C = 0, *D = 0;
1807 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1808 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1809 Value *V1 = 0, *V2 = 0;
1810 C1 = dyn_cast<ConstantInt>(C);
1811 C2 = dyn_cast<ConstantInt>(D);
1812 if (C1 && C2) { // (A & C1)|(B & C2)
1813 // If we have: ((V + N) & C1) | (V & C2)
1814 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1815 // replace with V+N.
1816 if (C1->getValue() == ~C2->getValue()) {
1817 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
1818 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1819 // Add commutes, try both ways.
1820 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1821 return ReplaceInstUsesWith(I, A);
1822 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1823 return ReplaceInstUsesWith(I, A);
1825 // Or commutes, try both ways.
1826 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
1827 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1828 // Add commutes, try both ways.
1829 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1830 return ReplaceInstUsesWith(I, B);
1831 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1832 return ReplaceInstUsesWith(I, B);
1836 if ((C1->getValue() & C2->getValue()) == 0) {
1837 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
1838 // iff (C1&C2) == 0 and (N&~C1) == 0
1839 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
1840 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
1841 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
1842 return BinaryOperator::CreateAnd(A,
1843 ConstantInt::get(A->getContext(),
1844 C1->getValue()|C2->getValue()));
1845 // Or commutes, try both ways.
1846 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
1847 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
1848 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
1849 return BinaryOperator::CreateAnd(B,
1850 ConstantInt::get(B->getContext(),
1851 C1->getValue()|C2->getValue()));
1853 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
1854 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
1855 ConstantInt *C3 = 0, *C4 = 0;
1856 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
1857 (C3->getValue() & ~C1->getValue()) == 0 &&
1858 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
1859 (C4->getValue() & ~C2->getValue()) == 0) {
1860 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
1861 return BinaryOperator::CreateAnd(V2,
1862 ConstantInt::get(B->getContext(),
1863 C1->getValue()|C2->getValue()));
1868 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
1869 // Don't do this for vector select idioms, the code generator doesn't handle
1871 if (!I.getType()->isVectorTy()) {
1872 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
1874 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
1876 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
1878 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
1882 // ((A&~B)|(~A&B)) -> A^B
1883 if ((match(C, m_Not(m_Specific(D))) &&
1884 match(B, m_Not(m_Specific(A)))))
1885 return BinaryOperator::CreateXor(A, D);
1886 // ((~B&A)|(~A&B)) -> A^B
1887 if ((match(A, m_Not(m_Specific(D))) &&
1888 match(B, m_Not(m_Specific(C)))))
1889 return BinaryOperator::CreateXor(C, D);
1890 // ((A&~B)|(B&~A)) -> A^B
1891 if ((match(C, m_Not(m_Specific(B))) &&
1892 match(D, m_Not(m_Specific(A)))))
1893 return BinaryOperator::CreateXor(A, B);
1894 // ((~B&A)|(B&~A)) -> A^B
1895 if ((match(A, m_Not(m_Specific(B))) &&
1896 match(D, m_Not(m_Specific(C)))))
1897 return BinaryOperator::CreateXor(C, B);
1899 // ((A|B)&1)|(B&-2) -> (A&1) | B
1900 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
1901 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
1902 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
1903 if (Ret) return Ret;
1905 // (B&-2)|((A|B)&1) -> (A&1) | B
1906 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
1907 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
1908 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
1909 if (Ret) return Ret;
1913 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
1914 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1915 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1916 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1917 SI0->getOperand(1) == SI1->getOperand(1) &&
1918 (SI0->hasOneUse() || SI1->hasOneUse())) {
1919 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
1921 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1922 SI1->getOperand(1));
1926 // (~A | ~B) == (~(A & B)) - De Morgan's Law
1927 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1928 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1929 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1930 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
1931 I.getName()+".demorgan");
1932 return BinaryOperator::CreateNot(And);
1935 // Canonicalize xor to the RHS.
1936 bool SwappedForXor = false;
1937 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
1938 std::swap(Op0, Op1);
1939 SwappedForXor = true;
1942 // A | ( A ^ B) -> A | B
1943 // A | (~A ^ B) -> A | ~B
1944 // (A & B) | (A ^ B)
1945 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
1946 if (Op0 == A || Op0 == B)
1947 return BinaryOperator::CreateOr(A, B);
1949 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
1950 match(Op0, m_And(m_Specific(B), m_Specific(A))))
1951 return BinaryOperator::CreateOr(A, B);
1953 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
1954 Value *Not = Builder->CreateNot(B, B->getName()+".not");
1955 return BinaryOperator::CreateOr(Not, Op0);
1957 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
1958 Value *Not = Builder->CreateNot(A, A->getName()+".not");
1959 return BinaryOperator::CreateOr(Not, Op0);
1963 // A | ~(A | B) -> A | ~B
1964 // A | ~(A ^ B) -> A | ~B
1965 if (match(Op1, m_Not(m_Value(A))))
1966 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
1967 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
1968 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
1969 B->getOpcode() == Instruction::Xor)) {
1970 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
1972 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
1973 return BinaryOperator::CreateOr(Not, Op0);
1977 std::swap(Op0, Op1);
1979 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
1980 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
1981 if (Value *Res = FoldOrOfICmps(LHS, RHS))
1982 return ReplaceInstUsesWith(I, Res);
1984 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
1985 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1986 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1987 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
1988 return ReplaceInstUsesWith(I, Res);
1990 // fold (or (cast A), (cast B)) -> (cast (or A, B))
1991 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
1992 CastInst *Op1C = dyn_cast<CastInst>(Op1);
1993 if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
1994 Type *SrcTy = Op0C->getOperand(0)->getType();
1995 if (SrcTy == Op1C->getOperand(0)->getType() &&
1996 SrcTy->isIntOrIntVectorTy()) {
1997 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1999 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
2000 // Only do this if the casts both really cause code to be
2002 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
2003 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
2004 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
2005 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2008 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
2009 // cast is otherwise not optimizable. This happens for vector sexts.
2010 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
2011 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
2012 if (Value *Res = FoldOrOfICmps(LHS, RHS))
2013 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
2015 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
2016 // cast is otherwise not optimizable. This happens for vector sexts.
2017 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
2018 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
2019 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2020 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
2025 // or(sext(A), B) -> A ? -1 : B where A is an i1
2026 // or(A, sext(B)) -> B ? -1 : A where B is an i1
2027 if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2028 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2029 if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2030 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2032 // Note: If we've gotten to the point of visiting the outer OR, then the
2033 // inner one couldn't be simplified. If it was a constant, then it won't
2034 // be simplified by a later pass either, so we try swapping the inner/outer
2035 // ORs in the hopes that we'll be able to simplify it this way.
2036 // (X|C) | V --> (X|V) | C
2037 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2038 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2039 Value *Inner = Builder->CreateOr(A, Op1);
2040 Inner->takeName(Op0);
2041 return BinaryOperator::CreateOr(Inner, C1);
2044 return Changed ? &I : 0;
2047 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2048 bool Changed = SimplifyAssociativeOrCommutative(I);
2049 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2051 if (Value *V = SimplifyXorInst(Op0, Op1, TD))
2052 return ReplaceInstUsesWith(I, V);
2054 // (A&B)^(A&C) -> A&(B^C) etc
2055 if (Value *V = SimplifyUsingDistributiveLaws(I))
2056 return ReplaceInstUsesWith(I, V);
2058 // See if we can simplify any instructions used by the instruction whose sole
2059 // purpose is to compute bits we don't care about.
2060 if (SimplifyDemandedInstructionBits(I))
2063 // Is this a ~ operation?
2064 if (Value *NotOp = dyn_castNotVal(&I)) {
2065 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2066 if (Op0I->getOpcode() == Instruction::And ||
2067 Op0I->getOpcode() == Instruction::Or) {
2068 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2069 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2070 if (dyn_castNotVal(Op0I->getOperand(1)))
2071 Op0I->swapOperands();
2072 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2074 Builder->CreateNot(Op0I->getOperand(1),
2075 Op0I->getOperand(1)->getName()+".not");
2076 if (Op0I->getOpcode() == Instruction::And)
2077 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2078 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2081 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2082 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2083 if (isFreeToInvert(Op0I->getOperand(0)) &&
2084 isFreeToInvert(Op0I->getOperand(1))) {
2086 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2088 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2089 if (Op0I->getOpcode() == Instruction::And)
2090 return BinaryOperator::CreateOr(NotX, NotY);
2091 return BinaryOperator::CreateAnd(NotX, NotY);
2094 } else if (Op0I->getOpcode() == Instruction::AShr) {
2095 // ~(~X >>s Y) --> (X >>s Y)
2096 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2097 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
2103 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2104 if (RHS->isOne() && Op0->hasOneUse())
2105 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2106 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2107 return CmpInst::Create(CI->getOpcode(),
2108 CI->getInversePredicate(),
2109 CI->getOperand(0), CI->getOperand(1));
2111 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2112 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2113 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2114 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2115 Instruction::CastOps Opcode = Op0C->getOpcode();
2116 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2117 (RHS == ConstantExpr::getCast(Opcode,
2118 ConstantInt::getTrue(I.getContext()),
2119 Op0C->getDestTy()))) {
2120 CI->setPredicate(CI->getInversePredicate());
2121 return CastInst::Create(Opcode, CI, Op0C->getType());
2127 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2128 // ~(c-X) == X-c-1 == X+(-c-1)
2129 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2130 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2131 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2132 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2133 ConstantInt::get(I.getType(), 1));
2134 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2137 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2138 if (Op0I->getOpcode() == Instruction::Add) {
2139 // ~(X-c) --> (-c-1)-X
2140 if (RHS->isAllOnesValue()) {
2141 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2142 return BinaryOperator::CreateSub(
2143 ConstantExpr::getSub(NegOp0CI,
2144 ConstantInt::get(I.getType(), 1)),
2145 Op0I->getOperand(0));
2146 } else if (RHS->getValue().isSignBit()) {
2147 // (X + C) ^ signbit -> (X + C + signbit)
2148 Constant *C = ConstantInt::get(I.getContext(),
2149 RHS->getValue() + Op0CI->getValue());
2150 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2153 } else if (Op0I->getOpcode() == Instruction::Or) {
2154 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2155 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
2156 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2157 // Anything in both C1 and C2 is known to be zero, remove it from
2159 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2160 NewRHS = ConstantExpr::getAnd(NewRHS,
2161 ConstantExpr::getNot(CommonBits));
2163 I.setOperand(0, Op0I->getOperand(0));
2164 I.setOperand(1, NewRHS);
2167 } else if (Op0I->getOpcode() == Instruction::LShr) {
2168 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2172 if (Op0I->hasOneUse() &&
2173 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2174 E1->getOpcode() == Instruction::Xor &&
2175 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2176 // fold (C1 >> C2) ^ C3
2177 ConstantInt *C2 = Op0CI, *C3 = RHS;
2178 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2179 FoldConst ^= C3->getValue();
2180 // Prepare the two operands.
2181 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2182 Opnd0->takeName(Op0I);
2183 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2184 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2186 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2192 // Try to fold constant and into select arguments.
2193 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2194 if (Instruction *R = FoldOpIntoSelect(I, SI))
2196 if (isa<PHINode>(Op0))
2197 if (Instruction *NV = FoldOpIntoPhi(I))
2201 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2204 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2205 if (A == Op0) { // B^(B|A) == (A|B)^B
2206 Op1I->swapOperands();
2208 std::swap(Op0, Op1);
2209 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2210 I.swapOperands(); // Simplified below.
2211 std::swap(Op0, Op1);
2213 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
2215 if (A == Op0) { // A^(A&B) -> A^(B&A)
2216 Op1I->swapOperands();
2219 if (B == Op0) { // A^(B&A) -> (B&A)^A
2220 I.swapOperands(); // Simplified below.
2221 std::swap(Op0, Op1);
2226 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2229 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2230 Op0I->hasOneUse()) {
2231 if (A == Op1) // (B|A)^B == (A|B)^B
2233 if (B == Op1) // (A|B)^B == A & ~B
2234 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
2235 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2237 if (A == Op1) // (A&B)^A -> (B&A)^A
2239 if (B == Op1 && // (B&A)^A == ~B & A
2240 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
2241 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
2246 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
2247 if (Op0I && Op1I && Op0I->isShift() &&
2248 Op0I->getOpcode() == Op1I->getOpcode() &&
2249 Op0I->getOperand(1) == Op1I->getOperand(1) &&
2250 (Op0I->hasOneUse() || Op1I->hasOneUse())) {
2252 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2254 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
2255 Op1I->getOperand(1));
2259 Value *A, *B, *C, *D;
2260 // (A & B)^(A | B) -> A ^ B
2261 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2262 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
2263 if ((A == C && B == D) || (A == D && B == C))
2264 return BinaryOperator::CreateXor(A, B);
2266 // (A | B)^(A & B) -> A ^ B
2267 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2268 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2269 if ((A == C && B == D) || (A == D && B == C))
2270 return BinaryOperator::CreateXor(A, B);
2274 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2275 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2276 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2277 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2278 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2279 LHS->getOperand(1) == RHS->getOperand(0))
2280 LHS->swapOperands();
2281 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2282 LHS->getOperand(1) == RHS->getOperand(1)) {
2283 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2284 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2285 bool isSigned = LHS->isSigned() || RHS->isSigned();
2286 return ReplaceInstUsesWith(I,
2287 getNewICmpValue(isSigned, Code, Op0, Op1,
2292 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2293 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2294 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2295 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
2296 Type *SrcTy = Op0C->getOperand(0)->getType();
2297 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
2298 // Only do this if the casts both really cause code to be generated.
2299 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
2301 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
2303 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2304 Op1C->getOperand(0), I.getName());
2305 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2310 return Changed ? &I : 0;