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 "InstCombineInternal.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"
20 #include "llvm/Transforms/Utils/Local.h"
22 using namespace PatternMatch;
24 #define DEBUG_TYPE "instcombine"
26 /// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
28 static unsigned getFCmpCode(FCmpInst::Predicate CC) {
29 assert(FCmpInst::FCMP_FALSE <= CC && CC <= FCmpInst::FCMP_TRUE &&
30 "Unexpected FCmp predicate!");
31 // Take advantage of the bit pattern of FCmpInst::Predicate here.
33 static_assert(FCmpInst::FCMP_FALSE == 0, ""); // 0 0 0 0
34 static_assert(FCmpInst::FCMP_OEQ == 1, ""); // 0 0 0 1
35 static_assert(FCmpInst::FCMP_OGT == 2, ""); // 0 0 1 0
36 static_assert(FCmpInst::FCMP_OGE == 3, ""); // 0 0 1 1
37 static_assert(FCmpInst::FCMP_OLT == 4, ""); // 0 1 0 0
38 static_assert(FCmpInst::FCMP_OLE == 5, ""); // 0 1 0 1
39 static_assert(FCmpInst::FCMP_ONE == 6, ""); // 0 1 1 0
40 static_assert(FCmpInst::FCMP_ORD == 7, ""); // 0 1 1 1
41 static_assert(FCmpInst::FCMP_UNO == 8, ""); // 1 0 0 0
42 static_assert(FCmpInst::FCMP_UEQ == 9, ""); // 1 0 0 1
43 static_assert(FCmpInst::FCMP_UGT == 10, ""); // 1 0 1 0
44 static_assert(FCmpInst::FCMP_UGE == 11, ""); // 1 0 1 1
45 static_assert(FCmpInst::FCMP_ULT == 12, ""); // 1 1 0 0
46 static_assert(FCmpInst::FCMP_ULE == 13, ""); // 1 1 0 1
47 static_assert(FCmpInst::FCMP_UNE == 14, ""); // 1 1 1 0
48 static_assert(FCmpInst::FCMP_TRUE == 15, ""); // 1 1 1 1
52 /// This is the complement of getICmpCode, which turns an opcode and two
53 /// operands into either a constant true or false, or a brand new ICmp
54 /// instruction. The sign is passed in to determine which kind of predicate to
55 /// use in the new icmp instruction.
56 static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
57 InstCombiner::BuilderTy *Builder) {
58 ICmpInst::Predicate NewPred;
59 if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
61 return Builder->CreateICmp(NewPred, LHS, RHS);
64 /// This is the complement of getFCmpCode, which turns an opcode and two
65 /// operands into either a FCmp instruction, or a true/false constant.
66 static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
67 InstCombiner::BuilderTy *Builder) {
68 const auto Pred = static_cast<FCmpInst::Predicate>(Code);
69 assert(FCmpInst::FCMP_FALSE <= Pred && Pred <= FCmpInst::FCMP_TRUE &&
70 "Unexpected FCmp predicate!");
71 if (Pred == FCmpInst::FCMP_FALSE)
72 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
73 if (Pred == FCmpInst::FCMP_TRUE)
74 return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
75 return Builder->CreateFCmp(Pred, LHS, RHS);
78 /// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
79 /// \param I Binary operator to transform.
80 /// \return Pointer to node that must replace the original binary operator, or
81 /// null pointer if no transformation was made.
82 Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
83 IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
86 if (I.getType()->isVectorTy())
89 // Can only do bitwise ops.
90 if (!I.isBitwiseLogicOp())
93 Value *OldLHS = I.getOperand(0);
94 Value *OldRHS = I.getOperand(1);
95 ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
96 ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
97 IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
98 IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
99 bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
100 bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
102 if (!IsBswapLHS && !IsBswapRHS)
105 if (!IsBswapLHS && !ConstLHS)
108 if (!IsBswapRHS && !ConstRHS)
111 /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
112 /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
113 Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
114 Builder->getInt(ConstLHS->getValue().byteSwap());
116 Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
117 Builder->getInt(ConstRHS->getValue().byteSwap());
119 Value *BinOp = Builder->CreateBinOp(I.getOpcode(), NewLHS, NewRHS);
120 Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap, ITy);
121 return Builder->CreateCall(F, BinOp);
124 /// This handles expressions of the form ((val OP C1) & C2). Where
125 /// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.
126 Instruction *InstCombiner::OptAndOp(BinaryOperator *Op,
129 BinaryOperator &TheAnd) {
130 Value *X = Op->getOperand(0);
131 Constant *Together = nullptr;
133 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
135 switch (Op->getOpcode()) {
137 case Instruction::Xor:
138 if (Op->hasOneUse()) {
139 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
140 Value *And = Builder->CreateAnd(X, AndRHS);
142 return BinaryOperator::CreateXor(And, Together);
145 case Instruction::Or:
146 if (Op->hasOneUse()){
147 ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
148 if (TogetherCI && !TogetherCI->isZero()){
149 // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
150 // NOTE: This reduces the number of bits set in the & mask, which
151 // can expose opportunities for store narrowing.
152 Together = ConstantExpr::getXor(AndRHS, Together);
153 Value *And = Builder->CreateAnd(X, Together);
155 return BinaryOperator::CreateOr(And, OpRHS);
160 case Instruction::Add:
161 if (Op->hasOneUse()) {
162 // Adding a one to a single bit bit-field should be turned into an XOR
163 // of the bit. First thing to check is to see if this AND is with a
164 // single bit constant.
165 const APInt &AndRHSV = AndRHS->getValue();
167 // If there is only one bit set.
168 if (AndRHSV.isPowerOf2()) {
169 // Ok, at this point, we know that we are masking the result of the
170 // ADD down to exactly one bit. If the constant we are adding has
171 // no bits set below this bit, then we can eliminate the ADD.
172 const APInt& AddRHS = OpRHS->getValue();
174 // Check to see if any bits below the one bit set in AndRHSV are set.
175 if ((AddRHS & (AndRHSV - 1)).isNullValue()) {
176 // If not, the only thing that can effect the output of the AND is
177 // the bit specified by AndRHSV. If that bit is set, the effect of
178 // the XOR is to toggle the bit. If it is clear, then the ADD has
180 if ((AddRHS & AndRHSV).isNullValue()) { // Bit is not set, noop
181 TheAnd.setOperand(0, X);
184 // Pull the XOR out of the AND.
185 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
186 NewAnd->takeName(Op);
187 return BinaryOperator::CreateXor(NewAnd, AndRHS);
194 case Instruction::Shl: {
195 // We know that the AND will not produce any of the bits shifted in, so if
196 // the anded constant includes them, clear them now!
198 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
199 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
200 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
201 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
203 if (CI->getValue() == ShlMask)
204 // Masking out bits that the shift already masks.
205 return replaceInstUsesWith(TheAnd, Op); // No need for the and.
207 if (CI != AndRHS) { // Reducing bits set in and.
208 TheAnd.setOperand(1, CI);
213 case Instruction::LShr: {
214 // We know that the AND will not produce any of the bits shifted in, so if
215 // the anded constant includes them, clear them now! This only applies to
216 // unsigned shifts, because a signed shr may bring in set bits!
218 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
219 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
220 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
221 ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
223 if (CI->getValue() == ShrMask)
224 // Masking out bits that the shift already masks.
225 return replaceInstUsesWith(TheAnd, Op);
228 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
233 case Instruction::AShr:
235 // See if this is shifting in some sign extension, then masking it out
237 if (Op->hasOneUse()) {
238 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
239 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
240 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
241 Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
242 if (C == AndRHS) { // Masking out bits shifted in.
243 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
244 // Make the argument unsigned.
245 Value *ShVal = Op->getOperand(0);
246 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
247 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
255 /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
256 /// (V < Lo || V >= Hi). This method expects that Lo <= Hi. IsSigned indicates
257 /// whether to treat V, Lo, and Hi as signed or not.
258 Value *InstCombiner::insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
259 bool isSigned, bool Inside) {
260 assert((isSigned ? Lo.sle(Hi) : Lo.ule(Hi)) &&
261 "Lo is not <= Hi in range emission code!");
263 Type *Ty = V->getType();
265 return Inside ? ConstantInt::getFalse(Ty) : ConstantInt::getTrue(Ty);
267 // V >= Min && V < Hi --> V < Hi
268 // V < Min || V >= Hi --> V >= Hi
269 ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
270 if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) {
271 Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred;
272 return Builder->CreateICmp(Pred, V, ConstantInt::get(Ty, Hi));
275 // V >= Lo && V < Hi --> V - Lo u< Hi - Lo
276 // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo
278 Builder->CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off");
279 Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo);
280 return Builder->CreateICmp(Pred, VMinusLo, HiMinusLo);
283 /// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns
284 /// that can be simplified.
285 /// One of A and B is considered the mask. The other is the value. This is
286 /// described as the "AMask" or "BMask" part of the enum. If the enum contains
287 /// only "Mask", then both A and B can be considered masks. If A is the mask,
288 /// then it was proven that (A & C) == C. This is trivial if C == A or C == 0.
289 /// If both A and C are constants, this proof is also easy.
290 /// For the following explanations, we assume that A is the mask.
292 /// "AllOnes" declares that the comparison is true only if (A & B) == A or all
293 /// bits of A are set in B.
294 /// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes
296 /// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all
297 /// bits of A are cleared in B.
298 /// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes
300 /// "Mixed" declares that (A & B) == C and C might or might not contain any
301 /// number of one bits and zero bits.
302 /// Example: (icmp eq (A & 3), 1) -> AMask_Mixed
304 /// "Not" means that in above descriptions "==" should be replaced by "!=".
305 /// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes
307 /// If the mask A contains a single bit, then the following is equivalent:
308 /// (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
309 /// (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
310 enum MaskedICmpType {
312 AMask_NotAllOnes = 2,
314 BMask_NotAllOnes = 8,
316 Mask_NotAllZeros = 32,
318 AMask_NotMixed = 128,
323 /// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C)
325 static unsigned getMaskedICmpType(Value *A, Value *B, Value *C,
326 ICmpInst::Predicate Pred) {
327 ConstantInt *ACst = dyn_cast<ConstantInt>(A);
328 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
329 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
330 bool IsEq = (Pred == ICmpInst::ICMP_EQ);
331 bool IsAPow2 = (ACst && !ACst->isZero() && ACst->getValue().isPowerOf2());
332 bool IsBPow2 = (BCst && !BCst->isZero() && BCst->getValue().isPowerOf2());
333 unsigned MaskVal = 0;
334 if (CCst && CCst->isZero()) {
335 // if C is zero, then both A and B qualify as mask
336 MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed)
337 : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed));
339 MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed)
340 : (AMask_AllOnes | AMask_Mixed));
342 MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed)
343 : (BMask_AllOnes | BMask_Mixed));
348 MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed)
349 : (AMask_NotAllOnes | AMask_NotMixed));
351 MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed)
352 : (Mask_AllZeros | AMask_Mixed));
353 } else if (ACst && CCst && ConstantExpr::getAnd(ACst, CCst) == CCst) {
354 MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed);
358 MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed)
359 : (BMask_NotAllOnes | BMask_NotMixed));
361 MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed)
362 : (Mask_AllZeros | BMask_Mixed));
363 } else if (BCst && CCst && ConstantExpr::getAnd(BCst, CCst) == CCst) {
364 MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed);
370 /// Convert an analysis of a masked ICmp into its equivalent if all boolean
371 /// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
372 /// is adjacent to the corresponding normal flag (recording ==), this just
373 /// involves swapping those bits over.
374 static unsigned conjugateICmpMask(unsigned Mask) {
376 NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros |
377 AMask_Mixed | BMask_Mixed))
380 NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros |
381 AMask_NotMixed | BMask_NotMixed))
387 /// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E).
388 /// Return the set of pattern classes (from MaskedICmpType) that both LHS and
390 static unsigned getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C,
391 Value *&D, Value *&E, ICmpInst *LHS,
393 ICmpInst::Predicate &PredL,
394 ICmpInst::Predicate &PredR) {
395 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
397 // vectors are not (yet?) supported
398 if (LHS->getOperand(0)->getType()->isVectorTy())
401 // Here comes the tricky part:
402 // LHS might be of the form L11 & L12 == X, X == L21 & L22,
403 // and L11 & L12 == L21 & L22. The same goes for RHS.
404 // Now we must find those components L** and R**, that are equal, so
405 // that we can extract the parameters A, B, C, D, and E for the canonical
407 Value *L1 = LHS->getOperand(0);
408 Value *L2 = LHS->getOperand(1);
409 Value *L11, *L12, *L21, *L22;
410 // Check whether the icmp can be decomposed into a bit test.
411 if (decomposeBitTestICmp(LHS, PredL, L11, L12, L2)) {
412 L21 = L22 = L1 = nullptr;
414 // Look for ANDs in the LHS icmp.
415 if (!L1->getType()->isIntegerTy()) {
416 // You can icmp pointers, for example. They really aren't masks.
418 } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
419 // Any icmp can be viewed as being trivially masked; if it allows us to
420 // remove one, it's worth it.
422 L12 = Constant::getAllOnesValue(L1->getType());
425 if (!L2->getType()->isIntegerTy()) {
426 // You can icmp pointers, for example. They really aren't masks.
428 } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
430 L22 = Constant::getAllOnesValue(L2->getType());
434 // Bail if LHS was a icmp that can't be decomposed into an equality.
435 if (!ICmpInst::isEquality(PredL))
438 Value *R1 = RHS->getOperand(0);
439 Value *R2 = RHS->getOperand(1);
442 if (decomposeBitTestICmp(RHS, PredR, R11, R12, R2)) {
443 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
446 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
455 } else if (R1->getType()->isIntegerTy()) {
456 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
457 // As before, model no mask as a trivial mask if it'll let us do an
460 R12 = Constant::getAllOnesValue(R1->getType());
463 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
468 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
476 // Bail if RHS was a icmp that can't be decomposed into an equality.
477 if (!ICmpInst::isEquality(PredR))
480 // Look for ANDs on the right side of the RHS icmp.
481 if (!Ok && R2->getType()->isIntegerTy()) {
482 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
484 R12 = Constant::getAllOnesValue(R2->getType());
487 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
492 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
507 } else if (L12 == A) {
510 } else if (L21 == A) {
513 } else if (L22 == A) {
518 unsigned LeftType = getMaskedICmpType(A, B, C, PredL);
519 unsigned RightType = getMaskedICmpType(A, D, E, PredR);
520 return LeftType & RightType;
523 /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
524 /// into a single (icmp(A & X) ==/!= Y).
525 static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
526 llvm::InstCombiner::BuilderTy *Builder) {
527 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
528 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
530 getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR);
534 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) &&
535 "Expected equality predicates for masked type of icmps.");
537 // In full generality:
538 // (icmp (A & B) Op C) | (icmp (A & D) Op E)
539 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
541 // If the latter can be converted into (icmp (A & X) Op Y) then the former is
542 // equivalent to (icmp (A & X) !Op Y).
544 // Therefore, we can pretend for the rest of this function that we're dealing
545 // with the conjunction, provided we flip the sense of any comparisons (both
546 // input and output).
548 // In most cases we're going to produce an EQ for the "&&" case.
549 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
551 // Convert the masking analysis into its equivalent with negated
553 Mask = conjugateICmpMask(Mask);
556 if (Mask & Mask_AllZeros) {
557 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
558 // -> (icmp eq (A & (B|D)), 0)
559 Value *NewOr = Builder->CreateOr(B, D);
560 Value *NewAnd = Builder->CreateAnd(A, NewOr);
561 // We can't use C as zero because we might actually handle
562 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
563 // with B and D, having a single bit set.
564 Value *Zero = Constant::getNullValue(A->getType());
565 return Builder->CreateICmp(NewCC, NewAnd, Zero);
567 if (Mask & BMask_AllOnes) {
568 // (icmp eq (A & B), B) & (icmp eq (A & D), D)
569 // -> (icmp eq (A & (B|D)), (B|D))
570 Value *NewOr = Builder->CreateOr(B, D);
571 Value *NewAnd = Builder->CreateAnd(A, NewOr);
572 return Builder->CreateICmp(NewCC, NewAnd, NewOr);
574 if (Mask & AMask_AllOnes) {
575 // (icmp eq (A & B), A) & (icmp eq (A & D), A)
576 // -> (icmp eq (A & (B&D)), A)
577 Value *NewAnd1 = Builder->CreateAnd(B, D);
578 Value *NewAnd2 = Builder->CreateAnd(A, NewAnd1);
579 return Builder->CreateICmp(NewCC, NewAnd2, A);
582 // Remaining cases assume at least that B and D are constant, and depend on
583 // their actual values. This isn't strictly necessary, just a "handle the
584 // easy cases for now" decision.
585 ConstantInt *BCst = dyn_cast<ConstantInt>(B);
588 ConstantInt *DCst = dyn_cast<ConstantInt>(D);
592 if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) {
593 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
594 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
595 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
596 // Only valid if one of the masks is a superset of the other (check "B&D" is
597 // the same as either B or D).
598 APInt NewMask = BCst->getValue() & DCst->getValue();
600 if (NewMask == BCst->getValue())
602 else if (NewMask == DCst->getValue())
606 if (Mask & AMask_NotAllOnes) {
607 // (icmp ne (A & B), B) & (icmp ne (A & D), D)
608 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
609 // Only valid if one of the masks is a superset of the other (check "B|D" is
610 // the same as either B or D).
611 APInt NewMask = BCst->getValue() | DCst->getValue();
613 if (NewMask == BCst->getValue())
615 else if (NewMask == DCst->getValue())
619 if (Mask & BMask_Mixed) {
620 // (icmp eq (A & B), C) & (icmp eq (A & D), E)
621 // We already know that B & C == C && D & E == E.
622 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
623 // C and E, which are shared by both the mask B and the mask D, don't
624 // contradict, then we can transform to
625 // -> (icmp eq (A & (B|D)), (C|E))
626 // Currently, we only handle the case of B, C, D, and E being constant.
627 // We can't simply use C and E because we might actually handle
628 // (icmp ne (A & B), B) & (icmp eq (A & D), D)
629 // with B and D, having a single bit set.
630 ConstantInt *CCst = dyn_cast<ConstantInt>(C);
633 ConstantInt *ECst = dyn_cast<ConstantInt>(E);
637 CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
639 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
641 // If there is a conflict, we should actually return a false for the
643 if (((BCst->getValue() & DCst->getValue()) &
644 (CCst->getValue() ^ ECst->getValue())).getBoolValue())
645 return ConstantInt::get(LHS->getType(), !IsAnd);
647 Value *NewOr1 = Builder->CreateOr(B, D);
648 Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
649 Value *NewAnd = Builder->CreateAnd(A, NewOr1);
650 return Builder->CreateICmp(NewCC, NewAnd, NewOr2);
656 /// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
657 /// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
658 /// If \p Inverted is true then the check is for the inverted range, e.g.
659 /// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
660 Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
662 // Check the lower range comparison, e.g. x >= 0
663 // InstCombine already ensured that if there is a constant it's on the RHS.
664 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
668 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
669 Cmp0->getPredicate());
671 // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
672 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
673 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
676 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
677 Cmp1->getPredicate());
679 Value *Input = Cmp0->getOperand(0);
681 if (Cmp1->getOperand(0) == Input) {
682 // For the upper range compare we have: icmp x, n
683 RangeEnd = Cmp1->getOperand(1);
684 } else if (Cmp1->getOperand(1) == Input) {
685 // For the upper range compare we have: icmp n, x
686 RangeEnd = Cmp1->getOperand(0);
687 Pred1 = ICmpInst::getSwappedPredicate(Pred1);
692 // Check the upper range comparison, e.g. x < n
693 ICmpInst::Predicate NewPred;
695 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
696 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
697 default: return nullptr;
700 // This simplification is only valid if the upper range is not negative.
701 KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1);
702 if (!Known.isNonNegative())
706 NewPred = ICmpInst::getInversePredicate(NewPred);
708 return Builder->CreateICmp(NewPred, Input, RangeEnd);
712 foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS,
714 InstCombiner::BuilderTy *Builder) {
715 Value *X = LHS->getOperand(0);
716 if (X != RHS->getOperand(0))
719 const APInt *C1, *C2;
720 if (!match(LHS->getOperand(1), m_APInt(C1)) ||
721 !match(RHS->getOperand(1), m_APInt(C2)))
724 // We only handle (X != C1 && X != C2) and (X == C1 || X == C2).
725 ICmpInst::Predicate Pred = LHS->getPredicate();
726 if (Pred != RHS->getPredicate())
728 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
730 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
733 // The larger unsigned constant goes on the right.
737 APInt Xor = *C1 ^ *C2;
738 if (Xor.isPowerOf2()) {
739 // If LHSC and RHSC differ by only one bit, then set that bit in X and
740 // compare against the larger constant:
741 // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2
742 // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2
743 // We choose an 'or' with a Pow2 constant rather than the inverse mask with
744 // 'and' because that may lead to smaller codegen from a smaller constant.
745 Value *Or = Builder->CreateOr(X, ConstantInt::get(X->getType(), Xor));
746 return Builder->CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2));
749 // Special case: get the ordering right when the values wrap around zero.
750 // Ie, we assumed the constants were unsigned when swapping earlier.
751 if (C1->isNullValue() && C2->isAllOnesValue())
754 if (*C1 == *C2 - 1) {
755 // (X == 13 || X == 14) --> X - 13 <=u 1
756 // (X != 13 && X != 14) --> X - 13 >u 1
757 // An 'add' is the canonical IR form, so favor that over a 'sub'.
758 Value *Add = Builder->CreateAdd(X, ConstantInt::get(X->getType(), -(*C1)));
759 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_ULE;
760 return Builder->CreateICmp(NewPred, Add, ConstantInt::get(X->getType(), 1));
766 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
767 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
768 Value *InstCombiner::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS,
771 ICmpInst::Predicate Pred = LHS->getPredicate();
772 if (Pred != RHS->getPredicate())
774 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE)
776 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ)
779 // TODO support vector splats
780 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
781 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
782 if (!LHSC || !RHSC || !LHSC->isZero() || !RHSC->isZero())
785 Value *A, *B, *C, *D;
786 if (match(LHS->getOperand(0), m_And(m_Value(A), m_Value(B))) &&
787 match(RHS->getOperand(0), m_And(m_Value(C), m_Value(D)))) {
788 if (A == D || B == D)
794 isKnownToBeAPowerOfTwo(B, false, 0, &CxtI) &&
795 isKnownToBeAPowerOfTwo(D, false, 0, &CxtI)) {
796 Value *Mask = Builder->CreateOr(B, D);
797 Value *Masked = Builder->CreateAnd(A, Mask);
798 auto NewPred = JoinedByAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
799 return Builder->CreateICmp(NewPred, Masked, Mask);
806 /// Fold (icmp)&(icmp) if possible.
807 Value *InstCombiner::foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS,
809 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2)
810 // if K1 and K2 are a one-bit mask.
811 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, true, CxtI))
814 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
816 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
817 if (PredicatesFoldable(PredL, PredR)) {
818 if (LHS->getOperand(0) == RHS->getOperand(1) &&
819 LHS->getOperand(1) == RHS->getOperand(0))
821 if (LHS->getOperand(0) == RHS->getOperand(0) &&
822 LHS->getOperand(1) == RHS->getOperand(1)) {
823 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
824 unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
825 bool isSigned = LHS->isSigned() || RHS->isSigned();
826 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
830 // handle (roughly): (icmp eq (A & B), C) & (icmp eq (A & D), E)
831 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
834 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
835 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
838 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
839 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
842 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, true, Builder))
845 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
846 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
847 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
848 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
852 if (LHSC == RHSC && PredL == PredR) {
853 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
854 // where C is a power of 2 or
855 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
856 if ((PredL == ICmpInst::ICMP_ULT && LHSC->getValue().isPowerOf2()) ||
857 (PredL == ICmpInst::ICMP_EQ && LHSC->isZero())) {
858 Value *NewOr = Builder->CreateOr(LHS0, RHS0);
859 return Builder->CreateICmp(PredL, NewOr, LHSC);
863 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
864 // where CMAX is the all ones value for the truncated type,
865 // iff the lower bits of C2 and CA are zero.
866 if (PredL == ICmpInst::ICMP_EQ && PredL == PredR && LHS->hasOneUse() &&
869 ConstantInt *AndC, *SmallC = nullptr, *BigC = nullptr;
871 // (trunc x) == C1 & (and x, CA) == C2
872 // (and x, CA) == C2 & (trunc x) == C1
873 if (match(RHS0, m_Trunc(m_Value(V))) &&
874 match(LHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
877 } else if (match(LHS0, m_Trunc(m_Value(V))) &&
878 match(RHS0, m_And(m_Specific(V), m_ConstantInt(AndC)))) {
883 if (SmallC && BigC) {
884 unsigned BigBitSize = BigC->getType()->getBitWidth();
885 unsigned SmallBitSize = SmallC->getType()->getBitWidth();
887 // Check that the low bits are zero.
888 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
889 if ((Low & AndC->getValue()).isNullValue() &&
890 (Low & BigC->getValue()).isNullValue()) {
891 Value *NewAnd = Builder->CreateAnd(V, Low | AndC->getValue());
892 APInt N = SmallC->getValue().zext(BigBitSize) | BigC->getValue();
893 Value *NewVal = ConstantInt::get(AndC->getType()->getContext(), N);
894 return Builder->CreateICmp(PredL, NewAnd, NewVal);
899 // From here on, we only handle:
900 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
904 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
905 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
906 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
907 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
908 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
911 // We can't fold (ugt x, C) & (sgt x, C2).
912 if (!PredicatesFoldable(PredL, PredR))
915 // Ensure that the larger constant is on the RHS.
917 if (CmpInst::isSigned(PredL) ||
918 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
919 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
921 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
925 std::swap(LHSC, RHSC);
926 std::swap(PredL, PredR);
929 // At this point, we know we have two icmp instructions
930 // comparing a value against two constants and and'ing the result
931 // together. Because of the above check, we know that we only have
932 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
933 // (from the icmp folding check above), that the two constants
934 // are not equal and that the larger constant is on the RHS
935 assert(LHSC != RHSC && "Compares not folded above?");
939 llvm_unreachable("Unknown integer condition code!");
940 case ICmpInst::ICMP_NE:
943 llvm_unreachable("Unknown integer condition code!");
944 case ICmpInst::ICMP_ULT:
945 if (LHSC == SubOne(RHSC)) // (X != 13 & X u< 14) -> X < 13
946 return Builder->CreateICmpULT(LHS0, LHSC);
947 if (LHSC->isNullValue()) // (X != 0 & X u< 14) -> X-1 u< 13
948 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
950 break; // (X != 13 & X u< 15) -> no change
951 case ICmpInst::ICMP_SLT:
952 if (LHSC == SubOne(RHSC)) // (X != 13 & X s< 14) -> X < 13
953 return Builder->CreateICmpSLT(LHS0, LHSC);
954 break; // (X != 13 & X s< 15) -> no change
955 case ICmpInst::ICMP_NE:
956 // Potential folds for this case should already be handled.
960 case ICmpInst::ICMP_UGT:
963 llvm_unreachable("Unknown integer condition code!");
964 case ICmpInst::ICMP_NE:
965 if (RHSC == AddOne(LHSC)) // (X u> 13 & X != 14) -> X u> 14
966 return Builder->CreateICmp(PredL, LHS0, RHSC);
967 break; // (X u> 13 & X != 15) -> no change
968 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
969 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(),
973 case ICmpInst::ICMP_SGT:
976 llvm_unreachable("Unknown integer condition code!");
977 case ICmpInst::ICMP_NE:
978 if (RHSC == AddOne(LHSC)) // (X s> 13 & X != 14) -> X s> 14
979 return Builder->CreateICmp(PredL, LHS0, RHSC);
980 break; // (X s> 13 & X != 15) -> no change
981 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
982 return insertRangeTest(LHS0, LHSC->getValue() + 1, RHSC->getValue(), true,
991 /// Optimize (fcmp)&(fcmp). NOTE: Unlike the rest of instcombine, this returns
992 /// a Value which should already be inserted into the function.
993 Value *InstCombiner::foldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
994 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
995 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
996 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
998 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
999 // Swap RHS operands to match LHS.
1000 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1001 std::swap(Op1LHS, Op1RHS);
1004 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1005 // Suppose the relation between x and y is R, where R is one of
1006 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
1007 // testing the desired relations.
1009 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1010 // bool(R & CC0) && bool(R & CC1)
1011 // = bool((R & CC0) & (R & CC1))
1012 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
1013 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1014 return getFCmpValue(getFCmpCode(Op0CC) & getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1017 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1018 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
1019 if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
1022 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
1023 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1024 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1025 // If either of the constants are nans, then the whole thing returns
1027 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1028 return Builder->getFalse();
1029 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
1032 // Handle vector zeros. This occurs because the canonical form of
1033 // "fcmp ord x,x" is "fcmp ord x, 0".
1034 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1035 isa<ConstantAggregateZero>(RHS->getOperand(1)))
1036 return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
1043 /// Match De Morgan's Laws:
1044 /// (~A & ~B) == (~(A | B))
1045 /// (~A | ~B) == (~(A & B))
1046 static Instruction *matchDeMorgansLaws(BinaryOperator &I,
1047 InstCombiner::BuilderTy &Builder) {
1048 auto Opcode = I.getOpcode();
1049 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1050 "Trying to match De Morgan's Laws with something other than and/or");
1052 // Flip the logic operation.
1053 Opcode = (Opcode == Instruction::And) ? Instruction::Or : Instruction::And;
1056 if (match(I.getOperand(0), m_OneUse(m_Not(m_Value(A)))) &&
1057 match(I.getOperand(1), m_OneUse(m_Not(m_Value(B)))) &&
1058 !IsFreeToInvert(A, A->hasOneUse()) &&
1059 !IsFreeToInvert(B, B->hasOneUse())) {
1060 Value *AndOr = Builder.CreateBinOp(Opcode, A, B, I.getName() + ".demorgan");
1061 return BinaryOperator::CreateNot(AndOr);
1067 bool InstCombiner::shouldOptimizeCast(CastInst *CI) {
1068 Value *CastSrc = CI->getOperand(0);
1070 // Noop casts and casts of constants should be eliminated trivially.
1071 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc))
1074 // If this cast is paired with another cast that can be eliminated, we prefer
1075 // to have it eliminated.
1076 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc))
1077 if (isEliminableCastPair(PrecedingCI, CI))
1080 // If this is a vector sext from a compare, then we don't want to break the
1081 // idiom where each element of the extended vector is either zero or all ones.
1082 if (CI->getOpcode() == Instruction::SExt &&
1083 isa<CmpInst>(CastSrc) && CI->getDestTy()->isVectorTy())
1089 /// Fold {and,or,xor} (cast X), C.
1090 static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast,
1091 InstCombiner::BuilderTy *Builder) {
1093 if (!match(Logic.getOperand(1), m_Constant(C)))
1096 auto LogicOpc = Logic.getOpcode();
1097 Type *DestTy = Logic.getType();
1098 Type *SrcTy = Cast->getSrcTy();
1100 // Move the logic operation ahead of a zext if the constant is unchanged in
1101 // the smaller source type. Performing the logic in a smaller type may provide
1102 // more information to later folds, and the smaller logic instruction may be
1103 // cheaper (particularly in the case of vectors).
1105 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) {
1106 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy);
1107 Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy);
1108 if (ZextTruncC == C) {
1109 // LogicOpc (zext X), C --> zext (LogicOpc X, C)
1110 Value *NewOp = Builder->CreateBinOp(LogicOpc, X, TruncC);
1111 return new ZExtInst(NewOp, DestTy);
1118 /// Fold {and,or,xor} (cast X), Y.
1119 Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
1120 auto LogicOpc = I.getOpcode();
1121 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding");
1123 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1124 CastInst *Cast0 = dyn_cast<CastInst>(Op0);
1128 // This must be a cast from an integer or integer vector source type to allow
1129 // transformation of the logic operation to the source type.
1130 Type *DestTy = I.getType();
1131 Type *SrcTy = Cast0->getSrcTy();
1132 if (!SrcTy->isIntOrIntVectorTy())
1135 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder))
1138 CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1142 // Both operands of the logic operation are casts. The casts must be of the
1143 // same type for reduction.
1144 auto CastOpcode = Cast0->getOpcode();
1145 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
1148 Value *Cast0Src = Cast0->getOperand(0);
1149 Value *Cast1Src = Cast1->getOperand(0);
1151 // fold logic(cast(A), cast(B)) -> cast(logic(A, B))
1152 if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) {
1153 Value *NewOp = Builder->CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1155 return CastInst::Create(CastOpcode, NewOp, DestTy);
1158 // For now, only 'and'/'or' have optimizations after this.
1159 if (LogicOpc == Instruction::Xor)
1162 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
1163 // cast is otherwise not optimizable. This happens for vector sexts.
1164 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1165 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1166 if (ICmp0 && ICmp1) {
1167 Value *Res = LogicOpc == Instruction::And ? foldAndOfICmps(ICmp0, ICmp1, I)
1168 : foldOrOfICmps(ICmp0, ICmp1, I);
1170 return CastInst::Create(CastOpcode, Res, DestTy);
1174 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
1175 // cast is otherwise not optimizable. This happens for vector sexts.
1176 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1177 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1178 if (FCmp0 && FCmp1) {
1179 Value *Res = LogicOpc == Instruction::And ? foldAndOfFCmps(FCmp0, FCmp1)
1180 : foldOrOfFCmps(FCmp0, FCmp1);
1182 return CastInst::Create(CastOpcode, Res, DestTy);
1189 static Instruction *foldBoolSextMaskToSelect(BinaryOperator &I) {
1190 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1192 // Canonicalize SExt or Not to the LHS
1193 if (match(Op1, m_SExt(m_Value())) || match(Op1, m_Not(m_Value()))) {
1194 std::swap(Op0, Op1);
1197 // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1199 if (match(Op0, m_SExt(m_Value(X))) &&
1200 X->getType()->getScalarType()->isIntegerTy(1)) {
1201 Value *Zero = Constant::getNullValue(Op1->getType());
1202 return SelectInst::Create(X, Op1, Zero);
1205 // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1206 if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1207 X->getType()->getScalarType()->isIntegerTy(1)) {
1208 Value *Zero = Constant::getNullValue(Op0->getType());
1209 return SelectInst::Create(X, Zero, Op1);
1215 static Instruction *foldAndToXor(BinaryOperator &I,
1216 InstCombiner::BuilderTy &Builder) {
1217 assert(I.getOpcode() == Instruction::And);
1218 Value *Op0 = I.getOperand(0);
1219 Value *Op1 = I.getOperand(1);
1222 // Operand complexity canonicalization guarantees that the 'or' is Op0.
1223 // (A | B) & ~(A & B) --> A ^ B
1224 // (A | B) & ~(B & A) --> A ^ B
1225 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1226 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B)))))
1227 return BinaryOperator::CreateXor(A, B);
1229 // (A | ~B) & (~A | B) --> ~(A ^ B)
1230 // (A | ~B) & (B | ~A) --> ~(A ^ B)
1231 // (~B | A) & (~A | B) --> ~(A ^ B)
1232 // (~B | A) & (B | ~A) --> ~(A ^ B)
1233 if (Op0->hasOneUse() || Op1->hasOneUse())
1234 if (match(Op0, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
1235 match(Op1, m_c_Or(m_Not(m_Specific(A)), m_Specific(B))))
1236 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
1241 static Instruction *foldOrToXor(BinaryOperator &I,
1242 InstCombiner::BuilderTy &Builder) {
1243 assert(I.getOpcode() == Instruction::Or);
1244 Value *Op0 = I.getOperand(0);
1245 Value *Op1 = I.getOperand(1);
1248 // Operand complexity canonicalization guarantees that the 'and' is Op0.
1249 // (A & B) | ~(A | B) --> ~(A ^ B)
1250 // (A & B) | ~(B | A) --> ~(A ^ B)
1251 if (Op0->hasOneUse() || Op1->hasOneUse())
1252 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1253 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
1254 return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
1256 // (A & ~B) | (~A & B) --> A ^ B
1257 // (A & ~B) | (B & ~A) --> A ^ B
1258 // (~B & A) | (~A & B) --> A ^ B
1259 // (~B & A) | (B & ~A) --> A ^ B
1260 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
1261 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))
1262 return BinaryOperator::CreateXor(A, B);
1267 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1268 // here. We should standardize that construct where it is needed or choose some
1269 // other way to ensure that commutated variants of patterns are not missed.
1270 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1271 bool Changed = SimplifyAssociativeOrCommutative(I);
1272 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1274 if (Value *V = SimplifyVectorOp(I))
1275 return replaceInstUsesWith(I, V);
1277 if (Value *V = SimplifyAndInst(Op0, Op1, SQ.getWithInstruction(&I)))
1278 return replaceInstUsesWith(I, V);
1280 // See if we can simplify any instructions used by the instruction whose sole
1281 // purpose is to compute bits we don't care about.
1282 if (SimplifyDemandedInstructionBits(I))
1285 // Do this before using distributive laws to catch simple and/or/not patterns.
1286 if (Instruction *Xor = foldAndToXor(I, *Builder))
1289 // (A|B)&(A|C) -> A|(B&C) etc
1290 if (Value *V = SimplifyUsingDistributiveLaws(I))
1291 return replaceInstUsesWith(I, V);
1293 if (Value *V = SimplifyBSwap(I))
1294 return replaceInstUsesWith(I, V);
1296 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1297 const APInt &AndRHSMask = AndRHS->getValue();
1299 // Optimize a variety of ((val OP C1) & C2) combinations...
1300 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1301 Value *Op0LHS = Op0I->getOperand(0);
1302 Value *Op0RHS = Op0I->getOperand(1);
1303 switch (Op0I->getOpcode()) {
1305 case Instruction::Xor:
1306 case Instruction::Or: {
1307 // If the mask is only needed on one incoming arm, push it up.
1308 if (!Op0I->hasOneUse()) break;
1310 APInt NotAndRHS(~AndRHSMask);
1311 if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
1312 // Not masking anything out for the LHS, move to RHS.
1313 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1314 Op0RHS->getName()+".masked");
1315 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1317 if (!isa<Constant>(Op0RHS) &&
1318 MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
1319 // Not masking anything out for the RHS, move to LHS.
1320 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1321 Op0LHS->getName()+".masked");
1322 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1327 case Instruction::Sub:
1329 if (AndRHSMask.isOneValue() && match(Op0LHS, m_Zero()))
1330 return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1334 case Instruction::Shl:
1335 case Instruction::LShr:
1336 // (1 << x) & 1 --> zext(x == 0)
1337 // (1 >> x) & 1 --> zext(x == 0)
1338 if (AndRHSMask.isOneValue() && Op0LHS == AndRHS) {
1340 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1341 return new ZExtInst(NewICmp, I.getType());
1346 // ((C1 OP zext(X)) & C2) -> zext((C1-X) & C2) if C2 fits in the bitwidth
1347 // of X and OP behaves well when given trunc(C1) and X.
1348 switch (Op0I->getOpcode()) {
1351 case Instruction::Xor:
1352 case Instruction::Or:
1353 case Instruction::Mul:
1354 case Instruction::Add:
1355 case Instruction::Sub:
1358 if (match(Op0I, m_c_BinOp(m_ZExt(m_Value(X)), m_ConstantInt(C1)))) {
1359 if (AndRHSMask.isIntN(X->getType()->getScalarSizeInBits())) {
1360 auto *TruncC1 = ConstantExpr::getTrunc(C1, X->getType());
1362 if (isa<ZExtInst>(Op0LHS))
1363 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), X, TruncC1);
1365 BinOp = Builder->CreateBinOp(Op0I->getOpcode(), TruncC1, X);
1366 auto *TruncC2 = ConstantExpr::getTrunc(AndRHS, X->getType());
1367 auto *And = Builder->CreateAnd(BinOp, TruncC2);
1368 return new ZExtInst(And, I.getType());
1373 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1374 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1378 // If this is an integer truncation, and if the source is an 'and' with
1379 // immediate, transform it. This frequently occurs for bitfield accesses.
1381 Value *X = nullptr; ConstantInt *YC = nullptr;
1382 if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1383 // Change: and (trunc (and X, YC) to T), C2
1384 // into : and (trunc X to T), trunc(YC) & C2
1385 // This will fold the two constants together, which may allow
1386 // other simplifications.
1387 Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1388 Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1389 C3 = ConstantExpr::getAnd(C3, AndRHS);
1390 return BinaryOperator::CreateAnd(NewCast, C3);
1395 if (isa<Constant>(Op1))
1396 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
1399 if (Instruction *DeMorgan = matchDeMorgansLaws(I, *Builder))
1403 Value *A = nullptr, *B = nullptr, *C = nullptr;
1404 // A&(A^B) => A & ~B
1406 Value *tmpOp0 = Op0;
1407 Value *tmpOp1 = Op1;
1408 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
1409 if (A == Op1 || B == Op1 ) {
1416 if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
1420 // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
1421 // A is originally -1 (or a vector of -1 and undefs), then we enter
1422 // an endless loop. By checking that A is non-constant we ensure that
1423 // we will never get to the loop.
1424 if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
1425 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
1429 // (A&((~A)|B)) -> A&B
1430 if (match(Op0, m_c_Or(m_Not(m_Specific(Op1)), m_Value(A))))
1431 return BinaryOperator::CreateAnd(A, Op1);
1432 if (match(Op1, m_c_Or(m_Not(m_Specific(Op0)), m_Value(A))))
1433 return BinaryOperator::CreateAnd(A, Op0);
1435 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1436 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1437 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1438 if (Op1->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
1439 return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1441 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1442 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1443 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1444 if (Op0->hasOneUse() || IsFreeToInvert(C, C->hasOneUse()))
1445 return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
1447 // (A | B) & ((~A) ^ B) -> (A & B)
1448 // (A | B) & (B ^ (~A)) -> (A & B)
1449 // (B | A) & ((~A) ^ B) -> (A & B)
1450 // (B | A) & (B ^ (~A)) -> (A & B)
1451 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1452 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
1453 return BinaryOperator::CreateAnd(A, B);
1455 // ((~A) ^ B) & (A | B) -> (A & B)
1456 // ((~A) ^ B) & (B | A) -> (A & B)
1457 // (B ^ (~A)) & (A | B) -> (A & B)
1458 // (B ^ (~A)) & (B | A) -> (A & B)
1459 if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1460 match(Op1, m_c_Or(m_Specific(A), m_Specific(B))))
1461 return BinaryOperator::CreateAnd(A, B);
1465 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1466 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1468 if (Value *Res = foldAndOfICmps(LHS, RHS, I))
1469 return replaceInstUsesWith(I, Res);
1471 // TODO: Make this recursive; it's a little tricky because an arbitrary
1472 // number of 'and' instructions might have to be created.
1474 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1475 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1476 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
1477 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1478 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1479 if (Value *Res = foldAndOfICmps(LHS, Cmp, I))
1480 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1482 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1483 if (auto *Cmp = dyn_cast<ICmpInst>(X))
1484 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
1485 return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1486 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1487 if (Value *Res = foldAndOfICmps(Cmp, RHS, I))
1488 return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1492 // If and'ing two fcmp, try combine them into one.
1493 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1494 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1495 if (Value *Res = foldAndOfFCmps(LHS, RHS))
1496 return replaceInstUsesWith(I, Res);
1498 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1501 if (Instruction *Select = foldBoolSextMaskToSelect(I))
1504 return Changed ? &I : nullptr;
1507 /// Given an OR instruction, check to see if this is a bswap idiom. If so,
1508 /// insert the new intrinsic and return it.
1509 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1510 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1512 // Look through zero extends.
1513 if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1514 Op0 = Ext->getOperand(0);
1516 if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1517 Op1 = Ext->getOperand(0);
1519 // (A | B) | C and A | (B | C) -> bswap if possible.
1520 bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1521 match(Op1, m_Or(m_Value(), m_Value()));
1523 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
1524 bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1525 match(Op1, m_LogicalShift(m_Value(), m_Value()));
1527 // (A & B) | (C & D) -> bswap if possible.
1528 bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1529 match(Op1, m_And(m_Value(), m_Value()));
1531 if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1534 SmallVector<Instruction*, 4> Insts;
1535 if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
1537 Instruction *LastInst = Insts.pop_back_val();
1538 LastInst->removeFromParent();
1540 for (auto *Inst : Insts)
1545 /// If all elements of two constant vectors are 0/-1 and inverses, return true.
1546 static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
1547 unsigned NumElts = C1->getType()->getVectorNumElements();
1548 for (unsigned i = 0; i != NumElts; ++i) {
1549 Constant *EltC1 = C1->getAggregateElement(i);
1550 Constant *EltC2 = C2->getAggregateElement(i);
1551 if (!EltC1 || !EltC2)
1554 // One element must be all ones, and the other must be all zeros.
1555 // FIXME: Allow undef elements.
1556 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1557 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1563 /// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1564 /// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1565 /// B, it can be used as the condition operand of a select instruction.
1566 static Value *getSelectCondition(Value *A, Value *B,
1567 InstCombiner::BuilderTy &Builder) {
1568 // If these are scalars or vectors of i1, A can be used directly.
1569 Type *Ty = A->getType();
1570 if (match(A, m_Not(m_Specific(B))) && Ty->getScalarType()->isIntegerTy(1))
1573 // If A and B are sign-extended, look through the sexts to find the booleans.
1576 if (match(A, m_SExt(m_Value(Cond))) &&
1577 Cond->getType()->getScalarType()->isIntegerTy(1) &&
1578 match(B, m_OneUse(m_Not(m_Value(NotB))))) {
1579 NotB = peekThroughBitcast(NotB, true);
1580 if (match(NotB, m_SExt(m_Specific(Cond))))
1584 // All scalar (and most vector) possibilities should be handled now.
1585 // Try more matches that only apply to non-splat constant vectors.
1586 if (!Ty->isVectorTy())
1589 // If both operands are constants, see if the constants are inverse bitmasks.
1591 if (match(A, m_Constant(AC)) && match(B, m_Constant(BC)) &&
1592 areInverseVectorBitmasks(AC, BC))
1593 return ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1595 // If both operands are xor'd with constants using the same sexted boolean
1596 // operand, see if the constants are inverse bitmasks.
1597 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AC)))) &&
1598 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BC)))) &&
1599 Cond->getType()->getScalarType()->isIntegerTy(1) &&
1600 areInverseVectorBitmasks(AC, BC)) {
1601 AC = ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1602 return Builder.CreateXor(Cond, AC);
1607 /// We have an expression of the form (A & C) | (B & D). Try to simplify this
1608 /// to "A' ? C : D", where A' is a boolean or vector of booleans.
1609 static Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D,
1610 InstCombiner::BuilderTy &Builder) {
1611 // The potential condition of the select may be bitcasted. In that case, look
1612 // through its bitcast and the corresponding bitcast of the 'not' condition.
1613 Type *OrigType = A->getType();
1614 A = peekThroughBitcast(A, true);
1615 B = peekThroughBitcast(B, true);
1617 if (Value *Cond = getSelectCondition(A, B, Builder)) {
1618 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
1619 // The bitcasts will either all exist or all not exist. The builder will
1620 // not create unnecessary casts if the types already match.
1621 Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1622 Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1623 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1624 return Builder.CreateBitCast(Select, OrigType);
1630 /// Fold (icmp)|(icmp) if possible.
1631 Value *InstCombiner::foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1632 Instruction &CxtI) {
1633 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2)
1634 // if K1 and K2 are a one-bit mask.
1635 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, false, CxtI))
1638 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1640 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS->getOperand(1));
1641 ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS->getOperand(1));
1643 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1644 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1645 // The original condition actually refers to the following two ranges:
1646 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1647 // We can fold these two ranges if:
1648 // 1) C1 and C2 is unsigned greater than C3.
1649 // 2) The two ranges are separated.
1650 // 3) C1 ^ C2 is one-bit mask.
1651 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1652 // This implies all values in the two ranges differ by exactly one bit.
1654 if ((PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) &&
1655 PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() &&
1656 LHSC->getType() == RHSC->getType() &&
1657 LHSC->getValue() == (RHSC->getValue())) {
1659 Value *LAdd = LHS->getOperand(0);
1660 Value *RAdd = RHS->getOperand(0);
1662 Value *LAddOpnd, *RAddOpnd;
1663 ConstantInt *LAddC, *RAddC;
1664 if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddC))) &&
1665 match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddC))) &&
1666 LAddC->getValue().ugt(LHSC->getValue()) &&
1667 RAddC->getValue().ugt(LHSC->getValue())) {
1669 APInt DiffC = LAddC->getValue() ^ RAddC->getValue();
1670 if (LAddOpnd == RAddOpnd && DiffC.isPowerOf2()) {
1671 ConstantInt *MaxAddC = nullptr;
1672 if (LAddC->getValue().ult(RAddC->getValue()))
1677 APInt RRangeLow = -RAddC->getValue();
1678 APInt RRangeHigh = RRangeLow + LHSC->getValue();
1679 APInt LRangeLow = -LAddC->getValue();
1680 APInt LRangeHigh = LRangeLow + LHSC->getValue();
1681 APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1682 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1683 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1684 : RRangeLow - LRangeLow;
1686 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
1687 RangeDiff.ugt(LHSC->getValue())) {
1688 Value *MaskC = ConstantInt::get(LAddC->getType(), ~DiffC);
1690 Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskC);
1691 Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddC);
1692 return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSC));
1698 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1699 if (PredicatesFoldable(PredL, PredR)) {
1700 if (LHS->getOperand(0) == RHS->getOperand(1) &&
1701 LHS->getOperand(1) == RHS->getOperand(0))
1702 LHS->swapOperands();
1703 if (LHS->getOperand(0) == RHS->getOperand(0) &&
1704 LHS->getOperand(1) == RHS->getOperand(1)) {
1705 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1706 unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1707 bool isSigned = LHS->isSigned() || RHS->isSigned();
1708 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
1712 // handle (roughly):
1713 // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1714 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
1717 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0);
1718 if (LHS->hasOneUse() || RHS->hasOneUse()) {
1719 // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1720 // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
1721 Value *A = nullptr, *B = nullptr;
1722 if (PredL == ICmpInst::ICMP_EQ && LHSC && LHSC->isZero()) {
1724 if (PredR == ICmpInst::ICMP_ULT && LHS0 == RHS->getOperand(1))
1726 else if (PredR == ICmpInst::ICMP_UGT && LHS0 == RHS0)
1727 A = RHS->getOperand(1);
1729 // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1730 // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1731 else if (PredR == ICmpInst::ICMP_EQ && RHSC && RHSC->isZero()) {
1733 if (PredL == ICmpInst::ICMP_ULT && RHS0 == LHS->getOperand(1))
1735 else if (PredL == ICmpInst::ICMP_UGT && LHS0 == RHS0)
1736 A = LHS->getOperand(1);
1739 return Builder->CreateICmp(
1741 Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1744 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1745 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1748 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1749 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1752 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, false, Builder))
1755 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1759 if (LHSC == RHSC && PredL == PredR) {
1760 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1761 if (PredL == ICmpInst::ICMP_NE && LHSC->isZero()) {
1762 Value *NewOr = Builder->CreateOr(LHS0, RHS0);
1763 return Builder->CreateICmp(PredL, NewOr, LHSC);
1767 // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
1768 // iff C2 + CA == C1.
1769 if (PredL == ICmpInst::ICMP_ULT && PredR == ICmpInst::ICMP_EQ) {
1771 if (match(LHS0, m_Add(m_Specific(RHS0), m_ConstantInt(AddC))))
1772 if (RHSC->getValue() + AddC->getValue() == LHSC->getValue())
1773 return Builder->CreateICmpULE(LHS0, LHSC);
1776 // From here on, we only handle:
1777 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1781 // ICMP_[US][GL]E X, C is folded to ICMP_[US][GL]T elsewhere.
1782 if (PredL == ICmpInst::ICMP_UGE || PredL == ICmpInst::ICMP_ULE ||
1783 PredR == ICmpInst::ICMP_UGE || PredR == ICmpInst::ICMP_ULE ||
1784 PredL == ICmpInst::ICMP_SGE || PredL == ICmpInst::ICMP_SLE ||
1785 PredR == ICmpInst::ICMP_SGE || PredR == ICmpInst::ICMP_SLE)
1788 // We can't fold (ugt x, C) | (sgt x, C2).
1789 if (!PredicatesFoldable(PredL, PredR))
1792 // Ensure that the larger constant is on the RHS.
1794 if (CmpInst::isSigned(PredL) ||
1795 (ICmpInst::isEquality(PredL) && CmpInst::isSigned(PredR)))
1796 ShouldSwap = LHSC->getValue().sgt(RHSC->getValue());
1798 ShouldSwap = LHSC->getValue().ugt(RHSC->getValue());
1801 std::swap(LHS, RHS);
1802 std::swap(LHSC, RHSC);
1803 std::swap(PredL, PredR);
1806 // At this point, we know we have two icmp instructions
1807 // comparing a value against two constants and or'ing the result
1808 // together. Because of the above check, we know that we only have
1809 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1810 // icmp folding check above), that the two constants are not
1812 assert(LHSC != RHSC && "Compares not folded above?");
1816 llvm_unreachable("Unknown integer condition code!");
1817 case ICmpInst::ICMP_EQ:
1820 llvm_unreachable("Unknown integer condition code!");
1821 case ICmpInst::ICMP_EQ:
1822 // Potential folds for this case should already be handled.
1824 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
1825 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
1829 case ICmpInst::ICMP_ULT:
1832 llvm_unreachable("Unknown integer condition code!");
1833 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
1835 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
1836 assert(!RHSC->isMaxValue(false) && "Missed icmp simplification");
1837 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1,
1841 case ICmpInst::ICMP_SLT:
1844 llvm_unreachable("Unknown integer condition code!");
1845 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
1847 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
1848 assert(!RHSC->isMaxValue(true) && "Missed icmp simplification");
1849 return insertRangeTest(LHS0, LHSC->getValue(), RHSC->getValue() + 1, true,
1857 /// Optimize (fcmp)|(fcmp). NOTE: Unlike the rest of instcombine, this returns
1858 /// a Value which should already be inserted into the function.
1859 Value *InstCombiner::foldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
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);
1870 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
1871 // This is a similar transformation to the one in FoldAndOfFCmps.
1873 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1874 // bool(R & CC0) || bool(R & CC1)
1875 // = bool((R & CC0) | (R & CC1))
1876 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
1877 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1878 return getFCmpValue(getFCmpCode(Op0CC) | getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1881 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
1882 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
1883 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
1884 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1885 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1886 // If either of the constants are nans, then the whole thing returns
1888 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1889 return Builder->getTrue();
1891 // Otherwise, no need to compare the two constants, compare the
1893 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1896 // Handle vector zeros. This occurs because the canonical form of
1897 // "fcmp uno x,x" is "fcmp uno x, 0".
1898 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1899 isa<ConstantAggregateZero>(RHS->getOperand(1)))
1900 return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
1908 /// This helper function folds:
1910 /// ((A | B) & C1) | (B & C2)
1916 /// when the XOR of the two constants is "all ones" (-1).
1917 static Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
1918 Value *A, Value *B, Value *C,
1919 InstCombiner::BuilderTy *Builder) {
1920 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1921 if (!CI1) return nullptr;
1923 Value *V1 = nullptr;
1924 ConstantInt *CI2 = nullptr;
1925 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
1927 APInt Xor = CI1->getValue() ^ CI2->getValue();
1928 if (!Xor.isAllOnesValue()) return nullptr;
1930 if (V1 == A || V1 == B) {
1931 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
1932 return BinaryOperator::CreateOr(NewOp, V1);
1938 /// \brief This helper function folds:
1940 /// ((A ^ B) & C1) | (B & C2)
1946 /// when the XOR of the two constants is "all ones" (-1).
1947 static Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op,
1948 Value *A, Value *B, Value *C,
1949 InstCombiner::BuilderTy *Builder) {
1950 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
1954 Value *V1 = nullptr;
1955 ConstantInt *CI2 = nullptr;
1956 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
1959 APInt Xor = CI1->getValue() ^ CI2->getValue();
1960 if (!Xor.isAllOnesValue())
1963 if (V1 == A || V1 == B) {
1964 Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
1965 return BinaryOperator::CreateXor(NewOp, V1);
1971 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
1972 // here. We should standardize that construct where it is needed or choose some
1973 // other way to ensure that commutated variants of patterns are not missed.
1974 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1975 bool Changed = SimplifyAssociativeOrCommutative(I);
1976 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1978 if (Value *V = SimplifyVectorOp(I))
1979 return replaceInstUsesWith(I, V);
1981 if (Value *V = SimplifyOrInst(Op0, Op1, SQ.getWithInstruction(&I)))
1982 return replaceInstUsesWith(I, V);
1984 // See if we can simplify any instructions used by the instruction whose sole
1985 // purpose is to compute bits we don't care about.
1986 if (SimplifyDemandedInstructionBits(I))
1989 // Do this before using distributive laws to catch simple and/or/not patterns.
1990 if (Instruction *Xor = foldOrToXor(I, *Builder))
1993 // (A&B)|(A&C) -> A&(B|C) etc
1994 if (Value *V = SimplifyUsingDistributiveLaws(I))
1995 return replaceInstUsesWith(I, V);
1997 if (Value *V = SimplifyBSwap(I))
1998 return replaceInstUsesWith(I, V);
2000 if (isa<Constant>(Op1))
2001 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2004 // Given an OR instruction, check to see if this is a bswap.
2005 if (Instruction *BSwap = MatchBSwap(I))
2011 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2012 if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2013 MaskedValueIsZero(Op1, *C, 0, &I)) {
2014 Value *NOr = Builder->CreateOr(A, Op1);
2016 return BinaryOperator::CreateXor(NOr,
2017 ConstantInt::get(NOr->getType(), *C));
2020 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2021 if (match(Op1, m_OneUse(m_Xor(m_Value(A), m_APInt(C)))) &&
2022 MaskedValueIsZero(Op0, *C, 0, &I)) {
2023 Value *NOr = Builder->CreateOr(A, Op0);
2025 return BinaryOperator::CreateXor(NOr,
2026 ConstantInt::get(NOr->getType(), *C));
2032 // ((~A & B) | A) -> (A | B)
2033 if (match(Op0, m_c_And(m_Not(m_Specific(Op1)), m_Value(A))))
2034 return BinaryOperator::CreateOr(A, Op1);
2035 if (match(Op1, m_c_And(m_Not(m_Specific(Op0)), m_Value(A))))
2036 return BinaryOperator::CreateOr(Op0, A);
2038 // ((A & B) | ~A) -> (~A | B)
2039 // The NOT is guaranteed to be in the RHS by complexity ordering.
2040 if (match(Op1, m_Not(m_Value(A))) &&
2041 match(Op0, m_c_And(m_Specific(A), m_Value(B))))
2042 return BinaryOperator::CreateOr(Op1, B);
2045 Value *C = nullptr, *D = nullptr;
2046 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2047 match(Op1, m_And(m_Value(B), m_Value(D)))) {
2048 Value *V1 = nullptr, *V2 = nullptr;
2049 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
2050 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
2051 if (C1 && C2) { // (A & C1)|(B & C2)
2052 if ((C1->getValue() & C2->getValue()).isNullValue()) {
2053 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
2054 // iff (C1&C2) == 0 and (N&~C1) == 0
2055 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
2057 MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2059 MaskedValueIsZero(V1, ~C1->getValue(), 0, &I)))) // (N|V)
2060 return BinaryOperator::CreateAnd(A,
2061 Builder->getInt(C1->getValue()|C2->getValue()));
2062 // Or commutes, try both ways.
2063 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
2065 MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2067 MaskedValueIsZero(V1, ~C2->getValue(), 0, &I)))) // (N|V)
2068 return BinaryOperator::CreateAnd(B,
2069 Builder->getInt(C1->getValue()|C2->getValue()));
2071 // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
2072 // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
2073 ConstantInt *C3 = nullptr, *C4 = nullptr;
2074 if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2075 (C3->getValue() & ~C1->getValue()).isNullValue() &&
2076 match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2077 (C4->getValue() & ~C2->getValue()).isNullValue()) {
2078 V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2079 return BinaryOperator::CreateAnd(V2,
2080 Builder->getInt(C1->getValue()|C2->getValue()));
2085 // Don't try to form a select if it's unlikely that we'll get rid of at
2086 // least one of the operands. A select is generally more expensive than the
2087 // 'or' that it is replacing.
2088 if (Op0->hasOneUse() || Op1->hasOneUse()) {
2089 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
2090 if (Value *V = matchSelectFromAndOr(A, C, B, D, *Builder))
2091 return replaceInstUsesWith(I, V);
2092 if (Value *V = matchSelectFromAndOr(A, C, D, B, *Builder))
2093 return replaceInstUsesWith(I, V);
2094 if (Value *V = matchSelectFromAndOr(C, A, B, D, *Builder))
2095 return replaceInstUsesWith(I, V);
2096 if (Value *V = matchSelectFromAndOr(C, A, D, B, *Builder))
2097 return replaceInstUsesWith(I, V);
2098 if (Value *V = matchSelectFromAndOr(B, D, A, C, *Builder))
2099 return replaceInstUsesWith(I, V);
2100 if (Value *V = matchSelectFromAndOr(B, D, C, A, *Builder))
2101 return replaceInstUsesWith(I, V);
2102 if (Value *V = matchSelectFromAndOr(D, B, A, C, *Builder))
2103 return replaceInstUsesWith(I, V);
2104 if (Value *V = matchSelectFromAndOr(D, B, C, A, *Builder))
2105 return replaceInstUsesWith(I, V);
2108 // ((A|B)&1)|(B&-2) -> (A&1) | B
2109 if (match(A, m_c_Or(m_Value(V1), m_Specific(B)))) {
2110 if (Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C, Builder))
2113 // (B&-2)|((A|B)&1) -> (A&1) | B
2114 if (match(B, m_c_Or(m_Specific(A), m_Value(V1)))) {
2115 if (Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D, Builder))
2118 // ((A^B)&1)|(B&-2) -> (A&1) ^ B
2119 if (match(A, m_c_Xor(m_Value(V1), m_Specific(B)))) {
2120 if (Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C, Builder))
2123 // (B&-2)|((A^B)&1) -> (A&1) ^ B
2124 if (match(B, m_c_Xor(m_Specific(A), m_Value(V1)))) {
2125 if (Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D, Builder))
2130 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2131 if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2132 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2133 return BinaryOperator::CreateOr(Op0, C);
2135 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2136 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2137 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2138 return BinaryOperator::CreateOr(Op1, C);
2140 // ((B | C) & A) | B -> B | (A & C)
2141 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2142 return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2144 if (Instruction *DeMorgan = matchDeMorgansLaws(I, *Builder))
2147 // Canonicalize xor to the RHS.
2148 bool SwappedForXor = false;
2149 if (match(Op0, m_Xor(m_Value(), m_Value()))) {
2150 std::swap(Op0, Op1);
2151 SwappedForXor = true;
2154 // A | ( A ^ B) -> A | B
2155 // A | (~A ^ B) -> A | ~B
2156 // (A & B) | (A ^ B)
2157 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2158 if (Op0 == A || Op0 == B)
2159 return BinaryOperator::CreateOr(A, B);
2161 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2162 match(Op0, m_And(m_Specific(B), m_Specific(A))))
2163 return BinaryOperator::CreateOr(A, B);
2165 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2166 Value *Not = Builder->CreateNot(B, B->getName()+".not");
2167 return BinaryOperator::CreateOr(Not, Op0);
2169 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2170 Value *Not = Builder->CreateNot(A, A->getName()+".not");
2171 return BinaryOperator::CreateOr(Not, Op0);
2175 // A | ~(A | B) -> A | ~B
2176 // A | ~(A ^ B) -> A | ~B
2177 if (match(Op1, m_Not(m_Value(A))))
2178 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
2179 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2180 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2181 B->getOpcode() == Instruction::Xor)) {
2182 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2184 Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2185 return BinaryOperator::CreateOr(Not, Op0);
2188 // (A & B) | (~A ^ B) -> (~A ^ B)
2189 // (A & B) | (B ^ ~A) -> (~A ^ B)
2190 // (B & A) | (~A ^ B) -> (~A ^ B)
2191 // (B & A) | (B ^ ~A) -> (~A ^ B)
2192 // The match order is important: match the xor first because the 'not'
2193 // operation defines 'A'. We do not need to match the xor as Op0 because the
2194 // xor was canonicalized to Op1 above.
2195 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2196 match(Op0, m_c_And(m_Specific(A), m_Specific(B))))
2197 return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2200 std::swap(Op0, Op1);
2203 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2204 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2206 if (Value *Res = foldOrOfICmps(LHS, RHS, I))
2207 return replaceInstUsesWith(I, Res);
2209 // TODO: Make this recursive; it's a little tricky because an arbitrary
2210 // number of 'or' instructions might have to be created.
2212 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2213 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2214 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
2215 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
2216 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2217 if (Value *Res = foldOrOfICmps(LHS, Cmp, I))
2218 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
2220 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2221 if (auto *Cmp = dyn_cast<ICmpInst>(X))
2222 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
2223 return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
2224 if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2225 if (Value *Res = foldOrOfICmps(Cmp, RHS, I))
2226 return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
2230 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
2231 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2232 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2233 if (Value *Res = foldOrOfFCmps(LHS, RHS))
2234 return replaceInstUsesWith(I, Res);
2236 if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2239 // or(sext(A), B) / or(B, sext(A)) --> A ? -1 : B, where A is i1 or <N x i1>.
2240 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
2241 A->getType()->getScalarType()->isIntegerTy(1))
2242 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2243 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
2244 A->getType()->getScalarType()->isIntegerTy(1))
2245 return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2247 // Note: If we've gotten to the point of visiting the outer OR, then the
2248 // inner one couldn't be simplified. If it was a constant, then it won't
2249 // be simplified by a later pass either, so we try swapping the inner/outer
2250 // ORs in the hopes that we'll be able to simplify it this way.
2251 // (X|C) | V --> (X|V) | C
2253 if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2254 match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2255 Value *Inner = Builder->CreateOr(A, Op1);
2256 Inner->takeName(Op0);
2257 return BinaryOperator::CreateOr(Inner, C1);
2260 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2261 // Since this OR statement hasn't been optimized further yet, we hope
2262 // that this transformation will allow the new ORs to be optimized.
2264 Value *X = nullptr, *Y = nullptr;
2265 if (Op0->hasOneUse() && Op1->hasOneUse() &&
2266 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2267 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2268 Value *orTrue = Builder->CreateOr(A, C);
2269 Value *orFalse = Builder->CreateOr(B, D);
2270 return SelectInst::Create(X, orTrue, orFalse);
2274 return Changed ? &I : nullptr;
2277 /// A ^ B can be specified using other logic ops in a variety of patterns. We
2278 /// can fold these early and efficiently by morphing an existing instruction.
2279 static Instruction *foldXorToXor(BinaryOperator &I) {
2280 assert(I.getOpcode() == Instruction::Xor);
2281 Value *Op0 = I.getOperand(0);
2282 Value *Op1 = I.getOperand(1);
2285 // There are 4 commuted variants for each of the basic patterns.
2287 // (A & B) ^ (A | B) -> A ^ B
2288 // (A & B) ^ (B | A) -> A ^ B
2289 // (A | B) ^ (A & B) -> A ^ B
2290 // (A | B) ^ (B & A) -> A ^ B
2291 if ((match(Op0, m_And(m_Value(A), m_Value(B))) &&
2292 match(Op1, m_c_Or(m_Specific(A), m_Specific(B)))) ||
2293 (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2294 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))) {
2300 // (A | ~B) ^ (~A | B) -> A ^ B
2301 // (~B | A) ^ (~A | B) -> A ^ B
2302 // (~A | B) ^ (A | ~B) -> A ^ B
2303 // (B | ~A) ^ (A | ~B) -> A ^ B
2304 if ((match(Op0, m_c_Or(m_Value(A), m_Not(m_Value(B)))) &&
2305 match(Op1, m_Or(m_Not(m_Specific(A)), m_Specific(B)))) ||
2306 (match(Op0, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
2307 match(Op1, m_Or(m_Specific(A), m_Not(m_Specific(B)))))) {
2313 // (A & ~B) ^ (~A & B) -> A ^ B
2314 // (~B & A) ^ (~A & B) -> A ^ B
2315 // (~A & B) ^ (A & ~B) -> A ^ B
2316 // (B & ~A) ^ (A & ~B) -> A ^ B
2317 if ((match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2318 match(Op1, m_And(m_Not(m_Specific(A)), m_Specific(B)))) ||
2319 (match(Op0, m_c_And(m_Not(m_Value(A)), m_Value(B))) &&
2320 match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B)))))) {
2329 Value *InstCombiner::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
2330 if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2331 if (LHS->getOperand(0) == RHS->getOperand(1) &&
2332 LHS->getOperand(1) == RHS->getOperand(0))
2333 LHS->swapOperands();
2334 if (LHS->getOperand(0) == RHS->getOperand(0) &&
2335 LHS->getOperand(1) == RHS->getOperand(1)) {
2336 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2337 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2338 unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2339 bool isSigned = LHS->isSigned() || RHS->isSigned();
2340 return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
2344 // Instead of trying to imitate the folds for and/or, decompose this 'xor'
2345 // into those logic ops. That is, try to turn this into an and-of-icmps
2346 // because we have many folds for that pattern.
2348 // This is based on a truth table definition of xor:
2349 // X ^ Y --> (X | Y) & !(X & Y)
2350 if (Value *OrICmp = SimplifyBinOp(Instruction::Or, LHS, RHS, SQ)) {
2351 // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y).
2352 // TODO: If OrICmp is false, the whole thing is false (InstSimplify?).
2353 if (Value *AndICmp = SimplifyBinOp(Instruction::And, LHS, RHS, SQ)) {
2354 // TODO: Independently handle cases where the 'and' side is a constant.
2355 if (OrICmp == LHS && AndICmp == RHS && RHS->hasOneUse()) {
2356 // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS
2357 RHS->setPredicate(RHS->getInversePredicate());
2358 return Builder->CreateAnd(LHS, RHS);
2360 if (OrICmp == RHS && AndICmp == LHS && LHS->hasOneUse()) {
2361 // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS
2362 LHS->setPredicate(LHS->getInversePredicate());
2363 return Builder->CreateAnd(LHS, RHS);
2371 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
2372 // here. We should standardize that construct where it is needed or choose some
2373 // other way to ensure that commutated variants of patterns are not missed.
2374 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2375 bool Changed = SimplifyAssociativeOrCommutative(I);
2376 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2378 if (Value *V = SimplifyVectorOp(I))
2379 return replaceInstUsesWith(I, V);
2381 if (Value *V = SimplifyXorInst(Op0, Op1, SQ.getWithInstruction(&I)))
2382 return replaceInstUsesWith(I, V);
2384 if (Instruction *NewXor = foldXorToXor(I))
2387 // (A&B)^(A&C) -> A&(B^C) etc
2388 if (Value *V = SimplifyUsingDistributiveLaws(I))
2389 return replaceInstUsesWith(I, V);
2391 // See if we can simplify any instructions used by the instruction whose sole
2392 // purpose is to compute bits we don't care about.
2393 if (SimplifyDemandedInstructionBits(I))
2396 if (Value *V = SimplifyBSwap(I))
2397 return replaceInstUsesWith(I, V);
2399 // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand.
2402 // We must eliminate the and/or (one-use) for these transforms to not increase
2403 // the instruction count.
2404 // ~(~X & Y) --> (X | ~Y)
2405 // ~(Y & ~X) --> (X | ~Y)
2406 if (match(&I, m_Not(m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y)))))) {
2407 Value *NotY = Builder->CreateNot(Y, Y->getName() + ".not");
2408 return BinaryOperator::CreateOr(X, NotY);
2410 // ~(~X | Y) --> (X & ~Y)
2411 // ~(Y | ~X) --> (X & ~Y)
2412 if (match(&I, m_Not(m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y)))))) {
2413 Value *NotY = Builder->CreateNot(Y, Y->getName() + ".not");
2414 return BinaryOperator::CreateAnd(X, NotY);
2417 // Is this a 'not' (~) fed by a binary operator?
2418 BinaryOperator *NotVal;
2419 if (match(&I, m_Not(m_BinOp(NotVal)))) {
2420 if (NotVal->getOpcode() == Instruction::And ||
2421 NotVal->getOpcode() == Instruction::Or) {
2422 // Apply DeMorgan's Law when inverts are free:
2423 // ~(X & Y) --> (~X | ~Y)
2424 // ~(X | Y) --> (~X & ~Y)
2425 if (IsFreeToInvert(NotVal->getOperand(0),
2426 NotVal->getOperand(0)->hasOneUse()) &&
2427 IsFreeToInvert(NotVal->getOperand(1),
2428 NotVal->getOperand(1)->hasOneUse())) {
2429 Value *NotX = Builder->CreateNot(NotVal->getOperand(0), "notlhs");
2430 Value *NotY = Builder->CreateNot(NotVal->getOperand(1), "notrhs");
2431 if (NotVal->getOpcode() == Instruction::And)
2432 return BinaryOperator::CreateOr(NotX, NotY);
2433 return BinaryOperator::CreateAnd(NotX, NotY);
2437 // ~(~X >>s Y) --> (X >>s Y)
2438 if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y))))
2439 return BinaryOperator::CreateAShr(X, Y);
2441 // If we are inverting a right-shifted constant, we may be able to eliminate
2442 // the 'not' by inverting the constant and using the opposite shift type.
2443 // Canonicalization rules ensure that only a negative constant uses 'ashr',
2444 // but we must check that in case that transform has not fired yet.
2446 if (match(NotVal, m_AShr(m_APInt(C), m_Value(Y))) && C->isNegative()) {
2447 // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits)
2448 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2449 return BinaryOperator::CreateLShr(NotC, Y);
2452 if (match(NotVal, m_LShr(m_APInt(C), m_Value(Y))) && C->isNonNegative()) {
2453 // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits)
2454 Constant *NotC = ConstantInt::get(I.getType(), ~(*C));
2455 return BinaryOperator::CreateAShr(NotC, Y);
2459 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2460 ICmpInst::Predicate Pred;
2461 if (match(Op0, m_OneUse(m_Cmp(Pred, m_Value(), m_Value()))) &&
2462 match(Op1, m_AllOnes())) {
2463 cast<CmpInst>(Op0)->setPredicate(CmpInst::getInversePredicate(Pred));
2464 return replaceInstUsesWith(I, Op0);
2467 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(Op1)) {
2468 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2469 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2470 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2471 if (CI->hasOneUse() && Op0C->hasOneUse()) {
2472 Instruction::CastOps Opcode = Op0C->getOpcode();
2473 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2474 (RHSC == ConstantExpr::getCast(Opcode, Builder->getTrue(),
2475 Op0C->getDestTy()))) {
2476 CI->setPredicate(CI->getInversePredicate());
2477 return CastInst::Create(Opcode, CI, Op0C->getType());
2483 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2484 // ~(c-X) == X-c-1 == X+(-c-1)
2485 if (Op0I->getOpcode() == Instruction::Sub && RHSC->isAllOnesValue())
2486 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2487 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2488 return BinaryOperator::CreateAdd(Op0I->getOperand(1),
2492 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2493 if (Op0I->getOpcode() == Instruction::Add) {
2494 // ~(X-c) --> (-c-1)-X
2495 if (RHSC->isAllOnesValue()) {
2496 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2497 return BinaryOperator::CreateSub(SubOne(NegOp0CI),
2498 Op0I->getOperand(0));
2499 } else if (RHSC->getValue().isSignMask()) {
2500 // (X + C) ^ signmask -> (X + C + signmask)
2501 Constant *C = Builder->getInt(RHSC->getValue() + Op0CI->getValue());
2502 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2505 } else if (Op0I->getOpcode() == Instruction::Or) {
2506 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2507 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2509 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHSC);
2510 // Anything in both C1 and C2 is known to be zero, remove it from
2512 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHSC);
2513 NewRHS = ConstantExpr::getAnd(NewRHS,
2514 ConstantExpr::getNot(CommonBits));
2516 I.setOperand(0, Op0I->getOperand(0));
2517 I.setOperand(1, NewRHS);
2520 } else if (Op0I->getOpcode() == Instruction::LShr) {
2521 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2525 if (Op0I->hasOneUse() &&
2526 (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2527 E1->getOpcode() == Instruction::Xor &&
2528 (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2529 // fold (C1 >> C2) ^ C3
2530 ConstantInt *C2 = Op0CI, *C3 = RHSC;
2531 APInt FoldConst = C1->getValue().lshr(C2->getValue());
2532 FoldConst ^= C3->getValue();
2533 // Prepare the two operands.
2534 Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2535 Opnd0->takeName(Op0I);
2536 cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2537 Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2539 return BinaryOperator::CreateXor(Opnd0, FoldVal);
2546 if (isa<Constant>(Op1))
2547 if (Instruction *FoldedLogic = foldOpWithConstantIntoOperand(I))
2552 if (match(Op1, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
2553 if (A == Op0) { // A^(A|B) == A^(B|A)
2554 cast<BinaryOperator>(Op1)->swapOperands();
2557 if (B == Op0) { // A^(B|A) == (B|A)^A
2558 I.swapOperands(); // Simplified below.
2559 std::swap(Op0, Op1);
2561 } else if (match(Op1, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
2562 if (A == Op0) { // A^(A&B) -> A^(B&A)
2563 cast<BinaryOperator>(Op1)->swapOperands();
2566 if (B == Op0) { // A^(B&A) -> (B&A)^A
2567 I.swapOperands(); // Simplified below.
2568 std::swap(Op0, Op1);
2575 if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B))))) {
2576 if (A == Op1) // (B|A)^B == (A|B)^B
2578 if (B == Op1) // (A|B)^B == A & ~B
2579 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
2580 } else if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B))))) {
2581 if (A == Op1) // (A&B)^A -> (B&A)^A
2584 if (B == Op1 && // (B&A)^A == ~B & A
2585 !match(Op1, m_APInt(C))) { // Canonical form is (B&C)^C
2586 return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
2592 Value *A, *B, *C, *D;
2593 // (A ^ C)^(A | B) -> ((~A) & B) ^ C
2594 if (match(Op0, m_Xor(m_Value(D), m_Value(C))) &&
2595 match(Op1, m_Or(m_Value(A), m_Value(B)))) {
2597 return BinaryOperator::CreateXor(
2598 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2600 return BinaryOperator::CreateXor(
2601 Builder->CreateAnd(Builder->CreateNot(B), A), C);
2603 // (A | B)^(A ^ C) -> ((~A) & B) ^ C
2604 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
2605 match(Op1, m_Xor(m_Value(D), m_Value(C)))) {
2607 return BinaryOperator::CreateXor(
2608 Builder->CreateAnd(Builder->CreateNot(A), B), C);
2610 return BinaryOperator::CreateXor(
2611 Builder->CreateAnd(Builder->CreateNot(B), A), C);
2613 // (A & B) ^ (A ^ B) -> (A | B)
2614 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2615 match(Op1, m_c_Xor(m_Specific(A), m_Specific(B))))
2616 return BinaryOperator::CreateOr(A, B);
2617 // (A ^ B) ^ (A & B) -> (A | B)
2618 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2619 match(Op1, m_c_And(m_Specific(A), m_Specific(B))))
2620 return BinaryOperator::CreateOr(A, B);
2623 // (A & ~B) ^ ~A -> ~(A & B)
2624 // (~B & A) ^ ~A -> ~(A & B)
2626 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2627 match(Op1, m_Not(m_Specific(A))))
2628 return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2630 if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2631 if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2632 if (Value *V = foldXorOfICmps(LHS, RHS))
2633 return replaceInstUsesWith(I, V);
2635 if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2638 return Changed ? &I : nullptr;