1 //===- InstCombineAndOrXor.cpp --------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the visitAnd, visitOr, and visitXor functions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "InstCombineInternal.h" 14 #include "llvm/Analysis/CmpInstAnalysis.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/InstCombine/InstCombiner.h" 20 #include "llvm/Transforms/Utils/Local.h" 21 22 using namespace llvm; 23 using namespace PatternMatch; 24 25 #define DEBUG_TYPE "instcombine" 26 27 /// This is the complement of getICmpCode, which turns an opcode and two 28 /// operands into either a constant true or false, or a brand new ICmp 29 /// instruction. The sign is passed in to determine which kind of predicate to 30 /// use in the new icmp instruction. 31 static Value *getNewICmpValue(unsigned Code, bool Sign, Value *LHS, Value *RHS, 32 InstCombiner::BuilderTy &Builder) { 33 ICmpInst::Predicate NewPred; 34 if (Constant *TorF = getPredForICmpCode(Code, Sign, LHS->getType(), NewPred)) 35 return TorF; 36 return Builder.CreateICmp(NewPred, LHS, RHS); 37 } 38 39 /// This is the complement of getFCmpCode, which turns an opcode and two 40 /// operands into either a FCmp instruction, or a true/false constant. 41 static Value *getFCmpValue(unsigned Code, Value *LHS, Value *RHS, 42 InstCombiner::BuilderTy &Builder) { 43 FCmpInst::Predicate NewPred; 44 if (Constant *TorF = getPredForFCmpCode(Code, LHS->getType(), NewPred)) 45 return TorF; 46 return Builder.CreateFCmp(NewPred, LHS, RHS); 47 } 48 49 /// Transform BITWISE_OP(BSWAP(A),BSWAP(B)) or 50 /// BITWISE_OP(BSWAP(A), Constant) to BSWAP(BITWISE_OP(A, B)) 51 /// \param I Binary operator to transform. 52 /// \return Pointer to node that must replace the original binary operator, or 53 /// null pointer if no transformation was made. 54 static Value *SimplifyBSwap(BinaryOperator &I, 55 InstCombiner::BuilderTy &Builder) { 56 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bswap simplifying"); 57 58 Value *OldLHS = I.getOperand(0); 59 Value *OldRHS = I.getOperand(1); 60 61 Value *NewLHS; 62 if (!match(OldLHS, m_BSwap(m_Value(NewLHS)))) 63 return nullptr; 64 65 Value *NewRHS; 66 const APInt *C; 67 68 if (match(OldRHS, m_BSwap(m_Value(NewRHS)))) { 69 // OP( BSWAP(x), BSWAP(y) ) -> BSWAP( OP(x, y) ) 70 if (!OldLHS->hasOneUse() && !OldRHS->hasOneUse()) 71 return nullptr; 72 // NewRHS initialized by the matcher. 73 } else if (match(OldRHS, m_APInt(C))) { 74 // OP( BSWAP(x), CONSTANT ) -> BSWAP( OP(x, BSWAP(CONSTANT) ) ) 75 if (!OldLHS->hasOneUse()) 76 return nullptr; 77 NewRHS = ConstantInt::get(I.getType(), C->byteSwap()); 78 } else 79 return nullptr; 80 81 Value *BinOp = Builder.CreateBinOp(I.getOpcode(), NewLHS, NewRHS); 82 Function *F = Intrinsic::getDeclaration(I.getModule(), Intrinsic::bswap, 83 I.getType()); 84 return Builder.CreateCall(F, BinOp); 85 } 86 87 /// Emit a computation of: (V >= Lo && V < Hi) if Inside is true, otherwise 88 /// (V < Lo || V >= Hi). This method expects that Lo < Hi. IsSigned indicates 89 /// whether to treat V, Lo, and Hi as signed or not. 90 Value *InstCombinerImpl::insertRangeTest(Value *V, const APInt &Lo, 91 const APInt &Hi, bool isSigned, 92 bool Inside) { 93 assert((isSigned ? Lo.slt(Hi) : Lo.ult(Hi)) && 94 "Lo is not < Hi in range emission code!"); 95 96 Type *Ty = V->getType(); 97 98 // V >= Min && V < Hi --> V < Hi 99 // V < Min || V >= Hi --> V >= Hi 100 ICmpInst::Predicate Pred = Inside ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE; 101 if (isSigned ? Lo.isMinSignedValue() : Lo.isMinValue()) { 102 Pred = isSigned ? ICmpInst::getSignedPredicate(Pred) : Pred; 103 return Builder.CreateICmp(Pred, V, ConstantInt::get(Ty, Hi)); 104 } 105 106 // V >= Lo && V < Hi --> V - Lo u< Hi - Lo 107 // V < Lo || V >= Hi --> V - Lo u>= Hi - Lo 108 Value *VMinusLo = 109 Builder.CreateSub(V, ConstantInt::get(Ty, Lo), V->getName() + ".off"); 110 Constant *HiMinusLo = ConstantInt::get(Ty, Hi - Lo); 111 return Builder.CreateICmp(Pred, VMinusLo, HiMinusLo); 112 } 113 114 /// Classify (icmp eq (A & B), C) and (icmp ne (A & B), C) as matching patterns 115 /// that can be simplified. 116 /// One of A and B is considered the mask. The other is the value. This is 117 /// described as the "AMask" or "BMask" part of the enum. If the enum contains 118 /// only "Mask", then both A and B can be considered masks. If A is the mask, 119 /// then it was proven that (A & C) == C. This is trivial if C == A or C == 0. 120 /// If both A and C are constants, this proof is also easy. 121 /// For the following explanations, we assume that A is the mask. 122 /// 123 /// "AllOnes" declares that the comparison is true only if (A & B) == A or all 124 /// bits of A are set in B. 125 /// Example: (icmp eq (A & 3), 3) -> AMask_AllOnes 126 /// 127 /// "AllZeros" declares that the comparison is true only if (A & B) == 0 or all 128 /// bits of A are cleared in B. 129 /// Example: (icmp eq (A & 3), 0) -> Mask_AllZeroes 130 /// 131 /// "Mixed" declares that (A & B) == C and C might or might not contain any 132 /// number of one bits and zero bits. 133 /// Example: (icmp eq (A & 3), 1) -> AMask_Mixed 134 /// 135 /// "Not" means that in above descriptions "==" should be replaced by "!=". 136 /// Example: (icmp ne (A & 3), 3) -> AMask_NotAllOnes 137 /// 138 /// If the mask A contains a single bit, then the following is equivalent: 139 /// (icmp eq (A & B), A) equals (icmp ne (A & B), 0) 140 /// (icmp ne (A & B), A) equals (icmp eq (A & B), 0) 141 enum MaskedICmpType { 142 AMask_AllOnes = 1, 143 AMask_NotAllOnes = 2, 144 BMask_AllOnes = 4, 145 BMask_NotAllOnes = 8, 146 Mask_AllZeros = 16, 147 Mask_NotAllZeros = 32, 148 AMask_Mixed = 64, 149 AMask_NotMixed = 128, 150 BMask_Mixed = 256, 151 BMask_NotMixed = 512 152 }; 153 154 /// Return the set of patterns (from MaskedICmpType) that (icmp SCC (A & B), C) 155 /// satisfies. 156 static unsigned getMaskedICmpType(Value *A, Value *B, Value *C, 157 ICmpInst::Predicate Pred) { 158 const APInt *ConstA = nullptr, *ConstB = nullptr, *ConstC = nullptr; 159 match(A, m_APInt(ConstA)); 160 match(B, m_APInt(ConstB)); 161 match(C, m_APInt(ConstC)); 162 bool IsEq = (Pred == ICmpInst::ICMP_EQ); 163 bool IsAPow2 = ConstA && ConstA->isPowerOf2(); 164 bool IsBPow2 = ConstB && ConstB->isPowerOf2(); 165 unsigned MaskVal = 0; 166 if (ConstC && ConstC->isZero()) { 167 // if C is zero, then both A and B qualify as mask 168 MaskVal |= (IsEq ? (Mask_AllZeros | AMask_Mixed | BMask_Mixed) 169 : (Mask_NotAllZeros | AMask_NotMixed | BMask_NotMixed)); 170 if (IsAPow2) 171 MaskVal |= (IsEq ? (AMask_NotAllOnes | AMask_NotMixed) 172 : (AMask_AllOnes | AMask_Mixed)); 173 if (IsBPow2) 174 MaskVal |= (IsEq ? (BMask_NotAllOnes | BMask_NotMixed) 175 : (BMask_AllOnes | BMask_Mixed)); 176 return MaskVal; 177 } 178 179 if (A == C) { 180 MaskVal |= (IsEq ? (AMask_AllOnes | AMask_Mixed) 181 : (AMask_NotAllOnes | AMask_NotMixed)); 182 if (IsAPow2) 183 MaskVal |= (IsEq ? (Mask_NotAllZeros | AMask_NotMixed) 184 : (Mask_AllZeros | AMask_Mixed)); 185 } else if (ConstA && ConstC && ConstC->isSubsetOf(*ConstA)) { 186 MaskVal |= (IsEq ? AMask_Mixed : AMask_NotMixed); 187 } 188 189 if (B == C) { 190 MaskVal |= (IsEq ? (BMask_AllOnes | BMask_Mixed) 191 : (BMask_NotAllOnes | BMask_NotMixed)); 192 if (IsBPow2) 193 MaskVal |= (IsEq ? (Mask_NotAllZeros | BMask_NotMixed) 194 : (Mask_AllZeros | BMask_Mixed)); 195 } else if (ConstB && ConstC && ConstC->isSubsetOf(*ConstB)) { 196 MaskVal |= (IsEq ? BMask_Mixed : BMask_NotMixed); 197 } 198 199 return MaskVal; 200 } 201 202 /// Convert an analysis of a masked ICmp into its equivalent if all boolean 203 /// operations had the opposite sense. Since each "NotXXX" flag (recording !=) 204 /// is adjacent to the corresponding normal flag (recording ==), this just 205 /// involves swapping those bits over. 206 static unsigned conjugateICmpMask(unsigned Mask) { 207 unsigned NewMask; 208 NewMask = (Mask & (AMask_AllOnes | BMask_AllOnes | Mask_AllZeros | 209 AMask_Mixed | BMask_Mixed)) 210 << 1; 211 212 NewMask |= (Mask & (AMask_NotAllOnes | BMask_NotAllOnes | Mask_NotAllZeros | 213 AMask_NotMixed | BMask_NotMixed)) 214 >> 1; 215 216 return NewMask; 217 } 218 219 // Adapts the external decomposeBitTestICmp for local use. 220 static bool decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate &Pred, 221 Value *&X, Value *&Y, Value *&Z) { 222 APInt Mask; 223 if (!llvm::decomposeBitTestICmp(LHS, RHS, Pred, X, Mask)) 224 return false; 225 226 Y = ConstantInt::get(X->getType(), Mask); 227 Z = ConstantInt::get(X->getType(), 0); 228 return true; 229 } 230 231 /// Handle (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E). 232 /// Return the pattern classes (from MaskedICmpType) for the left hand side and 233 /// the right hand side as a pair. 234 /// LHS and RHS are the left hand side and the right hand side ICmps and PredL 235 /// and PredR are their predicates, respectively. 236 static 237 Optional<std::pair<unsigned, unsigned>> 238 getMaskedTypeForICmpPair(Value *&A, Value *&B, Value *&C, 239 Value *&D, Value *&E, ICmpInst *LHS, 240 ICmpInst *RHS, 241 ICmpInst::Predicate &PredL, 242 ICmpInst::Predicate &PredR) { 243 // Don't allow pointers. Splat vectors are fine. 244 if (!LHS->getOperand(0)->getType()->isIntOrIntVectorTy() || 245 !RHS->getOperand(0)->getType()->isIntOrIntVectorTy()) 246 return None; 247 248 // Here comes the tricky part: 249 // LHS might be of the form L11 & L12 == X, X == L21 & L22, 250 // and L11 & L12 == L21 & L22. The same goes for RHS. 251 // Now we must find those components L** and R**, that are equal, so 252 // that we can extract the parameters A, B, C, D, and E for the canonical 253 // above. 254 Value *L1 = LHS->getOperand(0); 255 Value *L2 = LHS->getOperand(1); 256 Value *L11, *L12, *L21, *L22; 257 // Check whether the icmp can be decomposed into a bit test. 258 if (decomposeBitTestICmp(L1, L2, PredL, L11, L12, L2)) { 259 L21 = L22 = L1 = nullptr; 260 } else { 261 // Look for ANDs in the LHS icmp. 262 if (!match(L1, m_And(m_Value(L11), m_Value(L12)))) { 263 // Any icmp can be viewed as being trivially masked; if it allows us to 264 // remove one, it's worth it. 265 L11 = L1; 266 L12 = Constant::getAllOnesValue(L1->getType()); 267 } 268 269 if (!match(L2, m_And(m_Value(L21), m_Value(L22)))) { 270 L21 = L2; 271 L22 = Constant::getAllOnesValue(L2->getType()); 272 } 273 } 274 275 // Bail if LHS was a icmp that can't be decomposed into an equality. 276 if (!ICmpInst::isEquality(PredL)) 277 return None; 278 279 Value *R1 = RHS->getOperand(0); 280 Value *R2 = RHS->getOperand(1); 281 Value *R11, *R12; 282 bool Ok = false; 283 if (decomposeBitTestICmp(R1, R2, PredR, R11, R12, R2)) { 284 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) { 285 A = R11; 286 D = R12; 287 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) { 288 A = R12; 289 D = R11; 290 } else { 291 return None; 292 } 293 E = R2; 294 R1 = nullptr; 295 Ok = true; 296 } else { 297 if (!match(R1, m_And(m_Value(R11), m_Value(R12)))) { 298 // As before, model no mask as a trivial mask if it'll let us do an 299 // optimization. 300 R11 = R1; 301 R12 = Constant::getAllOnesValue(R1->getType()); 302 } 303 304 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) { 305 A = R11; 306 D = R12; 307 E = R2; 308 Ok = true; 309 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) { 310 A = R12; 311 D = R11; 312 E = R2; 313 Ok = true; 314 } 315 } 316 317 // Bail if RHS was a icmp that can't be decomposed into an equality. 318 if (!ICmpInst::isEquality(PredR)) 319 return None; 320 321 // Look for ANDs on the right side of the RHS icmp. 322 if (!Ok) { 323 if (!match(R2, m_And(m_Value(R11), m_Value(R12)))) { 324 R11 = R2; 325 R12 = Constant::getAllOnesValue(R2->getType()); 326 } 327 328 if (R11 == L11 || R11 == L12 || R11 == L21 || R11 == L22) { 329 A = R11; 330 D = R12; 331 E = R1; 332 Ok = true; 333 } else if (R12 == L11 || R12 == L12 || R12 == L21 || R12 == L22) { 334 A = R12; 335 D = R11; 336 E = R1; 337 Ok = true; 338 } else { 339 return None; 340 } 341 342 assert(Ok && "Failed to find AND on the right side of the RHS icmp."); 343 } 344 345 if (L11 == A) { 346 B = L12; 347 C = L2; 348 } else if (L12 == A) { 349 B = L11; 350 C = L2; 351 } else if (L21 == A) { 352 B = L22; 353 C = L1; 354 } else if (L22 == A) { 355 B = L21; 356 C = L1; 357 } 358 359 unsigned LeftType = getMaskedICmpType(A, B, C, PredL); 360 unsigned RightType = getMaskedICmpType(A, D, E, PredR); 361 return Optional<std::pair<unsigned, unsigned>>(std::make_pair(LeftType, RightType)); 362 } 363 364 /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E) into a single 365 /// (icmp(A & X) ==/!= Y), where the left-hand side is of type Mask_NotAllZeros 366 /// and the right hand side is of type BMask_Mixed. For example, 367 /// (icmp (A & 12) != 0) & (icmp (A & 15) == 8) -> (icmp (A & 15) == 8). 368 static Value *foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed( 369 ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C, 370 Value *D, Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR, 371 InstCombiner::BuilderTy &Builder) { 372 // We are given the canonical form: 373 // (icmp ne (A & B), 0) & (icmp eq (A & D), E). 374 // where D & E == E. 375 // 376 // If IsAnd is false, we get it in negated form: 377 // (icmp eq (A & B), 0) | (icmp ne (A & D), E) -> 378 // !((icmp ne (A & B), 0) & (icmp eq (A & D), E)). 379 // 380 // We currently handle the case of B, C, D, E are constant. 381 // 382 ConstantInt *BCst, *CCst, *DCst, *ECst; 383 if (!match(B, m_ConstantInt(BCst)) || !match(C, m_ConstantInt(CCst)) || 384 !match(D, m_ConstantInt(DCst)) || !match(E, m_ConstantInt(ECst))) 385 return nullptr; 386 387 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 388 389 // Update E to the canonical form when D is a power of two and RHS is 390 // canonicalized as, 391 // (icmp ne (A & D), 0) -> (icmp eq (A & D), D) or 392 // (icmp ne (A & D), D) -> (icmp eq (A & D), 0). 393 if (PredR != NewCC) 394 ECst = cast<ConstantInt>(ConstantExpr::getXor(DCst, ECst)); 395 396 // If B or D is zero, skip because if LHS or RHS can be trivially folded by 397 // other folding rules and this pattern won't apply any more. 398 if (BCst->getValue() == 0 || DCst->getValue() == 0) 399 return nullptr; 400 401 // If B and D don't intersect, ie. (B & D) == 0, no folding because we can't 402 // deduce anything from it. 403 // For example, 404 // (icmp ne (A & 12), 0) & (icmp eq (A & 3), 1) -> no folding. 405 if ((BCst->getValue() & DCst->getValue()) == 0) 406 return nullptr; 407 408 // If the following two conditions are met: 409 // 410 // 1. mask B covers only a single bit that's not covered by mask D, that is, 411 // (B & (B ^ D)) is a power of 2 (in other words, B minus the intersection of 412 // B and D has only one bit set) and, 413 // 414 // 2. RHS (and E) indicates that the rest of B's bits are zero (in other 415 // words, the intersection of B and D is zero), that is, ((B & D) & E) == 0 416 // 417 // then that single bit in B must be one and thus the whole expression can be 418 // folded to 419 // (A & (B | D)) == (B & (B ^ D)) | E. 420 // 421 // For example, 422 // (icmp ne (A & 12), 0) & (icmp eq (A & 7), 1) -> (icmp eq (A & 15), 9) 423 // (icmp ne (A & 15), 0) & (icmp eq (A & 7), 0) -> (icmp eq (A & 15), 8) 424 if ((((BCst->getValue() & DCst->getValue()) & ECst->getValue()) == 0) && 425 (BCst->getValue() & (BCst->getValue() ^ DCst->getValue())).isPowerOf2()) { 426 APInt BorD = BCst->getValue() | DCst->getValue(); 427 APInt BandBxorDorE = (BCst->getValue() & (BCst->getValue() ^ DCst->getValue())) | 428 ECst->getValue(); 429 Value *NewMask = ConstantInt::get(BCst->getType(), BorD); 430 Value *NewMaskedValue = ConstantInt::get(BCst->getType(), BandBxorDorE); 431 Value *NewAnd = Builder.CreateAnd(A, NewMask); 432 return Builder.CreateICmp(NewCC, NewAnd, NewMaskedValue); 433 } 434 435 auto IsSubSetOrEqual = [](ConstantInt *C1, ConstantInt *C2) { 436 return (C1->getValue() & C2->getValue()) == C1->getValue(); 437 }; 438 auto IsSuperSetOrEqual = [](ConstantInt *C1, ConstantInt *C2) { 439 return (C1->getValue() & C2->getValue()) == C2->getValue(); 440 }; 441 442 // In the following, we consider only the cases where B is a superset of D, B 443 // is a subset of D, or B == D because otherwise there's at least one bit 444 // covered by B but not D, in which case we can't deduce much from it, so 445 // no folding (aside from the single must-be-one bit case right above.) 446 // For example, 447 // (icmp ne (A & 14), 0) & (icmp eq (A & 3), 1) -> no folding. 448 if (!IsSubSetOrEqual(BCst, DCst) && !IsSuperSetOrEqual(BCst, DCst)) 449 return nullptr; 450 451 // At this point, either B is a superset of D, B is a subset of D or B == D. 452 453 // If E is zero, if B is a subset of (or equal to) D, LHS and RHS contradict 454 // and the whole expression becomes false (or true if negated), otherwise, no 455 // folding. 456 // For example, 457 // (icmp ne (A & 3), 0) & (icmp eq (A & 7), 0) -> false. 458 // (icmp ne (A & 15), 0) & (icmp eq (A & 3), 0) -> no folding. 459 if (ECst->isZero()) { 460 if (IsSubSetOrEqual(BCst, DCst)) 461 return ConstantInt::get(LHS->getType(), !IsAnd); 462 return nullptr; 463 } 464 465 // At this point, B, D, E aren't zero and (B & D) == B, (B & D) == D or B == 466 // D. If B is a superset of (or equal to) D, since E is not zero, LHS is 467 // subsumed by RHS (RHS implies LHS.) So the whole expression becomes 468 // RHS. For example, 469 // (icmp ne (A & 255), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8). 470 // (icmp ne (A & 15), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8). 471 if (IsSuperSetOrEqual(BCst, DCst)) 472 return RHS; 473 // Otherwise, B is a subset of D. If B and E have a common bit set, 474 // ie. (B & E) != 0, then LHS is subsumed by RHS. For example. 475 // (icmp ne (A & 12), 0) & (icmp eq (A & 15), 8) -> (icmp eq (A & 15), 8). 476 assert(IsSubSetOrEqual(BCst, DCst) && "Precondition due to above code"); 477 if ((BCst->getValue() & ECst->getValue()) != 0) 478 return RHS; 479 // Otherwise, LHS and RHS contradict and the whole expression becomes false 480 // (or true if negated.) For example, 481 // (icmp ne (A & 7), 0) & (icmp eq (A & 15), 8) -> false. 482 // (icmp ne (A & 6), 0) & (icmp eq (A & 15), 8) -> false. 483 return ConstantInt::get(LHS->getType(), !IsAnd); 484 } 485 486 /// Try to fold (icmp(A & B) ==/!= 0) &/| (icmp(A & D) ==/!= E) into a single 487 /// (icmp(A & X) ==/!= Y), where the left-hand side and the right hand side 488 /// aren't of the common mask pattern type. 489 static Value *foldLogOpOfMaskedICmpsAsymmetric( 490 ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, Value *A, Value *B, Value *C, 491 Value *D, Value *E, ICmpInst::Predicate PredL, ICmpInst::Predicate PredR, 492 unsigned LHSMask, unsigned RHSMask, InstCombiner::BuilderTy &Builder) { 493 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) && 494 "Expected equality predicates for masked type of icmps."); 495 // Handle Mask_NotAllZeros-BMask_Mixed cases. 496 // (icmp ne/eq (A & B), C) &/| (icmp eq/ne (A & D), E), or 497 // (icmp eq/ne (A & B), C) &/| (icmp ne/eq (A & D), E) 498 // which gets swapped to 499 // (icmp ne/eq (A & D), E) &/| (icmp eq/ne (A & B), C). 500 if (!IsAnd) { 501 LHSMask = conjugateICmpMask(LHSMask); 502 RHSMask = conjugateICmpMask(RHSMask); 503 } 504 if ((LHSMask & Mask_NotAllZeros) && (RHSMask & BMask_Mixed)) { 505 if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed( 506 LHS, RHS, IsAnd, A, B, C, D, E, 507 PredL, PredR, Builder)) { 508 return V; 509 } 510 } else if ((LHSMask & BMask_Mixed) && (RHSMask & Mask_NotAllZeros)) { 511 if (Value *V = foldLogOpOfMaskedICmps_NotAllZeros_BMask_Mixed( 512 RHS, LHS, IsAnd, A, D, E, B, C, 513 PredR, PredL, Builder)) { 514 return V; 515 } 516 } 517 return nullptr; 518 } 519 520 /// Try to fold (icmp(A & B) ==/!= C) &/| (icmp(A & D) ==/!= E) 521 /// into a single (icmp(A & X) ==/!= Y). 522 static Value *foldLogOpOfMaskedICmps(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, 523 InstCombiner::BuilderTy &Builder) { 524 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr, *E = nullptr; 525 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate(); 526 Optional<std::pair<unsigned, unsigned>> MaskPair = 527 getMaskedTypeForICmpPair(A, B, C, D, E, LHS, RHS, PredL, PredR); 528 if (!MaskPair) 529 return nullptr; 530 assert(ICmpInst::isEquality(PredL) && ICmpInst::isEquality(PredR) && 531 "Expected equality predicates for masked type of icmps."); 532 unsigned LHSMask = MaskPair->first; 533 unsigned RHSMask = MaskPair->second; 534 unsigned Mask = LHSMask & RHSMask; 535 if (Mask == 0) { 536 // Even if the two sides don't share a common pattern, check if folding can 537 // still happen. 538 if (Value *V = foldLogOpOfMaskedICmpsAsymmetric( 539 LHS, RHS, IsAnd, A, B, C, D, E, PredL, PredR, LHSMask, RHSMask, 540 Builder)) 541 return V; 542 return nullptr; 543 } 544 545 // In full generality: 546 // (icmp (A & B) Op C) | (icmp (A & D) Op E) 547 // == ![ (icmp (A & B) !Op C) & (icmp (A & D) !Op E) ] 548 // 549 // If the latter can be converted into (icmp (A & X) Op Y) then the former is 550 // equivalent to (icmp (A & X) !Op Y). 551 // 552 // Therefore, we can pretend for the rest of this function that we're dealing 553 // with the conjunction, provided we flip the sense of any comparisons (both 554 // input and output). 555 556 // In most cases we're going to produce an EQ for the "&&" case. 557 ICmpInst::Predicate NewCC = IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 558 if (!IsAnd) { 559 // Convert the masking analysis into its equivalent with negated 560 // comparisons. 561 Mask = conjugateICmpMask(Mask); 562 } 563 564 if (Mask & Mask_AllZeros) { 565 // (icmp eq (A & B), 0) & (icmp eq (A & D), 0) 566 // -> (icmp eq (A & (B|D)), 0) 567 Value *NewOr = Builder.CreateOr(B, D); 568 Value *NewAnd = Builder.CreateAnd(A, NewOr); 569 // We can't use C as zero because we might actually handle 570 // (icmp ne (A & B), B) & (icmp ne (A & D), D) 571 // with B and D, having a single bit set. 572 Value *Zero = Constant::getNullValue(A->getType()); 573 return Builder.CreateICmp(NewCC, NewAnd, Zero); 574 } 575 if (Mask & BMask_AllOnes) { 576 // (icmp eq (A & B), B) & (icmp eq (A & D), D) 577 // -> (icmp eq (A & (B|D)), (B|D)) 578 Value *NewOr = Builder.CreateOr(B, D); 579 Value *NewAnd = Builder.CreateAnd(A, NewOr); 580 return Builder.CreateICmp(NewCC, NewAnd, NewOr); 581 } 582 if (Mask & AMask_AllOnes) { 583 // (icmp eq (A & B), A) & (icmp eq (A & D), A) 584 // -> (icmp eq (A & (B&D)), A) 585 Value *NewAnd1 = Builder.CreateAnd(B, D); 586 Value *NewAnd2 = Builder.CreateAnd(A, NewAnd1); 587 return Builder.CreateICmp(NewCC, NewAnd2, A); 588 } 589 590 // Remaining cases assume at least that B and D are constant, and depend on 591 // their actual values. This isn't strictly necessary, just a "handle the 592 // easy cases for now" decision. 593 const APInt *ConstB, *ConstD; 594 if (!match(B, m_APInt(ConstB)) || !match(D, m_APInt(ConstD))) 595 return nullptr; 596 597 if (Mask & (Mask_NotAllZeros | BMask_NotAllOnes)) { 598 // (icmp ne (A & B), 0) & (icmp ne (A & D), 0) and 599 // (icmp ne (A & B), B) & (icmp ne (A & D), D) 600 // -> (icmp ne (A & B), 0) or (icmp ne (A & D), 0) 601 // Only valid if one of the masks is a superset of the other (check "B&D" is 602 // the same as either B or D). 603 APInt NewMask = *ConstB & *ConstD; 604 if (NewMask == *ConstB) 605 return LHS; 606 else if (NewMask == *ConstD) 607 return RHS; 608 } 609 610 if (Mask & AMask_NotAllOnes) { 611 // (icmp ne (A & B), B) & (icmp ne (A & D), D) 612 // -> (icmp ne (A & B), A) or (icmp ne (A & D), A) 613 // Only valid if one of the masks is a superset of the other (check "B|D" is 614 // the same as either B or D). 615 APInt NewMask = *ConstB | *ConstD; 616 if (NewMask == *ConstB) 617 return LHS; 618 else if (NewMask == *ConstD) 619 return RHS; 620 } 621 622 if (Mask & BMask_Mixed) { 623 // (icmp eq (A & B), C) & (icmp eq (A & D), E) 624 // We already know that B & C == C && D & E == E. 625 // If we can prove that (B & D) & (C ^ E) == 0, that is, the bits of 626 // C and E, which are shared by both the mask B and the mask D, don't 627 // contradict, then we can transform to 628 // -> (icmp eq (A & (B|D)), (C|E)) 629 // Currently, we only handle the case of B, C, D, and E being constant. 630 // We can't simply use C and E because we might actually handle 631 // (icmp ne (A & B), B) & (icmp eq (A & D), D) 632 // with B and D, having a single bit set. 633 const APInt *OldConstC, *OldConstE; 634 if (!match(C, m_APInt(OldConstC)) || !match(E, m_APInt(OldConstE))) 635 return nullptr; 636 637 const APInt ConstC = PredL != NewCC ? *ConstB ^ *OldConstC : *OldConstC; 638 const APInt ConstE = PredR != NewCC ? *ConstD ^ *OldConstE : *OldConstE; 639 640 // If there is a conflict, we should actually return a false for the 641 // whole construct. 642 if (((*ConstB & *ConstD) & (ConstC ^ ConstE)).getBoolValue()) 643 return ConstantInt::get(LHS->getType(), !IsAnd); 644 645 Value *NewOr1 = Builder.CreateOr(B, D); 646 Value *NewAnd = Builder.CreateAnd(A, NewOr1); 647 Constant *NewOr2 = ConstantInt::get(A->getType(), ConstC | ConstE); 648 return Builder.CreateICmp(NewCC, NewAnd, NewOr2); 649 } 650 651 return nullptr; 652 } 653 654 /// Try to fold a signed range checked with lower bound 0 to an unsigned icmp. 655 /// Example: (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n 656 /// If \p Inverted is true then the check is for the inverted range, e.g. 657 /// (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n 658 Value *InstCombinerImpl::simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1, 659 bool Inverted) { 660 // Check the lower range comparison, e.g. x >= 0 661 // InstCombine already ensured that if there is a constant it's on the RHS. 662 ConstantInt *RangeStart = dyn_cast<ConstantInt>(Cmp0->getOperand(1)); 663 if (!RangeStart) 664 return nullptr; 665 666 ICmpInst::Predicate Pred0 = (Inverted ? Cmp0->getInversePredicate() : 667 Cmp0->getPredicate()); 668 669 // Accept x > -1 or x >= 0 (after potentially inverting the predicate). 670 if (!((Pred0 == ICmpInst::ICMP_SGT && RangeStart->isMinusOne()) || 671 (Pred0 == ICmpInst::ICMP_SGE && RangeStart->isZero()))) 672 return nullptr; 673 674 ICmpInst::Predicate Pred1 = (Inverted ? Cmp1->getInversePredicate() : 675 Cmp1->getPredicate()); 676 677 Value *Input = Cmp0->getOperand(0); 678 Value *RangeEnd; 679 if (Cmp1->getOperand(0) == Input) { 680 // For the upper range compare we have: icmp x, n 681 RangeEnd = Cmp1->getOperand(1); 682 } else if (Cmp1->getOperand(1) == Input) { 683 // For the upper range compare we have: icmp n, x 684 RangeEnd = Cmp1->getOperand(0); 685 Pred1 = ICmpInst::getSwappedPredicate(Pred1); 686 } else { 687 return nullptr; 688 } 689 690 // Check the upper range comparison, e.g. x < n 691 ICmpInst::Predicate NewPred; 692 switch (Pred1) { 693 case ICmpInst::ICMP_SLT: NewPred = ICmpInst::ICMP_ULT; break; 694 case ICmpInst::ICMP_SLE: NewPred = ICmpInst::ICMP_ULE; break; 695 default: return nullptr; 696 } 697 698 // This simplification is only valid if the upper range is not negative. 699 KnownBits Known = computeKnownBits(RangeEnd, /*Depth=*/0, Cmp1); 700 if (!Known.isNonNegative()) 701 return nullptr; 702 703 if (Inverted) 704 NewPred = ICmpInst::getInversePredicate(NewPred); 705 706 return Builder.CreateICmp(NewPred, Input, RangeEnd); 707 } 708 709 static Value * 710 foldAndOrOfEqualityCmpsWithConstants(ICmpInst *LHS, ICmpInst *RHS, 711 bool JoinedByAnd, 712 InstCombiner::BuilderTy &Builder) { 713 Value *X = LHS->getOperand(0); 714 if (X != RHS->getOperand(0)) 715 return nullptr; 716 717 const APInt *C1, *C2; 718 if (!match(LHS->getOperand(1), m_APInt(C1)) || 719 !match(RHS->getOperand(1), m_APInt(C2))) 720 return nullptr; 721 722 // We only handle (X != C1 && X != C2) and (X == C1 || X == C2). 723 ICmpInst::Predicate Pred = LHS->getPredicate(); 724 if (Pred != RHS->getPredicate()) 725 return nullptr; 726 if (JoinedByAnd && Pred != ICmpInst::ICMP_NE) 727 return nullptr; 728 if (!JoinedByAnd && Pred != ICmpInst::ICMP_EQ) 729 return nullptr; 730 731 // The larger unsigned constant goes on the right. 732 if (C1->ugt(*C2)) 733 std::swap(C1, C2); 734 735 APInt Xor = *C1 ^ *C2; 736 if (Xor.isPowerOf2()) { 737 // If LHSC and RHSC differ by only one bit, then set that bit in X and 738 // compare against the larger constant: 739 // (X == C1 || X == C2) --> (X | (C1 ^ C2)) == C2 740 // (X != C1 && X != C2) --> (X | (C1 ^ C2)) != C2 741 // We choose an 'or' with a Pow2 constant rather than the inverse mask with 742 // 'and' because that may lead to smaller codegen from a smaller constant. 743 Value *Or = Builder.CreateOr(X, ConstantInt::get(X->getType(), Xor)); 744 return Builder.CreateICmp(Pred, Or, ConstantInt::get(X->getType(), *C2)); 745 } 746 747 return nullptr; 748 } 749 750 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2) 751 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2) 752 Value *InstCombinerImpl::foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, 753 ICmpInst *RHS, 754 Instruction *CxtI, 755 bool IsAnd, 756 bool IsLogical) { 757 CmpInst::Predicate Pred = IsAnd ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ; 758 if (LHS->getPredicate() != Pred || RHS->getPredicate() != Pred) 759 return nullptr; 760 761 if (!match(LHS->getOperand(1), m_Zero()) || 762 !match(RHS->getOperand(1), m_Zero())) 763 return nullptr; 764 765 Value *L1, *L2, *R1, *R2; 766 if (match(LHS->getOperand(0), m_And(m_Value(L1), m_Value(L2))) && 767 match(RHS->getOperand(0), m_And(m_Value(R1), m_Value(R2)))) { 768 if (L1 == R2 || L2 == R2) 769 std::swap(R1, R2); 770 if (L2 == R1) 771 std::swap(L1, L2); 772 773 if (L1 == R1 && 774 isKnownToBeAPowerOfTwo(L2, false, 0, CxtI) && 775 isKnownToBeAPowerOfTwo(R2, false, 0, CxtI)) { 776 // If this is a logical and/or, then we must prevent propagation of a 777 // poison value from the RHS by inserting freeze. 778 if (IsLogical) 779 R2 = Builder.CreateFreeze(R2); 780 Value *Mask = Builder.CreateOr(L2, R2); 781 Value *Masked = Builder.CreateAnd(L1, Mask); 782 auto NewPred = IsAnd ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE; 783 return Builder.CreateICmp(NewPred, Masked, Mask); 784 } 785 } 786 787 return nullptr; 788 } 789 790 /// General pattern: 791 /// X & Y 792 /// 793 /// Where Y is checking that all the high bits (covered by a mask 4294967168) 794 /// are uniform, i.e. %arg & 4294967168 can be either 4294967168 or 0 795 /// Pattern can be one of: 796 /// %t = add i32 %arg, 128 797 /// %r = icmp ult i32 %t, 256 798 /// Or 799 /// %t0 = shl i32 %arg, 24 800 /// %t1 = ashr i32 %t0, 24 801 /// %r = icmp eq i32 %t1, %arg 802 /// Or 803 /// %t0 = trunc i32 %arg to i8 804 /// %t1 = sext i8 %t0 to i32 805 /// %r = icmp eq i32 %t1, %arg 806 /// This pattern is a signed truncation check. 807 /// 808 /// And X is checking that some bit in that same mask is zero. 809 /// I.e. can be one of: 810 /// %r = icmp sgt i32 %arg, -1 811 /// Or 812 /// %t = and i32 %arg, 2147483648 813 /// %r = icmp eq i32 %t, 0 814 /// 815 /// Since we are checking that all the bits in that mask are the same, 816 /// and a particular bit is zero, what we are really checking is that all the 817 /// masked bits are zero. 818 /// So this should be transformed to: 819 /// %r = icmp ult i32 %arg, 128 820 static Value *foldSignedTruncationCheck(ICmpInst *ICmp0, ICmpInst *ICmp1, 821 Instruction &CxtI, 822 InstCombiner::BuilderTy &Builder) { 823 assert(CxtI.getOpcode() == Instruction::And); 824 825 // Match icmp ult (add %arg, C01), C1 (C1 == C01 << 1; powers of two) 826 auto tryToMatchSignedTruncationCheck = [](ICmpInst *ICmp, Value *&X, 827 APInt &SignBitMask) -> bool { 828 CmpInst::Predicate Pred; 829 const APInt *I01, *I1; // powers of two; I1 == I01 << 1 830 if (!(match(ICmp, 831 m_ICmp(Pred, m_Add(m_Value(X), m_Power2(I01)), m_Power2(I1))) && 832 Pred == ICmpInst::ICMP_ULT && I1->ugt(*I01) && I01->shl(1) == *I1)) 833 return false; 834 // Which bit is the new sign bit as per the 'signed truncation' pattern? 835 SignBitMask = *I01; 836 return true; 837 }; 838 839 // One icmp needs to be 'signed truncation check'. 840 // We need to match this first, else we will mismatch commutative cases. 841 Value *X1; 842 APInt HighestBit; 843 ICmpInst *OtherICmp; 844 if (tryToMatchSignedTruncationCheck(ICmp1, X1, HighestBit)) 845 OtherICmp = ICmp0; 846 else if (tryToMatchSignedTruncationCheck(ICmp0, X1, HighestBit)) 847 OtherICmp = ICmp1; 848 else 849 return nullptr; 850 851 assert(HighestBit.isPowerOf2() && "expected to be power of two (non-zero)"); 852 853 // Try to match/decompose into: icmp eq (X & Mask), 0 854 auto tryToDecompose = [](ICmpInst *ICmp, Value *&X, 855 APInt &UnsetBitsMask) -> bool { 856 CmpInst::Predicate Pred = ICmp->getPredicate(); 857 // Can it be decomposed into icmp eq (X & Mask), 0 ? 858 if (llvm::decomposeBitTestICmp(ICmp->getOperand(0), ICmp->getOperand(1), 859 Pred, X, UnsetBitsMask, 860 /*LookThroughTrunc=*/false) && 861 Pred == ICmpInst::ICMP_EQ) 862 return true; 863 // Is it icmp eq (X & Mask), 0 already? 864 const APInt *Mask; 865 if (match(ICmp, m_ICmp(Pred, m_And(m_Value(X), m_APInt(Mask)), m_Zero())) && 866 Pred == ICmpInst::ICMP_EQ) { 867 UnsetBitsMask = *Mask; 868 return true; 869 } 870 return false; 871 }; 872 873 // And the other icmp needs to be decomposable into a bit test. 874 Value *X0; 875 APInt UnsetBitsMask; 876 if (!tryToDecompose(OtherICmp, X0, UnsetBitsMask)) 877 return nullptr; 878 879 assert(!UnsetBitsMask.isZero() && "empty mask makes no sense."); 880 881 // Are they working on the same value? 882 Value *X; 883 if (X1 == X0) { 884 // Ok as is. 885 X = X1; 886 } else if (match(X0, m_Trunc(m_Specific(X1)))) { 887 UnsetBitsMask = UnsetBitsMask.zext(X1->getType()->getScalarSizeInBits()); 888 X = X1; 889 } else 890 return nullptr; 891 892 // So which bits should be uniform as per the 'signed truncation check'? 893 // (all the bits starting with (i.e. including) HighestBit) 894 APInt SignBitsMask = ~(HighestBit - 1U); 895 896 // UnsetBitsMask must have some common bits with SignBitsMask, 897 if (!UnsetBitsMask.intersects(SignBitsMask)) 898 return nullptr; 899 900 // Does UnsetBitsMask contain any bits outside of SignBitsMask? 901 if (!UnsetBitsMask.isSubsetOf(SignBitsMask)) { 902 APInt OtherHighestBit = (~UnsetBitsMask) + 1U; 903 if (!OtherHighestBit.isPowerOf2()) 904 return nullptr; 905 HighestBit = APIntOps::umin(HighestBit, OtherHighestBit); 906 } 907 // Else, if it does not, then all is ok as-is. 908 909 // %r = icmp ult %X, SignBit 910 return Builder.CreateICmpULT(X, ConstantInt::get(X->getType(), HighestBit), 911 CxtI.getName() + ".simplified"); 912 } 913 914 /// Fold (icmp eq ctpop(X) 1) | (icmp eq X 0) into (icmp ult ctpop(X) 2) and 915 /// fold (icmp ne ctpop(X) 1) & (icmp ne X 0) into (icmp ugt ctpop(X) 1). 916 static Value *foldIsPowerOf2OrZero(ICmpInst *Cmp0, ICmpInst *Cmp1, bool IsAnd, 917 InstCombiner::BuilderTy &Builder) { 918 CmpInst::Predicate Pred0, Pred1; 919 Value *X; 920 if (!match(Cmp0, m_ICmp(Pred0, m_Intrinsic<Intrinsic::ctpop>(m_Value(X)), 921 m_SpecificInt(1))) || 922 !match(Cmp1, m_ICmp(Pred1, m_Specific(X), m_ZeroInt()))) 923 return nullptr; 924 925 Value *CtPop = Cmp0->getOperand(0); 926 if (IsAnd && Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_NE) 927 return Builder.CreateICmpUGT(CtPop, ConstantInt::get(CtPop->getType(), 1)); 928 if (!IsAnd && Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_EQ) 929 return Builder.CreateICmpULT(CtPop, ConstantInt::get(CtPop->getType(), 2)); 930 931 return nullptr; 932 } 933 934 /// Reduce a pair of compares that check if a value has exactly 1 bit set. 935 static Value *foldIsPowerOf2(ICmpInst *Cmp0, ICmpInst *Cmp1, bool JoinedByAnd, 936 InstCombiner::BuilderTy &Builder) { 937 // Handle 'and' / 'or' commutation: make the equality check the first operand. 938 if (JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_NE) 939 std::swap(Cmp0, Cmp1); 940 else if (!JoinedByAnd && Cmp1->getPredicate() == ICmpInst::ICMP_EQ) 941 std::swap(Cmp0, Cmp1); 942 943 // (X != 0) && (ctpop(X) u< 2) --> ctpop(X) == 1 944 CmpInst::Predicate Pred0, Pred1; 945 Value *X; 946 if (JoinedByAnd && match(Cmp0, m_ICmp(Pred0, m_Value(X), m_ZeroInt())) && 947 match(Cmp1, m_ICmp(Pred1, m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)), 948 m_SpecificInt(2))) && 949 Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_ULT) { 950 Value *CtPop = Cmp1->getOperand(0); 951 return Builder.CreateICmpEQ(CtPop, ConstantInt::get(CtPop->getType(), 1)); 952 } 953 // (X == 0) || (ctpop(X) u> 1) --> ctpop(X) != 1 954 if (!JoinedByAnd && match(Cmp0, m_ICmp(Pred0, m_Value(X), m_ZeroInt())) && 955 match(Cmp1, m_ICmp(Pred1, m_Intrinsic<Intrinsic::ctpop>(m_Specific(X)), 956 m_SpecificInt(1))) && 957 Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_UGT) { 958 Value *CtPop = Cmp1->getOperand(0); 959 return Builder.CreateICmpNE(CtPop, ConstantInt::get(CtPop->getType(), 1)); 960 } 961 return nullptr; 962 } 963 964 /// Commuted variants are assumed to be handled by calling this function again 965 /// with the parameters swapped. 966 static Value *foldUnsignedUnderflowCheck(ICmpInst *ZeroICmp, 967 ICmpInst *UnsignedICmp, bool IsAnd, 968 const SimplifyQuery &Q, 969 InstCombiner::BuilderTy &Builder) { 970 Value *ZeroCmpOp; 971 ICmpInst::Predicate EqPred; 972 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(ZeroCmpOp), m_Zero())) || 973 !ICmpInst::isEquality(EqPred)) 974 return nullptr; 975 976 auto IsKnownNonZero = [&](Value *V) { 977 return isKnownNonZero(V, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT); 978 }; 979 980 ICmpInst::Predicate UnsignedPred; 981 982 Value *A, *B; 983 if (match(UnsignedICmp, 984 m_c_ICmp(UnsignedPred, m_Specific(ZeroCmpOp), m_Value(A))) && 985 match(ZeroCmpOp, m_c_Add(m_Specific(A), m_Value(B))) && 986 (ZeroICmp->hasOneUse() || UnsignedICmp->hasOneUse())) { 987 auto GetKnownNonZeroAndOther = [&](Value *&NonZero, Value *&Other) { 988 if (!IsKnownNonZero(NonZero)) 989 std::swap(NonZero, Other); 990 return IsKnownNonZero(NonZero); 991 }; 992 993 // Given ZeroCmpOp = (A + B) 994 // ZeroCmpOp <= A && ZeroCmpOp != 0 --> (0-B) < A 995 // ZeroCmpOp > A || ZeroCmpOp == 0 --> (0-B) >= A 996 // 997 // ZeroCmpOp < A && ZeroCmpOp != 0 --> (0-X) < Y iff 998 // ZeroCmpOp >= A || ZeroCmpOp == 0 --> (0-X) >= Y iff 999 // with X being the value (A/B) that is known to be non-zero, 1000 // and Y being remaining value. 1001 if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE && 1002 IsAnd) 1003 return Builder.CreateICmpULT(Builder.CreateNeg(B), A); 1004 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE && 1005 IsAnd && GetKnownNonZeroAndOther(B, A)) 1006 return Builder.CreateICmpULT(Builder.CreateNeg(B), A); 1007 if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ && 1008 !IsAnd) 1009 return Builder.CreateICmpUGE(Builder.CreateNeg(B), A); 1010 if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ && 1011 !IsAnd && GetKnownNonZeroAndOther(B, A)) 1012 return Builder.CreateICmpUGE(Builder.CreateNeg(B), A); 1013 } 1014 1015 Value *Base, *Offset; 1016 if (!match(ZeroCmpOp, m_Sub(m_Value(Base), m_Value(Offset)))) 1017 return nullptr; 1018 1019 if (!match(UnsignedICmp, 1020 m_c_ICmp(UnsignedPred, m_Specific(Base), m_Specific(Offset))) || 1021 !ICmpInst::isUnsigned(UnsignedPred)) 1022 return nullptr; 1023 1024 // Base >=/> Offset && (Base - Offset) != 0 <--> Base > Offset 1025 // (no overflow and not null) 1026 if ((UnsignedPred == ICmpInst::ICMP_UGE || 1027 UnsignedPred == ICmpInst::ICMP_UGT) && 1028 EqPred == ICmpInst::ICMP_NE && IsAnd) 1029 return Builder.CreateICmpUGT(Base, Offset); 1030 1031 // Base <=/< Offset || (Base - Offset) == 0 <--> Base <= Offset 1032 // (overflow or null) 1033 if ((UnsignedPred == ICmpInst::ICMP_ULE || 1034 UnsignedPred == ICmpInst::ICMP_ULT) && 1035 EqPred == ICmpInst::ICMP_EQ && !IsAnd) 1036 return Builder.CreateICmpULE(Base, Offset); 1037 1038 // Base <= Offset && (Base - Offset) != 0 --> Base < Offset 1039 if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE && 1040 IsAnd) 1041 return Builder.CreateICmpULT(Base, Offset); 1042 1043 // Base > Offset || (Base - Offset) == 0 --> Base >= Offset 1044 if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ && 1045 !IsAnd) 1046 return Builder.CreateICmpUGE(Base, Offset); 1047 1048 return nullptr; 1049 } 1050 1051 struct IntPart { 1052 Value *From; 1053 unsigned StartBit; 1054 unsigned NumBits; 1055 }; 1056 1057 /// Match an extraction of bits from an integer. 1058 static Optional<IntPart> matchIntPart(Value *V) { 1059 Value *X; 1060 if (!match(V, m_OneUse(m_Trunc(m_Value(X))))) 1061 return None; 1062 1063 unsigned NumOriginalBits = X->getType()->getScalarSizeInBits(); 1064 unsigned NumExtractedBits = V->getType()->getScalarSizeInBits(); 1065 Value *Y; 1066 const APInt *Shift; 1067 // For a trunc(lshr Y, Shift) pattern, make sure we're only extracting bits 1068 // from Y, not any shifted-in zeroes. 1069 if (match(X, m_OneUse(m_LShr(m_Value(Y), m_APInt(Shift)))) && 1070 Shift->ule(NumOriginalBits - NumExtractedBits)) 1071 return {{Y, (unsigned)Shift->getZExtValue(), NumExtractedBits}}; 1072 return {{X, 0, NumExtractedBits}}; 1073 } 1074 1075 /// Materialize an extraction of bits from an integer in IR. 1076 static Value *extractIntPart(const IntPart &P, IRBuilderBase &Builder) { 1077 Value *V = P.From; 1078 if (P.StartBit) 1079 V = Builder.CreateLShr(V, P.StartBit); 1080 Type *TruncTy = V->getType()->getWithNewBitWidth(P.NumBits); 1081 if (TruncTy != V->getType()) 1082 V = Builder.CreateTrunc(V, TruncTy); 1083 return V; 1084 } 1085 1086 /// (icmp eq X0, Y0) & (icmp eq X1, Y1) -> icmp eq X01, Y01 1087 /// (icmp ne X0, Y0) | (icmp ne X1, Y1) -> icmp ne X01, Y01 1088 /// where X0, X1 and Y0, Y1 are adjacent parts extracted from an integer. 1089 Value *InstCombinerImpl::foldEqOfParts(ICmpInst *Cmp0, ICmpInst *Cmp1, 1090 bool IsAnd) { 1091 if (!Cmp0->hasOneUse() || !Cmp1->hasOneUse()) 1092 return nullptr; 1093 1094 CmpInst::Predicate Pred = IsAnd ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE; 1095 if (Cmp0->getPredicate() != Pred || Cmp1->getPredicate() != Pred) 1096 return nullptr; 1097 1098 Optional<IntPart> L0 = matchIntPart(Cmp0->getOperand(0)); 1099 Optional<IntPart> R0 = matchIntPart(Cmp0->getOperand(1)); 1100 Optional<IntPart> L1 = matchIntPart(Cmp1->getOperand(0)); 1101 Optional<IntPart> R1 = matchIntPart(Cmp1->getOperand(1)); 1102 if (!L0 || !R0 || !L1 || !R1) 1103 return nullptr; 1104 1105 // Make sure the LHS/RHS compare a part of the same value, possibly after 1106 // an operand swap. 1107 if (L0->From != L1->From || R0->From != R1->From) { 1108 if (L0->From != R1->From || R0->From != L1->From) 1109 return nullptr; 1110 std::swap(L1, R1); 1111 } 1112 1113 // Make sure the extracted parts are adjacent, canonicalizing to L0/R0 being 1114 // the low part and L1/R1 being the high part. 1115 if (L0->StartBit + L0->NumBits != L1->StartBit || 1116 R0->StartBit + R0->NumBits != R1->StartBit) { 1117 if (L1->StartBit + L1->NumBits != L0->StartBit || 1118 R1->StartBit + R1->NumBits != R0->StartBit) 1119 return nullptr; 1120 std::swap(L0, L1); 1121 std::swap(R0, R1); 1122 } 1123 1124 // We can simplify to a comparison of these larger parts of the integers. 1125 IntPart L = {L0->From, L0->StartBit, L0->NumBits + L1->NumBits}; 1126 IntPart R = {R0->From, R0->StartBit, R0->NumBits + R1->NumBits}; 1127 Value *LValue = extractIntPart(L, Builder); 1128 Value *RValue = extractIntPart(R, Builder); 1129 return Builder.CreateICmp(Pred, LValue, RValue); 1130 } 1131 1132 /// Reduce logic-of-compares with equality to a constant by substituting a 1133 /// common operand with the constant. Callers are expected to call this with 1134 /// Cmp0/Cmp1 switched to handle logic op commutativity. 1135 static Value *foldAndOrOfICmpsWithConstEq(ICmpInst *Cmp0, ICmpInst *Cmp1, 1136 BinaryOperator &Logic, 1137 InstCombiner::BuilderTy &Builder, 1138 const SimplifyQuery &Q) { 1139 bool IsAnd = Logic.getOpcode() == Instruction::And; 1140 assert((IsAnd || Logic.getOpcode() == Instruction::Or) && "Wrong logic op"); 1141 1142 // Match an equality compare with a non-poison constant as Cmp0. 1143 // Also, give up if the compare can be constant-folded to avoid looping. 1144 ICmpInst::Predicate Pred0; 1145 Value *X; 1146 Constant *C; 1147 if (!match(Cmp0, m_ICmp(Pred0, m_Value(X), m_Constant(C))) || 1148 !isGuaranteedNotToBeUndefOrPoison(C) || isa<Constant>(X)) 1149 return nullptr; 1150 if ((IsAnd && Pred0 != ICmpInst::ICMP_EQ) || 1151 (!IsAnd && Pred0 != ICmpInst::ICMP_NE)) 1152 return nullptr; 1153 1154 // The other compare must include a common operand (X). Canonicalize the 1155 // common operand as operand 1 (Pred1 is swapped if the common operand was 1156 // operand 0). 1157 Value *Y; 1158 ICmpInst::Predicate Pred1; 1159 if (!match(Cmp1, m_c_ICmp(Pred1, m_Value(Y), m_Deferred(X)))) 1160 return nullptr; 1161 1162 // Replace variable with constant value equivalence to remove a variable use: 1163 // (X == C) && (Y Pred1 X) --> (X == C) && (Y Pred1 C) 1164 // (X != C) || (Y Pred1 X) --> (X != C) || (Y Pred1 C) 1165 // Can think of the 'or' substitution with the 'and' bool equivalent: 1166 // A || B --> A || (!A && B) 1167 Value *SubstituteCmp = SimplifyICmpInst(Pred1, Y, C, Q); 1168 if (!SubstituteCmp) { 1169 // If we need to create a new instruction, require that the old compare can 1170 // be removed. 1171 if (!Cmp1->hasOneUse()) 1172 return nullptr; 1173 SubstituteCmp = Builder.CreateICmp(Pred1, Y, C); 1174 } 1175 return Builder.CreateBinOp(Logic.getOpcode(), Cmp0, SubstituteCmp); 1176 } 1177 1178 /// Fold (icmp Pred1 V1, C1) & (icmp Pred2 V2, C2) 1179 /// or (icmp Pred1 V1, C1) | (icmp Pred2 V2, C2) 1180 /// into a single comparison using range-based reasoning. 1181 static Value *foldAndOrOfICmpsUsingRanges( 1182 ICmpInst::Predicate Pred1, Value *V1, const APInt &C1, 1183 ICmpInst::Predicate Pred2, Value *V2, const APInt &C2, 1184 IRBuilderBase &Builder, bool IsAnd) { 1185 // Look through add of a constant offset on V1, V2, or both operands. This 1186 // allows us to interpret the V + C' < C'' range idiom into a proper range. 1187 const APInt *Offset1 = nullptr, *Offset2 = nullptr; 1188 if (V1 != V2) { 1189 Value *X; 1190 if (match(V1, m_Add(m_Value(X), m_APInt(Offset1)))) 1191 V1 = X; 1192 if (match(V2, m_Add(m_Value(X), m_APInt(Offset2)))) 1193 V2 = X; 1194 } 1195 1196 if (V1 != V2) 1197 return nullptr; 1198 1199 ConstantRange CR1 = ConstantRange::makeExactICmpRegion(Pred1, C1); 1200 if (Offset1) 1201 CR1 = CR1.subtract(*Offset1); 1202 1203 ConstantRange CR2 = ConstantRange::makeExactICmpRegion(Pred2, C2); 1204 if (Offset2) 1205 CR2 = CR2.subtract(*Offset2); 1206 1207 Optional<ConstantRange> CR = 1208 IsAnd ? CR1.exactIntersectWith(CR2) : CR1.exactUnionWith(CR2); 1209 if (!CR) 1210 return nullptr; 1211 1212 CmpInst::Predicate NewPred; 1213 APInt NewC, Offset; 1214 CR->getEquivalentICmp(NewPred, NewC, Offset); 1215 1216 Type *Ty = V1->getType(); 1217 Value *NewV = V1; 1218 if (Offset != 0) 1219 NewV = Builder.CreateAdd(NewV, ConstantInt::get(Ty, Offset)); 1220 return Builder.CreateICmp(NewPred, NewV, ConstantInt::get(Ty, NewC)); 1221 } 1222 1223 Value *InstCombinerImpl::foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS, 1224 bool IsAnd, bool IsLogicalSelect) { 1225 Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1); 1226 Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1); 1227 FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate(); 1228 1229 if (LHS0 == RHS1 && RHS0 == LHS1) { 1230 // Swap RHS operands to match LHS. 1231 PredR = FCmpInst::getSwappedPredicate(PredR); 1232 std::swap(RHS0, RHS1); 1233 } 1234 1235 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y). 1236 // Suppose the relation between x and y is R, where R is one of 1237 // U(1000), L(0100), G(0010) or E(0001), and CC0 and CC1 are the bitmasks for 1238 // testing the desired relations. 1239 // 1240 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this: 1241 // bool(R & CC0) && bool(R & CC1) 1242 // = bool((R & CC0) & (R & CC1)) 1243 // = bool(R & (CC0 & CC1)) <= by re-association, commutation, and idempotency 1244 // 1245 // Since (R & CC0) and (R & CC1) are either R or 0, we actually have this: 1246 // bool(R & CC0) || bool(R & CC1) 1247 // = bool((R & CC0) | (R & CC1)) 1248 // = bool(R & (CC0 | CC1)) <= by reversed distribution (contribution? ;) 1249 if (LHS0 == RHS0 && LHS1 == RHS1) { 1250 unsigned FCmpCodeL = getFCmpCode(PredL); 1251 unsigned FCmpCodeR = getFCmpCode(PredR); 1252 unsigned NewPred = IsAnd ? FCmpCodeL & FCmpCodeR : FCmpCodeL | FCmpCodeR; 1253 1254 // Intersect the fast math flags. 1255 // TODO: We can union the fast math flags unless this is a logical select. 1256 IRBuilder<>::FastMathFlagGuard FMFG(Builder); 1257 FastMathFlags FMF = LHS->getFastMathFlags(); 1258 FMF &= RHS->getFastMathFlags(); 1259 Builder.setFastMathFlags(FMF); 1260 1261 return getFCmpValue(NewPred, LHS0, LHS1, Builder); 1262 } 1263 1264 // This transform is not valid for a logical select. 1265 if (!IsLogicalSelect && 1266 ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) || 1267 (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && 1268 !IsAnd))) { 1269 if (LHS0->getType() != RHS0->getType()) 1270 return nullptr; 1271 1272 // FCmp canonicalization ensures that (fcmp ord/uno X, X) and 1273 // (fcmp ord/uno X, C) will be transformed to (fcmp X, +0.0). 1274 if (match(LHS1, m_PosZeroFP()) && match(RHS1, m_PosZeroFP())) 1275 // Ignore the constants because they are obviously not NANs: 1276 // (fcmp ord x, 0.0) & (fcmp ord y, 0.0) -> (fcmp ord x, y) 1277 // (fcmp uno x, 0.0) | (fcmp uno y, 0.0) -> (fcmp uno x, y) 1278 return Builder.CreateFCmp(PredL, LHS0, RHS0); 1279 } 1280 1281 return nullptr; 1282 } 1283 1284 /// This a limited reassociation for a special case (see above) where we are 1285 /// checking if two values are either both NAN (unordered) or not-NAN (ordered). 1286 /// This could be handled more generally in '-reassociation', but it seems like 1287 /// an unlikely pattern for a large number of logic ops and fcmps. 1288 static Instruction *reassociateFCmps(BinaryOperator &BO, 1289 InstCombiner::BuilderTy &Builder) { 1290 Instruction::BinaryOps Opcode = BO.getOpcode(); 1291 assert((Opcode == Instruction::And || Opcode == Instruction::Or) && 1292 "Expecting and/or op for fcmp transform"); 1293 1294 // There are 4 commuted variants of the pattern. Canonicalize operands of this 1295 // logic op so an fcmp is operand 0 and a matching logic op is operand 1. 1296 Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1), *X; 1297 FCmpInst::Predicate Pred; 1298 if (match(Op1, m_FCmp(Pred, m_Value(), m_AnyZeroFP()))) 1299 std::swap(Op0, Op1); 1300 1301 // Match inner binop and the predicate for combining 2 NAN checks into 1. 1302 Value *BO10, *BO11; 1303 FCmpInst::Predicate NanPred = Opcode == Instruction::And ? FCmpInst::FCMP_ORD 1304 : FCmpInst::FCMP_UNO; 1305 if (!match(Op0, m_FCmp(Pred, m_Value(X), m_AnyZeroFP())) || Pred != NanPred || 1306 !match(Op1, m_BinOp(Opcode, m_Value(BO10), m_Value(BO11)))) 1307 return nullptr; 1308 1309 // The inner logic op must have a matching fcmp operand. 1310 Value *Y; 1311 if (!match(BO10, m_FCmp(Pred, m_Value(Y), m_AnyZeroFP())) || 1312 Pred != NanPred || X->getType() != Y->getType()) 1313 std::swap(BO10, BO11); 1314 1315 if (!match(BO10, m_FCmp(Pred, m_Value(Y), m_AnyZeroFP())) || 1316 Pred != NanPred || X->getType() != Y->getType()) 1317 return nullptr; 1318 1319 // and (fcmp ord X, 0), (and (fcmp ord Y, 0), Z) --> and (fcmp ord X, Y), Z 1320 // or (fcmp uno X, 0), (or (fcmp uno Y, 0), Z) --> or (fcmp uno X, Y), Z 1321 Value *NewFCmp = Builder.CreateFCmp(Pred, X, Y); 1322 if (auto *NewFCmpInst = dyn_cast<FCmpInst>(NewFCmp)) { 1323 // Intersect FMF from the 2 source fcmps. 1324 NewFCmpInst->copyIRFlags(Op0); 1325 NewFCmpInst->andIRFlags(BO10); 1326 } 1327 return BinaryOperator::Create(Opcode, NewFCmp, BO11); 1328 } 1329 1330 /// Match variations of De Morgan's Laws: 1331 /// (~A & ~B) == (~(A | B)) 1332 /// (~A | ~B) == (~(A & B)) 1333 static Instruction *matchDeMorgansLaws(BinaryOperator &I, 1334 InstCombiner::BuilderTy &Builder) { 1335 const Instruction::BinaryOps Opcode = I.getOpcode(); 1336 assert((Opcode == Instruction::And || Opcode == Instruction::Or) && 1337 "Trying to match De Morgan's Laws with something other than and/or"); 1338 1339 // Flip the logic operation. 1340 const Instruction::BinaryOps FlippedOpcode = 1341 (Opcode == Instruction::And) ? Instruction::Or : Instruction::And; 1342 1343 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1344 Value *A, *B; 1345 if (match(Op0, m_OneUse(m_Not(m_Value(A)))) && 1346 match(Op1, m_OneUse(m_Not(m_Value(B)))) && 1347 !InstCombiner::isFreeToInvert(A, A->hasOneUse()) && 1348 !InstCombiner::isFreeToInvert(B, B->hasOneUse())) { 1349 Value *AndOr = 1350 Builder.CreateBinOp(FlippedOpcode, A, B, I.getName() + ".demorgan"); 1351 return BinaryOperator::CreateNot(AndOr); 1352 } 1353 1354 // The 'not' ops may require reassociation. 1355 // (A & ~B) & ~C --> A & ~(B | C) 1356 // (~B & A) & ~C --> A & ~(B | C) 1357 // (A | ~B) | ~C --> A | ~(B & C) 1358 // (~B | A) | ~C --> A | ~(B & C) 1359 Value *C; 1360 if (match(Op0, m_OneUse(m_c_BinOp(Opcode, m_Value(A), m_Not(m_Value(B))))) && 1361 match(Op1, m_Not(m_Value(C)))) { 1362 Value *FlippedBO = Builder.CreateBinOp(FlippedOpcode, B, C); 1363 return BinaryOperator::Create(Opcode, A, Builder.CreateNot(FlippedBO)); 1364 } 1365 1366 return nullptr; 1367 } 1368 1369 bool InstCombinerImpl::shouldOptimizeCast(CastInst *CI) { 1370 Value *CastSrc = CI->getOperand(0); 1371 1372 // Noop casts and casts of constants should be eliminated trivially. 1373 if (CI->getSrcTy() == CI->getDestTy() || isa<Constant>(CastSrc)) 1374 return false; 1375 1376 // If this cast is paired with another cast that can be eliminated, we prefer 1377 // to have it eliminated. 1378 if (const auto *PrecedingCI = dyn_cast<CastInst>(CastSrc)) 1379 if (isEliminableCastPair(PrecedingCI, CI)) 1380 return false; 1381 1382 return true; 1383 } 1384 1385 /// Fold {and,or,xor} (cast X), C. 1386 static Instruction *foldLogicCastConstant(BinaryOperator &Logic, CastInst *Cast, 1387 InstCombiner::BuilderTy &Builder) { 1388 Constant *C = dyn_cast<Constant>(Logic.getOperand(1)); 1389 if (!C) 1390 return nullptr; 1391 1392 auto LogicOpc = Logic.getOpcode(); 1393 Type *DestTy = Logic.getType(); 1394 Type *SrcTy = Cast->getSrcTy(); 1395 1396 // Move the logic operation ahead of a zext or sext if the constant is 1397 // unchanged in the smaller source type. Performing the logic in a smaller 1398 // type may provide more information to later folds, and the smaller logic 1399 // instruction may be cheaper (particularly in the case of vectors). 1400 Value *X; 1401 if (match(Cast, m_OneUse(m_ZExt(m_Value(X))))) { 1402 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy); 1403 Constant *ZextTruncC = ConstantExpr::getZExt(TruncC, DestTy); 1404 if (ZextTruncC == C) { 1405 // LogicOpc (zext X), C --> zext (LogicOpc X, C) 1406 Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC); 1407 return new ZExtInst(NewOp, DestTy); 1408 } 1409 } 1410 1411 if (match(Cast, m_OneUse(m_SExt(m_Value(X))))) { 1412 Constant *TruncC = ConstantExpr::getTrunc(C, SrcTy); 1413 Constant *SextTruncC = ConstantExpr::getSExt(TruncC, DestTy); 1414 if (SextTruncC == C) { 1415 // LogicOpc (sext X), C --> sext (LogicOpc X, C) 1416 Value *NewOp = Builder.CreateBinOp(LogicOpc, X, TruncC); 1417 return new SExtInst(NewOp, DestTy); 1418 } 1419 } 1420 1421 return nullptr; 1422 } 1423 1424 /// Fold {and,or,xor} (cast X), Y. 1425 Instruction *InstCombinerImpl::foldCastedBitwiseLogic(BinaryOperator &I) { 1426 auto LogicOpc = I.getOpcode(); 1427 assert(I.isBitwiseLogicOp() && "Unexpected opcode for bitwise logic folding"); 1428 1429 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1430 CastInst *Cast0 = dyn_cast<CastInst>(Op0); 1431 if (!Cast0) 1432 return nullptr; 1433 1434 // This must be a cast from an integer or integer vector source type to allow 1435 // transformation of the logic operation to the source type. 1436 Type *DestTy = I.getType(); 1437 Type *SrcTy = Cast0->getSrcTy(); 1438 if (!SrcTy->isIntOrIntVectorTy()) 1439 return nullptr; 1440 1441 if (Instruction *Ret = foldLogicCastConstant(I, Cast0, Builder)) 1442 return Ret; 1443 1444 CastInst *Cast1 = dyn_cast<CastInst>(Op1); 1445 if (!Cast1) 1446 return nullptr; 1447 1448 // Both operands of the logic operation are casts. The casts must be of the 1449 // same type for reduction. 1450 auto CastOpcode = Cast0->getOpcode(); 1451 if (CastOpcode != Cast1->getOpcode() || SrcTy != Cast1->getSrcTy()) 1452 return nullptr; 1453 1454 Value *Cast0Src = Cast0->getOperand(0); 1455 Value *Cast1Src = Cast1->getOperand(0); 1456 1457 // fold logic(cast(A), cast(B)) -> cast(logic(A, B)) 1458 if (shouldOptimizeCast(Cast0) && shouldOptimizeCast(Cast1)) { 1459 Value *NewOp = Builder.CreateBinOp(LogicOpc, Cast0Src, Cast1Src, 1460 I.getName()); 1461 return CastInst::Create(CastOpcode, NewOp, DestTy); 1462 } 1463 1464 // For now, only 'and'/'or' have optimizations after this. 1465 if (LogicOpc == Instruction::Xor) 1466 return nullptr; 1467 1468 // If this is logic(cast(icmp), cast(icmp)), try to fold this even if the 1469 // cast is otherwise not optimizable. This happens for vector sexts. 1470 ICmpInst *ICmp0 = dyn_cast<ICmpInst>(Cast0Src); 1471 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(Cast1Src); 1472 if (ICmp0 && ICmp1) { 1473 if (Value *Res = 1474 foldAndOrOfICmps(ICmp0, ICmp1, I, LogicOpc == Instruction::And)) 1475 return CastInst::Create(CastOpcode, Res, DestTy); 1476 return nullptr; 1477 } 1478 1479 // If this is logic(cast(fcmp), cast(fcmp)), try to fold this even if the 1480 // cast is otherwise not optimizable. This happens for vector sexts. 1481 FCmpInst *FCmp0 = dyn_cast<FCmpInst>(Cast0Src); 1482 FCmpInst *FCmp1 = dyn_cast<FCmpInst>(Cast1Src); 1483 if (FCmp0 && FCmp1) 1484 if (Value *R = foldLogicOfFCmps(FCmp0, FCmp1, LogicOpc == Instruction::And)) 1485 return CastInst::Create(CastOpcode, R, DestTy); 1486 1487 return nullptr; 1488 } 1489 1490 static Instruction *foldAndToXor(BinaryOperator &I, 1491 InstCombiner::BuilderTy &Builder) { 1492 assert(I.getOpcode() == Instruction::And); 1493 Value *Op0 = I.getOperand(0); 1494 Value *Op1 = I.getOperand(1); 1495 Value *A, *B; 1496 1497 // Operand complexity canonicalization guarantees that the 'or' is Op0. 1498 // (A | B) & ~(A & B) --> A ^ B 1499 // (A | B) & ~(B & A) --> A ^ B 1500 if (match(&I, m_BinOp(m_Or(m_Value(A), m_Value(B)), 1501 m_Not(m_c_And(m_Deferred(A), m_Deferred(B)))))) 1502 return BinaryOperator::CreateXor(A, B); 1503 1504 // (A | ~B) & (~A | B) --> ~(A ^ B) 1505 // (A | ~B) & (B | ~A) --> ~(A ^ B) 1506 // (~B | A) & (~A | B) --> ~(A ^ B) 1507 // (~B | A) & (B | ~A) --> ~(A ^ B) 1508 if (Op0->hasOneUse() || Op1->hasOneUse()) 1509 if (match(&I, m_BinOp(m_c_Or(m_Value(A), m_Not(m_Value(B))), 1510 m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B))))) 1511 return BinaryOperator::CreateNot(Builder.CreateXor(A, B)); 1512 1513 return nullptr; 1514 } 1515 1516 static Instruction *foldOrToXor(BinaryOperator &I, 1517 InstCombiner::BuilderTy &Builder) { 1518 assert(I.getOpcode() == Instruction::Or); 1519 Value *Op0 = I.getOperand(0); 1520 Value *Op1 = I.getOperand(1); 1521 Value *A, *B; 1522 1523 // Operand complexity canonicalization guarantees that the 'and' is Op0. 1524 // (A & B) | ~(A | B) --> ~(A ^ B) 1525 // (A & B) | ~(B | A) --> ~(A ^ B) 1526 if (Op0->hasOneUse() || Op1->hasOneUse()) 1527 if (match(Op0, m_And(m_Value(A), m_Value(B))) && 1528 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))) 1529 return BinaryOperator::CreateNot(Builder.CreateXor(A, B)); 1530 1531 // Operand complexity canonicalization guarantees that the 'xor' is Op0. 1532 // (A ^ B) | ~(A | B) --> ~(A & B) 1533 // (A ^ B) | ~(B | A) --> ~(A & B) 1534 if (Op0->hasOneUse() || Op1->hasOneUse()) 1535 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) && 1536 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))) 1537 return BinaryOperator::CreateNot(Builder.CreateAnd(A, B)); 1538 1539 // (A & ~B) | (~A & B) --> A ^ B 1540 // (A & ~B) | (B & ~A) --> A ^ B 1541 // (~B & A) | (~A & B) --> A ^ B 1542 // (~B & A) | (B & ~A) --> A ^ B 1543 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) && 1544 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))) 1545 return BinaryOperator::CreateXor(A, B); 1546 1547 return nullptr; 1548 } 1549 1550 /// Return true if a constant shift amount is always less than the specified 1551 /// bit-width. If not, the shift could create poison in the narrower type. 1552 static bool canNarrowShiftAmt(Constant *C, unsigned BitWidth) { 1553 APInt Threshold(C->getType()->getScalarSizeInBits(), BitWidth); 1554 return match(C, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, Threshold)); 1555 } 1556 1557 /// Try to use narrower ops (sink zext ops) for an 'and' with binop operand and 1558 /// a common zext operand: and (binop (zext X), C), (zext X). 1559 Instruction *InstCombinerImpl::narrowMaskedBinOp(BinaryOperator &And) { 1560 // This transform could also apply to {or, and, xor}, but there are better 1561 // folds for those cases, so we don't expect those patterns here. AShr is not 1562 // handled because it should always be transformed to LShr in this sequence. 1563 // The subtract transform is different because it has a constant on the left. 1564 // Add/mul commute the constant to RHS; sub with constant RHS becomes add. 1565 Value *Op0 = And.getOperand(0), *Op1 = And.getOperand(1); 1566 Constant *C; 1567 if (!match(Op0, m_OneUse(m_Add(m_Specific(Op1), m_Constant(C)))) && 1568 !match(Op0, m_OneUse(m_Mul(m_Specific(Op1), m_Constant(C)))) && 1569 !match(Op0, m_OneUse(m_LShr(m_Specific(Op1), m_Constant(C)))) && 1570 !match(Op0, m_OneUse(m_Shl(m_Specific(Op1), m_Constant(C)))) && 1571 !match(Op0, m_OneUse(m_Sub(m_Constant(C), m_Specific(Op1))))) 1572 return nullptr; 1573 1574 Value *X; 1575 if (!match(Op1, m_ZExt(m_Value(X))) || Op1->hasNUsesOrMore(3)) 1576 return nullptr; 1577 1578 Type *Ty = And.getType(); 1579 if (!isa<VectorType>(Ty) && !shouldChangeType(Ty, X->getType())) 1580 return nullptr; 1581 1582 // If we're narrowing a shift, the shift amount must be safe (less than the 1583 // width) in the narrower type. If the shift amount is greater, instsimplify 1584 // usually handles that case, but we can't guarantee/assert it. 1585 Instruction::BinaryOps Opc = cast<BinaryOperator>(Op0)->getOpcode(); 1586 if (Opc == Instruction::LShr || Opc == Instruction::Shl) 1587 if (!canNarrowShiftAmt(C, X->getType()->getScalarSizeInBits())) 1588 return nullptr; 1589 1590 // and (sub C, (zext X)), (zext X) --> zext (and (sub C', X), X) 1591 // and (binop (zext X), C), (zext X) --> zext (and (binop X, C'), X) 1592 Value *NewC = ConstantExpr::getTrunc(C, X->getType()); 1593 Value *NewBO = Opc == Instruction::Sub ? Builder.CreateBinOp(Opc, NewC, X) 1594 : Builder.CreateBinOp(Opc, X, NewC); 1595 return new ZExtInst(Builder.CreateAnd(NewBO, X), Ty); 1596 } 1597 1598 /// Try folding relatively complex patterns for both And and Or operations 1599 /// with all And and Or swapped. 1600 static Instruction *foldComplexAndOrPatterns(BinaryOperator &I, 1601 InstCombiner::BuilderTy &Builder) { 1602 const Instruction::BinaryOps Opcode = I.getOpcode(); 1603 assert(Opcode == Instruction::And || Opcode == Instruction::Or); 1604 1605 // Flip the logic operation. 1606 const Instruction::BinaryOps FlippedOpcode = 1607 (Opcode == Instruction::And) ? Instruction::Or : Instruction::And; 1608 1609 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1610 Value *A, *B, *C, *X, *Y, *Dummy; 1611 1612 // Match following expressions: 1613 // (~(A | B) & C) 1614 // (~(A & B) | C) 1615 // Captures X = ~(A | B) or ~(A & B) 1616 const auto matchNotOrAnd = 1617 [Opcode, FlippedOpcode](Value *Op, auto m_A, auto m_B, auto m_C, 1618 Value *&X, bool CountUses = false) -> bool { 1619 if (CountUses && !Op->hasOneUse()) 1620 return false; 1621 1622 if (match(Op, m_c_BinOp(FlippedOpcode, 1623 m_CombineAnd(m_Value(X), 1624 m_Not(m_c_BinOp(Opcode, m_A, m_B))), 1625 m_C))) 1626 return !CountUses || X->hasOneUse(); 1627 1628 return false; 1629 }; 1630 1631 // (~(A | B) & C) | ... --> ... 1632 // (~(A & B) | C) & ... --> ... 1633 // TODO: One use checks are conservative. We just need to check that a total 1634 // number of multiple used values does not exceed reduction 1635 // in operations. 1636 if (matchNotOrAnd(Op0, m_Value(A), m_Value(B), m_Value(C), X)) { 1637 // (~(A | B) & C) | (~(A | C) & B) --> (B ^ C) & ~A 1638 // (~(A & B) | C) & (~(A & C) | B) --> ~((B ^ C) & A) 1639 if (matchNotOrAnd(Op1, m_Specific(A), m_Specific(C), m_Specific(B), Dummy, 1640 true)) { 1641 Value *Xor = Builder.CreateXor(B, C); 1642 return (Opcode == Instruction::Or) 1643 ? BinaryOperator::CreateAnd(Xor, Builder.CreateNot(A)) 1644 : BinaryOperator::CreateNot(Builder.CreateAnd(Xor, A)); 1645 } 1646 1647 // (~(A | B) & C) | (~(B | C) & A) --> (A ^ C) & ~B 1648 // (~(A & B) | C) & (~(B & C) | A) --> ~((A ^ C) & B) 1649 if (matchNotOrAnd(Op1, m_Specific(B), m_Specific(C), m_Specific(A), Dummy, 1650 true)) { 1651 Value *Xor = Builder.CreateXor(A, C); 1652 return (Opcode == Instruction::Or) 1653 ? BinaryOperator::CreateAnd(Xor, Builder.CreateNot(B)) 1654 : BinaryOperator::CreateNot(Builder.CreateAnd(Xor, B)); 1655 } 1656 1657 // (~(A | B) & C) | ~(A | C) --> ~((B & C) | A) 1658 // (~(A & B) | C) & ~(A & C) --> ~((B | C) & A) 1659 if (match(Op1, m_OneUse(m_Not(m_OneUse( 1660 m_c_BinOp(Opcode, m_Specific(A), m_Specific(C))))))) 1661 return BinaryOperator::CreateNot(Builder.CreateBinOp( 1662 Opcode, Builder.CreateBinOp(FlippedOpcode, B, C), A)); 1663 1664 // (~(A | B) & C) | ~(B | C) --> ~((A & C) | B) 1665 // (~(A & B) | C) & ~(B & C) --> ~((A | C) & B) 1666 if (match(Op1, m_OneUse(m_Not(m_OneUse( 1667 m_c_BinOp(Opcode, m_Specific(B), m_Specific(C))))))) 1668 return BinaryOperator::CreateNot(Builder.CreateBinOp( 1669 Opcode, Builder.CreateBinOp(FlippedOpcode, A, C), B)); 1670 1671 // (~(A | B) & C) | ~(C | (A ^ B)) --> ~((A | B) & (C | (A ^ B))) 1672 // Note, the pattern with swapped and/or is not handled because the 1673 // result is more undefined than a source: 1674 // (~(A & B) | C) & ~(C & (A ^ B)) --> (A ^ B ^ C) | ~(A | C) is invalid. 1675 if (Opcode == Instruction::Or && Op0->hasOneUse() && 1676 match(Op1, m_OneUse(m_Not(m_CombineAnd( 1677 m_Value(Y), 1678 m_c_BinOp(Opcode, m_Specific(C), 1679 m_c_Xor(m_Specific(A), m_Specific(B)))))))) { 1680 // X = ~(A | B) 1681 // Y = (C | (A ^ B) 1682 Value *Or = cast<BinaryOperator>(X)->getOperand(0); 1683 return BinaryOperator::CreateNot(Builder.CreateAnd(Or, Y)); 1684 } 1685 } 1686 1687 // (~A & B & C) | ... --> ... 1688 // (~A | B | C) | ... --> ... 1689 // TODO: One use checks are conservative. We just need to check that a total 1690 // number of multiple used values does not exceed reduction 1691 // in operations. 1692 if (match(Op0, 1693 m_OneUse(m_c_BinOp(FlippedOpcode, 1694 m_BinOp(FlippedOpcode, m_Value(B), m_Value(C)), 1695 m_CombineAnd(m_Value(X), m_Not(m_Value(A)))))) || 1696 match(Op0, m_OneUse(m_c_BinOp( 1697 FlippedOpcode, 1698 m_c_BinOp(FlippedOpcode, m_Value(C), 1699 m_CombineAnd(m_Value(X), m_Not(m_Value(A)))), 1700 m_Value(B))))) { 1701 // X = ~A 1702 // (~A & B & C) | ~(A | B | C) --> ~(A | (B ^ C)) 1703 // (~A | B | C) & ~(A & B & C) --> (~A | (B ^ C)) 1704 if (match(Op1, m_OneUse(m_Not(m_c_BinOp( 1705 Opcode, m_c_BinOp(Opcode, m_Specific(A), m_Specific(B)), 1706 m_Specific(C))))) || 1707 match(Op1, m_OneUse(m_Not(m_c_BinOp( 1708 Opcode, m_c_BinOp(Opcode, m_Specific(B), m_Specific(C)), 1709 m_Specific(A))))) || 1710 match(Op1, m_OneUse(m_Not(m_c_BinOp( 1711 Opcode, m_c_BinOp(Opcode, m_Specific(A), m_Specific(C)), 1712 m_Specific(B)))))) { 1713 Value *Xor = Builder.CreateXor(B, C); 1714 return (Opcode == Instruction::Or) 1715 ? BinaryOperator::CreateNot(Builder.CreateOr(Xor, A)) 1716 : BinaryOperator::CreateOr(Xor, X); 1717 } 1718 1719 // (~A & B & C) | ~(A | B) --> (C | ~B) & ~A 1720 // (~A | B | C) & ~(A & B) --> (C & ~B) | ~A 1721 if (match(Op1, m_OneUse(m_Not(m_OneUse( 1722 m_c_BinOp(Opcode, m_Specific(A), m_Specific(B))))))) 1723 return BinaryOperator::Create( 1724 FlippedOpcode, Builder.CreateBinOp(Opcode, C, Builder.CreateNot(B)), 1725 X); 1726 1727 // (~A & B & C) | ~(A | C) --> (B | ~C) & ~A 1728 // (~A | B | C) & ~(A & C) --> (B & ~C) | ~A 1729 if (match(Op1, m_OneUse(m_Not(m_OneUse( 1730 m_c_BinOp(Opcode, m_Specific(A), m_Specific(C))))))) 1731 return BinaryOperator::Create( 1732 FlippedOpcode, Builder.CreateBinOp(Opcode, B, Builder.CreateNot(C)), 1733 X); 1734 } 1735 1736 return nullptr; 1737 } 1738 1739 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches 1740 // here. We should standardize that construct where it is needed or choose some 1741 // other way to ensure that commutated variants of patterns are not missed. 1742 Instruction *InstCombinerImpl::visitAnd(BinaryOperator &I) { 1743 Type *Ty = I.getType(); 1744 1745 if (Value *V = SimplifyAndInst(I.getOperand(0), I.getOperand(1), 1746 SQ.getWithInstruction(&I))) 1747 return replaceInstUsesWith(I, V); 1748 1749 if (SimplifyAssociativeOrCommutative(I)) 1750 return &I; 1751 1752 if (Instruction *X = foldVectorBinop(I)) 1753 return X; 1754 1755 if (Instruction *Phi = foldBinopWithPhiOperands(I)) 1756 return Phi; 1757 1758 // See if we can simplify any instructions used by the instruction whose sole 1759 // purpose is to compute bits we don't care about. 1760 if (SimplifyDemandedInstructionBits(I)) 1761 return &I; 1762 1763 // Do this before using distributive laws to catch simple and/or/not patterns. 1764 if (Instruction *Xor = foldAndToXor(I, Builder)) 1765 return Xor; 1766 1767 if (Instruction *X = foldComplexAndOrPatterns(I, Builder)) 1768 return X; 1769 1770 // (A|B)&(A|C) -> A|(B&C) etc 1771 if (Value *V = SimplifyUsingDistributiveLaws(I)) 1772 return replaceInstUsesWith(I, V); 1773 1774 if (Value *V = SimplifyBSwap(I, Builder)) 1775 return replaceInstUsesWith(I, V); 1776 1777 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 1778 1779 Value *X, *Y; 1780 if (match(Op0, m_OneUse(m_LogicalShift(m_One(), m_Value(X)))) && 1781 match(Op1, m_One())) { 1782 // (1 << X) & 1 --> zext(X == 0) 1783 // (1 >> X) & 1 --> zext(X == 0) 1784 Value *IsZero = Builder.CreateICmpEQ(X, ConstantInt::get(Ty, 0)); 1785 return new ZExtInst(IsZero, Ty); 1786 } 1787 1788 const APInt *C; 1789 if (match(Op1, m_APInt(C))) { 1790 const APInt *XorC; 1791 if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_APInt(XorC))))) { 1792 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2) 1793 Constant *NewC = ConstantInt::get(Ty, *C & *XorC); 1794 Value *And = Builder.CreateAnd(X, Op1); 1795 And->takeName(Op0); 1796 return BinaryOperator::CreateXor(And, NewC); 1797 } 1798 1799 const APInt *OrC; 1800 if (match(Op0, m_OneUse(m_Or(m_Value(X), m_APInt(OrC))))) { 1801 // (X | C1) & C2 --> (X & C2^(C1&C2)) | (C1&C2) 1802 // NOTE: This reduces the number of bits set in the & mask, which 1803 // can expose opportunities for store narrowing for scalars. 1804 // NOTE: SimplifyDemandedBits should have already removed bits from C1 1805 // that aren't set in C2. Meaning we can replace (C1&C2) with C1 in 1806 // above, but this feels safer. 1807 APInt Together = *C & *OrC; 1808 Value *And = Builder.CreateAnd(X, ConstantInt::get(Ty, Together ^ *C)); 1809 And->takeName(Op0); 1810 return BinaryOperator::CreateOr(And, ConstantInt::get(Ty, Together)); 1811 } 1812 1813 // If the mask is only needed on one incoming arm, push the 'and' op up. 1814 if (match(Op0, m_OneUse(m_Xor(m_Value(X), m_Value(Y)))) || 1815 match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) { 1816 APInt NotAndMask(~(*C)); 1817 BinaryOperator::BinaryOps BinOp = cast<BinaryOperator>(Op0)->getOpcode(); 1818 if (MaskedValueIsZero(X, NotAndMask, 0, &I)) { 1819 // Not masking anything out for the LHS, move mask to RHS. 1820 // and ({x}or X, Y), C --> {x}or X, (and Y, C) 1821 Value *NewRHS = Builder.CreateAnd(Y, Op1, Y->getName() + ".masked"); 1822 return BinaryOperator::Create(BinOp, X, NewRHS); 1823 } 1824 if (!isa<Constant>(Y) && MaskedValueIsZero(Y, NotAndMask, 0, &I)) { 1825 // Not masking anything out for the RHS, move mask to LHS. 1826 // and ({x}or X, Y), C --> {x}or (and X, C), Y 1827 Value *NewLHS = Builder.CreateAnd(X, Op1, X->getName() + ".masked"); 1828 return BinaryOperator::Create(BinOp, NewLHS, Y); 1829 } 1830 } 1831 1832 unsigned Width = Ty->getScalarSizeInBits(); 1833 const APInt *ShiftC; 1834 if (match(Op0, m_OneUse(m_SExt(m_AShr(m_Value(X), m_APInt(ShiftC)))))) { 1835 if (*C == APInt::getLowBitsSet(Width, Width - ShiftC->getZExtValue())) { 1836 // We are clearing high bits that were potentially set by sext+ashr: 1837 // and (sext (ashr X, ShiftC)), C --> lshr (sext X), ShiftC 1838 Value *Sext = Builder.CreateSExt(X, Ty); 1839 Constant *ShAmtC = ConstantInt::get(Ty, ShiftC->zext(Width)); 1840 return BinaryOperator::CreateLShr(Sext, ShAmtC); 1841 } 1842 } 1843 1844 // If this 'and' clears the sign-bits added by ashr, replace with lshr: 1845 // and (ashr X, ShiftC), C --> lshr X, ShiftC 1846 if (match(Op0, m_AShr(m_Value(X), m_APInt(ShiftC))) && ShiftC->ult(Width) && 1847 C->isMask(Width - ShiftC->getZExtValue())) 1848 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, *ShiftC)); 1849 1850 const APInt *AddC; 1851 if (match(Op0, m_Add(m_Value(X), m_APInt(AddC)))) { 1852 // If we add zeros to every bit below a mask, the add has no effect: 1853 // (X + AddC) & LowMaskC --> X & LowMaskC 1854 unsigned Ctlz = C->countLeadingZeros(); 1855 APInt LowMask(APInt::getLowBitsSet(Width, Width - Ctlz)); 1856 if ((*AddC & LowMask).isZero()) 1857 return BinaryOperator::CreateAnd(X, Op1); 1858 1859 // If we are masking the result of the add down to exactly one bit and 1860 // the constant we are adding has no bits set below that bit, then the 1861 // add is flipping a single bit. Example: 1862 // (X + 4) & 4 --> (X & 4) ^ 4 1863 if (Op0->hasOneUse() && C->isPowerOf2() && (*AddC & (*C - 1)) == 0) { 1864 assert((*C & *AddC) != 0 && "Expected common bit"); 1865 Value *NewAnd = Builder.CreateAnd(X, Op1); 1866 return BinaryOperator::CreateXor(NewAnd, Op1); 1867 } 1868 } 1869 1870 // ((C1 OP zext(X)) & C2) -> zext((C1 OP X) & C2) if C2 fits in the 1871 // bitwidth of X and OP behaves well when given trunc(C1) and X. 1872 auto isSuitableBinOpcode = [](BinaryOperator *B) { 1873 switch (B->getOpcode()) { 1874 case Instruction::Xor: 1875 case Instruction::Or: 1876 case Instruction::Mul: 1877 case Instruction::Add: 1878 case Instruction::Sub: 1879 return true; 1880 default: 1881 return false; 1882 } 1883 }; 1884 BinaryOperator *BO; 1885 if (match(Op0, m_OneUse(m_BinOp(BO))) && isSuitableBinOpcode(BO)) { 1886 Value *X; 1887 const APInt *C1; 1888 // TODO: The one-use restrictions could be relaxed a little if the AND 1889 // is going to be removed. 1890 if (match(BO, m_c_BinOp(m_OneUse(m_ZExt(m_Value(X))), m_APInt(C1))) && 1891 C->isIntN(X->getType()->getScalarSizeInBits())) { 1892 unsigned XWidth = X->getType()->getScalarSizeInBits(); 1893 Constant *TruncC1 = ConstantInt::get(X->getType(), C1->trunc(XWidth)); 1894 Value *BinOp = isa<ZExtInst>(BO->getOperand(0)) 1895 ? Builder.CreateBinOp(BO->getOpcode(), X, TruncC1) 1896 : Builder.CreateBinOp(BO->getOpcode(), TruncC1, X); 1897 Constant *TruncC = ConstantInt::get(X->getType(), C->trunc(XWidth)); 1898 Value *And = Builder.CreateAnd(BinOp, TruncC); 1899 return new ZExtInst(And, Ty); 1900 } 1901 } 1902 } 1903 1904 if (match(&I, m_And(m_OneUse(m_Shl(m_ZExt(m_Value(X)), m_Value(Y))), 1905 m_SignMask())) && 1906 match(Y, m_SpecificInt_ICMP( 1907 ICmpInst::Predicate::ICMP_EQ, 1908 APInt(Ty->getScalarSizeInBits(), 1909 Ty->getScalarSizeInBits() - 1910 X->getType()->getScalarSizeInBits())))) { 1911 auto *SExt = Builder.CreateSExt(X, Ty, X->getName() + ".signext"); 1912 auto *SanitizedSignMask = cast<Constant>(Op1); 1913 // We must be careful with the undef elements of the sign bit mask, however: 1914 // the mask elt can be undef iff the shift amount for that lane was undef, 1915 // otherwise we need to sanitize undef masks to zero. 1916 SanitizedSignMask = Constant::replaceUndefsWith( 1917 SanitizedSignMask, ConstantInt::getNullValue(Ty->getScalarType())); 1918 SanitizedSignMask = 1919 Constant::mergeUndefsWith(SanitizedSignMask, cast<Constant>(Y)); 1920 return BinaryOperator::CreateAnd(SExt, SanitizedSignMask); 1921 } 1922 1923 if (Instruction *Z = narrowMaskedBinOp(I)) 1924 return Z; 1925 1926 if (I.getType()->isIntOrIntVectorTy(1)) { 1927 if (auto *SI0 = dyn_cast<SelectInst>(Op0)) { 1928 if (auto *I = 1929 foldAndOrOfSelectUsingImpliedCond(Op1, *SI0, /* IsAnd */ true)) 1930 return I; 1931 } 1932 if (auto *SI1 = dyn_cast<SelectInst>(Op1)) { 1933 if (auto *I = 1934 foldAndOrOfSelectUsingImpliedCond(Op0, *SI1, /* IsAnd */ true)) 1935 return I; 1936 } 1937 } 1938 1939 if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I)) 1940 return FoldedLogic; 1941 1942 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder)) 1943 return DeMorgan; 1944 1945 { 1946 Value *A, *B, *C; 1947 // A & (A ^ B) --> A & ~B 1948 if (match(Op1, m_OneUse(m_c_Xor(m_Specific(Op0), m_Value(B))))) 1949 return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(B)); 1950 // (A ^ B) & A --> A & ~B 1951 if (match(Op0, m_OneUse(m_c_Xor(m_Specific(Op1), m_Value(B))))) 1952 return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(B)); 1953 1954 // A & ~(A ^ B) --> A & B 1955 if (match(Op1, m_Not(m_c_Xor(m_Specific(Op0), m_Value(B))))) 1956 return BinaryOperator::CreateAnd(Op0, B); 1957 // ~(A ^ B) & A --> A & B 1958 if (match(Op0, m_Not(m_c_Xor(m_Specific(Op1), m_Value(B))))) 1959 return BinaryOperator::CreateAnd(Op1, B); 1960 1961 // (A ^ B) & ((B ^ C) ^ A) -> (A ^ B) & ~C 1962 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) 1963 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A)))) 1964 if (Op1->hasOneUse() || isFreeToInvert(C, C->hasOneUse())) 1965 return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(C)); 1966 1967 // ((A ^ C) ^ B) & (B ^ A) -> (B ^ A) & ~C 1968 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B)))) 1969 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A)))) 1970 if (Op0->hasOneUse() || isFreeToInvert(C, C->hasOneUse())) 1971 return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(C)); 1972 1973 // (A | B) & (~A ^ B) -> A & B 1974 // (A | B) & (B ^ ~A) -> A & B 1975 // (B | A) & (~A ^ B) -> A & B 1976 // (B | A) & (B ^ ~A) -> A & B 1977 if (match(Op1, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) && 1978 match(Op0, m_c_Or(m_Specific(A), m_Specific(B)))) 1979 return BinaryOperator::CreateAnd(A, B); 1980 1981 // (~A ^ B) & (A | B) -> A & B 1982 // (~A ^ B) & (B | A) -> A & B 1983 // (B ^ ~A) & (A | B) -> A & B 1984 // (B ^ ~A) & (B | A) -> A & B 1985 if (match(Op0, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) && 1986 match(Op1, m_c_Or(m_Specific(A), m_Specific(B)))) 1987 return BinaryOperator::CreateAnd(A, B); 1988 1989 // (~A | B) & (A ^ B) -> ~A & B 1990 // (~A | B) & (B ^ A) -> ~A & B 1991 // (B | ~A) & (A ^ B) -> ~A & B 1992 // (B | ~A) & (B ^ A) -> ~A & B 1993 if (match(Op0, m_c_Or(m_Not(m_Value(A)), m_Value(B))) && 1994 match(Op1, m_c_Xor(m_Specific(A), m_Specific(B)))) 1995 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B); 1996 1997 // (A ^ B) & (~A | B) -> ~A & B 1998 // (B ^ A) & (~A | B) -> ~A & B 1999 // (A ^ B) & (B | ~A) -> ~A & B 2000 // (B ^ A) & (B | ~A) -> ~A & B 2001 if (match(Op1, m_c_Or(m_Not(m_Value(A)), m_Value(B))) && 2002 match(Op0, m_c_Xor(m_Specific(A), m_Specific(B)))) 2003 return BinaryOperator::CreateAnd(Builder.CreateNot(A), B); 2004 } 2005 2006 { 2007 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0); 2008 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1); 2009 if (LHS && RHS) 2010 if (Value *Res = foldAndOrOfICmps(LHS, RHS, I, /* IsAnd */ true)) 2011 return replaceInstUsesWith(I, Res); 2012 2013 // TODO: Make this recursive; it's a little tricky because an arbitrary 2014 // number of 'and' instructions might have to be created. 2015 if (LHS && match(Op1, m_OneUse(m_And(m_Value(X), m_Value(Y))))) { 2016 if (auto *Cmp = dyn_cast<ICmpInst>(X)) 2017 if (Value *Res = foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ true)) 2018 return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y)); 2019 if (auto *Cmp = dyn_cast<ICmpInst>(Y)) 2020 if (Value *Res = foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ true)) 2021 return replaceInstUsesWith(I, Builder.CreateAnd(Res, X)); 2022 } 2023 if (RHS && match(Op0, m_OneUse(m_And(m_Value(X), m_Value(Y))))) { 2024 if (auto *Cmp = dyn_cast<ICmpInst>(X)) 2025 if (Value *Res = foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ true)) 2026 return replaceInstUsesWith(I, Builder.CreateAnd(Res, Y)); 2027 if (auto *Cmp = dyn_cast<ICmpInst>(Y)) 2028 if (Value *Res = foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ true)) 2029 return replaceInstUsesWith(I, Builder.CreateAnd(Res, X)); 2030 } 2031 } 2032 2033 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) 2034 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) 2035 if (Value *Res = foldLogicOfFCmps(LHS, RHS, /*IsAnd*/ true)) 2036 return replaceInstUsesWith(I, Res); 2037 2038 if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder)) 2039 return FoldedFCmps; 2040 2041 if (Instruction *CastedAnd = foldCastedBitwiseLogic(I)) 2042 return CastedAnd; 2043 2044 if (Instruction *Sel = foldBinopOfSextBoolToSelect(I)) 2045 return Sel; 2046 2047 // and(sext(A), B) / and(B, sext(A)) --> A ? B : 0, where A is i1 or <N x i1>. 2048 // TODO: Move this into foldBinopOfSextBoolToSelect as a more generalized fold 2049 // with binop identity constant. But creating a select with non-constant 2050 // arm may not be reversible due to poison semantics. Is that a good 2051 // canonicalization? 2052 Value *A; 2053 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) && 2054 A->getType()->isIntOrIntVectorTy(1)) 2055 return SelectInst::Create(A, Op1, Constant::getNullValue(Ty)); 2056 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) && 2057 A->getType()->isIntOrIntVectorTy(1)) 2058 return SelectInst::Create(A, Op0, Constant::getNullValue(Ty)); 2059 2060 // (iN X s>> (N-1)) & Y --> (X s< 0) ? Y : 0 2061 unsigned FullShift = Ty->getScalarSizeInBits() - 1; 2062 if (match(&I, m_c_And(m_OneUse(m_AShr(m_Value(X), m_SpecificInt(FullShift))), 2063 m_Value(Y)))) { 2064 Constant *Zero = ConstantInt::getNullValue(Ty); 2065 Value *Cmp = Builder.CreateICmpSLT(X, Zero, "isneg"); 2066 return SelectInst::Create(Cmp, Y, Zero); 2067 } 2068 // If there's a 'not' of the shifted value, swap the select operands: 2069 // ~(iN X s>> (N-1)) & Y --> (X s< 0) ? 0 : Y 2070 if (match(&I, m_c_And(m_OneUse(m_Not( 2071 m_AShr(m_Value(X), m_SpecificInt(FullShift)))), 2072 m_Value(Y)))) { 2073 Constant *Zero = ConstantInt::getNullValue(Ty); 2074 Value *Cmp = Builder.CreateICmpSLT(X, Zero, "isneg"); 2075 return SelectInst::Create(Cmp, Zero, Y); 2076 } 2077 2078 // (~x) & y --> ~(x | (~y)) iff that gets rid of inversions 2079 if (sinkNotIntoOtherHandOfAndOrOr(I)) 2080 return &I; 2081 2082 // An and recurrence w/loop invariant step is equivelent to (and start, step) 2083 PHINode *PN = nullptr; 2084 Value *Start = nullptr, *Step = nullptr; 2085 if (matchSimpleRecurrence(&I, PN, Start, Step) && DT.dominates(Step, PN)) 2086 return replaceInstUsesWith(I, Builder.CreateAnd(Start, Step)); 2087 2088 return nullptr; 2089 } 2090 2091 Instruction *InstCombinerImpl::matchBSwapOrBitReverse(Instruction &I, 2092 bool MatchBSwaps, 2093 bool MatchBitReversals) { 2094 SmallVector<Instruction *, 4> Insts; 2095 if (!recognizeBSwapOrBitReverseIdiom(&I, MatchBSwaps, MatchBitReversals, 2096 Insts)) 2097 return nullptr; 2098 Instruction *LastInst = Insts.pop_back_val(); 2099 LastInst->removeFromParent(); 2100 2101 for (auto *Inst : Insts) 2102 Worklist.push(Inst); 2103 return LastInst; 2104 } 2105 2106 /// Match UB-safe variants of the funnel shift intrinsic. 2107 static Instruction *matchFunnelShift(Instruction &Or, InstCombinerImpl &IC) { 2108 // TODO: Can we reduce the code duplication between this and the related 2109 // rotate matching code under visitSelect and visitTrunc? 2110 unsigned Width = Or.getType()->getScalarSizeInBits(); 2111 2112 // First, find an or'd pair of opposite shifts: 2113 // or (lshr ShVal0, ShAmt0), (shl ShVal1, ShAmt1) 2114 BinaryOperator *Or0, *Or1; 2115 if (!match(Or.getOperand(0), m_BinOp(Or0)) || 2116 !match(Or.getOperand(1), m_BinOp(Or1))) 2117 return nullptr; 2118 2119 Value *ShVal0, *ShVal1, *ShAmt0, *ShAmt1; 2120 if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(ShVal0), m_Value(ShAmt0)))) || 2121 !match(Or1, m_OneUse(m_LogicalShift(m_Value(ShVal1), m_Value(ShAmt1)))) || 2122 Or0->getOpcode() == Or1->getOpcode()) 2123 return nullptr; 2124 2125 // Canonicalize to or(shl(ShVal0, ShAmt0), lshr(ShVal1, ShAmt1)). 2126 if (Or0->getOpcode() == BinaryOperator::LShr) { 2127 std::swap(Or0, Or1); 2128 std::swap(ShVal0, ShVal1); 2129 std::swap(ShAmt0, ShAmt1); 2130 } 2131 assert(Or0->getOpcode() == BinaryOperator::Shl && 2132 Or1->getOpcode() == BinaryOperator::LShr && 2133 "Illegal or(shift,shift) pair"); 2134 2135 // Match the shift amount operands for a funnel shift pattern. This always 2136 // matches a subtraction on the R operand. 2137 auto matchShiftAmount = [&](Value *L, Value *R, unsigned Width) -> Value * { 2138 // Check for constant shift amounts that sum to the bitwidth. 2139 const APInt *LI, *RI; 2140 if (match(L, m_APIntAllowUndef(LI)) && match(R, m_APIntAllowUndef(RI))) 2141 if (LI->ult(Width) && RI->ult(Width) && (*LI + *RI) == Width) 2142 return ConstantInt::get(L->getType(), *LI); 2143 2144 Constant *LC, *RC; 2145 if (match(L, m_Constant(LC)) && match(R, m_Constant(RC)) && 2146 match(L, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) && 2147 match(R, m_SpecificInt_ICMP(ICmpInst::ICMP_ULT, APInt(Width, Width))) && 2148 match(ConstantExpr::getAdd(LC, RC), m_SpecificIntAllowUndef(Width))) 2149 return ConstantExpr::mergeUndefsWith(LC, RC); 2150 2151 // (shl ShVal, X) | (lshr ShVal, (Width - x)) iff X < Width. 2152 // We limit this to X < Width in case the backend re-expands the intrinsic, 2153 // and has to reintroduce a shift modulo operation (InstCombine might remove 2154 // it after this fold). This still doesn't guarantee that the final codegen 2155 // will match this original pattern. 2156 if (match(R, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(L))))) { 2157 KnownBits KnownL = IC.computeKnownBits(L, /*Depth*/ 0, &Or); 2158 return KnownL.getMaxValue().ult(Width) ? L : nullptr; 2159 } 2160 2161 // For non-constant cases, the following patterns currently only work for 2162 // rotation patterns. 2163 // TODO: Add general funnel-shift compatible patterns. 2164 if (ShVal0 != ShVal1) 2165 return nullptr; 2166 2167 // For non-constant cases we don't support non-pow2 shift masks. 2168 // TODO: Is it worth matching urem as well? 2169 if (!isPowerOf2_32(Width)) 2170 return nullptr; 2171 2172 // The shift amount may be masked with negation: 2173 // (shl ShVal, (X & (Width - 1))) | (lshr ShVal, ((-X) & (Width - 1))) 2174 Value *X; 2175 unsigned Mask = Width - 1; 2176 if (match(L, m_And(m_Value(X), m_SpecificInt(Mask))) && 2177 match(R, m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask)))) 2178 return X; 2179 2180 // Similar to above, but the shift amount may be extended after masking, 2181 // so return the extended value as the parameter for the intrinsic. 2182 if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) && 2183 match(R, m_And(m_Neg(m_ZExt(m_And(m_Specific(X), m_SpecificInt(Mask)))), 2184 m_SpecificInt(Mask)))) 2185 return L; 2186 2187 if (match(L, m_ZExt(m_And(m_Value(X), m_SpecificInt(Mask)))) && 2188 match(R, m_ZExt(m_And(m_Neg(m_Specific(X)), m_SpecificInt(Mask))))) 2189 return L; 2190 2191 return nullptr; 2192 }; 2193 2194 Value *ShAmt = matchShiftAmount(ShAmt0, ShAmt1, Width); 2195 bool IsFshl = true; // Sub on LSHR. 2196 if (!ShAmt) { 2197 ShAmt = matchShiftAmount(ShAmt1, ShAmt0, Width); 2198 IsFshl = false; // Sub on SHL. 2199 } 2200 if (!ShAmt) 2201 return nullptr; 2202 2203 Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr; 2204 Function *F = Intrinsic::getDeclaration(Or.getModule(), IID, Or.getType()); 2205 return CallInst::Create(F, {ShVal0, ShVal1, ShAmt}); 2206 } 2207 2208 /// Attempt to combine or(zext(x),shl(zext(y),bw/2) concat packing patterns. 2209 static Instruction *matchOrConcat(Instruction &Or, 2210 InstCombiner::BuilderTy &Builder) { 2211 assert(Or.getOpcode() == Instruction::Or && "bswap requires an 'or'"); 2212 Value *Op0 = Or.getOperand(0), *Op1 = Or.getOperand(1); 2213 Type *Ty = Or.getType(); 2214 2215 unsigned Width = Ty->getScalarSizeInBits(); 2216 if ((Width & 1) != 0) 2217 return nullptr; 2218 unsigned HalfWidth = Width / 2; 2219 2220 // Canonicalize zext (lower half) to LHS. 2221 if (!isa<ZExtInst>(Op0)) 2222 std::swap(Op0, Op1); 2223 2224 // Find lower/upper half. 2225 Value *LowerSrc, *ShlVal, *UpperSrc; 2226 const APInt *C; 2227 if (!match(Op0, m_OneUse(m_ZExt(m_Value(LowerSrc)))) || 2228 !match(Op1, m_OneUse(m_Shl(m_Value(ShlVal), m_APInt(C)))) || 2229 !match(ShlVal, m_OneUse(m_ZExt(m_Value(UpperSrc))))) 2230 return nullptr; 2231 if (*C != HalfWidth || LowerSrc->getType() != UpperSrc->getType() || 2232 LowerSrc->getType()->getScalarSizeInBits() != HalfWidth) 2233 return nullptr; 2234 2235 auto ConcatIntrinsicCalls = [&](Intrinsic::ID id, Value *Lo, Value *Hi) { 2236 Value *NewLower = Builder.CreateZExt(Lo, Ty); 2237 Value *NewUpper = Builder.CreateZExt(Hi, Ty); 2238 NewUpper = Builder.CreateShl(NewUpper, HalfWidth); 2239 Value *BinOp = Builder.CreateOr(NewLower, NewUpper); 2240 Function *F = Intrinsic::getDeclaration(Or.getModule(), id, Ty); 2241 return Builder.CreateCall(F, BinOp); 2242 }; 2243 2244 // BSWAP: Push the concat down, swapping the lower/upper sources. 2245 // concat(bswap(x),bswap(y)) -> bswap(concat(x,y)) 2246 Value *LowerBSwap, *UpperBSwap; 2247 if (match(LowerSrc, m_BSwap(m_Value(LowerBSwap))) && 2248 match(UpperSrc, m_BSwap(m_Value(UpperBSwap)))) 2249 return ConcatIntrinsicCalls(Intrinsic::bswap, UpperBSwap, LowerBSwap); 2250 2251 // BITREVERSE: Push the concat down, swapping the lower/upper sources. 2252 // concat(bitreverse(x),bitreverse(y)) -> bitreverse(concat(x,y)) 2253 Value *LowerBRev, *UpperBRev; 2254 if (match(LowerSrc, m_BitReverse(m_Value(LowerBRev))) && 2255 match(UpperSrc, m_BitReverse(m_Value(UpperBRev)))) 2256 return ConcatIntrinsicCalls(Intrinsic::bitreverse, UpperBRev, LowerBRev); 2257 2258 return nullptr; 2259 } 2260 2261 /// If all elements of two constant vectors are 0/-1 and inverses, return true. 2262 static bool areInverseVectorBitmasks(Constant *C1, Constant *C2) { 2263 unsigned NumElts = cast<FixedVectorType>(C1->getType())->getNumElements(); 2264 for (unsigned i = 0; i != NumElts; ++i) { 2265 Constant *EltC1 = C1->getAggregateElement(i); 2266 Constant *EltC2 = C2->getAggregateElement(i); 2267 if (!EltC1 || !EltC2) 2268 return false; 2269 2270 // One element must be all ones, and the other must be all zeros. 2271 if (!((match(EltC1, m_Zero()) && match(EltC2, m_AllOnes())) || 2272 (match(EltC2, m_Zero()) && match(EltC1, m_AllOnes())))) 2273 return false; 2274 } 2275 return true; 2276 } 2277 2278 /// We have an expression of the form (A & C) | (B & D). If A is a scalar or 2279 /// vector composed of all-zeros or all-ones values and is the bitwise 'not' of 2280 /// B, it can be used as the condition operand of a select instruction. 2281 Value *InstCombinerImpl::getSelectCondition(Value *A, Value *B) { 2282 // We may have peeked through bitcasts in the caller. 2283 // Exit immediately if we don't have (vector) integer types. 2284 Type *Ty = A->getType(); 2285 if (!Ty->isIntOrIntVectorTy() || !B->getType()->isIntOrIntVectorTy()) 2286 return nullptr; 2287 2288 // If A is the 'not' operand of B and has enough signbits, we have our answer. 2289 if (match(B, m_Not(m_Specific(A)))) { 2290 // If these are scalars or vectors of i1, A can be used directly. 2291 if (Ty->isIntOrIntVectorTy(1)) 2292 return A; 2293 2294 // If we look through a vector bitcast, the caller will bitcast the operands 2295 // to match the condition's number of bits (N x i1). 2296 // To make this poison-safe, disallow bitcast from wide element to narrow 2297 // element. That could allow poison in lanes where it was not present in the 2298 // original code. 2299 A = peekThroughBitcast(A); 2300 if (A->getType()->isIntOrIntVectorTy()) { 2301 unsigned NumSignBits = ComputeNumSignBits(A); 2302 if (NumSignBits == A->getType()->getScalarSizeInBits() && 2303 NumSignBits <= Ty->getScalarSizeInBits()) 2304 return Builder.CreateTrunc(A, CmpInst::makeCmpResultType(A->getType())); 2305 } 2306 return nullptr; 2307 } 2308 2309 // If both operands are constants, see if the constants are inverse bitmasks. 2310 Constant *AConst, *BConst; 2311 if (match(A, m_Constant(AConst)) && match(B, m_Constant(BConst))) 2312 if (AConst == ConstantExpr::getNot(BConst) && 2313 ComputeNumSignBits(A) == Ty->getScalarSizeInBits()) 2314 return Builder.CreateZExtOrTrunc(A, CmpInst::makeCmpResultType(Ty)); 2315 2316 // Look for more complex patterns. The 'not' op may be hidden behind various 2317 // casts. Look through sexts and bitcasts to find the booleans. 2318 Value *Cond; 2319 Value *NotB; 2320 if (match(A, m_SExt(m_Value(Cond))) && 2321 Cond->getType()->isIntOrIntVectorTy(1)) { 2322 // A = sext i1 Cond; B = sext (not (i1 Cond)) 2323 if (match(B, m_SExt(m_Not(m_Specific(Cond))))) 2324 return Cond; 2325 2326 // A = sext i1 Cond; B = not ({bitcast} (sext (i1 Cond))) 2327 // TODO: The one-use checks are unnecessary or misplaced. If the caller 2328 // checked for uses on logic ops/casts, that should be enough to 2329 // make this transform worthwhile. 2330 if (match(B, m_OneUse(m_Not(m_Value(NotB))))) { 2331 NotB = peekThroughBitcast(NotB, true); 2332 if (match(NotB, m_SExt(m_Specific(Cond)))) 2333 return Cond; 2334 } 2335 } 2336 2337 // All scalar (and most vector) possibilities should be handled now. 2338 // Try more matches that only apply to non-splat constant vectors. 2339 if (!Ty->isVectorTy()) 2340 return nullptr; 2341 2342 // If both operands are xor'd with constants using the same sexted boolean 2343 // operand, see if the constants are inverse bitmasks. 2344 // TODO: Use ConstantExpr::getNot()? 2345 if (match(A, (m_Xor(m_SExt(m_Value(Cond)), m_Constant(AConst)))) && 2346 match(B, (m_Xor(m_SExt(m_Specific(Cond)), m_Constant(BConst)))) && 2347 Cond->getType()->isIntOrIntVectorTy(1) && 2348 areInverseVectorBitmasks(AConst, BConst)) { 2349 AConst = ConstantExpr::getTrunc(AConst, CmpInst::makeCmpResultType(Ty)); 2350 return Builder.CreateXor(Cond, AConst); 2351 } 2352 return nullptr; 2353 } 2354 2355 /// We have an expression of the form (A & C) | (B & D). Try to simplify this 2356 /// to "A' ? C : D", where A' is a boolean or vector of booleans. 2357 Value *InstCombinerImpl::matchSelectFromAndOr(Value *A, Value *C, Value *B, 2358 Value *D) { 2359 // The potential condition of the select may be bitcasted. In that case, look 2360 // through its bitcast and the corresponding bitcast of the 'not' condition. 2361 Type *OrigType = A->getType(); 2362 A = peekThroughBitcast(A, true); 2363 B = peekThroughBitcast(B, true); 2364 if (Value *Cond = getSelectCondition(A, B)) { 2365 // ((bc Cond) & C) | ((bc ~Cond) & D) --> bc (select Cond, (bc C), (bc D)) 2366 // If this is a vector, we may need to cast to match the condition's length. 2367 // The bitcasts will either all exist or all not exist. The builder will 2368 // not create unnecessary casts if the types already match. 2369 Type *SelTy = A->getType(); 2370 if (auto *VecTy = dyn_cast<VectorType>(Cond->getType())) { 2371 unsigned Elts = VecTy->getElementCount().getKnownMinValue(); 2372 Type *EltTy = Builder.getIntNTy(SelTy->getPrimitiveSizeInBits() / Elts); 2373 SelTy = VectorType::get(EltTy, VecTy->getElementCount()); 2374 } 2375 Value *BitcastC = Builder.CreateBitCast(C, SelTy); 2376 Value *BitcastD = Builder.CreateBitCast(D, SelTy); 2377 Value *Select = Builder.CreateSelect(Cond, BitcastC, BitcastD); 2378 return Builder.CreateBitCast(Select, OrigType); 2379 } 2380 2381 return nullptr; 2382 } 2383 2384 // (icmp eq X, 0) | (icmp ult Other, X) -> (icmp ule Other, X-1) 2385 Value *foldAndOrOfICmpEqZeroAndICmp(ICmpInst *LHS, ICmpInst *RHS, bool IsAnd, 2386 IRBuilderBase &Builder) { 2387 if (IsAnd) 2388 return nullptr; 2389 2390 ICmpInst::Predicate LPred = LHS->getPredicate(); 2391 ICmpInst::Predicate RPred = RHS->getPredicate(); 2392 Value *LHS0 = LHS->getOperand(0); 2393 if (LPred != ICmpInst::ICMP_EQ || !match(LHS->getOperand(1), m_Zero()) || 2394 !LHS0->getType()->isIntOrIntVectorTy() || 2395 !(LHS->hasOneUse() || RHS->hasOneUse())) 2396 return nullptr; 2397 2398 Value *Other; 2399 if (RPred == ICmpInst::ICMP_ULT && RHS->getOperand(1) == LHS0) 2400 Other = RHS->getOperand(0); 2401 else if (RPred == ICmpInst::ICMP_UGT && RHS->getOperand(0) == LHS0) 2402 Other = RHS->getOperand(1); 2403 else 2404 return nullptr; 2405 2406 return Builder.CreateICmp( 2407 ICmpInst::ICMP_UGE, 2408 Builder.CreateAdd(LHS0, Constant::getAllOnesValue(LHS0->getType())), 2409 Other); 2410 } 2411 2412 /// Fold (icmp)&(icmp) or (icmp)|(icmp) if possible. 2413 Value *InstCombinerImpl::foldAndOrOfICmps(ICmpInst *LHS, ICmpInst *RHS, 2414 BinaryOperator &BO, bool IsAnd) { 2415 const SimplifyQuery Q = SQ.getWithInstruction(&BO); 2416 2417 // Fold (iszero(A & K1) | iszero(A & K2)) -> (A & (K1 | K2)) != (K1 | K2) 2418 // Fold (!iszero(A & K1) & !iszero(A & K2)) -> (A & (K1 | K2)) == (K1 | K2) 2419 // if K1 and K2 are a one-bit mask. 2420 if (Value *V = foldAndOrOfICmpsOfAndWithPow2(LHS, RHS, &BO, IsAnd)) 2421 return V; 2422 2423 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate(); 2424 Value *LHS0 = LHS->getOperand(0), *RHS0 = RHS->getOperand(0); 2425 Value *LHS1 = LHS->getOperand(1), *RHS1 = RHS->getOperand(1); 2426 const APInt *LHSC = nullptr, *RHSC = nullptr; 2427 match(LHS1, m_APInt(LHSC)); 2428 match(RHS1, m_APInt(RHSC)); 2429 2430 // Fold (icmp ult/ule (A + C1), C3) | (icmp ult/ule (A + C2), C3) 2431 // --> (icmp ult/ule ((A & ~(C1 ^ C2)) + max(C1, C2)), C3) 2432 // The original condition actually refers to the following two ranges: 2433 // [MAX_UINT-C1+1, MAX_UINT-C1+1+C3] and [MAX_UINT-C2+1, MAX_UINT-C2+1+C3] 2434 // We can fold these two ranges if: 2435 // 1) C1 and C2 is unsigned greater than C3. 2436 // 2) The two ranges are separated. 2437 // 3) C1 ^ C2 is one-bit mask. 2438 // 4) LowRange1 ^ LowRange2 and HighRange1 ^ HighRange2 are one-bit mask. 2439 // This implies all values in the two ranges differ by exactly one bit. 2440 if (!IsAnd && (PredL == ICmpInst::ICMP_ULT || PredL == ICmpInst::ICMP_ULE) && 2441 PredL == PredR && LHSC && RHSC && LHS->hasOneUse() && RHS->hasOneUse() && 2442 LHSC->getBitWidth() == RHSC->getBitWidth() && *LHSC == *RHSC) { 2443 2444 Value *AddOpnd; 2445 const APInt *LAddC, *RAddC; 2446 if (match(LHS0, m_Add(m_Value(AddOpnd), m_APInt(LAddC))) && 2447 match(RHS0, m_Add(m_Specific(AddOpnd), m_APInt(RAddC))) && 2448 LAddC->ugt(*LHSC) && RAddC->ugt(*LHSC)) { 2449 2450 APInt DiffC = *LAddC ^ *RAddC; 2451 if (DiffC.isPowerOf2()) { 2452 const APInt *MaxAddC = nullptr; 2453 if (LAddC->ult(*RAddC)) 2454 MaxAddC = RAddC; 2455 else 2456 MaxAddC = LAddC; 2457 2458 APInt RRangeLow = -*RAddC; 2459 APInt RRangeHigh = RRangeLow + *LHSC; 2460 APInt LRangeLow = -*LAddC; 2461 APInt LRangeHigh = LRangeLow + *LHSC; 2462 APInt LowRangeDiff = RRangeLow ^ LRangeLow; 2463 APInt HighRangeDiff = RRangeHigh ^ LRangeHigh; 2464 APInt RangeDiff = LRangeLow.sgt(RRangeLow) ? LRangeLow - RRangeLow 2465 : RRangeLow - LRangeLow; 2466 2467 if (LowRangeDiff.isPowerOf2() && LowRangeDiff == HighRangeDiff && 2468 RangeDiff.ugt(*LHSC)) { 2469 Type *Ty = AddOpnd->getType(); 2470 Value *MaskC = ConstantInt::get(Ty, ~DiffC); 2471 2472 Value *NewAnd = Builder.CreateAnd(AddOpnd, MaskC); 2473 Value *NewAdd = Builder.CreateAdd(NewAnd, 2474 ConstantInt::get(Ty, *MaxAddC)); 2475 return Builder.CreateICmp(LHS->getPredicate(), NewAdd, 2476 ConstantInt::get(Ty, *LHSC)); 2477 } 2478 } 2479 } 2480 } 2481 2482 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B) 2483 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B) 2484 if (predicatesFoldable(PredL, PredR)) { 2485 if (LHS0 == RHS1 && LHS1 == RHS0) { 2486 PredL = ICmpInst::getSwappedPredicate(PredL); 2487 std::swap(LHS0, LHS1); 2488 } 2489 if (LHS0 == RHS0 && LHS1 == RHS1) { 2490 unsigned Code = IsAnd ? getICmpCode(PredL) & getICmpCode(PredR) 2491 : getICmpCode(PredL) | getICmpCode(PredR); 2492 bool IsSigned = LHS->isSigned() || RHS->isSigned(); 2493 return getNewICmpValue(Code, IsSigned, LHS0, LHS1, Builder); 2494 } 2495 } 2496 2497 // handle (roughly): 2498 // (icmp ne (A & B), C) | (icmp ne (A & D), E) 2499 // (icmp eq (A & B), C) & (icmp eq (A & D), E) 2500 if (Value *V = foldLogOpOfMaskedICmps(LHS, RHS, IsAnd, Builder)) 2501 return V; 2502 2503 if (Value *V = foldAndOrOfICmpEqZeroAndICmp(LHS, RHS, IsAnd, Builder)) 2504 return V; 2505 if (Value *V = foldAndOrOfICmpEqZeroAndICmp(RHS, LHS, IsAnd, Builder)) 2506 return V; 2507 2508 if (Value *V = foldAndOrOfICmpsWithConstEq(LHS, RHS, BO, Builder, Q)) 2509 return V; 2510 if (Value *V = foldAndOrOfICmpsWithConstEq(RHS, LHS, BO, Builder, Q)) 2511 return V; 2512 2513 if (Value *V = foldIsPowerOf2OrZero(LHS, RHS, IsAnd, Builder)) 2514 return V; 2515 if (Value *V = foldIsPowerOf2OrZero(RHS, LHS, IsAnd, Builder)) 2516 return V; 2517 2518 // E.g. (icmp slt x, 0) | (icmp sgt x, n) --> icmp ugt x, n 2519 // E.g. (icmp sge x, 0) & (icmp slt x, n) --> icmp ult x, n 2520 if (Value *V = simplifyRangeCheck(LHS, RHS, /*Inverted=*/!IsAnd)) 2521 return V; 2522 2523 // E.g. (icmp sgt x, n) | (icmp slt x, 0) --> icmp ugt x, n 2524 // E.g. (icmp slt x, n) & (icmp sge x, 0) --> icmp ult x, n 2525 if (Value *V = simplifyRangeCheck(RHS, LHS, /*Inverted=*/!IsAnd)) 2526 return V; 2527 2528 if (Value *V = foldAndOrOfEqualityCmpsWithConstants(LHS, RHS, IsAnd, Builder)) 2529 return V; 2530 2531 if (IsAnd) 2532 if (Value *V = foldSignedTruncationCheck(LHS, RHS, BO, Builder)) 2533 return V; 2534 2535 if (Value *V = foldIsPowerOf2(LHS, RHS, IsAnd, Builder)) 2536 return V; 2537 2538 if (Value *X = foldUnsignedUnderflowCheck(LHS, RHS, IsAnd, Q, Builder)) 2539 return X; 2540 if (Value *X = foldUnsignedUnderflowCheck(RHS, LHS, IsAnd, Q, Builder)) 2541 return X; 2542 2543 if (Value *X = foldEqOfParts(LHS, RHS, IsAnd)) 2544 return X; 2545 2546 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0) 2547 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0) 2548 // TODO: Remove this when foldLogOpOfMaskedICmps can handle undefs. 2549 if (PredL == (IsAnd ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE) && 2550 PredL == PredR && match(LHS1, m_ZeroInt()) && match(RHS1, m_ZeroInt()) && 2551 LHS0->getType() == RHS0->getType()) { 2552 Value *NewOr = Builder.CreateOr(LHS0, RHS0); 2553 return Builder.CreateICmp(PredL, NewOr, 2554 Constant::getNullValue(NewOr->getType())); 2555 } 2556 2557 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2). 2558 if (!LHSC || !RHSC) 2559 return nullptr; 2560 2561 // (trunc x) == C1 & (and x, CA) == C2 -> (and x, CA|CMAX) == C1|C2 2562 // where CMAX is the all ones value for the truncated type, 2563 // iff the lower bits of C2 and CA are zero. 2564 if (IsAnd && PredL == ICmpInst::ICMP_EQ && PredL == PredR && 2565 LHS->hasOneUse() && RHS->hasOneUse()) { 2566 Value *V; 2567 const APInt *AndC, *SmallC = nullptr, *BigC = nullptr; 2568 2569 // (trunc x) == C1 & (and x, CA) == C2 2570 // (and x, CA) == C2 & (trunc x) == C1 2571 if (match(RHS0, m_Trunc(m_Value(V))) && 2572 match(LHS0, m_And(m_Specific(V), m_APInt(AndC)))) { 2573 SmallC = RHSC; 2574 BigC = LHSC; 2575 } else if (match(LHS0, m_Trunc(m_Value(V))) && 2576 match(RHS0, m_And(m_Specific(V), m_APInt(AndC)))) { 2577 SmallC = LHSC; 2578 BigC = RHSC; 2579 } 2580 2581 if (SmallC && BigC) { 2582 unsigned BigBitSize = BigC->getBitWidth(); 2583 unsigned SmallBitSize = SmallC->getBitWidth(); 2584 2585 // Check that the low bits are zero. 2586 APInt Low = APInt::getLowBitsSet(BigBitSize, SmallBitSize); 2587 if ((Low & *AndC).isZero() && (Low & *BigC).isZero()) { 2588 Value *NewAnd = Builder.CreateAnd(V, Low | *AndC); 2589 APInt N = SmallC->zext(BigBitSize) | *BigC; 2590 Value *NewVal = ConstantInt::get(NewAnd->getType(), N); 2591 return Builder.CreateICmp(PredL, NewAnd, NewVal); 2592 } 2593 } 2594 } 2595 2596 return foldAndOrOfICmpsUsingRanges(PredL, LHS0, *LHSC, PredR, RHS0, *RHSC, 2597 Builder, IsAnd); 2598 } 2599 2600 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches 2601 // here. We should standardize that construct where it is needed or choose some 2602 // other way to ensure that commutated variants of patterns are not missed. 2603 Instruction *InstCombinerImpl::visitOr(BinaryOperator &I) { 2604 if (Value *V = SimplifyOrInst(I.getOperand(0), I.getOperand(1), 2605 SQ.getWithInstruction(&I))) 2606 return replaceInstUsesWith(I, V); 2607 2608 if (SimplifyAssociativeOrCommutative(I)) 2609 return &I; 2610 2611 if (Instruction *X = foldVectorBinop(I)) 2612 return X; 2613 2614 if (Instruction *Phi = foldBinopWithPhiOperands(I)) 2615 return Phi; 2616 2617 // See if we can simplify any instructions used by the instruction whose sole 2618 // purpose is to compute bits we don't care about. 2619 if (SimplifyDemandedInstructionBits(I)) 2620 return &I; 2621 2622 // Do this before using distributive laws to catch simple and/or/not patterns. 2623 if (Instruction *Xor = foldOrToXor(I, Builder)) 2624 return Xor; 2625 2626 if (Instruction *X = foldComplexAndOrPatterns(I, Builder)) 2627 return X; 2628 2629 // (A&B)|(A&C) -> A&(B|C) etc 2630 if (Value *V = SimplifyUsingDistributiveLaws(I)) 2631 return replaceInstUsesWith(I, V); 2632 2633 if (Value *V = SimplifyBSwap(I, Builder)) 2634 return replaceInstUsesWith(I, V); 2635 2636 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 2637 Type *Ty = I.getType(); 2638 if (Ty->isIntOrIntVectorTy(1)) { 2639 if (auto *SI0 = dyn_cast<SelectInst>(Op0)) { 2640 if (auto *I = 2641 foldAndOrOfSelectUsingImpliedCond(Op1, *SI0, /* IsAnd */ false)) 2642 return I; 2643 } 2644 if (auto *SI1 = dyn_cast<SelectInst>(Op1)) { 2645 if (auto *I = 2646 foldAndOrOfSelectUsingImpliedCond(Op0, *SI1, /* IsAnd */ false)) 2647 return I; 2648 } 2649 } 2650 2651 if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I)) 2652 return FoldedLogic; 2653 2654 if (Instruction *BitOp = matchBSwapOrBitReverse(I, /*MatchBSwaps*/ true, 2655 /*MatchBitReversals*/ true)) 2656 return BitOp; 2657 2658 if (Instruction *Funnel = matchFunnelShift(I, *this)) 2659 return Funnel; 2660 2661 if (Instruction *Concat = matchOrConcat(I, Builder)) 2662 return replaceInstUsesWith(I, Concat); 2663 2664 Value *X, *Y; 2665 const APInt *CV; 2666 if (match(&I, m_c_Or(m_OneUse(m_Xor(m_Value(X), m_APInt(CV))), m_Value(Y))) && 2667 !CV->isAllOnes() && MaskedValueIsZero(Y, *CV, 0, &I)) { 2668 // (X ^ C) | Y -> (X | Y) ^ C iff Y & C == 0 2669 // The check for a 'not' op is for efficiency (if Y is known zero --> ~X). 2670 Value *Or = Builder.CreateOr(X, Y); 2671 return BinaryOperator::CreateXor(Or, ConstantInt::get(Ty, *CV)); 2672 } 2673 2674 // If the operands have no common bits set: 2675 // or (mul X, Y), X --> add (mul X, Y), X --> mul X, (Y + 1) 2676 if (match(&I, 2677 m_c_Or(m_OneUse(m_Mul(m_Value(X), m_Value(Y))), m_Deferred(X))) && 2678 haveNoCommonBitsSet(Op0, Op1, DL)) { 2679 Value *IncrementY = Builder.CreateAdd(Y, ConstantInt::get(Ty, 1)); 2680 return BinaryOperator::CreateMul(X, IncrementY); 2681 } 2682 2683 // (A & C) | (B & D) 2684 Value *A, *B, *C, *D; 2685 if (match(Op0, m_And(m_Value(A), m_Value(C))) && 2686 match(Op1, m_And(m_Value(B), m_Value(D)))) { 2687 2688 // (A & C0) | (B & C1) 2689 const APInt *C0, *C1; 2690 if (match(C, m_APInt(C0)) && match(D, m_APInt(C1))) { 2691 Value *X; 2692 if (*C0 == ~*C1) { 2693 // ((X | B) & MaskC) | (B & ~MaskC) -> (X & MaskC) | B 2694 if (match(A, m_c_Or(m_Value(X), m_Specific(B)))) 2695 return BinaryOperator::CreateOr(Builder.CreateAnd(X, *C0), B); 2696 // (A & MaskC) | ((X | A) & ~MaskC) -> (X & ~MaskC) | A 2697 if (match(B, m_c_Or(m_Specific(A), m_Value(X)))) 2698 return BinaryOperator::CreateOr(Builder.CreateAnd(X, *C1), A); 2699 2700 // ((X ^ B) & MaskC) | (B & ~MaskC) -> (X & MaskC) ^ B 2701 if (match(A, m_c_Xor(m_Value(X), m_Specific(B)))) 2702 return BinaryOperator::CreateXor(Builder.CreateAnd(X, *C0), B); 2703 // (A & MaskC) | ((X ^ A) & ~MaskC) -> (X & ~MaskC) ^ A 2704 if (match(B, m_c_Xor(m_Specific(A), m_Value(X)))) 2705 return BinaryOperator::CreateXor(Builder.CreateAnd(X, *C1), A); 2706 } 2707 2708 if ((*C0 & *C1).isZero()) { 2709 // ((X | B) & C0) | (B & C1) --> (X | B) & (C0 | C1) 2710 // iff (C0 & C1) == 0 and (X & ~C0) == 0 2711 if (match(A, m_c_Or(m_Value(X), m_Specific(B))) && 2712 MaskedValueIsZero(X, ~*C0, 0, &I)) { 2713 Constant *C01 = ConstantInt::get(Ty, *C0 | *C1); 2714 return BinaryOperator::CreateAnd(A, C01); 2715 } 2716 // (A & C0) | ((X | A) & C1) --> (X | A) & (C0 | C1) 2717 // iff (C0 & C1) == 0 and (X & ~C1) == 0 2718 if (match(B, m_c_Or(m_Value(X), m_Specific(A))) && 2719 MaskedValueIsZero(X, ~*C1, 0, &I)) { 2720 Constant *C01 = ConstantInt::get(Ty, *C0 | *C1); 2721 return BinaryOperator::CreateAnd(B, C01); 2722 } 2723 // ((X | C2) & C0) | ((X | C3) & C1) --> (X | C2 | C3) & (C0 | C1) 2724 // iff (C0 & C1) == 0 and (C2 & ~C0) == 0 and (C3 & ~C1) == 0. 2725 const APInt *C2, *C3; 2726 if (match(A, m_Or(m_Value(X), m_APInt(C2))) && 2727 match(B, m_Or(m_Specific(X), m_APInt(C3))) && 2728 (*C2 & ~*C0).isZero() && (*C3 & ~*C1).isZero()) { 2729 Value *Or = Builder.CreateOr(X, *C2 | *C3, "bitfield"); 2730 Constant *C01 = ConstantInt::get(Ty, *C0 | *C1); 2731 return BinaryOperator::CreateAnd(Or, C01); 2732 } 2733 } 2734 } 2735 2736 // Don't try to form a select if it's unlikely that we'll get rid of at 2737 // least one of the operands. A select is generally more expensive than the 2738 // 'or' that it is replacing. 2739 if (Op0->hasOneUse() || Op1->hasOneUse()) { 2740 // (Cond & C) | (~Cond & D) -> Cond ? C : D, and commuted variants. 2741 if (Value *V = matchSelectFromAndOr(A, C, B, D)) 2742 return replaceInstUsesWith(I, V); 2743 if (Value *V = matchSelectFromAndOr(A, C, D, B)) 2744 return replaceInstUsesWith(I, V); 2745 if (Value *V = matchSelectFromAndOr(C, A, B, D)) 2746 return replaceInstUsesWith(I, V); 2747 if (Value *V = matchSelectFromAndOr(C, A, D, B)) 2748 return replaceInstUsesWith(I, V); 2749 if (Value *V = matchSelectFromAndOr(B, D, A, C)) 2750 return replaceInstUsesWith(I, V); 2751 if (Value *V = matchSelectFromAndOr(B, D, C, A)) 2752 return replaceInstUsesWith(I, V); 2753 if (Value *V = matchSelectFromAndOr(D, B, A, C)) 2754 return replaceInstUsesWith(I, V); 2755 if (Value *V = matchSelectFromAndOr(D, B, C, A)) 2756 return replaceInstUsesWith(I, V); 2757 } 2758 } 2759 2760 // (A ^ B) | ((B ^ C) ^ A) -> (A ^ B) | C 2761 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) 2762 if (match(Op1, m_Xor(m_Xor(m_Specific(B), m_Value(C)), m_Specific(A)))) 2763 return BinaryOperator::CreateOr(Op0, C); 2764 2765 // ((A ^ C) ^ B) | (B ^ A) -> (B ^ A) | C 2766 if (match(Op0, m_Xor(m_Xor(m_Value(A), m_Value(C)), m_Value(B)))) 2767 if (match(Op1, m_Xor(m_Specific(B), m_Specific(A)))) 2768 return BinaryOperator::CreateOr(Op1, C); 2769 2770 // ((B | C) & A) | B -> B | (A & C) 2771 if (match(Op0, m_And(m_Or(m_Specific(Op1), m_Value(C)), m_Value(A)))) 2772 return BinaryOperator::CreateOr(Op1, Builder.CreateAnd(A, C)); 2773 2774 if (Instruction *DeMorgan = matchDeMorgansLaws(I, Builder)) 2775 return DeMorgan; 2776 2777 // Canonicalize xor to the RHS. 2778 bool SwappedForXor = false; 2779 if (match(Op0, m_Xor(m_Value(), m_Value()))) { 2780 std::swap(Op0, Op1); 2781 SwappedForXor = true; 2782 } 2783 2784 // A | ( A ^ B) -> A | B 2785 // A | (~A ^ B) -> A | ~B 2786 // (A & B) | (A ^ B) 2787 // ~A | (A ^ B) -> ~(A & B) 2788 // The swap above should always make Op0 the 'not' for the last case. 2789 if (match(Op1, m_Xor(m_Value(A), m_Value(B)))) { 2790 if (Op0 == A || Op0 == B) 2791 return BinaryOperator::CreateOr(A, B); 2792 2793 if (match(Op0, m_And(m_Specific(A), m_Specific(B))) || 2794 match(Op0, m_And(m_Specific(B), m_Specific(A)))) 2795 return BinaryOperator::CreateOr(A, B); 2796 2797 if ((Op0->hasOneUse() || Op1->hasOneUse()) && 2798 (match(Op0, m_Not(m_Specific(A))) || match(Op0, m_Not(m_Specific(B))))) 2799 return BinaryOperator::CreateNot(Builder.CreateAnd(A, B)); 2800 2801 if (Op1->hasOneUse() && match(A, m_Not(m_Specific(Op0)))) { 2802 Value *Not = Builder.CreateNot(B, B->getName() + ".not"); 2803 return BinaryOperator::CreateOr(Not, Op0); 2804 } 2805 if (Op1->hasOneUse() && match(B, m_Not(m_Specific(Op0)))) { 2806 Value *Not = Builder.CreateNot(A, A->getName() + ".not"); 2807 return BinaryOperator::CreateOr(Not, Op0); 2808 } 2809 } 2810 2811 // A | ~(A | B) -> A | ~B 2812 // A | ~(A ^ B) -> A | ~B 2813 if (match(Op1, m_Not(m_Value(A)))) 2814 if (BinaryOperator *B = dyn_cast<BinaryOperator>(A)) 2815 if ((Op0 == B->getOperand(0) || Op0 == B->getOperand(1)) && 2816 Op1->hasOneUse() && (B->getOpcode() == Instruction::Or || 2817 B->getOpcode() == Instruction::Xor)) { 2818 Value *NotOp = Op0 == B->getOperand(0) ? B->getOperand(1) : 2819 B->getOperand(0); 2820 Value *Not = Builder.CreateNot(NotOp, NotOp->getName() + ".not"); 2821 return BinaryOperator::CreateOr(Not, Op0); 2822 } 2823 2824 if (SwappedForXor) 2825 std::swap(Op0, Op1); 2826 2827 { 2828 ICmpInst *LHS = dyn_cast<ICmpInst>(Op0); 2829 ICmpInst *RHS = dyn_cast<ICmpInst>(Op1); 2830 if (LHS && RHS) 2831 if (Value *Res = foldAndOrOfICmps(LHS, RHS, I, /* IsAnd */ false)) 2832 return replaceInstUsesWith(I, Res); 2833 2834 // TODO: Make this recursive; it's a little tricky because an arbitrary 2835 // number of 'or' instructions might have to be created. 2836 Value *X, *Y; 2837 if (LHS && match(Op1, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) { 2838 if (auto *Cmp = dyn_cast<ICmpInst>(X)) 2839 if (Value *Res = foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ false)) 2840 return replaceInstUsesWith(I, Builder.CreateOr(Res, Y)); 2841 if (auto *Cmp = dyn_cast<ICmpInst>(Y)) 2842 if (Value *Res = foldAndOrOfICmps(LHS, Cmp, I, /* IsAnd */ false)) 2843 return replaceInstUsesWith(I, Builder.CreateOr(Res, X)); 2844 } 2845 if (RHS && match(Op0, m_OneUse(m_Or(m_Value(X), m_Value(Y))))) { 2846 if (auto *Cmp = dyn_cast<ICmpInst>(X)) 2847 if (Value *Res = foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ false)) 2848 return replaceInstUsesWith(I, Builder.CreateOr(Res, Y)); 2849 if (auto *Cmp = dyn_cast<ICmpInst>(Y)) 2850 if (Value *Res = foldAndOrOfICmps(Cmp, RHS, I, /* IsAnd */ false)) 2851 return replaceInstUsesWith(I, Builder.CreateOr(Res, X)); 2852 } 2853 } 2854 2855 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) 2856 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) 2857 if (Value *Res = foldLogicOfFCmps(LHS, RHS, /*IsAnd*/ false)) 2858 return replaceInstUsesWith(I, Res); 2859 2860 if (Instruction *FoldedFCmps = reassociateFCmps(I, Builder)) 2861 return FoldedFCmps; 2862 2863 if (Instruction *CastedOr = foldCastedBitwiseLogic(I)) 2864 return CastedOr; 2865 2866 if (Instruction *Sel = foldBinopOfSextBoolToSelect(I)) 2867 return Sel; 2868 2869 // or(sext(A), B) / or(B, sext(A)) --> A ? -1 : B, where A is i1 or <N x i1>. 2870 // TODO: Move this into foldBinopOfSextBoolToSelect as a more generalized fold 2871 // with binop identity constant. But creating a select with non-constant 2872 // arm may not be reversible due to poison semantics. Is that a good 2873 // canonicalization? 2874 if (match(Op0, m_OneUse(m_SExt(m_Value(A)))) && 2875 A->getType()->isIntOrIntVectorTy(1)) 2876 return SelectInst::Create(A, ConstantInt::getAllOnesValue(Ty), Op1); 2877 if (match(Op1, m_OneUse(m_SExt(m_Value(A)))) && 2878 A->getType()->isIntOrIntVectorTy(1)) 2879 return SelectInst::Create(A, ConstantInt::getAllOnesValue(Ty), Op0); 2880 2881 // Note: If we've gotten to the point of visiting the outer OR, then the 2882 // inner one couldn't be simplified. If it was a constant, then it won't 2883 // be simplified by a later pass either, so we try swapping the inner/outer 2884 // ORs in the hopes that we'll be able to simplify it this way. 2885 // (X|C) | V --> (X|V) | C 2886 ConstantInt *CI; 2887 if (Op0->hasOneUse() && !match(Op1, m_ConstantInt()) && 2888 match(Op0, m_Or(m_Value(A), m_ConstantInt(CI)))) { 2889 Value *Inner = Builder.CreateOr(A, Op1); 2890 Inner->takeName(Op0); 2891 return BinaryOperator::CreateOr(Inner, CI); 2892 } 2893 2894 // Change (or (bool?A:B),(bool?C:D)) --> (bool?(or A,C):(or B,D)) 2895 // Since this OR statement hasn't been optimized further yet, we hope 2896 // that this transformation will allow the new ORs to be optimized. 2897 { 2898 Value *X = nullptr, *Y = nullptr; 2899 if (Op0->hasOneUse() && Op1->hasOneUse() && 2900 match(Op0, m_Select(m_Value(X), m_Value(A), m_Value(B))) && 2901 match(Op1, m_Select(m_Value(Y), m_Value(C), m_Value(D))) && X == Y) { 2902 Value *orTrue = Builder.CreateOr(A, C); 2903 Value *orFalse = Builder.CreateOr(B, D); 2904 return SelectInst::Create(X, orTrue, orFalse); 2905 } 2906 } 2907 2908 // or(ashr(subNSW(Y, X), ScalarSizeInBits(Y) - 1), X) --> X s> Y ? -1 : X. 2909 { 2910 Value *X, *Y; 2911 if (match(&I, m_c_Or(m_OneUse(m_AShr( 2912 m_NSWSub(m_Value(Y), m_Value(X)), 2913 m_SpecificInt(Ty->getScalarSizeInBits() - 1))), 2914 m_Deferred(X)))) { 2915 Value *NewICmpInst = Builder.CreateICmpSGT(X, Y); 2916 Value *AllOnes = ConstantInt::getAllOnesValue(Ty); 2917 return SelectInst::Create(NewICmpInst, AllOnes, X); 2918 } 2919 } 2920 2921 if (Instruction *V = 2922 canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(I)) 2923 return V; 2924 2925 CmpInst::Predicate Pred; 2926 Value *Mul, *Ov, *MulIsNotZero, *UMulWithOv; 2927 // Check if the OR weakens the overflow condition for umul.with.overflow by 2928 // treating any non-zero result as overflow. In that case, we overflow if both 2929 // umul.with.overflow operands are != 0, as in that case the result can only 2930 // be 0, iff the multiplication overflows. 2931 if (match(&I, 2932 m_c_Or(m_CombineAnd(m_ExtractValue<1>(m_Value(UMulWithOv)), 2933 m_Value(Ov)), 2934 m_CombineAnd(m_ICmp(Pred, 2935 m_CombineAnd(m_ExtractValue<0>( 2936 m_Deferred(UMulWithOv)), 2937 m_Value(Mul)), 2938 m_ZeroInt()), 2939 m_Value(MulIsNotZero)))) && 2940 (Ov->hasOneUse() || (MulIsNotZero->hasOneUse() && Mul->hasOneUse())) && 2941 Pred == CmpInst::ICMP_NE) { 2942 Value *A, *B; 2943 if (match(UMulWithOv, m_Intrinsic<Intrinsic::umul_with_overflow>( 2944 m_Value(A), m_Value(B)))) { 2945 Value *NotNullA = Builder.CreateIsNotNull(A); 2946 Value *NotNullB = Builder.CreateIsNotNull(B); 2947 return BinaryOperator::CreateAnd(NotNullA, NotNullB); 2948 } 2949 } 2950 2951 // (~x) | y --> ~(x & (~y)) iff that gets rid of inversions 2952 if (sinkNotIntoOtherHandOfAndOrOr(I)) 2953 return &I; 2954 2955 // Improve "get low bit mask up to and including bit X" pattern: 2956 // (1 << X) | ((1 << X) + -1) --> -1 l>> (bitwidth(x) - 1 - X) 2957 if (match(&I, m_c_Or(m_Add(m_Shl(m_One(), m_Value(X)), m_AllOnes()), 2958 m_Shl(m_One(), m_Deferred(X)))) && 2959 match(&I, m_c_Or(m_OneUse(m_Value()), m_Value()))) { 2960 Value *Sub = Builder.CreateSub( 2961 ConstantInt::get(Ty, Ty->getScalarSizeInBits() - 1), X); 2962 return BinaryOperator::CreateLShr(Constant::getAllOnesValue(Ty), Sub); 2963 } 2964 2965 // An or recurrence w/loop invariant step is equivelent to (or start, step) 2966 PHINode *PN = nullptr; 2967 Value *Start = nullptr, *Step = nullptr; 2968 if (matchSimpleRecurrence(&I, PN, Start, Step) && DT.dominates(Step, PN)) 2969 return replaceInstUsesWith(I, Builder.CreateOr(Start, Step)); 2970 2971 return nullptr; 2972 } 2973 2974 /// A ^ B can be specified using other logic ops in a variety of patterns. We 2975 /// can fold these early and efficiently by morphing an existing instruction. 2976 static Instruction *foldXorToXor(BinaryOperator &I, 2977 InstCombiner::BuilderTy &Builder) { 2978 assert(I.getOpcode() == Instruction::Xor); 2979 Value *Op0 = I.getOperand(0); 2980 Value *Op1 = I.getOperand(1); 2981 Value *A, *B; 2982 2983 // There are 4 commuted variants for each of the basic patterns. 2984 2985 // (A & B) ^ (A | B) -> A ^ B 2986 // (A & B) ^ (B | A) -> A ^ B 2987 // (A | B) ^ (A & B) -> A ^ B 2988 // (A | B) ^ (B & A) -> A ^ B 2989 if (match(&I, m_c_Xor(m_And(m_Value(A), m_Value(B)), 2990 m_c_Or(m_Deferred(A), m_Deferred(B))))) 2991 return BinaryOperator::CreateXor(A, B); 2992 2993 // (A | ~B) ^ (~A | B) -> A ^ B 2994 // (~B | A) ^ (~A | B) -> A ^ B 2995 // (~A | B) ^ (A | ~B) -> A ^ B 2996 // (B | ~A) ^ (A | ~B) -> A ^ B 2997 if (match(&I, m_Xor(m_c_Or(m_Value(A), m_Not(m_Value(B))), 2998 m_c_Or(m_Not(m_Deferred(A)), m_Deferred(B))))) 2999 return BinaryOperator::CreateXor(A, B); 3000 3001 // (A & ~B) ^ (~A & B) -> A ^ B 3002 // (~B & A) ^ (~A & B) -> A ^ B 3003 // (~A & B) ^ (A & ~B) -> A ^ B 3004 // (B & ~A) ^ (A & ~B) -> A ^ B 3005 if (match(&I, m_Xor(m_c_And(m_Value(A), m_Not(m_Value(B))), 3006 m_c_And(m_Not(m_Deferred(A)), m_Deferred(B))))) 3007 return BinaryOperator::CreateXor(A, B); 3008 3009 // For the remaining cases we need to get rid of one of the operands. 3010 if (!Op0->hasOneUse() && !Op1->hasOneUse()) 3011 return nullptr; 3012 3013 // (A | B) ^ ~(A & B) -> ~(A ^ B) 3014 // (A | B) ^ ~(B & A) -> ~(A ^ B) 3015 // (A & B) ^ ~(A | B) -> ~(A ^ B) 3016 // (A & B) ^ ~(B | A) -> ~(A ^ B) 3017 // Complexity sorting ensures the not will be on the right side. 3018 if ((match(Op0, m_Or(m_Value(A), m_Value(B))) && 3019 match(Op1, m_Not(m_c_And(m_Specific(A), m_Specific(B))))) || 3020 (match(Op0, m_And(m_Value(A), m_Value(B))) && 3021 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))) 3022 return BinaryOperator::CreateNot(Builder.CreateXor(A, B)); 3023 3024 return nullptr; 3025 } 3026 3027 Value *InstCombinerImpl::foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS, 3028 BinaryOperator &I) { 3029 assert(I.getOpcode() == Instruction::Xor && I.getOperand(0) == LHS && 3030 I.getOperand(1) == RHS && "Should be 'xor' with these operands"); 3031 3032 if (predicatesFoldable(LHS->getPredicate(), RHS->getPredicate())) { 3033 if (LHS->getOperand(0) == RHS->getOperand(1) && 3034 LHS->getOperand(1) == RHS->getOperand(0)) 3035 LHS->swapOperands(); 3036 if (LHS->getOperand(0) == RHS->getOperand(0) && 3037 LHS->getOperand(1) == RHS->getOperand(1)) { 3038 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B) 3039 Value *Op0 = LHS->getOperand(0), *Op1 = LHS->getOperand(1); 3040 unsigned Code = 3041 getICmpCode(LHS->getPredicate()) ^ getICmpCode(RHS->getPredicate()); 3042 bool IsSigned = LHS->isSigned() || RHS->isSigned(); 3043 return getNewICmpValue(Code, IsSigned, Op0, Op1, Builder); 3044 } 3045 } 3046 3047 // TODO: This can be generalized to compares of non-signbits using 3048 // decomposeBitTestICmp(). It could be enhanced more by using (something like) 3049 // foldLogOpOfMaskedICmps(). 3050 ICmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate(); 3051 Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1); 3052 Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1); 3053 if ((LHS->hasOneUse() || RHS->hasOneUse()) && 3054 LHS0->getType() == RHS0->getType() && 3055 LHS0->getType()->isIntOrIntVectorTy()) { 3056 // (X > -1) ^ (Y > -1) --> (X ^ Y) < 0 3057 // (X < 0) ^ (Y < 0) --> (X ^ Y) < 0 3058 if ((PredL == CmpInst::ICMP_SGT && match(LHS1, m_AllOnes()) && 3059 PredR == CmpInst::ICMP_SGT && match(RHS1, m_AllOnes())) || 3060 (PredL == CmpInst::ICMP_SLT && match(LHS1, m_Zero()) && 3061 PredR == CmpInst::ICMP_SLT && match(RHS1, m_Zero()))) { 3062 Value *Zero = ConstantInt::getNullValue(LHS0->getType()); 3063 return Builder.CreateICmpSLT(Builder.CreateXor(LHS0, RHS0), Zero); 3064 } 3065 // (X > -1) ^ (Y < 0) --> (X ^ Y) > -1 3066 // (X < 0) ^ (Y > -1) --> (X ^ Y) > -1 3067 if ((PredL == CmpInst::ICMP_SGT && match(LHS1, m_AllOnes()) && 3068 PredR == CmpInst::ICMP_SLT && match(RHS1, m_Zero())) || 3069 (PredL == CmpInst::ICMP_SLT && match(LHS1, m_Zero()) && 3070 PredR == CmpInst::ICMP_SGT && match(RHS1, m_AllOnes()))) { 3071 Value *MinusOne = ConstantInt::getAllOnesValue(LHS0->getType()); 3072 return Builder.CreateICmpSGT(Builder.CreateXor(LHS0, RHS0), MinusOne); 3073 } 3074 } 3075 3076 // Instead of trying to imitate the folds for and/or, decompose this 'xor' 3077 // into those logic ops. That is, try to turn this into an and-of-icmps 3078 // because we have many folds for that pattern. 3079 // 3080 // This is based on a truth table definition of xor: 3081 // X ^ Y --> (X | Y) & !(X & Y) 3082 if (Value *OrICmp = SimplifyBinOp(Instruction::Or, LHS, RHS, SQ)) { 3083 // TODO: If OrICmp is true, then the definition of xor simplifies to !(X&Y). 3084 // TODO: If OrICmp is false, the whole thing is false (InstSimplify?). 3085 if (Value *AndICmp = SimplifyBinOp(Instruction::And, LHS, RHS, SQ)) { 3086 // TODO: Independently handle cases where the 'and' side is a constant. 3087 ICmpInst *X = nullptr, *Y = nullptr; 3088 if (OrICmp == LHS && AndICmp == RHS) { 3089 // (LHS | RHS) & !(LHS & RHS) --> LHS & !RHS --> X & !Y 3090 X = LHS; 3091 Y = RHS; 3092 } 3093 if (OrICmp == RHS && AndICmp == LHS) { 3094 // !(LHS & RHS) & (LHS | RHS) --> !LHS & RHS --> !Y & X 3095 X = RHS; 3096 Y = LHS; 3097 } 3098 if (X && Y && (Y->hasOneUse() || canFreelyInvertAllUsersOf(Y, &I))) { 3099 // Invert the predicate of 'Y', thus inverting its output. 3100 Y->setPredicate(Y->getInversePredicate()); 3101 // So, are there other uses of Y? 3102 if (!Y->hasOneUse()) { 3103 // We need to adapt other uses of Y though. Get a value that matches 3104 // the original value of Y before inversion. While this increases 3105 // immediate instruction count, we have just ensured that all the 3106 // users are freely-invertible, so that 'not' *will* get folded away. 3107 BuilderTy::InsertPointGuard Guard(Builder); 3108 // Set insertion point to right after the Y. 3109 Builder.SetInsertPoint(Y->getParent(), ++(Y->getIterator())); 3110 Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not"); 3111 // Replace all uses of Y (excluding the one in NotY!) with NotY. 3112 Worklist.pushUsersToWorkList(*Y); 3113 Y->replaceUsesWithIf(NotY, 3114 [NotY](Use &U) { return U.getUser() != NotY; }); 3115 } 3116 // All done. 3117 return Builder.CreateAnd(LHS, RHS); 3118 } 3119 } 3120 } 3121 3122 return nullptr; 3123 } 3124 3125 /// If we have a masked merge, in the canonical form of: 3126 /// (assuming that A only has one use.) 3127 /// | A | |B| 3128 /// ((x ^ y) & M) ^ y 3129 /// | D | 3130 /// * If M is inverted: 3131 /// | D | 3132 /// ((x ^ y) & ~M) ^ y 3133 /// We can canonicalize by swapping the final xor operand 3134 /// to eliminate the 'not' of the mask. 3135 /// ((x ^ y) & M) ^ x 3136 /// * If M is a constant, and D has one use, we transform to 'and' / 'or' ops 3137 /// because that shortens the dependency chain and improves analysis: 3138 /// (x & M) | (y & ~M) 3139 static Instruction *visitMaskedMerge(BinaryOperator &I, 3140 InstCombiner::BuilderTy &Builder) { 3141 Value *B, *X, *D; 3142 Value *M; 3143 if (!match(&I, m_c_Xor(m_Value(B), 3144 m_OneUse(m_c_And( 3145 m_CombineAnd(m_c_Xor(m_Deferred(B), m_Value(X)), 3146 m_Value(D)), 3147 m_Value(M)))))) 3148 return nullptr; 3149 3150 Value *NotM; 3151 if (match(M, m_Not(m_Value(NotM)))) { 3152 // De-invert the mask and swap the value in B part. 3153 Value *NewA = Builder.CreateAnd(D, NotM); 3154 return BinaryOperator::CreateXor(NewA, X); 3155 } 3156 3157 Constant *C; 3158 if (D->hasOneUse() && match(M, m_Constant(C))) { 3159 // Propagating undef is unsafe. Clamp undef elements to -1. 3160 Type *EltTy = C->getType()->getScalarType(); 3161 C = Constant::replaceUndefsWith(C, ConstantInt::getAllOnesValue(EltTy)); 3162 // Unfold. 3163 Value *LHS = Builder.CreateAnd(X, C); 3164 Value *NotC = Builder.CreateNot(C); 3165 Value *RHS = Builder.CreateAnd(B, NotC); 3166 return BinaryOperator::CreateOr(LHS, RHS); 3167 } 3168 3169 return nullptr; 3170 } 3171 3172 // Transform 3173 // ~(x ^ y) 3174 // into: 3175 // (~x) ^ y 3176 // or into 3177 // x ^ (~y) 3178 static Instruction *sinkNotIntoXor(BinaryOperator &I, 3179 InstCombiner::BuilderTy &Builder) { 3180 Value *X, *Y; 3181 // FIXME: one-use check is not needed in general, but currently we are unable 3182 // to fold 'not' into 'icmp', if that 'icmp' has multiple uses. (D35182) 3183 if (!match(&I, m_Not(m_OneUse(m_Xor(m_Value(X), m_Value(Y)))))) 3184 return nullptr; 3185 3186 // We only want to do the transform if it is free to do. 3187 if (InstCombiner::isFreeToInvert(X, X->hasOneUse())) { 3188 // Ok, good. 3189 } else if (InstCombiner::isFreeToInvert(Y, Y->hasOneUse())) { 3190 std::swap(X, Y); 3191 } else 3192 return nullptr; 3193 3194 Value *NotX = Builder.CreateNot(X, X->getName() + ".not"); 3195 return BinaryOperator::CreateXor(NotX, Y, I.getName() + ".demorgan"); 3196 } 3197 3198 /// Canonicalize a shifty way to code absolute value to the more common pattern 3199 /// that uses negation and select. 3200 static Instruction *canonicalizeAbs(BinaryOperator &Xor, 3201 InstCombiner::BuilderTy &Builder) { 3202 assert(Xor.getOpcode() == Instruction::Xor && "Expected an xor instruction."); 3203 3204 // There are 4 potential commuted variants. Move the 'ashr' candidate to Op1. 3205 // We're relying on the fact that we only do this transform when the shift has 3206 // exactly 2 uses and the add has exactly 1 use (otherwise, we might increase 3207 // instructions). 3208 Value *Op0 = Xor.getOperand(0), *Op1 = Xor.getOperand(1); 3209 if (Op0->hasNUses(2)) 3210 std::swap(Op0, Op1); 3211 3212 Type *Ty = Xor.getType(); 3213 Value *A; 3214 const APInt *ShAmt; 3215 if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) && 3216 Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 && 3217 match(Op0, m_OneUse(m_c_Add(m_Specific(A), m_Specific(Op1))))) { 3218 // Op1 = ashr i32 A, 31 ; smear the sign bit 3219 // xor (add A, Op1), Op1 ; add -1 and flip bits if negative 3220 // --> (A < 0) ? -A : A 3221 Value *Cmp = Builder.CreateICmpSLT(A, ConstantInt::getNullValue(Ty)); 3222 // Copy the nuw/nsw flags from the add to the negate. 3223 auto *Add = cast<BinaryOperator>(Op0); 3224 Value *Neg = Builder.CreateNeg(A, "", Add->hasNoUnsignedWrap(), 3225 Add->hasNoSignedWrap()); 3226 return SelectInst::Create(Cmp, Neg, A); 3227 } 3228 return nullptr; 3229 } 3230 3231 // Transform 3232 // z = (~x) &/| y 3233 // into: 3234 // z = ~(x |/& (~y)) 3235 // iff y is free to invert and all uses of z can be freely updated. 3236 bool InstCombinerImpl::sinkNotIntoOtherHandOfAndOrOr(BinaryOperator &I) { 3237 Instruction::BinaryOps NewOpc; 3238 switch (I.getOpcode()) { 3239 case Instruction::And: 3240 NewOpc = Instruction::Or; 3241 break; 3242 case Instruction::Or: 3243 NewOpc = Instruction::And; 3244 break; 3245 default: 3246 return false; 3247 }; 3248 3249 Value *X, *Y; 3250 if (!match(&I, m_c_BinOp(m_Not(m_Value(X)), m_Value(Y)))) 3251 return false; 3252 3253 // Will we be able to fold the `not` into Y eventually? 3254 if (!InstCombiner::isFreeToInvert(Y, Y->hasOneUse())) 3255 return false; 3256 3257 // And can our users be adapted? 3258 if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr)) 3259 return false; 3260 3261 Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not"); 3262 Value *NewBinOp = 3263 BinaryOperator::Create(NewOpc, X, NotY, I.getName() + ".not"); 3264 Builder.Insert(NewBinOp); 3265 replaceInstUsesWith(I, NewBinOp); 3266 // We can not just create an outer `not`, it will most likely be immediately 3267 // folded back, reconstructing our initial pattern, and causing an 3268 // infinite combine loop, so immediately manually fold it away. 3269 freelyInvertAllUsersOf(NewBinOp); 3270 return true; 3271 } 3272 3273 Instruction *InstCombinerImpl::foldNot(BinaryOperator &I) { 3274 Value *NotOp; 3275 if (!match(&I, m_Not(m_Value(NotOp)))) 3276 return nullptr; 3277 3278 // Apply DeMorgan's Law for 'nand' / 'nor' logic with an inverted operand. 3279 // We must eliminate the and/or (one-use) for these transforms to not increase 3280 // the instruction count. 3281 // 3282 // ~(~X & Y) --> (X | ~Y) 3283 // ~(Y & ~X) --> (X | ~Y) 3284 // 3285 // Note: The logical matches do not check for the commuted patterns because 3286 // those are handled via SimplifySelectsFeedingBinaryOp(). 3287 Type *Ty = I.getType(); 3288 Value *X, *Y; 3289 if (match(NotOp, m_OneUse(m_c_And(m_Not(m_Value(X)), m_Value(Y))))) { 3290 Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not"); 3291 return BinaryOperator::CreateOr(X, NotY); 3292 } 3293 if (match(NotOp, m_OneUse(m_LogicalAnd(m_Not(m_Value(X)), m_Value(Y))))) { 3294 Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not"); 3295 return SelectInst::Create(X, ConstantInt::getTrue(Ty), NotY); 3296 } 3297 3298 // ~(~X | Y) --> (X & ~Y) 3299 // ~(Y | ~X) --> (X & ~Y) 3300 if (match(NotOp, m_OneUse(m_c_Or(m_Not(m_Value(X)), m_Value(Y))))) { 3301 Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not"); 3302 return BinaryOperator::CreateAnd(X, NotY); 3303 } 3304 if (match(NotOp, m_OneUse(m_LogicalOr(m_Not(m_Value(X)), m_Value(Y))))) { 3305 Value *NotY = Builder.CreateNot(Y, Y->getName() + ".not"); 3306 return SelectInst::Create(X, NotY, ConstantInt::getFalse(Ty)); 3307 } 3308 3309 // Is this a 'not' (~) fed by a binary operator? 3310 BinaryOperator *NotVal; 3311 if (match(NotOp, m_BinOp(NotVal))) { 3312 if (NotVal->getOpcode() == Instruction::And || 3313 NotVal->getOpcode() == Instruction::Or) { 3314 // Apply DeMorgan's Law when inverts are free: 3315 // ~(X & Y) --> (~X | ~Y) 3316 // ~(X | Y) --> (~X & ~Y) 3317 if (isFreeToInvert(NotVal->getOperand(0), 3318 NotVal->getOperand(0)->hasOneUse()) && 3319 isFreeToInvert(NotVal->getOperand(1), 3320 NotVal->getOperand(1)->hasOneUse())) { 3321 Value *NotX = Builder.CreateNot(NotVal->getOperand(0), "notlhs"); 3322 Value *NotY = Builder.CreateNot(NotVal->getOperand(1), "notrhs"); 3323 if (NotVal->getOpcode() == Instruction::And) 3324 return BinaryOperator::CreateOr(NotX, NotY); 3325 return BinaryOperator::CreateAnd(NotX, NotY); 3326 } 3327 } 3328 3329 // ~((-X) | Y) --> (X - 1) & (~Y) 3330 if (match(NotVal, 3331 m_OneUse(m_c_Or(m_OneUse(m_Neg(m_Value(X))), m_Value(Y))))) { 3332 Value *DecX = Builder.CreateAdd(X, ConstantInt::getAllOnesValue(Ty)); 3333 Value *NotY = Builder.CreateNot(Y); 3334 return BinaryOperator::CreateAnd(DecX, NotY); 3335 } 3336 3337 // ~(~X >>s Y) --> (X >>s Y) 3338 if (match(NotVal, m_AShr(m_Not(m_Value(X)), m_Value(Y)))) 3339 return BinaryOperator::CreateAShr(X, Y); 3340 3341 // If we are inverting a right-shifted constant, we may be able to eliminate 3342 // the 'not' by inverting the constant and using the opposite shift type. 3343 // Canonicalization rules ensure that only a negative constant uses 'ashr', 3344 // but we must check that in case that transform has not fired yet. 3345 3346 // ~(C >>s Y) --> ~C >>u Y (when inverting the replicated sign bits) 3347 Constant *C; 3348 if (match(NotVal, m_AShr(m_Constant(C), m_Value(Y))) && 3349 match(C, m_Negative())) { 3350 // We matched a negative constant, so propagating undef is unsafe. 3351 // Clamp undef elements to -1. 3352 Type *EltTy = Ty->getScalarType(); 3353 C = Constant::replaceUndefsWith(C, ConstantInt::getAllOnesValue(EltTy)); 3354 return BinaryOperator::CreateLShr(ConstantExpr::getNot(C), Y); 3355 } 3356 3357 // ~(C >>u Y) --> ~C >>s Y (when inverting the replicated sign bits) 3358 if (match(NotVal, m_LShr(m_Constant(C), m_Value(Y))) && 3359 match(C, m_NonNegative())) { 3360 // We matched a non-negative constant, so propagating undef is unsafe. 3361 // Clamp undef elements to 0. 3362 Type *EltTy = Ty->getScalarType(); 3363 C = Constant::replaceUndefsWith(C, ConstantInt::getNullValue(EltTy)); 3364 return BinaryOperator::CreateAShr(ConstantExpr::getNot(C), Y); 3365 } 3366 3367 // ~(X + C) --> ~C - X 3368 if (match(NotVal, m_c_Add(m_Value(X), m_ImmConstant(C)))) 3369 return BinaryOperator::CreateSub(ConstantExpr::getNot(C), X); 3370 3371 // ~(X - Y) --> ~X + Y 3372 // FIXME: is it really beneficial to sink the `not` here? 3373 if (match(NotVal, m_Sub(m_Value(X), m_Value(Y)))) 3374 if (isa<Constant>(X) || NotVal->hasOneUse()) 3375 return BinaryOperator::CreateAdd(Builder.CreateNot(X), Y); 3376 3377 // ~(~X + Y) --> X - Y 3378 if (match(NotVal, m_c_Add(m_Not(m_Value(X)), m_Value(Y)))) 3379 return BinaryOperator::CreateWithCopiedFlags(Instruction::Sub, X, Y, 3380 NotVal); 3381 } 3382 3383 // not (cmp A, B) = !cmp A, B 3384 CmpInst::Predicate Pred; 3385 if (match(NotOp, m_OneUse(m_Cmp(Pred, m_Value(), m_Value())))) { 3386 cast<CmpInst>(NotOp)->setPredicate(CmpInst::getInversePredicate(Pred)); 3387 return replaceInstUsesWith(I, NotOp); 3388 } 3389 3390 // Eliminate a bitwise 'not' op of 'not' min/max by inverting the min/max: 3391 // ~min(~X, ~Y) --> max(X, Y) 3392 // ~max(~X, Y) --> min(X, ~Y) 3393 auto *II = dyn_cast<IntrinsicInst>(NotOp); 3394 if (II && II->hasOneUse()) { 3395 if (match(NotOp, m_MaxOrMin(m_Value(X), m_Value(Y))) && 3396 isFreeToInvert(X, X->hasOneUse()) && 3397 isFreeToInvert(Y, Y->hasOneUse())) { 3398 Intrinsic::ID InvID = getInverseMinMaxIntrinsic(II->getIntrinsicID()); 3399 Value *NotX = Builder.CreateNot(X); 3400 Value *NotY = Builder.CreateNot(Y); 3401 Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, NotX, NotY); 3402 return replaceInstUsesWith(I, InvMaxMin); 3403 } 3404 if (match(NotOp, m_c_MaxOrMin(m_Not(m_Value(X)), m_Value(Y)))) { 3405 Intrinsic::ID InvID = getInverseMinMaxIntrinsic(II->getIntrinsicID()); 3406 Value *NotY = Builder.CreateNot(Y); 3407 Value *InvMaxMin = Builder.CreateBinaryIntrinsic(InvID, X, NotY); 3408 return replaceInstUsesWith(I, InvMaxMin); 3409 } 3410 } 3411 3412 if (NotOp->hasOneUse()) { 3413 // Pull 'not' into operands of select if both operands are one-use compares 3414 // or one is one-use compare and the other one is a constant. 3415 // Inverting the predicates eliminates the 'not' operation. 3416 // Example: 3417 // not (select ?, (cmp TPred, ?, ?), (cmp FPred, ?, ?) --> 3418 // select ?, (cmp InvTPred, ?, ?), (cmp InvFPred, ?, ?) 3419 // not (select ?, (cmp TPred, ?, ?), true --> 3420 // select ?, (cmp InvTPred, ?, ?), false 3421 if (auto *Sel = dyn_cast<SelectInst>(NotOp)) { 3422 Value *TV = Sel->getTrueValue(); 3423 Value *FV = Sel->getFalseValue(); 3424 auto *CmpT = dyn_cast<CmpInst>(TV); 3425 auto *CmpF = dyn_cast<CmpInst>(FV); 3426 bool InvertibleT = (CmpT && CmpT->hasOneUse()) || isa<Constant>(TV); 3427 bool InvertibleF = (CmpF && CmpF->hasOneUse()) || isa<Constant>(FV); 3428 if (InvertibleT && InvertibleF) { 3429 if (CmpT) 3430 CmpT->setPredicate(CmpT->getInversePredicate()); 3431 else 3432 Sel->setTrueValue(ConstantExpr::getNot(cast<Constant>(TV))); 3433 if (CmpF) 3434 CmpF->setPredicate(CmpF->getInversePredicate()); 3435 else 3436 Sel->setFalseValue(ConstantExpr::getNot(cast<Constant>(FV))); 3437 return replaceInstUsesWith(I, Sel); 3438 } 3439 } 3440 } 3441 3442 if (Instruction *NewXor = sinkNotIntoXor(I, Builder)) 3443 return NewXor; 3444 3445 return nullptr; 3446 } 3447 3448 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches 3449 // here. We should standardize that construct where it is needed or choose some 3450 // other way to ensure that commutated variants of patterns are not missed. 3451 Instruction *InstCombinerImpl::visitXor(BinaryOperator &I) { 3452 if (Value *V = SimplifyXorInst(I.getOperand(0), I.getOperand(1), 3453 SQ.getWithInstruction(&I))) 3454 return replaceInstUsesWith(I, V); 3455 3456 if (SimplifyAssociativeOrCommutative(I)) 3457 return &I; 3458 3459 if (Instruction *X = foldVectorBinop(I)) 3460 return X; 3461 3462 if (Instruction *Phi = foldBinopWithPhiOperands(I)) 3463 return Phi; 3464 3465 if (Instruction *NewXor = foldXorToXor(I, Builder)) 3466 return NewXor; 3467 3468 // (A&B)^(A&C) -> A&(B^C) etc 3469 if (Value *V = SimplifyUsingDistributiveLaws(I)) 3470 return replaceInstUsesWith(I, V); 3471 3472 // See if we can simplify any instructions used by the instruction whose sole 3473 // purpose is to compute bits we don't care about. 3474 if (SimplifyDemandedInstructionBits(I)) 3475 return &I; 3476 3477 if (Value *V = SimplifyBSwap(I, Builder)) 3478 return replaceInstUsesWith(I, V); 3479 3480 if (Instruction *R = foldNot(I)) 3481 return R; 3482 3483 // Fold (X & M) ^ (Y & ~M) -> (X & M) | (Y & ~M) 3484 // This it a special case in haveNoCommonBitsSet, but the computeKnownBits 3485 // calls in there are unnecessary as SimplifyDemandedInstructionBits should 3486 // have already taken care of those cases. 3487 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); 3488 Value *M; 3489 if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(M)), m_Value()), 3490 m_c_And(m_Deferred(M), m_Value())))) 3491 return BinaryOperator::CreateOr(Op0, Op1); 3492 3493 if (Instruction *Xor = visitMaskedMerge(I, Builder)) 3494 return Xor; 3495 3496 Value *X, *Y; 3497 Constant *C1; 3498 if (match(Op1, m_Constant(C1))) { 3499 Constant *C2; 3500 3501 if (match(Op0, m_OneUse(m_Or(m_Value(X), m_ImmConstant(C2)))) && 3502 match(C1, m_ImmConstant())) { 3503 // (X | C2) ^ C1 --> (X & ~C2) ^ (C1^C2) 3504 C2 = Constant::replaceUndefsWith( 3505 C2, Constant::getAllOnesValue(C2->getType()->getScalarType())); 3506 Value *And = Builder.CreateAnd( 3507 X, Constant::mergeUndefsWith(ConstantExpr::getNot(C2), C1)); 3508 return BinaryOperator::CreateXor( 3509 And, Constant::mergeUndefsWith(ConstantExpr::getXor(C1, C2), C1)); 3510 } 3511 3512 // Use DeMorgan and reassociation to eliminate a 'not' op. 3513 if (match(Op0, m_OneUse(m_Or(m_Not(m_Value(X)), m_Constant(C2))))) { 3514 // (~X | C2) ^ C1 --> ((X & ~C2) ^ -1) ^ C1 --> (X & ~C2) ^ ~C1 3515 Value *And = Builder.CreateAnd(X, ConstantExpr::getNot(C2)); 3516 return BinaryOperator::CreateXor(And, ConstantExpr::getNot(C1)); 3517 } 3518 if (match(Op0, m_OneUse(m_And(m_Not(m_Value(X)), m_Constant(C2))))) { 3519 // (~X & C2) ^ C1 --> ((X | ~C2) ^ -1) ^ C1 --> (X | ~C2) ^ ~C1 3520 Value *Or = Builder.CreateOr(X, ConstantExpr::getNot(C2)); 3521 return BinaryOperator::CreateXor(Or, ConstantExpr::getNot(C1)); 3522 } 3523 3524 // Convert xor ([trunc] (ashr X, BW-1)), C => 3525 // select(X >s -1, C, ~C) 3526 // The ashr creates "AllZeroOrAllOne's", which then optionally inverses the 3527 // constant depending on whether this input is less than 0. 3528 const APInt *CA; 3529 if (match(Op0, m_OneUse(m_TruncOrSelf( 3530 m_AShr(m_Value(X), m_APIntAllowUndef(CA))))) && 3531 *CA == X->getType()->getScalarSizeInBits() - 1 && 3532 !match(C1, m_AllOnes())) { 3533 assert(!C1->isZeroValue() && "Unexpected xor with 0"); 3534 Value *ICmp = 3535 Builder.CreateICmpSGT(X, Constant::getAllOnesValue(X->getType())); 3536 return SelectInst::Create(ICmp, Op1, Builder.CreateNot(Op1)); 3537 } 3538 } 3539 3540 Type *Ty = I.getType(); 3541 { 3542 const APInt *RHSC; 3543 if (match(Op1, m_APInt(RHSC))) { 3544 Value *X; 3545 const APInt *C; 3546 // (C - X) ^ signmaskC --> (C + signmaskC) - X 3547 if (RHSC->isSignMask() && match(Op0, m_Sub(m_APInt(C), m_Value(X)))) 3548 return BinaryOperator::CreateSub(ConstantInt::get(Ty, *C + *RHSC), X); 3549 3550 // (X + C) ^ signmaskC --> X + (C + signmaskC) 3551 if (RHSC->isSignMask() && match(Op0, m_Add(m_Value(X), m_APInt(C)))) 3552 return BinaryOperator::CreateAdd(X, ConstantInt::get(Ty, *C + *RHSC)); 3553 3554 // (X | C) ^ RHSC --> X ^ (C ^ RHSC) iff X & C == 0 3555 if (match(Op0, m_Or(m_Value(X), m_APInt(C))) && 3556 MaskedValueIsZero(X, *C, 0, &I)) 3557 return BinaryOperator::CreateXor(X, ConstantInt::get(Ty, *C ^ *RHSC)); 3558 3559 // If RHSC is inverting the remaining bits of shifted X, 3560 // canonicalize to a 'not' before the shift to help SCEV and codegen: 3561 // (X << C) ^ RHSC --> ~X << C 3562 if (match(Op0, m_OneUse(m_Shl(m_Value(X), m_APInt(C)))) && 3563 *RHSC == APInt::getAllOnes(Ty->getScalarSizeInBits()).shl(*C)) { 3564 Value *NotX = Builder.CreateNot(X); 3565 return BinaryOperator::CreateShl(NotX, ConstantInt::get(Ty, *C)); 3566 } 3567 // (X >>u C) ^ RHSC --> ~X >>u C 3568 if (match(Op0, m_OneUse(m_LShr(m_Value(X), m_APInt(C)))) && 3569 *RHSC == APInt::getAllOnes(Ty->getScalarSizeInBits()).lshr(*C)) { 3570 Value *NotX = Builder.CreateNot(X); 3571 return BinaryOperator::CreateLShr(NotX, ConstantInt::get(Ty, *C)); 3572 } 3573 // TODO: We could handle 'ashr' here as well. That would be matching 3574 // a 'not' op and moving it before the shift. Doing that requires 3575 // preventing the inverse fold in canShiftBinOpWithConstantRHS(). 3576 } 3577 } 3578 3579 // FIXME: This should not be limited to scalar (pull into APInt match above). 3580 { 3581 Value *X; 3582 ConstantInt *C1, *C2, *C3; 3583 // ((X^C1) >> C2) ^ C3 -> (X>>C2) ^ ((C1>>C2)^C3) 3584 if (match(Op1, m_ConstantInt(C3)) && 3585 match(Op0, m_LShr(m_Xor(m_Value(X), m_ConstantInt(C1)), 3586 m_ConstantInt(C2))) && 3587 Op0->hasOneUse()) { 3588 // fold (C1 >> C2) ^ C3 3589 APInt FoldConst = C1->getValue().lshr(C2->getValue()); 3590 FoldConst ^= C3->getValue(); 3591 // Prepare the two operands. 3592 auto *Opnd0 = Builder.CreateLShr(X, C2); 3593 Opnd0->takeName(Op0); 3594 return BinaryOperator::CreateXor(Opnd0, ConstantInt::get(Ty, FoldConst)); 3595 } 3596 } 3597 3598 if (Instruction *FoldedLogic = foldBinOpIntoSelectOrPhi(I)) 3599 return FoldedLogic; 3600 3601 // Y ^ (X | Y) --> X & ~Y 3602 // Y ^ (Y | X) --> X & ~Y 3603 if (match(Op1, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op0))))) 3604 return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op0)); 3605 // (X | Y) ^ Y --> X & ~Y 3606 // (Y | X) ^ Y --> X & ~Y 3607 if (match(Op0, m_OneUse(m_c_Or(m_Value(X), m_Specific(Op1))))) 3608 return BinaryOperator::CreateAnd(X, Builder.CreateNot(Op1)); 3609 3610 // Y ^ (X & Y) --> ~X & Y 3611 // Y ^ (Y & X) --> ~X & Y 3612 if (match(Op1, m_OneUse(m_c_And(m_Value(X), m_Specific(Op0))))) 3613 return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(X)); 3614 // (X & Y) ^ Y --> ~X & Y 3615 // (Y & X) ^ Y --> ~X & Y 3616 // Canonical form is (X & C) ^ C; don't touch that. 3617 // TODO: A 'not' op is better for analysis and codegen, but demanded bits must 3618 // be fixed to prefer that (otherwise we get infinite looping). 3619 if (!match(Op1, m_Constant()) && 3620 match(Op0, m_OneUse(m_c_And(m_Value(X), m_Specific(Op1))))) 3621 return BinaryOperator::CreateAnd(Op1, Builder.CreateNot(X)); 3622 3623 Value *A, *B, *C; 3624 // (A ^ B) ^ (A | C) --> (~A & C) ^ B -- There are 4 commuted variants. 3625 if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))), 3626 m_OneUse(m_c_Or(m_Deferred(A), m_Value(C)))))) 3627 return BinaryOperator::CreateXor( 3628 Builder.CreateAnd(Builder.CreateNot(A), C), B); 3629 3630 // (A ^ B) ^ (B | C) --> (~B & C) ^ A -- There are 4 commuted variants. 3631 if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_Value(A), m_Value(B))), 3632 m_OneUse(m_c_Or(m_Deferred(B), m_Value(C)))))) 3633 return BinaryOperator::CreateXor( 3634 Builder.CreateAnd(Builder.CreateNot(B), C), A); 3635 3636 // (A & B) ^ (A ^ B) -> (A | B) 3637 if (match(Op0, m_And(m_Value(A), m_Value(B))) && 3638 match(Op1, m_c_Xor(m_Specific(A), m_Specific(B)))) 3639 return BinaryOperator::CreateOr(A, B); 3640 // (A ^ B) ^ (A & B) -> (A | B) 3641 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) && 3642 match(Op1, m_c_And(m_Specific(A), m_Specific(B)))) 3643 return BinaryOperator::CreateOr(A, B); 3644 3645 // (A & ~B) ^ ~A -> ~(A & B) 3646 // (~B & A) ^ ~A -> ~(A & B) 3647 if (match(Op0, m_c_And(m_Value(A), m_Not(m_Value(B)))) && 3648 match(Op1, m_Not(m_Specific(A)))) 3649 return BinaryOperator::CreateNot(Builder.CreateAnd(A, B)); 3650 3651 // (~A & B) ^ A --> A | B -- There are 4 commuted variants. 3652 if (match(&I, m_c_Xor(m_c_And(m_Not(m_Value(A)), m_Value(B)), m_Deferred(A)))) 3653 return BinaryOperator::CreateOr(A, B); 3654 3655 // (~A | B) ^ A --> ~(A & B) 3656 if (match(Op0, m_OneUse(m_c_Or(m_Not(m_Specific(Op1)), m_Value(B))))) 3657 return BinaryOperator::CreateNot(Builder.CreateAnd(Op1, B)); 3658 3659 // A ^ (~A | B) --> ~(A & B) 3660 if (match(Op1, m_OneUse(m_c_Or(m_Not(m_Specific(Op0)), m_Value(B))))) 3661 return BinaryOperator::CreateNot(Builder.CreateAnd(Op0, B)); 3662 3663 // (A | B) ^ (A | C) --> (B ^ C) & ~A -- There are 4 commuted variants. 3664 // TODO: Loosen one-use restriction if common operand is a constant. 3665 Value *D; 3666 if (match(Op0, m_OneUse(m_Or(m_Value(A), m_Value(B)))) && 3667 match(Op1, m_OneUse(m_Or(m_Value(C), m_Value(D))))) { 3668 if (B == C || B == D) 3669 std::swap(A, B); 3670 if (A == C) 3671 std::swap(C, D); 3672 if (A == D) { 3673 Value *NotA = Builder.CreateNot(A); 3674 return BinaryOperator::CreateAnd(Builder.CreateXor(B, C), NotA); 3675 } 3676 } 3677 3678 if (auto *LHS = dyn_cast<ICmpInst>(I.getOperand(0))) 3679 if (auto *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) 3680 if (Value *V = foldXorOfICmps(LHS, RHS, I)) 3681 return replaceInstUsesWith(I, V); 3682 3683 if (Instruction *CastedXor = foldCastedBitwiseLogic(I)) 3684 return CastedXor; 3685 3686 if (Instruction *Abs = canonicalizeAbs(I, Builder)) 3687 return Abs; 3688 3689 // Otherwise, if all else failed, try to hoist the xor-by-constant: 3690 // (X ^ C) ^ Y --> (X ^ Y) ^ C 3691 // Just like we do in other places, we completely avoid the fold 3692 // for constantexprs, at least to avoid endless combine loop. 3693 if (match(&I, m_c_Xor(m_OneUse(m_Xor(m_CombineAnd(m_Value(X), 3694 m_Unless(m_ConstantExpr())), 3695 m_ImmConstant(C1))), 3696 m_Value(Y)))) 3697 return BinaryOperator::CreateXor(Builder.CreateXor(X, Y), C1); 3698 3699 return nullptr; 3700 } 3701