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/ConstantRange.h"
17 #include "llvm/IR/Intrinsics.h"
18 #include "llvm/IR/PatternMatch.h"
19 #include "llvm/Transforms/Utils/CmpInstAnalysis.h"
21 using namespace PatternMatch;
23 #define DEBUG_TYPE "instcombine"
25 /// isFreeToInvert - Return true if the specified value is free to invert (apply
26 /// ~ to). This happens in cases where the ~ can be eliminated.
27 static inline bool isFreeToInvert(Value *V) {
29 if (BinaryOperator::isNot(V))
32 // Constants can be considered to be not'ed values.
33 if (isa<ConstantInt>(V))
36 // Compares can be inverted if they have a single use.
37 if (CmpInst *CI = dyn_cast<CmpInst>(V))
38 return CI->hasOneUse();
43 static inline Value *dyn_castNotVal(Value *V) {
44 // If this is not(not(x)) don't return that this is a not: we want the two
45 // not's to be folded first.
46 if (BinaryOperator::isNot(V)) {
47 Value *Operand = BinaryOperator::getNotArgument(V);
48 if (!isFreeToInvert(Operand))
52 // Constants can be considered to be not'ed values...
53 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
54 return ConstantInt::get(C->getType(), ~C->getValue());
58 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
59 /// predicate into a three bit mask. It also returns whether it is an ordered
60 /// predicate by reference.
61 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
64 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
65 case FCmpInst::FCMP_UNO: return 0; // 000
66 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
67 case FCmpInst::FCMP_UGT: return 1; // 001
68 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
69 case FCmpInst::FCMP_UEQ: return 2; // 010
70 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
71 case FCmpInst::FCMP_UGE: return 3; // 011
72 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
73 case FCmpInst::FCMP_ULT: return 4; // 100
74 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
75 case FCmpInst::FCMP_UNE: return 5; // 101
76 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
77 case FCmpInst::FCMP_ULE: return 6; // 110
80 // Not expecting FCMP_FALSE and FCMP_TRUE;
81 llvm_unreachable("Unexpected FCmp predicate!");
85 /// getNewICmpValue - This is the complement of getICmpCode, which turns an
86 /// opcode and two operands into either a constant true or false, or a brand
87 /// new ICmp instruction. The sign is passed in to determine which kind
88 /// of predicate to use in the new icmp instruction.
89 static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
90 InstCombiner::BuilderTy *Builder) {
91 ICmpInst::Predicate NewPred;
92 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
94 return Builder->CreateICmp(NewPred, LHS, RHS);
97 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
98 /// opcode and two operands into either a FCmp instruction. isordered is passed
99 /// in to determine which kind of predicate to use in the new fcmp instruction.
100 static Value *getFCmpValue(bool isordered, unsigned code,
101 Value *LHS, Value *RHS,
102 InstCombiner::BuilderTy *Builder) {
103 CmpInst::Predicate Pred;
105 default: llvm_unreachable("Illegal FCmp code!");
106 case 0: Pred = isordered ? FCmpInst::FCMP_ORD : FCmpInst::FCMP_UNO; break;
107 case 1: Pred = isordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; break;
108 case 2: Pred = isordered ? FCmpInst::FCMP_OEQ : FCmpInst::FCMP_UEQ; break;
109 case 3: Pred = isordered ? FCmpInst::FCMP_OGE : FCmpInst::FCMP_UGE; break;
110 case 4: Pred = isordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; break;
111 case 5: Pred = isordered ? FCmpInst::FCMP_ONE : FCmpInst::FCMP_UNE; break;
112 case 6: Pred = isordered ? FCmpInst::FCMP_OLE : FCmpInst::FCMP_ULE; break;
114 if (!isordered) return ConstantInt::getTrue(LHS->getContext());
115 Pred = FCmpInst::FCMP_ORD; break;
117 return Builder->CreateFCmp(Pred, LHS, RHS);
120 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
121 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
122 // guaranteed to be a binary operator.
123 Instruction *InstCombiner::OptAndOp(Instruction *Op,
126 BinaryOperator &TheAnd) {
127 Value *X = Op->getOperand(0);
128 Constant *Together = nullptr;
130 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
132 switch (Op->getOpcode()) {
133 case Instruction::Xor:
134 if (Op->hasOneUse()) {
135 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
136 Value *And = Builder->CreateAnd(X, AndRHS);
138 return BinaryOperator::CreateXor(And, Together);
141 case Instruction::Or:
142 if (Op->hasOneUse()){
143 if (Together != OpRHS) {
144 // (X | C1) & C2 --> (X | (C1&C2)) & C2
145 Value *Or = Builder->CreateOr(X, Together);
147 return BinaryOperator::CreateAnd(Or, AndRHS);
150 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
151 if (TogetherCI && !TogetherCI->isZero()){
152 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
153 // NOTE: This reduces the number of bits set in the & mask, which
154 // can expose opportunities for store narrowing.
155 Together = ConstantExpr::getXor(AndRHS, Together);
156 Value *And = Builder->CreateAnd(X, Together);
158 return BinaryOperator::CreateOr(And, OpRHS);
163 case Instruction::Add:
164 if (Op->hasOneUse()) {
165 // Adding a one to a single bit bit-field should be turned into an XOR
166 // of the bit. First thing to check is to see if this AND is with a
167 // single bit constant.
168 const APInt &AndRHSV = AndRHS->getValue();
170 // If there is only one bit set.
171 if (AndRHSV.isPowerOf2()) {
172 // Ok, at this point, we know that we are masking the result of the
173 // ADD down to exactly one bit. If the constant we are adding has
174 // no bits set below this bit, then we can eliminate the ADD.
175 const APInt& AddRHS = OpRHS->getValue();
177 // Check to see if any bits below the one bit set in AndRHSV are set.
178 if ((AddRHS & (AndRHSV-1)) == 0) {
179 // If not, the only thing that can effect the output of the AND is
180 // the bit specified by AndRHSV. If that bit is set, the effect of
181 // the XOR is to toggle the bit. If it is clear, then the ADD has
183 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
184 TheAnd.setOperand(0, X);
187 // Pull the XOR out of the AND.
188 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
189 NewAnd->takeName(Op);
190 return BinaryOperator::CreateXor(NewAnd, AndRHS);
197 case Instruction::Shl: {
198 // We know that the AND will not produce any of the bits shifted in, so if
199 // the anded constant includes them, clear them now!
201 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
202 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
203 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
204 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
206 if (CI->getValue() == ShlMask)
207 // Masking out bits that the shift already masks.
208 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
210 if (CI != AndRHS) { // Reducing bits set in and.
211 TheAnd.setOperand(1, CI);
216 case Instruction::LShr: {
217 // We know that the AND will not produce any of the bits shifted in, so if
218 // the anded constant includes them, clear them now! This only applies to
219 // unsigned shifts, because a signed shr may bring in set bits!
221 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
222 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
223 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
224 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
226 if (CI->getValue() == ShrMask)
227 // Masking out bits that the shift already masks.
228 return ReplaceInstUsesWith(TheAnd, Op);
231 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
236 case Instruction::AShr:
238 // See if this is shifting in some sign extension, then masking it out
240 if (Op->hasOneUse()) {
241 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
242 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
243 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
244 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
245 if (C == AndRHS) { // Masking out bits shifted in.
246 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
247 // Make the argument unsigned.
248 Value *ShVal = Op->getOperand(0);
249 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
250 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
258 /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
259 /// (V < Lo || V >= Hi). In practice, we emit the more efficient
260 /// (V-Lo) \<u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
261 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
262 /// insert new instructions.
263 Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
264 bool isSigned, bool Inside) {
265 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
266 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
267 "Lo is not <= Hi in range emission code!");
270 if (Lo == Hi) // Trivially false.
271 return Builder->getFalse();
273 // V >= Min && V < Hi --> V < Hi
274 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
275 ICmpInst::Predicate pred = (isSigned ?
276 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
277 return Builder->CreateICmp(pred, V, Hi);
280 // Emit V-Lo <u Hi-Lo
281 Constant *NegLo = ConstantExpr::getNeg(Lo);
282 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
283 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
284 return Builder->CreateICmpULT(Add, UpperBound);
287 if (Lo == Hi) // Trivially true.
288 return Builder->getTrue();
290 // V < Min || V >= Hi -> V > Hi-1
291 Hi = SubOne(cast<ConstantInt>(Hi));
292 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
293 ICmpInst::Predicate pred = (isSigned ?
294 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
295 return Builder->CreateICmp(pred, V, Hi);
298 // Emit V-Lo >u Hi-1-Lo
299 // Note that Hi has already had one subtracted from it, above.
300 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
301 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
302 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
303 return Builder->CreateICmpUGT(Add, LowerBound);
306 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
307 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
308 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
309 // not, since all 1s are not contiguous.
310 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
311 const APInt& V = Val->getValue();
312 uint32_t BitWidth = Val->getType()->getBitWidth();
313 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
315 // look for the first zero bit after the run of ones
316 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
317 // look for the first non-zero bit
318 ME = V.getActiveBits();
322 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
323 /// where isSub determines whether the operator is a sub. If we can fold one of
324 /// the following xforms:
326 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
327 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
328 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
330 /// return (A +/- B).
332 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
333 ConstantInt *Mask, bool isSub,
335 Instruction *LHSI = dyn_cast<Instruction>(LHS);
336 if (!LHSI || LHSI->getNumOperands() != 2 ||
337 !isa<ConstantInt>(LHSI->getOperand(1))) return nullptr;
339 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
341 switch (LHSI->getOpcode()) {
342 default: return nullptr;
343 case Instruction::And:
344 if (ConstantExpr::getAnd(N, Mask) == Mask) {
345 // If the AndRHS is a power of two minus one (0+1+), this is simple.
346 if ((Mask->getValue().countLeadingZeros() +
347 Mask->getValue().countPopulation()) ==
348 Mask->getValue().getBitWidth())
351 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
352 // part, we don't need any explicit masks to take them out of A. If that
353 // is all N is, ignore it.
354 uint32_t MB = 0, ME = 0;
355 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
356 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
357 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
358 if (MaskedValueIsZero(RHS, Mask))
363 case Instruction::Or:
364 case Instruction::Xor:
365 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
366 if ((Mask->getValue().countLeadingZeros() +
367 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
368 && ConstantExpr::getAnd(N, Mask)->isNullValue())
374 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
375 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
378 /// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
379 /// One of A and B is considered the mask, the other the value. This is
380 /// described as the "AMask" or "BMask" part of the enum. If the enum
381 /// contains only "Mask", then both A and B can be considered masks.
382 /// If A is the mask, then it was proven, that (A & C) == C. This
383 /// is trivial if C == A, or C == 0. If both A and C are constants, this
384 /// proof is also easy.
385 /// For the following explanations we assume that A is the mask.
386 /// The part "AllOnes" declares, that the comparison is true only
387 /// if (A & B) == A, or all bits of A are set in B.
388 /// Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
389 /// The part "AllZeroes" declares, that the comparison is true only
390 /// if (A & B) == 0, or all bits of A are cleared in B.
391 /// Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
392 /// The part "Mixed" declares, that (A & B) == C and C might or might not
393 /// contain any number of one bits and zero bits.
394 /// Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
395 /// The Part "Not" means, that in above descriptions "==" should be replaced
397 /// Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
398 /// If the mask A contains a single bit, then the following is equivalent:
399 /// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
400 /// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
401 enum MaskedICmpType {
402 FoldMskICmp_AMask_AllOnes = 1,
403 FoldMskICmp_AMask_NotAllOnes = 2,
404 FoldMskICmp_BMask_AllOnes = 4,
405 FoldMskICmp_BMask_NotAllOnes = 8,
406 FoldMskICmp_Mask_AllZeroes = 16,
407 FoldMskICmp_Mask_NotAllZeroes = 32,
408 FoldMskICmp_AMask_Mixed = 64,
409 FoldMskICmp_AMask_NotMixed = 128,
410 FoldMskICmp_BMask_Mixed = 256,
411 FoldMskICmp_BMask_NotMixed = 512
414 /// return the set of pattern classes (from MaskedICmpType)
415 /// that (icmp SCC (A & B), C) satisfies
416 static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
417 ICmpInst::Predicate SCC)
419 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
420 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
421 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
422 bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
423 bool icmp_abit = (ACst && !ACst->isZero() &&
424 ACst->getValue().isPowerOf2());
425 bool icmp_bbit = (BCst && !BCst->isZero() &&
426 BCst->getValue().isPowerOf2());
428 if (CCst && CCst->isZero()) {
429 // if C is zero, then both A and B qualify as mask
430 result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
431 FoldMskICmp_Mask_AllZeroes |
432 FoldMskICmp_AMask_Mixed |
433 FoldMskICmp_BMask_Mixed)
434 : (FoldMskICmp_Mask_NotAllZeroes |
435 FoldMskICmp_Mask_NotAllZeroes |
436 FoldMskICmp_AMask_NotMixed |
437 FoldMskICmp_BMask_NotMixed));
439 result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
440 FoldMskICmp_AMask_NotMixed)
441 : (FoldMskICmp_AMask_AllOnes |
442 FoldMskICmp_AMask_Mixed));
444 result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
445 FoldMskICmp_BMask_NotMixed)
446 : (FoldMskICmp_BMask_AllOnes |
447 FoldMskICmp_BMask_Mixed));
451 result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
452 FoldMskICmp_AMask_Mixed)
453 : (FoldMskICmp_AMask_NotAllOnes |
454 FoldMskICmp_AMask_NotMixed));
456 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
457 FoldMskICmp_AMask_NotMixed)
458 : (FoldMskICmp_Mask_AllZeroes |
459 FoldMskICmp_AMask_Mixed));
460 } else if (ACst && CCst &&
461 ConstantExpr::getAnd(ACst, CCst) == CCst) {
462 result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
463 : FoldMskICmp_AMask_NotMixed);
466 result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
467 FoldMskICmp_BMask_Mixed)
468 : (FoldMskICmp_BMask_NotAllOnes |
469 FoldMskICmp_BMask_NotMixed));
471 result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
472 FoldMskICmp_BMask_NotMixed)
473 : (FoldMskICmp_Mask_AllZeroes |
474 FoldMskICmp_BMask_Mixed));
475 } else if (BCst && CCst &&
476 ConstantExpr::getAnd(BCst, CCst) == CCst) {
477 result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
478 : FoldMskICmp_BMask_NotMixed);
483 /// Convert an analysis of a masked ICmp into its equivalent if all boolean
484 /// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
485 /// is adjacent to the corresponding normal flag (recording ==), this just
486 /// involves swapping those bits over.
487 static unsigned conjugateICmpMask(unsigned Mask) {
489 NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
490 FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
491 FoldMskICmp_BMask_Mixed))
495 (Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
496 FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
497 FoldMskICmp_BMask_NotMixed))
503 /// decomposeBitTestICmp - Decompose an icmp into the form ((X & Y) pred Z)
504 /// if possible. The returned predicate is either == or !=. Returns false if
505 /// decomposition fails.
506 static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
507 Value *&X, Value *&Y, Value *&Z) {
508 ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1));
512 switch (I->getPredicate()) {
515 case ICmpInst::ICMP_SLT:
516 // X < 0 is equivalent to (X & SignBit) != 0.
519 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
520 Pred = ICmpInst::ICMP_NE;
522 case ICmpInst::ICMP_SGT:
523 // X > -1 is equivalent to (X & SignBit) == 0.
524 if (!C->isAllOnesValue())
526 Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
527 Pred = ICmpInst::ICMP_EQ;
529 case ICmpInst::ICMP_ULT:
530 // X <u 2^n is equivalent to (X & ~(2^n-1)) == 0.
531 if (!C->getValue().isPowerOf2())
533 Y = ConstantInt::get(I->getContext(), -C->getValue());
534 Pred = ICmpInst::ICMP_EQ;
536 case ICmpInst::ICMP_UGT:
537 // X >u 2^n-1 is equivalent to (X & ~(2^n-1)) != 0.
538 if (!(C->getValue() + 1).isPowerOf2())
540 Y = ConstantInt::get(I->getContext(), ~C->getValue());
541 Pred = ICmpInst::ICMP_NE;
545 X = I->getOperand(0);
546 Z = ConstantInt::getNullValue(C->getType());
550 /// foldLogOpOfMaskedICmpsHelper:
551 /// handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
552 /// return the set of pattern classes (from MaskedICmpType)
553 /// that both LHS and RHS satisfy
554 static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
555 Value*& B, Value*& C,
556 Value*& D, Value*& E,
557 ICmpInst *LHS, ICmpInst *RHS,
558 ICmpInst::Predicate &LHSCC,
559 ICmpInst::Predicate &RHSCC) {
560 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
561 // vectors are not (yet?) supported
562 if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
564 // Here comes the tricky part:
565 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
566 // and L11 & L12 == L21 & L22. The same goes for RHS.
567 // Now we must find those components L** and R**, that are equal, so
568 // that we can extract the parameters A, B, C, D, and E for the canonical
570 Value *L1 = LHS->getOperand(0);
571 Value *L2 = LHS->getOperand(1);
572 Value *L11,*L12,*L21,*L22;
573 // Check whether the icmp can be decomposed into a bit test.
574 if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
575 L21 = L22 = L1 = nullptr;
577 // Look for ANDs in the LHS icmp.
578 if (!L1->getType()->isIntegerTy()) {
579 // You can icmp pointers, for example. They really aren't masks.
581 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
582 // Any icmp can be viewed as being trivially masked; if it allows us to
583 // remove one, it's worth it.
585 L12 = Constant::getAllOnesValue(L1->getType());
588 if (!L2->getType()->isIntegerTy()) {
589 // You can icmp pointers, for example. They really aren't masks.
591 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
593 L22 = Constant::getAllOnesValue(L2->getType());
597 // Bail if LHS was a icmp that can't be decomposed into an equality.
598 if (!ICmpInst::isEquality(LHSCC))
601 Value *R1 = RHS->getOperand(0);
602 Value *R2 = RHS->getOperand(1);
605 if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
606 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
608 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
613 E = R2; R1 = nullptr; ok = true;
614 } else if (R1->getType()->isIntegerTy()) {
615 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
616 // As before, model no mask as a trivial mask if it'll let us do an
619 R12 = Constant::getAllOnesValue(R1->getType());
622 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
623 A = R11; D = R12; E = R2; ok = true;
624 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
625 A = R12; D = R11; E = R2; ok = true;
629 // Bail if RHS was a icmp that can't be decomposed into an equality.
630 if (!ICmpInst::isEquality(RHSCC))
633 // Look for ANDs in on the right side of the RHS icmp.
634 if (!ok && R2->getType()->isIntegerTy()) {
635 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
637 R12 = Constant::getAllOnesValue(R2->getType());
640 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
641 A = R11; D = R12; E = R1; ok = true;
642 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
643 A = R12; D = R11; E = R1; ok = true;
653 } else if (L12 == A) {
655 } else if (L21 == A) {
657 } else if (L22 == A) {
661 unsigned left_type = getTypeOfMaskedICmp(A, B, C, LHSCC);
662 unsigned right_type = getTypeOfMaskedICmp(A, D, E, RHSCC);
663 return left_type & right_type;
665 /// foldLogOpOfMaskedICmps:
666 /// try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
667 /// into a single (icmp(A & X) ==/!= Y)
668 static Value* foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
669 llvm::InstCombiner::BuilderTy* Builder) {
670 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
671 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
672 unsigned mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
674 if (mask == 0) return nullptr;
675 assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
676 "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
678 // In full generality:
679 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
680 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
682 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
683 // equivalent to (icmp (A & X) !Op Y).
685 // Therefore, we can pretend for the rest of this function that we're dealing
686 // with the conjunction, provided we flip the sense of any comparisons (both
687 // input and output).
689 // In most cases we're going to produce an EQ for the "&&" case.
690 ICmpInst::Predicate NEWCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
692 // Convert the masking analysis into its equivalent with negated
694 mask = conjugateICmpMask(mask);
697 if (mask & FoldMskICmp_Mask_AllZeroes) {
698 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
699 // -> (icmp eq (A & (B|D)), 0)
700 Value* newOr = Builder->CreateOr(B, D);
701 Value* newAnd = Builder->CreateAnd(A, newOr);
702 // we can't use C as zero, because we might actually handle
703 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
704 // with B and D, having a single bit set
705 Value* zero = Constant::getNullValue(A->getType());
706 return Builder->CreateICmp(NEWCC, newAnd, zero);
708 if (mask & FoldMskICmp_BMask_AllOnes) {
709 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
710 // -> (icmp eq (A & (B|D)), (B|D))
711 Value* newOr = Builder->CreateOr(B, D);
712 Value* newAnd = Builder->CreateAnd(A, newOr);
713 return Builder->CreateICmp(NEWCC, newAnd, newOr);
715 if (mask & FoldMskICmp_AMask_AllOnes) {
716 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
717 // -> (icmp eq (A & (B&D)), A)
718 Value* newAnd1 = Builder->CreateAnd(B, D);
719 Value* newAnd = Builder->CreateAnd(A, newAnd1);
720 return Builder->CreateICmp(NEWCC, newAnd, A);
723 // Remaining cases assume at least that B and D are constant, and depend on
724 // their actual values. This isn't strictly, necessary, just a "handle the
725 // easy cases for now" decision.
726 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
727 if (!BCst) return nullptr;
728 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
729 if (!DCst) return nullptr;
731 if (mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
732 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
733 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
734 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
735 // Only valid if one of the masks is a superset of the other (check "B&D" is
736 // the same as either B or D).
737 APInt NewMask = BCst->getValue() & DCst->getValue();
739 if (NewMask == BCst->getValue())
741 else if (NewMask == DCst->getValue())
744 if (mask & FoldMskICmp_AMask_NotAllOnes) {
745 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
746 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
747 // Only valid if one of the masks is a superset of the other (check "B|D" is
748 // the same as either B or D).
749 APInt NewMask = BCst->getValue() | DCst->getValue();
751 if (NewMask == BCst->getValue())
753 else if (NewMask == DCst->getValue())
756 if (mask & FoldMskICmp_BMask_Mixed) {
757 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
758 // We already know that B & C == C && D & E == E.
759 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
760 // C and E, which are shared by both the mask B and the mask D, don't
761 // contradict, then we can transform to
762 // -> (icmp eq (A & (B|D)), (C|E))
763 // Currently, we only handle the case of B, C, D, and E being constant.
764 // we can't simply use C and E, because we might actually handle
765 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
766 // with B and D, having a single bit set
767 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
768 if (!CCst) return nullptr;
770 CCst = dyn_cast<ConstantInt>( ConstantExpr::getXor(BCst, CCst) );
771 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
772 if (!ECst) return nullptr;
774 ECst = dyn_cast<ConstantInt>( ConstantExpr::getXor(DCst, ECst) );
775 ConstantInt* MCst = dyn_cast<ConstantInt>(
776 ConstantExpr::getAnd(ConstantExpr::getAnd(BCst, DCst),
777 ConstantExpr::getXor(CCst, ECst)) );
778 // if there is a conflict we should actually return a false for the
782 Value *newOr1 = Builder->CreateOr(B, D);
783 Value *newOr2 = ConstantExpr::getOr(CCst, ECst);
784 Value *newAnd = Builder->CreateAnd(A, newOr1);
785 return Builder->CreateICmp(NEWCC, newAnd, newOr2);
790 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
791 Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
792 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
794 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
795 if (PredicatesFoldable(LHSCC, RHSCC)) {
796 if (LHS->getOperand(0) == RHS->getOperand(1) &&
797 LHS->getOperand(1) == RHS->getOperand(0))
799 if (LHS->getOperand(0) == RHS->getOperand(0) &&
800 LHS->getOperand(1) == RHS->getOperand(1)) {
801 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
802 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
803 bool isSigned = LHS->isSigned() || RHS->isSigned();
804 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
808 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
809 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
812 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
813 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
814 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
815 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
816 if (!LHSCst || !RHSCst) return nullptr;
818 if (LHSCst == RHSCst && LHSCC == RHSCC) {
819 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
820 // where C is a power of 2
821 if (LHSCC == ICmpInst::ICMP_ULT &&
822 LHSCst->getValue().isPowerOf2()) {
823 Value *NewOr = Builder->CreateOr(Val, Val2);
824 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
827 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
828 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
829 Value *NewOr = Builder->CreateOr(Val, Val2);
830 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
834 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
835 // where CMAX is the all ones value for the truncated type,
836 // iff the lower bits of C2 and CA are zero.
837 if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
838 LHS->hasOneUse() && RHS->hasOneUse()) {
840 ConstantInt *AndCst, *SmallCst = nullptr, *BigCst = nullptr;
842 // (trunc x) == C1 & (and x, CA) == C2
843 // (and x, CA) == C2 & (trunc x) == C1
844 if (match(Val2, m_Trunc(m_Value(V))) &&
845 match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
848 } else if (match(Val, m_Trunc(m_Value(V))) &&
849 match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
854 if (SmallCst && BigCst) {
855 unsigned BigBitSize = BigCst->getType()->getBitWidth();
856 unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
858 // Check that the low bits are zero.
859 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
860 if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
861 Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
862 APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
863 Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
864 return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
869 // From here on, we only handle:
870 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
871 if (Val != Val2) return nullptr;
873 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
874 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
875 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
876 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
877 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
880 // Make a constant range that's the intersection of the two icmp ranges.
881 // If the intersection is empty, we know that the result is false.
882 ConstantRange LHSRange =
883 ConstantRange::makeICmpRegion(LHSCC, LHSCst->getValue());
884 ConstantRange RHSRange =
885 ConstantRange::makeICmpRegion(RHSCC, RHSCst->getValue());
887 if (LHSRange.intersectWith(RHSRange).isEmptySet())
888 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
890 // We can't fold (ugt x, C) & (sgt x, C2).
891 if (!PredicatesFoldable(LHSCC, RHSCC))
894 // Ensure that the larger constant is on the RHS.
896 if (CmpInst::isSigned(LHSCC) ||
897 (ICmpInst::isEquality(LHSCC) &&
898 CmpInst::isSigned(RHSCC)))
899 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
901 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
905 std::swap(LHSCst, RHSCst);
906 std::swap(LHSCC, RHSCC);
909 // At this point, we know we have two icmp instructions
910 // comparing a value against two constants and and'ing the result
911 // together. Because of the above check, we know that we only have
912 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
913 // (from the icmp folding check above), that the two constants
914 // are not equal and that the larger constant is on the RHS
915 assert(LHSCst != RHSCst && "Compares not folded above?");
918 default: llvm_unreachable("Unknown integer condition code!");
919 case ICmpInst::ICMP_EQ:
921 default: llvm_unreachable("Unknown integer condition code!");
922 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
923 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
924 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
927 case ICmpInst::ICMP_NE:
929 default: llvm_unreachable("Unknown integer condition code!");
930 case ICmpInst::ICMP_ULT:
931 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
932 return Builder->CreateICmpULT(Val, LHSCst);
933 break; // (X != 13 & X u< 15) -> no change
934 case ICmpInst::ICMP_SLT:
935 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
936 return Builder->CreateICmpSLT(Val, LHSCst);
937 break; // (X != 13 & X s< 15) -> no change
938 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
939 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
940 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
942 case ICmpInst::ICMP_NE:
943 // Special case to get the ordering right when the values wrap around
945 if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
946 std::swap(LHSCst, RHSCst);
947 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
948 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
949 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
950 return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
951 Val->getName()+".cmp");
953 break; // (X != 13 & X != 15) -> no change
956 case ICmpInst::ICMP_ULT:
958 default: llvm_unreachable("Unknown integer condition code!");
959 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
960 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
961 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
962 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
964 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
965 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
967 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
971 case ICmpInst::ICMP_SLT:
973 default: llvm_unreachable("Unknown integer condition code!");
974 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
976 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
977 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
979 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
983 case ICmpInst::ICMP_UGT:
985 default: llvm_unreachable("Unknown integer condition code!");
986 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
987 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
989 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
991 case ICmpInst::ICMP_NE:
992 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
993 return Builder->CreateICmp(LHSCC, Val, RHSCst);
994 break; // (X u> 13 & X != 15) -> no change
995 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
996 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
997 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
1001 case ICmpInst::ICMP_SGT:
1003 default: llvm_unreachable("Unknown integer condition code!");
1004 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
1005 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
1007 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
1009 case ICmpInst::ICMP_NE:
1010 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
1011 return Builder->CreateICmp(LHSCC, Val, RHSCst);
1012 break; // (X s> 13 & X != 15) -> no change
1013 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
1014 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
1015 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
1024 /// FoldAndOfFCmps - Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of
1025 /// instcombine, this returns a Value which should already be inserted into the
1027 Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1028 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1029 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
1030 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
1033 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1034 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1035 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1036 // If either of the constants are nans, then the whole thing returns
1038 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1039 return Builder->getFalse();
1040 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
1043 // Handle vector zeros. This occurs because the canonical form of
1044 // "fcmp ord x,x" is "fcmp ord x, 0".
1045 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1046 isa<ConstantAggregateZero>(RHS->getOperand(1)))
1047 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
1051 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1052 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1053 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1056 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1057 // Swap RHS operands to match LHS.
1058 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1059 std::swap(Op1LHS, Op1RHS);
1062 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1063 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1065 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1066 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
1067 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1068 if (Op0CC == FCmpInst::FCMP_TRUE)
1070 if (Op1CC == FCmpInst::FCMP_TRUE)
1075 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1076 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1077 // uno && ord -> false
1078 if (Op0Pred == 0 && Op1Pred == 0 && Op0Ordered != Op1Ordered)
1079 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1081 std::swap(LHS, RHS);
1082 std::swap(Op0Pred, Op1Pred);
1083 std::swap(Op0Ordered, Op1Ordered);
1086 // uno && ueq -> uno && (uno || eq) -> uno
1087 // ord && olt -> ord && (ord && lt) -> olt
1088 if (!Op0Ordered && (Op0Ordered == Op1Ordered))
1090 if (Op0Ordered && (Op0Ordered == Op1Ordered))
1093 // uno && oeq -> uno && (ord && eq) -> false
1095 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1096 // ord && ueq -> ord && (uno || eq) -> oeq
1097 return getFCmpValue(true, Op1Pred, Op0LHS, Op0RHS, Builder);
1105 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1106 bool Changed = SimplifyAssociativeOrCommutative(I);
1107 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1109 if (Value *V = SimplifyVectorOp(I))
1110 return ReplaceInstUsesWith(I, V);
1112 if (Value *V = SimplifyAndInst(Op0, Op1, DL))
1113 return ReplaceInstUsesWith(I, V);
1115 // (A|B)&(A|C) -> A|(B&C) etc
1116 if (Value *V = SimplifyUsingDistributiveLaws(I))
1117 return ReplaceInstUsesWith(I, V);
1119 // See if we can simplify any instructions used by the instruction whose sole
1120 // purpose is to compute bits we don't care about.
1121 if (SimplifyDemandedInstructionBits(I))
1124 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1125 const APInt &AndRHSMask = AndRHS->getValue();
1127 // Optimize a variety of ((val OP C1) & C2) combinations...
1128 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1129 Value *Op0LHS = Op0I->getOperand(0);
1130 Value *Op0RHS = Op0I->getOperand(1);
1131 switch (Op0I->getOpcode()) {
1133 case Instruction::Xor:
1134 case Instruction::Or: {
1135 // If the mask is only needed on one incoming arm, push it up.
1136 if (!Op0I->hasOneUse()) break;
1138 APInt NotAndRHS(~AndRHSMask);
1139 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1140 // Not masking anything out for the LHS, move to RHS.
1141 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1142 Op0RHS->getName()+".masked");
1143 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1145 if (!isa<Constant>(Op0RHS) &&
1146 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1147 // Not masking anything out for the RHS, move to LHS.
1148 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1149 Op0LHS->getName()+".masked");
1150 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1155 case Instruction::Add:
1156 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1157 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1158 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1159 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1160 return BinaryOperator::CreateAnd(V, AndRHS);
1161 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1162 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
1165 case Instruction::Sub:
1166 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1167 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1168 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1169 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1170 return BinaryOperator::CreateAnd(V, AndRHS);
1172 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1173 // has 1's for all bits that the subtraction with A might affect.
1174 if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
1175 uint32_t BitWidth = AndRHSMask.getBitWidth();
1176 uint32_t Zeros = AndRHSMask.countLeadingZeros();
1177 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1179 if (MaskedValueIsZero(Op0LHS, Mask)) {
1180 Value *NewNeg = Builder->CreateNeg(Op0RHS);
1181 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1186 case Instruction::Shl:
1187 case Instruction::LShr:
1188 // (1 << x) & 1 --> zext(x == 0)
1189 // (1 >> x) & 1 --> zext(x == 0)
1190 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1192 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1193 return new ZExtInst(NewICmp, I.getType());
1198 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1199 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1203 // If this is an integer truncation, and if the source is an 'and' with
1204 // immediate, transform it. This frequently occurs for bitfield accesses.
1206 Value *X = nullptr; ConstantInt *YC = nullptr;
1207 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1208 // Change: and (trunc (and X, YC) to T), C2
1209 // into : and (trunc X to T), trunc(YC) & C2
1210 // This will fold the two constants together, which may allow
1211 // other simplifications.
1212 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1213 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1214 C3 = ConstantExpr::getAnd(C3, AndRHS);
1215 return BinaryOperator::CreateAnd(NewCast, C3);
1219 // Try to fold constant and into select arguments.
1220 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1221 if (Instruction *R = FoldOpIntoSelect(I, SI))
1223 if (isa<PHINode>(Op0))
1224 if (Instruction *NV = FoldOpIntoPhi(I))
1229 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1230 if (Value *Op0NotVal = dyn_castNotVal(Op0))
1231 if (Value *Op1NotVal = dyn_castNotVal(Op1))
1232 if (Op0->hasOneUse() && Op1->hasOneUse()) {
1233 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
1234 I.getName()+".demorgan");
1235 return BinaryOperator::CreateNot(Or);
1239 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
1240 // (A|B) & ~(A&B) -> A^B
1241 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1242 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1243 ((A == C && B == D) || (A == D && B == C)))
1244 return BinaryOperator::CreateXor(A, B);
1246 // ~(A&B) & (A|B) -> A^B
1247 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1248 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1249 ((A == C && B == D) || (A == D && B == C)))
1250 return BinaryOperator::CreateXor(A, B);
1252 // A&(A^B) => A & ~B
1254 Value *tmpOp0 = Op0;
1255 Value *tmpOp1 = Op1;
1256 if (Op0->hasOneUse() &&
1257 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
1258 if (A == Op1 || B == Op1 ) {
1265 if (tmpOp1->hasOneUse() &&
1266 match(tmpOp1, m_Xor(m_Value(A), m_Value(B)))) {
1270 // Notice that the patten (A&(~B)) is actually (A&(-1^B)), so if
1271 // A is originally -1 (or a vector of -1 and undefs), then we enter
1272 // an endless loop. By checking that A is non-constant we ensure that
1273 // we will never get to the loop.
1274 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
1275 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
1279 // (A&((~A)|B)) -> A&B
1280 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1281 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1282 return BinaryOperator::CreateAnd(A, Op1);
1283 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1284 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1285 return BinaryOperator::CreateAnd(A, Op0);
1287 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1288 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1289 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1290 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
1291 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1293 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1294 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1295 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1296 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
1297 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
1300 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1))
1301 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
1302 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1303 return ReplaceInstUsesWith(I, Res);
1305 // If and'ing two fcmp, try combine them into one.
1306 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1307 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1308 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1309 return ReplaceInstUsesWith(I, Res);
1312 // fold (and (cast A), (cast B)) -> (cast (and A, B))
1313 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
1314 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
1315 Type *SrcTy = Op0C->getOperand(0)->getType();
1316 if (Op0C->getOpcode() == Op1C->getOpcode() && // same cast kind ?
1317 SrcTy == Op1C->getOperand(0)->getType() &&
1318 SrcTy->isIntOrIntVectorTy()) {
1319 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
1321 // Only do this if the casts both really cause code to be generated.
1322 if (ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
1323 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
1324 Value *NewOp = Builder->CreateAnd(Op0COp, Op1COp, I.getName());
1325 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
1328 // If this is and(cast(icmp), cast(icmp)), try to fold this even if the
1329 // cast is otherwise not optimizable. This happens for vector sexts.
1330 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
1331 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
1332 if (Value *Res = FoldAndOfICmps(LHS, RHS))
1333 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1335 // If this is and(cast(fcmp), cast(fcmp)), try to fold this even if the
1336 // cast is otherwise not optimizable. This happens for vector sexts.
1337 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
1338 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
1339 if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1340 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
1344 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
1345 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
1346 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
1347 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
1348 SI0->getOperand(1) == SI1->getOperand(1) &&
1349 (SI0->hasOneUse() || SI1->hasOneUse())) {
1351 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
1353 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
1354 SI1->getOperand(1));
1360 bool OpsSwapped = false;
1361 // Canonicalize SExt or Not to the LHS
1362 if (match(Op1, m_SExt(m_Value())) ||
1363 match(Op1, m_Not(m_Value()))) {
1364 std::swap(Op0, Op1);
1368 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1369 if (match(Op0, m_SExt(m_Value(X))) &&
1370 X->getType()->getScalarType()->isIntegerTy(1)) {
1371 Value *Zero = Constant::getNullValue(Op1->getType());
1372 return SelectInst::Create(X, Op1, Zero);
1375 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1376 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1377 X->getType()->getScalarType()->isIntegerTy(1)) {
1378 Value *Zero = Constant::getNullValue(Op0->getType());
1379 return SelectInst::Create(X, Zero, Op1);
1383 std::swap(Op0, Op1);
1386 return Changed ? &I : nullptr;
1389 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
1390 /// capable of providing pieces of a bswap. The subexpression provides pieces
1391 /// of a bswap if it is proven that each of the non-zero bytes in the output of
1392 /// the expression came from the corresponding "byte swapped" byte in some other
1393 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
1394 /// we know that the expression deposits the low byte of %X into the high byte
1395 /// of the bswap result and that all other bytes are zero. This expression is
1396 /// accepted, the high byte of ByteValues is set to X to indicate a correct
1399 /// This function returns true if the match was unsuccessful and false if so.
1400 /// On entry to the function the "OverallLeftShift" is a signed integer value
1401 /// indicating the number of bytes that the subexpression is later shifted. For
1402 /// example, if the expression is later right shifted by 16 bits, the
1403 /// OverallLeftShift value would be -2 on entry. This is used to specify which
1404 /// byte of ByteValues is actually being set.
1406 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
1407 /// byte is masked to zero by a user. For example, in (X & 255), X will be
1408 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
1409 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
1410 /// always in the local (OverallLeftShift) coordinate space.
1412 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
1413 SmallVectorImpl<Value *> &ByteValues) {
1414 if (Instruction *I = dyn_cast<Instruction>(V)) {
1415 // If this is an or instruction, it may be an inner node of the bswap.
1416 if (I->getOpcode() == Instruction::Or) {
1417 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1419 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
1423 // If this is a logical shift by a constant multiple of 8, recurse with
1424 // OverallLeftShift and ByteMask adjusted.
1425 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
1427 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
1428 // Ensure the shift amount is defined and of a byte value.
1429 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
1432 unsigned ByteShift = ShAmt >> 3;
1433 if (I->getOpcode() == Instruction::Shl) {
1434 // X << 2 -> collect(X, +2)
1435 OverallLeftShift += ByteShift;
1436 ByteMask >>= ByteShift;
1438 // X >>u 2 -> collect(X, -2)
1439 OverallLeftShift -= ByteShift;
1440 ByteMask <<= ByteShift;
1441 ByteMask &= (~0U >> (32-ByteValues.size()));
1444 if (OverallLeftShift >= (int)ByteValues.size()) return true;
1445 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
1447 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1451 // If this is a logical 'and' with a mask that clears bytes, clear the
1452 // corresponding bytes in ByteMask.
1453 if (I->getOpcode() == Instruction::And &&
1454 isa<ConstantInt>(I->getOperand(1))) {
1455 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
1456 unsigned NumBytes = ByteValues.size();
1457 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
1458 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
1460 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
1461 // If this byte is masked out by a later operation, we don't care what
1463 if ((ByteMask & (1 << i)) == 0)
1466 // If the AndMask is all zeros for this byte, clear the bit.
1467 APInt MaskB = AndMask & Byte;
1469 ByteMask &= ~(1U << i);
1473 // If the AndMask is not all ones for this byte, it's not a bytezap.
1477 // Otherwise, this byte is kept.
1480 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
1485 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
1486 // the input value to the bswap. Some observations: 1) if more than one byte
1487 // is demanded from this input, then it could not be successfully assembled
1488 // into a byteswap. At least one of the two bytes would not be aligned with
1489 // their ultimate destination.
1490 if (!isPowerOf2_32(ByteMask)) return true;
1491 unsigned InputByteNo = countTrailingZeros(ByteMask);
1493 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
1494 // is demanded, it needs to go into byte 0 of the result. This means that the
1495 // byte needs to be shifted until it lands in the right byte bucket. The
1496 // shift amount depends on the position: if the byte is coming from the high
1497 // part of the value (e.g. byte 3) then it must be shifted right. If from the
1498 // low part, it must be shifted left.
1499 unsigned DestByteNo = InputByteNo + OverallLeftShift;
1500 if (ByteValues.size()-1-DestByteNo != InputByteNo)
1503 // If the destination byte value is already defined, the values are or'd
1504 // together, which isn't a bswap (unless it's an or of the same bits).
1505 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
1507 ByteValues[DestByteNo] = V;
1511 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
1512 /// If so, insert the new bswap intrinsic and return it.
1513 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1514 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
1515 if (!ITy || ITy->getBitWidth() % 16 ||
1516 // ByteMask only allows up to 32-byte values.
1517 ITy->getBitWidth() > 32*8)
1518 return nullptr; // Can only bswap pairs of bytes. Can't do vectors.
1520 /// ByteValues - For each byte of the result, we keep track of which value
1521 /// defines each byte.
1522 SmallVector<Value*, 8> ByteValues;
1523 ByteValues.resize(ITy->getBitWidth()/8);
1525 // Try to find all the pieces corresponding to the bswap.
1526 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
1527 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
1530 // Check to see if all of the bytes come from the same value.
1531 Value *V = ByteValues[0];
1532 if (!V) return nullptr; // Didn't find a byte? Must be zero.
1534 // Check to make sure that all of the bytes come from the same value.
1535 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
1536 if (ByteValues[i] != V)
1538 Module *M = I.getParent()->getParent()->getParent();
1539 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, ITy);
1540 return CallInst::Create(F, V);
1543 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
1544 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
1545 /// we can simplify this expression to "cond ? C : D or B".
1546 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
1547 Value *C, Value *D) {
1548 // If A is not a select of -1/0, this cannot match.
1549 Value *Cond = nullptr;
1550 if (!match(A, m_SExt(m_Value(Cond))) ||
1551 !Cond->getType()->isIntegerTy(1))
1554 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
1555 if (match(D, m_Not(m_SExt(m_Specific(Cond)))))
1556 return SelectInst::Create(Cond, C, B);
1557 if (match(D, m_SExt(m_Not(m_Specific(Cond)))))
1558 return SelectInst::Create(Cond, C, B);
1560 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
1561 if (match(B, m_Not(m_SExt(m_Specific(Cond)))))
1562 return SelectInst::Create(Cond, C, D);
1563 if (match(B, m_SExt(m_Not(m_Specific(Cond)))))
1564 return SelectInst::Create(Cond, C, D);
1568 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
1569 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
1570 ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1572 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1573 // if K1 and K2 are a one-bit mask.
1574 ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1575 ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1577 if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
1578 RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1580 BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1581 BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1582 if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1583 LAnd->getOpcode() == Instruction::And &&
1584 RAnd->getOpcode() == Instruction::And) {
1586 Value *Mask = nullptr;
1587 Value *Masked = nullptr;
1588 if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
1589 isKnownToBeAPowerOfTwo(LAnd->getOperand(1)) &&
1590 isKnownToBeAPowerOfTwo(RAnd->getOperand(1))) {
1591 Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1592 Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1593 } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
1594 isKnownToBeAPowerOfTwo(LAnd->getOperand(0)) &&
1595 isKnownToBeAPowerOfTwo(RAnd->getOperand(0))) {
1596 Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1597 Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1601 return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1605 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1606 if (PredicatesFoldable(LHSCC, RHSCC)) {
1607 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1608 LHS->getOperand(1) == RHS->getOperand(0))
1609 LHS->swapOperands();
1610 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1611 LHS->getOperand(1) == RHS->getOperand(1)) {
1612 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1613 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1614 bool isSigned = LHS->isSigned() || RHS->isSigned();
1615 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
1619 // handle (roughly):
1620 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1621 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
1624 Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1625 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1626 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1627 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
1628 Value *A = nullptr, *B = nullptr;
1629 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1631 if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1633 else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1634 A = RHS->getOperand(1);
1636 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1637 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1638 else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1640 if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1642 else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1643 A = LHS->getOperand(1);
1646 return Builder->CreateICmp(
1648 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1651 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1652 if (!LHSCst || !RHSCst) return nullptr;
1654 if (LHSCst == RHSCst && LHSCC == RHSCC) {
1655 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1656 if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1657 Value *NewOr = Builder->CreateOr(Val, Val2);
1658 return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1662 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
1663 // iff C2 + CA == C1.
1664 if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
1665 ConstantInt *AddCst;
1666 if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1667 if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
1668 return Builder->CreateICmpULE(Val, LHSCst);
1671 // From here on, we only handle:
1672 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1673 if (Val != Val2) return nullptr;
1675 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1676 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1677 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1678 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1679 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1682 // We can't fold (ugt x, C) | (sgt x, C2).
1683 if (!PredicatesFoldable(LHSCC, RHSCC))
1686 // Ensure that the larger constant is on the RHS.
1688 if (CmpInst::isSigned(LHSCC) ||
1689 (ICmpInst::isEquality(LHSCC) &&
1690 CmpInst::isSigned(RHSCC)))
1691 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1693 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1696 std::swap(LHS, RHS);
1697 std::swap(LHSCst, RHSCst);
1698 std::swap(LHSCC, RHSCC);
1701 // At this point, we know we have two icmp instructions
1702 // comparing a value against two constants and or'ing the result
1703 // together. Because of the above check, we know that we only have
1704 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1705 // icmp folding check above), that the two constants are not
1707 assert(LHSCst != RHSCst && "Compares not folded above?");
1710 default: llvm_unreachable("Unknown integer condition code!");
1711 case ICmpInst::ICMP_EQ:
1713 default: llvm_unreachable("Unknown integer condition code!");
1714 case ICmpInst::ICMP_EQ:
1715 if (LHS->getOperand(0) == RHS->getOperand(0)) {
1716 // if LHSCst and RHSCst differ only by one bit:
1717 // (A == C1 || A == C2) -> (A & ~(C1 ^ C2)) == C1
1718 assert(LHSCst->getValue().ule(LHSCst->getValue()));
1720 APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1721 if (Xor.isPowerOf2()) {
1722 Value *NegCst = Builder->getInt(~Xor);
1723 Value *And = Builder->CreateAnd(LHS->getOperand(0), NegCst);
1724 return Builder->CreateICmp(ICmpInst::ICMP_EQ, And, LHSCst);
1728 if (LHSCst == SubOne(RHSCst)) {
1729 // (X == 13 | X == 14) -> X-13 <u 2
1730 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1731 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1732 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1733 return Builder->CreateICmpULT(Add, AddCST);
1736 break; // (X == 13 | X == 15) -> no change
1737 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1738 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1740 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
1741 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
1742 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
1746 case ICmpInst::ICMP_NE:
1748 default: llvm_unreachable("Unknown integer condition code!");
1749 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
1750 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
1751 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
1753 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
1754 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
1755 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
1756 return Builder->getTrue();
1758 case ICmpInst::ICMP_ULT:
1760 default: llvm_unreachable("Unknown integer condition code!");
1761 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1763 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1764 // If RHSCst is [us]MAXINT, it is always false. Not handling
1765 // this can cause overflow.
1766 if (RHSCst->isMaxValue(false))
1768 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
1769 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
1771 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
1772 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
1774 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
1778 case ICmpInst::ICMP_SLT:
1780 default: llvm_unreachable("Unknown integer condition code!");
1781 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1783 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1784 // If RHSCst is [us]MAXINT, it is always false. Not handling
1785 // this can cause overflow.
1786 if (RHSCst->isMaxValue(true))
1788 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
1789 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
1791 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
1792 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
1794 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
1798 case ICmpInst::ICMP_UGT:
1800 default: llvm_unreachable("Unknown integer condition code!");
1801 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
1802 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
1804 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
1806 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
1807 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
1808 return Builder->getTrue();
1809 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
1813 case ICmpInst::ICMP_SGT:
1815 default: llvm_unreachable("Unknown integer condition code!");
1816 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
1817 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
1819 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
1821 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
1822 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
1823 return Builder->getTrue();
1824 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
1832 /// FoldOrOfFCmps - Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of
1833 /// instcombine, this returns a Value which should already be inserted into the
1835 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1836 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1837 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1838 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1839 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1840 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1841 // If either of the constants are nans, then the whole thing returns
1843 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1844 return Builder->getTrue();
1846 // Otherwise, no need to compare the two constants, compare the
1848 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1851 // Handle vector zeros. This occurs because the canonical form of
1852 // "fcmp uno x,x" is "fcmp uno x, 0".
1853 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1854 isa<ConstantAggregateZero>(RHS->getOperand(1)))
1855 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1860 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1861 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1862 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1864 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1865 // Swap RHS operands to match LHS.
1866 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1867 std::swap(Op1LHS, Op1RHS);
1869 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
1870 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1872 return Builder->CreateFCmp((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
1873 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
1874 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
1875 if (Op0CC == FCmpInst::FCMP_FALSE)
1877 if (Op1CC == FCmpInst::FCMP_FALSE)
1881 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
1882 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
1883 if (Op0Ordered == Op1Ordered) {
1884 // If both are ordered or unordered, return a new fcmp with
1885 // or'ed predicates.
1886 return getFCmpValue(Op0Ordered, Op0Pred|Op1Pred, Op0LHS, Op0RHS, Builder);
1892 /// FoldOrWithConstants - This helper function folds:
1894 /// ((A | B) & C1) | (B & C2)
1900 /// when the XOR of the two constants is "all ones" (-1).
1901 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
1902 Value *A, Value *B, Value *C) {
1903 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1904 if (!CI1) return nullptr;
1906 Value *V1 = nullptr;
1907 ConstantInt *CI2 = nullptr;
1908 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
1910 APInt Xor = CI1->getValue() ^ CI2->getValue();
1911 if (!Xor.isAllOnesValue()) return nullptr;
1913 if (V1 == A || V1 == B) {
1914 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1915 return BinaryOperator::CreateOr(NewOp, V1);
1921 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1922 bool Changed = SimplifyAssociativeOrCommutative(I);
1923 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1925 if (Value *V = SimplifyVectorOp(I))
1926 return ReplaceInstUsesWith(I, V);
1928 if (Value *V = SimplifyOrInst(Op0, Op1, DL))
1929 return ReplaceInstUsesWith(I, V);
1931 // (A&B)|(A&C) -> A&(B|C) etc
1932 if (Value *V = SimplifyUsingDistributiveLaws(I))
1933 return ReplaceInstUsesWith(I, V);
1935 // See if we can simplify any instructions used by the instruction whose sole
1936 // purpose is to compute bits we don't care about.
1937 if (SimplifyDemandedInstructionBits(I))
1940 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1941 ConstantInt *C1 = nullptr; Value *X = nullptr;
1942 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1943 // iff (C1 & C2) == 0.
1944 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
1945 (RHS->getValue() & C1->getValue()) != 0 &&
1947 Value *Or = Builder->CreateOr(X, RHS);
1949 return BinaryOperator::CreateAnd(Or,
1950 Builder->getInt(RHS->getValue() | C1->getValue()));
1953 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1954 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
1956 Value *Or = Builder->CreateOr(X, RHS);
1958 return BinaryOperator::CreateXor(Or,
1959 Builder->getInt(C1->getValue() & ~RHS->getValue()));
1962 // Try to fold constant and into select arguments.
1963 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1964 if (Instruction *R = FoldOpIntoSelect(I, SI))
1967 if (isa<PHINode>(Op0))
1968 if (Instruction *NV = FoldOpIntoPhi(I))
1972 Value *A = nullptr, *B = nullptr;
1973 ConstantInt *C1 = nullptr, *C2 = nullptr;
1975 // (A | B) | C and A | (B | C) -> bswap if possible.
1976 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1977 if (match(Op0, m_Or(m_Value(), m_Value())) ||
1978 match(Op1, m_Or(m_Value(), m_Value())) ||
1979 (match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1980 match(Op1, m_LogicalShift(m_Value(), m_Value())))) {
1981 if (Instruction *BSwap = MatchBSwap(I))
1985 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1986 if (Op0->hasOneUse() &&
1987 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1988 MaskedValueIsZero(Op1, C1->getValue())) {
1989 Value *NOr = Builder->CreateOr(A, Op1);
1991 return BinaryOperator::CreateXor(NOr, C1);
1994 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1995 if (Op1->hasOneUse() &&
1996 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1997 MaskedValueIsZero(Op0, C1->getValue())) {
1998 Value *NOr = Builder->CreateOr(A, Op0);
2000 return BinaryOperator::CreateXor(NOr, C1);
2003 // ((~A & B) | A) -> (A | B)
2004 if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2005 match(Op1, m_Specific(A)))
2006 return BinaryOperator::CreateOr(A, B);
2008 // ((A & B) | ~A) -> (~A | B)
2009 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2010 match(Op1, m_Not(m_Specific(A))))
2011 return BinaryOperator::CreateOr(Builder->CreateNot(A), B);
2014 Value *C = nullptr, *D = nullptr;
2015 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2016 match(Op1, m_And(m_Value(B), m_Value(D)))) {
2017 Value *V1 = nullptr, *V2 = nullptr;
2018 C1 = dyn_cast<ConstantInt>(C);
2019 C2 = dyn_cast<ConstantInt>(D);
2020 if (C1 && C2) { // (A & C1)|(B & C2)
2021 if ((C1->getValue() & C2->getValue()) == 0) {
2022 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
2023 // iff (C1&C2) == 0 and (N&~C1) == 0
2024 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
2025 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
2026 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
2027 return BinaryOperator::CreateAnd(A,
2028 Builder->getInt(C1->getValue()|C2->getValue()));
2029 // Or commutes, try both ways.
2030 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
2031 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
2032 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
2033 return BinaryOperator::CreateAnd(B,
2034 Builder->getInt(C1->getValue()|C2->getValue()));
2036 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
2037 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
2038 ConstantInt *C3 = nullptr, *C4 = nullptr;
2039 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2040 (C3->getValue() & ~C1->getValue()) == 0 &&
2041 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2042 (C4->getValue() & ~C2->getValue()) == 0) {
2043 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2044 return BinaryOperator::CreateAnd(V2,
2045 Builder->getInt(C1->getValue()|C2->getValue()));
2050 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants.
2051 // Don't do this for vector select idioms, the code generator doesn't handle
2053 if (!I.getType()->isVectorTy()) {
2054 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
2056 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
2058 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
2060 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
2064 // ((A&~B)|(~A&B)) -> A^B
2065 if ((match(C, m_Not(m_Specific(D))) &&
2066 match(B, m_Not(m_Specific(A)))))
2067 return BinaryOperator::CreateXor(A, D);
2068 // ((~B&A)|(~A&B)) -> A^B
2069 if ((match(A, m_Not(m_Specific(D))) &&
2070 match(B, m_Not(m_Specific(C)))))
2071 return BinaryOperator::CreateXor(C, D);
2072 // ((A&~B)|(B&~A)) -> A^B
2073 if ((match(C, m_Not(m_Specific(B))) &&
2074 match(D, m_Not(m_Specific(A)))))
2075 return BinaryOperator::CreateXor(A, B);
2076 // ((~B&A)|(B&~A)) -> A^B
2077 if ((match(A, m_Not(m_Specific(B))) &&
2078 match(D, m_Not(m_Specific(C)))))
2079 return BinaryOperator::CreateXor(C, B);
2081 // ((A|B)&1)|(B&-2) -> (A&1) | B
2082 if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2083 match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2084 Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2085 if (Ret) return Ret;
2087 // (B&-2)|((A|B)&1) -> (A&1) | B
2088 if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2089 match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2090 Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2091 if (Ret) return Ret;
2095 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2096 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2097 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2098 if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
2099 return BinaryOperator::CreateOr(Op0, C);
2101 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2102 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2103 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2104 if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
2105 return BinaryOperator::CreateOr(Op1, C);
2107 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
2108 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
2109 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
2110 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
2111 SI0->getOperand(1) == SI1->getOperand(1) &&
2112 (SI0->hasOneUse() || SI1->hasOneUse())) {
2113 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
2115 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
2116 SI1->getOperand(1));
2120 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2121 if (Value *Op0NotVal = dyn_castNotVal(Op0))
2122 if (Value *Op1NotVal = dyn_castNotVal(Op1))
2123 if (Op0->hasOneUse() && Op1->hasOneUse()) {
2124 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
2125 I.getName()+".demorgan");
2126 return BinaryOperator::CreateNot(And);
2129 // Canonicalize xor to the RHS.
2130 bool SwappedForXor = false;
2131 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
2132 std::swap(Op0, Op1);
2133 SwappedForXor = true;
2136 // A | ( A ^ B) -> A | B
2137 // A | (~A ^ B) -> A | ~B
2138 // (A & B) | (A ^ B)
2139 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2140 if (Op0 == A || Op0 == B)
2141 return BinaryOperator::CreateOr(A, B);
2143 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2144 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2145 return BinaryOperator::CreateOr(A, B);
2147 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2148 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2149 return BinaryOperator::CreateOr(Not, Op0);
2151 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2152 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2153 return BinaryOperator::CreateOr(Not, Op0);
2157 // A | ~(A | B) -> A | ~B
2158 // A | ~(A ^ B) -> A | ~B
2159 if (match(Op1, m_Not(m_Value(A))))
2160 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
2161 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2162 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2163 B->getOpcode() == Instruction::Xor)) {
2164 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2166 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2167 return BinaryOperator::CreateOr(Not, Op0);
2171 std::swap(Op0, Op1);
2173 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2174 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2175 if (Value *Res = FoldOrOfICmps(LHS, RHS))
2176 return ReplaceInstUsesWith(I, Res);
2178 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2179 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2180 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2181 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2182 return ReplaceInstUsesWith(I, Res);
2184 // fold (or (cast A), (cast B)) -> (cast (or A, B))
2185 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2186 CastInst *Op1C = dyn_cast<CastInst>(Op1);
2187 if (Op1C && Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
2188 Type *SrcTy = Op0C->getOperand(0)->getType();
2189 if (SrcTy == Op1C->getOperand(0)->getType() &&
2190 SrcTy->isIntOrIntVectorTy()) {
2191 Value *Op0COp = Op0C->getOperand(0), *Op1COp = Op1C->getOperand(0);
2193 if ((!isa<ICmpInst>(Op0COp) || !isa<ICmpInst>(Op1COp)) &&
2194 // Only do this if the casts both really cause code to be
2196 ShouldOptimizeCast(Op0C->getOpcode(), Op0COp, I.getType()) &&
2197 ShouldOptimizeCast(Op1C->getOpcode(), Op1COp, I.getType())) {
2198 Value *NewOp = Builder->CreateOr(Op0COp, Op1COp, I.getName());
2199 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2202 // If this is or(cast(icmp), cast(icmp)), try to fold this even if the
2203 // cast is otherwise not optimizable. This happens for vector sexts.
2204 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1COp))
2205 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0COp))
2206 if (Value *Res = FoldOrOfICmps(LHS, RHS))
2207 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
2209 // If this is or(cast(fcmp), cast(fcmp)), try to fold this even if the
2210 // cast is otherwise not optimizable. This happens for vector sexts.
2211 if (FCmpInst *RHS = dyn_cast<FCmpInst>(Op1COp))
2212 if (FCmpInst *LHS = dyn_cast<FCmpInst>(Op0COp))
2213 if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2214 return CastInst::Create(Op0C->getOpcode(), Res, I.getType());
2219 // or(sext(A), B) -> A ? -1 : B where A is an i1
2220 // or(A, sext(B)) -> B ? -1 : A where B is an i1
2221 if (match(Op0, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2222 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2223 if (match(Op1, m_SExt(m_Value(A))) && A->getType()->isIntegerTy(1))
2224 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2226 // Note: If we've gotten to the point of visiting the outer OR, then the
2227 // inner one couldn't be simplified. If it was a constant, then it won't
2228 // be simplified by a later pass either, so we try swapping the inner/outer
2229 // ORs in the hopes that we'll be able to simplify it this way.
2230 // (X|C) | V --> (X|V) | C
2231 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2232 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2233 Value *Inner = Builder->CreateOr(A, Op1);
2234 Inner->takeName(Op0);
2235 return BinaryOperator::CreateOr(Inner, C1);
2238 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2239 // Since this OR statement hasn't been optimized further yet, we hope
2240 // that this transformation will allow the new ORs to be optimized.
2242 Value *X = nullptr, *Y = nullptr;
2243 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2244 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2245 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2246 Value *orTrue = Builder->CreateOr(A, C);
2247 Value *orFalse = Builder->CreateOr(B, D);
2248 return SelectInst::Create(X, orTrue, orFalse);
2252 return Changed ? &I : nullptr;
2255 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2256 bool Changed = SimplifyAssociativeOrCommutative(I);
2257 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2259 if (Value *V = SimplifyVectorOp(I))
2260 return ReplaceInstUsesWith(I, V);
2262 if (Value *V = SimplifyXorInst(Op0, Op1, DL))
2263 return ReplaceInstUsesWith(I, V);
2265 // (A&B)^(A&C) -> A&(B^C) etc
2266 if (Value *V = SimplifyUsingDistributiveLaws(I))
2267 return ReplaceInstUsesWith(I, V);
2269 // See if we can simplify any instructions used by the instruction whose sole
2270 // purpose is to compute bits we don't care about.
2271 if (SimplifyDemandedInstructionBits(I))
2274 // Is this a ~ operation?
2275 if (Value *NotOp = dyn_castNotVal(&I)) {
2276 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2277 if (Op0I->getOpcode() == Instruction::And ||
2278 Op0I->getOpcode() == Instruction::Or) {
2279 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2280 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2281 if (dyn_castNotVal(Op0I->getOperand(1)))
2282 Op0I->swapOperands();
2283 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2285 Builder->CreateNot(Op0I->getOperand(1),
2286 Op0I->getOperand(1)->getName()+".not");
2287 if (Op0I->getOpcode() == Instruction::And)
2288 return BinaryOperator::CreateOr(Op0NotVal, NotY);
2289 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2292 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2293 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2294 if (isFreeToInvert(Op0I->getOperand(0)) &&
2295 isFreeToInvert(Op0I->getOperand(1))) {
2297 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2299 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2300 if (Op0I->getOpcode() == Instruction::And)
2301 return BinaryOperator::CreateOr(NotX, NotY);
2302 return BinaryOperator::CreateAnd(NotX, NotY);
2305 } else if (Op0I->getOpcode() == Instruction::AShr) {
2306 // ~(~X >>s Y) --> (X >>s Y)
2307 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2308 return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
2314 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2315 if (RHS->isOne() && Op0->hasOneUse())
2316 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2317 if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2318 return CmpInst::Create(CI->getOpcode(),
2319 CI->getInversePredicate(),
2320 CI->getOperand(0), CI->getOperand(1));
2322 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2323 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2324 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2325 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2326 Instruction::CastOps Opcode = Op0C->getOpcode();
2327 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2328 (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
2329 Op0C->getDestTy()))) {
2330 CI->setPredicate(CI->getInversePredicate());
2331 return CastInst::Create(Opcode, CI, Op0C->getType());
2337 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2338 // ~(c-X) == X-c-1 == X+(-c-1)
2339 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2340 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2341 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2342 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2343 ConstantInt::get(I.getType(), 1));
2344 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2347 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2348 if (Op0I->getOpcode() == Instruction::Add) {
2349 // ~(X-c) --> (-c-1)-X
2350 if (RHS->isAllOnesValue()) {
2351 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2352 return BinaryOperator::CreateSub(
2353 ConstantExpr::getSub(NegOp0CI,
2354 ConstantInt::get(I.getType(), 1)),
2355 Op0I->getOperand(0));
2356 } else if (RHS->getValue().isSignBit()) {
2357 // (X + C) ^ signbit -> (X + C + signbit)
2358 Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
2359 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2362 } else if (Op0I->getOpcode() == Instruction::Or) {
2363 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2364 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
2365 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2366 // Anything in both C1 and C2 is known to be zero, remove it from
2368 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2369 NewRHS = ConstantExpr::getAnd(NewRHS,
2370 ConstantExpr::getNot(CommonBits));
2372 I.setOperand(0, Op0I->getOperand(0));
2373 I.setOperand(1, NewRHS);
2376 } else if (Op0I->getOpcode() == Instruction::LShr) {
2377 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2381 if (Op0I->hasOneUse() &&
2382 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2383 E1->getOpcode() == Instruction::Xor &&
2384 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2385 // fold (C1 >> C2) ^ C3
2386 ConstantInt *C2 = Op0CI, *C3 = RHS;
2387 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2388 FoldConst ^= C3->getValue();
2389 // Prepare the two operands.
2390 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2391 Opnd0->takeName(Op0I);
2392 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2393 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2395 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2401 // Try to fold constant and into select arguments.
2402 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2403 if (Instruction *R = FoldOpIntoSelect(I, SI))
2405 if (isa<PHINode>(Op0))
2406 if (Instruction *NV = FoldOpIntoPhi(I))
2410 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2413 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2414 if (A == Op0) { // B^(B|A) == (A|B)^B
2415 Op1I->swapOperands();
2417 std::swap(Op0, Op1);
2418 } else if (B == Op0) { // B^(A|B) == (A|B)^B
2419 I.swapOperands(); // Simplified below.
2420 std::swap(Op0, Op1);
2422 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
2424 if (A == Op0) { // A^(A&B) -> A^(B&A)
2425 Op1I->swapOperands();
2428 if (B == Op0) { // A^(B&A) -> (B&A)^A
2429 I.swapOperands(); // Simplified below.
2430 std::swap(Op0, Op1);
2435 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2438 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2439 Op0I->hasOneUse()) {
2440 if (A == Op1) // (B|A)^B == (A|B)^B
2442 if (B == Op1) // (A|B)^B == A & ~B
2443 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
2444 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2446 if (A == Op1) // (A&B)^A -> (B&A)^A
2448 if (B == Op1 && // (B&A)^A == ~B & A
2449 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
2450 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
2455 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
2456 if (Op0I && Op1I && Op0I->isShift() &&
2457 Op0I->getOpcode() == Op1I->getOpcode() &&
2458 Op0I->getOperand(1) == Op1I->getOperand(1) &&
2459 (Op0I->hasOneUse() || Op1I->hasOneUse())) {
2461 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
2463 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
2464 Op1I->getOperand(1));
2468 Value *A, *B, *C, *D;
2469 // (A & B)^(A | B) -> A ^ B
2470 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2471 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
2472 if ((A == C && B == D) || (A == D && B == C))
2473 return BinaryOperator::CreateXor(A, B);
2475 // (A | B)^(A & B) -> A ^ B
2476 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2477 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2478 if ((A == C && B == D) || (A == D && B == C))
2479 return BinaryOperator::CreateXor(A, B);
2481 // (A & B) ^ (A ^ B) -> (A | B)
2482 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2483 match(Op1I, m_Xor(m_Specific(A), m_Specific(B))))
2484 return BinaryOperator::CreateOr(A, B);
2485 // (A ^ B) ^ (A & B) -> (A | B)
2486 if (match(Op0I, m_Xor(m_Value(A), m_Value(B))) &&
2487 match(Op1I, m_And(m_Specific(A), m_Specific(B))))
2488 return BinaryOperator::CreateOr(A, B);
2491 // (A | B)^(~A) -> (A | ~B)
2492 Value *A = nullptr, *B = nullptr;
2493 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2494 match(Op1, m_Not(m_Specific(A))))
2495 return BinaryOperator::CreateOr(A, Builder->CreateNot(B));
2497 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2498 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2499 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2500 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2501 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2502 LHS->getOperand(1) == RHS->getOperand(0))
2503 LHS->swapOperands();
2504 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2505 LHS->getOperand(1) == RHS->getOperand(1)) {
2506 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2507 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2508 bool isSigned = LHS->isSigned() || RHS->isSigned();
2509 return ReplaceInstUsesWith(I,
2510 getNewICmpValue(isSigned, Code, Op0, Op1,
2515 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
2516 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2517 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2518 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
2519 Type *SrcTy = Op0C->getOperand(0)->getType();
2520 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegerTy() &&
2521 // Only do this if the casts both really cause code to be generated.
2522 ShouldOptimizeCast(Op0C->getOpcode(), Op0C->getOperand(0),
2524 ShouldOptimizeCast(Op1C->getOpcode(), Op1C->getOperand(0),
2526 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
2527 Op1C->getOperand(0), I.getName());
2528 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
2533 return Changed ? &I : nullptr;