• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- InstCombineAndOrXor.cpp --------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the visitAnd, visitOr, and visitXor functions.
11 //
12 //===----------------------------------------------------------------------===//
13 
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"
21 using namespace llvm;
22 using namespace PatternMatch;
23 
24 #define DEBUG_TYPE "instcombine"
25 
dyn_castNotVal(Value * V)26 static inline Value *dyn_castNotVal(Value *V) {
27   // If this is not(not(x)) don't return that this is a not: we want the two
28   // not's to be folded first.
29   if (BinaryOperator::isNot(V)) {
30     Value *Operand = BinaryOperator::getNotArgument(V);
31     if (!IsFreeToInvert(Operand, Operand->hasOneUse()))
32       return Operand;
33   }
34 
35   // Constants can be considered to be not'ed values...
36   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
37     return ConstantInt::get(C->getType(), ~C->getValue());
38   return nullptr;
39 }
40 
41 /// Similar to getICmpCode but for FCmpInst. This encodes a fcmp predicate into
42 /// a four bit mask.
getFCmpCode(FCmpInst::Predicate CC)43 static unsigned getFCmpCode(FCmpInst::Predicate CC) {
44   assert(FCmpInst::FCMP_FALSE <= CC && CC <= FCmpInst::FCMP_TRUE &&
45          "Unexpected FCmp predicate!");
46   // Take advantage of the bit pattern of FCmpInst::Predicate here.
47   //                                                 U L G E
48   static_assert(FCmpInst::FCMP_FALSE ==  0, "");  // 0 0 0 0
49   static_assert(FCmpInst::FCMP_OEQ   ==  1, "");  // 0 0 0 1
50   static_assert(FCmpInst::FCMP_OGT   ==  2, "");  // 0 0 1 0
51   static_assert(FCmpInst::FCMP_OGE   ==  3, "");  // 0 0 1 1
52   static_assert(FCmpInst::FCMP_OLT   ==  4, "");  // 0 1 0 0
53   static_assert(FCmpInst::FCMP_OLE   ==  5, "");  // 0 1 0 1
54   static_assert(FCmpInst::FCMP_ONE   ==  6, "");  // 0 1 1 0
55   static_assert(FCmpInst::FCMP_ORD   ==  7, "");  // 0 1 1 1
56   static_assert(FCmpInst::FCMP_UNO   ==  8, "");  // 1 0 0 0
57   static_assert(FCmpInst::FCMP_UEQ   ==  9, "");  // 1 0 0 1
58   static_assert(FCmpInst::FCMP_UGT   == 10, "");  // 1 0 1 0
59   static_assert(FCmpInst::FCMP_UGE   == 11, "");  // 1 0 1 1
60   static_assert(FCmpInst::FCMP_ULT   == 12, "");  // 1 1 0 0
61   static_assert(FCmpInst::FCMP_ULE   == 13, "");  // 1 1 0 1
62   static_assert(FCmpInst::FCMP_UNE   == 14, "");  // 1 1 1 0
63   static_assert(FCmpInst::FCMP_TRUE  == 15, "");  // 1 1 1 1
64   return CC;
65 }
66 
67 /// This is the complement of getICmpCode, which turns an opcode and two
68 /// operands into either a constant true or false, or a brand new ICmp
69 /// instruction. The sign is passed in to determine which kind of predicate to
70 /// use in the new icmp instruction.
getNewICmpValue(bool Sign,unsigned Code,Value * LHS,Value * RHS,InstCombiner::BuilderTy * Builder)71 static Value *getNewICmpValue(bool Sign, unsigned Code, Value *LHS, Value *RHS,
72                               InstCombiner::BuilderTy *Builder) {
73   ICmpInst::Predicate NewPred;
74   if (Value *NewConstant = getICmpValue(Sign, Code, LHS, RHS, NewPred))
75     return NewConstant;
76   return Builder->CreateICmp(NewPred, LHS, RHS);
77 }
78 
79 /// This is the complement of getFCmpCode, which turns an opcode and two
80 /// operands into either a FCmp instruction, or a true/false constant.
getFCmpValue(unsigned Code,Value * LHS,Value * RHS,InstCombiner::BuilderTy * Builder)81 static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS,
82                            InstCombiner::BuilderTy *Builder) {
83   const auto Pred = static_cast<FCmpInst::Predicate>(Code);
84   assert(FCmpInst::FCMP_FALSE <= Pred && Pred <= FCmpInst::FCMP_TRUE &&
85          "Unexpected FCmp predicate!");
86   if (Pred == FCmpInst::FCMP_FALSE)
87     return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
88   if (Pred == FCmpInst::FCMP_TRUE)
89     return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 1);
90   return Builder->CreateFCmp(Pred, LHS, RHS);
91 }
92 
93 /// \brief Transform BITWISE_OP(BSWAP(A),BSWAP(B)) to BSWAP(BITWISE_OP(A, B))
94 /// \param I Binary operator to transform.
95 /// \return Pointer to node that must replace the original binary operator, or
96 ///         null pointer if no transformation was made.
SimplifyBSwap(BinaryOperator & I)97 Value *InstCombiner::SimplifyBSwap(BinaryOperator &I) {
98   IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
99 
100   // Can't do vectors.
101   if (I.getType()->isVectorTy()) return nullptr;
102 
103   // Can only do bitwise ops.
104   unsigned Op = I.getOpcode();
105   if (Op != Instruction::And && Op != Instruction::Or &&
106       Op != Instruction::Xor)
107     return nullptr;
108 
109   Value *OldLHS = I.getOperand(0);
110   Value *OldRHS = I.getOperand(1);
111   ConstantInt *ConstLHS = dyn_cast<ConstantInt>(OldLHS);
112   ConstantInt *ConstRHS = dyn_cast<ConstantInt>(OldRHS);
113   IntrinsicInst *IntrLHS = dyn_cast<IntrinsicInst>(OldLHS);
114   IntrinsicInst *IntrRHS = dyn_cast<IntrinsicInst>(OldRHS);
115   bool IsBswapLHS = (IntrLHS && IntrLHS->getIntrinsicID() == Intrinsic::bswap);
116   bool IsBswapRHS = (IntrRHS && IntrRHS->getIntrinsicID() == Intrinsic::bswap);
117 
118   if (!IsBswapLHS && !IsBswapRHS)
119     return nullptr;
120 
121   if (!IsBswapLHS && !ConstLHS)
122     return nullptr;
123 
124   if (!IsBswapRHS && !ConstRHS)
125     return nullptr;
126 
127   /// OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) )
128   /// OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) )
129   Value *NewLHS = IsBswapLHS ? IntrLHS->getOperand(0) :
130                   Builder->getInt(ConstLHS->getValue().byteSwap());
131 
132   Value *NewRHS = IsBswapRHS ? IntrRHS->getOperand(0) :
133                   Builder->getInt(ConstRHS->getValue().byteSwap());
134 
135   Value *BinOp = nullptr;
136   if (Op == Instruction::And)
137     BinOp = Builder->CreateAnd(NewLHS, NewRHS);
138   else if (Op == Instruction::Or)
139     BinOp = Builder->CreateOr(NewLHS, NewRHS);
140   else //if (Op == Instruction::Xor)
141     BinOp = Builder->CreateXor(NewLHS, NewRHS);
142 
143   Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap, ITy);
144   return Builder->CreateCall(F, BinOp);
145 }
146 
147 /// This handles expressions of the form ((val OP C1) & C2).  Where
148 /// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
149 /// guaranteed to be a binary operator.
OptAndOp(Instruction * Op,ConstantInt * OpRHS,ConstantInt * AndRHS,BinaryOperator & TheAnd)150 Instruction *InstCombiner::OptAndOp(Instruction *Op,
151                                     ConstantInt *OpRHS,
152                                     ConstantInt *AndRHS,
153                                     BinaryOperator &TheAnd) {
154   Value *X = Op->getOperand(0);
155   Constant *Together = nullptr;
156   if (!Op->isShift())
157     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
158 
159   switch (Op->getOpcode()) {
160   case Instruction::Xor:
161     if (Op->hasOneUse()) {
162       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
163       Value *And = Builder->CreateAnd(X, AndRHS);
164       And->takeName(Op);
165       return BinaryOperator::CreateXor(And, Together);
166     }
167     break;
168   case Instruction::Or:
169     if (Op->hasOneUse()){
170       if (Together != OpRHS) {
171         // (X | C1) & C2 --> (X | (C1&C2)) & C2
172         Value *Or = Builder->CreateOr(X, Together);
173         Or->takeName(Op);
174         return BinaryOperator::CreateAnd(Or, AndRHS);
175       }
176 
177       ConstantInt *TogetherCI = dyn_cast<ConstantInt>(Together);
178       if (TogetherCI && !TogetherCI->isZero()){
179         // (X | C1) & C2 --> (X & (C2^(C1&C2))) | C1
180         // NOTE: This reduces the number of bits set in the & mask, which
181         // can expose opportunities for store narrowing.
182         Together = ConstantExpr::getXor(AndRHS, Together);
183         Value *And = Builder->CreateAnd(X, Together);
184         And->takeName(Op);
185         return BinaryOperator::CreateOr(And, OpRHS);
186       }
187     }
188 
189     break;
190   case Instruction::Add:
191     if (Op->hasOneUse()) {
192       // Adding a one to a single bit bit-field should be turned into an XOR
193       // of the bit.  First thing to check is to see if this AND is with a
194       // single bit constant.
195       const APInt &AndRHSV = AndRHS->getValue();
196 
197       // If there is only one bit set.
198       if (AndRHSV.isPowerOf2()) {
199         // Ok, at this point, we know that we are masking the result of the
200         // ADD down to exactly one bit.  If the constant we are adding has
201         // no bits set below this bit, then we can eliminate the ADD.
202         const APInt& AddRHS = OpRHS->getValue();
203 
204         // Check to see if any bits below the one bit set in AndRHSV are set.
205         if ((AddRHS & (AndRHSV-1)) == 0) {
206           // If not, the only thing that can effect the output of the AND is
207           // the bit specified by AndRHSV.  If that bit is set, the effect of
208           // the XOR is to toggle the bit.  If it is clear, then the ADD has
209           // no effect.
210           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
211             TheAnd.setOperand(0, X);
212             return &TheAnd;
213           } else {
214             // Pull the XOR out of the AND.
215             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
216             NewAnd->takeName(Op);
217             return BinaryOperator::CreateXor(NewAnd, AndRHS);
218           }
219         }
220       }
221     }
222     break;
223 
224   case Instruction::Shl: {
225     // We know that the AND will not produce any of the bits shifted in, so if
226     // the anded constant includes them, clear them now!
227     //
228     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
229     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
230     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
231     ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShlMask);
232 
233     if (CI->getValue() == ShlMask)
234       // Masking out bits that the shift already masks.
235       return replaceInstUsesWith(TheAnd, Op);   // No need for the and.
236 
237     if (CI != AndRHS) {                  // Reducing bits set in and.
238       TheAnd.setOperand(1, CI);
239       return &TheAnd;
240     }
241     break;
242   }
243   case Instruction::LShr: {
244     // We know that the AND will not produce any of the bits shifted in, so if
245     // the anded constant includes them, clear them now!  This only applies to
246     // unsigned shifts, because a signed shr may bring in set bits!
247     //
248     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
249     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
250     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
251     ConstantInt *CI = Builder->getInt(AndRHS->getValue() & ShrMask);
252 
253     if (CI->getValue() == ShrMask)
254       // Masking out bits that the shift already masks.
255       return replaceInstUsesWith(TheAnd, Op);
256 
257     if (CI != AndRHS) {
258       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
259       return &TheAnd;
260     }
261     break;
262   }
263   case Instruction::AShr:
264     // Signed shr.
265     // See if this is shifting in some sign extension, then masking it out
266     // with an and.
267     if (Op->hasOneUse()) {
268       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
269       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
270       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
271       Constant *C = Builder->getInt(AndRHS->getValue() & ShrMask);
272       if (C == AndRHS) {          // Masking out bits shifted in.
273         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
274         // Make the argument unsigned.
275         Value *ShVal = Op->getOperand(0);
276         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
277         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
278       }
279     }
280     break;
281   }
282   return nullptr;
283 }
284 
285 /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise
286 /// (V < Lo || V >= Hi).  In practice, we emit the more efficient
287 /// (V-Lo) \<u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
288 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
289 /// insert new instructions.
InsertRangeTest(Value * V,Constant * Lo,Constant * Hi,bool isSigned,bool Inside)290 Value *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
291                                      bool isSigned, bool Inside) {
292   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
293             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
294          "Lo is not <= Hi in range emission code!");
295 
296   if (Inside) {
297     if (Lo == Hi)  // Trivially false.
298       return Builder->getFalse();
299 
300     // V >= Min && V < Hi --> V < Hi
301     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
302       ICmpInst::Predicate pred = (isSigned ?
303         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
304       return Builder->CreateICmp(pred, V, Hi);
305     }
306 
307     // Emit V-Lo <u Hi-Lo
308     Constant *NegLo = ConstantExpr::getNeg(Lo);
309     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
310     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
311     return Builder->CreateICmpULT(Add, UpperBound);
312   }
313 
314   if (Lo == Hi)  // Trivially true.
315     return Builder->getTrue();
316 
317   // V < Min || V >= Hi -> V > Hi-1
318   Hi = SubOne(cast<ConstantInt>(Hi));
319   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
320     ICmpInst::Predicate pred = (isSigned ?
321         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
322     return Builder->CreateICmp(pred, V, Hi);
323   }
324 
325   // Emit V-Lo >u Hi-1-Lo
326   // Note that Hi has already had one subtracted from it, above.
327   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
328   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
329   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
330   return Builder->CreateICmpUGT(Add, LowerBound);
331 }
332 
333 /// Returns true iff Val consists of one contiguous run of 1s with any number
334 /// of 0s on either side.  The 1s are allowed to wrap from LSB to MSB,
335 /// so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
336 /// not, since all 1s are not contiguous.
isRunOfOnes(ConstantInt * Val,uint32_t & MB,uint32_t & ME)337 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
338   const APInt& V = Val->getValue();
339   uint32_t BitWidth = Val->getType()->getBitWidth();
340   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
341 
342   // look for the first zero bit after the run of ones
343   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
344   // look for the first non-zero bit
345   ME = V.getActiveBits();
346   return true;
347 }
348 
349 /// This is part of an expression (LHS +/- RHS) & Mask, where isSub determines
350 /// whether the operator is a sub. If we can fold one of the following xforms:
351 ///
352 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
353 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
354 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
355 ///
356 /// return (A +/- B).
357 ///
FoldLogicalPlusAnd(Value * LHS,Value * RHS,ConstantInt * Mask,bool isSub,Instruction & I)358 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
359                                         ConstantInt *Mask, bool isSub,
360                                         Instruction &I) {
361   Instruction *LHSI = dyn_cast<Instruction>(LHS);
362   if (!LHSI || LHSI->getNumOperands() != 2 ||
363       !isa<ConstantInt>(LHSI->getOperand(1))) return nullptr;
364 
365   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
366 
367   switch (LHSI->getOpcode()) {
368   default: return nullptr;
369   case Instruction::And:
370     if (ConstantExpr::getAnd(N, Mask) == Mask) {
371       // If the AndRHS is a power of two minus one (0+1+), this is simple.
372       if ((Mask->getValue().countLeadingZeros() +
373            Mask->getValue().countPopulation()) ==
374           Mask->getValue().getBitWidth())
375         break;
376 
377       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
378       // part, we don't need any explicit masks to take them out of A.  If that
379       // is all N is, ignore it.
380       uint32_t MB = 0, ME = 0;
381       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
382         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
383         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
384         if (MaskedValueIsZero(RHS, Mask, 0, &I))
385           break;
386       }
387     }
388     return nullptr;
389   case Instruction::Or:
390   case Instruction::Xor:
391     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
392     if ((Mask->getValue().countLeadingZeros() +
393          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
394         && ConstantExpr::getAnd(N, Mask)->isNullValue())
395       break;
396     return nullptr;
397   }
398 
399   if (isSub)
400     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
401   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
402 }
403 
404 /// enum for classifying (icmp eq (A & B), C) and (icmp ne (A & B), C)
405 /// One of A and B is considered the mask, the other the value. This is
406 /// described as the "AMask" or "BMask" part of the enum. If the enum
407 /// contains only "Mask", then both A and B can be considered masks.
408 /// If A is the mask, then it was proven, that (A & C) == C. This
409 /// is trivial if C == A, or C == 0. If both A and C are constants, this
410 /// proof is also easy.
411 /// For the following explanations we assume that A is the mask.
412 /// The part "AllOnes" declares, that the comparison is true only
413 /// if (A & B) == A, or all bits of A are set in B.
414 ///   Example: (icmp eq (A & 3), 3) -> FoldMskICmp_AMask_AllOnes
415 /// The part "AllZeroes" declares, that the comparison is true only
416 /// if (A & B) == 0, or all bits of A are cleared in B.
417 ///   Example: (icmp eq (A & 3), 0) -> FoldMskICmp_Mask_AllZeroes
418 /// The part "Mixed" declares, that (A & B) == C and C might or might not
419 /// contain any number of one bits and zero bits.
420 ///   Example: (icmp eq (A & 3), 1) -> FoldMskICmp_AMask_Mixed
421 /// The Part "Not" means, that in above descriptions "==" should be replaced
422 /// by "!=".
423 ///   Example: (icmp ne (A & 3), 3) -> FoldMskICmp_AMask_NotAllOnes
424 /// If the mask A contains a single bit, then the following is equivalent:
425 ///    (icmp eq (A & B), A) equals (icmp ne (A & B), 0)
426 ///    (icmp ne (A & B), A) equals (icmp eq (A & B), 0)
427 enum MaskedICmpType {
428   FoldMskICmp_AMask_AllOnes           =     1,
429   FoldMskICmp_AMask_NotAllOnes        =     2,
430   FoldMskICmp_BMask_AllOnes           =     4,
431   FoldMskICmp_BMask_NotAllOnes        =     8,
432   FoldMskICmp_Mask_AllZeroes          =    16,
433   FoldMskICmp_Mask_NotAllZeroes       =    32,
434   FoldMskICmp_AMask_Mixed             =    64,
435   FoldMskICmp_AMask_NotMixed          =   128,
436   FoldMskICmp_BMask_Mixed             =   256,
437   FoldMskICmp_BMask_NotMixed          =   512
438 };
439 
440 /// Return the set of pattern classes (from MaskedICmpType)
441 /// that (icmp SCC (A & B), C) satisfies.
getTypeOfMaskedICmp(Value * A,Value * B,Value * C,ICmpInst::Predicate SCC)442 static unsigned getTypeOfMaskedICmp(Value* A, Value* B, Value* C,
443                                     ICmpInst::Predicate SCC)
444 {
445   ConstantInt *ACst = dyn_cast<ConstantInt>(A);
446   ConstantInt *BCst = dyn_cast<ConstantInt>(B);
447   ConstantInt *CCst = dyn_cast<ConstantInt>(C);
448   bool icmp_eq = (SCC == ICmpInst::ICMP_EQ);
449   bool icmp_abit = (ACst && !ACst->isZero() &&
450                     ACst->getValue().isPowerOf2());
451   bool icmp_bbit = (BCst && !BCst->isZero() &&
452                     BCst->getValue().isPowerOf2());
453   unsigned result = 0;
454   if (CCst && CCst->isZero()) {
455     // if C is zero, then both A and B qualify as mask
456     result |= (icmp_eq ? (FoldMskICmp_Mask_AllZeroes |
457                           FoldMskICmp_AMask_Mixed |
458                           FoldMskICmp_BMask_Mixed)
459                        : (FoldMskICmp_Mask_NotAllZeroes |
460                           FoldMskICmp_AMask_NotMixed |
461                           FoldMskICmp_BMask_NotMixed));
462     if (icmp_abit)
463       result |= (icmp_eq ? (FoldMskICmp_AMask_NotAllOnes |
464                             FoldMskICmp_AMask_NotMixed)
465                          : (FoldMskICmp_AMask_AllOnes |
466                             FoldMskICmp_AMask_Mixed));
467     if (icmp_bbit)
468       result |= (icmp_eq ? (FoldMskICmp_BMask_NotAllOnes |
469                             FoldMskICmp_BMask_NotMixed)
470                          : (FoldMskICmp_BMask_AllOnes |
471                             FoldMskICmp_BMask_Mixed));
472     return result;
473   }
474   if (A == C) {
475     result |= (icmp_eq ? (FoldMskICmp_AMask_AllOnes |
476                           FoldMskICmp_AMask_Mixed)
477                        : (FoldMskICmp_AMask_NotAllOnes |
478                           FoldMskICmp_AMask_NotMixed));
479     if (icmp_abit)
480       result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
481                             FoldMskICmp_AMask_NotMixed)
482                          : (FoldMskICmp_Mask_AllZeroes |
483                             FoldMskICmp_AMask_Mixed));
484   } else if (ACst && CCst &&
485              ConstantExpr::getAnd(ACst, CCst) == CCst) {
486     result |= (icmp_eq ? FoldMskICmp_AMask_Mixed
487                        : FoldMskICmp_AMask_NotMixed);
488   }
489   if (B == C) {
490     result |= (icmp_eq ? (FoldMskICmp_BMask_AllOnes |
491                           FoldMskICmp_BMask_Mixed)
492                        : (FoldMskICmp_BMask_NotAllOnes |
493                           FoldMskICmp_BMask_NotMixed));
494     if (icmp_bbit)
495       result |= (icmp_eq ? (FoldMskICmp_Mask_NotAllZeroes |
496                             FoldMskICmp_BMask_NotMixed)
497                          : (FoldMskICmp_Mask_AllZeroes |
498                             FoldMskICmp_BMask_Mixed));
499   } else if (BCst && CCst &&
500              ConstantExpr::getAnd(BCst, CCst) == CCst) {
501     result |= (icmp_eq ? FoldMskICmp_BMask_Mixed
502                        : FoldMskICmp_BMask_NotMixed);
503   }
504   return result;
505 }
506 
507 /// Convert an analysis of a masked ICmp into its equivalent if all boolean
508 /// operations had the opposite sense. Since each "NotXXX" flag (recording !=)
509 /// is adjacent to the corresponding normal flag (recording ==), this just
510 /// involves swapping those bits over.
conjugateICmpMask(unsigned Mask)511 static unsigned conjugateICmpMask(unsigned Mask) {
512   unsigned NewMask;
513   NewMask = (Mask & (FoldMskICmp_AMask_AllOnes | FoldMskICmp_BMask_AllOnes |
514                      FoldMskICmp_Mask_AllZeroes | FoldMskICmp_AMask_Mixed |
515                      FoldMskICmp_BMask_Mixed))
516             << 1;
517 
518   NewMask |=
519       (Mask & (FoldMskICmp_AMask_NotAllOnes | FoldMskICmp_BMask_NotAllOnes |
520                FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_AMask_NotMixed |
521                FoldMskICmp_BMask_NotMixed))
522       >> 1;
523 
524   return NewMask;
525 }
526 
527 /// Decompose an icmp into the form ((X & Y) pred Z) if possible.
528 /// The returned predicate is either == or !=. Returns false if
529 /// decomposition fails.
decomposeBitTestICmp(const ICmpInst * I,ICmpInst::Predicate & Pred,Value * & X,Value * & Y,Value * & Z)530 static bool decomposeBitTestICmp(const ICmpInst *I, ICmpInst::Predicate &Pred,
531                                  Value *&X, Value *&Y, Value *&Z) {
532   ConstantInt *C = dyn_cast<ConstantInt>(I->getOperand(1));
533   if (!C)
534     return false;
535 
536   switch (I->getPredicate()) {
537   default:
538     return false;
539   case ICmpInst::ICMP_SLT:
540     // X < 0 is equivalent to (X & SignBit) != 0.
541     if (!C->isZero())
542       return false;
543     Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
544     Pred = ICmpInst::ICMP_NE;
545     break;
546   case ICmpInst::ICMP_SGT:
547     // X > -1 is equivalent to (X & SignBit) == 0.
548     if (!C->isAllOnesValue())
549       return false;
550     Y = ConstantInt::get(I->getContext(), APInt::getSignBit(C->getBitWidth()));
551     Pred = ICmpInst::ICMP_EQ;
552     break;
553   case ICmpInst::ICMP_ULT:
554     // X <u 2^n is equivalent to (X & ~(2^n-1)) == 0.
555     if (!C->getValue().isPowerOf2())
556       return false;
557     Y = ConstantInt::get(I->getContext(), -C->getValue());
558     Pred = ICmpInst::ICMP_EQ;
559     break;
560   case ICmpInst::ICMP_UGT:
561     // X >u 2^n-1 is equivalent to (X & ~(2^n-1)) != 0.
562     if (!(C->getValue() + 1).isPowerOf2())
563       return false;
564     Y = ConstantInt::get(I->getContext(), ~C->getValue());
565     Pred = ICmpInst::ICMP_NE;
566     break;
567   }
568 
569   X = I->getOperand(0);
570   Z = ConstantInt::getNullValue(C->getType());
571   return true;
572 }
573 
574 /// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
575 /// Return the set of pattern classes (from MaskedICmpType)
576 /// that both LHS and RHS satisfy.
foldLogOpOfMaskedICmpsHelper(Value * & A,Value * & B,Value * & C,Value * & D,Value * & E,ICmpInst * LHS,ICmpInst * RHS,ICmpInst::Predicate & LHSCC,ICmpInst::Predicate & RHSCC)577 static unsigned foldLogOpOfMaskedICmpsHelper(Value*& A,
578                                              Value*& B, Value*& C,
579                                              Value*& D, Value*& E,
580                                              ICmpInst *LHS, ICmpInst *RHS,
581                                              ICmpInst::Predicate &LHSCC,
582                                              ICmpInst::Predicate &RHSCC) {
583   if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType()) return 0;
584   // vectors are not (yet?) supported
585   if (LHS->getOperand(0)->getType()->isVectorTy()) return 0;
586 
587   // Here comes the tricky part:
588   // LHS might be of the form L11 & L12 == X, X == L21 & L22,
589   // and L11 & L12 == L21 & L22. The same goes for RHS.
590   // Now we must find those components L** and R**, that are equal, so
591   // that we can extract the parameters A, B, C, D, and E for the canonical
592   // above.
593   Value *L1 = LHS->getOperand(0);
594   Value *L2 = LHS->getOperand(1);
595   Value *L11,*L12,*L21,*L22;
596   // Check whether the icmp can be decomposed into a bit test.
597   if (decomposeBitTestICmp(LHS, LHSCC, L11, L12, L2)) {
598     L21 = L22 = L1 = nullptr;
599   } else {
600     // Look for ANDs in the LHS icmp.
601     if (!L1->getType()->isIntegerTy()) {
602       // You can icmp pointers, for example. They really aren't masks.
603       L11 = L12 = nullptr;
604     } else if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) {
605       // Any icmp can be viewed as being trivially masked; if it allows us to
606       // remove one, it's worth it.
607       L11 = L1;
608       L12 = Constant::getAllOnesValue(L1->getType());
609     }
610 
611     if (!L2->getType()->isIntegerTy()) {
612       // You can icmp pointers, for example. They really aren't masks.
613       L21 = L22 = nullptr;
614     } else if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) {
615       L21 = L2;
616       L22 = Constant::getAllOnesValue(L2->getType());
617     }
618   }
619 
620   // Bail if LHS was a icmp that can't be decomposed into an equality.
621   if (!ICmpInst::isEquality(LHSCC))
622     return 0;
623 
624   Value *R1 = RHS->getOperand(0);
625   Value *R2 = RHS->getOperand(1);
626   Value *R11,*R12;
627   bool ok = false;
628   if (decomposeBitTestICmp(RHS, RHSCC, R11, R12, R2)) {
629     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
630       A = R11; D = R12;
631     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
632       A = R12; D = R11;
633     } else {
634       return 0;
635     }
636     E = R2; R1 = nullptr; ok = true;
637   } else if (R1->getType()->isIntegerTy()) {
638     if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) {
639       // As before, model no mask as a trivial mask if it'll let us do an
640       // optimization.
641       R11 = R1;
642       R12 = Constant::getAllOnesValue(R1->getType());
643     }
644 
645     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
646       A = R11; D = R12; E = R2; ok = true;
647     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
648       A = R12; D = R11; E = R2; ok = true;
649     }
650   }
651 
652   // Bail if RHS was a icmp that can't be decomposed into an equality.
653   if (!ICmpInst::isEquality(RHSCC))
654     return 0;
655 
656   // Look for ANDs on the right side of the RHS icmp.
657   if (!ok && R2->getType()->isIntegerTy()) {
658     if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) {
659       R11 = R2;
660       R12 = Constant::getAllOnesValue(R2->getType());
661     }
662 
663     if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) {
664       A = R11; D = R12; E = R1; ok = true;
665     } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) {
666       A = R12; D = R11; E = R1; ok = true;
667     } else {
668       return 0;
669     }
670   }
671   if (!ok)
672     return 0;
673 
674   if (L11 == A) {
675     B = L12; C = L2;
676   } else if (L12 == A) {
677     B = L11; C = L2;
678   } else if (L21 == A) {
679     B = L22; C = L1;
680   } else if (L22 == A) {
681     B = L21; C = L1;
682   }
683 
684   unsigned LeftType = getTypeOfMaskedICmp(A, B, C, LHSCC);
685   unsigned RightType = getTypeOfMaskedICmp(A, D, E, RHSCC);
686   return LeftType & RightType;
687 }
688 
689 /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E)
690 /// into a single (icmp(A & X) ==/!= Y).
foldLogOpOfMaskedICmps(ICmpInst * LHS,ICmpInst * RHS,bool IsAnd,llvm::InstCombiner::BuilderTy * Builder)691 static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd,
692                                      llvm::InstCombiner::BuilderTy *Builder) {
693   Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr;
694   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
695   unsigned Mask = foldLogOpOfMaskedICmpsHelper(A, B, C, D, E, LHS, RHS,
696                                                LHSCC, RHSCC);
697   if (Mask == 0) return nullptr;
698   assert(ICmpInst::isEquality(LHSCC) && ICmpInst::isEquality(RHSCC) &&
699          "foldLogOpOfMaskedICmpsHelper must return an equality predicate.");
700 
701   // In full generality:
702   //     (icmp (A & B) Op C) | (icmp (A & D) Op E)
703   // ==  ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ]
704   //
705   // If the latter can be converted into (icmp (A & X) Op Y) then the former is
706   // equivalent to (icmp (A & X) !Op Y).
707   //
708   // Therefore, we can pretend for the rest of this function that we're dealing
709   // with the conjunction, provided we flip the sense of any comparisons (both
710   // input and output).
711 
712   // In most cases we're going to produce an EQ for the "&&" case.
713   ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
714   if (!IsAnd) {
715     // Convert the masking analysis into its equivalent with negated
716     // comparisons.
717     Mask = conjugateICmpMask(Mask);
718   }
719 
720   if (Mask & FoldMskICmp_Mask_AllZeroes) {
721     // (icmp eq (A & B), 0) & (icmp eq (A & D), 0)
722     // -> (icmp eq (A & (B|D)), 0)
723     Value *NewOr = Builder->CreateOr(B, D);
724     Value *NewAnd = Builder->CreateAnd(A, NewOr);
725     // We can't use C as zero because we might actually handle
726     //   (icmp ne (A & B), B) & (icmp ne (A & D), D)
727     // with B and D, having a single bit set.
728     Value *Zero = Constant::getNullValue(A->getType());
729     return Builder->CreateICmp(NewCC, NewAnd, Zero);
730   }
731   if (Mask & FoldMskICmp_BMask_AllOnes) {
732     // (icmp eq (A & B), B) & (icmp eq (A & D), D)
733     // -> (icmp eq (A & (B|D)), (B|D))
734     Value *NewOr = Builder->CreateOr(B, D);
735     Value *NewAnd = Builder->CreateAnd(A, NewOr);
736     return Builder->CreateICmp(NewCC, NewAnd, NewOr);
737   }
738   if (Mask & FoldMskICmp_AMask_AllOnes) {
739     // (icmp eq (A & B), A) & (icmp eq (A & D), A)
740     // -> (icmp eq (A & (B&D)), A)
741     Value *NewAnd1 = Builder->CreateAnd(B, D);
742     Value *NewAnd2 = Builder->CreateAnd(A, NewAnd1);
743     return Builder->CreateICmp(NewCC, NewAnd2, A);
744   }
745 
746   // Remaining cases assume at least that B and D are constant, and depend on
747   // their actual values. This isn't strictly necessary, just a "handle the
748   // easy cases for now" decision.
749   ConstantInt *BCst = dyn_cast<ConstantInt>(B);
750   if (!BCst) return nullptr;
751   ConstantInt *DCst = dyn_cast<ConstantInt>(D);
752   if (!DCst) return nullptr;
753 
754   if (Mask & (FoldMskICmp_Mask_NotAllZeroes | FoldMskICmp_BMask_NotAllOnes)) {
755     // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and
756     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
757     //     -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0)
758     // Only valid if one of the masks is a superset of the other (check "B&D" is
759     // the same as either B or D).
760     APInt NewMask = BCst->getValue() & DCst->getValue();
761 
762     if (NewMask == BCst->getValue())
763       return LHS;
764     else if (NewMask == DCst->getValue())
765       return RHS;
766   }
767   if (Mask & FoldMskICmp_AMask_NotAllOnes) {
768     // (icmp ne (A & B), B) & (icmp ne (A & D), D)
769     //     -> (icmp ne (A & B), A) or (icmp ne (A & D), A)
770     // Only valid if one of the masks is a superset of the other (check "B|D" is
771     // the same as either B or D).
772     APInt NewMask = BCst->getValue() | DCst->getValue();
773 
774     if (NewMask == BCst->getValue())
775       return LHS;
776     else if (NewMask == DCst->getValue())
777       return RHS;
778   }
779   if (Mask & FoldMskICmp_BMask_Mixed) {
780     // (icmp eq (A & B), C) & (icmp eq (A & D), E)
781     // We already know that B & C == C && D & E == E.
782     // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of
783     // C and E, which are shared by both the mask B and the mask D, don't
784     // contradict, then we can transform to
785     // -> (icmp eq (A & (B|D)), (C|E))
786     // Currently, we only handle the case of B, C, D, and E being constant.
787     // We can't simply use C and E because we might actually handle
788     //   (icmp ne (A & B), B) & (icmp eq (A & D), D)
789     // with B and D, having a single bit set.
790     ConstantInt *CCst = dyn_cast<ConstantInt>(C);
791     if (!CCst) return nullptr;
792     ConstantInt *ECst = dyn_cast<ConstantInt>(E);
793     if (!ECst) return nullptr;
794     if (LHSCC != NewCC)
795       CCst = cast<ConstantInt>(ConstantExpr::getXor(BCst, CCst));
796     if (RHSCC != NewCC)
797       ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst));
798     // If there is a conflict, we should actually return a false for the
799     // whole construct.
800     if (((BCst->getValue() & DCst->getValue()) &
801          (CCst->getValue() ^ ECst->getValue())) != 0)
802       return ConstantInt::get(LHS->getType(), !IsAnd);
803     Value *NewOr1 = Builder->CreateOr(B, D);
804     Value *NewOr2 = ConstantExpr::getOr(CCst, ECst);
805     Value *NewAnd = Builder->CreateAnd(A, NewOr1);
806     return Builder->CreateICmp(NewCC, NewAnd, NewOr2);
807   }
808   return nullptr;
809 }
810 
811 /// Try to fold a signed range checked with lower bound 0 to an unsigned icmp.
812 /// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
813 /// If \p Inverted is true then the check is for the inverted range, e.g.
814 /// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
simplifyRangeCheck(ICmpInst * Cmp0,ICmpInst * Cmp1,bool Inverted)815 Value *InstCombiner::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1,
816                                         bool Inverted) {
817   // Check the lower range comparison, e.g. x >= 0
818   // InstCombine already ensured that if there is a constant it's on the RHS.
819   ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1));
820   if (!RangeStart)
821     return nullptr;
822 
823   ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() :
824                                Cmp0->getPredicate());
825 
826   // Accept x > -1 or x >= 0 (after potentially inverting the predicate).
827   if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) ||
828         (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero())))
829     return nullptr;
830 
831   ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() :
832                                Cmp1->getPredicate());
833 
834   Value *Input = Cmp0->getOperand(0);
835   Value *RangeEnd;
836   if (Cmp1->getOperand(0) == Input) {
837     // For the upper range compare we have: icmp x, n
838     RangeEnd = Cmp1->getOperand(1);
839   } else if (Cmp1->getOperand(1) == Input) {
840     // For the upper range compare we have: icmp n, x
841     RangeEnd = Cmp1->getOperand(0);
842     Pred1 = ICmpInst::getSwappedPredicate(Pred1);
843   } else {
844     return nullptr;
845   }
846 
847   // Check the upper range comparison, e.g. x < n
848   ICmpInst::Predicate NewPred;
849   switch (Pred1) {
850     case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break;
851     case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break;
852     default: return nullptr;
853   }
854 
855   // This simplification is only valid if the upper range is not negative.
856   bool IsNegative, IsNotNegative;
857   ComputeSignBit(RangeEnd, IsNotNegative, IsNegative, /*Depth=*/0, Cmp1);
858   if (!IsNotNegative)
859     return nullptr;
860 
861   if (Inverted)
862     NewPred = ICmpInst::getInversePredicate(NewPred);
863 
864   return Builder->CreateICmp(NewPred, Input, RangeEnd);
865 }
866 
867 /// Fold (icmp)&(icmp) if possible.
FoldAndOfICmps(ICmpInst * LHS,ICmpInst * RHS)868 Value *InstCombiner::FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS) {
869   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
870 
871   // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
872   if (PredicatesFoldable(LHSCC, RHSCC)) {
873     if (LHS->getOperand(0) == RHS->getOperand(1) &&
874         LHS->getOperand(1) == RHS->getOperand(0))
875       LHS->swapOperands();
876     if (LHS->getOperand(0) == RHS->getOperand(0) &&
877         LHS->getOperand(1) == RHS->getOperand(1)) {
878       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
879       unsigned Code = getICmpCode(LHS) & getICmpCode(RHS);
880       bool isSigned = LHS->isSigned() || RHS->isSigned();
881       return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
882     }
883   }
884 
885   // handle (roughly):  (icmp eq (A & B), C) & (icmp eq (A & D), E)
886   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, true, Builder))
887     return V;
888 
889   // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n
890   if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/false))
891     return V;
892 
893   // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n
894   if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/false))
895     return V;
896 
897   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
898   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
899   ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
900   ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
901   if (!LHSCst || !RHSCst) return nullptr;
902 
903   if (LHSCst == RHSCst && LHSCC == RHSCC) {
904     // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
905     // where C is a power of 2 or
906     // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
907     if ((LHSCC == ICmpInst::ICMP_ULT && LHSCst->getValue().isPowerOf2()) ||
908         (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero())) {
909       Value *NewOr = Builder->CreateOr(Val, Val2);
910       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
911     }
912   }
913 
914   // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2
915   // where CMAX is the all ones value for the truncated type,
916   // iff the lower bits of C2 and CA are zero.
917   if (LHSCC == ICmpInst::ICMP_EQ && LHSCC == RHSCC &&
918       LHS->hasOneUse() && RHS->hasOneUse()) {
919     Value *V;
920     ConstantInt *AndCst, *SmallCst = nullptr, *BigCst = nullptr;
921 
922     // (trunc x) == C1 & (and x, CA) == C2
923     // (and x, CA) == C2 & (trunc x) == C1
924     if (match(Val2, m_Trunc(m_Value(V))) &&
925         match(Val, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
926       SmallCst = RHSCst;
927       BigCst = LHSCst;
928     } else if (match(Val, m_Trunc(m_Value(V))) &&
929                match(Val2, m_And(m_Specific(V), m_ConstantInt(AndCst)))) {
930       SmallCst = LHSCst;
931       BigCst = RHSCst;
932     }
933 
934     if (SmallCst && BigCst) {
935       unsigned BigBitSize = BigCst->getType()->getBitWidth();
936       unsigned SmallBitSize = SmallCst->getType()->getBitWidth();
937 
938       // Check that the low bits are zero.
939       APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize);
940       if ((Low & AndCst->getValue()) == 0 && (Low & BigCst->getValue()) == 0) {
941         Value *NewAnd = Builder->CreateAnd(V, Low | AndCst->getValue());
942         APInt N = SmallCst->getValue().zext(BigBitSize) | BigCst->getValue();
943         Value *NewVal = ConstantInt::get(AndCst->getType()->getContext(), N);
944         return Builder->CreateICmp(LHSCC, NewAnd, NewVal);
945       }
946     }
947   }
948 
949   // From here on, we only handle:
950   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
951   if (Val != Val2) return nullptr;
952 
953   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
954   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
955       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
956       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
957       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
958     return nullptr;
959 
960   // We can't fold (ugt x, C) & (sgt x, C2).
961   if (!PredicatesFoldable(LHSCC, RHSCC))
962     return nullptr;
963 
964   // Ensure that the larger constant is on the RHS.
965   bool ShouldSwap;
966   if (CmpInst::isSigned(LHSCC) ||
967       (ICmpInst::isEquality(LHSCC) &&
968        CmpInst::isSigned(RHSCC)))
969     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
970   else
971     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
972 
973   if (ShouldSwap) {
974     std::swap(LHS, RHS);
975     std::swap(LHSCst, RHSCst);
976     std::swap(LHSCC, RHSCC);
977   }
978 
979   // At this point, we know we have two icmp instructions
980   // comparing a value against two constants and and'ing the result
981   // together.  Because of the above check, we know that we only have
982   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
983   // (from the icmp folding check above), that the two constants
984   // are not equal and that the larger constant is on the RHS
985   assert(LHSCst != RHSCst && "Compares not folded above?");
986 
987   switch (LHSCC) {
988   default: llvm_unreachable("Unknown integer condition code!");
989   case ICmpInst::ICMP_EQ:
990     switch (RHSCC) {
991     default: llvm_unreachable("Unknown integer condition code!");
992     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
993     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
994     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
995       return LHS;
996     }
997   case ICmpInst::ICMP_NE:
998     switch (RHSCC) {
999     default: llvm_unreachable("Unknown integer condition code!");
1000     case ICmpInst::ICMP_ULT:
1001       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
1002         return Builder->CreateICmpULT(Val, LHSCst);
1003       if (LHSCst->isNullValue())    // (X !=  0 & X u< 14) -> X-1 u< 13
1004         return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
1005       break;                        // (X != 13 & X u< 15) -> no change
1006     case ICmpInst::ICMP_SLT:
1007       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
1008         return Builder->CreateICmpSLT(Val, LHSCst);
1009       break;                        // (X != 13 & X s< 15) -> no change
1010     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
1011     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
1012     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
1013       return RHS;
1014     case ICmpInst::ICMP_NE:
1015       // Special case to get the ordering right when the values wrap around
1016       // zero.
1017       if (LHSCst->getValue() == 0 && RHSCst->getValue().isAllOnesValue())
1018         std::swap(LHSCst, RHSCst);
1019       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
1020         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1021         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1022         return Builder->CreateICmpUGT(Add, ConstantInt::get(Add->getType(), 1),
1023                                       Val->getName()+".cmp");
1024       }
1025       break;                        // (X != 13 & X != 15) -> no change
1026     }
1027     break;
1028   case ICmpInst::ICMP_ULT:
1029     switch (RHSCC) {
1030     default: llvm_unreachable("Unknown integer condition code!");
1031     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
1032     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
1033       return ConstantInt::get(CmpInst::makeCmpResultType(LHS->getType()), 0);
1034     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
1035       break;
1036     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
1037     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
1038       return LHS;
1039     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
1040       break;
1041     }
1042     break;
1043   case ICmpInst::ICMP_SLT:
1044     switch (RHSCC) {
1045     default: llvm_unreachable("Unknown integer condition code!");
1046     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
1047       break;
1048     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
1049     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
1050       return LHS;
1051     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
1052       break;
1053     }
1054     break;
1055   case ICmpInst::ICMP_UGT:
1056     switch (RHSCC) {
1057     default: llvm_unreachable("Unknown integer condition code!");
1058     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
1059     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
1060       return RHS;
1061     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
1062       break;
1063     case ICmpInst::ICMP_NE:
1064       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
1065         return Builder->CreateICmp(LHSCC, Val, RHSCst);
1066       break;                        // (X u> 13 & X != 15) -> no change
1067     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
1068       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true);
1069     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
1070       break;
1071     }
1072     break;
1073   case ICmpInst::ICMP_SGT:
1074     switch (RHSCC) {
1075     default: llvm_unreachable("Unknown integer condition code!");
1076     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
1077     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
1078       return RHS;
1079     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
1080       break;
1081     case ICmpInst::ICMP_NE:
1082       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
1083         return Builder->CreateICmp(LHSCC, Val, RHSCst);
1084       break;                        // (X s> 13 & X != 15) -> no change
1085     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
1086       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true);
1087     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
1088       break;
1089     }
1090     break;
1091   }
1092 
1093   return nullptr;
1094 }
1095 
1096 /// Optimize (fcmp)&(fcmp).  NOTE: Unlike the rest of instcombine, this returns
1097 /// a Value which should already be inserted into the function.
FoldAndOfFCmps(FCmpInst * LHS,FCmpInst * RHS)1098 Value *InstCombiner::FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
1099   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
1100   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
1101   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
1102 
1103   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
1104     // Swap RHS operands to match LHS.
1105     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
1106     std::swap(Op1LHS, Op1RHS);
1107   }
1108 
1109   // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
1110   // Suppose the relation between x and y is R, where R is one of
1111   // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for
1112   // testing the desired relations.
1113   //
1114   // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
1115   //    bool(R & CC0) && bool(R & CC1)
1116   //  = bool((R & CC0) & (R & CC1))
1117   //  = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency
1118   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
1119     return getFCmpValue(getFCmpCode(Op0CC) & getFCmpCode(Op1CC), Op0LHS, Op0RHS,
1120                         Builder);
1121 
1122   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
1123       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
1124     if (LHS->getOperand(0)->getType() != RHS->getOperand(0)->getType())
1125       return nullptr;
1126 
1127     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
1128     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
1129       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
1130         // If either of the constants are nans, then the whole thing returns
1131         // false.
1132         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
1133           return Builder->getFalse();
1134         return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
1135       }
1136 
1137     // Handle vector zeros.  This occurs because the canonical form of
1138     // "fcmp ord x,x" is "fcmp ord x, 0".
1139     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
1140         isa<ConstantAggregateZero>(RHS->getOperand(1)))
1141       return Builder->CreateFCmpORD(LHS->getOperand(0), RHS->getOperand(0));
1142     return nullptr;
1143   }
1144 
1145   return nullptr;
1146 }
1147 
1148 /// Match De Morgan's Laws:
1149 /// (~A & ~B) == (~(A | B))
1150 /// (~A | ~B) == (~(A & B))
matchDeMorgansLaws(BinaryOperator & I,InstCombiner::BuilderTy * Builder)1151 static Instruction *matchDeMorgansLaws(BinaryOperator &I,
1152                                        InstCombiner::BuilderTy *Builder) {
1153   auto Opcode = I.getOpcode();
1154   assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1155          "Trying to match De Morgan's Laws with something other than and/or");
1156   // Flip the logic operation.
1157   if (Opcode == Instruction::And)
1158     Opcode = Instruction::Or;
1159   else
1160     Opcode = Instruction::And;
1161 
1162   Value *Op0 = I.getOperand(0);
1163   Value *Op1 = I.getOperand(1);
1164   // TODO: Use pattern matchers instead of dyn_cast.
1165   if (Value *Op0NotVal = dyn_castNotVal(Op0))
1166     if (Value *Op1NotVal = dyn_castNotVal(Op1))
1167       if (Op0->hasOneUse() && Op1->hasOneUse()) {
1168         Value *LogicOp = Builder->CreateBinOp(Opcode, Op0NotVal, Op1NotVal,
1169                                               I.getName() + ".demorgan");
1170         return BinaryOperator::CreateNot(LogicOp);
1171       }
1172 
1173   // De Morgan's Law in disguise:
1174   // (zext(bool A) ^ 1) & (zext(bool B) ^ 1) -> zext(~(A | B))
1175   // (zext(bool A) ^ 1) | (zext(bool B) ^ 1) -> zext(~(A & B))
1176   Value *A = nullptr;
1177   Value *B = nullptr;
1178   ConstantInt *C1 = nullptr;
1179   if (match(Op0, m_OneUse(m_Xor(m_ZExt(m_Value(A)), m_ConstantInt(C1)))) &&
1180       match(Op1, m_OneUse(m_Xor(m_ZExt(m_Value(B)), m_Specific(C1))))) {
1181     // TODO: This check could be loosened to handle different type sizes.
1182     // Alternatively, we could fix the definition of m_Not to recognize a not
1183     // operation hidden by a zext?
1184     if (A->getType()->isIntegerTy(1) && B->getType()->isIntegerTy(1) &&
1185         C1->isOne()) {
1186       Value *LogicOp = Builder->CreateBinOp(Opcode, A, B,
1187                                             I.getName() + ".demorgan");
1188       Value *Not = Builder->CreateNot(LogicOp);
1189       return CastInst::CreateZExtOrBitCast(Not, I.getType());
1190     }
1191   }
1192 
1193   return nullptr;
1194 }
1195 
foldCastedBitwiseLogic(BinaryOperator & I)1196 Instruction *InstCombiner::foldCastedBitwiseLogic(BinaryOperator &I) {
1197   auto LogicOpc = I.getOpcode();
1198   assert((LogicOpc == Instruction::And || LogicOpc == Instruction::Or ||
1199           LogicOpc == Instruction::Xor) &&
1200          "Unexpected opcode for bitwise logic folding");
1201 
1202   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1203   CastInst *Cast0 = dyn_cast<CastInst>(Op0);
1204   if (!Cast0)
1205     return nullptr;
1206 
1207   // This must be a cast from an integer or integer vector source type to allow
1208   // transformation of the logic operation to the source type.
1209   Type *DestTy = I.getType();
1210   Type *SrcTy = Cast0->getSrcTy();
1211   if (!SrcTy->isIntOrIntVectorTy())
1212     return nullptr;
1213 
1214   // If one operand is a bitcast and the other is a constant, move the logic
1215   // operation ahead of the bitcast. That is, do the logic operation in the
1216   // original type. This can eliminate useless bitcasts and allow normal
1217   // combines that would otherwise be impeded by the bitcast. Canonicalization
1218   // ensures that if there is a constant operand, it will be the second operand.
1219   Value *BC = nullptr;
1220   Constant *C = nullptr;
1221   if ((match(Op0, m_BitCast(m_Value(BC))) && match(Op1, m_Constant(C)))) {
1222     Value *NewConstant = ConstantExpr::getBitCast(C, SrcTy);
1223     Value *NewOp = Builder->CreateBinOp(LogicOpc, BC, NewConstant, I.getName());
1224     return CastInst::CreateBitOrPointerCast(NewOp, DestTy);
1225   }
1226 
1227   CastInst *Cast1 = dyn_cast<CastInst>(Op1);
1228   if (!Cast1)
1229     return nullptr;
1230 
1231   // Both operands of the logic operation are casts. The casts must be of the
1232   // same type for reduction.
1233   auto CastOpcode = Cast0->getOpcode();
1234   if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy())
1235     return nullptr;
1236 
1237   Value *Cast0Src = Cast0->getOperand(0);
1238   Value *Cast1Src = Cast1->getOperand(0);
1239 
1240   // fold (logic (cast A), (cast B)) -> (cast (logic A, B))
1241 
1242   // Only do this if the casts both really cause code to be generated.
1243   if ((!isa<ICmpInst>(Cast0Src) || !isa<ICmpInst>(Cast1Src)) &&
1244       ShouldOptimizeCast(CastOpcode, Cast0Src, DestTy) &&
1245       ShouldOptimizeCast(CastOpcode, Cast1Src, DestTy)) {
1246     Value *NewOp = Builder->CreateBinOp(LogicOpc, Cast0Src, Cast1Src,
1247                                         I.getName());
1248     return CastInst::Create(CastOpcode, NewOp, DestTy);
1249   }
1250 
1251   // For now, only 'and'/'or' have optimizations after this.
1252   if (LogicOpc == Instruction::Xor)
1253     return nullptr;
1254 
1255   // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the
1256   // cast is otherwise not optimizable.  This happens for vector sexts.
1257   ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src);
1258   ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src);
1259   if (ICmp0 && ICmp1) {
1260     Value *Res = LogicOpc == Instruction::And ? FoldAndOfICmps(ICmp0, ICmp1)
1261                                               : FoldOrOfICmps(ICmp0, ICmp1, &I);
1262     if (Res)
1263       return CastInst::Create(CastOpcode, Res, DestTy);
1264     return nullptr;
1265   }
1266 
1267   // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the
1268   // cast is otherwise not optimizable.  This happens for vector sexts.
1269   FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src);
1270   FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src);
1271   if (FCmp0 && FCmp1) {
1272     Value *Res = LogicOpc == Instruction::And ? FoldAndOfFCmps(FCmp0, FCmp1)
1273                                               : FoldOrOfFCmps(FCmp0, FCmp1);
1274     if (Res)
1275       return CastInst::Create(CastOpcode, Res, DestTy);
1276     return nullptr;
1277   }
1278 
1279   return nullptr;
1280 }
1281 
foldBoolSextMaskToSelect(BinaryOperator & I)1282 static Instruction *foldBoolSextMaskToSelect(BinaryOperator &I) {
1283   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1284 
1285   // Canonicalize SExt or Not to the LHS
1286   if (match(Op1, m_SExt(m_Value())) || match(Op1, m_Not(m_Value()))) {
1287     std::swap(Op0, Op1);
1288   }
1289 
1290   // Fold (and (sext bool to A), B) --> (select bool, B, 0)
1291   Value *X = nullptr;
1292   if (match(Op0, m_SExt(m_Value(X))) &&
1293       X->getType()->getScalarType()->isIntegerTy(1)) {
1294     Value *Zero = Constant::getNullValue(Op1->getType());
1295     return SelectInst::Create(X, Op1, Zero);
1296   }
1297 
1298   // Fold (and ~(sext bool to A), B) --> (select bool, 0, B)
1299   if (match(Op0, m_Not(m_SExt(m_Value(X)))) &&
1300       X->getType()->getScalarType()->isIntegerTy(1)) {
1301     Value *Zero = Constant::getNullValue(Op0->getType());
1302     return SelectInst::Create(X, Zero, Op1);
1303   }
1304 
1305   return nullptr;
1306 }
1307 
visitAnd(BinaryOperator & I)1308 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1309   bool Changed = SimplifyAssociativeOrCommutative(I);
1310   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1311 
1312   if (Value *V = SimplifyVectorOp(I))
1313     return replaceInstUsesWith(I, V);
1314 
1315   if (Value *V = SimplifyAndInst(Op0, Op1, DL, TLI, DT, AC))
1316     return replaceInstUsesWith(I, V);
1317 
1318   // (A|B)&(A|C) -> A|(B&C) etc
1319   if (Value *V = SimplifyUsingDistributiveLaws(I))
1320     return replaceInstUsesWith(I, V);
1321 
1322   // See if we can simplify any instructions used by the instruction whose sole
1323   // purpose is to compute bits we don't care about.
1324   if (SimplifyDemandedInstructionBits(I))
1325     return &I;
1326 
1327   if (Value *V = SimplifyBSwap(I))
1328     return replaceInstUsesWith(I, V);
1329 
1330   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
1331     const APInt &AndRHSMask = AndRHS->getValue();
1332 
1333     // Optimize a variety of ((val OP C1) & C2) combinations...
1334     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1335       Value *Op0LHS = Op0I->getOperand(0);
1336       Value *Op0RHS = Op0I->getOperand(1);
1337       switch (Op0I->getOpcode()) {
1338       default: break;
1339       case Instruction::Xor:
1340       case Instruction::Or: {
1341         // If the mask is only needed on one incoming arm, push it up.
1342         if (!Op0I->hasOneUse()) break;
1343 
1344         APInt NotAndRHS(~AndRHSMask);
1345         if (MaskedValueIsZero(Op0LHS, NotAndRHS, 0, &I)) {
1346           // Not masking anything out for the LHS, move to RHS.
1347           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
1348                                              Op0RHS->getName()+".masked");
1349           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
1350         }
1351         if (!isa<Constant>(Op0RHS) &&
1352             MaskedValueIsZero(Op0RHS, NotAndRHS, 0, &I)) {
1353           // Not masking anything out for the RHS, move to LHS.
1354           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
1355                                              Op0LHS->getName()+".masked");
1356           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
1357         }
1358 
1359         break;
1360       }
1361       case Instruction::Add:
1362         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1363         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1364         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1365         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1366           return BinaryOperator::CreateAnd(V, AndRHS);
1367         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1368           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
1369         break;
1370 
1371       case Instruction::Sub:
1372         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1373         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1374         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1375         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1376           return BinaryOperator::CreateAnd(V, AndRHS);
1377 
1378         // -x & 1 -> x & 1
1379         if (AndRHSMask == 1 && match(Op0LHS, m_Zero()))
1380           return BinaryOperator::CreateAnd(Op0RHS, AndRHS);
1381 
1382         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
1383         // has 1's for all bits that the subtraction with A might affect.
1384         if (Op0I->hasOneUse() && !match(Op0LHS, m_Zero())) {
1385           uint32_t BitWidth = AndRHSMask.getBitWidth();
1386           uint32_t Zeros = AndRHSMask.countLeadingZeros();
1387           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
1388 
1389           if (MaskedValueIsZero(Op0LHS, Mask, 0, &I)) {
1390             Value *NewNeg = Builder->CreateNeg(Op0RHS);
1391             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
1392           }
1393         }
1394         break;
1395 
1396       case Instruction::Shl:
1397       case Instruction::LShr:
1398         // (1 << x) & 1 --> zext(x == 0)
1399         // (1 >> x) & 1 --> zext(x == 0)
1400         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
1401           Value *NewICmp =
1402             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
1403           return new ZExtInst(NewICmp, I.getType());
1404         }
1405         break;
1406       }
1407 
1408       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1409         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1410           return Res;
1411     }
1412 
1413     // If this is an integer truncation, and if the source is an 'and' with
1414     // immediate, transform it.  This frequently occurs for bitfield accesses.
1415     {
1416       Value *X = nullptr; ConstantInt *YC = nullptr;
1417       if (match(Op0, m_Trunc(m_And(m_Value(X), m_ConstantInt(YC))))) {
1418         // Change: and (trunc (and X, YC) to T), C2
1419         // into  : and (trunc X to T), trunc(YC) & C2
1420         // This will fold the two constants together, which may allow
1421         // other simplifications.
1422         Value *NewCast = Builder->CreateTrunc(X, I.getType(), "and.shrunk");
1423         Constant *C3 = ConstantExpr::getTrunc(YC, I.getType());
1424         C3 = ConstantExpr::getAnd(C3, AndRHS);
1425         return BinaryOperator::CreateAnd(NewCast, C3);
1426       }
1427     }
1428 
1429     // Try to fold constant and into select arguments.
1430     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1431       if (Instruction *R = FoldOpIntoSelect(I, SI))
1432         return R;
1433     if (isa<PHINode>(Op0))
1434       if (Instruction *NV = FoldOpIntoPhi(I))
1435         return NV;
1436   }
1437 
1438   if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
1439     return DeMorgan;
1440 
1441   {
1442     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
1443     // (A|B) & ~(A&B) -> A^B
1444     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1445         match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1446         ((A == C && B == D) || (A == D && B == C)))
1447       return BinaryOperator::CreateXor(A, B);
1448 
1449     // ~(A&B) & (A|B) -> A^B
1450     if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1451         match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
1452         ((A == C && B == D) || (A == D && B == C)))
1453       return BinaryOperator::CreateXor(A, B);
1454 
1455     // A&(A^B) => A & ~B
1456     {
1457       Value *tmpOp0 = Op0;
1458       Value *tmpOp1 = Op1;
1459       if (match(Op0, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
1460         if (A == Op1 || B == Op1 ) {
1461           tmpOp1 = Op0;
1462           tmpOp0 = Op1;
1463           // Simplify below
1464         }
1465       }
1466 
1467       if (match(tmpOp1, m_OneUse(m_Xor(m_Value(A), m_Value(B))))) {
1468         if (B == tmpOp0) {
1469           std::swap(A, B);
1470         }
1471         // Notice that the pattern (A&(~B)) is actually (A&(-1^B)), so if
1472         // A is originally -1 (or a vector of -1 and undefs), then we enter
1473         // an endless loop. By checking that A is non-constant we ensure that
1474         // we will never get to the loop.
1475         if (A == tmpOp0 && !isa<Constant>(A)) // A&(A^B) -> A & ~B
1476           return BinaryOperator::CreateAnd(A, Builder->CreateNot(B));
1477       }
1478     }
1479 
1480     // (A&((~A)|B)) -> A&B
1481     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
1482         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
1483       return BinaryOperator::CreateAnd(A, Op1);
1484     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
1485         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
1486       return BinaryOperator::CreateAnd(A, Op0);
1487 
1488     // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C
1489     if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
1490       if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
1491         if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
1492           return BinaryOperator::CreateAnd(Op0, Builder->CreateNot(C));
1493 
1494     // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C
1495     if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
1496       if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
1497         if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
1498           return BinaryOperator::CreateAnd(Op1, Builder->CreateNot(C));
1499 
1500     // (A | B) & ((~A) ^ B) -> (A & B)
1501     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1502         match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
1503       return BinaryOperator::CreateAnd(A, B);
1504 
1505     // ((~A) ^ B) & (A | B) -> (A & B)
1506     if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
1507         match(Op1, m_Or(m_Specific(A), m_Specific(B))))
1508       return BinaryOperator::CreateAnd(A, B);
1509   }
1510 
1511   {
1512     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
1513     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
1514     if (LHS && RHS)
1515       if (Value *Res = FoldAndOfICmps(LHS, RHS))
1516         return replaceInstUsesWith(I, Res);
1517 
1518     // TODO: Make this recursive; it's a little tricky because an arbitrary
1519     // number of 'and' instructions might have to be created.
1520     Value *X, *Y;
1521     if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1522       if (auto *Cmp = dyn_cast<ICmpInst>(X))
1523         if (Value *Res = FoldAndOfICmps(LHS, Cmp))
1524           return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1525       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1526         if (Value *Res = FoldAndOfICmps(LHS, Cmp))
1527           return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1528     }
1529     if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) {
1530       if (auto *Cmp = dyn_cast<ICmpInst>(X))
1531         if (Value *Res = FoldAndOfICmps(Cmp, RHS))
1532           return replaceInstUsesWith(I, Builder->CreateAnd(Res, Y));
1533       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
1534         if (Value *Res = FoldAndOfICmps(Cmp, RHS))
1535           return replaceInstUsesWith(I, Builder->CreateAnd(Res, X));
1536     }
1537   }
1538 
1539   // If and'ing two fcmp, try combine them into one.
1540   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
1541     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
1542       if (Value *Res = FoldAndOfFCmps(LHS, RHS))
1543         return replaceInstUsesWith(I, Res);
1544 
1545   if (Instruction *CastedAnd = foldCastedBitwiseLogic(I))
1546     return CastedAnd;
1547 
1548   if (Instruction *Select = foldBoolSextMaskToSelect(I))
1549     return Select;
1550 
1551   return Changed ? &I : nullptr;
1552 }
1553 
1554 /// Given an OR instruction, check to see if this is a bswap idiom. If so,
1555 /// insert the new intrinsic and return it.
MatchBSwap(BinaryOperator & I)1556 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
1557   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1558 
1559   // Look through zero extends.
1560   if (Instruction *Ext = dyn_cast<ZExtInst>(Op0))
1561     Op0 = Ext->getOperand(0);
1562 
1563   if (Instruction *Ext = dyn_cast<ZExtInst>(Op1))
1564     Op1 = Ext->getOperand(0);
1565 
1566   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
1567   bool OrOfOrs = match(Op0, m_Or(m_Value(), m_Value())) ||
1568                  match(Op1, m_Or(m_Value(), m_Value()));
1569 
1570   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
1571   bool OrOfShifts = match(Op0, m_LogicalShift(m_Value(), m_Value())) &&
1572                     match(Op1, m_LogicalShift(m_Value(), m_Value()));
1573 
1574   // (A & B) | (C & D)                              -> bswap if possible.
1575   bool OrOfAnds = match(Op0, m_And(m_Value(), m_Value())) &&
1576                   match(Op1, m_And(m_Value(), m_Value()));
1577 
1578   if (!OrOfOrs && !OrOfShifts && !OrOfAnds)
1579     return nullptr;
1580 
1581   SmallVector<Instruction*, 4> Insts;
1582   if (!recognizeBSwapOrBitReverseIdiom(&I, true, false, Insts))
1583     return nullptr;
1584   Instruction *LastInst = Insts.pop_back_val();
1585   LastInst->removeFromParent();
1586 
1587   for (auto *Inst : Insts)
1588     Worklist.Add(Inst);
1589   return LastInst;
1590 }
1591 
1592 /// If all elements of two constant vectors are 0/-1 and inverses, return true.
areInverseVectorBitmasks(Constant * C1,Constant * C2)1593 static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) {
1594   unsigned NumElts = C1->getType()->getVectorNumElements();
1595   for (unsigned i = 0; i != NumElts; ++i) {
1596     Constant *EltC1 = C1->getAggregateElement(i);
1597     Constant *EltC2 = C2->getAggregateElement(i);
1598     if (!EltC1 || !EltC2)
1599       return false;
1600 
1601     // One element must be all ones, and the other must be all zeros.
1602     // FIXME: Allow undef elements.
1603     if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) ||
1604           (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes()))))
1605       return false;
1606   }
1607   return true;
1608 }
1609 
1610 /// We have an expression of the form (A & C) | (B & D). If A is a scalar or
1611 /// vector composed of all-zeros or all-ones values and is the bitwise 'not' of
1612 /// B, it can be used as the condition operand of a select instruction.
getSelectCondition(Value * A,Value * B,InstCombiner::BuilderTy & Builder)1613 static Value *getSelectCondition(Value *A, Value *B,
1614                                  InstCombiner::BuilderTy &Builder) {
1615   // If these are scalars or vectors of i1, A can be used directly.
1616   Type *Ty = A->getType();
1617   if (match(A, m_Not(m_Specific(B))) && Ty->getScalarType()->isIntegerTy(1))
1618     return A;
1619 
1620   // If A and B are sign-extended, look through the sexts to find the booleans.
1621   Value *Cond;
1622   if (match(A, m_SExt(m_Value(Cond))) &&
1623       Cond->getType()->getScalarType()->isIntegerTy(1) &&
1624       match(B, m_CombineOr(m_Not(m_SExt(m_Specific(Cond))),
1625                            m_SExt(m_Not(m_Specific(Cond))))))
1626     return Cond;
1627 
1628   // All scalar (and most vector) possibilities should be handled now.
1629   // Try more matches that only apply to non-splat constant vectors.
1630   if (!Ty->isVectorTy())
1631     return nullptr;
1632 
1633   // If both operands are constants, see if the constants are inverse bitmasks.
1634   Constant *AC, *BC;
1635   if (match(A, m_Constant(AC)) && match(B, m_Constant(BC)) &&
1636       areInverseVectorBitmasks(AC, BC))
1637     return ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1638 
1639   // If both operands are xor'd with constants using the same sexted boolean
1640   // operand, see if the constants are inverse bitmasks.
1641   if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AC)))) &&
1642       match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BC)))) &&
1643       Cond->getType()->getScalarType()->isIntegerTy(1) &&
1644       areInverseVectorBitmasks(AC, BC)) {
1645     AC = ConstantExpr::getTrunc(AC, CmpInst::makeCmpResultType(Ty));
1646     return Builder.CreateXor(Cond, AC);
1647   }
1648   return nullptr;
1649 }
1650 
1651 /// We have an expression of the form (A & C) | (B & D). Try to simplify this
1652 /// to "A' ? C : D", where A' is a boolean or vector of booleans.
matchSelectFromAndOr(Value * A,Value * C,Value * B,Value * D,InstCombiner::BuilderTy & Builder)1653 static Value *matchSelectFromAndOr(Value *A, Value *C, Value *B, Value *D,
1654                                    InstCombiner::BuilderTy &Builder) {
1655   // The potential condition of the select may be bitcasted. In that case, look
1656   // through its bitcast and the corresponding bitcast of the 'not' condition.
1657   Type *OrigType = A->getType();
1658   Value *SrcA, *SrcB;
1659   if (match(A, m_OneUse(m_BitCast(m_Value(SrcA)))) &&
1660       match(B, m_OneUse(m_BitCast(m_Value(SrcB))))) {
1661     A = SrcA;
1662     B = SrcB;
1663   }
1664 
1665   if (Value *Cond = getSelectCondition(A, B, Builder)) {
1666     // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D))
1667     // The bitcasts will either all exist or all not exist. The builder will
1668     // not create unnecessary casts if the types already match.
1669     Value *BitcastC = Builder.CreateBitCast(C, A->getType());
1670     Value *BitcastD = Builder.CreateBitCast(D, A->getType());
1671     Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD);
1672     return Builder.CreateBitCast(Select, OrigType);
1673   }
1674 
1675   return nullptr;
1676 }
1677 
1678 /// Fold (icmp)|(icmp) if possible.
FoldOrOfICmps(ICmpInst * LHS,ICmpInst * RHS,Instruction * CxtI)1679 Value *InstCombiner::FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS,
1680                                    Instruction *CxtI) {
1681   ICmpInst::Predicate LHSCC = LHS->getPredicate(), RHSCC = RHS->getPredicate();
1682 
1683   // Fold (iszero(A & K1) | iszero(A & K2)) ->  (A & (K1 | K2)) != (K1 | K2)
1684   // if K1 and K2 are a one-bit mask.
1685   ConstantInt *LHSCst = dyn_cast<ConstantInt>(LHS->getOperand(1));
1686   ConstantInt *RHSCst = dyn_cast<ConstantInt>(RHS->getOperand(1));
1687 
1688   if (LHS->getPredicate() == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero() &&
1689       RHS->getPredicate() == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1690 
1691     BinaryOperator *LAnd = dyn_cast<BinaryOperator>(LHS->getOperand(0));
1692     BinaryOperator *RAnd = dyn_cast<BinaryOperator>(RHS->getOperand(0));
1693     if (LAnd && RAnd && LAnd->hasOneUse() && RHS->hasOneUse() &&
1694         LAnd->getOpcode() == Instruction::And &&
1695         RAnd->getOpcode() == Instruction::And) {
1696 
1697       Value *Mask = nullptr;
1698       Value *Masked = nullptr;
1699       if (LAnd->getOperand(0) == RAnd->getOperand(0) &&
1700           isKnownToBeAPowerOfTwo(LAnd->getOperand(1), DL, false, 0, AC, CxtI,
1701                                  DT) &&
1702           isKnownToBeAPowerOfTwo(RAnd->getOperand(1), DL, false, 0, AC, CxtI,
1703                                  DT)) {
1704         Mask = Builder->CreateOr(LAnd->getOperand(1), RAnd->getOperand(1));
1705         Masked = Builder->CreateAnd(LAnd->getOperand(0), Mask);
1706       } else if (LAnd->getOperand(1) == RAnd->getOperand(1) &&
1707                  isKnownToBeAPowerOfTwo(LAnd->getOperand(0), DL, false, 0, AC,
1708                                         CxtI, DT) &&
1709                  isKnownToBeAPowerOfTwo(RAnd->getOperand(0), DL, false, 0, AC,
1710                                         CxtI, DT)) {
1711         Mask = Builder->CreateOr(LAnd->getOperand(0), RAnd->getOperand(0));
1712         Masked = Builder->CreateAnd(LAnd->getOperand(1), Mask);
1713       }
1714 
1715       if (Masked)
1716         return Builder->CreateICmp(ICmpInst::ICMP_NE, Masked, Mask);
1717     }
1718   }
1719 
1720   // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3)
1721   //                   -->  (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3)
1722   // The original condition actually refers to the following two ranges:
1723   // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3]
1724   // We can fold these two ranges if:
1725   // 1) C1 and C2 is unsigned greater than C3.
1726   // 2) The two ranges are separated.
1727   // 3) C1 ^ C2 is one-bit mask.
1728   // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask.
1729   // This implies all values in the two ranges differ by exactly one bit.
1730 
1731   if ((LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_ULE) &&
1732       LHSCC == RHSCC && LHSCst && RHSCst && LHS->hasOneUse() &&
1733       RHS->hasOneUse() && LHSCst->getType() == RHSCst->getType() &&
1734       LHSCst->getValue() == (RHSCst->getValue())) {
1735 
1736     Value *LAdd = LHS->getOperand(0);
1737     Value *RAdd = RHS->getOperand(0);
1738 
1739     Value *LAddOpnd, *RAddOpnd;
1740     ConstantInt *LAddCst, *RAddCst;
1741     if (match(LAdd, m_Add(m_Value(LAddOpnd), m_ConstantInt(LAddCst))) &&
1742         match(RAdd, m_Add(m_Value(RAddOpnd), m_ConstantInt(RAddCst))) &&
1743         LAddCst->getValue().ugt(LHSCst->getValue()) &&
1744         RAddCst->getValue().ugt(LHSCst->getValue())) {
1745 
1746       APInt DiffCst = LAddCst->getValue() ^ RAddCst->getValue();
1747       if (LAddOpnd == RAddOpnd && DiffCst.isPowerOf2()) {
1748         ConstantInt *MaxAddCst = nullptr;
1749         if (LAddCst->getValue().ult(RAddCst->getValue()))
1750           MaxAddCst = RAddCst;
1751         else
1752           MaxAddCst = LAddCst;
1753 
1754         APInt RRangeLow = -RAddCst->getValue();
1755         APInt RRangeHigh = RRangeLow + LHSCst->getValue();
1756         APInt LRangeLow = -LAddCst->getValue();
1757         APInt LRangeHigh = LRangeLow + LHSCst->getValue();
1758         APInt LowRangeDiff = RRangeLow ^ LRangeLow;
1759         APInt HighRangeDiff = RRangeHigh ^ LRangeHigh;
1760         APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow
1761                                                    : RRangeLow - LRangeLow;
1762 
1763         if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff &&
1764             RangeDiff.ugt(LHSCst->getValue())) {
1765           Value *MaskCst = ConstantInt::get(LAddCst->getType(), ~DiffCst);
1766 
1767           Value *NewAnd = Builder->CreateAnd(LAddOpnd, MaskCst);
1768           Value *NewAdd = Builder->CreateAdd(NewAnd, MaxAddCst);
1769           return (Builder->CreateICmp(LHS->getPredicate(), NewAdd, LHSCst));
1770         }
1771       }
1772     }
1773   }
1774 
1775   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
1776   if (PredicatesFoldable(LHSCC, RHSCC)) {
1777     if (LHS->getOperand(0) == RHS->getOperand(1) &&
1778         LHS->getOperand(1) == RHS->getOperand(0))
1779       LHS->swapOperands();
1780     if (LHS->getOperand(0) == RHS->getOperand(0) &&
1781         LHS->getOperand(1) == RHS->getOperand(1)) {
1782       Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
1783       unsigned Code = getICmpCode(LHS) | getICmpCode(RHS);
1784       bool isSigned = LHS->isSigned() || RHS->isSigned();
1785       return getNewICmpValue(isSigned, Code, Op0, Op1, Builder);
1786     }
1787   }
1788 
1789   // handle (roughly):
1790   // (icmp ne (A & B), C) | (icmp ne (A & D), E)
1791   if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, false, Builder))
1792     return V;
1793 
1794   Value *Val = LHS->getOperand(0), *Val2 = RHS->getOperand(0);
1795   if (LHS->hasOneUse() || RHS->hasOneUse()) {
1796     // (icmp eq B, 0) | (icmp ult A, B) -> (icmp ule A, B-1)
1797     // (icmp eq B, 0) | (icmp ugt B, A) -> (icmp ule A, B-1)
1798     Value *A = nullptr, *B = nullptr;
1799     if (LHSCC == ICmpInst::ICMP_EQ && LHSCst && LHSCst->isZero()) {
1800       B = Val;
1801       if (RHSCC == ICmpInst::ICMP_ULT && Val == RHS->getOperand(1))
1802         A = Val2;
1803       else if (RHSCC == ICmpInst::ICMP_UGT && Val == Val2)
1804         A = RHS->getOperand(1);
1805     }
1806     // (icmp ult A, B) | (icmp eq B, 0) -> (icmp ule A, B-1)
1807     // (icmp ugt B, A) | (icmp eq B, 0) -> (icmp ule A, B-1)
1808     else if (RHSCC == ICmpInst::ICMP_EQ && RHSCst && RHSCst->isZero()) {
1809       B = Val2;
1810       if (LHSCC == ICmpInst::ICMP_ULT && Val2 == LHS->getOperand(1))
1811         A = Val;
1812       else if (LHSCC == ICmpInst::ICMP_UGT && Val2 == Val)
1813         A = LHS->getOperand(1);
1814     }
1815     if (A && B)
1816       return Builder->CreateICmp(
1817           ICmpInst::ICMP_UGE,
1818           Builder->CreateAdd(B, ConstantInt::getSigned(B->getType(), -1)), A);
1819   }
1820 
1821   // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n
1822   if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/true))
1823     return V;
1824 
1825   // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n
1826   if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/true))
1827     return V;
1828 
1829   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
1830   if (!LHSCst || !RHSCst) return nullptr;
1831 
1832   if (LHSCst == RHSCst && LHSCC == RHSCC) {
1833     // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
1834     if (LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
1835       Value *NewOr = Builder->CreateOr(Val, Val2);
1836       return Builder->CreateICmp(LHSCC, NewOr, LHSCst);
1837     }
1838   }
1839 
1840   // (icmp ult (X + CA), C1) | (icmp eq X, C2) -> (icmp ule (X + CA), C1)
1841   //   iff C2 + CA == C1.
1842   if (LHSCC == ICmpInst::ICMP_ULT && RHSCC == ICmpInst::ICMP_EQ) {
1843     ConstantInt *AddCst;
1844     if (match(Val, m_Add(m_Specific(Val2), m_ConstantInt(AddCst))))
1845       if (RHSCst->getValue() + AddCst->getValue() == LHSCst->getValue())
1846         return Builder->CreateICmpULE(Val, LHSCst);
1847   }
1848 
1849   // From here on, we only handle:
1850   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
1851   if (Val != Val2) return nullptr;
1852 
1853   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
1854   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
1855       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
1856       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
1857       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
1858     return nullptr;
1859 
1860   // We can't fold (ugt x, C) | (sgt x, C2).
1861   if (!PredicatesFoldable(LHSCC, RHSCC))
1862     return nullptr;
1863 
1864   // Ensure that the larger constant is on the RHS.
1865   bool ShouldSwap;
1866   if (CmpInst::isSigned(LHSCC) ||
1867       (ICmpInst::isEquality(LHSCC) &&
1868        CmpInst::isSigned(RHSCC)))
1869     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
1870   else
1871     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
1872 
1873   if (ShouldSwap) {
1874     std::swap(LHS, RHS);
1875     std::swap(LHSCst, RHSCst);
1876     std::swap(LHSCC, RHSCC);
1877   }
1878 
1879   // At this point, we know we have two icmp instructions
1880   // comparing a value against two constants and or'ing the result
1881   // together.  Because of the above check, we know that we only have
1882   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
1883   // icmp folding check above), that the two constants are not
1884   // equal.
1885   assert(LHSCst != RHSCst && "Compares not folded above?");
1886 
1887   switch (LHSCC) {
1888   default: llvm_unreachable("Unknown integer condition code!");
1889   case ICmpInst::ICMP_EQ:
1890     switch (RHSCC) {
1891     default: llvm_unreachable("Unknown integer condition code!");
1892     case ICmpInst::ICMP_EQ:
1893       if (LHS->getOperand(0) == RHS->getOperand(0)) {
1894         // if LHSCst and RHSCst differ only by one bit:
1895         // (A == C1 || A == C2) -> (A | (C1 ^ C2)) == C2
1896         assert(LHSCst->getValue().ule(LHSCst->getValue()));
1897 
1898         APInt Xor = LHSCst->getValue() ^ RHSCst->getValue();
1899         if (Xor.isPowerOf2()) {
1900           Value *Cst = Builder->getInt(Xor);
1901           Value *Or = Builder->CreateOr(LHS->getOperand(0), Cst);
1902           return Builder->CreateICmp(ICmpInst::ICMP_EQ, Or, RHSCst);
1903         }
1904       }
1905 
1906       if (LHSCst == SubOne(RHSCst)) {
1907         // (X == 13 | X == 14) -> X-13 <u 2
1908         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1909         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
1910         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1911         return Builder->CreateICmpULT(Add, AddCST);
1912       }
1913 
1914       break;                         // (X == 13 | X == 15) -> no change
1915     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
1916     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
1917       break;
1918     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
1919     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
1920     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
1921       return RHS;
1922     }
1923     break;
1924   case ICmpInst::ICMP_NE:
1925     switch (RHSCC) {
1926     default: llvm_unreachable("Unknown integer condition code!");
1927     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
1928     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
1929     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
1930       return LHS;
1931     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
1932     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
1933     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
1934       return Builder->getTrue();
1935     }
1936   case ICmpInst::ICMP_ULT:
1937     switch (RHSCC) {
1938     default: llvm_unreachable("Unknown integer condition code!");
1939     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
1940       break;
1941     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
1942       // If RHSCst is [us]MAXINT, it is always false.  Not handling
1943       // this can cause overflow.
1944       if (RHSCst->isMaxValue(false))
1945         return LHS;
1946       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false);
1947     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
1948       break;
1949     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
1950     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
1951       return RHS;
1952     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
1953       break;
1954     }
1955     break;
1956   case ICmpInst::ICMP_SLT:
1957     switch (RHSCC) {
1958     default: llvm_unreachable("Unknown integer condition code!");
1959     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
1960       break;
1961     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
1962       // If RHSCst is [us]MAXINT, it is always false.  Not handling
1963       // this can cause overflow.
1964       if (RHSCst->isMaxValue(true))
1965         return LHS;
1966       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false);
1967     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
1968       break;
1969     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
1970     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
1971       return RHS;
1972     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
1973       break;
1974     }
1975     break;
1976   case ICmpInst::ICMP_UGT:
1977     switch (RHSCC) {
1978     default: llvm_unreachable("Unknown integer condition code!");
1979     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
1980     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
1981       return LHS;
1982     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
1983       break;
1984     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
1985     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
1986       return Builder->getTrue();
1987     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
1988       break;
1989     }
1990     break;
1991   case ICmpInst::ICMP_SGT:
1992     switch (RHSCC) {
1993     default: llvm_unreachable("Unknown integer condition code!");
1994     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
1995     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
1996       return LHS;
1997     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
1998       break;
1999     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
2000     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
2001       return Builder->getTrue();
2002     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
2003       break;
2004     }
2005     break;
2006   }
2007   return nullptr;
2008 }
2009 
2010 /// Optimize (fcmp)|(fcmp).  NOTE: Unlike the rest of instcombine, this returns
2011 /// a Value which should already be inserted into the function.
FoldOrOfFCmps(FCmpInst * LHS,FCmpInst * RHS)2012 Value *InstCombiner::FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS) {
2013   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
2014   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
2015   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
2016 
2017   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
2018     // Swap RHS operands to match LHS.
2019     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
2020     std::swap(Op1LHS, Op1RHS);
2021   }
2022 
2023   // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
2024   // This is a similar transformation to the one in FoldAndOfFCmps.
2025   //
2026   // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this:
2027   //    bool(R & CC0) || bool(R & CC1)
2028   //  = bool((R & CC0) | (R & CC1))
2029   //  = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;)
2030   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS)
2031     return getFCmpValue(getFCmpCode(Op0CC) | getFCmpCode(Op1CC), Op0LHS, Op0RHS,
2032                         Builder);
2033 
2034   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
2035       RHS->getPredicate() == FCmpInst::FCMP_UNO &&
2036       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
2037     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
2038       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
2039         // If either of the constants are nans, then the whole thing returns
2040         // true.
2041         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
2042           return Builder->getTrue();
2043 
2044         // Otherwise, no need to compare the two constants, compare the
2045         // rest.
2046         return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
2047       }
2048 
2049     // Handle vector zeros.  This occurs because the canonical form of
2050     // "fcmp uno x,x" is "fcmp uno x, 0".
2051     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
2052         isa<ConstantAggregateZero>(RHS->getOperand(1)))
2053       return Builder->CreateFCmpUNO(LHS->getOperand(0), RHS->getOperand(0));
2054 
2055     return nullptr;
2056   }
2057 
2058   return nullptr;
2059 }
2060 
2061 /// This helper function folds:
2062 ///
2063 ///     ((A | B) & C1) | (B & C2)
2064 ///
2065 /// into:
2066 ///
2067 ///     (A & C1) | B
2068 ///
2069 /// when the XOR of the two constants is "all ones" (-1).
FoldOrWithConstants(BinaryOperator & I,Value * Op,Value * A,Value * B,Value * C)2070 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
2071                                                Value *A, Value *B, Value *C) {
2072   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2073   if (!CI1) return nullptr;
2074 
2075   Value *V1 = nullptr;
2076   ConstantInt *CI2 = nullptr;
2077   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return nullptr;
2078 
2079   APInt Xor = CI1->getValue() ^ CI2->getValue();
2080   if (!Xor.isAllOnesValue()) return nullptr;
2081 
2082   if (V1 == A || V1 == B) {
2083     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
2084     return BinaryOperator::CreateOr(NewOp, V1);
2085   }
2086 
2087   return nullptr;
2088 }
2089 
2090 /// \brief This helper function folds:
2091 ///
2092 ///     ((A | B) & C1) ^ (B & C2)
2093 ///
2094 /// into:
2095 ///
2096 ///     (A & C1) ^ B
2097 ///
2098 /// when the XOR of the two constants is "all ones" (-1).
FoldXorWithConstants(BinaryOperator & I,Value * Op,Value * A,Value * B,Value * C)2099 Instruction *InstCombiner::FoldXorWithConstants(BinaryOperator &I, Value *Op,
2100                                                 Value *A, Value *B, Value *C) {
2101   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
2102   if (!CI1)
2103     return nullptr;
2104 
2105   Value *V1 = nullptr;
2106   ConstantInt *CI2 = nullptr;
2107   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2))))
2108     return nullptr;
2109 
2110   APInt Xor = CI1->getValue() ^ CI2->getValue();
2111   if (!Xor.isAllOnesValue())
2112     return nullptr;
2113 
2114   if (V1 == A || V1 == B) {
2115     Value *NewOp = Builder->CreateAnd(V1 == A ? B : A, CI1);
2116     return BinaryOperator::CreateXor(NewOp, V1);
2117   }
2118 
2119   return nullptr;
2120 }
2121 
visitOr(BinaryOperator & I)2122 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
2123   bool Changed = SimplifyAssociativeOrCommutative(I);
2124   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2125 
2126   if (Value *V = SimplifyVectorOp(I))
2127     return replaceInstUsesWith(I, V);
2128 
2129   if (Value *V = SimplifyOrInst(Op0, Op1, DL, TLI, DT, AC))
2130     return replaceInstUsesWith(I, V);
2131 
2132   // (A&B)|(A&C) -> A&(B|C) etc
2133   if (Value *V = SimplifyUsingDistributiveLaws(I))
2134     return replaceInstUsesWith(I, V);
2135 
2136   // See if we can simplify any instructions used by the instruction whose sole
2137   // purpose is to compute bits we don't care about.
2138   if (SimplifyDemandedInstructionBits(I))
2139     return &I;
2140 
2141   if (Value *V = SimplifyBSwap(I))
2142     return replaceInstUsesWith(I, V);
2143 
2144   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2145     ConstantInt *C1 = nullptr; Value *X = nullptr;
2146     // (X & C1) | C2 --> (X | C2) & (C1|C2)
2147     // iff (C1 & C2) == 0.
2148     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
2149         (RHS->getValue() & C1->getValue()) != 0 &&
2150         Op0->hasOneUse()) {
2151       Value *Or = Builder->CreateOr(X, RHS);
2152       Or->takeName(Op0);
2153       return BinaryOperator::CreateAnd(Or,
2154                              Builder->getInt(RHS->getValue() | C1->getValue()));
2155     }
2156 
2157     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2158     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
2159         Op0->hasOneUse()) {
2160       Value *Or = Builder->CreateOr(X, RHS);
2161       Or->takeName(Op0);
2162       return BinaryOperator::CreateXor(Or,
2163                             Builder->getInt(C1->getValue() & ~RHS->getValue()));
2164     }
2165 
2166     // Try to fold constant and into select arguments.
2167     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2168       if (Instruction *R = FoldOpIntoSelect(I, SI))
2169         return R;
2170 
2171     if (isa<PHINode>(Op0))
2172       if (Instruction *NV = FoldOpIntoPhi(I))
2173         return NV;
2174   }
2175 
2176   // Given an OR instruction, check to see if this is a bswap.
2177   if (Instruction *BSwap = MatchBSwap(I))
2178     return BSwap;
2179 
2180   Value *A = nullptr, *B = nullptr;
2181   ConstantInt *C1 = nullptr, *C2 = nullptr;
2182 
2183   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2184   if (Op0->hasOneUse() &&
2185       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2186       MaskedValueIsZero(Op1, C1->getValue(), 0, &I)) {
2187     Value *NOr = Builder->CreateOr(A, Op1);
2188     NOr->takeName(Op0);
2189     return BinaryOperator::CreateXor(NOr, C1);
2190   }
2191 
2192   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2193   if (Op1->hasOneUse() &&
2194       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2195       MaskedValueIsZero(Op0, C1->getValue(), 0, &I)) {
2196     Value *NOr = Builder->CreateOr(A, Op0);
2197     NOr->takeName(Op0);
2198     return BinaryOperator::CreateXor(NOr, C1);
2199   }
2200 
2201   // ((~A & B) | A) -> (A | B)
2202   if (match(Op0, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2203       match(Op1, m_Specific(A)))
2204     return BinaryOperator::CreateOr(A, B);
2205 
2206   // ((A & B) | ~A) -> (~A | B)
2207   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2208       match(Op1, m_Not(m_Specific(A))))
2209     return BinaryOperator::CreateOr(Builder->CreateNot(A), B);
2210 
2211   // (A & (~B)) | (A ^ B) -> (A ^ B)
2212   if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2213       match(Op1, m_Xor(m_Specific(A), m_Specific(B))))
2214     return BinaryOperator::CreateXor(A, B);
2215 
2216   // (A ^ B) | ( A & (~B)) -> (A ^ B)
2217   if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2218       match(Op1, m_And(m_Specific(A), m_Not(m_Specific(B)))))
2219     return BinaryOperator::CreateXor(A, B);
2220 
2221   // (A & C)|(B & D)
2222   Value *C = nullptr, *D = nullptr;
2223   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
2224       match(Op1, m_And(m_Value(B), m_Value(D)))) {
2225     Value *V1 = nullptr, *V2 = nullptr;
2226     C1 = dyn_cast<ConstantInt>(C);
2227     C2 = dyn_cast<ConstantInt>(D);
2228     if (C1 && C2) {  // (A & C1)|(B & C2)
2229       if ((C1->getValue() & C2->getValue()) == 0) {
2230         // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
2231         // iff (C1&C2) == 0 and (N&~C1) == 0
2232         if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
2233             ((V1 == B &&
2234               MaskedValueIsZero(V2, ~C1->getValue(), 0, &I)) || // (V|N)
2235              (V2 == B &&
2236               MaskedValueIsZero(V1, ~C1->getValue(), 0, &I))))  // (N|V)
2237           return BinaryOperator::CreateAnd(A,
2238                                 Builder->getInt(C1->getValue()|C2->getValue()));
2239         // Or commutes, try both ways.
2240         if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
2241             ((V1 == A &&
2242               MaskedValueIsZero(V2, ~C2->getValue(), 0, &I)) || // (V|N)
2243              (V2 == A &&
2244               MaskedValueIsZero(V1, ~C2->getValue(), 0, &I))))  // (N|V)
2245           return BinaryOperator::CreateAnd(B,
2246                                 Builder->getInt(C1->getValue()|C2->getValue()));
2247 
2248         // ((V|C3)&C1) | ((V|C4)&C2) --> (V|C3|C4)&(C1|C2)
2249         // iff (C1&C2) == 0 and (C3&~C1) == 0 and (C4&~C2) == 0.
2250         ConstantInt *C3 = nullptr, *C4 = nullptr;
2251         if (match(A, m_Or(m_Value(V1), m_ConstantInt(C3))) &&
2252             (C3->getValue() & ~C1->getValue()) == 0 &&
2253             match(B, m_Or(m_Specific(V1), m_ConstantInt(C4))) &&
2254             (C4->getValue() & ~C2->getValue()) == 0) {
2255           V2 = Builder->CreateOr(V1, ConstantExpr::getOr(C3, C4), "bitfield");
2256           return BinaryOperator::CreateAnd(V2,
2257                                 Builder->getInt(C1->getValue()|C2->getValue()));
2258         }
2259       }
2260     }
2261 
2262     // Don't try to form a select if it's unlikely that we'll get rid of at
2263     // least one of the operands. A select is generally more expensive than the
2264     // 'or' that it is replacing.
2265     if (Op0->hasOneUse() || Op1->hasOneUse()) {
2266       // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants.
2267       if (Value *V = matchSelectFromAndOr(A, C, B, D, *Builder))
2268         return replaceInstUsesWith(I, V);
2269       if (Value *V = matchSelectFromAndOr(A, C, D, B, *Builder))
2270         return replaceInstUsesWith(I, V);
2271       if (Value *V = matchSelectFromAndOr(C, A, B, D, *Builder))
2272         return replaceInstUsesWith(I, V);
2273       if (Value *V = matchSelectFromAndOr(C, A, D, B, *Builder))
2274         return replaceInstUsesWith(I, V);
2275       if (Value *V = matchSelectFromAndOr(B, D, A, C, *Builder))
2276         return replaceInstUsesWith(I, V);
2277       if (Value *V = matchSelectFromAndOr(B, D, C, A, *Builder))
2278         return replaceInstUsesWith(I, V);
2279       if (Value *V = matchSelectFromAndOr(D, B, A, C, *Builder))
2280         return replaceInstUsesWith(I, V);
2281       if (Value *V = matchSelectFromAndOr(D, B, C, A, *Builder))
2282         return replaceInstUsesWith(I, V);
2283     }
2284 
2285     // ((A&~B)|(~A&B)) -> A^B
2286     if ((match(C, m_Not(m_Specific(D))) &&
2287          match(B, m_Not(m_Specific(A)))))
2288       return BinaryOperator::CreateXor(A, D);
2289     // ((~B&A)|(~A&B)) -> A^B
2290     if ((match(A, m_Not(m_Specific(D))) &&
2291          match(B, m_Not(m_Specific(C)))))
2292       return BinaryOperator::CreateXor(C, D);
2293     // ((A&~B)|(B&~A)) -> A^B
2294     if ((match(C, m_Not(m_Specific(B))) &&
2295          match(D, m_Not(m_Specific(A)))))
2296       return BinaryOperator::CreateXor(A, B);
2297     // ((~B&A)|(B&~A)) -> A^B
2298     if ((match(A, m_Not(m_Specific(B))) &&
2299          match(D, m_Not(m_Specific(C)))))
2300       return BinaryOperator::CreateXor(C, B);
2301 
2302     // ((A|B)&1)|(B&-2) -> (A&1) | B
2303     if (match(A, m_Or(m_Value(V1), m_Specific(B))) ||
2304         match(A, m_Or(m_Specific(B), m_Value(V1)))) {
2305       Instruction *Ret = FoldOrWithConstants(I, Op1, V1, B, C);
2306       if (Ret) return Ret;
2307     }
2308     // (B&-2)|((A|B)&1) -> (A&1) | B
2309     if (match(B, m_Or(m_Specific(A), m_Value(V1))) ||
2310         match(B, m_Or(m_Value(V1), m_Specific(A)))) {
2311       Instruction *Ret = FoldOrWithConstants(I, Op0, A, V1, D);
2312       if (Ret) return Ret;
2313     }
2314     // ((A^B)&1)|(B&-2) -> (A&1) ^ B
2315     if (match(A, m_Xor(m_Value(V1), m_Specific(B))) ||
2316         match(A, m_Xor(m_Specific(B), m_Value(V1)))) {
2317       Instruction *Ret = FoldXorWithConstants(I, Op1, V1, B, C);
2318       if (Ret) return Ret;
2319     }
2320     // (B&-2)|((A^B)&1) -> (A&1) ^ B
2321     if (match(B, m_Xor(m_Specific(A), m_Value(V1))) ||
2322         match(B, m_Xor(m_Value(V1), m_Specific(A)))) {
2323       Instruction *Ret = FoldXorWithConstants(I, Op0, A, V1, D);
2324       if (Ret) return Ret;
2325     }
2326   }
2327 
2328   // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C
2329   if (match(Op0, m_Xor(m_Value(A), m_Value(B))))
2330     if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A))))
2331       if (Op1->hasOneUse() || cast<BinaryOperator>(Op1)->hasOneUse())
2332         return BinaryOperator::CreateOr(Op0, C);
2333 
2334   // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C
2335   if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B))))
2336     if (match(Op1, m_Xor(m_Specific(B), m_Specific(A))))
2337       if (Op0->hasOneUse() || cast<BinaryOperator>(Op0)->hasOneUse())
2338         return BinaryOperator::CreateOr(Op1, C);
2339 
2340   // ((B | C) & A) | B -> B | (A & C)
2341   if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A))))
2342     return BinaryOperator::CreateOr(Op1, Builder->CreateAnd(A, C));
2343 
2344   if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder))
2345     return DeMorgan;
2346 
2347   // Canonicalize xor to the RHS.
2348   bool SwappedForXor = false;
2349   if (match(Op0, m_Xor(m_Value(), m_Value()))) {
2350     std::swap(Op0, Op1);
2351     SwappedForXor = true;
2352   }
2353 
2354   // A | ( A ^ B) -> A |  B
2355   // A | (~A ^ B) -> A | ~B
2356   // (A & B) | (A ^ B)
2357   if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2358     if (Op0 == A || Op0 == B)
2359       return BinaryOperator::CreateOr(A, B);
2360 
2361     if (match(Op0, m_And(m_Specific(A), m_Specific(B))) ||
2362         match(Op0, m_And(m_Specific(B), m_Specific(A))))
2363       return BinaryOperator::CreateOr(A, B);
2364 
2365     if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) {
2366       Value *Not = Builder->CreateNot(B, B->getName()+".not");
2367       return BinaryOperator::CreateOr(Not, Op0);
2368     }
2369     if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) {
2370       Value *Not = Builder->CreateNot(A, A->getName()+".not");
2371       return BinaryOperator::CreateOr(Not, Op0);
2372     }
2373   }
2374 
2375   // A | ~(A | B) -> A | ~B
2376   // A | ~(A ^ B) -> A | ~B
2377   if (match(Op1, m_Not(m_Value(A))))
2378     if (BinaryOperator *B = dyn_cast<BinaryOperator>(A))
2379       if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) &&
2380           Op1->hasOneUse() && (B->getOpcode() == Instruction::Or ||
2381                                B->getOpcode() == Instruction::Xor)) {
2382         Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) :
2383                                                  B->getOperand(0);
2384         Value *Not = Builder->CreateNot(NotOp, NotOp->getName()+".not");
2385         return BinaryOperator::CreateOr(Not, Op0);
2386       }
2387 
2388   // (A & B) | ((~A) ^ B) -> (~A ^ B)
2389   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2390       match(Op1, m_Xor(m_Not(m_Specific(A)), m_Specific(B))))
2391     return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2392 
2393   // ((~A) ^ B) | (A & B) -> (~A ^ B)
2394   if (match(Op0, m_Xor(m_Not(m_Value(A)), m_Value(B))) &&
2395       match(Op1, m_And(m_Specific(A), m_Specific(B))))
2396     return BinaryOperator::CreateXor(Builder->CreateNot(A), B);
2397 
2398   if (SwappedForXor)
2399     std::swap(Op0, Op1);
2400 
2401   {
2402     ICmpInst *LHS = dyn_cast<ICmpInst>(Op0);
2403     ICmpInst *RHS = dyn_cast<ICmpInst>(Op1);
2404     if (LHS && RHS)
2405       if (Value *Res = FoldOrOfICmps(LHS, RHS, &I))
2406         return replaceInstUsesWith(I, Res);
2407 
2408     // TODO: Make this recursive; it's a little tricky because an arbitrary
2409     // number of 'or' instructions might have to be created.
2410     Value *X, *Y;
2411     if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2412       if (auto *Cmp = dyn_cast<ICmpInst>(X))
2413         if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
2414           return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
2415       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2416         if (Value *Res = FoldOrOfICmps(LHS, Cmp, &I))
2417           return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
2418     }
2419     if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) {
2420       if (auto *Cmp = dyn_cast<ICmpInst>(X))
2421         if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
2422           return replaceInstUsesWith(I, Builder->CreateOr(Res, Y));
2423       if (auto *Cmp = dyn_cast<ICmpInst>(Y))
2424         if (Value *Res = FoldOrOfICmps(Cmp, RHS, &I))
2425           return replaceInstUsesWith(I, Builder->CreateOr(Res, X));
2426     }
2427   }
2428 
2429   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
2430   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0)))
2431     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
2432       if (Value *Res = FoldOrOfFCmps(LHS, RHS))
2433         return replaceInstUsesWith(I, Res);
2434 
2435   if (Instruction *CastedOr = foldCastedBitwiseLogic(I))
2436     return CastedOr;
2437 
2438   // or(sext(A), B) / or(B, sext(A)) --> A ? -1 : B, where A is i1 or <N x i1>.
2439   if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) &&
2440       A->getType()->getScalarType()->isIntegerTy(1))
2441     return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op1);
2442   if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) &&
2443       A->getType()->getScalarType()->isIntegerTy(1))
2444     return SelectInst::Create(A, ConstantInt::getSigned(I.getType(), -1), Op0);
2445 
2446   // Note: If we've gotten to the point of visiting the outer OR, then the
2447   // inner one couldn't be simplified.  If it was a constant, then it won't
2448   // be simplified by a later pass either, so we try swapping the inner/outer
2449   // ORs in the hopes that we'll be able to simplify it this way.
2450   // (X|C) | V --> (X|V) | C
2451   if (Op0->hasOneUse() && !isa<ConstantInt>(Op1) &&
2452       match(Op0, m_Or(m_Value(A), m_ConstantInt(C1)))) {
2453     Value *Inner = Builder->CreateOr(A, Op1);
2454     Inner->takeName(Op0);
2455     return BinaryOperator::CreateOr(Inner, C1);
2456   }
2457 
2458   // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D))
2459   // Since this OR statement hasn't been optimized further yet, we hope
2460   // that this transformation will allow the new ORs to be optimized.
2461   {
2462     Value *X = nullptr, *Y = nullptr;
2463     if (Op0->hasOneUse() && Op1->hasOneUse() &&
2464         match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) &&
2465         match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) {
2466       Value *orTrue = Builder->CreateOr(A, C);
2467       Value *orFalse = Builder->CreateOr(B, D);
2468       return SelectInst::Create(X, orTrue, orFalse);
2469     }
2470   }
2471 
2472   return Changed ? &I : nullptr;
2473 }
2474 
visitXor(BinaryOperator & I)2475 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2476   bool Changed = SimplifyAssociativeOrCommutative(I);
2477   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2478 
2479   if (Value *V = SimplifyVectorOp(I))
2480     return replaceInstUsesWith(I, V);
2481 
2482   if (Value *V = SimplifyXorInst(Op0, Op1, DL, TLI, DT, AC))
2483     return replaceInstUsesWith(I, V);
2484 
2485   // (A&B)^(A&C) -> A&(B^C) etc
2486   if (Value *V = SimplifyUsingDistributiveLaws(I))
2487     return replaceInstUsesWith(I, V);
2488 
2489   // See if we can simplify any instructions used by the instruction whose sole
2490   // purpose is to compute bits we don't care about.
2491   if (SimplifyDemandedInstructionBits(I))
2492     return &I;
2493 
2494   if (Value *V = SimplifyBSwap(I))
2495     return replaceInstUsesWith(I, V);
2496 
2497   // Is this a ~ operation?
2498   if (Value *NotOp = dyn_castNotVal(&I)) {
2499     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
2500       if (Op0I->getOpcode() == Instruction::And ||
2501           Op0I->getOpcode() == Instruction::Or) {
2502         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
2503         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
2504         if (dyn_castNotVal(Op0I->getOperand(1)))
2505           Op0I->swapOperands();
2506         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2507           Value *NotY =
2508             Builder->CreateNot(Op0I->getOperand(1),
2509                                Op0I->getOperand(1)->getName()+".not");
2510           if (Op0I->getOpcode() == Instruction::And)
2511             return BinaryOperator::CreateOr(Op0NotVal, NotY);
2512           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
2513         }
2514 
2515         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
2516         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
2517         if (IsFreeToInvert(Op0I->getOperand(0),
2518                            Op0I->getOperand(0)->hasOneUse()) &&
2519             IsFreeToInvert(Op0I->getOperand(1),
2520                            Op0I->getOperand(1)->hasOneUse())) {
2521           Value *NotX =
2522             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
2523           Value *NotY =
2524             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
2525           if (Op0I->getOpcode() == Instruction::And)
2526             return BinaryOperator::CreateOr(NotX, NotY);
2527           return BinaryOperator::CreateAnd(NotX, NotY);
2528         }
2529 
2530       } else if (Op0I->getOpcode() == Instruction::AShr) {
2531         // ~(~X >>s Y) --> (X >>s Y)
2532         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0)))
2533           return BinaryOperator::CreateAShr(Op0NotVal, Op0I->getOperand(1));
2534       }
2535     }
2536   }
2537 
2538   if (Constant *RHS = dyn_cast<Constant>(Op1)) {
2539     if (RHS->isAllOnesValue() && Op0->hasOneUse())
2540       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
2541       if (CmpInst *CI = dyn_cast<CmpInst>(Op0))
2542         return CmpInst::Create(CI->getOpcode(),
2543                                CI->getInversePredicate(),
2544                                CI->getOperand(0), CI->getOperand(1));
2545   }
2546 
2547   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2548     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
2549     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2550       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
2551         if (CI->hasOneUse() && Op0C->hasOneUse()) {
2552           Instruction::CastOps Opcode = Op0C->getOpcode();
2553           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
2554               (RHS == ConstantExpr::getCast(Opcode, Builder->getTrue(),
2555                                             Op0C->getDestTy()))) {
2556             CI->setPredicate(CI->getInversePredicate());
2557             return CastInst::Create(Opcode, CI, Op0C->getType());
2558           }
2559         }
2560       }
2561     }
2562 
2563     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2564       // ~(c-X) == X-c-1 == X+(-c-1)
2565       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2566         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2567           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2568           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2569                                       ConstantInt::get(I.getType(), 1));
2570           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
2571         }
2572 
2573       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
2574         if (Op0I->getOpcode() == Instruction::Add) {
2575           // ~(X-c) --> (-c-1)-X
2576           if (RHS->isAllOnesValue()) {
2577             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2578             return BinaryOperator::CreateSub(
2579                            ConstantExpr::getSub(NegOp0CI,
2580                                       ConstantInt::get(I.getType(), 1)),
2581                                       Op0I->getOperand(0));
2582           } else if (RHS->getValue().isSignBit()) {
2583             // (X + C) ^ signbit -> (X + C + signbit)
2584             Constant *C = Builder->getInt(RHS->getValue() + Op0CI->getValue());
2585             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
2586 
2587           }
2588         } else if (Op0I->getOpcode() == Instruction::Or) {
2589           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2590           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue(),
2591                                 0, &I)) {
2592             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2593             // Anything in both C1 and C2 is known to be zero, remove it from
2594             // NewRHS.
2595             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2596             NewRHS = ConstantExpr::getAnd(NewRHS,
2597                                        ConstantExpr::getNot(CommonBits));
2598             Worklist.Add(Op0I);
2599             I.setOperand(0, Op0I->getOperand(0));
2600             I.setOperand(1, NewRHS);
2601             return &I;
2602           }
2603         } else if (Op0I->getOpcode() == Instruction::LShr) {
2604           // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3)
2605           // E1 = "X ^ C1"
2606           BinaryOperator *E1;
2607           ConstantInt *C1;
2608           if (Op0I->hasOneUse() &&
2609               (E1 = dyn_cast<BinaryOperator>(Op0I->getOperand(0))) &&
2610               E1->getOpcode() == Instruction::Xor &&
2611               (C1 = dyn_cast<ConstantInt>(E1->getOperand(1)))) {
2612             // fold (C1 >> C2) ^ C3
2613             ConstantInt *C2 = Op0CI, *C3 = RHS;
2614             APInt FoldConst = C1->getValue().lshr(C2->getValue());
2615             FoldConst ^= C3->getValue();
2616             // Prepare the two operands.
2617             Value *Opnd0 = Builder->CreateLShr(E1->getOperand(0), C2);
2618             Opnd0->takeName(Op0I);
2619             cast<Instruction>(Opnd0)->setDebugLoc(I.getDebugLoc());
2620             Value *FoldVal = ConstantInt::get(Opnd0->getType(), FoldConst);
2621 
2622             return BinaryOperator::CreateXor(Opnd0, FoldVal);
2623           }
2624         }
2625       }
2626     }
2627 
2628     // Try to fold constant and into select arguments.
2629     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2630       if (Instruction *R = FoldOpIntoSelect(I, SI))
2631         return R;
2632     if (isa<PHINode>(Op0))
2633       if (Instruction *NV = FoldOpIntoPhi(I))
2634         return NV;
2635   }
2636 
2637   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
2638   if (Op1I) {
2639     Value *A, *B;
2640     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2641       if (A == Op0) {              // B^(B|A) == (A|B)^B
2642         Op1I->swapOperands();
2643         I.swapOperands();
2644         std::swap(Op0, Op1);
2645       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
2646         I.swapOperands();     // Simplified below.
2647         std::swap(Op0, Op1);
2648       }
2649     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
2650                Op1I->hasOneUse()){
2651       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
2652         Op1I->swapOperands();
2653         std::swap(A, B);
2654       }
2655       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
2656         I.swapOperands();     // Simplified below.
2657         std::swap(Op0, Op1);
2658       }
2659     }
2660   }
2661 
2662   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
2663   if (Op0I) {
2664     Value *A, *B;
2665     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2666         Op0I->hasOneUse()) {
2667       if (A == Op1)                                  // (B|A)^B == (A|B)^B
2668         std::swap(A, B);
2669       if (B == Op1)                                  // (A|B)^B == A & ~B
2670         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1));
2671     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2672                Op0I->hasOneUse()){
2673       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
2674         std::swap(A, B);
2675       if (B == Op1 &&                                      // (B&A)^A == ~B & A
2676           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
2677         return BinaryOperator::CreateAnd(Builder->CreateNot(A), Op1);
2678       }
2679     }
2680   }
2681 
2682   if (Op0I && Op1I) {
2683     Value *A, *B, *C, *D;
2684     // (A & B)^(A | B) -> A ^ B
2685     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2686         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
2687       if ((A == C && B == D) || (A == D && B == C))
2688         return BinaryOperator::CreateXor(A, B);
2689     }
2690     // (A | B)^(A & B) -> A ^ B
2691     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2692         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
2693       if ((A == C && B == D) || (A == D && B == C))
2694         return BinaryOperator::CreateXor(A, B);
2695     }
2696     // (A | ~B) ^ (~A | B) -> A ^ B
2697     if (match(Op0I, m_Or(m_Value(A), m_Not(m_Value(B)))) &&
2698         match(Op1I, m_Or(m_Not(m_Specific(A)), m_Specific(B)))) {
2699       return BinaryOperator::CreateXor(A, B);
2700     }
2701     // (~A | B) ^ (A | ~B) -> A ^ B
2702     if (match(Op0I, m_Or(m_Not(m_Value(A)), m_Value(B))) &&
2703         match(Op1I, m_Or(m_Specific(A), m_Not(m_Specific(B))))) {
2704       return BinaryOperator::CreateXor(A, B);
2705     }
2706     // (A & ~B) ^ (~A & B) -> A ^ B
2707     if (match(Op0I, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2708         match(Op1I, m_And(m_Not(m_Specific(A)), m_Specific(B)))) {
2709       return BinaryOperator::CreateXor(A, B);
2710     }
2711     // (~A & B) ^ (A & ~B) -> A ^ B
2712     if (match(Op0I, m_And(m_Not(m_Value(A)), m_Value(B))) &&
2713         match(Op1I, m_And(m_Specific(A), m_Not(m_Specific(B))))) {
2714       return BinaryOperator::CreateXor(A, B);
2715     }
2716     // (A ^ C)^(A | B) -> ((~A) & B) ^ C
2717     if (match(Op0I, m_Xor(m_Value(D), m_Value(C))) &&
2718         match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
2719       if (D == A)
2720         return BinaryOperator::CreateXor(
2721             Builder->CreateAnd(Builder->CreateNot(A), B), C);
2722       if (D == B)
2723         return BinaryOperator::CreateXor(
2724             Builder->CreateAnd(Builder->CreateNot(B), A), C);
2725     }
2726     // (A | B)^(A ^ C) -> ((~A) & B) ^ C
2727     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
2728         match(Op1I, m_Xor(m_Value(D), m_Value(C)))) {
2729       if (D == A)
2730         return BinaryOperator::CreateXor(
2731             Builder->CreateAnd(Builder->CreateNot(A), B), C);
2732       if (D == B)
2733         return BinaryOperator::CreateXor(
2734             Builder->CreateAnd(Builder->CreateNot(B), A), C);
2735     }
2736     // (A & B) ^ (A ^ B) -> (A | B)
2737     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
2738         match(Op1I, m_Xor(m_Specific(A), m_Specific(B))))
2739       return BinaryOperator::CreateOr(A, B);
2740     // (A ^ B) ^ (A & B) -> (A | B)
2741     if (match(Op0I, m_Xor(m_Value(A), m_Value(B))) &&
2742         match(Op1I, m_And(m_Specific(A), m_Specific(B))))
2743       return BinaryOperator::CreateOr(A, B);
2744   }
2745 
2746   Value *A = nullptr, *B = nullptr;
2747   // (A & ~B) ^ (~A) -> ~(A & B)
2748   if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
2749       match(Op1, m_Not(m_Specific(A))))
2750     return BinaryOperator::CreateNot(Builder->CreateAnd(A, B));
2751 
2752   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
2753   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
2754     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
2755       if (PredicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) {
2756         if (LHS->getOperand(0) == RHS->getOperand(1) &&
2757             LHS->getOperand(1) == RHS->getOperand(0))
2758           LHS->swapOperands();
2759         if (LHS->getOperand(0) == RHS->getOperand(0) &&
2760             LHS->getOperand(1) == RHS->getOperand(1)) {
2761           Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1);
2762           unsigned Code = getICmpCode(LHS) ^ getICmpCode(RHS);
2763           bool isSigned = LHS->isSigned() || RHS->isSigned();
2764           return replaceInstUsesWith(I,
2765                                getNewICmpValue(isSigned, Code, Op0, Op1,
2766                                                Builder));
2767         }
2768       }
2769 
2770   if (Instruction *CastedXor = foldCastedBitwiseLogic(I))
2771     return CastedXor;
2772 
2773   return Changed ? &I : nullptr;
2774 }
2775