1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===// 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 routines for folding instructions into simpler forms 10 // that do not require creating new instructions. This does constant folding 11 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either 12 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value 13 // ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been 14 // simplified: This is usually true and assuming it simplifies the logic (if 15 // they have not been simplified then results are correct but maybe suboptimal). 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/Analysis/InstructionSimplify.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/Analysis/AssumptionCache.h" 25 #include "llvm/Analysis/CaptureTracking.h" 26 #include "llvm/Analysis/CmpInstAnalysis.h" 27 #include "llvm/Analysis/ConstantFolding.h" 28 #include "llvm/Analysis/LoopAnalysisManager.h" 29 #include "llvm/Analysis/MemoryBuiltins.h" 30 #include "llvm/Analysis/OverflowInstAnalysis.h" 31 #include "llvm/Analysis/ValueTracking.h" 32 #include "llvm/Analysis/VectorUtils.h" 33 #include "llvm/IR/ConstantRange.h" 34 #include "llvm/IR/DataLayout.h" 35 #include "llvm/IR/Dominators.h" 36 #include "llvm/IR/GetElementPtrTypeIterator.h" 37 #include "llvm/IR/GlobalAlias.h" 38 #include "llvm/IR/InstrTypes.h" 39 #include "llvm/IR/Instructions.h" 40 #include "llvm/IR/Operator.h" 41 #include "llvm/IR/PatternMatch.h" 42 #include "llvm/IR/ValueHandle.h" 43 #include "llvm/Support/KnownBits.h" 44 #include <algorithm> 45 using namespace llvm; 46 using namespace llvm::PatternMatch; 47 48 #define DEBUG_TYPE "instsimplify" 49 50 enum { RecursionLimit = 3 }; 51 52 STATISTIC(NumExpand, "Number of expansions"); 53 STATISTIC(NumReassoc, "Number of reassociations"); 54 55 static Value *SimplifyAndInst(Value *, Value *, const SimplifyQuery &, unsigned); 56 static Value *simplifyUnOp(unsigned, Value *, const SimplifyQuery &, unsigned); 57 static Value *simplifyFPUnOp(unsigned, Value *, const FastMathFlags &, 58 const SimplifyQuery &, unsigned); 59 static Value *SimplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &, 60 unsigned); 61 static Value *SimplifyBinOp(unsigned, Value *, Value *, const FastMathFlags &, 62 const SimplifyQuery &, unsigned); 63 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &, 64 unsigned); 65 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, 66 const SimplifyQuery &Q, unsigned MaxRecurse); 67 static Value *SimplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned); 68 static Value *SimplifyXorInst(Value *, Value *, const SimplifyQuery &, unsigned); 69 static Value *SimplifyCastInst(unsigned, Value *, Type *, 70 const SimplifyQuery &, unsigned); 71 static Value *SimplifyGEPInst(Type *, ArrayRef<Value *>, const SimplifyQuery &, 72 unsigned); 73 static Value *SimplifySelectInst(Value *, Value *, Value *, 74 const SimplifyQuery &, unsigned); 75 76 static Value *foldSelectWithBinaryOp(Value *Cond, Value *TrueVal, 77 Value *FalseVal) { 78 BinaryOperator::BinaryOps BinOpCode; 79 if (auto *BO = dyn_cast<BinaryOperator>(Cond)) 80 BinOpCode = BO->getOpcode(); 81 else 82 return nullptr; 83 84 CmpInst::Predicate ExpectedPred, Pred1, Pred2; 85 if (BinOpCode == BinaryOperator::Or) { 86 ExpectedPred = ICmpInst::ICMP_NE; 87 } else if (BinOpCode == BinaryOperator::And) { 88 ExpectedPred = ICmpInst::ICMP_EQ; 89 } else 90 return nullptr; 91 92 // %A = icmp eq %TV, %FV 93 // %B = icmp eq %X, %Y (and one of these is a select operand) 94 // %C = and %A, %B 95 // %D = select %C, %TV, %FV 96 // --> 97 // %FV 98 99 // %A = icmp ne %TV, %FV 100 // %B = icmp ne %X, %Y (and one of these is a select operand) 101 // %C = or %A, %B 102 // %D = select %C, %TV, %FV 103 // --> 104 // %TV 105 Value *X, *Y; 106 if (!match(Cond, m_c_BinOp(m_c_ICmp(Pred1, m_Specific(TrueVal), 107 m_Specific(FalseVal)), 108 m_ICmp(Pred2, m_Value(X), m_Value(Y)))) || 109 Pred1 != Pred2 || Pred1 != ExpectedPred) 110 return nullptr; 111 112 if (X == TrueVal || X == FalseVal || Y == TrueVal || Y == FalseVal) 113 return BinOpCode == BinaryOperator::Or ? TrueVal : FalseVal; 114 115 return nullptr; 116 } 117 118 /// For a boolean type or a vector of boolean type, return false or a vector 119 /// with every element false. 120 static Constant *getFalse(Type *Ty) { 121 return ConstantInt::getFalse(Ty); 122 } 123 124 /// For a boolean type or a vector of boolean type, return true or a vector 125 /// with every element true. 126 static Constant *getTrue(Type *Ty) { 127 return ConstantInt::getTrue(Ty); 128 } 129 130 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"? 131 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS, 132 Value *RHS) { 133 CmpInst *Cmp = dyn_cast<CmpInst>(V); 134 if (!Cmp) 135 return false; 136 CmpInst::Predicate CPred = Cmp->getPredicate(); 137 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1); 138 if (CPred == Pred && CLHS == LHS && CRHS == RHS) 139 return true; 140 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS && 141 CRHS == LHS; 142 } 143 144 /// Simplify comparison with true or false branch of select: 145 /// %sel = select i1 %cond, i32 %tv, i32 %fv 146 /// %cmp = icmp sle i32 %sel, %rhs 147 /// Compose new comparison by substituting %sel with either %tv or %fv 148 /// and see if it simplifies. 149 static Value *simplifyCmpSelCase(CmpInst::Predicate Pred, Value *LHS, 150 Value *RHS, Value *Cond, 151 const SimplifyQuery &Q, unsigned MaxRecurse, 152 Constant *TrueOrFalse) { 153 Value *SimplifiedCmp = SimplifyCmpInst(Pred, LHS, RHS, Q, MaxRecurse); 154 if (SimplifiedCmp == Cond) { 155 // %cmp simplified to the select condition (%cond). 156 return TrueOrFalse; 157 } else if (!SimplifiedCmp && isSameCompare(Cond, Pred, LHS, RHS)) { 158 // It didn't simplify. However, if composed comparison is equivalent 159 // to the select condition (%cond) then we can replace it. 160 return TrueOrFalse; 161 } 162 return SimplifiedCmp; 163 } 164 165 /// Simplify comparison with true branch of select 166 static Value *simplifyCmpSelTrueCase(CmpInst::Predicate Pred, Value *LHS, 167 Value *RHS, Value *Cond, 168 const SimplifyQuery &Q, 169 unsigned MaxRecurse) { 170 return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse, 171 getTrue(Cond->getType())); 172 } 173 174 /// Simplify comparison with false branch of select 175 static Value *simplifyCmpSelFalseCase(CmpInst::Predicate Pred, Value *LHS, 176 Value *RHS, Value *Cond, 177 const SimplifyQuery &Q, 178 unsigned MaxRecurse) { 179 return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse, 180 getFalse(Cond->getType())); 181 } 182 183 /// We know comparison with both branches of select can be simplified, but they 184 /// are not equal. This routine handles some logical simplifications. 185 static Value *handleOtherCmpSelSimplifications(Value *TCmp, Value *FCmp, 186 Value *Cond, 187 const SimplifyQuery &Q, 188 unsigned MaxRecurse) { 189 // If the false value simplified to false, then the result of the compare 190 // is equal to "Cond && TCmp". This also catches the case when the false 191 // value simplified to false and the true value to true, returning "Cond". 192 // Folding select to and/or isn't poison-safe in general; impliesPoison 193 // checks whether folding it does not convert a well-defined value into 194 // poison. 195 if (match(FCmp, m_Zero()) && impliesPoison(TCmp, Cond)) 196 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse)) 197 return V; 198 // If the true value simplified to true, then the result of the compare 199 // is equal to "Cond || FCmp". 200 if (match(TCmp, m_One()) && impliesPoison(FCmp, Cond)) 201 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse)) 202 return V; 203 // Finally, if the false value simplified to true and the true value to 204 // false, then the result of the compare is equal to "!Cond". 205 if (match(FCmp, m_One()) && match(TCmp, m_Zero())) 206 if (Value *V = SimplifyXorInst( 207 Cond, Constant::getAllOnesValue(Cond->getType()), Q, MaxRecurse)) 208 return V; 209 return nullptr; 210 } 211 212 /// Does the given value dominate the specified phi node? 213 static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) { 214 Instruction *I = dyn_cast<Instruction>(V); 215 if (!I) 216 // Arguments and constants dominate all instructions. 217 return true; 218 219 // If we are processing instructions (and/or basic blocks) that have not been 220 // fully added to a function, the parent nodes may still be null. Simply 221 // return the conservative answer in these cases. 222 if (!I->getParent() || !P->getParent() || !I->getFunction()) 223 return false; 224 225 // If we have a DominatorTree then do a precise test. 226 if (DT) 227 return DT->dominates(I, P); 228 229 // Otherwise, if the instruction is in the entry block and is not an invoke, 230 // then it obviously dominates all phi nodes. 231 if (I->getParent()->isEntryBlock() && !isa<InvokeInst>(I) && 232 !isa<CallBrInst>(I)) 233 return true; 234 235 return false; 236 } 237 238 /// Try to simplify a binary operator of form "V op OtherOp" where V is 239 /// "(B0 opex B1)" by distributing 'op' across 'opex' as 240 /// "(B0 op OtherOp) opex (B1 op OtherOp)". 241 static Value *expandBinOp(Instruction::BinaryOps Opcode, Value *V, 242 Value *OtherOp, Instruction::BinaryOps OpcodeToExpand, 243 const SimplifyQuery &Q, unsigned MaxRecurse) { 244 auto *B = dyn_cast<BinaryOperator>(V); 245 if (!B || B->getOpcode() != OpcodeToExpand) 246 return nullptr; 247 Value *B0 = B->getOperand(0), *B1 = B->getOperand(1); 248 Value *L = SimplifyBinOp(Opcode, B0, OtherOp, Q.getWithoutUndef(), 249 MaxRecurse); 250 if (!L) 251 return nullptr; 252 Value *R = SimplifyBinOp(Opcode, B1, OtherOp, Q.getWithoutUndef(), 253 MaxRecurse); 254 if (!R) 255 return nullptr; 256 257 // Does the expanded pair of binops simplify to the existing binop? 258 if ((L == B0 && R == B1) || 259 (Instruction::isCommutative(OpcodeToExpand) && L == B1 && R == B0)) { 260 ++NumExpand; 261 return B; 262 } 263 264 // Otherwise, return "L op' R" if it simplifies. 265 Value *S = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse); 266 if (!S) 267 return nullptr; 268 269 ++NumExpand; 270 return S; 271 } 272 273 /// Try to simplify binops of form "A op (B op' C)" or the commuted variant by 274 /// distributing op over op'. 275 static Value *expandCommutativeBinOp(Instruction::BinaryOps Opcode, 276 Value *L, Value *R, 277 Instruction::BinaryOps OpcodeToExpand, 278 const SimplifyQuery &Q, 279 unsigned MaxRecurse) { 280 // Recursion is always used, so bail out at once if we already hit the limit. 281 if (!MaxRecurse--) 282 return nullptr; 283 284 if (Value *V = expandBinOp(Opcode, L, R, OpcodeToExpand, Q, MaxRecurse)) 285 return V; 286 if (Value *V = expandBinOp(Opcode, R, L, OpcodeToExpand, Q, MaxRecurse)) 287 return V; 288 return nullptr; 289 } 290 291 /// Generic simplifications for associative binary operations. 292 /// Returns the simpler value, or null if none was found. 293 static Value *SimplifyAssociativeBinOp(Instruction::BinaryOps Opcode, 294 Value *LHS, Value *RHS, 295 const SimplifyQuery &Q, 296 unsigned MaxRecurse) { 297 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!"); 298 299 // Recursion is always used, so bail out at once if we already hit the limit. 300 if (!MaxRecurse--) 301 return nullptr; 302 303 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS); 304 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS); 305 306 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely. 307 if (Op0 && Op0->getOpcode() == Opcode) { 308 Value *A = Op0->getOperand(0); 309 Value *B = Op0->getOperand(1); 310 Value *C = RHS; 311 312 // Does "B op C" simplify? 313 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) { 314 // It does! Return "A op V" if it simplifies or is already available. 315 // If V equals B then "A op V" is just the LHS. 316 if (V == B) return LHS; 317 // Otherwise return "A op V" if it simplifies. 318 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) { 319 ++NumReassoc; 320 return W; 321 } 322 } 323 } 324 325 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely. 326 if (Op1 && Op1->getOpcode() == Opcode) { 327 Value *A = LHS; 328 Value *B = Op1->getOperand(0); 329 Value *C = Op1->getOperand(1); 330 331 // Does "A op B" simplify? 332 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) { 333 // It does! Return "V op C" if it simplifies or is already available. 334 // If V equals B then "V op C" is just the RHS. 335 if (V == B) return RHS; 336 // Otherwise return "V op C" if it simplifies. 337 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) { 338 ++NumReassoc; 339 return W; 340 } 341 } 342 } 343 344 // The remaining transforms require commutativity as well as associativity. 345 if (!Instruction::isCommutative(Opcode)) 346 return nullptr; 347 348 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely. 349 if (Op0 && Op0->getOpcode() == Opcode) { 350 Value *A = Op0->getOperand(0); 351 Value *B = Op0->getOperand(1); 352 Value *C = RHS; 353 354 // Does "C op A" simplify? 355 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) { 356 // It does! Return "V op B" if it simplifies or is already available. 357 // If V equals A then "V op B" is just the LHS. 358 if (V == A) return LHS; 359 // Otherwise return "V op B" if it simplifies. 360 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) { 361 ++NumReassoc; 362 return W; 363 } 364 } 365 } 366 367 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely. 368 if (Op1 && Op1->getOpcode() == Opcode) { 369 Value *A = LHS; 370 Value *B = Op1->getOperand(0); 371 Value *C = Op1->getOperand(1); 372 373 // Does "C op A" simplify? 374 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) { 375 // It does! Return "B op V" if it simplifies or is already available. 376 // If V equals C then "B op V" is just the RHS. 377 if (V == C) return RHS; 378 // Otherwise return "B op V" if it simplifies. 379 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) { 380 ++NumReassoc; 381 return W; 382 } 383 } 384 } 385 386 return nullptr; 387 } 388 389 /// In the case of a binary operation with a select instruction as an operand, 390 /// try to simplify the binop by seeing whether evaluating it on both branches 391 /// of the select results in the same value. Returns the common value if so, 392 /// otherwise returns null. 393 static Value *ThreadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS, 394 Value *RHS, const SimplifyQuery &Q, 395 unsigned MaxRecurse) { 396 // Recursion is always used, so bail out at once if we already hit the limit. 397 if (!MaxRecurse--) 398 return nullptr; 399 400 SelectInst *SI; 401 if (isa<SelectInst>(LHS)) { 402 SI = cast<SelectInst>(LHS); 403 } else { 404 assert(isa<SelectInst>(RHS) && "No select instruction operand!"); 405 SI = cast<SelectInst>(RHS); 406 } 407 408 // Evaluate the BinOp on the true and false branches of the select. 409 Value *TV; 410 Value *FV; 411 if (SI == LHS) { 412 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse); 413 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse); 414 } else { 415 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse); 416 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse); 417 } 418 419 // If they simplified to the same value, then return the common value. 420 // If they both failed to simplify then return null. 421 if (TV == FV) 422 return TV; 423 424 // If one branch simplified to undef, return the other one. 425 if (TV && Q.isUndefValue(TV)) 426 return FV; 427 if (FV && Q.isUndefValue(FV)) 428 return TV; 429 430 // If applying the operation did not change the true and false select values, 431 // then the result of the binop is the select itself. 432 if (TV == SI->getTrueValue() && FV == SI->getFalseValue()) 433 return SI; 434 435 // If one branch simplified and the other did not, and the simplified 436 // value is equal to the unsimplified one, return the simplified value. 437 // For example, select (cond, X, X & Z) & Z -> X & Z. 438 if ((FV && !TV) || (TV && !FV)) { 439 // Check that the simplified value has the form "X op Y" where "op" is the 440 // same as the original operation. 441 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV); 442 if (Simplified && Simplified->getOpcode() == unsigned(Opcode)) { 443 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS". 444 // We already know that "op" is the same as for the simplified value. See 445 // if the operands match too. If so, return the simplified value. 446 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue(); 447 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS; 448 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch; 449 if (Simplified->getOperand(0) == UnsimplifiedLHS && 450 Simplified->getOperand(1) == UnsimplifiedRHS) 451 return Simplified; 452 if (Simplified->isCommutative() && 453 Simplified->getOperand(1) == UnsimplifiedLHS && 454 Simplified->getOperand(0) == UnsimplifiedRHS) 455 return Simplified; 456 } 457 } 458 459 return nullptr; 460 } 461 462 /// In the case of a comparison with a select instruction, try to simplify the 463 /// comparison by seeing whether both branches of the select result in the same 464 /// value. Returns the common value if so, otherwise returns null. 465 /// For example, if we have: 466 /// %tmp = select i1 %cmp, i32 1, i32 2 467 /// %cmp1 = icmp sle i32 %tmp, 3 468 /// We can simplify %cmp1 to true, because both branches of select are 469 /// less than 3. We compose new comparison by substituting %tmp with both 470 /// branches of select and see if it can be simplified. 471 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS, 472 Value *RHS, const SimplifyQuery &Q, 473 unsigned MaxRecurse) { 474 // Recursion is always used, so bail out at once if we already hit the limit. 475 if (!MaxRecurse--) 476 return nullptr; 477 478 // Make sure the select is on the LHS. 479 if (!isa<SelectInst>(LHS)) { 480 std::swap(LHS, RHS); 481 Pred = CmpInst::getSwappedPredicate(Pred); 482 } 483 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!"); 484 SelectInst *SI = cast<SelectInst>(LHS); 485 Value *Cond = SI->getCondition(); 486 Value *TV = SI->getTrueValue(); 487 Value *FV = SI->getFalseValue(); 488 489 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it. 490 // Does "cmp TV, RHS" simplify? 491 Value *TCmp = simplifyCmpSelTrueCase(Pred, TV, RHS, Cond, Q, MaxRecurse); 492 if (!TCmp) 493 return nullptr; 494 495 // Does "cmp FV, RHS" simplify? 496 Value *FCmp = simplifyCmpSelFalseCase(Pred, FV, RHS, Cond, Q, MaxRecurse); 497 if (!FCmp) 498 return nullptr; 499 500 // If both sides simplified to the same value, then use it as the result of 501 // the original comparison. 502 if (TCmp == FCmp) 503 return TCmp; 504 505 // The remaining cases only make sense if the select condition has the same 506 // type as the result of the comparison, so bail out if this is not so. 507 if (Cond->getType()->isVectorTy() == RHS->getType()->isVectorTy()) 508 return handleOtherCmpSelSimplifications(TCmp, FCmp, Cond, Q, MaxRecurse); 509 510 return nullptr; 511 } 512 513 /// In the case of a binary operation with an operand that is a PHI instruction, 514 /// try to simplify the binop by seeing whether evaluating it on the incoming 515 /// phi values yields the same result for every value. If so returns the common 516 /// value, otherwise returns null. 517 static Value *ThreadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS, 518 Value *RHS, const SimplifyQuery &Q, 519 unsigned MaxRecurse) { 520 // Recursion is always used, so bail out at once if we already hit the limit. 521 if (!MaxRecurse--) 522 return nullptr; 523 524 PHINode *PI; 525 if (isa<PHINode>(LHS)) { 526 PI = cast<PHINode>(LHS); 527 // Bail out if RHS and the phi may be mutually interdependent due to a loop. 528 if (!valueDominatesPHI(RHS, PI, Q.DT)) 529 return nullptr; 530 } else { 531 assert(isa<PHINode>(RHS) && "No PHI instruction operand!"); 532 PI = cast<PHINode>(RHS); 533 // Bail out if LHS and the phi may be mutually interdependent due to a loop. 534 if (!valueDominatesPHI(LHS, PI, Q.DT)) 535 return nullptr; 536 } 537 538 // Evaluate the BinOp on the incoming phi values. 539 Value *CommonValue = nullptr; 540 for (Value *Incoming : PI->incoming_values()) { 541 // If the incoming value is the phi node itself, it can safely be skipped. 542 if (Incoming == PI) continue; 543 Value *V = PI == LHS ? 544 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) : 545 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse); 546 // If the operation failed to simplify, or simplified to a different value 547 // to previously, then give up. 548 if (!V || (CommonValue && V != CommonValue)) 549 return nullptr; 550 CommonValue = V; 551 } 552 553 return CommonValue; 554 } 555 556 /// In the case of a comparison with a PHI instruction, try to simplify the 557 /// comparison by seeing whether comparing with all of the incoming phi values 558 /// yields the same result every time. If so returns the common result, 559 /// otherwise returns null. 560 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS, 561 const SimplifyQuery &Q, unsigned MaxRecurse) { 562 // Recursion is always used, so bail out at once if we already hit the limit. 563 if (!MaxRecurse--) 564 return nullptr; 565 566 // Make sure the phi is on the LHS. 567 if (!isa<PHINode>(LHS)) { 568 std::swap(LHS, RHS); 569 Pred = CmpInst::getSwappedPredicate(Pred); 570 } 571 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!"); 572 PHINode *PI = cast<PHINode>(LHS); 573 574 // Bail out if RHS and the phi may be mutually interdependent due to a loop. 575 if (!valueDominatesPHI(RHS, PI, Q.DT)) 576 return nullptr; 577 578 // Evaluate the BinOp on the incoming phi values. 579 Value *CommonValue = nullptr; 580 for (unsigned u = 0, e = PI->getNumIncomingValues(); u < e; ++u) { 581 Value *Incoming = PI->getIncomingValue(u); 582 Instruction *InTI = PI->getIncomingBlock(u)->getTerminator(); 583 // If the incoming value is the phi node itself, it can safely be skipped. 584 if (Incoming == PI) continue; 585 // Change the context instruction to the "edge" that flows into the phi. 586 // This is important because that is where incoming is actually "evaluated" 587 // even though it is used later somewhere else. 588 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q.getWithInstruction(InTI), 589 MaxRecurse); 590 // If the operation failed to simplify, or simplified to a different value 591 // to previously, then give up. 592 if (!V || (CommonValue && V != CommonValue)) 593 return nullptr; 594 CommonValue = V; 595 } 596 597 return CommonValue; 598 } 599 600 static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode, 601 Value *&Op0, Value *&Op1, 602 const SimplifyQuery &Q) { 603 if (auto *CLHS = dyn_cast<Constant>(Op0)) { 604 if (auto *CRHS = dyn_cast<Constant>(Op1)) 605 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL); 606 607 // Canonicalize the constant to the RHS if this is a commutative operation. 608 if (Instruction::isCommutative(Opcode)) 609 std::swap(Op0, Op1); 610 } 611 return nullptr; 612 } 613 614 /// Given operands for an Add, see if we can fold the result. 615 /// If not, this returns null. 616 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW, 617 const SimplifyQuery &Q, unsigned MaxRecurse) { 618 if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q)) 619 return C; 620 621 // X + undef -> undef 622 if (Q.isUndefValue(Op1)) 623 return Op1; 624 625 // X + 0 -> X 626 if (match(Op1, m_Zero())) 627 return Op0; 628 629 // If two operands are negative, return 0. 630 if (isKnownNegation(Op0, Op1)) 631 return Constant::getNullValue(Op0->getType()); 632 633 // X + (Y - X) -> Y 634 // (Y - X) + X -> Y 635 // Eg: X + -X -> 0 636 Value *Y = nullptr; 637 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) || 638 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1)))) 639 return Y; 640 641 // X + ~X -> -1 since ~X = -X-1 642 Type *Ty = Op0->getType(); 643 if (match(Op0, m_Not(m_Specific(Op1))) || 644 match(Op1, m_Not(m_Specific(Op0)))) 645 return Constant::getAllOnesValue(Ty); 646 647 // add nsw/nuw (xor Y, signmask), signmask --> Y 648 // The no-wrapping add guarantees that the top bit will be set by the add. 649 // Therefore, the xor must be clearing the already set sign bit of Y. 650 if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) && 651 match(Op0, m_Xor(m_Value(Y), m_SignMask()))) 652 return Y; 653 654 // add nuw %x, -1 -> -1, because %x can only be 0. 655 if (IsNUW && match(Op1, m_AllOnes())) 656 return Op1; // Which is -1. 657 658 /// i1 add -> xor. 659 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1)) 660 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1)) 661 return V; 662 663 // Try some generic simplifications for associative operations. 664 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q, 665 MaxRecurse)) 666 return V; 667 668 // Threading Add over selects and phi nodes is pointless, so don't bother. 669 // Threading over the select in "A + select(cond, B, C)" means evaluating 670 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and 671 // only if B and C are equal. If B and C are equal then (since we assume 672 // that operands have already been simplified) "select(cond, B, C)" should 673 // have been simplified to the common value of B and C already. Analysing 674 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly 675 // for threading over phi nodes. 676 677 return nullptr; 678 } 679 680 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW, 681 const SimplifyQuery &Query) { 682 return ::SimplifyAddInst(Op0, Op1, IsNSW, IsNUW, Query, RecursionLimit); 683 } 684 685 /// Compute the base pointer and cumulative constant offsets for V. 686 /// 687 /// This strips all constant offsets off of V, leaving it the base pointer, and 688 /// accumulates the total constant offset applied in the returned constant. It 689 /// returns 0 if V is not a pointer, and returns the constant '0' if there are 690 /// no constant offsets applied. 691 /// 692 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't 693 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc. 694 /// folding. 695 static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V, 696 bool AllowNonInbounds = false) { 697 assert(V->getType()->isPtrOrPtrVectorTy()); 698 699 Type *IntIdxTy = DL.getIndexType(V->getType())->getScalarType(); 700 APInt Offset = APInt::getNullValue(IntIdxTy->getIntegerBitWidth()); 701 702 V = V->stripAndAccumulateConstantOffsets(DL, Offset, AllowNonInbounds); 703 // As that strip may trace through `addrspacecast`, need to sext or trunc 704 // the offset calculated. 705 IntIdxTy = DL.getIndexType(V->getType())->getScalarType(); 706 Offset = Offset.sextOrTrunc(IntIdxTy->getIntegerBitWidth()); 707 708 Constant *OffsetIntPtr = ConstantInt::get(IntIdxTy, Offset); 709 if (VectorType *VecTy = dyn_cast<VectorType>(V->getType())) 710 return ConstantVector::getSplat(VecTy->getElementCount(), OffsetIntPtr); 711 return OffsetIntPtr; 712 } 713 714 /// Compute the constant difference between two pointer values. 715 /// If the difference is not a constant, returns zero. 716 static Constant *computePointerDifference(const DataLayout &DL, Value *LHS, 717 Value *RHS) { 718 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS); 719 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS); 720 721 // If LHS and RHS are not related via constant offsets to the same base 722 // value, there is nothing we can do here. 723 if (LHS != RHS) 724 return nullptr; 725 726 // Otherwise, the difference of LHS - RHS can be computed as: 727 // LHS - RHS 728 // = (LHSOffset + Base) - (RHSOffset + Base) 729 // = LHSOffset - RHSOffset 730 return ConstantExpr::getSub(LHSOffset, RHSOffset); 731 } 732 733 /// Given operands for a Sub, see if we can fold the result. 734 /// If not, this returns null. 735 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 736 const SimplifyQuery &Q, unsigned MaxRecurse) { 737 if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q)) 738 return C; 739 740 // X - poison -> poison 741 // poison - X -> poison 742 if (isa<PoisonValue>(Op0) || isa<PoisonValue>(Op1)) 743 return PoisonValue::get(Op0->getType()); 744 745 // X - undef -> undef 746 // undef - X -> undef 747 if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) 748 return UndefValue::get(Op0->getType()); 749 750 // X - 0 -> X 751 if (match(Op1, m_Zero())) 752 return Op0; 753 754 // X - X -> 0 755 if (Op0 == Op1) 756 return Constant::getNullValue(Op0->getType()); 757 758 // Is this a negation? 759 if (match(Op0, m_Zero())) { 760 // 0 - X -> 0 if the sub is NUW. 761 if (isNUW) 762 return Constant::getNullValue(Op0->getType()); 763 764 KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 765 if (Known.Zero.isMaxSignedValue()) { 766 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then 767 // Op1 must be 0 because negating the minimum signed value is undefined. 768 if (isNSW) 769 return Constant::getNullValue(Op0->getType()); 770 771 // 0 - X -> X if X is 0 or the minimum signed value. 772 return Op1; 773 } 774 } 775 776 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies. 777 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X 778 Value *X = nullptr, *Y = nullptr, *Z = Op1; 779 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z 780 // See if "V === Y - Z" simplifies. 781 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1)) 782 // It does! Now see if "X + V" simplifies. 783 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) { 784 // It does, we successfully reassociated! 785 ++NumReassoc; 786 return W; 787 } 788 // See if "V === X - Z" simplifies. 789 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1)) 790 // It does! Now see if "Y + V" simplifies. 791 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) { 792 // It does, we successfully reassociated! 793 ++NumReassoc; 794 return W; 795 } 796 } 797 798 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies. 799 // For example, X - (X + 1) -> -1 800 X = Op0; 801 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z) 802 // See if "V === X - Y" simplifies. 803 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1)) 804 // It does! Now see if "V - Z" simplifies. 805 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) { 806 // It does, we successfully reassociated! 807 ++NumReassoc; 808 return W; 809 } 810 // See if "V === X - Z" simplifies. 811 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1)) 812 // It does! Now see if "V - Y" simplifies. 813 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) { 814 // It does, we successfully reassociated! 815 ++NumReassoc; 816 return W; 817 } 818 } 819 820 // Z - (X - Y) -> (Z - X) + Y if everything simplifies. 821 // For example, X - (X - Y) -> Y. 822 Z = Op0; 823 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y) 824 // See if "V === Z - X" simplifies. 825 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1)) 826 // It does! Now see if "V + Y" simplifies. 827 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) { 828 // It does, we successfully reassociated! 829 ++NumReassoc; 830 return W; 831 } 832 833 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies. 834 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) && 835 match(Op1, m_Trunc(m_Value(Y)))) 836 if (X->getType() == Y->getType()) 837 // See if "V === X - Y" simplifies. 838 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1)) 839 // It does! Now see if "trunc V" simplifies. 840 if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(), 841 Q, MaxRecurse - 1)) 842 // It does, return the simplified "trunc V". 843 return W; 844 845 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...). 846 if (match(Op0, m_PtrToInt(m_Value(X))) && 847 match(Op1, m_PtrToInt(m_Value(Y)))) 848 if (Constant *Result = computePointerDifference(Q.DL, X, Y)) 849 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true); 850 851 // i1 sub -> xor. 852 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1)) 853 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1)) 854 return V; 855 856 // Threading Sub over selects and phi nodes is pointless, so don't bother. 857 // Threading over the select in "A - select(cond, B, C)" means evaluating 858 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and 859 // only if B and C are equal. If B and C are equal then (since we assume 860 // that operands have already been simplified) "select(cond, B, C)" should 861 // have been simplified to the common value of B and C already. Analysing 862 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly 863 // for threading over phi nodes. 864 865 return nullptr; 866 } 867 868 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 869 const SimplifyQuery &Q) { 870 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit); 871 } 872 873 /// Given operands for a Mul, see if we can fold the result. 874 /// If not, this returns null. 875 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 876 unsigned MaxRecurse) { 877 if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q)) 878 return C; 879 880 // X * poison -> poison 881 if (isa<PoisonValue>(Op1)) 882 return Op1; 883 884 // X * undef -> 0 885 // X * 0 -> 0 886 if (Q.isUndefValue(Op1) || match(Op1, m_Zero())) 887 return Constant::getNullValue(Op0->getType()); 888 889 // X * 1 -> X 890 if (match(Op1, m_One())) 891 return Op0; 892 893 // (X / Y) * Y -> X if the division is exact. 894 Value *X = nullptr; 895 if (Q.IIQ.UseInstrInfo && 896 (match(Op0, 897 m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y 898 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))) // Y * (X / Y) 899 return X; 900 901 // i1 mul -> and. 902 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1)) 903 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1)) 904 return V; 905 906 // Try some generic simplifications for associative operations. 907 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q, 908 MaxRecurse)) 909 return V; 910 911 // Mul distributes over Add. Try some generic simplifications based on this. 912 if (Value *V = expandCommutativeBinOp(Instruction::Mul, Op0, Op1, 913 Instruction::Add, Q, MaxRecurse)) 914 return V; 915 916 // If the operation is with the result of a select instruction, check whether 917 // operating on either branch of the select always yields the same value. 918 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 919 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q, 920 MaxRecurse)) 921 return V; 922 923 // If the operation is with the result of a phi instruction, check whether 924 // operating on all incoming values of the phi always yields the same value. 925 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 926 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q, 927 MaxRecurse)) 928 return V; 929 930 return nullptr; 931 } 932 933 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 934 return ::SimplifyMulInst(Op0, Op1, Q, RecursionLimit); 935 } 936 937 /// Check for common or similar folds of integer division or integer remainder. 938 /// This applies to all 4 opcodes (sdiv/udiv/srem/urem). 939 static Value *simplifyDivRem(Instruction::BinaryOps Opcode, Value *Op0, 940 Value *Op1, const SimplifyQuery &Q) { 941 bool IsDiv = (Opcode == Instruction::SDiv || Opcode == Instruction::UDiv); 942 bool IsSigned = (Opcode == Instruction::SDiv || Opcode == Instruction::SRem); 943 944 Type *Ty = Op0->getType(); 945 946 // X / undef -> poison 947 // X % undef -> poison 948 if (Q.isUndefValue(Op1)) 949 return PoisonValue::get(Ty); 950 951 // X / 0 -> poison 952 // X % 0 -> poison 953 // We don't need to preserve faults! 954 if (match(Op1, m_Zero())) 955 return PoisonValue::get(Ty); 956 957 // If any element of a constant divisor fixed width vector is zero or undef 958 // the behavior is undefined and we can fold the whole op to poison. 959 auto *Op1C = dyn_cast<Constant>(Op1); 960 auto *VTy = dyn_cast<FixedVectorType>(Ty); 961 if (Op1C && VTy) { 962 unsigned NumElts = VTy->getNumElements(); 963 for (unsigned i = 0; i != NumElts; ++i) { 964 Constant *Elt = Op1C->getAggregateElement(i); 965 if (Elt && (Elt->isNullValue() || Q.isUndefValue(Elt))) 966 return PoisonValue::get(Ty); 967 } 968 } 969 970 // poison / X -> poison 971 // poison % X -> poison 972 if (isa<PoisonValue>(Op0)) 973 return Op0; 974 975 // undef / X -> 0 976 // undef % X -> 0 977 if (Q.isUndefValue(Op0)) 978 return Constant::getNullValue(Ty); 979 980 // 0 / X -> 0 981 // 0 % X -> 0 982 if (match(Op0, m_Zero())) 983 return Constant::getNullValue(Op0->getType()); 984 985 // X / X -> 1 986 // X % X -> 0 987 if (Op0 == Op1) 988 return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty); 989 990 // X / 1 -> X 991 // X % 1 -> 0 992 // If this is a boolean op (single-bit element type), we can't have 993 // division-by-zero or remainder-by-zero, so assume the divisor is 1. 994 // Similarly, if we're zero-extending a boolean divisor, then assume it's a 1. 995 Value *X; 996 if (match(Op1, m_One()) || Ty->isIntOrIntVectorTy(1) || 997 (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))) 998 return IsDiv ? Op0 : Constant::getNullValue(Ty); 999 1000 // If X * Y does not overflow, then: 1001 // X * Y / Y -> X 1002 // X * Y % Y -> 0 1003 if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) { 1004 auto *Mul = cast<OverflowingBinaryOperator>(Op0); 1005 // The multiplication can't overflow if it is defined not to, or if 1006 // X == A / Y for some A. 1007 if ((IsSigned && Q.IIQ.hasNoSignedWrap(Mul)) || 1008 (!IsSigned && Q.IIQ.hasNoUnsignedWrap(Mul)) || 1009 (IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) || 1010 (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1))))) { 1011 return IsDiv ? X : Constant::getNullValue(Op0->getType()); 1012 } 1013 } 1014 1015 return nullptr; 1016 } 1017 1018 /// Given a predicate and two operands, return true if the comparison is true. 1019 /// This is a helper for div/rem simplification where we return some other value 1020 /// when we can prove a relationship between the operands. 1021 static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS, 1022 const SimplifyQuery &Q, unsigned MaxRecurse) { 1023 Value *V = SimplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse); 1024 Constant *C = dyn_cast_or_null<Constant>(V); 1025 return (C && C->isAllOnesValue()); 1026 } 1027 1028 /// Return true if we can simplify X / Y to 0. Remainder can adapt that answer 1029 /// to simplify X % Y to X. 1030 static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q, 1031 unsigned MaxRecurse, bool IsSigned) { 1032 // Recursion is always used, so bail out at once if we already hit the limit. 1033 if (!MaxRecurse--) 1034 return false; 1035 1036 if (IsSigned) { 1037 // |X| / |Y| --> 0 1038 // 1039 // We require that 1 operand is a simple constant. That could be extended to 1040 // 2 variables if we computed the sign bit for each. 1041 // 1042 // Make sure that a constant is not the minimum signed value because taking 1043 // the abs() of that is undefined. 1044 Type *Ty = X->getType(); 1045 const APInt *C; 1046 if (match(X, m_APInt(C)) && !C->isMinSignedValue()) { 1047 // Is the variable divisor magnitude always greater than the constant 1048 // dividend magnitude? 1049 // |Y| > |C| --> Y < -abs(C) or Y > abs(C) 1050 Constant *PosDividendC = ConstantInt::get(Ty, C->abs()); 1051 Constant *NegDividendC = ConstantInt::get(Ty, -C->abs()); 1052 if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) || 1053 isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse)) 1054 return true; 1055 } 1056 if (match(Y, m_APInt(C))) { 1057 // Special-case: we can't take the abs() of a minimum signed value. If 1058 // that's the divisor, then all we have to do is prove that the dividend 1059 // is also not the minimum signed value. 1060 if (C->isMinSignedValue()) 1061 return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse); 1062 1063 // Is the variable dividend magnitude always less than the constant 1064 // divisor magnitude? 1065 // |X| < |C| --> X > -abs(C) and X < abs(C) 1066 Constant *PosDivisorC = ConstantInt::get(Ty, C->abs()); 1067 Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs()); 1068 if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) && 1069 isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse)) 1070 return true; 1071 } 1072 return false; 1073 } 1074 1075 // IsSigned == false. 1076 // Is the dividend unsigned less than the divisor? 1077 return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse); 1078 } 1079 1080 /// These are simplifications common to SDiv and UDiv. 1081 static Value *simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, 1082 const SimplifyQuery &Q, unsigned MaxRecurse) { 1083 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q)) 1084 return C; 1085 1086 if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q)) 1087 return V; 1088 1089 bool IsSigned = Opcode == Instruction::SDiv; 1090 1091 // (X rem Y) / Y -> 0 1092 if ((IsSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) || 1093 (!IsSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1))))) 1094 return Constant::getNullValue(Op0->getType()); 1095 1096 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow 1097 ConstantInt *C1, *C2; 1098 if (!IsSigned && match(Op0, m_UDiv(m_Value(), m_ConstantInt(C1))) && 1099 match(Op1, m_ConstantInt(C2))) { 1100 bool Overflow; 1101 (void)C1->getValue().umul_ov(C2->getValue(), Overflow); 1102 if (Overflow) 1103 return Constant::getNullValue(Op0->getType()); 1104 } 1105 1106 // If the operation is with the result of a select instruction, check whether 1107 // operating on either branch of the select always yields the same value. 1108 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1109 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) 1110 return V; 1111 1112 // If the operation is with the result of a phi instruction, check whether 1113 // operating on all incoming values of the phi always yields the same value. 1114 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1115 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) 1116 return V; 1117 1118 if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned)) 1119 return Constant::getNullValue(Op0->getType()); 1120 1121 return nullptr; 1122 } 1123 1124 /// These are simplifications common to SRem and URem. 1125 static Value *simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, 1126 const SimplifyQuery &Q, unsigned MaxRecurse) { 1127 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q)) 1128 return C; 1129 1130 if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q)) 1131 return V; 1132 1133 // (X % Y) % Y -> X % Y 1134 if ((Opcode == Instruction::SRem && 1135 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) || 1136 (Opcode == Instruction::URem && 1137 match(Op0, m_URem(m_Value(), m_Specific(Op1))))) 1138 return Op0; 1139 1140 // (X << Y) % X -> 0 1141 if (Q.IIQ.UseInstrInfo && 1142 ((Opcode == Instruction::SRem && 1143 match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) || 1144 (Opcode == Instruction::URem && 1145 match(Op0, m_NUWShl(m_Specific(Op1), m_Value()))))) 1146 return Constant::getNullValue(Op0->getType()); 1147 1148 // If the operation is with the result of a select instruction, check whether 1149 // operating on either branch of the select always yields the same value. 1150 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1151 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) 1152 return V; 1153 1154 // If the operation is with the result of a phi instruction, check whether 1155 // operating on all incoming values of the phi always yields the same value. 1156 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1157 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) 1158 return V; 1159 1160 // If X / Y == 0, then X % Y == X. 1161 if (isDivZero(Op0, Op1, Q, MaxRecurse, Opcode == Instruction::SRem)) 1162 return Op0; 1163 1164 return nullptr; 1165 } 1166 1167 /// Given operands for an SDiv, see if we can fold the result. 1168 /// If not, this returns null. 1169 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 1170 unsigned MaxRecurse) { 1171 // If two operands are negated and no signed overflow, return -1. 1172 if (isKnownNegation(Op0, Op1, /*NeedNSW=*/true)) 1173 return Constant::getAllOnesValue(Op0->getType()); 1174 1175 return simplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse); 1176 } 1177 1178 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 1179 return ::SimplifySDivInst(Op0, Op1, Q, RecursionLimit); 1180 } 1181 1182 /// Given operands for a UDiv, see if we can fold the result. 1183 /// If not, this returns null. 1184 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 1185 unsigned MaxRecurse) { 1186 return simplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse); 1187 } 1188 1189 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 1190 return ::SimplifyUDivInst(Op0, Op1, Q, RecursionLimit); 1191 } 1192 1193 /// Given operands for an SRem, see if we can fold the result. 1194 /// If not, this returns null. 1195 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 1196 unsigned MaxRecurse) { 1197 // If the divisor is 0, the result is undefined, so assume the divisor is -1. 1198 // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0 1199 Value *X; 1200 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) 1201 return ConstantInt::getNullValue(Op0->getType()); 1202 1203 // If the two operands are negated, return 0. 1204 if (isKnownNegation(Op0, Op1)) 1205 return ConstantInt::getNullValue(Op0->getType()); 1206 1207 return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse); 1208 } 1209 1210 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 1211 return ::SimplifySRemInst(Op0, Op1, Q, RecursionLimit); 1212 } 1213 1214 /// Given operands for a URem, see if we can fold the result. 1215 /// If not, this returns null. 1216 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 1217 unsigned MaxRecurse) { 1218 return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse); 1219 } 1220 1221 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 1222 return ::SimplifyURemInst(Op0, Op1, Q, RecursionLimit); 1223 } 1224 1225 /// Returns true if a shift by \c Amount always yields poison. 1226 static bool isPoisonShift(Value *Amount, const SimplifyQuery &Q) { 1227 Constant *C = dyn_cast<Constant>(Amount); 1228 if (!C) 1229 return false; 1230 1231 // X shift by undef -> poison because it may shift by the bitwidth. 1232 if (Q.isUndefValue(C)) 1233 return true; 1234 1235 // Shifting by the bitwidth or more is undefined. 1236 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1237 if (CI->getValue().uge(CI->getType()->getScalarSizeInBits())) 1238 return true; 1239 1240 // If all lanes of a vector shift are undefined the whole shift is. 1241 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) { 1242 for (unsigned I = 0, 1243 E = cast<FixedVectorType>(C->getType())->getNumElements(); 1244 I != E; ++I) 1245 if (!isPoisonShift(C->getAggregateElement(I), Q)) 1246 return false; 1247 return true; 1248 } 1249 1250 return false; 1251 } 1252 1253 /// Given operands for an Shl, LShr or AShr, see if we can fold the result. 1254 /// If not, this returns null. 1255 static Value *SimplifyShift(Instruction::BinaryOps Opcode, Value *Op0, 1256 Value *Op1, bool IsNSW, const SimplifyQuery &Q, 1257 unsigned MaxRecurse) { 1258 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q)) 1259 return C; 1260 1261 // poison shift by X -> poison 1262 if (isa<PoisonValue>(Op0)) 1263 return Op0; 1264 1265 // 0 shift by X -> 0 1266 if (match(Op0, m_Zero())) 1267 return Constant::getNullValue(Op0->getType()); 1268 1269 // X shift by 0 -> X 1270 // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones 1271 // would be poison. 1272 Value *X; 1273 if (match(Op1, m_Zero()) || 1274 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))) 1275 return Op0; 1276 1277 // Fold undefined shifts. 1278 if (isPoisonShift(Op1, Q)) 1279 return PoisonValue::get(Op0->getType()); 1280 1281 // If the operation is with the result of a select instruction, check whether 1282 // operating on either branch of the select always yields the same value. 1283 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1284 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) 1285 return V; 1286 1287 // If the operation is with the result of a phi instruction, check whether 1288 // operating on all incoming values of the phi always yields the same value. 1289 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1290 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) 1291 return V; 1292 1293 // If any bits in the shift amount make that value greater than or equal to 1294 // the number of bits in the type, the shift is undefined. 1295 KnownBits KnownAmt = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 1296 if (KnownAmt.getMinValue().uge(KnownAmt.getBitWidth())) 1297 return PoisonValue::get(Op0->getType()); 1298 1299 // If all valid bits in the shift amount are known zero, the first operand is 1300 // unchanged. 1301 unsigned NumValidShiftBits = Log2_32_Ceil(KnownAmt.getBitWidth()); 1302 if (KnownAmt.countMinTrailingZeros() >= NumValidShiftBits) 1303 return Op0; 1304 1305 // Check for nsw shl leading to a poison value. 1306 if (IsNSW) { 1307 assert(Opcode == Instruction::Shl && "Expected shl for nsw instruction"); 1308 KnownBits KnownVal = computeKnownBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 1309 KnownBits KnownShl = KnownBits::shl(KnownVal, KnownAmt); 1310 1311 if (KnownVal.Zero.isSignBitSet()) 1312 KnownShl.Zero.setSignBit(); 1313 if (KnownVal.One.isSignBitSet()) 1314 KnownShl.One.setSignBit(); 1315 1316 if (KnownShl.hasConflict()) 1317 return PoisonValue::get(Op0->getType()); 1318 } 1319 1320 return nullptr; 1321 } 1322 1323 /// Given operands for an Shl, LShr or AShr, see if we can 1324 /// fold the result. If not, this returns null. 1325 static Value *SimplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0, 1326 Value *Op1, bool isExact, const SimplifyQuery &Q, 1327 unsigned MaxRecurse) { 1328 if (Value *V = 1329 SimplifyShift(Opcode, Op0, Op1, /*IsNSW*/ false, Q, MaxRecurse)) 1330 return V; 1331 1332 // X >> X -> 0 1333 if (Op0 == Op1) 1334 return Constant::getNullValue(Op0->getType()); 1335 1336 // undef >> X -> 0 1337 // undef >> X -> undef (if it's exact) 1338 if (Q.isUndefValue(Op0)) 1339 return isExact ? Op0 : Constant::getNullValue(Op0->getType()); 1340 1341 // The low bit cannot be shifted out of an exact shift if it is set. 1342 if (isExact) { 1343 KnownBits Op0Known = computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT); 1344 if (Op0Known.One[0]) 1345 return Op0; 1346 } 1347 1348 return nullptr; 1349 } 1350 1351 /// Given operands for an Shl, see if we can fold the result. 1352 /// If not, this returns null. 1353 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 1354 const SimplifyQuery &Q, unsigned MaxRecurse) { 1355 if (Value *V = 1356 SimplifyShift(Instruction::Shl, Op0, Op1, isNSW, Q, MaxRecurse)) 1357 return V; 1358 1359 // undef << X -> 0 1360 // undef << X -> undef if (if it's NSW/NUW) 1361 if (Q.isUndefValue(Op0)) 1362 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType()); 1363 1364 // (X >> A) << A -> X 1365 Value *X; 1366 if (Q.IIQ.UseInstrInfo && 1367 match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1))))) 1368 return X; 1369 1370 // shl nuw i8 C, %x -> C iff C has sign bit set. 1371 if (isNUW && match(Op0, m_Negative())) 1372 return Op0; 1373 // NOTE: could use computeKnownBits() / LazyValueInfo, 1374 // but the cost-benefit analysis suggests it isn't worth it. 1375 1376 return nullptr; 1377 } 1378 1379 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 1380 const SimplifyQuery &Q) { 1381 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit); 1382 } 1383 1384 /// Given operands for an LShr, see if we can fold the result. 1385 /// If not, this returns null. 1386 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact, 1387 const SimplifyQuery &Q, unsigned MaxRecurse) { 1388 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q, 1389 MaxRecurse)) 1390 return V; 1391 1392 // (X << A) >> A -> X 1393 Value *X; 1394 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1)))) 1395 return X; 1396 1397 // ((X << A) | Y) >> A -> X if effective width of Y is not larger than A. 1398 // We can return X as we do in the above case since OR alters no bits in X. 1399 // SimplifyDemandedBits in InstCombine can do more general optimization for 1400 // bit manipulation. This pattern aims to provide opportunities for other 1401 // optimizers by supporting a simple but common case in InstSimplify. 1402 Value *Y; 1403 const APInt *ShRAmt, *ShLAmt; 1404 if (match(Op1, m_APInt(ShRAmt)) && 1405 match(Op0, m_c_Or(m_NUWShl(m_Value(X), m_APInt(ShLAmt)), m_Value(Y))) && 1406 *ShRAmt == *ShLAmt) { 1407 const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 1408 const unsigned Width = Op0->getType()->getScalarSizeInBits(); 1409 const unsigned EffWidthY = Width - YKnown.countMinLeadingZeros(); 1410 if (ShRAmt->uge(EffWidthY)) 1411 return X; 1412 } 1413 1414 return nullptr; 1415 } 1416 1417 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact, 1418 const SimplifyQuery &Q) { 1419 return ::SimplifyLShrInst(Op0, Op1, isExact, Q, RecursionLimit); 1420 } 1421 1422 /// Given operands for an AShr, see if we can fold the result. 1423 /// If not, this returns null. 1424 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact, 1425 const SimplifyQuery &Q, unsigned MaxRecurse) { 1426 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q, 1427 MaxRecurse)) 1428 return V; 1429 1430 // all ones >>a X -> -1 1431 // Do not return Op0 because it may contain undef elements if it's a vector. 1432 if (match(Op0, m_AllOnes())) 1433 return Constant::getAllOnesValue(Op0->getType()); 1434 1435 // (X << A) >> A -> X 1436 Value *X; 1437 if (Q.IIQ.UseInstrInfo && match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1)))) 1438 return X; 1439 1440 // Arithmetic shifting an all-sign-bit value is a no-op. 1441 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 1442 if (NumSignBits == Op0->getType()->getScalarSizeInBits()) 1443 return Op0; 1444 1445 return nullptr; 1446 } 1447 1448 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact, 1449 const SimplifyQuery &Q) { 1450 return ::SimplifyAShrInst(Op0, Op1, isExact, Q, RecursionLimit); 1451 } 1452 1453 /// Commuted variants are assumed to be handled by calling this function again 1454 /// with the parameters swapped. 1455 static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp, 1456 ICmpInst *UnsignedICmp, bool IsAnd, 1457 const SimplifyQuery &Q) { 1458 Value *X, *Y; 1459 1460 ICmpInst::Predicate EqPred; 1461 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) || 1462 !ICmpInst::isEquality(EqPred)) 1463 return nullptr; 1464 1465 ICmpInst::Predicate UnsignedPred; 1466 1467 Value *A, *B; 1468 // Y = (A - B); 1469 if (match(Y, m_Sub(m_Value(A), m_Value(B)))) { 1470 if (match(UnsignedICmp, 1471 m_c_ICmp(UnsignedPred, m_Specific(A), m_Specific(B))) && 1472 ICmpInst::isUnsigned(UnsignedPred)) { 1473 // A >=/<= B || (A - B) != 0 <--> true 1474 if ((UnsignedPred == ICmpInst::ICMP_UGE || 1475 UnsignedPred == ICmpInst::ICMP_ULE) && 1476 EqPred == ICmpInst::ICMP_NE && !IsAnd) 1477 return ConstantInt::getTrue(UnsignedICmp->getType()); 1478 // A </> B && (A - B) == 0 <--> false 1479 if ((UnsignedPred == ICmpInst::ICMP_ULT || 1480 UnsignedPred == ICmpInst::ICMP_UGT) && 1481 EqPred == ICmpInst::ICMP_EQ && IsAnd) 1482 return ConstantInt::getFalse(UnsignedICmp->getType()); 1483 1484 // A </> B && (A - B) != 0 <--> A </> B 1485 // A </> B || (A - B) != 0 <--> (A - B) != 0 1486 if (EqPred == ICmpInst::ICMP_NE && (UnsignedPred == ICmpInst::ICMP_ULT || 1487 UnsignedPred == ICmpInst::ICMP_UGT)) 1488 return IsAnd ? UnsignedICmp : ZeroICmp; 1489 1490 // A <=/>= B && (A - B) == 0 <--> (A - B) == 0 1491 // A <=/>= B || (A - B) == 0 <--> A <=/>= B 1492 if (EqPred == ICmpInst::ICMP_EQ && (UnsignedPred == ICmpInst::ICMP_ULE || 1493 UnsignedPred == ICmpInst::ICMP_UGE)) 1494 return IsAnd ? ZeroICmp : UnsignedICmp; 1495 } 1496 1497 // Given Y = (A - B) 1498 // Y >= A && Y != 0 --> Y >= A iff B != 0 1499 // Y < A || Y == 0 --> Y < A iff B != 0 1500 if (match(UnsignedICmp, 1501 m_c_ICmp(UnsignedPred, m_Specific(Y), m_Specific(A)))) { 1502 if (UnsignedPred == ICmpInst::ICMP_UGE && IsAnd && 1503 EqPred == ICmpInst::ICMP_NE && 1504 isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT)) 1505 return UnsignedICmp; 1506 if (UnsignedPred == ICmpInst::ICMP_ULT && !IsAnd && 1507 EqPred == ICmpInst::ICMP_EQ && 1508 isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT)) 1509 return UnsignedICmp; 1510 } 1511 } 1512 1513 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) && 1514 ICmpInst::isUnsigned(UnsignedPred)) 1515 ; 1516 else if (match(UnsignedICmp, 1517 m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) && 1518 ICmpInst::isUnsigned(UnsignedPred)) 1519 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred); 1520 else 1521 return nullptr; 1522 1523 // X > Y && Y == 0 --> Y == 0 iff X != 0 1524 // X > Y || Y == 0 --> X > Y iff X != 0 1525 if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ && 1526 isKnownNonZero(X, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT)) 1527 return IsAnd ? ZeroICmp : UnsignedICmp; 1528 1529 // X <= Y && Y != 0 --> X <= Y iff X != 0 1530 // X <= Y || Y != 0 --> Y != 0 iff X != 0 1531 if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE && 1532 isKnownNonZero(X, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT)) 1533 return IsAnd ? UnsignedICmp : ZeroICmp; 1534 1535 // The transforms below here are expected to be handled more generally with 1536 // simplifyAndOrOfICmpsWithLimitConst() or in InstCombine's 1537 // foldAndOrOfICmpsWithConstEq(). If we are looking to trim optimizer overlap, 1538 // these are candidates for removal. 1539 1540 // X < Y && Y != 0 --> X < Y 1541 // X < Y || Y != 0 --> Y != 0 1542 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE) 1543 return IsAnd ? UnsignedICmp : ZeroICmp; 1544 1545 // X >= Y && Y == 0 --> Y == 0 1546 // X >= Y || Y == 0 --> X >= Y 1547 if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ) 1548 return IsAnd ? ZeroICmp : UnsignedICmp; 1549 1550 // X < Y && Y == 0 --> false 1551 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ && 1552 IsAnd) 1553 return getFalse(UnsignedICmp->getType()); 1554 1555 // X >= Y || Y != 0 --> true 1556 if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_NE && 1557 !IsAnd) 1558 return getTrue(UnsignedICmp->getType()); 1559 1560 return nullptr; 1561 } 1562 1563 /// Commuted variants are assumed to be handled by calling this function again 1564 /// with the parameters swapped. 1565 static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) { 1566 ICmpInst::Predicate Pred0, Pred1; 1567 Value *A ,*B; 1568 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) || 1569 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B)))) 1570 return nullptr; 1571 1572 // We have (icmp Pred0, A, B) & (icmp Pred1, A, B). 1573 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we 1574 // can eliminate Op1 from this 'and'. 1575 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1)) 1576 return Op0; 1577 1578 // Check for any combination of predicates that are guaranteed to be disjoint. 1579 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) || 1580 (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) || 1581 (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) || 1582 (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)) 1583 return getFalse(Op0->getType()); 1584 1585 return nullptr; 1586 } 1587 1588 /// Commuted variants are assumed to be handled by calling this function again 1589 /// with the parameters swapped. 1590 static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) { 1591 ICmpInst::Predicate Pred0, Pred1; 1592 Value *A ,*B; 1593 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) || 1594 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B)))) 1595 return nullptr; 1596 1597 // We have (icmp Pred0, A, B) | (icmp Pred1, A, B). 1598 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we 1599 // can eliminate Op0 from this 'or'. 1600 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1)) 1601 return Op1; 1602 1603 // Check for any combination of predicates that cover the entire range of 1604 // possibilities. 1605 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) || 1606 (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) || 1607 (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) || 1608 (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE)) 1609 return getTrue(Op0->getType()); 1610 1611 return nullptr; 1612 } 1613 1614 /// Test if a pair of compares with a shared operand and 2 constants has an 1615 /// empty set intersection, full set union, or if one compare is a superset of 1616 /// the other. 1617 static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1, 1618 bool IsAnd) { 1619 // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)). 1620 if (Cmp0->getOperand(0) != Cmp1->getOperand(0)) 1621 return nullptr; 1622 1623 const APInt *C0, *C1; 1624 if (!match(Cmp0->getOperand(1), m_APInt(C0)) || 1625 !match(Cmp1->getOperand(1), m_APInt(C1))) 1626 return nullptr; 1627 1628 auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0); 1629 auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1); 1630 1631 // For and-of-compares, check if the intersection is empty: 1632 // (icmp X, C0) && (icmp X, C1) --> empty set --> false 1633 if (IsAnd && Range0.intersectWith(Range1).isEmptySet()) 1634 return getFalse(Cmp0->getType()); 1635 1636 // For or-of-compares, check if the union is full: 1637 // (icmp X, C0) || (icmp X, C1) --> full set --> true 1638 if (!IsAnd && Range0.unionWith(Range1).isFullSet()) 1639 return getTrue(Cmp0->getType()); 1640 1641 // Is one range a superset of the other? 1642 // If this is and-of-compares, take the smaller set: 1643 // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42 1644 // If this is or-of-compares, take the larger set: 1645 // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4 1646 if (Range0.contains(Range1)) 1647 return IsAnd ? Cmp1 : Cmp0; 1648 if (Range1.contains(Range0)) 1649 return IsAnd ? Cmp0 : Cmp1; 1650 1651 return nullptr; 1652 } 1653 1654 static Value *simplifyAndOrOfICmpsWithZero(ICmpInst *Cmp0, ICmpInst *Cmp1, 1655 bool IsAnd) { 1656 ICmpInst::Predicate P0 = Cmp0->getPredicate(), P1 = Cmp1->getPredicate(); 1657 if (!match(Cmp0->getOperand(1), m_Zero()) || 1658 !match(Cmp1->getOperand(1), m_Zero()) || P0 != P1) 1659 return nullptr; 1660 1661 if ((IsAnd && P0 != ICmpInst::ICMP_NE) || (!IsAnd && P1 != ICmpInst::ICMP_EQ)) 1662 return nullptr; 1663 1664 // We have either "(X == 0 || Y == 0)" or "(X != 0 && Y != 0)". 1665 Value *X = Cmp0->getOperand(0); 1666 Value *Y = Cmp1->getOperand(0); 1667 1668 // If one of the compares is a masked version of a (not) null check, then 1669 // that compare implies the other, so we eliminate the other. Optionally, look 1670 // through a pointer-to-int cast to match a null check of a pointer type. 1671 1672 // (X == 0) || (([ptrtoint] X & ?) == 0) --> ([ptrtoint] X & ?) == 0 1673 // (X == 0) || ((? & [ptrtoint] X) == 0) --> (? & [ptrtoint] X) == 0 1674 // (X != 0) && (([ptrtoint] X & ?) != 0) --> ([ptrtoint] X & ?) != 0 1675 // (X != 0) && ((? & [ptrtoint] X) != 0) --> (? & [ptrtoint] X) != 0 1676 if (match(Y, m_c_And(m_Specific(X), m_Value())) || 1677 match(Y, m_c_And(m_PtrToInt(m_Specific(X)), m_Value()))) 1678 return Cmp1; 1679 1680 // (([ptrtoint] Y & ?) == 0) || (Y == 0) --> ([ptrtoint] Y & ?) == 0 1681 // ((? & [ptrtoint] Y) == 0) || (Y == 0) --> (? & [ptrtoint] Y) == 0 1682 // (([ptrtoint] Y & ?) != 0) && (Y != 0) --> ([ptrtoint] Y & ?) != 0 1683 // ((? & [ptrtoint] Y) != 0) && (Y != 0) --> (? & [ptrtoint] Y) != 0 1684 if (match(X, m_c_And(m_Specific(Y), m_Value())) || 1685 match(X, m_c_And(m_PtrToInt(m_Specific(Y)), m_Value()))) 1686 return Cmp0; 1687 1688 return nullptr; 1689 } 1690 1691 static Value *simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1, 1692 const InstrInfoQuery &IIQ) { 1693 // (icmp (add V, C0), C1) & (icmp V, C0) 1694 ICmpInst::Predicate Pred0, Pred1; 1695 const APInt *C0, *C1; 1696 Value *V; 1697 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1)))) 1698 return nullptr; 1699 1700 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value()))) 1701 return nullptr; 1702 1703 auto *AddInst = cast<OverflowingBinaryOperator>(Op0->getOperand(0)); 1704 if (AddInst->getOperand(1) != Op1->getOperand(1)) 1705 return nullptr; 1706 1707 Type *ITy = Op0->getType(); 1708 bool isNSW = IIQ.hasNoSignedWrap(AddInst); 1709 bool isNUW = IIQ.hasNoUnsignedWrap(AddInst); 1710 1711 const APInt Delta = *C1 - *C0; 1712 if (C0->isStrictlyPositive()) { 1713 if (Delta == 2) { 1714 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT) 1715 return getFalse(ITy); 1716 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW) 1717 return getFalse(ITy); 1718 } 1719 if (Delta == 1) { 1720 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT) 1721 return getFalse(ITy); 1722 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW) 1723 return getFalse(ITy); 1724 } 1725 } 1726 if (C0->getBoolValue() && isNUW) { 1727 if (Delta == 2) 1728 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT) 1729 return getFalse(ITy); 1730 if (Delta == 1) 1731 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT) 1732 return getFalse(ITy); 1733 } 1734 1735 return nullptr; 1736 } 1737 1738 /// Try to eliminate compares with signed or unsigned min/max constants. 1739 static Value *simplifyAndOrOfICmpsWithLimitConst(ICmpInst *Cmp0, ICmpInst *Cmp1, 1740 bool IsAnd) { 1741 // Canonicalize an equality compare as Cmp0. 1742 if (Cmp1->isEquality()) 1743 std::swap(Cmp0, Cmp1); 1744 if (!Cmp0->isEquality()) 1745 return nullptr; 1746 1747 // The non-equality compare must include a common operand (X). Canonicalize 1748 // the common operand as operand 0 (the predicate is swapped if the common 1749 // operand was operand 1). 1750 ICmpInst::Predicate Pred0 = Cmp0->getPredicate(); 1751 Value *X = Cmp0->getOperand(0); 1752 ICmpInst::Predicate Pred1; 1753 bool HasNotOp = match(Cmp1, m_c_ICmp(Pred1, m_Not(m_Specific(X)), m_Value())); 1754 if (!HasNotOp && !match(Cmp1, m_c_ICmp(Pred1, m_Specific(X), m_Value()))) 1755 return nullptr; 1756 if (ICmpInst::isEquality(Pred1)) 1757 return nullptr; 1758 1759 // The equality compare must be against a constant. Flip bits if we matched 1760 // a bitwise not. Convert a null pointer constant to an integer zero value. 1761 APInt MinMaxC; 1762 const APInt *C; 1763 if (match(Cmp0->getOperand(1), m_APInt(C))) 1764 MinMaxC = HasNotOp ? ~*C : *C; 1765 else if (isa<ConstantPointerNull>(Cmp0->getOperand(1))) 1766 MinMaxC = APInt::getNullValue(8); 1767 else 1768 return nullptr; 1769 1770 // DeMorganize if this is 'or': P0 || P1 --> !P0 && !P1. 1771 if (!IsAnd) { 1772 Pred0 = ICmpInst::getInversePredicate(Pred0); 1773 Pred1 = ICmpInst::getInversePredicate(Pred1); 1774 } 1775 1776 // Normalize to unsigned compare and unsigned min/max value. 1777 // Example for 8-bit: -128 + 128 -> 0; 127 + 128 -> 255 1778 if (ICmpInst::isSigned(Pred1)) { 1779 Pred1 = ICmpInst::getUnsignedPredicate(Pred1); 1780 MinMaxC += APInt::getSignedMinValue(MinMaxC.getBitWidth()); 1781 } 1782 1783 // (X != MAX) && (X < Y) --> X < Y 1784 // (X == MAX) || (X >= Y) --> X >= Y 1785 if (MinMaxC.isMaxValue()) 1786 if (Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_ULT) 1787 return Cmp1; 1788 1789 // (X != MIN) && (X > Y) --> X > Y 1790 // (X == MIN) || (X <= Y) --> X <= Y 1791 if (MinMaxC.isMinValue()) 1792 if (Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_UGT) 1793 return Cmp1; 1794 1795 return nullptr; 1796 } 1797 1798 static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1, 1799 const SimplifyQuery &Q) { 1800 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true, Q)) 1801 return X; 1802 if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true, Q)) 1803 return X; 1804 1805 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1)) 1806 return X; 1807 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op1, Op0)) 1808 return X; 1809 1810 if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true)) 1811 return X; 1812 1813 if (Value *X = simplifyAndOrOfICmpsWithLimitConst(Op0, Op1, true)) 1814 return X; 1815 1816 if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true)) 1817 return X; 1818 1819 if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1, Q.IIQ)) 1820 return X; 1821 if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0, Q.IIQ)) 1822 return X; 1823 1824 return nullptr; 1825 } 1826 1827 static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1, 1828 const InstrInfoQuery &IIQ) { 1829 // (icmp (add V, C0), C1) | (icmp V, C0) 1830 ICmpInst::Predicate Pred0, Pred1; 1831 const APInt *C0, *C1; 1832 Value *V; 1833 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1)))) 1834 return nullptr; 1835 1836 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value()))) 1837 return nullptr; 1838 1839 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0)); 1840 if (AddInst->getOperand(1) != Op1->getOperand(1)) 1841 return nullptr; 1842 1843 Type *ITy = Op0->getType(); 1844 bool isNSW = IIQ.hasNoSignedWrap(AddInst); 1845 bool isNUW = IIQ.hasNoUnsignedWrap(AddInst); 1846 1847 const APInt Delta = *C1 - *C0; 1848 if (C0->isStrictlyPositive()) { 1849 if (Delta == 2) { 1850 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE) 1851 return getTrue(ITy); 1852 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW) 1853 return getTrue(ITy); 1854 } 1855 if (Delta == 1) { 1856 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE) 1857 return getTrue(ITy); 1858 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW) 1859 return getTrue(ITy); 1860 } 1861 } 1862 if (C0->getBoolValue() && isNUW) { 1863 if (Delta == 2) 1864 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE) 1865 return getTrue(ITy); 1866 if (Delta == 1) 1867 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE) 1868 return getTrue(ITy); 1869 } 1870 1871 return nullptr; 1872 } 1873 1874 static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1, 1875 const SimplifyQuery &Q) { 1876 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false, Q)) 1877 return X; 1878 if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false, Q)) 1879 return X; 1880 1881 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1)) 1882 return X; 1883 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op1, Op0)) 1884 return X; 1885 1886 if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false)) 1887 return X; 1888 1889 if (Value *X = simplifyAndOrOfICmpsWithLimitConst(Op0, Op1, false)) 1890 return X; 1891 1892 if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false)) 1893 return X; 1894 1895 if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1, Q.IIQ)) 1896 return X; 1897 if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0, Q.IIQ)) 1898 return X; 1899 1900 return nullptr; 1901 } 1902 1903 static Value *simplifyAndOrOfFCmps(const TargetLibraryInfo *TLI, 1904 FCmpInst *LHS, FCmpInst *RHS, bool IsAnd) { 1905 Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1); 1906 Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1); 1907 if (LHS0->getType() != RHS0->getType()) 1908 return nullptr; 1909 1910 FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate(); 1911 if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) || 1912 (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) { 1913 // (fcmp ord NNAN, X) & (fcmp ord X, Y) --> fcmp ord X, Y 1914 // (fcmp ord NNAN, X) & (fcmp ord Y, X) --> fcmp ord Y, X 1915 // (fcmp ord X, NNAN) & (fcmp ord X, Y) --> fcmp ord X, Y 1916 // (fcmp ord X, NNAN) & (fcmp ord Y, X) --> fcmp ord Y, X 1917 // (fcmp uno NNAN, X) | (fcmp uno X, Y) --> fcmp uno X, Y 1918 // (fcmp uno NNAN, X) | (fcmp uno Y, X) --> fcmp uno Y, X 1919 // (fcmp uno X, NNAN) | (fcmp uno X, Y) --> fcmp uno X, Y 1920 // (fcmp uno X, NNAN) | (fcmp uno Y, X) --> fcmp uno Y, X 1921 if ((isKnownNeverNaN(LHS0, TLI) && (LHS1 == RHS0 || LHS1 == RHS1)) || 1922 (isKnownNeverNaN(LHS1, TLI) && (LHS0 == RHS0 || LHS0 == RHS1))) 1923 return RHS; 1924 1925 // (fcmp ord X, Y) & (fcmp ord NNAN, X) --> fcmp ord X, Y 1926 // (fcmp ord Y, X) & (fcmp ord NNAN, X) --> fcmp ord Y, X 1927 // (fcmp ord X, Y) & (fcmp ord X, NNAN) --> fcmp ord X, Y 1928 // (fcmp ord Y, X) & (fcmp ord X, NNAN) --> fcmp ord Y, X 1929 // (fcmp uno X, Y) | (fcmp uno NNAN, X) --> fcmp uno X, Y 1930 // (fcmp uno Y, X) | (fcmp uno NNAN, X) --> fcmp uno Y, X 1931 // (fcmp uno X, Y) | (fcmp uno X, NNAN) --> fcmp uno X, Y 1932 // (fcmp uno Y, X) | (fcmp uno X, NNAN) --> fcmp uno Y, X 1933 if ((isKnownNeverNaN(RHS0, TLI) && (RHS1 == LHS0 || RHS1 == LHS1)) || 1934 (isKnownNeverNaN(RHS1, TLI) && (RHS0 == LHS0 || RHS0 == LHS1))) 1935 return LHS; 1936 } 1937 1938 return nullptr; 1939 } 1940 1941 static Value *simplifyAndOrOfCmps(const SimplifyQuery &Q, 1942 Value *Op0, Value *Op1, bool IsAnd) { 1943 // Look through casts of the 'and' operands to find compares. 1944 auto *Cast0 = dyn_cast<CastInst>(Op0); 1945 auto *Cast1 = dyn_cast<CastInst>(Op1); 1946 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() && 1947 Cast0->getSrcTy() == Cast1->getSrcTy()) { 1948 Op0 = Cast0->getOperand(0); 1949 Op1 = Cast1->getOperand(0); 1950 } 1951 1952 Value *V = nullptr; 1953 auto *ICmp0 = dyn_cast<ICmpInst>(Op0); 1954 auto *ICmp1 = dyn_cast<ICmpInst>(Op1); 1955 if (ICmp0 && ICmp1) 1956 V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1, Q) 1957 : simplifyOrOfICmps(ICmp0, ICmp1, Q); 1958 1959 auto *FCmp0 = dyn_cast<FCmpInst>(Op0); 1960 auto *FCmp1 = dyn_cast<FCmpInst>(Op1); 1961 if (FCmp0 && FCmp1) 1962 V = simplifyAndOrOfFCmps(Q.TLI, FCmp0, FCmp1, IsAnd); 1963 1964 if (!V) 1965 return nullptr; 1966 if (!Cast0) 1967 return V; 1968 1969 // If we looked through casts, we can only handle a constant simplification 1970 // because we are not allowed to create a cast instruction here. 1971 if (auto *C = dyn_cast<Constant>(V)) 1972 return ConstantExpr::getCast(Cast0->getOpcode(), C, Cast0->getType()); 1973 1974 return nullptr; 1975 } 1976 1977 /// Given a bitwise logic op, check if the operands are add/sub with a common 1978 /// source value and inverted constant (identity: C - X -> ~(X + ~C)). 1979 static Value *simplifyLogicOfAddSub(Value *Op0, Value *Op1, 1980 Instruction::BinaryOps Opcode) { 1981 assert(Op0->getType() == Op1->getType() && "Mismatched binop types"); 1982 assert(BinaryOperator::isBitwiseLogicOp(Opcode) && "Expected logic op"); 1983 Value *X; 1984 Constant *C1, *C2; 1985 if ((match(Op0, m_Add(m_Value(X), m_Constant(C1))) && 1986 match(Op1, m_Sub(m_Constant(C2), m_Specific(X)))) || 1987 (match(Op1, m_Add(m_Value(X), m_Constant(C1))) && 1988 match(Op0, m_Sub(m_Constant(C2), m_Specific(X))))) { 1989 if (ConstantExpr::getNot(C1) == C2) { 1990 // (X + C) & (~C - X) --> (X + C) & ~(X + C) --> 0 1991 // (X + C) | (~C - X) --> (X + C) | ~(X + C) --> -1 1992 // (X + C) ^ (~C - X) --> (X + C) ^ ~(X + C) --> -1 1993 Type *Ty = Op0->getType(); 1994 return Opcode == Instruction::And ? ConstantInt::getNullValue(Ty) 1995 : ConstantInt::getAllOnesValue(Ty); 1996 } 1997 } 1998 return nullptr; 1999 } 2000 2001 /// Given operands for an And, see if we can fold the result. 2002 /// If not, this returns null. 2003 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 2004 unsigned MaxRecurse) { 2005 if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q)) 2006 return C; 2007 2008 // X & poison -> poison 2009 if (isa<PoisonValue>(Op1)) 2010 return Op1; 2011 2012 // X & undef -> 0 2013 if (Q.isUndefValue(Op1)) 2014 return Constant::getNullValue(Op0->getType()); 2015 2016 // X & X = X 2017 if (Op0 == Op1) 2018 return Op0; 2019 2020 // X & 0 = 0 2021 if (match(Op1, m_Zero())) 2022 return Constant::getNullValue(Op0->getType()); 2023 2024 // X & -1 = X 2025 if (match(Op1, m_AllOnes())) 2026 return Op0; 2027 2028 // A & ~A = ~A & A = 0 2029 if (match(Op0, m_Not(m_Specific(Op1))) || 2030 match(Op1, m_Not(m_Specific(Op0)))) 2031 return Constant::getNullValue(Op0->getType()); 2032 2033 // (A | ?) & A = A 2034 if (match(Op0, m_c_Or(m_Specific(Op1), m_Value()))) 2035 return Op1; 2036 2037 // A & (A | ?) = A 2038 if (match(Op1, m_c_Or(m_Specific(Op0), m_Value()))) 2039 return Op0; 2040 2041 if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::And)) 2042 return V; 2043 2044 // A mask that only clears known zeros of a shifted value is a no-op. 2045 Value *X; 2046 const APInt *Mask; 2047 const APInt *ShAmt; 2048 if (match(Op1, m_APInt(Mask))) { 2049 // If all bits in the inverted and shifted mask are clear: 2050 // and (shl X, ShAmt), Mask --> shl X, ShAmt 2051 if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) && 2052 (~(*Mask)).lshr(*ShAmt).isNullValue()) 2053 return Op0; 2054 2055 // If all bits in the inverted and shifted mask are clear: 2056 // and (lshr X, ShAmt), Mask --> lshr X, ShAmt 2057 if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) && 2058 (~(*Mask)).shl(*ShAmt).isNullValue()) 2059 return Op0; 2060 } 2061 2062 // If we have a multiplication overflow check that is being 'and'ed with a 2063 // check that one of the multipliers is not zero, we can omit the 'and', and 2064 // only keep the overflow check. 2065 if (isCheckForZeroAndMulWithOverflow(Op0, Op1, true)) 2066 return Op1; 2067 if (isCheckForZeroAndMulWithOverflow(Op1, Op0, true)) 2068 return Op0; 2069 2070 // A & (-A) = A if A is a power of two or zero. 2071 if (match(Op0, m_Neg(m_Specific(Op1))) || 2072 match(Op1, m_Neg(m_Specific(Op0)))) { 2073 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, 2074 Q.DT)) 2075 return Op0; 2076 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, 2077 Q.DT)) 2078 return Op1; 2079 } 2080 2081 // This is a similar pattern used for checking if a value is a power-of-2: 2082 // (A - 1) & A --> 0 (if A is a power-of-2 or 0) 2083 // A & (A - 1) --> 0 (if A is a power-of-2 or 0) 2084 if (match(Op0, m_Add(m_Specific(Op1), m_AllOnes())) && 2085 isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT)) 2086 return Constant::getNullValue(Op1->getType()); 2087 if (match(Op1, m_Add(m_Specific(Op0), m_AllOnes())) && 2088 isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT)) 2089 return Constant::getNullValue(Op0->getType()); 2090 2091 if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, true)) 2092 return V; 2093 2094 // Try some generic simplifications for associative operations. 2095 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q, 2096 MaxRecurse)) 2097 return V; 2098 2099 // And distributes over Or. Try some generic simplifications based on this. 2100 if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1, 2101 Instruction::Or, Q, MaxRecurse)) 2102 return V; 2103 2104 // And distributes over Xor. Try some generic simplifications based on this. 2105 if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1, 2106 Instruction::Xor, Q, MaxRecurse)) 2107 return V; 2108 2109 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) { 2110 if (Op0->getType()->isIntOrIntVectorTy(1)) { 2111 // A & (A && B) -> A && B 2112 if (match(Op1, m_Select(m_Specific(Op0), m_Value(), m_Zero()))) 2113 return Op1; 2114 else if (match(Op0, m_Select(m_Specific(Op1), m_Value(), m_Zero()))) 2115 return Op0; 2116 } 2117 // If the operation is with the result of a select instruction, check 2118 // whether operating on either branch of the select always yields the same 2119 // value. 2120 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q, 2121 MaxRecurse)) 2122 return V; 2123 } 2124 2125 // If the operation is with the result of a phi instruction, check whether 2126 // operating on all incoming values of the phi always yields the same value. 2127 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 2128 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q, 2129 MaxRecurse)) 2130 return V; 2131 2132 // Assuming the effective width of Y is not larger than A, i.e. all bits 2133 // from X and Y are disjoint in (X << A) | Y, 2134 // if the mask of this AND op covers all bits of X or Y, while it covers 2135 // no bits from the other, we can bypass this AND op. E.g., 2136 // ((X << A) | Y) & Mask -> Y, 2137 // if Mask = ((1 << effective_width_of(Y)) - 1) 2138 // ((X << A) | Y) & Mask -> X << A, 2139 // if Mask = ((1 << effective_width_of(X)) - 1) << A 2140 // SimplifyDemandedBits in InstCombine can optimize the general case. 2141 // This pattern aims to help other passes for a common case. 2142 Value *Y, *XShifted; 2143 if (match(Op1, m_APInt(Mask)) && 2144 match(Op0, m_c_Or(m_CombineAnd(m_NUWShl(m_Value(X), m_APInt(ShAmt)), 2145 m_Value(XShifted)), 2146 m_Value(Y)))) { 2147 const unsigned Width = Op0->getType()->getScalarSizeInBits(); 2148 const unsigned ShftCnt = ShAmt->getLimitedValue(Width); 2149 const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2150 const unsigned EffWidthY = Width - YKnown.countMinLeadingZeros(); 2151 if (EffWidthY <= ShftCnt) { 2152 const KnownBits XKnown = computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI, 2153 Q.DT); 2154 const unsigned EffWidthX = Width - XKnown.countMinLeadingZeros(); 2155 const APInt EffBitsY = APInt::getLowBitsSet(Width, EffWidthY); 2156 const APInt EffBitsX = APInt::getLowBitsSet(Width, EffWidthX) << ShftCnt; 2157 // If the mask is extracting all bits from X or Y as is, we can skip 2158 // this AND op. 2159 if (EffBitsY.isSubsetOf(*Mask) && !EffBitsX.intersects(*Mask)) 2160 return Y; 2161 if (EffBitsX.isSubsetOf(*Mask) && !EffBitsY.intersects(*Mask)) 2162 return XShifted; 2163 } 2164 } 2165 2166 return nullptr; 2167 } 2168 2169 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 2170 return ::SimplifyAndInst(Op0, Op1, Q, RecursionLimit); 2171 } 2172 2173 /// Given operands for an Or, see if we can fold the result. 2174 /// If not, this returns null. 2175 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 2176 unsigned MaxRecurse) { 2177 if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q)) 2178 return C; 2179 2180 // X | poison -> poison 2181 if (isa<PoisonValue>(Op1)) 2182 return Op1; 2183 2184 // X | undef -> -1 2185 // X | -1 = -1 2186 // Do not return Op1 because it may contain undef elements if it's a vector. 2187 if (Q.isUndefValue(Op1) || match(Op1, m_AllOnes())) 2188 return Constant::getAllOnesValue(Op0->getType()); 2189 2190 // X | X = X 2191 // X | 0 = X 2192 if (Op0 == Op1 || match(Op1, m_Zero())) 2193 return Op0; 2194 2195 // A | ~A = ~A | A = -1 2196 if (match(Op0, m_Not(m_Specific(Op1))) || 2197 match(Op1, m_Not(m_Specific(Op0)))) 2198 return Constant::getAllOnesValue(Op0->getType()); 2199 2200 // (A & ?) | A = A 2201 if (match(Op0, m_c_And(m_Specific(Op1), m_Value()))) 2202 return Op1; 2203 2204 // A | (A & ?) = A 2205 if (match(Op1, m_c_And(m_Specific(Op0), m_Value()))) 2206 return Op0; 2207 2208 // ~(A & ?) | A = -1 2209 if (match(Op0, m_Not(m_c_And(m_Specific(Op1), m_Value())))) 2210 return Constant::getAllOnesValue(Op1->getType()); 2211 2212 // A | ~(A & ?) = -1 2213 if (match(Op1, m_Not(m_c_And(m_Specific(Op0), m_Value())))) 2214 return Constant::getAllOnesValue(Op0->getType()); 2215 2216 if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Or)) 2217 return V; 2218 2219 Value *A, *B, *NotA; 2220 // (A & ~B) | (A ^ B) -> (A ^ B) 2221 // (~B & A) | (A ^ B) -> (A ^ B) 2222 // (A & ~B) | (B ^ A) -> (B ^ A) 2223 // (~B & A) | (B ^ A) -> (B ^ A) 2224 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && 2225 (match(Op0, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) || 2226 match(Op0, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))) 2227 return Op1; 2228 2229 // Commute the 'or' operands. 2230 // (A ^ B) | (A & ~B) -> (A ^ B) 2231 // (A ^ B) | (~B & A) -> (A ^ B) 2232 // (B ^ A) | (A & ~B) -> (B ^ A) 2233 // (B ^ A) | (~B & A) -> (B ^ A) 2234 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) && 2235 (match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) || 2236 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))) 2237 return Op0; 2238 2239 // (A & B) | (~A ^ B) -> (~A ^ B) 2240 // (B & A) | (~A ^ B) -> (~A ^ B) 2241 // (A & B) | (B ^ ~A) -> (B ^ ~A) 2242 // (B & A) | (B ^ ~A) -> (B ^ ~A) 2243 if (match(Op0, m_And(m_Value(A), m_Value(B))) && 2244 (match(Op1, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) || 2245 match(Op1, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B))))) 2246 return Op1; 2247 2248 // Commute the 'or' operands. 2249 // (~A ^ B) | (A & B) -> (~A ^ B) 2250 // (~A ^ B) | (B & A) -> (~A ^ B) 2251 // (B ^ ~A) | (A & B) -> (B ^ ~A) 2252 // (B ^ ~A) | (B & A) -> (B ^ ~A) 2253 if (match(Op1, m_And(m_Value(A), m_Value(B))) && 2254 (match(Op0, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) || 2255 match(Op0, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B))))) 2256 return Op0; 2257 2258 // (~A & B) | ~(A | B) --> ~A 2259 // (~A & B) | ~(B | A) --> ~A 2260 // (B & ~A) | ~(A | B) --> ~A 2261 // (B & ~A) | ~(B | A) --> ~A 2262 if (match(Op0, m_c_And(m_CombineAnd(m_Value(NotA), m_Not(m_Value(A))), 2263 m_Value(B))) && 2264 match(Op1, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))) 2265 return NotA; 2266 2267 // Commute the 'or' operands. 2268 // ~(A | B) | (~A & B) --> ~A 2269 // ~(B | A) | (~A & B) --> ~A 2270 // ~(A | B) | (B & ~A) --> ~A 2271 // ~(B | A) | (B & ~A) --> ~A 2272 if (match(Op1, m_c_And(m_CombineAnd(m_Value(NotA), m_Not(m_Value(A))), 2273 m_Value(B))) && 2274 match(Op0, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))) 2275 return NotA; 2276 2277 if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, false)) 2278 return V; 2279 2280 // If we have a multiplication overflow check that is being 'and'ed with a 2281 // check that one of the multipliers is not zero, we can omit the 'and', and 2282 // only keep the overflow check. 2283 if (isCheckForZeroAndMulWithOverflow(Op0, Op1, false)) 2284 return Op1; 2285 if (isCheckForZeroAndMulWithOverflow(Op1, Op0, false)) 2286 return Op0; 2287 2288 // Try some generic simplifications for associative operations. 2289 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q, 2290 MaxRecurse)) 2291 return V; 2292 2293 // Or distributes over And. Try some generic simplifications based on this. 2294 if (Value *V = expandCommutativeBinOp(Instruction::Or, Op0, Op1, 2295 Instruction::And, Q, MaxRecurse)) 2296 return V; 2297 2298 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) { 2299 if (Op0->getType()->isIntOrIntVectorTy(1)) { 2300 // A | (A || B) -> A || B 2301 if (match(Op1, m_Select(m_Specific(Op0), m_One(), m_Value()))) 2302 return Op1; 2303 else if (match(Op0, m_Select(m_Specific(Op1), m_One(), m_Value()))) 2304 return Op0; 2305 } 2306 // If the operation is with the result of a select instruction, check 2307 // whether operating on either branch of the select always yields the same 2308 // value. 2309 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q, 2310 MaxRecurse)) 2311 return V; 2312 } 2313 2314 // (A & C1)|(B & C2) 2315 const APInt *C1, *C2; 2316 if (match(Op0, m_And(m_Value(A), m_APInt(C1))) && 2317 match(Op1, m_And(m_Value(B), m_APInt(C2)))) { 2318 if (*C1 == ~*C2) { 2319 // (A & C1)|(B & C2) 2320 // If we have: ((V + N) & C1) | (V & C2) 2321 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0 2322 // replace with V+N. 2323 Value *N; 2324 if (C2->isMask() && // C2 == 0+1+ 2325 match(A, m_c_Add(m_Specific(B), m_Value(N)))) { 2326 // Add commutes, try both ways. 2327 if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) 2328 return A; 2329 } 2330 // Or commutes, try both ways. 2331 if (C1->isMask() && 2332 match(B, m_c_Add(m_Specific(A), m_Value(N)))) { 2333 // Add commutes, try both ways. 2334 if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) 2335 return B; 2336 } 2337 } 2338 } 2339 2340 // If the operation is with the result of a phi instruction, check whether 2341 // operating on all incoming values of the phi always yields the same value. 2342 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 2343 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse)) 2344 return V; 2345 2346 return nullptr; 2347 } 2348 2349 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 2350 return ::SimplifyOrInst(Op0, Op1, Q, RecursionLimit); 2351 } 2352 2353 /// Given operands for a Xor, see if we can fold the result. 2354 /// If not, this returns null. 2355 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 2356 unsigned MaxRecurse) { 2357 if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q)) 2358 return C; 2359 2360 // A ^ undef -> undef 2361 if (Q.isUndefValue(Op1)) 2362 return Op1; 2363 2364 // A ^ 0 = A 2365 if (match(Op1, m_Zero())) 2366 return Op0; 2367 2368 // A ^ A = 0 2369 if (Op0 == Op1) 2370 return Constant::getNullValue(Op0->getType()); 2371 2372 // A ^ ~A = ~A ^ A = -1 2373 if (match(Op0, m_Not(m_Specific(Op1))) || 2374 match(Op1, m_Not(m_Specific(Op0)))) 2375 return Constant::getAllOnesValue(Op0->getType()); 2376 2377 if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Xor)) 2378 return V; 2379 2380 // Try some generic simplifications for associative operations. 2381 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q, 2382 MaxRecurse)) 2383 return V; 2384 2385 // Threading Xor over selects and phi nodes is pointless, so don't bother. 2386 // Threading over the select in "A ^ select(cond, B, C)" means evaluating 2387 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and 2388 // only if B and C are equal. If B and C are equal then (since we assume 2389 // that operands have already been simplified) "select(cond, B, C)" should 2390 // have been simplified to the common value of B and C already. Analysing 2391 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly 2392 // for threading over phi nodes. 2393 2394 return nullptr; 2395 } 2396 2397 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 2398 return ::SimplifyXorInst(Op0, Op1, Q, RecursionLimit); 2399 } 2400 2401 2402 static Type *GetCompareTy(Value *Op) { 2403 return CmpInst::makeCmpResultType(Op->getType()); 2404 } 2405 2406 /// Rummage around inside V looking for something equivalent to the comparison 2407 /// "LHS Pred RHS". Return such a value if found, otherwise return null. 2408 /// Helper function for analyzing max/min idioms. 2409 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred, 2410 Value *LHS, Value *RHS) { 2411 SelectInst *SI = dyn_cast<SelectInst>(V); 2412 if (!SI) 2413 return nullptr; 2414 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); 2415 if (!Cmp) 2416 return nullptr; 2417 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1); 2418 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS) 2419 return Cmp; 2420 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) && 2421 LHS == CmpRHS && RHS == CmpLHS) 2422 return Cmp; 2423 return nullptr; 2424 } 2425 2426 // A significant optimization not implemented here is assuming that alloca 2427 // addresses are not equal to incoming argument values. They don't *alias*, 2428 // as we say, but that doesn't mean they aren't equal, so we take a 2429 // conservative approach. 2430 // 2431 // This is inspired in part by C++11 5.10p1: 2432 // "Two pointers of the same type compare equal if and only if they are both 2433 // null, both point to the same function, or both represent the same 2434 // address." 2435 // 2436 // This is pretty permissive. 2437 // 2438 // It's also partly due to C11 6.5.9p6: 2439 // "Two pointers compare equal if and only if both are null pointers, both are 2440 // pointers to the same object (including a pointer to an object and a 2441 // subobject at its beginning) or function, both are pointers to one past the 2442 // last element of the same array object, or one is a pointer to one past the 2443 // end of one array object and the other is a pointer to the start of a 2444 // different array object that happens to immediately follow the first array 2445 // object in the address space.) 2446 // 2447 // C11's version is more restrictive, however there's no reason why an argument 2448 // couldn't be a one-past-the-end value for a stack object in the caller and be 2449 // equal to the beginning of a stack object in the callee. 2450 // 2451 // If the C and C++ standards are ever made sufficiently restrictive in this 2452 // area, it may be possible to update LLVM's semantics accordingly and reinstate 2453 // this optimization. 2454 static Constant * 2455 computePointerICmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, 2456 const SimplifyQuery &Q) { 2457 const DataLayout &DL = Q.DL; 2458 const TargetLibraryInfo *TLI = Q.TLI; 2459 const DominatorTree *DT = Q.DT; 2460 const Instruction *CxtI = Q.CxtI; 2461 const InstrInfoQuery &IIQ = Q.IIQ; 2462 2463 // First, skip past any trivial no-ops. 2464 LHS = LHS->stripPointerCasts(); 2465 RHS = RHS->stripPointerCasts(); 2466 2467 // A non-null pointer is not equal to a null pointer. 2468 if (isa<ConstantPointerNull>(RHS) && ICmpInst::isEquality(Pred) && 2469 llvm::isKnownNonZero(LHS, DL, 0, nullptr, nullptr, nullptr, 2470 IIQ.UseInstrInfo)) 2471 return ConstantInt::get(GetCompareTy(LHS), 2472 !CmpInst::isTrueWhenEqual(Pred)); 2473 2474 // We can only fold certain predicates on pointer comparisons. 2475 switch (Pred) { 2476 default: 2477 return nullptr; 2478 2479 // Equality comaprisons are easy to fold. 2480 case CmpInst::ICMP_EQ: 2481 case CmpInst::ICMP_NE: 2482 break; 2483 2484 // We can only handle unsigned relational comparisons because 'inbounds' on 2485 // a GEP only protects against unsigned wrapping. 2486 case CmpInst::ICMP_UGT: 2487 case CmpInst::ICMP_UGE: 2488 case CmpInst::ICMP_ULT: 2489 case CmpInst::ICMP_ULE: 2490 // However, we have to switch them to their signed variants to handle 2491 // negative indices from the base pointer. 2492 Pred = ICmpInst::getSignedPredicate(Pred); 2493 break; 2494 } 2495 2496 // Strip off any constant offsets so that we can reason about them. 2497 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets 2498 // here and compare base addresses like AliasAnalysis does, however there are 2499 // numerous hazards. AliasAnalysis and its utilities rely on special rules 2500 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis 2501 // doesn't need to guarantee pointer inequality when it says NoAlias. 2502 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS); 2503 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS); 2504 2505 // If LHS and RHS are related via constant offsets to the same base 2506 // value, we can replace it with an icmp which just compares the offsets. 2507 if (LHS == RHS) 2508 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset); 2509 2510 // Various optimizations for (in)equality comparisons. 2511 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) { 2512 // Different non-empty allocations that exist at the same time have 2513 // different addresses (if the program can tell). Global variables always 2514 // exist, so they always exist during the lifetime of each other and all 2515 // allocas. Two different allocas usually have different addresses... 2516 // 2517 // However, if there's an @llvm.stackrestore dynamically in between two 2518 // allocas, they may have the same address. It's tempting to reduce the 2519 // scope of the problem by only looking at *static* allocas here. That would 2520 // cover the majority of allocas while significantly reducing the likelihood 2521 // of having an @llvm.stackrestore pop up in the middle. However, it's not 2522 // actually impossible for an @llvm.stackrestore to pop up in the middle of 2523 // an entry block. Also, if we have a block that's not attached to a 2524 // function, we can't tell if it's "static" under the current definition. 2525 // Theoretically, this problem could be fixed by creating a new kind of 2526 // instruction kind specifically for static allocas. Such a new instruction 2527 // could be required to be at the top of the entry block, thus preventing it 2528 // from being subject to a @llvm.stackrestore. Instcombine could even 2529 // convert regular allocas into these special allocas. It'd be nifty. 2530 // However, until then, this problem remains open. 2531 // 2532 // So, we'll assume that two non-empty allocas have different addresses 2533 // for now. 2534 // 2535 // With all that, if the offsets are within the bounds of their allocations 2536 // (and not one-past-the-end! so we can't use inbounds!), and their 2537 // allocations aren't the same, the pointers are not equal. 2538 // 2539 // Note that it's not necessary to check for LHS being a global variable 2540 // address, due to canonicalization and constant folding. 2541 if (isa<AllocaInst>(LHS) && 2542 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) { 2543 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset); 2544 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset); 2545 uint64_t LHSSize, RHSSize; 2546 ObjectSizeOpts Opts; 2547 Opts.NullIsUnknownSize = 2548 NullPointerIsDefined(cast<AllocaInst>(LHS)->getFunction()); 2549 if (LHSOffsetCI && RHSOffsetCI && 2550 getObjectSize(LHS, LHSSize, DL, TLI, Opts) && 2551 getObjectSize(RHS, RHSSize, DL, TLI, Opts)) { 2552 const APInt &LHSOffsetValue = LHSOffsetCI->getValue(); 2553 const APInt &RHSOffsetValue = RHSOffsetCI->getValue(); 2554 if (!LHSOffsetValue.isNegative() && 2555 !RHSOffsetValue.isNegative() && 2556 LHSOffsetValue.ult(LHSSize) && 2557 RHSOffsetValue.ult(RHSSize)) { 2558 return ConstantInt::get(GetCompareTy(LHS), 2559 !CmpInst::isTrueWhenEqual(Pred)); 2560 } 2561 } 2562 2563 // Repeat the above check but this time without depending on DataLayout 2564 // or being able to compute a precise size. 2565 if (!cast<PointerType>(LHS->getType())->isEmptyTy() && 2566 !cast<PointerType>(RHS->getType())->isEmptyTy() && 2567 LHSOffset->isNullValue() && 2568 RHSOffset->isNullValue()) 2569 return ConstantInt::get(GetCompareTy(LHS), 2570 !CmpInst::isTrueWhenEqual(Pred)); 2571 } 2572 2573 // Even if an non-inbounds GEP occurs along the path we can still optimize 2574 // equality comparisons concerning the result. We avoid walking the whole 2575 // chain again by starting where the last calls to 2576 // stripAndComputeConstantOffsets left off and accumulate the offsets. 2577 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true); 2578 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true); 2579 if (LHS == RHS) 2580 return ConstantExpr::getICmp(Pred, 2581 ConstantExpr::getAdd(LHSOffset, LHSNoBound), 2582 ConstantExpr::getAdd(RHSOffset, RHSNoBound)); 2583 2584 // If one side of the equality comparison must come from a noalias call 2585 // (meaning a system memory allocation function), and the other side must 2586 // come from a pointer that cannot overlap with dynamically-allocated 2587 // memory within the lifetime of the current function (allocas, byval 2588 // arguments, globals), then determine the comparison result here. 2589 SmallVector<const Value *, 8> LHSUObjs, RHSUObjs; 2590 getUnderlyingObjects(LHS, LHSUObjs); 2591 getUnderlyingObjects(RHS, RHSUObjs); 2592 2593 // Is the set of underlying objects all noalias calls? 2594 auto IsNAC = [](ArrayRef<const Value *> Objects) { 2595 return all_of(Objects, isNoAliasCall); 2596 }; 2597 2598 // Is the set of underlying objects all things which must be disjoint from 2599 // noalias calls. For allocas, we consider only static ones (dynamic 2600 // allocas might be transformed into calls to malloc not simultaneously 2601 // live with the compared-to allocation). For globals, we exclude symbols 2602 // that might be resolve lazily to symbols in another dynamically-loaded 2603 // library (and, thus, could be malloc'ed by the implementation). 2604 auto IsAllocDisjoint = [](ArrayRef<const Value *> Objects) { 2605 return all_of(Objects, [](const Value *V) { 2606 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) 2607 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca(); 2608 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) 2609 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() || 2610 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) && 2611 !GV->isThreadLocal(); 2612 if (const Argument *A = dyn_cast<Argument>(V)) 2613 return A->hasByValAttr(); 2614 return false; 2615 }); 2616 }; 2617 2618 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) || 2619 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs))) 2620 return ConstantInt::get(GetCompareTy(LHS), 2621 !CmpInst::isTrueWhenEqual(Pred)); 2622 2623 // Fold comparisons for non-escaping pointer even if the allocation call 2624 // cannot be elided. We cannot fold malloc comparison to null. Also, the 2625 // dynamic allocation call could be either of the operands. 2626 Value *MI = nullptr; 2627 if (isAllocLikeFn(LHS, TLI) && 2628 llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT)) 2629 MI = LHS; 2630 else if (isAllocLikeFn(RHS, TLI) && 2631 llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT)) 2632 MI = RHS; 2633 // FIXME: We should also fold the compare when the pointer escapes, but the 2634 // compare dominates the pointer escape 2635 if (MI && !PointerMayBeCaptured(MI, true, true)) 2636 return ConstantInt::get(GetCompareTy(LHS), 2637 CmpInst::isFalseWhenEqual(Pred)); 2638 } 2639 2640 // Otherwise, fail. 2641 return nullptr; 2642 } 2643 2644 /// Fold an icmp when its operands have i1 scalar type. 2645 static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS, 2646 Value *RHS, const SimplifyQuery &Q) { 2647 Type *ITy = GetCompareTy(LHS); // The return type. 2648 Type *OpTy = LHS->getType(); // The operand type. 2649 if (!OpTy->isIntOrIntVectorTy(1)) 2650 return nullptr; 2651 2652 // A boolean compared to true/false can be simplified in 14 out of the 20 2653 // (10 predicates * 2 constants) possible combinations. Cases not handled here 2654 // require a 'not' of the LHS, so those must be transformed in InstCombine. 2655 if (match(RHS, m_Zero())) { 2656 switch (Pred) { 2657 case CmpInst::ICMP_NE: // X != 0 -> X 2658 case CmpInst::ICMP_UGT: // X >u 0 -> X 2659 case CmpInst::ICMP_SLT: // X <s 0 -> X 2660 return LHS; 2661 2662 case CmpInst::ICMP_ULT: // X <u 0 -> false 2663 case CmpInst::ICMP_SGT: // X >s 0 -> false 2664 return getFalse(ITy); 2665 2666 case CmpInst::ICMP_UGE: // X >=u 0 -> true 2667 case CmpInst::ICMP_SLE: // X <=s 0 -> true 2668 return getTrue(ITy); 2669 2670 default: break; 2671 } 2672 } else if (match(RHS, m_One())) { 2673 switch (Pred) { 2674 case CmpInst::ICMP_EQ: // X == 1 -> X 2675 case CmpInst::ICMP_UGE: // X >=u 1 -> X 2676 case CmpInst::ICMP_SLE: // X <=s -1 -> X 2677 return LHS; 2678 2679 case CmpInst::ICMP_UGT: // X >u 1 -> false 2680 case CmpInst::ICMP_SLT: // X <s -1 -> false 2681 return getFalse(ITy); 2682 2683 case CmpInst::ICMP_ULE: // X <=u 1 -> true 2684 case CmpInst::ICMP_SGE: // X >=s -1 -> true 2685 return getTrue(ITy); 2686 2687 default: break; 2688 } 2689 } 2690 2691 switch (Pred) { 2692 default: 2693 break; 2694 case ICmpInst::ICMP_UGE: 2695 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false)) 2696 return getTrue(ITy); 2697 break; 2698 case ICmpInst::ICMP_SGE: 2699 /// For signed comparison, the values for an i1 are 0 and -1 2700 /// respectively. This maps into a truth table of: 2701 /// LHS | RHS | LHS >=s RHS | LHS implies RHS 2702 /// 0 | 0 | 1 (0 >= 0) | 1 2703 /// 0 | 1 | 1 (0 >= -1) | 1 2704 /// 1 | 0 | 0 (-1 >= 0) | 0 2705 /// 1 | 1 | 1 (-1 >= -1) | 1 2706 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false)) 2707 return getTrue(ITy); 2708 break; 2709 case ICmpInst::ICMP_ULE: 2710 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false)) 2711 return getTrue(ITy); 2712 break; 2713 } 2714 2715 return nullptr; 2716 } 2717 2718 /// Try hard to fold icmp with zero RHS because this is a common case. 2719 static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS, 2720 Value *RHS, const SimplifyQuery &Q) { 2721 if (!match(RHS, m_Zero())) 2722 return nullptr; 2723 2724 Type *ITy = GetCompareTy(LHS); // The return type. 2725 switch (Pred) { 2726 default: 2727 llvm_unreachable("Unknown ICmp predicate!"); 2728 case ICmpInst::ICMP_ULT: 2729 return getFalse(ITy); 2730 case ICmpInst::ICMP_UGE: 2731 return getTrue(ITy); 2732 case ICmpInst::ICMP_EQ: 2733 case ICmpInst::ICMP_ULE: 2734 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) 2735 return getFalse(ITy); 2736 break; 2737 case ICmpInst::ICMP_NE: 2738 case ICmpInst::ICMP_UGT: 2739 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) 2740 return getTrue(ITy); 2741 break; 2742 case ICmpInst::ICMP_SLT: { 2743 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2744 if (LHSKnown.isNegative()) 2745 return getTrue(ITy); 2746 if (LHSKnown.isNonNegative()) 2747 return getFalse(ITy); 2748 break; 2749 } 2750 case ICmpInst::ICMP_SLE: { 2751 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2752 if (LHSKnown.isNegative()) 2753 return getTrue(ITy); 2754 if (LHSKnown.isNonNegative() && 2755 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) 2756 return getFalse(ITy); 2757 break; 2758 } 2759 case ICmpInst::ICMP_SGE: { 2760 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2761 if (LHSKnown.isNegative()) 2762 return getFalse(ITy); 2763 if (LHSKnown.isNonNegative()) 2764 return getTrue(ITy); 2765 break; 2766 } 2767 case ICmpInst::ICMP_SGT: { 2768 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2769 if (LHSKnown.isNegative()) 2770 return getFalse(ITy); 2771 if (LHSKnown.isNonNegative() && 2772 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) 2773 return getTrue(ITy); 2774 break; 2775 } 2776 } 2777 2778 return nullptr; 2779 } 2780 2781 static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS, 2782 Value *RHS, const InstrInfoQuery &IIQ) { 2783 Type *ITy = GetCompareTy(RHS); // The return type. 2784 2785 Value *X; 2786 // Sign-bit checks can be optimized to true/false after unsigned 2787 // floating-point casts: 2788 // icmp slt (bitcast (uitofp X)), 0 --> false 2789 // icmp sgt (bitcast (uitofp X)), -1 --> true 2790 if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) { 2791 if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero())) 2792 return ConstantInt::getFalse(ITy); 2793 if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes())) 2794 return ConstantInt::getTrue(ITy); 2795 } 2796 2797 const APInt *C; 2798 if (!match(RHS, m_APIntAllowUndef(C))) 2799 return nullptr; 2800 2801 // Rule out tautological comparisons (eg., ult 0 or uge 0). 2802 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C); 2803 if (RHS_CR.isEmptySet()) 2804 return ConstantInt::getFalse(ITy); 2805 if (RHS_CR.isFullSet()) 2806 return ConstantInt::getTrue(ITy); 2807 2808 ConstantRange LHS_CR = computeConstantRange(LHS, IIQ.UseInstrInfo); 2809 if (!LHS_CR.isFullSet()) { 2810 if (RHS_CR.contains(LHS_CR)) 2811 return ConstantInt::getTrue(ITy); 2812 if (RHS_CR.inverse().contains(LHS_CR)) 2813 return ConstantInt::getFalse(ITy); 2814 } 2815 2816 // (mul nuw/nsw X, MulC) != C --> true (if C is not a multiple of MulC) 2817 // (mul nuw/nsw X, MulC) == C --> false (if C is not a multiple of MulC) 2818 const APInt *MulC; 2819 if (ICmpInst::isEquality(Pred) && 2820 ((match(LHS, m_NUWMul(m_Value(), m_APIntAllowUndef(MulC))) && 2821 *MulC != 0 && C->urem(*MulC) != 0) || 2822 (match(LHS, m_NSWMul(m_Value(), m_APIntAllowUndef(MulC))) && 2823 *MulC != 0 && C->srem(*MulC) != 0))) 2824 return ConstantInt::get(ITy, Pred == ICmpInst::ICMP_NE); 2825 2826 return nullptr; 2827 } 2828 2829 static Value *simplifyICmpWithBinOpOnLHS( 2830 CmpInst::Predicate Pred, BinaryOperator *LBO, Value *RHS, 2831 const SimplifyQuery &Q, unsigned MaxRecurse) { 2832 Type *ITy = GetCompareTy(RHS); // The return type. 2833 2834 Value *Y = nullptr; 2835 // icmp pred (or X, Y), X 2836 if (match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) { 2837 if (Pred == ICmpInst::ICMP_ULT) 2838 return getFalse(ITy); 2839 if (Pred == ICmpInst::ICMP_UGE) 2840 return getTrue(ITy); 2841 2842 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) { 2843 KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2844 KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2845 if (RHSKnown.isNonNegative() && YKnown.isNegative()) 2846 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy); 2847 if (RHSKnown.isNegative() || YKnown.isNonNegative()) 2848 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy); 2849 } 2850 } 2851 2852 // icmp pred (and X, Y), X 2853 if (match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) { 2854 if (Pred == ICmpInst::ICMP_UGT) 2855 return getFalse(ITy); 2856 if (Pred == ICmpInst::ICMP_ULE) 2857 return getTrue(ITy); 2858 } 2859 2860 // icmp pred (urem X, Y), Y 2861 if (match(LBO, m_URem(m_Value(), m_Specific(RHS)))) { 2862 switch (Pred) { 2863 default: 2864 break; 2865 case ICmpInst::ICMP_SGT: 2866 case ICmpInst::ICMP_SGE: { 2867 KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2868 if (!Known.isNonNegative()) 2869 break; 2870 LLVM_FALLTHROUGH; 2871 } 2872 case ICmpInst::ICMP_EQ: 2873 case ICmpInst::ICMP_UGT: 2874 case ICmpInst::ICMP_UGE: 2875 return getFalse(ITy); 2876 case ICmpInst::ICMP_SLT: 2877 case ICmpInst::ICMP_SLE: { 2878 KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2879 if (!Known.isNonNegative()) 2880 break; 2881 LLVM_FALLTHROUGH; 2882 } 2883 case ICmpInst::ICMP_NE: 2884 case ICmpInst::ICMP_ULT: 2885 case ICmpInst::ICMP_ULE: 2886 return getTrue(ITy); 2887 } 2888 } 2889 2890 // icmp pred (urem X, Y), X 2891 if (match(LBO, m_URem(m_Specific(RHS), m_Value()))) { 2892 if (Pred == ICmpInst::ICMP_ULE) 2893 return getTrue(ITy); 2894 if (Pred == ICmpInst::ICMP_UGT) 2895 return getFalse(ITy); 2896 } 2897 2898 // x >> y <=u x 2899 // x udiv y <=u x. 2900 if (match(LBO, m_LShr(m_Specific(RHS), m_Value())) || 2901 match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) { 2902 // icmp pred (X op Y), X 2903 if (Pred == ICmpInst::ICMP_UGT) 2904 return getFalse(ITy); 2905 if (Pred == ICmpInst::ICMP_ULE) 2906 return getTrue(ITy); 2907 } 2908 2909 // (x*C1)/C2 <= x for C1 <= C2. 2910 // This holds even if the multiplication overflows: Assume that x != 0 and 2911 // arithmetic is modulo M. For overflow to occur we must have C1 >= M/x and 2912 // thus C2 >= M/x. It follows that (x*C1)/C2 <= (M-1)/C2 <= ((M-1)*x)/M < x. 2913 // 2914 // Additionally, either the multiplication and division might be represented 2915 // as shifts: 2916 // (x*C1)>>C2 <= x for C1 < 2**C2. 2917 // (x<<C1)/C2 <= x for 2**C1 < C2. 2918 const APInt *C1, *C2; 2919 if ((match(LBO, m_UDiv(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) && 2920 C1->ule(*C2)) || 2921 (match(LBO, m_LShr(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) && 2922 C1->ule(APInt(C2->getBitWidth(), 1) << *C2)) || 2923 (match(LBO, m_UDiv(m_Shl(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) && 2924 (APInt(C1->getBitWidth(), 1) << *C1).ule(*C2))) { 2925 if (Pred == ICmpInst::ICMP_UGT) 2926 return getFalse(ITy); 2927 if (Pred == ICmpInst::ICMP_ULE) 2928 return getTrue(ITy); 2929 } 2930 2931 return nullptr; 2932 } 2933 2934 2935 // If only one of the icmp's operands has NSW flags, try to prove that: 2936 // 2937 // icmp slt (x + C1), (x +nsw C2) 2938 // 2939 // is equivalent to: 2940 // 2941 // icmp slt C1, C2 2942 // 2943 // which is true if x + C2 has the NSW flags set and: 2944 // *) C1 < C2 && C1 >= 0, or 2945 // *) C2 < C1 && C1 <= 0. 2946 // 2947 static bool trySimplifyICmpWithAdds(CmpInst::Predicate Pred, Value *LHS, 2948 Value *RHS) { 2949 // TODO: only support icmp slt for now. 2950 if (Pred != CmpInst::ICMP_SLT) 2951 return false; 2952 2953 // Canonicalize nsw add as RHS. 2954 if (!match(RHS, m_NSWAdd(m_Value(), m_Value()))) 2955 std::swap(LHS, RHS); 2956 if (!match(RHS, m_NSWAdd(m_Value(), m_Value()))) 2957 return false; 2958 2959 Value *X; 2960 const APInt *C1, *C2; 2961 if (!match(LHS, m_c_Add(m_Value(X), m_APInt(C1))) || 2962 !match(RHS, m_c_Add(m_Specific(X), m_APInt(C2)))) 2963 return false; 2964 2965 return (C1->slt(*C2) && C1->isNonNegative()) || 2966 (C2->slt(*C1) && C1->isNonPositive()); 2967 } 2968 2969 2970 /// TODO: A large part of this logic is duplicated in InstCombine's 2971 /// foldICmpBinOp(). We should be able to share that and avoid the code 2972 /// duplication. 2973 static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS, 2974 Value *RHS, const SimplifyQuery &Q, 2975 unsigned MaxRecurse) { 2976 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS); 2977 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS); 2978 if (MaxRecurse && (LBO || RBO)) { 2979 // Analyze the case when either LHS or RHS is an add instruction. 2980 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr; 2981 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null). 2982 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false; 2983 if (LBO && LBO->getOpcode() == Instruction::Add) { 2984 A = LBO->getOperand(0); 2985 B = LBO->getOperand(1); 2986 NoLHSWrapProblem = 2987 ICmpInst::isEquality(Pred) || 2988 (CmpInst::isUnsigned(Pred) && 2989 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) || 2990 (CmpInst::isSigned(Pred) && 2991 Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO))); 2992 } 2993 if (RBO && RBO->getOpcode() == Instruction::Add) { 2994 C = RBO->getOperand(0); 2995 D = RBO->getOperand(1); 2996 NoRHSWrapProblem = 2997 ICmpInst::isEquality(Pred) || 2998 (CmpInst::isUnsigned(Pred) && 2999 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) || 3000 (CmpInst::isSigned(Pred) && 3001 Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO))); 3002 } 3003 3004 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow. 3005 if ((A == RHS || B == RHS) && NoLHSWrapProblem) 3006 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A, 3007 Constant::getNullValue(RHS->getType()), Q, 3008 MaxRecurse - 1)) 3009 return V; 3010 3011 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow. 3012 if ((C == LHS || D == LHS) && NoRHSWrapProblem) 3013 if (Value *V = 3014 SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()), 3015 C == LHS ? D : C, Q, MaxRecurse - 1)) 3016 return V; 3017 3018 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow. 3019 bool CanSimplify = (NoLHSWrapProblem && NoRHSWrapProblem) || 3020 trySimplifyICmpWithAdds(Pred, LHS, RHS); 3021 if (A && C && (A == C || A == D || B == C || B == D) && CanSimplify) { 3022 // Determine Y and Z in the form icmp (X+Y), (X+Z). 3023 Value *Y, *Z; 3024 if (A == C) { 3025 // C + B == C + D -> B == D 3026 Y = B; 3027 Z = D; 3028 } else if (A == D) { 3029 // D + B == C + D -> B == C 3030 Y = B; 3031 Z = C; 3032 } else if (B == C) { 3033 // A + C == C + D -> A == D 3034 Y = A; 3035 Z = D; 3036 } else { 3037 assert(B == D); 3038 // A + D == C + D -> A == C 3039 Y = A; 3040 Z = C; 3041 } 3042 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1)) 3043 return V; 3044 } 3045 } 3046 3047 if (LBO) 3048 if (Value *V = simplifyICmpWithBinOpOnLHS(Pred, LBO, RHS, Q, MaxRecurse)) 3049 return V; 3050 3051 if (RBO) 3052 if (Value *V = simplifyICmpWithBinOpOnLHS( 3053 ICmpInst::getSwappedPredicate(Pred), RBO, LHS, Q, MaxRecurse)) 3054 return V; 3055 3056 // 0 - (zext X) pred C 3057 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) { 3058 const APInt *C; 3059 if (match(RHS, m_APInt(C))) { 3060 if (C->isStrictlyPositive()) { 3061 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_NE) 3062 return ConstantInt::getTrue(GetCompareTy(RHS)); 3063 if (Pred == ICmpInst::ICMP_SGE || Pred == ICmpInst::ICMP_EQ) 3064 return ConstantInt::getFalse(GetCompareTy(RHS)); 3065 } 3066 if (C->isNonNegative()) { 3067 if (Pred == ICmpInst::ICMP_SLE) 3068 return ConstantInt::getTrue(GetCompareTy(RHS)); 3069 if (Pred == ICmpInst::ICMP_SGT) 3070 return ConstantInt::getFalse(GetCompareTy(RHS)); 3071 } 3072 } 3073 } 3074 3075 // If C2 is a power-of-2 and C is not: 3076 // (C2 << X) == C --> false 3077 // (C2 << X) != C --> true 3078 const APInt *C; 3079 if (match(LHS, m_Shl(m_Power2(), m_Value())) && 3080 match(RHS, m_APIntAllowUndef(C)) && !C->isPowerOf2()) { 3081 // C2 << X can equal zero in some circumstances. 3082 // This simplification might be unsafe if C is zero. 3083 // 3084 // We know it is safe if: 3085 // - The shift is nsw. We can't shift out the one bit. 3086 // - The shift is nuw. We can't shift out the one bit. 3087 // - C2 is one. 3088 // - C isn't zero. 3089 if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) || 3090 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) || 3091 match(LHS, m_Shl(m_One(), m_Value())) || !C->isNullValue()) { 3092 if (Pred == ICmpInst::ICMP_EQ) 3093 return ConstantInt::getFalse(GetCompareTy(RHS)); 3094 if (Pred == ICmpInst::ICMP_NE) 3095 return ConstantInt::getTrue(GetCompareTy(RHS)); 3096 } 3097 } 3098 3099 // TODO: This is overly constrained. LHS can be any power-of-2. 3100 // (1 << X) >u 0x8000 --> false 3101 // (1 << X) <=u 0x8000 --> true 3102 if (match(LHS, m_Shl(m_One(), m_Value())) && match(RHS, m_SignMask())) { 3103 if (Pred == ICmpInst::ICMP_UGT) 3104 return ConstantInt::getFalse(GetCompareTy(RHS)); 3105 if (Pred == ICmpInst::ICMP_ULE) 3106 return ConstantInt::getTrue(GetCompareTy(RHS)); 3107 } 3108 3109 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() && 3110 LBO->getOperand(1) == RBO->getOperand(1)) { 3111 switch (LBO->getOpcode()) { 3112 default: 3113 break; 3114 case Instruction::UDiv: 3115 case Instruction::LShr: 3116 if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) || 3117 !Q.IIQ.isExact(RBO)) 3118 break; 3119 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 3120 RBO->getOperand(0), Q, MaxRecurse - 1)) 3121 return V; 3122 break; 3123 case Instruction::SDiv: 3124 if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) || 3125 !Q.IIQ.isExact(RBO)) 3126 break; 3127 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 3128 RBO->getOperand(0), Q, MaxRecurse - 1)) 3129 return V; 3130 break; 3131 case Instruction::AShr: 3132 if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO)) 3133 break; 3134 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 3135 RBO->getOperand(0), Q, MaxRecurse - 1)) 3136 return V; 3137 break; 3138 case Instruction::Shl: { 3139 bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO); 3140 bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO); 3141 if (!NUW && !NSW) 3142 break; 3143 if (!NSW && ICmpInst::isSigned(Pred)) 3144 break; 3145 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 3146 RBO->getOperand(0), Q, MaxRecurse - 1)) 3147 return V; 3148 break; 3149 } 3150 } 3151 } 3152 return nullptr; 3153 } 3154 3155 /// Simplify integer comparisons where at least one operand of the compare 3156 /// matches an integer min/max idiom. 3157 static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS, 3158 Value *RHS, const SimplifyQuery &Q, 3159 unsigned MaxRecurse) { 3160 Type *ITy = GetCompareTy(LHS); // The return type. 3161 Value *A, *B; 3162 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE; 3163 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B". 3164 3165 // Signed variants on "max(a,b)>=a -> true". 3166 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) { 3167 if (A != RHS) 3168 std::swap(A, B); // smax(A, B) pred A. 3169 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B". 3170 // We analyze this as smax(A, B) pred A. 3171 P = Pred; 3172 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) && 3173 (A == LHS || B == LHS)) { 3174 if (A != LHS) 3175 std::swap(A, B); // A pred smax(A, B). 3176 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B". 3177 // We analyze this as smax(A, B) swapped-pred A. 3178 P = CmpInst::getSwappedPredicate(Pred); 3179 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) && 3180 (A == RHS || B == RHS)) { 3181 if (A != RHS) 3182 std::swap(A, B); // smin(A, B) pred A. 3183 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B". 3184 // We analyze this as smax(-A, -B) swapped-pred -A. 3185 // Note that we do not need to actually form -A or -B thanks to EqP. 3186 P = CmpInst::getSwappedPredicate(Pred); 3187 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) && 3188 (A == LHS || B == LHS)) { 3189 if (A != LHS) 3190 std::swap(A, B); // A pred smin(A, B). 3191 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B". 3192 // We analyze this as smax(-A, -B) pred -A. 3193 // Note that we do not need to actually form -A or -B thanks to EqP. 3194 P = Pred; 3195 } 3196 if (P != CmpInst::BAD_ICMP_PREDICATE) { 3197 // Cases correspond to "max(A, B) p A". 3198 switch (P) { 3199 default: 3200 break; 3201 case CmpInst::ICMP_EQ: 3202 case CmpInst::ICMP_SLE: 3203 // Equivalent to "A EqP B". This may be the same as the condition tested 3204 // in the max/min; if so, we can just return that. 3205 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B)) 3206 return V; 3207 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B)) 3208 return V; 3209 // Otherwise, see if "A EqP B" simplifies. 3210 if (MaxRecurse) 3211 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1)) 3212 return V; 3213 break; 3214 case CmpInst::ICMP_NE: 3215 case CmpInst::ICMP_SGT: { 3216 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP); 3217 // Equivalent to "A InvEqP B". This may be the same as the condition 3218 // tested in the max/min; if so, we can just return that. 3219 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B)) 3220 return V; 3221 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B)) 3222 return V; 3223 // Otherwise, see if "A InvEqP B" simplifies. 3224 if (MaxRecurse) 3225 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1)) 3226 return V; 3227 break; 3228 } 3229 case CmpInst::ICMP_SGE: 3230 // Always true. 3231 return getTrue(ITy); 3232 case CmpInst::ICMP_SLT: 3233 // Always false. 3234 return getFalse(ITy); 3235 } 3236 } 3237 3238 // Unsigned variants on "max(a,b)>=a -> true". 3239 P = CmpInst::BAD_ICMP_PREDICATE; 3240 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) { 3241 if (A != RHS) 3242 std::swap(A, B); // umax(A, B) pred A. 3243 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B". 3244 // We analyze this as umax(A, B) pred A. 3245 P = Pred; 3246 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) && 3247 (A == LHS || B == LHS)) { 3248 if (A != LHS) 3249 std::swap(A, B); // A pred umax(A, B). 3250 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B". 3251 // We analyze this as umax(A, B) swapped-pred A. 3252 P = CmpInst::getSwappedPredicate(Pred); 3253 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) && 3254 (A == RHS || B == RHS)) { 3255 if (A != RHS) 3256 std::swap(A, B); // umin(A, B) pred A. 3257 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B". 3258 // We analyze this as umax(-A, -B) swapped-pred -A. 3259 // Note that we do not need to actually form -A or -B thanks to EqP. 3260 P = CmpInst::getSwappedPredicate(Pred); 3261 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) && 3262 (A == LHS || B == LHS)) { 3263 if (A != LHS) 3264 std::swap(A, B); // A pred umin(A, B). 3265 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B". 3266 // We analyze this as umax(-A, -B) pred -A. 3267 // Note that we do not need to actually form -A or -B thanks to EqP. 3268 P = Pred; 3269 } 3270 if (P != CmpInst::BAD_ICMP_PREDICATE) { 3271 // Cases correspond to "max(A, B) p A". 3272 switch (P) { 3273 default: 3274 break; 3275 case CmpInst::ICMP_EQ: 3276 case CmpInst::ICMP_ULE: 3277 // Equivalent to "A EqP B". This may be the same as the condition tested 3278 // in the max/min; if so, we can just return that. 3279 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B)) 3280 return V; 3281 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B)) 3282 return V; 3283 // Otherwise, see if "A EqP B" simplifies. 3284 if (MaxRecurse) 3285 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1)) 3286 return V; 3287 break; 3288 case CmpInst::ICMP_NE: 3289 case CmpInst::ICMP_UGT: { 3290 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP); 3291 // Equivalent to "A InvEqP B". This may be the same as the condition 3292 // tested in the max/min; if so, we can just return that. 3293 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B)) 3294 return V; 3295 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B)) 3296 return V; 3297 // Otherwise, see if "A InvEqP B" simplifies. 3298 if (MaxRecurse) 3299 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1)) 3300 return V; 3301 break; 3302 } 3303 case CmpInst::ICMP_UGE: 3304 return getTrue(ITy); 3305 case CmpInst::ICMP_ULT: 3306 return getFalse(ITy); 3307 } 3308 } 3309 3310 // Comparing 1 each of min/max with a common operand? 3311 // Canonicalize min operand to RHS. 3312 if (match(LHS, m_UMin(m_Value(), m_Value())) || 3313 match(LHS, m_SMin(m_Value(), m_Value()))) { 3314 std::swap(LHS, RHS); 3315 Pred = ICmpInst::getSwappedPredicate(Pred); 3316 } 3317 3318 Value *C, *D; 3319 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && 3320 match(RHS, m_SMin(m_Value(C), m_Value(D))) && 3321 (A == C || A == D || B == C || B == D)) { 3322 // smax(A, B) >=s smin(A, D) --> true 3323 if (Pred == CmpInst::ICMP_SGE) 3324 return getTrue(ITy); 3325 // smax(A, B) <s smin(A, D) --> false 3326 if (Pred == CmpInst::ICMP_SLT) 3327 return getFalse(ITy); 3328 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && 3329 match(RHS, m_UMin(m_Value(C), m_Value(D))) && 3330 (A == C || A == D || B == C || B == D)) { 3331 // umax(A, B) >=u umin(A, D) --> true 3332 if (Pred == CmpInst::ICMP_UGE) 3333 return getTrue(ITy); 3334 // umax(A, B) <u umin(A, D) --> false 3335 if (Pred == CmpInst::ICMP_ULT) 3336 return getFalse(ITy); 3337 } 3338 3339 return nullptr; 3340 } 3341 3342 static Value *simplifyICmpWithDominatingAssume(CmpInst::Predicate Predicate, 3343 Value *LHS, Value *RHS, 3344 const SimplifyQuery &Q) { 3345 // Gracefully handle instructions that have not been inserted yet. 3346 if (!Q.AC || !Q.CxtI || !Q.CxtI->getParent()) 3347 return nullptr; 3348 3349 for (Value *AssumeBaseOp : {LHS, RHS}) { 3350 for (auto &AssumeVH : Q.AC->assumptionsFor(AssumeBaseOp)) { 3351 if (!AssumeVH) 3352 continue; 3353 3354 CallInst *Assume = cast<CallInst>(AssumeVH); 3355 if (Optional<bool> Imp = 3356 isImpliedCondition(Assume->getArgOperand(0), Predicate, LHS, RHS, 3357 Q.DL)) 3358 if (isValidAssumeForContext(Assume, Q.CxtI, Q.DT)) 3359 return ConstantInt::get(GetCompareTy(LHS), *Imp); 3360 } 3361 } 3362 3363 return nullptr; 3364 } 3365 3366 /// Given operands for an ICmpInst, see if we can fold the result. 3367 /// If not, this returns null. 3368 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, 3369 const SimplifyQuery &Q, unsigned MaxRecurse) { 3370 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate; 3371 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!"); 3372 3373 if (Constant *CLHS = dyn_cast<Constant>(LHS)) { 3374 if (Constant *CRHS = dyn_cast<Constant>(RHS)) 3375 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI); 3376 3377 // If we have a constant, make sure it is on the RHS. 3378 std::swap(LHS, RHS); 3379 Pred = CmpInst::getSwappedPredicate(Pred); 3380 } 3381 assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X"); 3382 3383 Type *ITy = GetCompareTy(LHS); // The return type. 3384 3385 // icmp poison, X -> poison 3386 if (isa<PoisonValue>(RHS)) 3387 return PoisonValue::get(ITy); 3388 3389 // For EQ and NE, we can always pick a value for the undef to make the 3390 // predicate pass or fail, so we can return undef. 3391 // Matches behavior in llvm::ConstantFoldCompareInstruction. 3392 if (Q.isUndefValue(RHS) && ICmpInst::isEquality(Pred)) 3393 return UndefValue::get(ITy); 3394 3395 // icmp X, X -> true/false 3396 // icmp X, undef -> true/false because undef could be X. 3397 if (LHS == RHS || Q.isUndefValue(RHS)) 3398 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred)); 3399 3400 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q)) 3401 return V; 3402 3403 // TODO: Sink/common this with other potentially expensive calls that use 3404 // ValueTracking? See comment below for isKnownNonEqual(). 3405 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q)) 3406 return V; 3407 3408 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ)) 3409 return V; 3410 3411 // If both operands have range metadata, use the metadata 3412 // to simplify the comparison. 3413 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) { 3414 auto RHS_Instr = cast<Instruction>(RHS); 3415 auto LHS_Instr = cast<Instruction>(LHS); 3416 3417 if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) && 3418 Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) { 3419 auto RHS_CR = getConstantRangeFromMetadata( 3420 *RHS_Instr->getMetadata(LLVMContext::MD_range)); 3421 auto LHS_CR = getConstantRangeFromMetadata( 3422 *LHS_Instr->getMetadata(LLVMContext::MD_range)); 3423 3424 if (LHS_CR.icmp(Pred, RHS_CR)) 3425 return ConstantInt::getTrue(RHS->getContext()); 3426 3427 if (LHS_CR.icmp(CmpInst::getInversePredicate(Pred), RHS_CR)) 3428 return ConstantInt::getFalse(RHS->getContext()); 3429 } 3430 } 3431 3432 // Compare of cast, for example (zext X) != 0 -> X != 0 3433 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) { 3434 Instruction *LI = cast<CastInst>(LHS); 3435 Value *SrcOp = LI->getOperand(0); 3436 Type *SrcTy = SrcOp->getType(); 3437 Type *DstTy = LI->getType(); 3438 3439 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input 3440 // if the integer type is the same size as the pointer type. 3441 if (MaxRecurse && isa<PtrToIntInst>(LI) && 3442 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) { 3443 if (Constant *RHSC = dyn_cast<Constant>(RHS)) { 3444 // Transfer the cast to the constant. 3445 if (Value *V = SimplifyICmpInst(Pred, SrcOp, 3446 ConstantExpr::getIntToPtr(RHSC, SrcTy), 3447 Q, MaxRecurse-1)) 3448 return V; 3449 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) { 3450 if (RI->getOperand(0)->getType() == SrcTy) 3451 // Compare without the cast. 3452 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0), 3453 Q, MaxRecurse-1)) 3454 return V; 3455 } 3456 } 3457 3458 if (isa<ZExtInst>(LHS)) { 3459 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the 3460 // same type. 3461 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) { 3462 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType()) 3463 // Compare X and Y. Note that signed predicates become unsigned. 3464 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), 3465 SrcOp, RI->getOperand(0), Q, 3466 MaxRecurse-1)) 3467 return V; 3468 } 3469 // Fold (zext X) ule (sext X), (zext X) sge (sext X) to true. 3470 else if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) { 3471 if (SrcOp == RI->getOperand(0)) { 3472 if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_SGE) 3473 return ConstantInt::getTrue(ITy); 3474 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SLT) 3475 return ConstantInt::getFalse(ITy); 3476 } 3477 } 3478 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended 3479 // too. If not, then try to deduce the result of the comparison. 3480 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 3481 // Compute the constant that would happen if we truncated to SrcTy then 3482 // reextended to DstTy. 3483 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy); 3484 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy); 3485 3486 // If the re-extended constant didn't change then this is effectively 3487 // also a case of comparing two zero-extended values. 3488 if (RExt == CI && MaxRecurse) 3489 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), 3490 SrcOp, Trunc, Q, MaxRecurse-1)) 3491 return V; 3492 3493 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit 3494 // there. Use this to work out the result of the comparison. 3495 if (RExt != CI) { 3496 switch (Pred) { 3497 default: llvm_unreachable("Unknown ICmp predicate!"); 3498 // LHS <u RHS. 3499 case ICmpInst::ICMP_EQ: 3500 case ICmpInst::ICMP_UGT: 3501 case ICmpInst::ICMP_UGE: 3502 return ConstantInt::getFalse(CI->getContext()); 3503 3504 case ICmpInst::ICMP_NE: 3505 case ICmpInst::ICMP_ULT: 3506 case ICmpInst::ICMP_ULE: 3507 return ConstantInt::getTrue(CI->getContext()); 3508 3509 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS 3510 // is non-negative then LHS <s RHS. 3511 case ICmpInst::ICMP_SGT: 3512 case ICmpInst::ICMP_SGE: 3513 return CI->getValue().isNegative() ? 3514 ConstantInt::getTrue(CI->getContext()) : 3515 ConstantInt::getFalse(CI->getContext()); 3516 3517 case ICmpInst::ICMP_SLT: 3518 case ICmpInst::ICMP_SLE: 3519 return CI->getValue().isNegative() ? 3520 ConstantInt::getFalse(CI->getContext()) : 3521 ConstantInt::getTrue(CI->getContext()); 3522 } 3523 } 3524 } 3525 } 3526 3527 if (isa<SExtInst>(LHS)) { 3528 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the 3529 // same type. 3530 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) { 3531 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType()) 3532 // Compare X and Y. Note that the predicate does not change. 3533 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0), 3534 Q, MaxRecurse-1)) 3535 return V; 3536 } 3537 // Fold (sext X) uge (zext X), (sext X) sle (zext X) to true. 3538 else if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) { 3539 if (SrcOp == RI->getOperand(0)) { 3540 if (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_SLE) 3541 return ConstantInt::getTrue(ITy); 3542 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SGT) 3543 return ConstantInt::getFalse(ITy); 3544 } 3545 } 3546 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended 3547 // too. If not, then try to deduce the result of the comparison. 3548 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 3549 // Compute the constant that would happen if we truncated to SrcTy then 3550 // reextended to DstTy. 3551 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy); 3552 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy); 3553 3554 // If the re-extended constant didn't change then this is effectively 3555 // also a case of comparing two sign-extended values. 3556 if (RExt == CI && MaxRecurse) 3557 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1)) 3558 return V; 3559 3560 // Otherwise the upper bits of LHS are all equal, while RHS has varying 3561 // bits there. Use this to work out the result of the comparison. 3562 if (RExt != CI) { 3563 switch (Pred) { 3564 default: llvm_unreachable("Unknown ICmp predicate!"); 3565 case ICmpInst::ICMP_EQ: 3566 return ConstantInt::getFalse(CI->getContext()); 3567 case ICmpInst::ICMP_NE: 3568 return ConstantInt::getTrue(CI->getContext()); 3569 3570 // If RHS is non-negative then LHS <s RHS. If RHS is negative then 3571 // LHS >s RHS. 3572 case ICmpInst::ICMP_SGT: 3573 case ICmpInst::ICMP_SGE: 3574 return CI->getValue().isNegative() ? 3575 ConstantInt::getTrue(CI->getContext()) : 3576 ConstantInt::getFalse(CI->getContext()); 3577 case ICmpInst::ICMP_SLT: 3578 case ICmpInst::ICMP_SLE: 3579 return CI->getValue().isNegative() ? 3580 ConstantInt::getFalse(CI->getContext()) : 3581 ConstantInt::getTrue(CI->getContext()); 3582 3583 // If LHS is non-negative then LHS <u RHS. If LHS is negative then 3584 // LHS >u RHS. 3585 case ICmpInst::ICMP_UGT: 3586 case ICmpInst::ICMP_UGE: 3587 // Comparison is true iff the LHS <s 0. 3588 if (MaxRecurse) 3589 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp, 3590 Constant::getNullValue(SrcTy), 3591 Q, MaxRecurse-1)) 3592 return V; 3593 break; 3594 case ICmpInst::ICMP_ULT: 3595 case ICmpInst::ICMP_ULE: 3596 // Comparison is true iff the LHS >=s 0. 3597 if (MaxRecurse) 3598 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp, 3599 Constant::getNullValue(SrcTy), 3600 Q, MaxRecurse-1)) 3601 return V; 3602 break; 3603 } 3604 } 3605 } 3606 } 3607 } 3608 3609 // icmp eq|ne X, Y -> false|true if X != Y 3610 // This is potentially expensive, and we have already computedKnownBits for 3611 // compares with 0 above here, so only try this for a non-zero compare. 3612 if (ICmpInst::isEquality(Pred) && !match(RHS, m_Zero()) && 3613 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) { 3614 return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy); 3615 } 3616 3617 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse)) 3618 return V; 3619 3620 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse)) 3621 return V; 3622 3623 if (Value *V = simplifyICmpWithDominatingAssume(Pred, LHS, RHS, Q)) 3624 return V; 3625 3626 // Simplify comparisons of related pointers using a powerful, recursive 3627 // GEP-walk when we have target data available.. 3628 if (LHS->getType()->isPointerTy()) 3629 if (auto *C = computePointerICmp(Pred, LHS, RHS, Q)) 3630 return C; 3631 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS)) 3632 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS)) 3633 if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) == 3634 Q.DL.getTypeSizeInBits(CLHS->getType()) && 3635 Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) == 3636 Q.DL.getTypeSizeInBits(CRHS->getType())) 3637 if (auto *C = computePointerICmp(Pred, CLHS->getPointerOperand(), 3638 CRHS->getPointerOperand(), Q)) 3639 return C; 3640 3641 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) { 3642 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) { 3643 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() && 3644 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() && 3645 (ICmpInst::isEquality(Pred) || 3646 (GLHS->isInBounds() && GRHS->isInBounds() && 3647 Pred == ICmpInst::getSignedPredicate(Pred)))) { 3648 // The bases are equal and the indices are constant. Build a constant 3649 // expression GEP with the same indices and a null base pointer to see 3650 // what constant folding can make out of it. 3651 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType()); 3652 SmallVector<Value *, 4> IndicesLHS(GLHS->indices()); 3653 Constant *NewLHS = ConstantExpr::getGetElementPtr( 3654 GLHS->getSourceElementType(), Null, IndicesLHS); 3655 3656 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end()); 3657 Constant *NewRHS = ConstantExpr::getGetElementPtr( 3658 GLHS->getSourceElementType(), Null, IndicesRHS); 3659 Constant *NewICmp = ConstantExpr::getICmp(Pred, NewLHS, NewRHS); 3660 return ConstantFoldConstant(NewICmp, Q.DL); 3661 } 3662 } 3663 } 3664 3665 // If the comparison is with the result of a select instruction, check whether 3666 // comparing with either branch of the select always yields the same value. 3667 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)) 3668 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse)) 3669 return V; 3670 3671 // If the comparison is with the result of a phi instruction, check whether 3672 // doing the compare with each incoming phi value yields a common result. 3673 if (isa<PHINode>(LHS) || isa<PHINode>(RHS)) 3674 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse)) 3675 return V; 3676 3677 return nullptr; 3678 } 3679 3680 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, 3681 const SimplifyQuery &Q) { 3682 return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit); 3683 } 3684 3685 /// Given operands for an FCmpInst, see if we can fold the result. 3686 /// If not, this returns null. 3687 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 3688 FastMathFlags FMF, const SimplifyQuery &Q, 3689 unsigned MaxRecurse) { 3690 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate; 3691 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!"); 3692 3693 if (Constant *CLHS = dyn_cast<Constant>(LHS)) { 3694 if (Constant *CRHS = dyn_cast<Constant>(RHS)) 3695 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI); 3696 3697 // If we have a constant, make sure it is on the RHS. 3698 std::swap(LHS, RHS); 3699 Pred = CmpInst::getSwappedPredicate(Pred); 3700 } 3701 3702 // Fold trivial predicates. 3703 Type *RetTy = GetCompareTy(LHS); 3704 if (Pred == FCmpInst::FCMP_FALSE) 3705 return getFalse(RetTy); 3706 if (Pred == FCmpInst::FCMP_TRUE) 3707 return getTrue(RetTy); 3708 3709 // Fold (un)ordered comparison if we can determine there are no NaNs. 3710 if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD) 3711 if (FMF.noNaNs() || 3712 (isKnownNeverNaN(LHS, Q.TLI) && isKnownNeverNaN(RHS, Q.TLI))) 3713 return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD); 3714 3715 // NaN is unordered; NaN is not ordered. 3716 assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) && 3717 "Comparison must be either ordered or unordered"); 3718 if (match(RHS, m_NaN())) 3719 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred)); 3720 3721 // fcmp pred x, poison and fcmp pred poison, x 3722 // fold to poison 3723 if (isa<PoisonValue>(LHS) || isa<PoisonValue>(RHS)) 3724 return PoisonValue::get(RetTy); 3725 3726 // fcmp pred x, undef and fcmp pred undef, x 3727 // fold to true if unordered, false if ordered 3728 if (Q.isUndefValue(LHS) || Q.isUndefValue(RHS)) { 3729 // Choosing NaN for the undef will always make unordered comparison succeed 3730 // and ordered comparison fail. 3731 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred)); 3732 } 3733 3734 // fcmp x,x -> true/false. Not all compares are foldable. 3735 if (LHS == RHS) { 3736 if (CmpInst::isTrueWhenEqual(Pred)) 3737 return getTrue(RetTy); 3738 if (CmpInst::isFalseWhenEqual(Pred)) 3739 return getFalse(RetTy); 3740 } 3741 3742 // Handle fcmp with constant RHS. 3743 // TODO: Use match with a specific FP value, so these work with vectors with 3744 // undef lanes. 3745 const APFloat *C; 3746 if (match(RHS, m_APFloat(C))) { 3747 // Check whether the constant is an infinity. 3748 if (C->isInfinity()) { 3749 if (C->isNegative()) { 3750 switch (Pred) { 3751 case FCmpInst::FCMP_OLT: 3752 // No value is ordered and less than negative infinity. 3753 return getFalse(RetTy); 3754 case FCmpInst::FCMP_UGE: 3755 // All values are unordered with or at least negative infinity. 3756 return getTrue(RetTy); 3757 default: 3758 break; 3759 } 3760 } else { 3761 switch (Pred) { 3762 case FCmpInst::FCMP_OGT: 3763 // No value is ordered and greater than infinity. 3764 return getFalse(RetTy); 3765 case FCmpInst::FCMP_ULE: 3766 // All values are unordered with and at most infinity. 3767 return getTrue(RetTy); 3768 default: 3769 break; 3770 } 3771 } 3772 3773 // LHS == Inf 3774 if (Pred == FCmpInst::FCMP_OEQ && isKnownNeverInfinity(LHS, Q.TLI)) 3775 return getFalse(RetTy); 3776 // LHS != Inf 3777 if (Pred == FCmpInst::FCMP_UNE && isKnownNeverInfinity(LHS, Q.TLI)) 3778 return getTrue(RetTy); 3779 // LHS == Inf || LHS == NaN 3780 if (Pred == FCmpInst::FCMP_UEQ && isKnownNeverInfinity(LHS, Q.TLI) && 3781 isKnownNeverNaN(LHS, Q.TLI)) 3782 return getFalse(RetTy); 3783 // LHS != Inf && LHS != NaN 3784 if (Pred == FCmpInst::FCMP_ONE && isKnownNeverInfinity(LHS, Q.TLI) && 3785 isKnownNeverNaN(LHS, Q.TLI)) 3786 return getTrue(RetTy); 3787 } 3788 if (C->isNegative() && !C->isNegZero()) { 3789 assert(!C->isNaN() && "Unexpected NaN constant!"); 3790 // TODO: We can catch more cases by using a range check rather than 3791 // relying on CannotBeOrderedLessThanZero. 3792 switch (Pred) { 3793 case FCmpInst::FCMP_UGE: 3794 case FCmpInst::FCMP_UGT: 3795 case FCmpInst::FCMP_UNE: 3796 // (X >= 0) implies (X > C) when (C < 0) 3797 if (CannotBeOrderedLessThanZero(LHS, Q.TLI)) 3798 return getTrue(RetTy); 3799 break; 3800 case FCmpInst::FCMP_OEQ: 3801 case FCmpInst::FCMP_OLE: 3802 case FCmpInst::FCMP_OLT: 3803 // (X >= 0) implies !(X < C) when (C < 0) 3804 if (CannotBeOrderedLessThanZero(LHS, Q.TLI)) 3805 return getFalse(RetTy); 3806 break; 3807 default: 3808 break; 3809 } 3810 } 3811 3812 // Check comparison of [minnum/maxnum with constant] with other constant. 3813 const APFloat *C2; 3814 if ((match(LHS, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_APFloat(C2))) && 3815 *C2 < *C) || 3816 (match(LHS, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_APFloat(C2))) && 3817 *C2 > *C)) { 3818 bool IsMaxNum = 3819 cast<IntrinsicInst>(LHS)->getIntrinsicID() == Intrinsic::maxnum; 3820 // The ordered relationship and minnum/maxnum guarantee that we do not 3821 // have NaN constants, so ordered/unordered preds are handled the same. 3822 switch (Pred) { 3823 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_UEQ: 3824 // minnum(X, LesserC) == C --> false 3825 // maxnum(X, GreaterC) == C --> false 3826 return getFalse(RetTy); 3827 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_UNE: 3828 // minnum(X, LesserC) != C --> true 3829 // maxnum(X, GreaterC) != C --> true 3830 return getTrue(RetTy); 3831 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_UGE: 3832 case FCmpInst::FCMP_OGT: case FCmpInst::FCMP_UGT: 3833 // minnum(X, LesserC) >= C --> false 3834 // minnum(X, LesserC) > C --> false 3835 // maxnum(X, GreaterC) >= C --> true 3836 // maxnum(X, GreaterC) > C --> true 3837 return ConstantInt::get(RetTy, IsMaxNum); 3838 case FCmpInst::FCMP_OLE: case FCmpInst::FCMP_ULE: 3839 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_ULT: 3840 // minnum(X, LesserC) <= C --> true 3841 // minnum(X, LesserC) < C --> true 3842 // maxnum(X, GreaterC) <= C --> false 3843 // maxnum(X, GreaterC) < C --> false 3844 return ConstantInt::get(RetTy, !IsMaxNum); 3845 default: 3846 // TRUE/FALSE/ORD/UNO should be handled before this. 3847 llvm_unreachable("Unexpected fcmp predicate"); 3848 } 3849 } 3850 } 3851 3852 if (match(RHS, m_AnyZeroFP())) { 3853 switch (Pred) { 3854 case FCmpInst::FCMP_OGE: 3855 case FCmpInst::FCMP_ULT: 3856 // Positive or zero X >= 0.0 --> true 3857 // Positive or zero X < 0.0 --> false 3858 if ((FMF.noNaNs() || isKnownNeverNaN(LHS, Q.TLI)) && 3859 CannotBeOrderedLessThanZero(LHS, Q.TLI)) 3860 return Pred == FCmpInst::FCMP_OGE ? getTrue(RetTy) : getFalse(RetTy); 3861 break; 3862 case FCmpInst::FCMP_UGE: 3863 case FCmpInst::FCMP_OLT: 3864 // Positive or zero or nan X >= 0.0 --> true 3865 // Positive or zero or nan X < 0.0 --> false 3866 if (CannotBeOrderedLessThanZero(LHS, Q.TLI)) 3867 return Pred == FCmpInst::FCMP_UGE ? getTrue(RetTy) : getFalse(RetTy); 3868 break; 3869 default: 3870 break; 3871 } 3872 } 3873 3874 // If the comparison is with the result of a select instruction, check whether 3875 // comparing with either branch of the select always yields the same value. 3876 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)) 3877 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse)) 3878 return V; 3879 3880 // If the comparison is with the result of a phi instruction, check whether 3881 // doing the compare with each incoming phi value yields a common result. 3882 if (isa<PHINode>(LHS) || isa<PHINode>(RHS)) 3883 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse)) 3884 return V; 3885 3886 return nullptr; 3887 } 3888 3889 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 3890 FastMathFlags FMF, const SimplifyQuery &Q) { 3891 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit); 3892 } 3893 3894 static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp, 3895 const SimplifyQuery &Q, 3896 bool AllowRefinement, 3897 unsigned MaxRecurse) { 3898 assert(!Op->getType()->isVectorTy() && "This is not safe for vectors"); 3899 3900 // Trivial replacement. 3901 if (V == Op) 3902 return RepOp; 3903 3904 // We cannot replace a constant, and shouldn't even try. 3905 if (isa<Constant>(Op)) 3906 return nullptr; 3907 3908 auto *I = dyn_cast<Instruction>(V); 3909 if (!I || !is_contained(I->operands(), Op)) 3910 return nullptr; 3911 3912 // Replace Op with RepOp in instruction operands. 3913 SmallVector<Value *, 8> NewOps(I->getNumOperands()); 3914 transform(I->operands(), NewOps.begin(), 3915 [&](Value *V) { return V == Op ? RepOp : V; }); 3916 3917 if (!AllowRefinement) { 3918 // General InstSimplify functions may refine the result, e.g. by returning 3919 // a constant for a potentially poison value. To avoid this, implement only 3920 // a few non-refining but profitable transforms here. 3921 3922 if (auto *BO = dyn_cast<BinaryOperator>(I)) { 3923 unsigned Opcode = BO->getOpcode(); 3924 // id op x -> x, x op id -> x 3925 if (NewOps[0] == ConstantExpr::getBinOpIdentity(Opcode, I->getType())) 3926 return NewOps[1]; 3927 if (NewOps[1] == ConstantExpr::getBinOpIdentity(Opcode, I->getType(), 3928 /* RHS */ true)) 3929 return NewOps[0]; 3930 3931 // x & x -> x, x | x -> x 3932 if ((Opcode == Instruction::And || Opcode == Instruction::Or) && 3933 NewOps[0] == NewOps[1]) 3934 return NewOps[0]; 3935 } 3936 3937 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) { 3938 // getelementptr x, 0 -> x 3939 if (NewOps.size() == 2 && match(NewOps[1], m_Zero()) && 3940 !GEP->isInBounds()) 3941 return NewOps[0]; 3942 } 3943 } else if (MaxRecurse) { 3944 // The simplification queries below may return the original value. Consider: 3945 // %div = udiv i32 %arg, %arg2 3946 // %mul = mul nsw i32 %div, %arg2 3947 // %cmp = icmp eq i32 %mul, %arg 3948 // %sel = select i1 %cmp, i32 %div, i32 undef 3949 // Replacing %arg by %mul, %div becomes "udiv i32 %mul, %arg2", which 3950 // simplifies back to %arg. This can only happen because %mul does not 3951 // dominate %div. To ensure a consistent return value contract, we make sure 3952 // that this case returns nullptr as well. 3953 auto PreventSelfSimplify = [V](Value *Simplified) { 3954 return Simplified != V ? Simplified : nullptr; 3955 }; 3956 3957 if (auto *B = dyn_cast<BinaryOperator>(I)) 3958 return PreventSelfSimplify(SimplifyBinOp(B->getOpcode(), NewOps[0], 3959 NewOps[1], Q, MaxRecurse - 1)); 3960 3961 if (CmpInst *C = dyn_cast<CmpInst>(I)) 3962 return PreventSelfSimplify(SimplifyCmpInst(C->getPredicate(), NewOps[0], 3963 NewOps[1], Q, MaxRecurse - 1)); 3964 3965 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) 3966 return PreventSelfSimplify(SimplifyGEPInst(GEP->getSourceElementType(), 3967 NewOps, Q, MaxRecurse - 1)); 3968 3969 if (isa<SelectInst>(I)) 3970 return PreventSelfSimplify( 3971 SimplifySelectInst(NewOps[0], NewOps[1], NewOps[2], Q, 3972 MaxRecurse - 1)); 3973 // TODO: We could hand off more cases to instsimplify here. 3974 } 3975 3976 // If all operands are constant after substituting Op for RepOp then we can 3977 // constant fold the instruction. 3978 SmallVector<Constant *, 8> ConstOps; 3979 for (Value *NewOp : NewOps) { 3980 if (Constant *ConstOp = dyn_cast<Constant>(NewOp)) 3981 ConstOps.push_back(ConstOp); 3982 else 3983 return nullptr; 3984 } 3985 3986 // Consider: 3987 // %cmp = icmp eq i32 %x, 2147483647 3988 // %add = add nsw i32 %x, 1 3989 // %sel = select i1 %cmp, i32 -2147483648, i32 %add 3990 // 3991 // We can't replace %sel with %add unless we strip away the flags (which 3992 // will be done in InstCombine). 3993 // TODO: This may be unsound, because it only catches some forms of 3994 // refinement. 3995 if (!AllowRefinement && canCreatePoison(cast<Operator>(I))) 3996 return nullptr; 3997 3998 if (CmpInst *C = dyn_cast<CmpInst>(I)) 3999 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0], 4000 ConstOps[1], Q.DL, Q.TLI); 4001 4002 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 4003 if (!LI->isVolatile()) 4004 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL); 4005 4006 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI); 4007 } 4008 4009 Value *llvm::simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp, 4010 const SimplifyQuery &Q, 4011 bool AllowRefinement) { 4012 return ::simplifyWithOpReplaced(V, Op, RepOp, Q, AllowRefinement, 4013 RecursionLimit); 4014 } 4015 4016 /// Try to simplify a select instruction when its condition operand is an 4017 /// integer comparison where one operand of the compare is a constant. 4018 static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X, 4019 const APInt *Y, bool TrueWhenUnset) { 4020 const APInt *C; 4021 4022 // (X & Y) == 0 ? X & ~Y : X --> X 4023 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y 4024 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) && 4025 *Y == ~*C) 4026 return TrueWhenUnset ? FalseVal : TrueVal; 4027 4028 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y 4029 // (X & Y) != 0 ? X : X & ~Y --> X 4030 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) && 4031 *Y == ~*C) 4032 return TrueWhenUnset ? FalseVal : TrueVal; 4033 4034 if (Y->isPowerOf2()) { 4035 // (X & Y) == 0 ? X | Y : X --> X | Y 4036 // (X & Y) != 0 ? X | Y : X --> X 4037 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) && 4038 *Y == *C) 4039 return TrueWhenUnset ? TrueVal : FalseVal; 4040 4041 // (X & Y) == 0 ? X : X | Y --> X 4042 // (X & Y) != 0 ? X : X | Y --> X | Y 4043 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) && 4044 *Y == *C) 4045 return TrueWhenUnset ? TrueVal : FalseVal; 4046 } 4047 4048 return nullptr; 4049 } 4050 4051 /// An alternative way to test if a bit is set or not uses sgt/slt instead of 4052 /// eq/ne. 4053 static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS, 4054 ICmpInst::Predicate Pred, 4055 Value *TrueVal, Value *FalseVal) { 4056 Value *X; 4057 APInt Mask; 4058 if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask)) 4059 return nullptr; 4060 4061 return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask, 4062 Pred == ICmpInst::ICMP_EQ); 4063 } 4064 4065 /// Try to simplify a select instruction when its condition operand is an 4066 /// integer comparison. 4067 static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal, 4068 Value *FalseVal, const SimplifyQuery &Q, 4069 unsigned MaxRecurse) { 4070 ICmpInst::Predicate Pred; 4071 Value *CmpLHS, *CmpRHS; 4072 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS)))) 4073 return nullptr; 4074 4075 // Canonicalize ne to eq predicate. 4076 if (Pred == ICmpInst::ICMP_NE) { 4077 Pred = ICmpInst::ICMP_EQ; 4078 std::swap(TrueVal, FalseVal); 4079 } 4080 4081 if (Pred == ICmpInst::ICMP_EQ && match(CmpRHS, m_Zero())) { 4082 Value *X; 4083 const APInt *Y; 4084 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y)))) 4085 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y, 4086 /*TrueWhenUnset=*/true)) 4087 return V; 4088 4089 // Test for a bogus zero-shift-guard-op around funnel-shift or rotate. 4090 Value *ShAmt; 4091 auto isFsh = m_CombineOr(m_FShl(m_Value(X), m_Value(), m_Value(ShAmt)), 4092 m_FShr(m_Value(), m_Value(X), m_Value(ShAmt))); 4093 // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X 4094 // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X 4095 if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt) 4096 return X; 4097 4098 // Test for a zero-shift-guard-op around rotates. These are used to 4099 // avoid UB from oversized shifts in raw IR rotate patterns, but the 4100 // intrinsics do not have that problem. 4101 // We do not allow this transform for the general funnel shift case because 4102 // that would not preserve the poison safety of the original code. 4103 auto isRotate = 4104 m_CombineOr(m_FShl(m_Value(X), m_Deferred(X), m_Value(ShAmt)), 4105 m_FShr(m_Value(X), m_Deferred(X), m_Value(ShAmt))); 4106 // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt) 4107 // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt) 4108 if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt && 4109 Pred == ICmpInst::ICMP_EQ) 4110 return FalseVal; 4111 4112 // X == 0 ? abs(X) : -abs(X) --> -abs(X) 4113 // X == 0 ? -abs(X) : abs(X) --> abs(X) 4114 if (match(TrueVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))) && 4115 match(FalseVal, m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))))) 4116 return FalseVal; 4117 if (match(TrueVal, 4118 m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))) && 4119 match(FalseVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))) 4120 return FalseVal; 4121 } 4122 4123 // Check for other compares that behave like bit test. 4124 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred, 4125 TrueVal, FalseVal)) 4126 return V; 4127 4128 // If we have a scalar equality comparison, then we know the value in one of 4129 // the arms of the select. See if substituting this value into the arm and 4130 // simplifying the result yields the same value as the other arm. 4131 // Note that the equivalence/replacement opportunity does not hold for vectors 4132 // because each element of a vector select is chosen independently. 4133 if (Pred == ICmpInst::ICMP_EQ && !CondVal->getType()->isVectorTy()) { 4134 if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, 4135 /* AllowRefinement */ false, MaxRecurse) == 4136 TrueVal || 4137 simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, 4138 /* AllowRefinement */ false, MaxRecurse) == 4139 TrueVal) 4140 return FalseVal; 4141 if (simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, 4142 /* AllowRefinement */ true, MaxRecurse) == 4143 FalseVal || 4144 simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, 4145 /* AllowRefinement */ true, MaxRecurse) == 4146 FalseVal) 4147 return FalseVal; 4148 } 4149 4150 return nullptr; 4151 } 4152 4153 /// Try to simplify a select instruction when its condition operand is a 4154 /// floating-point comparison. 4155 static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F, 4156 const SimplifyQuery &Q) { 4157 FCmpInst::Predicate Pred; 4158 if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) && 4159 !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T)))) 4160 return nullptr; 4161 4162 // This transform is safe if we do not have (do not care about) -0.0 or if 4163 // at least one operand is known to not be -0.0. Otherwise, the select can 4164 // change the sign of a zero operand. 4165 bool HasNoSignedZeros = Q.CxtI && isa<FPMathOperator>(Q.CxtI) && 4166 Q.CxtI->hasNoSignedZeros(); 4167 const APFloat *C; 4168 if (HasNoSignedZeros || (match(T, m_APFloat(C)) && C->isNonZero()) || 4169 (match(F, m_APFloat(C)) && C->isNonZero())) { 4170 // (T == F) ? T : F --> F 4171 // (F == T) ? T : F --> F 4172 if (Pred == FCmpInst::FCMP_OEQ) 4173 return F; 4174 4175 // (T != F) ? T : F --> T 4176 // (F != T) ? T : F --> T 4177 if (Pred == FCmpInst::FCMP_UNE) 4178 return T; 4179 } 4180 4181 return nullptr; 4182 } 4183 4184 /// Given operands for a SelectInst, see if we can fold the result. 4185 /// If not, this returns null. 4186 static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal, 4187 const SimplifyQuery &Q, unsigned MaxRecurse) { 4188 if (auto *CondC = dyn_cast<Constant>(Cond)) { 4189 if (auto *TrueC = dyn_cast<Constant>(TrueVal)) 4190 if (auto *FalseC = dyn_cast<Constant>(FalseVal)) 4191 return ConstantFoldSelectInstruction(CondC, TrueC, FalseC); 4192 4193 // select poison, X, Y -> poison 4194 if (isa<PoisonValue>(CondC)) 4195 return PoisonValue::get(TrueVal->getType()); 4196 4197 // select undef, X, Y -> X or Y 4198 if (Q.isUndefValue(CondC)) 4199 return isa<Constant>(FalseVal) ? FalseVal : TrueVal; 4200 4201 // select true, X, Y --> X 4202 // select false, X, Y --> Y 4203 // For vectors, allow undef/poison elements in the condition to match the 4204 // defined elements, so we can eliminate the select. 4205 if (match(CondC, m_One())) 4206 return TrueVal; 4207 if (match(CondC, m_Zero())) 4208 return FalseVal; 4209 } 4210 4211 // select i1 Cond, i1 true, i1 false --> i1 Cond 4212 assert(Cond->getType()->isIntOrIntVectorTy(1) && 4213 "Select must have bool or bool vector condition"); 4214 assert(TrueVal->getType() == FalseVal->getType() && 4215 "Select must have same types for true/false ops"); 4216 if (Cond->getType() == TrueVal->getType() && 4217 match(TrueVal, m_One()) && match(FalseVal, m_ZeroInt())) 4218 return Cond; 4219 4220 // select ?, X, X -> X 4221 if (TrueVal == FalseVal) 4222 return TrueVal; 4223 4224 // If the true or false value is poison, we can fold to the other value. 4225 // If the true or false value is undef, we can fold to the other value as 4226 // long as the other value isn't poison. 4227 // select ?, poison, X -> X 4228 // select ?, undef, X -> X 4229 if (isa<PoisonValue>(TrueVal) || 4230 (Q.isUndefValue(TrueVal) && 4231 isGuaranteedNotToBePoison(FalseVal, Q.AC, Q.CxtI, Q.DT))) 4232 return FalseVal; 4233 // select ?, X, poison -> X 4234 // select ?, X, undef -> X 4235 if (isa<PoisonValue>(FalseVal) || 4236 (Q.isUndefValue(FalseVal) && 4237 isGuaranteedNotToBePoison(TrueVal, Q.AC, Q.CxtI, Q.DT))) 4238 return TrueVal; 4239 4240 // Deal with partial undef vector constants: select ?, VecC, VecC' --> VecC'' 4241 Constant *TrueC, *FalseC; 4242 if (isa<FixedVectorType>(TrueVal->getType()) && 4243 match(TrueVal, m_Constant(TrueC)) && 4244 match(FalseVal, m_Constant(FalseC))) { 4245 unsigned NumElts = 4246 cast<FixedVectorType>(TrueC->getType())->getNumElements(); 4247 SmallVector<Constant *, 16> NewC; 4248 for (unsigned i = 0; i != NumElts; ++i) { 4249 // Bail out on incomplete vector constants. 4250 Constant *TEltC = TrueC->getAggregateElement(i); 4251 Constant *FEltC = FalseC->getAggregateElement(i); 4252 if (!TEltC || !FEltC) 4253 break; 4254 4255 // If the elements match (undef or not), that value is the result. If only 4256 // one element is undef, choose the defined element as the safe result. 4257 if (TEltC == FEltC) 4258 NewC.push_back(TEltC); 4259 else if (isa<PoisonValue>(TEltC) || 4260 (Q.isUndefValue(TEltC) && isGuaranteedNotToBePoison(FEltC))) 4261 NewC.push_back(FEltC); 4262 else if (isa<PoisonValue>(FEltC) || 4263 (Q.isUndefValue(FEltC) && isGuaranteedNotToBePoison(TEltC))) 4264 NewC.push_back(TEltC); 4265 else 4266 break; 4267 } 4268 if (NewC.size() == NumElts) 4269 return ConstantVector::get(NewC); 4270 } 4271 4272 if (Value *V = 4273 simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse)) 4274 return V; 4275 4276 if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal, Q)) 4277 return V; 4278 4279 if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal)) 4280 return V; 4281 4282 Optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL); 4283 if (Imp) 4284 return *Imp ? TrueVal : FalseVal; 4285 4286 return nullptr; 4287 } 4288 4289 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal, 4290 const SimplifyQuery &Q) { 4291 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit); 4292 } 4293 4294 /// Given operands for an GetElementPtrInst, see if we can fold the result. 4295 /// If not, this returns null. 4296 static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops, 4297 const SimplifyQuery &Q, unsigned) { 4298 // The type of the GEP pointer operand. 4299 unsigned AS = 4300 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace(); 4301 4302 // getelementptr P -> P. 4303 if (Ops.size() == 1) 4304 return Ops[0]; 4305 4306 // Compute the (pointer) type returned by the GEP instruction. 4307 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1)); 4308 Type *GEPTy = PointerType::get(LastType, AS); 4309 for (Value *Op : Ops) { 4310 // If one of the operands is a vector, the result type is a vector of 4311 // pointers. All vector operands must have the same number of elements. 4312 if (VectorType *VT = dyn_cast<VectorType>(Op->getType())) { 4313 GEPTy = VectorType::get(GEPTy, VT->getElementCount()); 4314 break; 4315 } 4316 } 4317 4318 // getelementptr poison, idx -> poison 4319 // getelementptr baseptr, poison -> poison 4320 if (any_of(Ops, [](const auto *V) { return isa<PoisonValue>(V); })) 4321 return PoisonValue::get(GEPTy); 4322 4323 if (Q.isUndefValue(Ops[0])) 4324 return UndefValue::get(GEPTy); 4325 4326 bool IsScalableVec = 4327 isa<ScalableVectorType>(SrcTy) || any_of(Ops, [](const Value *V) { 4328 return isa<ScalableVectorType>(V->getType()); 4329 }); 4330 4331 if (Ops.size() == 2) { 4332 // getelementptr P, 0 -> P. 4333 if (match(Ops[1], m_Zero()) && Ops[0]->getType() == GEPTy) 4334 return Ops[0]; 4335 4336 Type *Ty = SrcTy; 4337 if (!IsScalableVec && Ty->isSized()) { 4338 Value *P; 4339 uint64_t C; 4340 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty); 4341 // getelementptr P, N -> P if P points to a type of zero size. 4342 if (TyAllocSize == 0 && Ops[0]->getType() == GEPTy) 4343 return Ops[0]; 4344 4345 // The following transforms are only safe if the ptrtoint cast 4346 // doesn't truncate the pointers. 4347 if (Ops[1]->getType()->getScalarSizeInBits() == 4348 Q.DL.getPointerSizeInBits(AS)) { 4349 auto CanSimplify = [GEPTy, &P, V = Ops[0]]() -> bool { 4350 return P->getType() == GEPTy && 4351 getUnderlyingObject(P) == getUnderlyingObject(V); 4352 }; 4353 // getelementptr V, (sub P, V) -> P if P points to a type of size 1. 4354 if (TyAllocSize == 1 && 4355 match(Ops[1], m_Sub(m_PtrToInt(m_Value(P)), 4356 m_PtrToInt(m_Specific(Ops[0])))) && 4357 CanSimplify()) 4358 return P; 4359 4360 // getelementptr V, (ashr (sub P, V), C) -> P if P points to a type of 4361 // size 1 << C. 4362 if (match(Ops[1], m_AShr(m_Sub(m_PtrToInt(m_Value(P)), 4363 m_PtrToInt(m_Specific(Ops[0]))), 4364 m_ConstantInt(C))) && 4365 TyAllocSize == 1ULL << C && CanSimplify()) 4366 return P; 4367 4368 // getelementptr V, (sdiv (sub P, V), C) -> P if P points to a type of 4369 // size C. 4370 if (match(Ops[1], m_SDiv(m_Sub(m_PtrToInt(m_Value(P)), 4371 m_PtrToInt(m_Specific(Ops[0]))), 4372 m_SpecificInt(TyAllocSize))) && 4373 CanSimplify()) 4374 return P; 4375 } 4376 } 4377 } 4378 4379 if (!IsScalableVec && Q.DL.getTypeAllocSize(LastType) == 1 && 4380 all_of(Ops.slice(1).drop_back(1), 4381 [](Value *Idx) { return match(Idx, m_Zero()); })) { 4382 unsigned IdxWidth = 4383 Q.DL.getIndexSizeInBits(Ops[0]->getType()->getPointerAddressSpace()); 4384 if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == IdxWidth) { 4385 APInt BasePtrOffset(IdxWidth, 0); 4386 Value *StrippedBasePtr = 4387 Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL, 4388 BasePtrOffset); 4389 4390 // Avoid creating inttoptr of zero here: While LLVMs treatment of 4391 // inttoptr is generally conservative, this particular case is folded to 4392 // a null pointer, which will have incorrect provenance. 4393 4394 // gep (gep V, C), (sub 0, V) -> C 4395 if (match(Ops.back(), 4396 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr)))) && 4397 !BasePtrOffset.isNullValue()) { 4398 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset); 4399 return ConstantExpr::getIntToPtr(CI, GEPTy); 4400 } 4401 // gep (gep V, C), (xor V, -1) -> C-1 4402 if (match(Ops.back(), 4403 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes())) && 4404 !BasePtrOffset.isOneValue()) { 4405 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1); 4406 return ConstantExpr::getIntToPtr(CI, GEPTy); 4407 } 4408 } 4409 } 4410 4411 // Check to see if this is constant foldable. 4412 if (!all_of(Ops, [](Value *V) { return isa<Constant>(V); })) 4413 return nullptr; 4414 4415 auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]), 4416 Ops.slice(1)); 4417 return ConstantFoldConstant(CE, Q.DL); 4418 } 4419 4420 Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops, 4421 const SimplifyQuery &Q) { 4422 return ::SimplifyGEPInst(SrcTy, Ops, Q, RecursionLimit); 4423 } 4424 4425 /// Given operands for an InsertValueInst, see if we can fold the result. 4426 /// If not, this returns null. 4427 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val, 4428 ArrayRef<unsigned> Idxs, const SimplifyQuery &Q, 4429 unsigned) { 4430 if (Constant *CAgg = dyn_cast<Constant>(Agg)) 4431 if (Constant *CVal = dyn_cast<Constant>(Val)) 4432 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs); 4433 4434 // insertvalue x, undef, n -> x 4435 if (Q.isUndefValue(Val)) 4436 return Agg; 4437 4438 // insertvalue x, (extractvalue y, n), n 4439 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val)) 4440 if (EV->getAggregateOperand()->getType() == Agg->getType() && 4441 EV->getIndices() == Idxs) { 4442 // insertvalue undef, (extractvalue y, n), n -> y 4443 if (Q.isUndefValue(Agg)) 4444 return EV->getAggregateOperand(); 4445 4446 // insertvalue y, (extractvalue y, n), n -> y 4447 if (Agg == EV->getAggregateOperand()) 4448 return Agg; 4449 } 4450 4451 return nullptr; 4452 } 4453 4454 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val, 4455 ArrayRef<unsigned> Idxs, 4456 const SimplifyQuery &Q) { 4457 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit); 4458 } 4459 4460 Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx, 4461 const SimplifyQuery &Q) { 4462 // Try to constant fold. 4463 auto *VecC = dyn_cast<Constant>(Vec); 4464 auto *ValC = dyn_cast<Constant>(Val); 4465 auto *IdxC = dyn_cast<Constant>(Idx); 4466 if (VecC && ValC && IdxC) 4467 return ConstantExpr::getInsertElement(VecC, ValC, IdxC); 4468 4469 // For fixed-length vector, fold into poison if index is out of bounds. 4470 if (auto *CI = dyn_cast<ConstantInt>(Idx)) { 4471 if (isa<FixedVectorType>(Vec->getType()) && 4472 CI->uge(cast<FixedVectorType>(Vec->getType())->getNumElements())) 4473 return PoisonValue::get(Vec->getType()); 4474 } 4475 4476 // If index is undef, it might be out of bounds (see above case) 4477 if (Q.isUndefValue(Idx)) 4478 return PoisonValue::get(Vec->getType()); 4479 4480 // If the scalar is poison, or it is undef and there is no risk of 4481 // propagating poison from the vector value, simplify to the vector value. 4482 if (isa<PoisonValue>(Val) || 4483 (Q.isUndefValue(Val) && isGuaranteedNotToBePoison(Vec))) 4484 return Vec; 4485 4486 // If we are extracting a value from a vector, then inserting it into the same 4487 // place, that's the input vector: 4488 // insertelt Vec, (extractelt Vec, Idx), Idx --> Vec 4489 if (match(Val, m_ExtractElt(m_Specific(Vec), m_Specific(Idx)))) 4490 return Vec; 4491 4492 return nullptr; 4493 } 4494 4495 /// Given operands for an ExtractValueInst, see if we can fold the result. 4496 /// If not, this returns null. 4497 static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs, 4498 const SimplifyQuery &, unsigned) { 4499 if (auto *CAgg = dyn_cast<Constant>(Agg)) 4500 return ConstantFoldExtractValueInstruction(CAgg, Idxs); 4501 4502 // extractvalue x, (insertvalue y, elt, n), n -> elt 4503 unsigned NumIdxs = Idxs.size(); 4504 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr; 4505 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) { 4506 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices(); 4507 unsigned NumInsertValueIdxs = InsertValueIdxs.size(); 4508 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs); 4509 if (InsertValueIdxs.slice(0, NumCommonIdxs) == 4510 Idxs.slice(0, NumCommonIdxs)) { 4511 if (NumIdxs == NumInsertValueIdxs) 4512 return IVI->getInsertedValueOperand(); 4513 break; 4514 } 4515 } 4516 4517 return nullptr; 4518 } 4519 4520 Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs, 4521 const SimplifyQuery &Q) { 4522 return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit); 4523 } 4524 4525 /// Given operands for an ExtractElementInst, see if we can fold the result. 4526 /// If not, this returns null. 4527 static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, 4528 const SimplifyQuery &Q, unsigned) { 4529 auto *VecVTy = cast<VectorType>(Vec->getType()); 4530 if (auto *CVec = dyn_cast<Constant>(Vec)) { 4531 if (auto *CIdx = dyn_cast<Constant>(Idx)) 4532 return ConstantExpr::getExtractElement(CVec, CIdx); 4533 4534 if (Q.isUndefValue(Vec)) 4535 return UndefValue::get(VecVTy->getElementType()); 4536 } 4537 4538 // An undef extract index can be arbitrarily chosen to be an out-of-range 4539 // index value, which would result in the instruction being poison. 4540 if (Q.isUndefValue(Idx)) 4541 return PoisonValue::get(VecVTy->getElementType()); 4542 4543 // If extracting a specified index from the vector, see if we can recursively 4544 // find a previously computed scalar that was inserted into the vector. 4545 if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) { 4546 // For fixed-length vector, fold into undef if index is out of bounds. 4547 unsigned MinNumElts = VecVTy->getElementCount().getKnownMinValue(); 4548 if (isa<FixedVectorType>(VecVTy) && IdxC->getValue().uge(MinNumElts)) 4549 return PoisonValue::get(VecVTy->getElementType()); 4550 // Handle case where an element is extracted from a splat. 4551 if (IdxC->getValue().ult(MinNumElts)) 4552 if (auto *Splat = getSplatValue(Vec)) 4553 return Splat; 4554 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue())) 4555 return Elt; 4556 } else { 4557 // The index is not relevant if our vector is a splat. 4558 if (Value *Splat = getSplatValue(Vec)) 4559 return Splat; 4560 } 4561 return nullptr; 4562 } 4563 4564 Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx, 4565 const SimplifyQuery &Q) { 4566 return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit); 4567 } 4568 4569 /// See if we can fold the given phi. If not, returns null. 4570 static Value *SimplifyPHINode(PHINode *PN, const SimplifyQuery &Q) { 4571 // WARNING: no matter how worthwhile it may seem, we can not perform PHI CSE 4572 // here, because the PHI we may succeed simplifying to was not 4573 // def-reachable from the original PHI! 4574 4575 // If all of the PHI's incoming values are the same then replace the PHI node 4576 // with the common value. 4577 Value *CommonValue = nullptr; 4578 bool HasUndefInput = false; 4579 for (Value *Incoming : PN->incoming_values()) { 4580 // If the incoming value is the phi node itself, it can safely be skipped. 4581 if (Incoming == PN) continue; 4582 if (Q.isUndefValue(Incoming)) { 4583 // Remember that we saw an undef value, but otherwise ignore them. 4584 HasUndefInput = true; 4585 continue; 4586 } 4587 if (CommonValue && Incoming != CommonValue) 4588 return nullptr; // Not the same, bail out. 4589 CommonValue = Incoming; 4590 } 4591 4592 // If CommonValue is null then all of the incoming values were either undef or 4593 // equal to the phi node itself. 4594 if (!CommonValue) 4595 return UndefValue::get(PN->getType()); 4596 4597 // If we have a PHI node like phi(X, undef, X), where X is defined by some 4598 // instruction, we cannot return X as the result of the PHI node unless it 4599 // dominates the PHI block. 4600 if (HasUndefInput) 4601 return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr; 4602 4603 return CommonValue; 4604 } 4605 4606 static Value *SimplifyCastInst(unsigned CastOpc, Value *Op, 4607 Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) { 4608 if (auto *C = dyn_cast<Constant>(Op)) 4609 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL); 4610 4611 if (auto *CI = dyn_cast<CastInst>(Op)) { 4612 auto *Src = CI->getOperand(0); 4613 Type *SrcTy = Src->getType(); 4614 Type *MidTy = CI->getType(); 4615 Type *DstTy = Ty; 4616 if (Src->getType() == Ty) { 4617 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode()); 4618 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc); 4619 Type *SrcIntPtrTy = 4620 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr; 4621 Type *MidIntPtrTy = 4622 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr; 4623 Type *DstIntPtrTy = 4624 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr; 4625 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy, 4626 SrcIntPtrTy, MidIntPtrTy, 4627 DstIntPtrTy) == Instruction::BitCast) 4628 return Src; 4629 } 4630 } 4631 4632 // bitcast x -> x 4633 if (CastOpc == Instruction::BitCast) 4634 if (Op->getType() == Ty) 4635 return Op; 4636 4637 return nullptr; 4638 } 4639 4640 Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty, 4641 const SimplifyQuery &Q) { 4642 return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit); 4643 } 4644 4645 /// For the given destination element of a shuffle, peek through shuffles to 4646 /// match a root vector source operand that contains that element in the same 4647 /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s). 4648 static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1, 4649 int MaskVal, Value *RootVec, 4650 unsigned MaxRecurse) { 4651 if (!MaxRecurse--) 4652 return nullptr; 4653 4654 // Bail out if any mask value is undefined. That kind of shuffle may be 4655 // simplified further based on demanded bits or other folds. 4656 if (MaskVal == -1) 4657 return nullptr; 4658 4659 // The mask value chooses which source operand we need to look at next. 4660 int InVecNumElts = cast<FixedVectorType>(Op0->getType())->getNumElements(); 4661 int RootElt = MaskVal; 4662 Value *SourceOp = Op0; 4663 if (MaskVal >= InVecNumElts) { 4664 RootElt = MaskVal - InVecNumElts; 4665 SourceOp = Op1; 4666 } 4667 4668 // If the source operand is a shuffle itself, look through it to find the 4669 // matching root vector. 4670 if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) { 4671 return foldIdentityShuffles( 4672 DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1), 4673 SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse); 4674 } 4675 4676 // TODO: Look through bitcasts? What if the bitcast changes the vector element 4677 // size? 4678 4679 // The source operand is not a shuffle. Initialize the root vector value for 4680 // this shuffle if that has not been done yet. 4681 if (!RootVec) 4682 RootVec = SourceOp; 4683 4684 // Give up as soon as a source operand does not match the existing root value. 4685 if (RootVec != SourceOp) 4686 return nullptr; 4687 4688 // The element must be coming from the same lane in the source vector 4689 // (although it may have crossed lanes in intermediate shuffles). 4690 if (RootElt != DestElt) 4691 return nullptr; 4692 4693 return RootVec; 4694 } 4695 4696 static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, 4697 ArrayRef<int> Mask, Type *RetTy, 4698 const SimplifyQuery &Q, 4699 unsigned MaxRecurse) { 4700 if (all_of(Mask, [](int Elem) { return Elem == UndefMaskElem; })) 4701 return UndefValue::get(RetTy); 4702 4703 auto *InVecTy = cast<VectorType>(Op0->getType()); 4704 unsigned MaskNumElts = Mask.size(); 4705 ElementCount InVecEltCount = InVecTy->getElementCount(); 4706 4707 bool Scalable = InVecEltCount.isScalable(); 4708 4709 SmallVector<int, 32> Indices; 4710 Indices.assign(Mask.begin(), Mask.end()); 4711 4712 // Canonicalization: If mask does not select elements from an input vector, 4713 // replace that input vector with poison. 4714 if (!Scalable) { 4715 bool MaskSelects0 = false, MaskSelects1 = false; 4716 unsigned InVecNumElts = InVecEltCount.getKnownMinValue(); 4717 for (unsigned i = 0; i != MaskNumElts; ++i) { 4718 if (Indices[i] == -1) 4719 continue; 4720 if ((unsigned)Indices[i] < InVecNumElts) 4721 MaskSelects0 = true; 4722 else 4723 MaskSelects1 = true; 4724 } 4725 if (!MaskSelects0) 4726 Op0 = PoisonValue::get(InVecTy); 4727 if (!MaskSelects1) 4728 Op1 = PoisonValue::get(InVecTy); 4729 } 4730 4731 auto *Op0Const = dyn_cast<Constant>(Op0); 4732 auto *Op1Const = dyn_cast<Constant>(Op1); 4733 4734 // If all operands are constant, constant fold the shuffle. This 4735 // transformation depends on the value of the mask which is not known at 4736 // compile time for scalable vectors 4737 if (Op0Const && Op1Const) 4738 return ConstantExpr::getShuffleVector(Op0Const, Op1Const, Mask); 4739 4740 // Canonicalization: if only one input vector is constant, it shall be the 4741 // second one. This transformation depends on the value of the mask which 4742 // is not known at compile time for scalable vectors 4743 if (!Scalable && Op0Const && !Op1Const) { 4744 std::swap(Op0, Op1); 4745 ShuffleVectorInst::commuteShuffleMask(Indices, 4746 InVecEltCount.getKnownMinValue()); 4747 } 4748 4749 // A splat of an inserted scalar constant becomes a vector constant: 4750 // shuf (inselt ?, C, IndexC), undef, <IndexC, IndexC...> --> <C, C...> 4751 // NOTE: We may have commuted above, so analyze the updated Indices, not the 4752 // original mask constant. 4753 // NOTE: This transformation depends on the value of the mask which is not 4754 // known at compile time for scalable vectors 4755 Constant *C; 4756 ConstantInt *IndexC; 4757 if (!Scalable && match(Op0, m_InsertElt(m_Value(), m_Constant(C), 4758 m_ConstantInt(IndexC)))) { 4759 // Match a splat shuffle mask of the insert index allowing undef elements. 4760 int InsertIndex = IndexC->getZExtValue(); 4761 if (all_of(Indices, [InsertIndex](int MaskElt) { 4762 return MaskElt == InsertIndex || MaskElt == -1; 4763 })) { 4764 assert(isa<UndefValue>(Op1) && "Expected undef operand 1 for splat"); 4765 4766 // Shuffle mask undefs become undefined constant result elements. 4767 SmallVector<Constant *, 16> VecC(MaskNumElts, C); 4768 for (unsigned i = 0; i != MaskNumElts; ++i) 4769 if (Indices[i] == -1) 4770 VecC[i] = UndefValue::get(C->getType()); 4771 return ConstantVector::get(VecC); 4772 } 4773 } 4774 4775 // A shuffle of a splat is always the splat itself. Legal if the shuffle's 4776 // value type is same as the input vectors' type. 4777 if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0)) 4778 if (Q.isUndefValue(Op1) && RetTy == InVecTy && 4779 is_splat(OpShuf->getShuffleMask())) 4780 return Op0; 4781 4782 // All remaining transformation depend on the value of the mask, which is 4783 // not known at compile time for scalable vectors. 4784 if (Scalable) 4785 return nullptr; 4786 4787 // Don't fold a shuffle with undef mask elements. This may get folded in a 4788 // better way using demanded bits or other analysis. 4789 // TODO: Should we allow this? 4790 if (is_contained(Indices, -1)) 4791 return nullptr; 4792 4793 // Check if every element of this shuffle can be mapped back to the 4794 // corresponding element of a single root vector. If so, we don't need this 4795 // shuffle. This handles simple identity shuffles as well as chains of 4796 // shuffles that may widen/narrow and/or move elements across lanes and back. 4797 Value *RootVec = nullptr; 4798 for (unsigned i = 0; i != MaskNumElts; ++i) { 4799 // Note that recursion is limited for each vector element, so if any element 4800 // exceeds the limit, this will fail to simplify. 4801 RootVec = 4802 foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse); 4803 4804 // We can't replace a widening/narrowing shuffle with one of its operands. 4805 if (!RootVec || RootVec->getType() != RetTy) 4806 return nullptr; 4807 } 4808 return RootVec; 4809 } 4810 4811 /// Given operands for a ShuffleVectorInst, fold the result or return null. 4812 Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1, 4813 ArrayRef<int> Mask, Type *RetTy, 4814 const SimplifyQuery &Q) { 4815 return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit); 4816 } 4817 4818 static Constant *foldConstant(Instruction::UnaryOps Opcode, 4819 Value *&Op, const SimplifyQuery &Q) { 4820 if (auto *C = dyn_cast<Constant>(Op)) 4821 return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL); 4822 return nullptr; 4823 } 4824 4825 /// Given the operand for an FNeg, see if we can fold the result. If not, this 4826 /// returns null. 4827 static Value *simplifyFNegInst(Value *Op, FastMathFlags FMF, 4828 const SimplifyQuery &Q, unsigned MaxRecurse) { 4829 if (Constant *C = foldConstant(Instruction::FNeg, Op, Q)) 4830 return C; 4831 4832 Value *X; 4833 // fneg (fneg X) ==> X 4834 if (match(Op, m_FNeg(m_Value(X)))) 4835 return X; 4836 4837 return nullptr; 4838 } 4839 4840 Value *llvm::SimplifyFNegInst(Value *Op, FastMathFlags FMF, 4841 const SimplifyQuery &Q) { 4842 return ::simplifyFNegInst(Op, FMF, Q, RecursionLimit); 4843 } 4844 4845 static Constant *propagateNaN(Constant *In) { 4846 // If the input is a vector with undef elements, just return a default NaN. 4847 if (!In->isNaN()) 4848 return ConstantFP::getNaN(In->getType()); 4849 4850 // Propagate the existing NaN constant when possible. 4851 // TODO: Should we quiet a signaling NaN? 4852 return In; 4853 } 4854 4855 /// Perform folds that are common to any floating-point operation. This implies 4856 /// transforms based on poison/undef/NaN because the operation itself makes no 4857 /// difference to the result. 4858 static Constant *simplifyFPOp(ArrayRef<Value *> Ops, FastMathFlags FMF, 4859 const SimplifyQuery &Q, 4860 fp::ExceptionBehavior ExBehavior, 4861 RoundingMode Rounding) { 4862 // Poison is independent of anything else. It always propagates from an 4863 // operand to a math result. 4864 if (any_of(Ops, [](Value *V) { return match(V, m_Poison()); })) 4865 return PoisonValue::get(Ops[0]->getType()); 4866 4867 for (Value *V : Ops) { 4868 bool IsNan = match(V, m_NaN()); 4869 bool IsInf = match(V, m_Inf()); 4870 bool IsUndef = Q.isUndefValue(V); 4871 4872 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 4873 // (an undef operand can be chosen to be Nan/Inf), then the result of 4874 // this operation is poison. 4875 if (FMF.noNaNs() && (IsNan || IsUndef)) 4876 return PoisonValue::get(V->getType()); 4877 if (FMF.noInfs() && (IsInf || IsUndef)) 4878 return PoisonValue::get(V->getType()); 4879 4880 if (isDefaultFPEnvironment(ExBehavior, Rounding)) { 4881 if (IsUndef || IsNan) 4882 return propagateNaN(cast<Constant>(V)); 4883 } else if (ExBehavior != fp::ebStrict) { 4884 if (IsNan) 4885 return propagateNaN(cast<Constant>(V)); 4886 } 4887 } 4888 return nullptr; 4889 } 4890 4891 /// Given operands for an FAdd, see if we can fold the result. If not, this 4892 /// returns null. 4893 static Value * 4894 SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF, 4895 const SimplifyQuery &Q, unsigned MaxRecurse, 4896 fp::ExceptionBehavior ExBehavior = fp::ebIgnore, 4897 RoundingMode Rounding = RoundingMode::NearestTiesToEven) { 4898 if (isDefaultFPEnvironment(ExBehavior, Rounding)) 4899 if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q)) 4900 return C; 4901 4902 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding)) 4903 return C; 4904 4905 if (!isDefaultFPEnvironment(ExBehavior, Rounding)) 4906 return nullptr; 4907 4908 // fadd X, -0 ==> X 4909 if (match(Op1, m_NegZeroFP())) 4910 return Op0; 4911 4912 // fadd X, 0 ==> X, when we know X is not -0 4913 if (match(Op1, m_PosZeroFP()) && 4914 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI))) 4915 return Op0; 4916 4917 // With nnan: -X + X --> 0.0 (and commuted variant) 4918 // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN. 4919 // Negative zeros are allowed because we always end up with positive zero: 4920 // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0 4921 // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0 4922 // X = 0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0 4923 // X = 0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0 4924 if (FMF.noNaNs()) { 4925 if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) || 4926 match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0)))) 4927 return ConstantFP::getNullValue(Op0->getType()); 4928 4929 if (match(Op0, m_FNeg(m_Specific(Op1))) || 4930 match(Op1, m_FNeg(m_Specific(Op0)))) 4931 return ConstantFP::getNullValue(Op0->getType()); 4932 } 4933 4934 // (X - Y) + Y --> X 4935 // Y + (X - Y) --> X 4936 Value *X; 4937 if (FMF.noSignedZeros() && FMF.allowReassoc() && 4938 (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) || 4939 match(Op1, m_FSub(m_Value(X), m_Specific(Op0))))) 4940 return X; 4941 4942 return nullptr; 4943 } 4944 4945 /// Given operands for an FSub, see if we can fold the result. If not, this 4946 /// returns null. 4947 static Value * 4948 SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF, 4949 const SimplifyQuery &Q, unsigned MaxRecurse, 4950 fp::ExceptionBehavior ExBehavior = fp::ebIgnore, 4951 RoundingMode Rounding = RoundingMode::NearestTiesToEven) { 4952 if (isDefaultFPEnvironment(ExBehavior, Rounding)) 4953 if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q)) 4954 return C; 4955 4956 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding)) 4957 return C; 4958 4959 if (!isDefaultFPEnvironment(ExBehavior, Rounding)) 4960 return nullptr; 4961 4962 // fsub X, +0 ==> X 4963 if (match(Op1, m_PosZeroFP())) 4964 return Op0; 4965 4966 // fsub X, -0 ==> X, when we know X is not -0 4967 if (match(Op1, m_NegZeroFP()) && 4968 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI))) 4969 return Op0; 4970 4971 // fsub -0.0, (fsub -0.0, X) ==> X 4972 // fsub -0.0, (fneg X) ==> X 4973 Value *X; 4974 if (match(Op0, m_NegZeroFP()) && 4975 match(Op1, m_FNeg(m_Value(X)))) 4976 return X; 4977 4978 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored. 4979 // fsub 0.0, (fneg X) ==> X if signed zeros are ignored. 4980 if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) && 4981 (match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))) || 4982 match(Op1, m_FNeg(m_Value(X))))) 4983 return X; 4984 4985 // fsub nnan x, x ==> 0.0 4986 if (FMF.noNaNs() && Op0 == Op1) 4987 return Constant::getNullValue(Op0->getType()); 4988 4989 // Y - (Y - X) --> X 4990 // (X + Y) - Y --> X 4991 if (FMF.noSignedZeros() && FMF.allowReassoc() && 4992 (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) || 4993 match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X))))) 4994 return X; 4995 4996 return nullptr; 4997 } 4998 4999 static Value *SimplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF, 5000 const SimplifyQuery &Q, unsigned MaxRecurse, 5001 fp::ExceptionBehavior ExBehavior, 5002 RoundingMode Rounding) { 5003 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding)) 5004 return C; 5005 5006 if (!isDefaultFPEnvironment(ExBehavior, Rounding)) 5007 return nullptr; 5008 5009 // fmul X, 1.0 ==> X 5010 if (match(Op1, m_FPOne())) 5011 return Op0; 5012 5013 // fmul 1.0, X ==> X 5014 if (match(Op0, m_FPOne())) 5015 return Op1; 5016 5017 // fmul nnan nsz X, 0 ==> 0 5018 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP())) 5019 return ConstantFP::getNullValue(Op0->getType()); 5020 5021 // fmul nnan nsz 0, X ==> 0 5022 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP())) 5023 return ConstantFP::getNullValue(Op1->getType()); 5024 5025 // sqrt(X) * sqrt(X) --> X, if we can: 5026 // 1. Remove the intermediate rounding (reassociate). 5027 // 2. Ignore non-zero negative numbers because sqrt would produce NAN. 5028 // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0. 5029 Value *X; 5030 if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) && 5031 FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros()) 5032 return X; 5033 5034 return nullptr; 5035 } 5036 5037 /// Given the operands for an FMul, see if we can fold the result 5038 static Value * 5039 SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5040 const SimplifyQuery &Q, unsigned MaxRecurse, 5041 fp::ExceptionBehavior ExBehavior = fp::ebIgnore, 5042 RoundingMode Rounding = RoundingMode::NearestTiesToEven) { 5043 if (isDefaultFPEnvironment(ExBehavior, Rounding)) 5044 if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q)) 5045 return C; 5046 5047 // Now apply simplifications that do not require rounding. 5048 return SimplifyFMAFMul(Op0, Op1, FMF, Q, MaxRecurse, ExBehavior, Rounding); 5049 } 5050 5051 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5052 const SimplifyQuery &Q, 5053 fp::ExceptionBehavior ExBehavior, 5054 RoundingMode Rounding) { 5055 return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior, 5056 Rounding); 5057 } 5058 5059 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5060 const SimplifyQuery &Q, 5061 fp::ExceptionBehavior ExBehavior, 5062 RoundingMode Rounding) { 5063 return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior, 5064 Rounding); 5065 } 5066 5067 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5068 const SimplifyQuery &Q, 5069 fp::ExceptionBehavior ExBehavior, 5070 RoundingMode Rounding) { 5071 return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior, 5072 Rounding); 5073 } 5074 5075 Value *llvm::SimplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF, 5076 const SimplifyQuery &Q, 5077 fp::ExceptionBehavior ExBehavior, 5078 RoundingMode Rounding) { 5079 return ::SimplifyFMAFMul(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior, 5080 Rounding); 5081 } 5082 5083 static Value * 5084 SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5085 const SimplifyQuery &Q, unsigned, 5086 fp::ExceptionBehavior ExBehavior = fp::ebIgnore, 5087 RoundingMode Rounding = RoundingMode::NearestTiesToEven) { 5088 if (isDefaultFPEnvironment(ExBehavior, Rounding)) 5089 if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q)) 5090 return C; 5091 5092 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding)) 5093 return C; 5094 5095 if (!isDefaultFPEnvironment(ExBehavior, Rounding)) 5096 return nullptr; 5097 5098 // X / 1.0 -> X 5099 if (match(Op1, m_FPOne())) 5100 return Op0; 5101 5102 // 0 / X -> 0 5103 // Requires that NaNs are off (X could be zero) and signed zeroes are 5104 // ignored (X could be positive or negative, so the output sign is unknown). 5105 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP())) 5106 return ConstantFP::getNullValue(Op0->getType()); 5107 5108 if (FMF.noNaNs()) { 5109 // X / X -> 1.0 is legal when NaNs are ignored. 5110 // We can ignore infinities because INF/INF is NaN. 5111 if (Op0 == Op1) 5112 return ConstantFP::get(Op0->getType(), 1.0); 5113 5114 // (X * Y) / Y --> X if we can reassociate to the above form. 5115 Value *X; 5116 if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1)))) 5117 return X; 5118 5119 // -X / X -> -1.0 and 5120 // X / -X -> -1.0 are legal when NaNs are ignored. 5121 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored. 5122 if (match(Op0, m_FNegNSZ(m_Specific(Op1))) || 5123 match(Op1, m_FNegNSZ(m_Specific(Op0)))) 5124 return ConstantFP::get(Op0->getType(), -1.0); 5125 } 5126 5127 return nullptr; 5128 } 5129 5130 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5131 const SimplifyQuery &Q, 5132 fp::ExceptionBehavior ExBehavior, 5133 RoundingMode Rounding) { 5134 return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior, 5135 Rounding); 5136 } 5137 5138 static Value * 5139 SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5140 const SimplifyQuery &Q, unsigned, 5141 fp::ExceptionBehavior ExBehavior = fp::ebIgnore, 5142 RoundingMode Rounding = RoundingMode::NearestTiesToEven) { 5143 if (isDefaultFPEnvironment(ExBehavior, Rounding)) 5144 if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q)) 5145 return C; 5146 5147 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding)) 5148 return C; 5149 5150 if (!isDefaultFPEnvironment(ExBehavior, Rounding)) 5151 return nullptr; 5152 5153 // Unlike fdiv, the result of frem always matches the sign of the dividend. 5154 // The constant match may include undef elements in a vector, so return a full 5155 // zero constant as the result. 5156 if (FMF.noNaNs()) { 5157 // +0 % X -> 0 5158 if (match(Op0, m_PosZeroFP())) 5159 return ConstantFP::getNullValue(Op0->getType()); 5160 // -0 % X -> -0 5161 if (match(Op0, m_NegZeroFP())) 5162 return ConstantFP::getNegativeZero(Op0->getType()); 5163 } 5164 5165 return nullptr; 5166 } 5167 5168 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5169 const SimplifyQuery &Q, 5170 fp::ExceptionBehavior ExBehavior, 5171 RoundingMode Rounding) { 5172 return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior, 5173 Rounding); 5174 } 5175 5176 //=== Helper functions for higher up the class hierarchy. 5177 5178 /// Given the operand for a UnaryOperator, see if we can fold the result. 5179 /// If not, this returns null. 5180 static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q, 5181 unsigned MaxRecurse) { 5182 switch (Opcode) { 5183 case Instruction::FNeg: 5184 return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse); 5185 default: 5186 llvm_unreachable("Unexpected opcode"); 5187 } 5188 } 5189 5190 /// Given the operand for a UnaryOperator, see if we can fold the result. 5191 /// If not, this returns null. 5192 /// Try to use FastMathFlags when folding the result. 5193 static Value *simplifyFPUnOp(unsigned Opcode, Value *Op, 5194 const FastMathFlags &FMF, 5195 const SimplifyQuery &Q, unsigned MaxRecurse) { 5196 switch (Opcode) { 5197 case Instruction::FNeg: 5198 return simplifyFNegInst(Op, FMF, Q, MaxRecurse); 5199 default: 5200 return simplifyUnOp(Opcode, Op, Q, MaxRecurse); 5201 } 5202 } 5203 5204 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q) { 5205 return ::simplifyUnOp(Opcode, Op, Q, RecursionLimit); 5206 } 5207 5208 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF, 5209 const SimplifyQuery &Q) { 5210 return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit); 5211 } 5212 5213 /// Given operands for a BinaryOperator, see if we can fold the result. 5214 /// If not, this returns null. 5215 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, 5216 const SimplifyQuery &Q, unsigned MaxRecurse) { 5217 switch (Opcode) { 5218 case Instruction::Add: 5219 return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse); 5220 case Instruction::Sub: 5221 return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse); 5222 case Instruction::Mul: 5223 return SimplifyMulInst(LHS, RHS, Q, MaxRecurse); 5224 case Instruction::SDiv: 5225 return SimplifySDivInst(LHS, RHS, Q, MaxRecurse); 5226 case Instruction::UDiv: 5227 return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse); 5228 case Instruction::SRem: 5229 return SimplifySRemInst(LHS, RHS, Q, MaxRecurse); 5230 case Instruction::URem: 5231 return SimplifyURemInst(LHS, RHS, Q, MaxRecurse); 5232 case Instruction::Shl: 5233 return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse); 5234 case Instruction::LShr: 5235 return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse); 5236 case Instruction::AShr: 5237 return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse); 5238 case Instruction::And: 5239 return SimplifyAndInst(LHS, RHS, Q, MaxRecurse); 5240 case Instruction::Or: 5241 return SimplifyOrInst(LHS, RHS, Q, MaxRecurse); 5242 case Instruction::Xor: 5243 return SimplifyXorInst(LHS, RHS, Q, MaxRecurse); 5244 case Instruction::FAdd: 5245 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 5246 case Instruction::FSub: 5247 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 5248 case Instruction::FMul: 5249 return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 5250 case Instruction::FDiv: 5251 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 5252 case Instruction::FRem: 5253 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 5254 default: 5255 llvm_unreachable("Unexpected opcode"); 5256 } 5257 } 5258 5259 /// Given operands for a BinaryOperator, see if we can fold the result. 5260 /// If not, this returns null. 5261 /// Try to use FastMathFlags when folding the result. 5262 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, 5263 const FastMathFlags &FMF, const SimplifyQuery &Q, 5264 unsigned MaxRecurse) { 5265 switch (Opcode) { 5266 case Instruction::FAdd: 5267 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse); 5268 case Instruction::FSub: 5269 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse); 5270 case Instruction::FMul: 5271 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse); 5272 case Instruction::FDiv: 5273 return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse); 5274 default: 5275 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse); 5276 } 5277 } 5278 5279 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, 5280 const SimplifyQuery &Q) { 5281 return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit); 5282 } 5283 5284 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, 5285 FastMathFlags FMF, const SimplifyQuery &Q) { 5286 return ::SimplifyBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit); 5287 } 5288 5289 /// Given operands for a CmpInst, see if we can fold the result. 5290 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 5291 const SimplifyQuery &Q, unsigned MaxRecurse) { 5292 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate)) 5293 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse); 5294 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse); 5295 } 5296 5297 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 5298 const SimplifyQuery &Q) { 5299 return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit); 5300 } 5301 5302 static bool IsIdempotent(Intrinsic::ID ID) { 5303 switch (ID) { 5304 default: return false; 5305 5306 // Unary idempotent: f(f(x)) = f(x) 5307 case Intrinsic::fabs: 5308 case Intrinsic::floor: 5309 case Intrinsic::ceil: 5310 case Intrinsic::trunc: 5311 case Intrinsic::rint: 5312 case Intrinsic::nearbyint: 5313 case Intrinsic::round: 5314 case Intrinsic::roundeven: 5315 case Intrinsic::canonicalize: 5316 return true; 5317 } 5318 } 5319 5320 static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset, 5321 const DataLayout &DL) { 5322 GlobalValue *PtrSym; 5323 APInt PtrOffset; 5324 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL)) 5325 return nullptr; 5326 5327 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext()); 5328 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext()); 5329 Type *Int32PtrTy = Int32Ty->getPointerTo(); 5330 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext()); 5331 5332 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset); 5333 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64) 5334 return nullptr; 5335 5336 uint64_t OffsetInt = OffsetConstInt->getSExtValue(); 5337 if (OffsetInt % 4 != 0) 5338 return nullptr; 5339 5340 Constant *C = ConstantExpr::getGetElementPtr( 5341 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy), 5342 ConstantInt::get(Int64Ty, OffsetInt / 4)); 5343 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL); 5344 if (!Loaded) 5345 return nullptr; 5346 5347 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded); 5348 if (!LoadedCE) 5349 return nullptr; 5350 5351 if (LoadedCE->getOpcode() == Instruction::Trunc) { 5352 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0)); 5353 if (!LoadedCE) 5354 return nullptr; 5355 } 5356 5357 if (LoadedCE->getOpcode() != Instruction::Sub) 5358 return nullptr; 5359 5360 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0)); 5361 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt) 5362 return nullptr; 5363 auto *LoadedLHSPtr = LoadedLHS->getOperand(0); 5364 5365 Constant *LoadedRHS = LoadedCE->getOperand(1); 5366 GlobalValue *LoadedRHSSym; 5367 APInt LoadedRHSOffset; 5368 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset, 5369 DL) || 5370 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset) 5371 return nullptr; 5372 5373 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy); 5374 } 5375 5376 static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0, 5377 const SimplifyQuery &Q) { 5378 // Idempotent functions return the same result when called repeatedly. 5379 Intrinsic::ID IID = F->getIntrinsicID(); 5380 if (IsIdempotent(IID)) 5381 if (auto *II = dyn_cast<IntrinsicInst>(Op0)) 5382 if (II->getIntrinsicID() == IID) 5383 return II; 5384 5385 Value *X; 5386 switch (IID) { 5387 case Intrinsic::fabs: 5388 if (SignBitMustBeZero(Op0, Q.TLI)) return Op0; 5389 break; 5390 case Intrinsic::bswap: 5391 // bswap(bswap(x)) -> x 5392 if (match(Op0, m_BSwap(m_Value(X)))) return X; 5393 break; 5394 case Intrinsic::bitreverse: 5395 // bitreverse(bitreverse(x)) -> x 5396 if (match(Op0, m_BitReverse(m_Value(X)))) return X; 5397 break; 5398 case Intrinsic::ctpop: { 5399 // If everything but the lowest bit is zero, that bit is the pop-count. Ex: 5400 // ctpop(and X, 1) --> and X, 1 5401 unsigned BitWidth = Op0->getType()->getScalarSizeInBits(); 5402 if (MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, BitWidth - 1), 5403 Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) 5404 return Op0; 5405 break; 5406 } 5407 case Intrinsic::exp: 5408 // exp(log(x)) -> x 5409 if (Q.CxtI->hasAllowReassoc() && 5410 match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X)))) return X; 5411 break; 5412 case Intrinsic::exp2: 5413 // exp2(log2(x)) -> x 5414 if (Q.CxtI->hasAllowReassoc() && 5415 match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X)))) return X; 5416 break; 5417 case Intrinsic::log: 5418 // log(exp(x)) -> x 5419 if (Q.CxtI->hasAllowReassoc() && 5420 match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X)))) return X; 5421 break; 5422 case Intrinsic::log2: 5423 // log2(exp2(x)) -> x 5424 if (Q.CxtI->hasAllowReassoc() && 5425 (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) || 5426 match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0), 5427 m_Value(X))))) return X; 5428 break; 5429 case Intrinsic::log10: 5430 // log10(pow(10.0, x)) -> x 5431 if (Q.CxtI->hasAllowReassoc() && 5432 match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0), 5433 m_Value(X)))) return X; 5434 break; 5435 case Intrinsic::floor: 5436 case Intrinsic::trunc: 5437 case Intrinsic::ceil: 5438 case Intrinsic::round: 5439 case Intrinsic::roundeven: 5440 case Intrinsic::nearbyint: 5441 case Intrinsic::rint: { 5442 // floor (sitofp x) -> sitofp x 5443 // floor (uitofp x) -> uitofp x 5444 // 5445 // Converting from int always results in a finite integral number or 5446 // infinity. For either of those inputs, these rounding functions always 5447 // return the same value, so the rounding can be eliminated. 5448 if (match(Op0, m_SIToFP(m_Value())) || match(Op0, m_UIToFP(m_Value()))) 5449 return Op0; 5450 break; 5451 } 5452 case Intrinsic::experimental_vector_reverse: 5453 // experimental.vector.reverse(experimental.vector.reverse(x)) -> x 5454 if (match(Op0, 5455 m_Intrinsic<Intrinsic::experimental_vector_reverse>(m_Value(X)))) 5456 return X; 5457 break; 5458 default: 5459 break; 5460 } 5461 5462 return nullptr; 5463 } 5464 5465 static APInt getMaxMinLimit(Intrinsic::ID IID, unsigned BitWidth) { 5466 switch (IID) { 5467 case Intrinsic::smax: return APInt::getSignedMaxValue(BitWidth); 5468 case Intrinsic::smin: return APInt::getSignedMinValue(BitWidth); 5469 case Intrinsic::umax: return APInt::getMaxValue(BitWidth); 5470 case Intrinsic::umin: return APInt::getMinValue(BitWidth); 5471 default: llvm_unreachable("Unexpected intrinsic"); 5472 } 5473 } 5474 5475 static ICmpInst::Predicate getMaxMinPredicate(Intrinsic::ID IID) { 5476 switch (IID) { 5477 case Intrinsic::smax: return ICmpInst::ICMP_SGE; 5478 case Intrinsic::smin: return ICmpInst::ICMP_SLE; 5479 case Intrinsic::umax: return ICmpInst::ICMP_UGE; 5480 case Intrinsic::umin: return ICmpInst::ICMP_ULE; 5481 default: llvm_unreachable("Unexpected intrinsic"); 5482 } 5483 } 5484 5485 /// Given a min/max intrinsic, see if it can be removed based on having an 5486 /// operand that is another min/max intrinsic with shared operand(s). The caller 5487 /// is expected to swap the operand arguments to handle commutation. 5488 static Value *foldMinMaxSharedOp(Intrinsic::ID IID, Value *Op0, Value *Op1) { 5489 Value *X, *Y; 5490 if (!match(Op0, m_MaxOrMin(m_Value(X), m_Value(Y)))) 5491 return nullptr; 5492 5493 auto *MM0 = dyn_cast<IntrinsicInst>(Op0); 5494 if (!MM0) 5495 return nullptr; 5496 Intrinsic::ID IID0 = MM0->getIntrinsicID(); 5497 5498 if (Op1 == X || Op1 == Y || 5499 match(Op1, m_c_MaxOrMin(m_Specific(X), m_Specific(Y)))) { 5500 // max (max X, Y), X --> max X, Y 5501 if (IID0 == IID) 5502 return MM0; 5503 // max (min X, Y), X --> X 5504 if (IID0 == getInverseMinMaxIntrinsic(IID)) 5505 return Op1; 5506 } 5507 return nullptr; 5508 } 5509 5510 static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1, 5511 const SimplifyQuery &Q) { 5512 Intrinsic::ID IID = F->getIntrinsicID(); 5513 Type *ReturnType = F->getReturnType(); 5514 unsigned BitWidth = ReturnType->getScalarSizeInBits(); 5515 switch (IID) { 5516 case Intrinsic::abs: 5517 // abs(abs(x)) -> abs(x). We don't need to worry about the nsw arg here. 5518 // It is always ok to pick the earlier abs. We'll just lose nsw if its only 5519 // on the outer abs. 5520 if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(), m_Value()))) 5521 return Op0; 5522 break; 5523 5524 case Intrinsic::cttz: { 5525 Value *X; 5526 if (match(Op0, m_Shl(m_One(), m_Value(X)))) 5527 return X; 5528 break; 5529 } 5530 case Intrinsic::ctlz: { 5531 Value *X; 5532 if (match(Op0, m_LShr(m_Negative(), m_Value(X)))) 5533 return X; 5534 if (match(Op0, m_AShr(m_Negative(), m_Value()))) 5535 return Constant::getNullValue(ReturnType); 5536 break; 5537 } 5538 case Intrinsic::smax: 5539 case Intrinsic::smin: 5540 case Intrinsic::umax: 5541 case Intrinsic::umin: { 5542 // If the arguments are the same, this is a no-op. 5543 if (Op0 == Op1) 5544 return Op0; 5545 5546 // Canonicalize constant operand as Op1. 5547 if (isa<Constant>(Op0)) 5548 std::swap(Op0, Op1); 5549 5550 // Assume undef is the limit value. 5551 if (Q.isUndefValue(Op1)) 5552 return ConstantInt::get(ReturnType, getMaxMinLimit(IID, BitWidth)); 5553 5554 const APInt *C; 5555 if (match(Op1, m_APIntAllowUndef(C))) { 5556 // Clamp to limit value. For example: 5557 // umax(i8 %x, i8 255) --> 255 5558 if (*C == getMaxMinLimit(IID, BitWidth)) 5559 return ConstantInt::get(ReturnType, *C); 5560 5561 // If the constant op is the opposite of the limit value, the other must 5562 // be larger/smaller or equal. For example: 5563 // umin(i8 %x, i8 255) --> %x 5564 if (*C == getMaxMinLimit(getInverseMinMaxIntrinsic(IID), BitWidth)) 5565 return Op0; 5566 5567 // Remove nested call if constant operands allow it. Example: 5568 // max (max X, 7), 5 -> max X, 7 5569 auto *MinMax0 = dyn_cast<IntrinsicInst>(Op0); 5570 if (MinMax0 && MinMax0->getIntrinsicID() == IID) { 5571 // TODO: loosen undef/splat restrictions for vector constants. 5572 Value *M00 = MinMax0->getOperand(0), *M01 = MinMax0->getOperand(1); 5573 const APInt *InnerC; 5574 if ((match(M00, m_APInt(InnerC)) || match(M01, m_APInt(InnerC))) && 5575 ((IID == Intrinsic::smax && InnerC->sge(*C)) || 5576 (IID == Intrinsic::smin && InnerC->sle(*C)) || 5577 (IID == Intrinsic::umax && InnerC->uge(*C)) || 5578 (IID == Intrinsic::umin && InnerC->ule(*C)))) 5579 return Op0; 5580 } 5581 } 5582 5583 if (Value *V = foldMinMaxSharedOp(IID, Op0, Op1)) 5584 return V; 5585 if (Value *V = foldMinMaxSharedOp(IID, Op1, Op0)) 5586 return V; 5587 5588 ICmpInst::Predicate Pred = getMaxMinPredicate(IID); 5589 if (isICmpTrue(Pred, Op0, Op1, Q.getWithoutUndef(), RecursionLimit)) 5590 return Op0; 5591 if (isICmpTrue(Pred, Op1, Op0, Q.getWithoutUndef(), RecursionLimit)) 5592 return Op1; 5593 5594 if (Optional<bool> Imp = 5595 isImpliedByDomCondition(Pred, Op0, Op1, Q.CxtI, Q.DL)) 5596 return *Imp ? Op0 : Op1; 5597 if (Optional<bool> Imp = 5598 isImpliedByDomCondition(Pred, Op1, Op0, Q.CxtI, Q.DL)) 5599 return *Imp ? Op1 : Op0; 5600 5601 break; 5602 } 5603 case Intrinsic::usub_with_overflow: 5604 case Intrinsic::ssub_with_overflow: 5605 // X - X -> { 0, false } 5606 // X - undef -> { 0, false } 5607 // undef - X -> { 0, false } 5608 if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) 5609 return Constant::getNullValue(ReturnType); 5610 break; 5611 case Intrinsic::uadd_with_overflow: 5612 case Intrinsic::sadd_with_overflow: 5613 // X + undef -> { -1, false } 5614 // undef + x -> { -1, false } 5615 if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) { 5616 return ConstantStruct::get( 5617 cast<StructType>(ReturnType), 5618 {Constant::getAllOnesValue(ReturnType->getStructElementType(0)), 5619 Constant::getNullValue(ReturnType->getStructElementType(1))}); 5620 } 5621 break; 5622 case Intrinsic::umul_with_overflow: 5623 case Intrinsic::smul_with_overflow: 5624 // 0 * X -> { 0, false } 5625 // X * 0 -> { 0, false } 5626 if (match(Op0, m_Zero()) || match(Op1, m_Zero())) 5627 return Constant::getNullValue(ReturnType); 5628 // undef * X -> { 0, false } 5629 // X * undef -> { 0, false } 5630 if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) 5631 return Constant::getNullValue(ReturnType); 5632 break; 5633 case Intrinsic::uadd_sat: 5634 // sat(MAX + X) -> MAX 5635 // sat(X + MAX) -> MAX 5636 if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes())) 5637 return Constant::getAllOnesValue(ReturnType); 5638 LLVM_FALLTHROUGH; 5639 case Intrinsic::sadd_sat: 5640 // sat(X + undef) -> -1 5641 // sat(undef + X) -> -1 5642 // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1). 5643 // For signed: Assume undef is ~X, in which case X + ~X = -1. 5644 if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) 5645 return Constant::getAllOnesValue(ReturnType); 5646 5647 // X + 0 -> X 5648 if (match(Op1, m_Zero())) 5649 return Op0; 5650 // 0 + X -> X 5651 if (match(Op0, m_Zero())) 5652 return Op1; 5653 break; 5654 case Intrinsic::usub_sat: 5655 // sat(0 - X) -> 0, sat(X - MAX) -> 0 5656 if (match(Op0, m_Zero()) || match(Op1, m_AllOnes())) 5657 return Constant::getNullValue(ReturnType); 5658 LLVM_FALLTHROUGH; 5659 case Intrinsic::ssub_sat: 5660 // X - X -> 0, X - undef -> 0, undef - X -> 0 5661 if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) 5662 return Constant::getNullValue(ReturnType); 5663 // X - 0 -> X 5664 if (match(Op1, m_Zero())) 5665 return Op0; 5666 break; 5667 case Intrinsic::load_relative: 5668 if (auto *C0 = dyn_cast<Constant>(Op0)) 5669 if (auto *C1 = dyn_cast<Constant>(Op1)) 5670 return SimplifyRelativeLoad(C0, C1, Q.DL); 5671 break; 5672 case Intrinsic::powi: 5673 if (auto *Power = dyn_cast<ConstantInt>(Op1)) { 5674 // powi(x, 0) -> 1.0 5675 if (Power->isZero()) 5676 return ConstantFP::get(Op0->getType(), 1.0); 5677 // powi(x, 1) -> x 5678 if (Power->isOne()) 5679 return Op0; 5680 } 5681 break; 5682 case Intrinsic::copysign: 5683 // copysign X, X --> X 5684 if (Op0 == Op1) 5685 return Op0; 5686 // copysign -X, X --> X 5687 // copysign X, -X --> -X 5688 if (match(Op0, m_FNeg(m_Specific(Op1))) || 5689 match(Op1, m_FNeg(m_Specific(Op0)))) 5690 return Op1; 5691 break; 5692 case Intrinsic::maxnum: 5693 case Intrinsic::minnum: 5694 case Intrinsic::maximum: 5695 case Intrinsic::minimum: { 5696 // If the arguments are the same, this is a no-op. 5697 if (Op0 == Op1) return Op0; 5698 5699 // Canonicalize constant operand as Op1. 5700 if (isa<Constant>(Op0)) 5701 std::swap(Op0, Op1); 5702 5703 // If an argument is undef, return the other argument. 5704 if (Q.isUndefValue(Op1)) 5705 return Op0; 5706 5707 bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum; 5708 bool IsMin = IID == Intrinsic::minimum || IID == Intrinsic::minnum; 5709 5710 // minnum(X, nan) -> X 5711 // maxnum(X, nan) -> X 5712 // minimum(X, nan) -> nan 5713 // maximum(X, nan) -> nan 5714 if (match(Op1, m_NaN())) 5715 return PropagateNaN ? propagateNaN(cast<Constant>(Op1)) : Op0; 5716 5717 // In the following folds, inf can be replaced with the largest finite 5718 // float, if the ninf flag is set. 5719 const APFloat *C; 5720 if (match(Op1, m_APFloat(C)) && 5721 (C->isInfinity() || (Q.CxtI->hasNoInfs() && C->isLargest()))) { 5722 // minnum(X, -inf) -> -inf 5723 // maxnum(X, +inf) -> +inf 5724 // minimum(X, -inf) -> -inf if nnan 5725 // maximum(X, +inf) -> +inf if nnan 5726 if (C->isNegative() == IsMin && (!PropagateNaN || Q.CxtI->hasNoNaNs())) 5727 return ConstantFP::get(ReturnType, *C); 5728 5729 // minnum(X, +inf) -> X if nnan 5730 // maxnum(X, -inf) -> X if nnan 5731 // minimum(X, +inf) -> X 5732 // maximum(X, -inf) -> X 5733 if (C->isNegative() != IsMin && (PropagateNaN || Q.CxtI->hasNoNaNs())) 5734 return Op0; 5735 } 5736 5737 // Min/max of the same operation with common operand: 5738 // m(m(X, Y)), X --> m(X, Y) (4 commuted variants) 5739 if (auto *M0 = dyn_cast<IntrinsicInst>(Op0)) 5740 if (M0->getIntrinsicID() == IID && 5741 (M0->getOperand(0) == Op1 || M0->getOperand(1) == Op1)) 5742 return Op0; 5743 if (auto *M1 = dyn_cast<IntrinsicInst>(Op1)) 5744 if (M1->getIntrinsicID() == IID && 5745 (M1->getOperand(0) == Op0 || M1->getOperand(1) == Op0)) 5746 return Op1; 5747 5748 break; 5749 } 5750 case Intrinsic::experimental_vector_extract: { 5751 Type *ReturnType = F->getReturnType(); 5752 5753 // (extract_vector (insert_vector _, X, 0), 0) -> X 5754 unsigned IdxN = cast<ConstantInt>(Op1)->getZExtValue(); 5755 Value *X = nullptr; 5756 if (match(Op0, m_Intrinsic<Intrinsic::experimental_vector_insert>( 5757 m_Value(), m_Value(X), m_Zero())) && 5758 IdxN == 0 && X->getType() == ReturnType) 5759 return X; 5760 5761 break; 5762 } 5763 default: 5764 break; 5765 } 5766 5767 return nullptr; 5768 } 5769 5770 static Value *simplifyIntrinsic(CallBase *Call, const SimplifyQuery &Q) { 5771 5772 // Intrinsics with no operands have some kind of side effect. Don't simplify. 5773 unsigned NumOperands = Call->getNumArgOperands(); 5774 if (!NumOperands) 5775 return nullptr; 5776 5777 Function *F = cast<Function>(Call->getCalledFunction()); 5778 Intrinsic::ID IID = F->getIntrinsicID(); 5779 if (NumOperands == 1) 5780 return simplifyUnaryIntrinsic(F, Call->getArgOperand(0), Q); 5781 5782 if (NumOperands == 2) 5783 return simplifyBinaryIntrinsic(F, Call->getArgOperand(0), 5784 Call->getArgOperand(1), Q); 5785 5786 // Handle intrinsics with 3 or more arguments. 5787 switch (IID) { 5788 case Intrinsic::masked_load: 5789 case Intrinsic::masked_gather: { 5790 Value *MaskArg = Call->getArgOperand(2); 5791 Value *PassthruArg = Call->getArgOperand(3); 5792 // If the mask is all zeros or undef, the "passthru" argument is the result. 5793 if (maskIsAllZeroOrUndef(MaskArg)) 5794 return PassthruArg; 5795 return nullptr; 5796 } 5797 case Intrinsic::fshl: 5798 case Intrinsic::fshr: { 5799 Value *Op0 = Call->getArgOperand(0), *Op1 = Call->getArgOperand(1), 5800 *ShAmtArg = Call->getArgOperand(2); 5801 5802 // If both operands are undef, the result is undef. 5803 if (Q.isUndefValue(Op0) && Q.isUndefValue(Op1)) 5804 return UndefValue::get(F->getReturnType()); 5805 5806 // If shift amount is undef, assume it is zero. 5807 if (Q.isUndefValue(ShAmtArg)) 5808 return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1); 5809 5810 const APInt *ShAmtC; 5811 if (match(ShAmtArg, m_APInt(ShAmtC))) { 5812 // If there's effectively no shift, return the 1st arg or 2nd arg. 5813 APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth()); 5814 if (ShAmtC->urem(BitWidth).isNullValue()) 5815 return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1); 5816 } 5817 return nullptr; 5818 } 5819 case Intrinsic::experimental_constrained_fma: { 5820 Value *Op0 = Call->getArgOperand(0); 5821 Value *Op1 = Call->getArgOperand(1); 5822 Value *Op2 = Call->getArgOperand(2); 5823 auto *FPI = cast<ConstrainedFPIntrinsic>(Call); 5824 if (Value *V = simplifyFPOp({Op0, Op1, Op2}, {}, Q, 5825 FPI->getExceptionBehavior().getValue(), 5826 FPI->getRoundingMode().getValue())) 5827 return V; 5828 return nullptr; 5829 } 5830 case Intrinsic::fma: 5831 case Intrinsic::fmuladd: { 5832 Value *Op0 = Call->getArgOperand(0); 5833 Value *Op1 = Call->getArgOperand(1); 5834 Value *Op2 = Call->getArgOperand(2); 5835 if (Value *V = simplifyFPOp({Op0, Op1, Op2}, {}, Q, fp::ebIgnore, 5836 RoundingMode::NearestTiesToEven)) 5837 return V; 5838 return nullptr; 5839 } 5840 case Intrinsic::smul_fix: 5841 case Intrinsic::smul_fix_sat: { 5842 Value *Op0 = Call->getArgOperand(0); 5843 Value *Op1 = Call->getArgOperand(1); 5844 Value *Op2 = Call->getArgOperand(2); 5845 Type *ReturnType = F->getReturnType(); 5846 5847 // Canonicalize constant operand as Op1 (ConstantFolding handles the case 5848 // when both Op0 and Op1 are constant so we do not care about that special 5849 // case here). 5850 if (isa<Constant>(Op0)) 5851 std::swap(Op0, Op1); 5852 5853 // X * 0 -> 0 5854 if (match(Op1, m_Zero())) 5855 return Constant::getNullValue(ReturnType); 5856 5857 // X * undef -> 0 5858 if (Q.isUndefValue(Op1)) 5859 return Constant::getNullValue(ReturnType); 5860 5861 // X * (1 << Scale) -> X 5862 APInt ScaledOne = 5863 APInt::getOneBitSet(ReturnType->getScalarSizeInBits(), 5864 cast<ConstantInt>(Op2)->getZExtValue()); 5865 if (ScaledOne.isNonNegative() && match(Op1, m_SpecificInt(ScaledOne))) 5866 return Op0; 5867 5868 return nullptr; 5869 } 5870 case Intrinsic::experimental_vector_insert: { 5871 Value *Vec = Call->getArgOperand(0); 5872 Value *SubVec = Call->getArgOperand(1); 5873 Value *Idx = Call->getArgOperand(2); 5874 Type *ReturnType = F->getReturnType(); 5875 5876 // (insert_vector Y, (extract_vector X, 0), 0) -> X 5877 // where: Y is X, or Y is undef 5878 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue(); 5879 Value *X = nullptr; 5880 if (match(SubVec, m_Intrinsic<Intrinsic::experimental_vector_extract>( 5881 m_Value(X), m_Zero())) && 5882 (Q.isUndefValue(Vec) || Vec == X) && IdxN == 0 && 5883 X->getType() == ReturnType) 5884 return X; 5885 5886 return nullptr; 5887 } 5888 case Intrinsic::experimental_constrained_fadd: { 5889 auto *FPI = cast<ConstrainedFPIntrinsic>(Call); 5890 return SimplifyFAddInst(FPI->getArgOperand(0), FPI->getArgOperand(1), 5891 FPI->getFastMathFlags(), Q, 5892 FPI->getExceptionBehavior().getValue(), 5893 FPI->getRoundingMode().getValue()); 5894 break; 5895 } 5896 case Intrinsic::experimental_constrained_fsub: { 5897 auto *FPI = cast<ConstrainedFPIntrinsic>(Call); 5898 return SimplifyFSubInst(FPI->getArgOperand(0), FPI->getArgOperand(1), 5899 FPI->getFastMathFlags(), Q, 5900 FPI->getExceptionBehavior().getValue(), 5901 FPI->getRoundingMode().getValue()); 5902 break; 5903 } 5904 case Intrinsic::experimental_constrained_fmul: { 5905 auto *FPI = cast<ConstrainedFPIntrinsic>(Call); 5906 return SimplifyFMulInst(FPI->getArgOperand(0), FPI->getArgOperand(1), 5907 FPI->getFastMathFlags(), Q, 5908 FPI->getExceptionBehavior().getValue(), 5909 FPI->getRoundingMode().getValue()); 5910 break; 5911 } 5912 case Intrinsic::experimental_constrained_fdiv: { 5913 auto *FPI = cast<ConstrainedFPIntrinsic>(Call); 5914 return SimplifyFDivInst(FPI->getArgOperand(0), FPI->getArgOperand(1), 5915 FPI->getFastMathFlags(), Q, 5916 FPI->getExceptionBehavior().getValue(), 5917 FPI->getRoundingMode().getValue()); 5918 break; 5919 } 5920 case Intrinsic::experimental_constrained_frem: { 5921 auto *FPI = cast<ConstrainedFPIntrinsic>(Call); 5922 return SimplifyFRemInst(FPI->getArgOperand(0), FPI->getArgOperand(1), 5923 FPI->getFastMathFlags(), Q, 5924 FPI->getExceptionBehavior().getValue(), 5925 FPI->getRoundingMode().getValue()); 5926 break; 5927 } 5928 default: 5929 return nullptr; 5930 } 5931 } 5932 5933 static Value *tryConstantFoldCall(CallBase *Call, const SimplifyQuery &Q) { 5934 auto *F = dyn_cast<Function>(Call->getCalledOperand()); 5935 if (!F || !canConstantFoldCallTo(Call, F)) 5936 return nullptr; 5937 5938 SmallVector<Constant *, 4> ConstantArgs; 5939 unsigned NumArgs = Call->getNumArgOperands(); 5940 ConstantArgs.reserve(NumArgs); 5941 for (auto &Arg : Call->args()) { 5942 Constant *C = dyn_cast<Constant>(&Arg); 5943 if (!C) { 5944 if (isa<MetadataAsValue>(Arg.get())) 5945 continue; 5946 return nullptr; 5947 } 5948 ConstantArgs.push_back(C); 5949 } 5950 5951 return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI); 5952 } 5953 5954 Value *llvm::SimplifyCall(CallBase *Call, const SimplifyQuery &Q) { 5955 // musttail calls can only be simplified if they are also DCEd. 5956 // As we can't guarantee this here, don't simplify them. 5957 if (Call->isMustTailCall()) 5958 return nullptr; 5959 5960 // call undef -> poison 5961 // call null -> poison 5962 Value *Callee = Call->getCalledOperand(); 5963 if (isa<UndefValue>(Callee) || isa<ConstantPointerNull>(Callee)) 5964 return PoisonValue::get(Call->getType()); 5965 5966 if (Value *V = tryConstantFoldCall(Call, Q)) 5967 return V; 5968 5969 auto *F = dyn_cast<Function>(Callee); 5970 if (F && F->isIntrinsic()) 5971 if (Value *Ret = simplifyIntrinsic(Call, Q)) 5972 return Ret; 5973 5974 return nullptr; 5975 } 5976 5977 /// Given operands for a Freeze, see if we can fold the result. 5978 static Value *SimplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) { 5979 // Use a utility function defined in ValueTracking. 5980 if (llvm::isGuaranteedNotToBeUndefOrPoison(Op0, Q.AC, Q.CxtI, Q.DT)) 5981 return Op0; 5982 // We have room for improvement. 5983 return nullptr; 5984 } 5985 5986 Value *llvm::SimplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) { 5987 return ::SimplifyFreezeInst(Op0, Q); 5988 } 5989 5990 static Constant *ConstructLoadOperandConstant(Value *Op) { 5991 SmallVector<Value *, 4> Worklist; 5992 // Invalid IR in unreachable code may contain self-referential values. Don't infinitely loop. 5993 SmallPtrSet<Value *, 4> Visited; 5994 Worklist.push_back(Op); 5995 while (true) { 5996 Value *CurOp = Worklist.back(); 5997 if (!Visited.insert(CurOp).second) 5998 return nullptr; 5999 if (isa<Constant>(CurOp)) 6000 break; 6001 if (auto *BC = dyn_cast<BitCastOperator>(CurOp)) { 6002 Worklist.push_back(BC->getOperand(0)); 6003 } else if (auto *GEP = dyn_cast<GEPOperator>(CurOp)) { 6004 for (unsigned I = 1; I != GEP->getNumOperands(); ++I) { 6005 if (!isa<Constant>(GEP->getOperand(I))) 6006 return nullptr; 6007 } 6008 Worklist.push_back(GEP->getOperand(0)); 6009 } else if (auto *II = dyn_cast<IntrinsicInst>(CurOp)) { 6010 if (II->isLaunderOrStripInvariantGroup()) 6011 Worklist.push_back(II->getOperand(0)); 6012 else 6013 return nullptr; 6014 } else { 6015 return nullptr; 6016 } 6017 } 6018 6019 Constant *NewOp = cast<Constant>(Worklist.pop_back_val()); 6020 while (!Worklist.empty()) { 6021 Value *CurOp = Worklist.pop_back_val(); 6022 if (isa<BitCastOperator>(CurOp)) { 6023 NewOp = ConstantExpr::getBitCast(NewOp, CurOp->getType()); 6024 } else if (auto *GEP = dyn_cast<GEPOperator>(CurOp)) { 6025 SmallVector<Constant *> Idxs; 6026 Idxs.reserve(GEP->getNumOperands() - 1); 6027 for (unsigned I = 1, E = GEP->getNumOperands(); I != E; ++I) { 6028 Idxs.push_back(cast<Constant>(GEP->getOperand(I))); 6029 } 6030 NewOp = ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), NewOp, 6031 Idxs, GEP->isInBounds(), 6032 GEP->getInRangeIndex()); 6033 } else { 6034 assert(isa<IntrinsicInst>(CurOp) && 6035 cast<IntrinsicInst>(CurOp)->isLaunderOrStripInvariantGroup() && 6036 "expected invariant group intrinsic"); 6037 NewOp = ConstantExpr::getBitCast(NewOp, CurOp->getType()); 6038 } 6039 } 6040 return NewOp; 6041 } 6042 6043 static Value *SimplifyLoadInst(LoadInst *LI, const SimplifyQuery &Q) { 6044 if (LI->isVolatile()) 6045 return nullptr; 6046 6047 if (auto *C = ConstantFoldInstruction(LI, Q.DL)) 6048 return C; 6049 6050 // The following only catches more cases than ConstantFoldInstruction() if the 6051 // load operand wasn't a constant. Specifically, invariant.group intrinsics. 6052 if (isa<Constant>(LI->getPointerOperand())) 6053 return nullptr; 6054 6055 if (auto *C = dyn_cast_or_null<Constant>( 6056 ConstructLoadOperandConstant(LI->getPointerOperand()))) 6057 return ConstantFoldLoadFromConstPtr(C, LI->getType(), Q.DL); 6058 6059 return nullptr; 6060 } 6061 6062 /// See if we can compute a simplified version of this instruction. 6063 /// If not, this returns null. 6064 6065 Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &SQ, 6066 OptimizationRemarkEmitter *ORE) { 6067 const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I); 6068 Value *Result; 6069 6070 switch (I->getOpcode()) { 6071 default: 6072 Result = ConstantFoldInstruction(I, Q.DL, Q.TLI); 6073 break; 6074 case Instruction::FNeg: 6075 Result = SimplifyFNegInst(I->getOperand(0), I->getFastMathFlags(), Q); 6076 break; 6077 case Instruction::FAdd: 6078 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1), 6079 I->getFastMathFlags(), Q); 6080 break; 6081 case Instruction::Add: 6082 Result = 6083 SimplifyAddInst(I->getOperand(0), I->getOperand(1), 6084 Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)), 6085 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q); 6086 break; 6087 case Instruction::FSub: 6088 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1), 6089 I->getFastMathFlags(), Q); 6090 break; 6091 case Instruction::Sub: 6092 Result = 6093 SimplifySubInst(I->getOperand(0), I->getOperand(1), 6094 Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)), 6095 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q); 6096 break; 6097 case Instruction::FMul: 6098 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1), 6099 I->getFastMathFlags(), Q); 6100 break; 6101 case Instruction::Mul: 6102 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), Q); 6103 break; 6104 case Instruction::SDiv: 6105 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), Q); 6106 break; 6107 case Instruction::UDiv: 6108 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), Q); 6109 break; 6110 case Instruction::FDiv: 6111 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), 6112 I->getFastMathFlags(), Q); 6113 break; 6114 case Instruction::SRem: 6115 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), Q); 6116 break; 6117 case Instruction::URem: 6118 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), Q); 6119 break; 6120 case Instruction::FRem: 6121 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), 6122 I->getFastMathFlags(), Q); 6123 break; 6124 case Instruction::Shl: 6125 Result = 6126 SimplifyShlInst(I->getOperand(0), I->getOperand(1), 6127 Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)), 6128 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q); 6129 break; 6130 case Instruction::LShr: 6131 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1), 6132 Q.IIQ.isExact(cast<BinaryOperator>(I)), Q); 6133 break; 6134 case Instruction::AShr: 6135 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1), 6136 Q.IIQ.isExact(cast<BinaryOperator>(I)), Q); 6137 break; 6138 case Instruction::And: 6139 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), Q); 6140 break; 6141 case Instruction::Or: 6142 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), Q); 6143 break; 6144 case Instruction::Xor: 6145 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), Q); 6146 break; 6147 case Instruction::ICmp: 6148 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), 6149 I->getOperand(0), I->getOperand(1), Q); 6150 break; 6151 case Instruction::FCmp: 6152 Result = 6153 SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), I->getOperand(0), 6154 I->getOperand(1), I->getFastMathFlags(), Q); 6155 break; 6156 case Instruction::Select: 6157 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1), 6158 I->getOperand(2), Q); 6159 break; 6160 case Instruction::GetElementPtr: { 6161 SmallVector<Value *, 8> Ops(I->operands()); 6162 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(), 6163 Ops, Q); 6164 break; 6165 } 6166 case Instruction::InsertValue: { 6167 InsertValueInst *IV = cast<InsertValueInst>(I); 6168 Result = SimplifyInsertValueInst(IV->getAggregateOperand(), 6169 IV->getInsertedValueOperand(), 6170 IV->getIndices(), Q); 6171 break; 6172 } 6173 case Instruction::InsertElement: { 6174 auto *IE = cast<InsertElementInst>(I); 6175 Result = SimplifyInsertElementInst(IE->getOperand(0), IE->getOperand(1), 6176 IE->getOperand(2), Q); 6177 break; 6178 } 6179 case Instruction::ExtractValue: { 6180 auto *EVI = cast<ExtractValueInst>(I); 6181 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(), 6182 EVI->getIndices(), Q); 6183 break; 6184 } 6185 case Instruction::ExtractElement: { 6186 auto *EEI = cast<ExtractElementInst>(I); 6187 Result = SimplifyExtractElementInst(EEI->getVectorOperand(), 6188 EEI->getIndexOperand(), Q); 6189 break; 6190 } 6191 case Instruction::ShuffleVector: { 6192 auto *SVI = cast<ShuffleVectorInst>(I); 6193 Result = 6194 SimplifyShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1), 6195 SVI->getShuffleMask(), SVI->getType(), Q); 6196 break; 6197 } 6198 case Instruction::PHI: 6199 Result = SimplifyPHINode(cast<PHINode>(I), Q); 6200 break; 6201 case Instruction::Call: { 6202 Result = SimplifyCall(cast<CallInst>(I), Q); 6203 break; 6204 } 6205 case Instruction::Freeze: 6206 Result = SimplifyFreezeInst(I->getOperand(0), Q); 6207 break; 6208 #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc: 6209 #include "llvm/IR/Instruction.def" 6210 #undef HANDLE_CAST_INST 6211 Result = 6212 SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(), Q); 6213 break; 6214 case Instruction::Alloca: 6215 // No simplifications for Alloca and it can't be constant folded. 6216 Result = nullptr; 6217 break; 6218 case Instruction::Load: 6219 Result = SimplifyLoadInst(cast<LoadInst>(I), Q); 6220 break; 6221 } 6222 6223 /// If called on unreachable code, the above logic may report that the 6224 /// instruction simplified to itself. Make life easier for users by 6225 /// detecting that case here, returning a safe value instead. 6226 return Result == I ? UndefValue::get(I->getType()) : Result; 6227 } 6228 6229 /// Implementation of recursive simplification through an instruction's 6230 /// uses. 6231 /// 6232 /// This is the common implementation of the recursive simplification routines. 6233 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to 6234 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of 6235 /// instructions to process and attempt to simplify it using 6236 /// InstructionSimplify. Recursively visited users which could not be 6237 /// simplified themselves are to the optional UnsimplifiedUsers set for 6238 /// further processing by the caller. 6239 /// 6240 /// This routine returns 'true' only when *it* simplifies something. The passed 6241 /// in simplified value does not count toward this. 6242 static bool replaceAndRecursivelySimplifyImpl( 6243 Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI, 6244 const DominatorTree *DT, AssumptionCache *AC, 6245 SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr) { 6246 bool Simplified = false; 6247 SmallSetVector<Instruction *, 8> Worklist; 6248 const DataLayout &DL = I->getModule()->getDataLayout(); 6249 6250 // If we have an explicit value to collapse to, do that round of the 6251 // simplification loop by hand initially. 6252 if (SimpleV) { 6253 for (User *U : I->users()) 6254 if (U != I) 6255 Worklist.insert(cast<Instruction>(U)); 6256 6257 // Replace the instruction with its simplified value. 6258 I->replaceAllUsesWith(SimpleV); 6259 6260 // Gracefully handle edge cases where the instruction is not wired into any 6261 // parent block. 6262 if (I->getParent() && !I->isEHPad() && !I->isTerminator() && 6263 !I->mayHaveSideEffects()) 6264 I->eraseFromParent(); 6265 } else { 6266 Worklist.insert(I); 6267 } 6268 6269 // Note that we must test the size on each iteration, the worklist can grow. 6270 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) { 6271 I = Worklist[Idx]; 6272 6273 // See if this instruction simplifies. 6274 SimpleV = SimplifyInstruction(I, {DL, TLI, DT, AC}); 6275 if (!SimpleV) { 6276 if (UnsimplifiedUsers) 6277 UnsimplifiedUsers->insert(I); 6278 continue; 6279 } 6280 6281 Simplified = true; 6282 6283 // Stash away all the uses of the old instruction so we can check them for 6284 // recursive simplifications after a RAUW. This is cheaper than checking all 6285 // uses of To on the recursive step in most cases. 6286 for (User *U : I->users()) 6287 Worklist.insert(cast<Instruction>(U)); 6288 6289 // Replace the instruction with its simplified value. 6290 I->replaceAllUsesWith(SimpleV); 6291 6292 // Gracefully handle edge cases where the instruction is not wired into any 6293 // parent block. 6294 if (I->getParent() && !I->isEHPad() && !I->isTerminator() && 6295 !I->mayHaveSideEffects()) 6296 I->eraseFromParent(); 6297 } 6298 return Simplified; 6299 } 6300 6301 bool llvm::replaceAndRecursivelySimplify( 6302 Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI, 6303 const DominatorTree *DT, AssumptionCache *AC, 6304 SmallSetVector<Instruction *, 8> *UnsimplifiedUsers) { 6305 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!"); 6306 assert(SimpleV && "Must provide a simplified value."); 6307 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC, 6308 UnsimplifiedUsers); 6309 } 6310 6311 namespace llvm { 6312 const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) { 6313 auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 6314 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr; 6315 auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 6316 auto *TLI = TLIWP ? &TLIWP->getTLI(F) : nullptr; 6317 auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>(); 6318 auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr; 6319 return {F.getParent()->getDataLayout(), TLI, DT, AC}; 6320 } 6321 6322 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR, 6323 const DataLayout &DL) { 6324 return {DL, &AR.TLI, &AR.DT, &AR.AC}; 6325 } 6326 6327 template <class T, class... TArgs> 6328 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM, 6329 Function &F) { 6330 auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F); 6331 auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F); 6332 auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F); 6333 return {F.getParent()->getDataLayout(), TLI, DT, AC}; 6334 } 6335 template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &, 6336 Function &); 6337 } 6338