1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements routines for folding instructions into simpler forms 11 // that do not require creating new instructions. This does constant folding 12 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either 13 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value 14 // ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been 15 // simplified: This is usually true and assuming it simplifies the logic (if 16 // they have not been simplified then results are correct but maybe suboptimal). 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "llvm/Analysis/InstructionSimplify.h" 21 #include "llvm/ADT/SetVector.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/ValueTracking.h" 31 #include "llvm/Analysis/VectorUtils.h" 32 #include "llvm/IR/ConstantRange.h" 33 #include "llvm/IR/DataLayout.h" 34 #include "llvm/IR/Dominators.h" 35 #include "llvm/IR/GetElementPtrTypeIterator.h" 36 #include "llvm/IR/GlobalAlias.h" 37 #include "llvm/IR/Operator.h" 38 #include "llvm/IR/PatternMatch.h" 39 #include "llvm/IR/ValueHandle.h" 40 #include "llvm/Support/KnownBits.h" 41 #include <algorithm> 42 using namespace llvm; 43 using namespace llvm::PatternMatch; 44 45 #define DEBUG_TYPE "instsimplify" 46 47 enum { RecursionLimit = 3 }; 48 49 STATISTIC(NumExpand, "Number of expansions"); 50 STATISTIC(NumReassoc, "Number of reassociations"); 51 52 static Value *SimplifyAndInst(Value *, Value *, const SimplifyQuery &, unsigned); 53 static Value *SimplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &, 54 unsigned); 55 static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &, 56 const SimplifyQuery &, unsigned); 57 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &, 58 unsigned); 59 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, 60 const SimplifyQuery &Q, unsigned MaxRecurse); 61 static Value *SimplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned); 62 static Value *SimplifyXorInst(Value *, Value *, const SimplifyQuery &, unsigned); 63 static Value *SimplifyCastInst(unsigned, Value *, Type *, 64 const SimplifyQuery &, unsigned); 65 static Value *SimplifyGEPInst(Type *, ArrayRef<Value *>, const SimplifyQuery &, 66 unsigned); 67 68 /// For a boolean type or a vector of boolean type, return false or a vector 69 /// with every element false. 70 static Constant *getFalse(Type *Ty) { 71 return ConstantInt::getFalse(Ty); 72 } 73 74 /// For a boolean type or a vector of boolean type, return true or a vector 75 /// with every element true. 76 static Constant *getTrue(Type *Ty) { 77 return ConstantInt::getTrue(Ty); 78 } 79 80 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"? 81 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS, 82 Value *RHS) { 83 CmpInst *Cmp = dyn_cast<CmpInst>(V); 84 if (!Cmp) 85 return false; 86 CmpInst::Predicate CPred = Cmp->getPredicate(); 87 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1); 88 if (CPred == Pred && CLHS == LHS && CRHS == RHS) 89 return true; 90 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS && 91 CRHS == LHS; 92 } 93 94 /// Does the given value dominate the specified phi node? 95 static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) { 96 Instruction *I = dyn_cast<Instruction>(V); 97 if (!I) 98 // Arguments and constants dominate all instructions. 99 return true; 100 101 // If we are processing instructions (and/or basic blocks) that have not been 102 // fully added to a function, the parent nodes may still be null. Simply 103 // return the conservative answer in these cases. 104 if (!I->getParent() || !P->getParent() || !I->getFunction()) 105 return false; 106 107 // If we have a DominatorTree then do a precise test. 108 if (DT) 109 return DT->dominates(I, P); 110 111 // Otherwise, if the instruction is in the entry block and is not an invoke, 112 // then it obviously dominates all phi nodes. 113 if (I->getParent() == &I->getFunction()->getEntryBlock() && 114 !isa<InvokeInst>(I)) 115 return true; 116 117 return false; 118 } 119 120 /// Simplify "A op (B op' C)" by distributing op over op', turning it into 121 /// "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is 122 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS. 123 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)". 124 /// Returns the simplified value, or null if no simplification was performed. 125 static Value *ExpandBinOp(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS, 126 Instruction::BinaryOps OpcodeToExpand, 127 const SimplifyQuery &Q, unsigned MaxRecurse) { 128 // Recursion is always used, so bail out at once if we already hit the limit. 129 if (!MaxRecurse--) 130 return nullptr; 131 132 // Check whether the expression has the form "(A op' B) op C". 133 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS)) 134 if (Op0->getOpcode() == OpcodeToExpand) { 135 // It does! Try turning it into "(A op C) op' (B op C)". 136 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS; 137 // Do "A op C" and "B op C" both simplify? 138 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) 139 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) { 140 // They do! Return "L op' R" if it simplifies or is already available. 141 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS. 142 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand) 143 && L == B && R == A)) { 144 ++NumExpand; 145 return LHS; 146 } 147 // Otherwise return "L op' R" if it simplifies. 148 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) { 149 ++NumExpand; 150 return V; 151 } 152 } 153 } 154 155 // Check whether the expression has the form "A op (B op' C)". 156 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS)) 157 if (Op1->getOpcode() == OpcodeToExpand) { 158 // It does! Try turning it into "(A op B) op' (A op C)". 159 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1); 160 // Do "A op B" and "A op C" both simplify? 161 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) 162 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) { 163 // They do! Return "L op' R" if it simplifies or is already available. 164 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS. 165 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand) 166 && L == C && R == B)) { 167 ++NumExpand; 168 return RHS; 169 } 170 // Otherwise return "L op' R" if it simplifies. 171 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) { 172 ++NumExpand; 173 return V; 174 } 175 } 176 } 177 178 return nullptr; 179 } 180 181 /// Generic simplifications for associative binary operations. 182 /// Returns the simpler value, or null if none was found. 183 static Value *SimplifyAssociativeBinOp(Instruction::BinaryOps Opcode, 184 Value *LHS, Value *RHS, 185 const SimplifyQuery &Q, 186 unsigned MaxRecurse) { 187 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!"); 188 189 // Recursion is always used, so bail out at once if we already hit the limit. 190 if (!MaxRecurse--) 191 return nullptr; 192 193 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS); 194 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS); 195 196 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely. 197 if (Op0 && Op0->getOpcode() == Opcode) { 198 Value *A = Op0->getOperand(0); 199 Value *B = Op0->getOperand(1); 200 Value *C = RHS; 201 202 // Does "B op C" simplify? 203 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) { 204 // It does! Return "A op V" if it simplifies or is already available. 205 // If V equals B then "A op V" is just the LHS. 206 if (V == B) return LHS; 207 // Otherwise return "A op V" if it simplifies. 208 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) { 209 ++NumReassoc; 210 return W; 211 } 212 } 213 } 214 215 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely. 216 if (Op1 && Op1->getOpcode() == Opcode) { 217 Value *A = LHS; 218 Value *B = Op1->getOperand(0); 219 Value *C = Op1->getOperand(1); 220 221 // Does "A op B" simplify? 222 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) { 223 // It does! Return "V op C" if it simplifies or is already available. 224 // If V equals B then "V op C" is just the RHS. 225 if (V == B) return RHS; 226 // Otherwise return "V op C" if it simplifies. 227 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) { 228 ++NumReassoc; 229 return W; 230 } 231 } 232 } 233 234 // The remaining transforms require commutativity as well as associativity. 235 if (!Instruction::isCommutative(Opcode)) 236 return nullptr; 237 238 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely. 239 if (Op0 && Op0->getOpcode() == Opcode) { 240 Value *A = Op0->getOperand(0); 241 Value *B = Op0->getOperand(1); 242 Value *C = RHS; 243 244 // Does "C op A" simplify? 245 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) { 246 // It does! Return "V op B" if it simplifies or is already available. 247 // If V equals A then "V op B" is just the LHS. 248 if (V == A) return LHS; 249 // Otherwise return "V op B" if it simplifies. 250 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) { 251 ++NumReassoc; 252 return W; 253 } 254 } 255 } 256 257 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely. 258 if (Op1 && Op1->getOpcode() == Opcode) { 259 Value *A = LHS; 260 Value *B = Op1->getOperand(0); 261 Value *C = Op1->getOperand(1); 262 263 // Does "C op A" simplify? 264 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) { 265 // It does! Return "B op V" if it simplifies or is already available. 266 // If V equals C then "B op V" is just the RHS. 267 if (V == C) return RHS; 268 // Otherwise return "B op V" if it simplifies. 269 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) { 270 ++NumReassoc; 271 return W; 272 } 273 } 274 } 275 276 return nullptr; 277 } 278 279 /// In the case of a binary operation with a select instruction as an operand, 280 /// try to simplify the binop by seeing whether evaluating it on both branches 281 /// of the select results in the same value. Returns the common value if so, 282 /// otherwise returns null. 283 static Value *ThreadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS, 284 Value *RHS, const SimplifyQuery &Q, 285 unsigned MaxRecurse) { 286 // Recursion is always used, so bail out at once if we already hit the limit. 287 if (!MaxRecurse--) 288 return nullptr; 289 290 SelectInst *SI; 291 if (isa<SelectInst>(LHS)) { 292 SI = cast<SelectInst>(LHS); 293 } else { 294 assert(isa<SelectInst>(RHS) && "No select instruction operand!"); 295 SI = cast<SelectInst>(RHS); 296 } 297 298 // Evaluate the BinOp on the true and false branches of the select. 299 Value *TV; 300 Value *FV; 301 if (SI == LHS) { 302 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse); 303 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse); 304 } else { 305 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse); 306 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse); 307 } 308 309 // If they simplified to the same value, then return the common value. 310 // If they both failed to simplify then return null. 311 if (TV == FV) 312 return TV; 313 314 // If one branch simplified to undef, return the other one. 315 if (TV && isa<UndefValue>(TV)) 316 return FV; 317 if (FV && isa<UndefValue>(FV)) 318 return TV; 319 320 // If applying the operation did not change the true and false select values, 321 // then the result of the binop is the select itself. 322 if (TV == SI->getTrueValue() && FV == SI->getFalseValue()) 323 return SI; 324 325 // If one branch simplified and the other did not, and the simplified 326 // value is equal to the unsimplified one, return the simplified value. 327 // For example, select (cond, X, X & Z) & Z -> X & Z. 328 if ((FV && !TV) || (TV && !FV)) { 329 // Check that the simplified value has the form "X op Y" where "op" is the 330 // same as the original operation. 331 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV); 332 if (Simplified && Simplified->getOpcode() == unsigned(Opcode)) { 333 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS". 334 // We already know that "op" is the same as for the simplified value. See 335 // if the operands match too. If so, return the simplified value. 336 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue(); 337 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS; 338 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch; 339 if (Simplified->getOperand(0) == UnsimplifiedLHS && 340 Simplified->getOperand(1) == UnsimplifiedRHS) 341 return Simplified; 342 if (Simplified->isCommutative() && 343 Simplified->getOperand(1) == UnsimplifiedLHS && 344 Simplified->getOperand(0) == UnsimplifiedRHS) 345 return Simplified; 346 } 347 } 348 349 return nullptr; 350 } 351 352 /// In the case of a comparison with a select instruction, try to simplify the 353 /// comparison by seeing whether both branches of the select result in the same 354 /// value. Returns the common value if so, otherwise returns null. 355 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS, 356 Value *RHS, const SimplifyQuery &Q, 357 unsigned MaxRecurse) { 358 // Recursion is always used, so bail out at once if we already hit the limit. 359 if (!MaxRecurse--) 360 return nullptr; 361 362 // Make sure the select is on the LHS. 363 if (!isa<SelectInst>(LHS)) { 364 std::swap(LHS, RHS); 365 Pred = CmpInst::getSwappedPredicate(Pred); 366 } 367 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!"); 368 SelectInst *SI = cast<SelectInst>(LHS); 369 Value *Cond = SI->getCondition(); 370 Value *TV = SI->getTrueValue(); 371 Value *FV = SI->getFalseValue(); 372 373 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it. 374 // Does "cmp TV, RHS" simplify? 375 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse); 376 if (TCmp == Cond) { 377 // It not only simplified, it simplified to the select condition. Replace 378 // it with 'true'. 379 TCmp = getTrue(Cond->getType()); 380 } else if (!TCmp) { 381 // It didn't simplify. However if "cmp TV, RHS" is equal to the select 382 // condition then we can replace it with 'true'. Otherwise give up. 383 if (!isSameCompare(Cond, Pred, TV, RHS)) 384 return nullptr; 385 TCmp = getTrue(Cond->getType()); 386 } 387 388 // Does "cmp FV, RHS" simplify? 389 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse); 390 if (FCmp == Cond) { 391 // It not only simplified, it simplified to the select condition. Replace 392 // it with 'false'. 393 FCmp = getFalse(Cond->getType()); 394 } else if (!FCmp) { 395 // It didn't simplify. However if "cmp FV, RHS" is equal to the select 396 // condition then we can replace it with 'false'. Otherwise give up. 397 if (!isSameCompare(Cond, Pred, FV, RHS)) 398 return nullptr; 399 FCmp = getFalse(Cond->getType()); 400 } 401 402 // If both sides simplified to the same value, then use it as the result of 403 // the original comparison. 404 if (TCmp == FCmp) 405 return TCmp; 406 407 // The remaining cases only make sense if the select condition has the same 408 // type as the result of the comparison, so bail out if this is not so. 409 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy()) 410 return nullptr; 411 // If the false value simplified to false, then the result of the compare 412 // is equal to "Cond && TCmp". This also catches the case when the false 413 // value simplified to false and the true value to true, returning "Cond". 414 if (match(FCmp, m_Zero())) 415 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse)) 416 return V; 417 // If the true value simplified to true, then the result of the compare 418 // is equal to "Cond || FCmp". 419 if (match(TCmp, m_One())) 420 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse)) 421 return V; 422 // Finally, if the false value simplified to true and the true value to 423 // false, then the result of the compare is equal to "!Cond". 424 if (match(FCmp, m_One()) && match(TCmp, m_Zero())) 425 if (Value *V = 426 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()), 427 Q, MaxRecurse)) 428 return V; 429 430 return nullptr; 431 } 432 433 /// In the case of a binary operation with an operand that is a PHI instruction, 434 /// try to simplify the binop by seeing whether evaluating it on the incoming 435 /// phi values yields the same result for every value. If so returns the common 436 /// value, otherwise returns null. 437 static Value *ThreadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS, 438 Value *RHS, const SimplifyQuery &Q, 439 unsigned MaxRecurse) { 440 // Recursion is always used, so bail out at once if we already hit the limit. 441 if (!MaxRecurse--) 442 return nullptr; 443 444 PHINode *PI; 445 if (isa<PHINode>(LHS)) { 446 PI = cast<PHINode>(LHS); 447 // Bail out if RHS and the phi may be mutually interdependent due to a loop. 448 if (!valueDominatesPHI(RHS, PI, Q.DT)) 449 return nullptr; 450 } else { 451 assert(isa<PHINode>(RHS) && "No PHI instruction operand!"); 452 PI = cast<PHINode>(RHS); 453 // Bail out if LHS and the phi may be mutually interdependent due to a loop. 454 if (!valueDominatesPHI(LHS, PI, Q.DT)) 455 return nullptr; 456 } 457 458 // Evaluate the BinOp on the incoming phi values. 459 Value *CommonValue = nullptr; 460 for (Value *Incoming : PI->incoming_values()) { 461 // If the incoming value is the phi node itself, it can safely be skipped. 462 if (Incoming == PI) continue; 463 Value *V = PI == LHS ? 464 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) : 465 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse); 466 // If the operation failed to simplify, or simplified to a different value 467 // to previously, then give up. 468 if (!V || (CommonValue && V != CommonValue)) 469 return nullptr; 470 CommonValue = V; 471 } 472 473 return CommonValue; 474 } 475 476 /// In the case of a comparison with a PHI instruction, try to simplify the 477 /// comparison by seeing whether comparing with all of the incoming phi values 478 /// yields the same result every time. If so returns the common result, 479 /// otherwise returns null. 480 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS, 481 const SimplifyQuery &Q, unsigned MaxRecurse) { 482 // Recursion is always used, so bail out at once if we already hit the limit. 483 if (!MaxRecurse--) 484 return nullptr; 485 486 // Make sure the phi is on the LHS. 487 if (!isa<PHINode>(LHS)) { 488 std::swap(LHS, RHS); 489 Pred = CmpInst::getSwappedPredicate(Pred); 490 } 491 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!"); 492 PHINode *PI = cast<PHINode>(LHS); 493 494 // Bail out if RHS and the phi may be mutually interdependent due to a loop. 495 if (!valueDominatesPHI(RHS, PI, Q.DT)) 496 return nullptr; 497 498 // Evaluate the BinOp on the incoming phi values. 499 Value *CommonValue = nullptr; 500 for (Value *Incoming : PI->incoming_values()) { 501 // If the incoming value is the phi node itself, it can safely be skipped. 502 if (Incoming == PI) continue; 503 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse); 504 // If the operation failed to simplify, or simplified to a different value 505 // to previously, then give up. 506 if (!V || (CommonValue && V != CommonValue)) 507 return nullptr; 508 CommonValue = V; 509 } 510 511 return CommonValue; 512 } 513 514 static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode, 515 Value *&Op0, Value *&Op1, 516 const SimplifyQuery &Q) { 517 if (auto *CLHS = dyn_cast<Constant>(Op0)) { 518 if (auto *CRHS = dyn_cast<Constant>(Op1)) 519 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL); 520 521 // Canonicalize the constant to the RHS if this is a commutative operation. 522 if (Instruction::isCommutative(Opcode)) 523 std::swap(Op0, Op1); 524 } 525 return nullptr; 526 } 527 528 /// Given operands for an Add, see if we can fold the result. 529 /// If not, this returns null. 530 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW, 531 const SimplifyQuery &Q, unsigned MaxRecurse) { 532 if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q)) 533 return C; 534 535 // X + undef -> undef 536 if (match(Op1, m_Undef())) 537 return Op1; 538 539 // X + 0 -> X 540 if (match(Op1, m_Zero())) 541 return Op0; 542 543 // If two operands are negative, return 0. 544 if (isKnownNegation(Op0, Op1)) 545 return Constant::getNullValue(Op0->getType()); 546 547 // X + (Y - X) -> Y 548 // (Y - X) + X -> Y 549 // Eg: X + -X -> 0 550 Value *Y = nullptr; 551 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) || 552 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1)))) 553 return Y; 554 555 // X + ~X -> -1 since ~X = -X-1 556 Type *Ty = Op0->getType(); 557 if (match(Op0, m_Not(m_Specific(Op1))) || 558 match(Op1, m_Not(m_Specific(Op0)))) 559 return Constant::getAllOnesValue(Ty); 560 561 // add nsw/nuw (xor Y, signmask), signmask --> Y 562 // The no-wrapping add guarantees that the top bit will be set by the add. 563 // Therefore, the xor must be clearing the already set sign bit of Y. 564 if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) && 565 match(Op0, m_Xor(m_Value(Y), m_SignMask()))) 566 return Y; 567 568 // add nuw %x, -1 -> -1, because %x can only be 0. 569 if (IsNUW && match(Op1, m_AllOnes())) 570 return Op1; // Which is -1. 571 572 /// i1 add -> xor. 573 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1)) 574 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1)) 575 return V; 576 577 // Try some generic simplifications for associative operations. 578 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q, 579 MaxRecurse)) 580 return V; 581 582 // Threading Add over selects and phi nodes is pointless, so don't bother. 583 // Threading over the select in "A + select(cond, B, C)" means evaluating 584 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and 585 // only if B and C are equal. If B and C are equal then (since we assume 586 // that operands have already been simplified) "select(cond, B, C)" should 587 // have been simplified to the common value of B and C already. Analysing 588 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly 589 // for threading over phi nodes. 590 591 return nullptr; 592 } 593 594 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW, 595 const SimplifyQuery &Query) { 596 return ::SimplifyAddInst(Op0, Op1, IsNSW, IsNUW, Query, RecursionLimit); 597 } 598 599 /// Compute the base pointer and cumulative constant offsets for V. 600 /// 601 /// This strips all constant offsets off of V, leaving it the base pointer, and 602 /// accumulates the total constant offset applied in the returned constant. It 603 /// returns 0 if V is not a pointer, and returns the constant '0' if there are 604 /// no constant offsets applied. 605 /// 606 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't 607 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc. 608 /// folding. 609 static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V, 610 bool AllowNonInbounds = false) { 611 assert(V->getType()->isPtrOrPtrVectorTy()); 612 613 Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType(); 614 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth()); 615 616 // Even though we don't look through PHI nodes, we could be called on an 617 // instruction in an unreachable block, which may be on a cycle. 618 SmallPtrSet<Value *, 4> Visited; 619 Visited.insert(V); 620 do { 621 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { 622 if ((!AllowNonInbounds && !GEP->isInBounds()) || 623 !GEP->accumulateConstantOffset(DL, Offset)) 624 break; 625 V = GEP->getPointerOperand(); 626 } else if (Operator::getOpcode(V) == Instruction::BitCast) { 627 V = cast<Operator>(V)->getOperand(0); 628 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 629 if (GA->isInterposable()) 630 break; 631 V = GA->getAliasee(); 632 } else { 633 if (auto CS = CallSite(V)) 634 if (Value *RV = CS.getReturnedArgOperand()) { 635 V = RV; 636 continue; 637 } 638 break; 639 } 640 assert(V->getType()->isPtrOrPtrVectorTy() && "Unexpected operand type!"); 641 } while (Visited.insert(V).second); 642 643 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset); 644 if (V->getType()->isVectorTy()) 645 return ConstantVector::getSplat(V->getType()->getVectorNumElements(), 646 OffsetIntPtr); 647 return OffsetIntPtr; 648 } 649 650 /// Compute the constant difference between two pointer values. 651 /// If the difference is not a constant, returns zero. 652 static Constant *computePointerDifference(const DataLayout &DL, Value *LHS, 653 Value *RHS) { 654 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS); 655 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS); 656 657 // If LHS and RHS are not related via constant offsets to the same base 658 // value, there is nothing we can do here. 659 if (LHS != RHS) 660 return nullptr; 661 662 // Otherwise, the difference of LHS - RHS can be computed as: 663 // LHS - RHS 664 // = (LHSOffset + Base) - (RHSOffset + Base) 665 // = LHSOffset - RHSOffset 666 return ConstantExpr::getSub(LHSOffset, RHSOffset); 667 } 668 669 /// Given operands for a Sub, see if we can fold the result. 670 /// If not, this returns null. 671 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 672 const SimplifyQuery &Q, unsigned MaxRecurse) { 673 if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q)) 674 return C; 675 676 // X - undef -> undef 677 // undef - X -> undef 678 if (match(Op0, m_Undef()) || match(Op1, m_Undef())) 679 return UndefValue::get(Op0->getType()); 680 681 // X - 0 -> X 682 if (match(Op1, m_Zero())) 683 return Op0; 684 685 // X - X -> 0 686 if (Op0 == Op1) 687 return Constant::getNullValue(Op0->getType()); 688 689 // Is this a negation? 690 if (match(Op0, m_Zero())) { 691 // 0 - X -> 0 if the sub is NUW. 692 if (isNUW) 693 return Constant::getNullValue(Op0->getType()); 694 695 KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 696 if (Known.Zero.isMaxSignedValue()) { 697 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then 698 // Op1 must be 0 because negating the minimum signed value is undefined. 699 if (isNSW) 700 return Constant::getNullValue(Op0->getType()); 701 702 // 0 - X -> X if X is 0 or the minimum signed value. 703 return Op1; 704 } 705 } 706 707 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies. 708 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X 709 Value *X = nullptr, *Y = nullptr, *Z = Op1; 710 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z 711 // See if "V === Y - Z" simplifies. 712 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1)) 713 // It does! Now see if "X + V" simplifies. 714 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) { 715 // It does, we successfully reassociated! 716 ++NumReassoc; 717 return W; 718 } 719 // See if "V === X - Z" simplifies. 720 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1)) 721 // It does! Now see if "Y + V" simplifies. 722 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) { 723 // It does, we successfully reassociated! 724 ++NumReassoc; 725 return W; 726 } 727 } 728 729 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies. 730 // For example, X - (X + 1) -> -1 731 X = Op0; 732 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z) 733 // See if "V === X - Y" simplifies. 734 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1)) 735 // It does! Now see if "V - Z" simplifies. 736 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) { 737 // It does, we successfully reassociated! 738 ++NumReassoc; 739 return W; 740 } 741 // See if "V === X - Z" simplifies. 742 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1)) 743 // It does! Now see if "V - Y" simplifies. 744 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) { 745 // It does, we successfully reassociated! 746 ++NumReassoc; 747 return W; 748 } 749 } 750 751 // Z - (X - Y) -> (Z - X) + Y if everything simplifies. 752 // For example, X - (X - Y) -> Y. 753 Z = Op0; 754 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y) 755 // See if "V === Z - X" simplifies. 756 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1)) 757 // It does! Now see if "V + Y" simplifies. 758 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) { 759 // It does, we successfully reassociated! 760 ++NumReassoc; 761 return W; 762 } 763 764 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies. 765 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) && 766 match(Op1, m_Trunc(m_Value(Y)))) 767 if (X->getType() == Y->getType()) 768 // See if "V === X - Y" simplifies. 769 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1)) 770 // It does! Now see if "trunc V" simplifies. 771 if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(), 772 Q, MaxRecurse - 1)) 773 // It does, return the simplified "trunc V". 774 return W; 775 776 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...). 777 if (match(Op0, m_PtrToInt(m_Value(X))) && 778 match(Op1, m_PtrToInt(m_Value(Y)))) 779 if (Constant *Result = computePointerDifference(Q.DL, X, Y)) 780 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true); 781 782 // i1 sub -> xor. 783 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1)) 784 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1)) 785 return V; 786 787 // Threading Sub over selects and phi nodes is pointless, so don't bother. 788 // Threading over the select in "A - select(cond, B, C)" means evaluating 789 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and 790 // only if B and C are equal. If B and C are equal then (since we assume 791 // that operands have already been simplified) "select(cond, B, C)" should 792 // have been simplified to the common value of B and C already. Analysing 793 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly 794 // for threading over phi nodes. 795 796 return nullptr; 797 } 798 799 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 800 const SimplifyQuery &Q) { 801 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit); 802 } 803 804 /// Given operands for a Mul, see if we can fold the result. 805 /// If not, this returns null. 806 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 807 unsigned MaxRecurse) { 808 if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q)) 809 return C; 810 811 // X * undef -> 0 812 // X * 0 -> 0 813 if (match(Op1, m_CombineOr(m_Undef(), m_Zero()))) 814 return Constant::getNullValue(Op0->getType()); 815 816 // X * 1 -> X 817 if (match(Op1, m_One())) 818 return Op0; 819 820 // (X / Y) * Y -> X if the division is exact. 821 Value *X = nullptr; 822 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y 823 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y) 824 return X; 825 826 // i1 mul -> and. 827 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1)) 828 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1)) 829 return V; 830 831 // Try some generic simplifications for associative operations. 832 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q, 833 MaxRecurse)) 834 return V; 835 836 // Mul distributes over Add. Try some generic simplifications based on this. 837 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add, 838 Q, MaxRecurse)) 839 return V; 840 841 // If the operation is with the result of a select instruction, check whether 842 // operating on either branch of the select always yields the same value. 843 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 844 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q, 845 MaxRecurse)) 846 return V; 847 848 // If the operation is with the result of a phi instruction, check whether 849 // operating on all incoming values of the phi always yields the same value. 850 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 851 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q, 852 MaxRecurse)) 853 return V; 854 855 return nullptr; 856 } 857 858 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 859 return ::SimplifyMulInst(Op0, Op1, Q, RecursionLimit); 860 } 861 862 /// Check for common or similar folds of integer division or integer remainder. 863 /// This applies to all 4 opcodes (sdiv/udiv/srem/urem). 864 static Value *simplifyDivRem(Value *Op0, Value *Op1, bool IsDiv) { 865 Type *Ty = Op0->getType(); 866 867 // X / undef -> undef 868 // X % undef -> undef 869 if (match(Op1, m_Undef())) 870 return Op1; 871 872 // X / 0 -> undef 873 // X % 0 -> undef 874 // We don't need to preserve faults! 875 if (match(Op1, m_Zero())) 876 return UndefValue::get(Ty); 877 878 // If any element of a constant divisor vector is zero or undef, the whole op 879 // is undef. 880 auto *Op1C = dyn_cast<Constant>(Op1); 881 if (Op1C && Ty->isVectorTy()) { 882 unsigned NumElts = Ty->getVectorNumElements(); 883 for (unsigned i = 0; i != NumElts; ++i) { 884 Constant *Elt = Op1C->getAggregateElement(i); 885 if (Elt && (Elt->isNullValue() || isa<UndefValue>(Elt))) 886 return UndefValue::get(Ty); 887 } 888 } 889 890 // undef / X -> 0 891 // undef % X -> 0 892 if (match(Op0, m_Undef())) 893 return Constant::getNullValue(Ty); 894 895 // 0 / X -> 0 896 // 0 % X -> 0 897 if (match(Op0, m_Zero())) 898 return Constant::getNullValue(Op0->getType()); 899 900 // X / X -> 1 901 // X % X -> 0 902 if (Op0 == Op1) 903 return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty); 904 905 // X / 1 -> X 906 // X % 1 -> 0 907 // If this is a boolean op (single-bit element type), we can't have 908 // division-by-zero or remainder-by-zero, so assume the divisor is 1. 909 // Similarly, if we're zero-extending a boolean divisor, then assume it's a 1. 910 Value *X; 911 if (match(Op1, m_One()) || Ty->isIntOrIntVectorTy(1) || 912 (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))) 913 return IsDiv ? Op0 : Constant::getNullValue(Ty); 914 915 return nullptr; 916 } 917 918 /// Given a predicate and two operands, return true if the comparison is true. 919 /// This is a helper for div/rem simplification where we return some other value 920 /// when we can prove a relationship between the operands. 921 static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS, 922 const SimplifyQuery &Q, unsigned MaxRecurse) { 923 Value *V = SimplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse); 924 Constant *C = dyn_cast_or_null<Constant>(V); 925 return (C && C->isAllOnesValue()); 926 } 927 928 /// Return true if we can simplify X / Y to 0. Remainder can adapt that answer 929 /// to simplify X % Y to X. 930 static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q, 931 unsigned MaxRecurse, bool IsSigned) { 932 // Recursion is always used, so bail out at once if we already hit the limit. 933 if (!MaxRecurse--) 934 return false; 935 936 if (IsSigned) { 937 // |X| / |Y| --> 0 938 // 939 // We require that 1 operand is a simple constant. That could be extended to 940 // 2 variables if we computed the sign bit for each. 941 // 942 // Make sure that a constant is not the minimum signed value because taking 943 // the abs() of that is undefined. 944 Type *Ty = X->getType(); 945 const APInt *C; 946 if (match(X, m_APInt(C)) && !C->isMinSignedValue()) { 947 // Is the variable divisor magnitude always greater than the constant 948 // dividend magnitude? 949 // |Y| > |C| --> Y < -abs(C) or Y > abs(C) 950 Constant *PosDividendC = ConstantInt::get(Ty, C->abs()); 951 Constant *NegDividendC = ConstantInt::get(Ty, -C->abs()); 952 if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) || 953 isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse)) 954 return true; 955 } 956 if (match(Y, m_APInt(C))) { 957 // Special-case: we can't take the abs() of a minimum signed value. If 958 // that's the divisor, then all we have to do is prove that the dividend 959 // is also not the minimum signed value. 960 if (C->isMinSignedValue()) 961 return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse); 962 963 // Is the variable dividend magnitude always less than the constant 964 // divisor magnitude? 965 // |X| < |C| --> X > -abs(C) and X < abs(C) 966 Constant *PosDivisorC = ConstantInt::get(Ty, C->abs()); 967 Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs()); 968 if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) && 969 isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse)) 970 return true; 971 } 972 return false; 973 } 974 975 // IsSigned == false. 976 // Is the dividend unsigned less than the divisor? 977 return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse); 978 } 979 980 /// These are simplifications common to SDiv and UDiv. 981 static Value *simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, 982 const SimplifyQuery &Q, unsigned MaxRecurse) { 983 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q)) 984 return C; 985 986 if (Value *V = simplifyDivRem(Op0, Op1, true)) 987 return V; 988 989 bool IsSigned = Opcode == Instruction::SDiv; 990 991 // (X * Y) / Y -> X if the multiplication does not overflow. 992 Value *X; 993 if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) { 994 auto *Mul = cast<OverflowingBinaryOperator>(Op0); 995 // If the Mul does not overflow, then we are good to go. 996 if ((IsSigned && Mul->hasNoSignedWrap()) || 997 (!IsSigned && Mul->hasNoUnsignedWrap())) 998 return X; 999 // If X has the form X = A / Y, then X * Y cannot overflow. 1000 if ((IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) || 1001 (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1))))) 1002 return X; 1003 } 1004 1005 // (X rem Y) / Y -> 0 1006 if ((IsSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) || 1007 (!IsSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1))))) 1008 return Constant::getNullValue(Op0->getType()); 1009 1010 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow 1011 ConstantInt *C1, *C2; 1012 if (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) && 1013 match(Op1, m_ConstantInt(C2))) { 1014 bool Overflow; 1015 (void)C1->getValue().umul_ov(C2->getValue(), Overflow); 1016 if (Overflow) 1017 return Constant::getNullValue(Op0->getType()); 1018 } 1019 1020 // If the operation is with the result of a select instruction, check whether 1021 // operating on either branch of the select always yields the same value. 1022 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1023 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) 1024 return V; 1025 1026 // If the operation is with the result of a phi instruction, check whether 1027 // operating on all incoming values of the phi always yields the same value. 1028 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1029 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) 1030 return V; 1031 1032 if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned)) 1033 return Constant::getNullValue(Op0->getType()); 1034 1035 return nullptr; 1036 } 1037 1038 /// These are simplifications common to SRem and URem. 1039 static Value *simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, 1040 const SimplifyQuery &Q, unsigned MaxRecurse) { 1041 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q)) 1042 return C; 1043 1044 if (Value *V = simplifyDivRem(Op0, Op1, false)) 1045 return V; 1046 1047 // (X % Y) % Y -> X % Y 1048 if ((Opcode == Instruction::SRem && 1049 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) || 1050 (Opcode == Instruction::URem && 1051 match(Op0, m_URem(m_Value(), m_Specific(Op1))))) 1052 return Op0; 1053 1054 // (X << Y) % X -> 0 1055 if ((Opcode == Instruction::SRem && 1056 match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) || 1057 (Opcode == Instruction::URem && 1058 match(Op0, m_NUWShl(m_Specific(Op1), m_Value())))) 1059 return Constant::getNullValue(Op0->getType()); 1060 1061 // If the operation is with the result of a select instruction, check whether 1062 // operating on either branch of the select always yields the same value. 1063 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1064 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) 1065 return V; 1066 1067 // If the operation is with the result of a phi instruction, check whether 1068 // operating on all incoming values of the phi always yields the same value. 1069 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1070 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) 1071 return V; 1072 1073 // If X / Y == 0, then X % Y == X. 1074 if (isDivZero(Op0, Op1, Q, MaxRecurse, Opcode == Instruction::SRem)) 1075 return Op0; 1076 1077 return nullptr; 1078 } 1079 1080 /// Given operands for an SDiv, see if we can fold the result. 1081 /// If not, this returns null. 1082 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 1083 unsigned MaxRecurse) { 1084 return simplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse); 1085 } 1086 1087 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 1088 return ::SimplifySDivInst(Op0, Op1, Q, RecursionLimit); 1089 } 1090 1091 /// Given operands for a UDiv, see if we can fold the result. 1092 /// If not, this returns null. 1093 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 1094 unsigned MaxRecurse) { 1095 return simplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse); 1096 } 1097 1098 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 1099 return ::SimplifyUDivInst(Op0, Op1, Q, RecursionLimit); 1100 } 1101 1102 /// Given operands for an SRem, see if we can fold the result. 1103 /// If not, this returns null. 1104 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 1105 unsigned MaxRecurse) { 1106 // If the divisor is 0, the result is undefined, so assume the divisor is -1. 1107 // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0 1108 Value *X; 1109 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) 1110 return ConstantInt::getNullValue(Op0->getType()); 1111 1112 return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse); 1113 } 1114 1115 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 1116 return ::SimplifySRemInst(Op0, Op1, Q, RecursionLimit); 1117 } 1118 1119 /// Given operands for a URem, see if we can fold the result. 1120 /// If not, this returns null. 1121 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 1122 unsigned MaxRecurse) { 1123 return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse); 1124 } 1125 1126 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 1127 return ::SimplifyURemInst(Op0, Op1, Q, RecursionLimit); 1128 } 1129 1130 /// Returns true if a shift by \c Amount always yields undef. 1131 static bool isUndefShift(Value *Amount) { 1132 Constant *C = dyn_cast<Constant>(Amount); 1133 if (!C) 1134 return false; 1135 1136 // X shift by undef -> undef because it may shift by the bitwidth. 1137 if (isa<UndefValue>(C)) 1138 return true; 1139 1140 // Shifting by the bitwidth or more is undefined. 1141 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1142 if (CI->getValue().getLimitedValue() >= 1143 CI->getType()->getScalarSizeInBits()) 1144 return true; 1145 1146 // If all lanes of a vector shift are undefined the whole shift is. 1147 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) { 1148 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I) 1149 if (!isUndefShift(C->getAggregateElement(I))) 1150 return false; 1151 return true; 1152 } 1153 1154 return false; 1155 } 1156 1157 /// Given operands for an Shl, LShr or AShr, see if we can fold the result. 1158 /// If not, this returns null. 1159 static Value *SimplifyShift(Instruction::BinaryOps Opcode, Value *Op0, 1160 Value *Op1, const SimplifyQuery &Q, unsigned MaxRecurse) { 1161 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q)) 1162 return C; 1163 1164 // 0 shift by X -> 0 1165 if (match(Op0, m_Zero())) 1166 return Constant::getNullValue(Op0->getType()); 1167 1168 // X shift by 0 -> X 1169 // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones 1170 // would be poison. 1171 Value *X; 1172 if (match(Op1, m_Zero()) || 1173 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))) 1174 return Op0; 1175 1176 // Fold undefined shifts. 1177 if (isUndefShift(Op1)) 1178 return UndefValue::get(Op0->getType()); 1179 1180 // If the operation is with the result of a select instruction, check whether 1181 // operating on either branch of the select always yields the same value. 1182 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1183 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) 1184 return V; 1185 1186 // If the operation is with the result of a phi instruction, check whether 1187 // operating on all incoming values of the phi always yields the same value. 1188 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1189 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) 1190 return V; 1191 1192 // If any bits in the shift amount make that value greater than or equal to 1193 // the number of bits in the type, the shift is undefined. 1194 KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 1195 if (Known.One.getLimitedValue() >= Known.getBitWidth()) 1196 return UndefValue::get(Op0->getType()); 1197 1198 // If all valid bits in the shift amount are known zero, the first operand is 1199 // unchanged. 1200 unsigned NumValidShiftBits = Log2_32_Ceil(Known.getBitWidth()); 1201 if (Known.countMinTrailingZeros() >= NumValidShiftBits) 1202 return Op0; 1203 1204 return nullptr; 1205 } 1206 1207 /// Given operands for an Shl, LShr or AShr, see if we can 1208 /// fold the result. If not, this returns null. 1209 static Value *SimplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0, 1210 Value *Op1, bool isExact, const SimplifyQuery &Q, 1211 unsigned MaxRecurse) { 1212 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse)) 1213 return V; 1214 1215 // X >> X -> 0 1216 if (Op0 == Op1) 1217 return Constant::getNullValue(Op0->getType()); 1218 1219 // undef >> X -> 0 1220 // undef >> X -> undef (if it's exact) 1221 if (match(Op0, m_Undef())) 1222 return isExact ? Op0 : Constant::getNullValue(Op0->getType()); 1223 1224 // The low bit cannot be shifted out of an exact shift if it is set. 1225 if (isExact) { 1226 KnownBits Op0Known = computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT); 1227 if (Op0Known.One[0]) 1228 return Op0; 1229 } 1230 1231 return nullptr; 1232 } 1233 1234 /// Given operands for an Shl, see if we can fold the result. 1235 /// If not, this returns null. 1236 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 1237 const SimplifyQuery &Q, unsigned MaxRecurse) { 1238 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse)) 1239 return V; 1240 1241 // undef << X -> 0 1242 // undef << X -> undef if (if it's NSW/NUW) 1243 if (match(Op0, m_Undef())) 1244 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType()); 1245 1246 // (X >> A) << A -> X 1247 Value *X; 1248 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1))))) 1249 return X; 1250 1251 // shl nuw i8 C, %x -> C iff C has sign bit set. 1252 if (isNUW && match(Op0, m_Negative())) 1253 return Op0; 1254 // NOTE: could use computeKnownBits() / LazyValueInfo, 1255 // but the cost-benefit analysis suggests it isn't worth it. 1256 1257 return nullptr; 1258 } 1259 1260 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 1261 const SimplifyQuery &Q) { 1262 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit); 1263 } 1264 1265 /// Given operands for an LShr, see if we can fold the result. 1266 /// If not, this returns null. 1267 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact, 1268 const SimplifyQuery &Q, unsigned MaxRecurse) { 1269 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q, 1270 MaxRecurse)) 1271 return V; 1272 1273 // (X << A) >> A -> X 1274 Value *X; 1275 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1)))) 1276 return X; 1277 1278 return nullptr; 1279 } 1280 1281 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact, 1282 const SimplifyQuery &Q) { 1283 return ::SimplifyLShrInst(Op0, Op1, isExact, Q, RecursionLimit); 1284 } 1285 1286 /// Given operands for an AShr, see if we can fold the result. 1287 /// If not, this returns null. 1288 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact, 1289 const SimplifyQuery &Q, unsigned MaxRecurse) { 1290 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q, 1291 MaxRecurse)) 1292 return V; 1293 1294 // all ones >>a X -> -1 1295 // Do not return Op0 because it may contain undef elements if it's a vector. 1296 if (match(Op0, m_AllOnes())) 1297 return Constant::getAllOnesValue(Op0->getType()); 1298 1299 // (X << A) >> A -> X 1300 Value *X; 1301 if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1)))) 1302 return X; 1303 1304 // Arithmetic shifting an all-sign-bit value is a no-op. 1305 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 1306 if (NumSignBits == Op0->getType()->getScalarSizeInBits()) 1307 return Op0; 1308 1309 return nullptr; 1310 } 1311 1312 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact, 1313 const SimplifyQuery &Q) { 1314 return ::SimplifyAShrInst(Op0, Op1, isExact, Q, RecursionLimit); 1315 } 1316 1317 /// Commuted variants are assumed to be handled by calling this function again 1318 /// with the parameters swapped. 1319 static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp, 1320 ICmpInst *UnsignedICmp, bool IsAnd) { 1321 Value *X, *Y; 1322 1323 ICmpInst::Predicate EqPred; 1324 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) || 1325 !ICmpInst::isEquality(EqPred)) 1326 return nullptr; 1327 1328 ICmpInst::Predicate UnsignedPred; 1329 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) && 1330 ICmpInst::isUnsigned(UnsignedPred)) 1331 ; 1332 else if (match(UnsignedICmp, 1333 m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) && 1334 ICmpInst::isUnsigned(UnsignedPred)) 1335 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred); 1336 else 1337 return nullptr; 1338 1339 // X < Y && Y != 0 --> X < Y 1340 // X < Y || Y != 0 --> Y != 0 1341 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE) 1342 return IsAnd ? UnsignedICmp : ZeroICmp; 1343 1344 // X >= Y || Y != 0 --> true 1345 // X >= Y || Y == 0 --> X >= Y 1346 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) { 1347 if (EqPred == ICmpInst::ICMP_NE) 1348 return getTrue(UnsignedICmp->getType()); 1349 return UnsignedICmp; 1350 } 1351 1352 // X < Y && Y == 0 --> false 1353 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ && 1354 IsAnd) 1355 return getFalse(UnsignedICmp->getType()); 1356 1357 return nullptr; 1358 } 1359 1360 /// Commuted variants are assumed to be handled by calling this function again 1361 /// with the parameters swapped. 1362 static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) { 1363 ICmpInst::Predicate Pred0, Pred1; 1364 Value *A ,*B; 1365 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) || 1366 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B)))) 1367 return nullptr; 1368 1369 // We have (icmp Pred0, A, B) & (icmp Pred1, A, B). 1370 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we 1371 // can eliminate Op1 from this 'and'. 1372 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1)) 1373 return Op0; 1374 1375 // Check for any combination of predicates that are guaranteed to be disjoint. 1376 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) || 1377 (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) || 1378 (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) || 1379 (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)) 1380 return getFalse(Op0->getType()); 1381 1382 return nullptr; 1383 } 1384 1385 /// Commuted variants are assumed to be handled by calling this function again 1386 /// with the parameters swapped. 1387 static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) { 1388 ICmpInst::Predicate Pred0, Pred1; 1389 Value *A ,*B; 1390 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) || 1391 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B)))) 1392 return nullptr; 1393 1394 // We have (icmp Pred0, A, B) | (icmp Pred1, A, B). 1395 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we 1396 // can eliminate Op0 from this 'or'. 1397 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1)) 1398 return Op1; 1399 1400 // Check for any combination of predicates that cover the entire range of 1401 // possibilities. 1402 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) || 1403 (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) || 1404 (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) || 1405 (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE)) 1406 return getTrue(Op0->getType()); 1407 1408 return nullptr; 1409 } 1410 1411 /// Test if a pair of compares with a shared operand and 2 constants has an 1412 /// empty set intersection, full set union, or if one compare is a superset of 1413 /// the other. 1414 static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1, 1415 bool IsAnd) { 1416 // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)). 1417 if (Cmp0->getOperand(0) != Cmp1->getOperand(0)) 1418 return nullptr; 1419 1420 const APInt *C0, *C1; 1421 if (!match(Cmp0->getOperand(1), m_APInt(C0)) || 1422 !match(Cmp1->getOperand(1), m_APInt(C1))) 1423 return nullptr; 1424 1425 auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0); 1426 auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1); 1427 1428 // For and-of-compares, check if the intersection is empty: 1429 // (icmp X, C0) && (icmp X, C1) --> empty set --> false 1430 if (IsAnd && Range0.intersectWith(Range1).isEmptySet()) 1431 return getFalse(Cmp0->getType()); 1432 1433 // For or-of-compares, check if the union is full: 1434 // (icmp X, C0) || (icmp X, C1) --> full set --> true 1435 if (!IsAnd && Range0.unionWith(Range1).isFullSet()) 1436 return getTrue(Cmp0->getType()); 1437 1438 // Is one range a superset of the other? 1439 // If this is and-of-compares, take the smaller set: 1440 // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42 1441 // If this is or-of-compares, take the larger set: 1442 // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4 1443 if (Range0.contains(Range1)) 1444 return IsAnd ? Cmp1 : Cmp0; 1445 if (Range1.contains(Range0)) 1446 return IsAnd ? Cmp0 : Cmp1; 1447 1448 return nullptr; 1449 } 1450 1451 static Value *simplifyAndOrOfICmpsWithZero(ICmpInst *Cmp0, ICmpInst *Cmp1, 1452 bool IsAnd) { 1453 ICmpInst::Predicate P0 = Cmp0->getPredicate(), P1 = Cmp1->getPredicate(); 1454 if (!match(Cmp0->getOperand(1), m_Zero()) || 1455 !match(Cmp1->getOperand(1), m_Zero()) || P0 != P1) 1456 return nullptr; 1457 1458 if ((IsAnd && P0 != ICmpInst::ICMP_NE) || (!IsAnd && P1 != ICmpInst::ICMP_EQ)) 1459 return nullptr; 1460 1461 // We have either "(X == 0 || Y == 0)" or "(X != 0 && Y != 0)". 1462 Value *X = Cmp0->getOperand(0); 1463 Value *Y = Cmp1->getOperand(0); 1464 1465 // If one of the compares is a masked version of a (not) null check, then 1466 // that compare implies the other, so we eliminate the other. Optionally, look 1467 // through a pointer-to-int cast to match a null check of a pointer type. 1468 1469 // (X == 0) || (([ptrtoint] X & ?) == 0) --> ([ptrtoint] X & ?) == 0 1470 // (X == 0) || ((? & [ptrtoint] X) == 0) --> (? & [ptrtoint] X) == 0 1471 // (X != 0) && (([ptrtoint] X & ?) != 0) --> ([ptrtoint] X & ?) != 0 1472 // (X != 0) && ((? & [ptrtoint] X) != 0) --> (? & [ptrtoint] X) != 0 1473 if (match(Y, m_c_And(m_Specific(X), m_Value())) || 1474 match(Y, m_c_And(m_PtrToInt(m_Specific(X)), m_Value()))) 1475 return Cmp1; 1476 1477 // (([ptrtoint] Y & ?) == 0) || (Y == 0) --> ([ptrtoint] Y & ?) == 0 1478 // ((? & [ptrtoint] Y) == 0) || (Y == 0) --> (? & [ptrtoint] Y) == 0 1479 // (([ptrtoint] Y & ?) != 0) && (Y != 0) --> ([ptrtoint] Y & ?) != 0 1480 // ((? & [ptrtoint] Y) != 0) && (Y != 0) --> (? & [ptrtoint] Y) != 0 1481 if (match(X, m_c_And(m_Specific(Y), m_Value())) || 1482 match(X, m_c_And(m_PtrToInt(m_Specific(Y)), m_Value()))) 1483 return Cmp0; 1484 1485 return nullptr; 1486 } 1487 1488 static Value *simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1) { 1489 // (icmp (add V, C0), C1) & (icmp V, C0) 1490 ICmpInst::Predicate Pred0, Pred1; 1491 const APInt *C0, *C1; 1492 Value *V; 1493 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1)))) 1494 return nullptr; 1495 1496 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value()))) 1497 return nullptr; 1498 1499 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0)); 1500 if (AddInst->getOperand(1) != Op1->getOperand(1)) 1501 return nullptr; 1502 1503 Type *ITy = Op0->getType(); 1504 bool isNSW = AddInst->hasNoSignedWrap(); 1505 bool isNUW = AddInst->hasNoUnsignedWrap(); 1506 1507 const APInt Delta = *C1 - *C0; 1508 if (C0->isStrictlyPositive()) { 1509 if (Delta == 2) { 1510 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT) 1511 return getFalse(ITy); 1512 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW) 1513 return getFalse(ITy); 1514 } 1515 if (Delta == 1) { 1516 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT) 1517 return getFalse(ITy); 1518 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW) 1519 return getFalse(ITy); 1520 } 1521 } 1522 if (C0->getBoolValue() && isNUW) { 1523 if (Delta == 2) 1524 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT) 1525 return getFalse(ITy); 1526 if (Delta == 1) 1527 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT) 1528 return getFalse(ITy); 1529 } 1530 1531 return nullptr; 1532 } 1533 1534 static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) { 1535 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true)) 1536 return X; 1537 if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true)) 1538 return X; 1539 1540 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1)) 1541 return X; 1542 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op1, Op0)) 1543 return X; 1544 1545 if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true)) 1546 return X; 1547 1548 if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true)) 1549 return X; 1550 1551 if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1)) 1552 return X; 1553 if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0)) 1554 return X; 1555 1556 return nullptr; 1557 } 1558 1559 static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1) { 1560 // (icmp (add V, C0), C1) | (icmp V, C0) 1561 ICmpInst::Predicate Pred0, Pred1; 1562 const APInt *C0, *C1; 1563 Value *V; 1564 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1)))) 1565 return nullptr; 1566 1567 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value()))) 1568 return nullptr; 1569 1570 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0)); 1571 if (AddInst->getOperand(1) != Op1->getOperand(1)) 1572 return nullptr; 1573 1574 Type *ITy = Op0->getType(); 1575 bool isNSW = AddInst->hasNoSignedWrap(); 1576 bool isNUW = AddInst->hasNoUnsignedWrap(); 1577 1578 const APInt Delta = *C1 - *C0; 1579 if (C0->isStrictlyPositive()) { 1580 if (Delta == 2) { 1581 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE) 1582 return getTrue(ITy); 1583 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW) 1584 return getTrue(ITy); 1585 } 1586 if (Delta == 1) { 1587 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE) 1588 return getTrue(ITy); 1589 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW) 1590 return getTrue(ITy); 1591 } 1592 } 1593 if (C0->getBoolValue() && isNUW) { 1594 if (Delta == 2) 1595 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE) 1596 return getTrue(ITy); 1597 if (Delta == 1) 1598 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE) 1599 return getTrue(ITy); 1600 } 1601 1602 return nullptr; 1603 } 1604 1605 static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) { 1606 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false)) 1607 return X; 1608 if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false)) 1609 return X; 1610 1611 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1)) 1612 return X; 1613 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op1, Op0)) 1614 return X; 1615 1616 if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false)) 1617 return X; 1618 1619 if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false)) 1620 return X; 1621 1622 if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1)) 1623 return X; 1624 if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0)) 1625 return X; 1626 1627 return nullptr; 1628 } 1629 1630 static Value *simplifyAndOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS, bool IsAnd) { 1631 Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1); 1632 Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1); 1633 if (LHS0->getType() != RHS0->getType()) 1634 return nullptr; 1635 1636 FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate(); 1637 if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) || 1638 (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) { 1639 // (fcmp ord NNAN, X) & (fcmp ord X, Y) --> fcmp ord X, Y 1640 // (fcmp ord NNAN, X) & (fcmp ord Y, X) --> fcmp ord Y, X 1641 // (fcmp ord X, NNAN) & (fcmp ord X, Y) --> fcmp ord X, Y 1642 // (fcmp ord X, NNAN) & (fcmp ord Y, X) --> fcmp ord Y, X 1643 // (fcmp uno NNAN, X) | (fcmp uno X, Y) --> fcmp uno X, Y 1644 // (fcmp uno NNAN, X) | (fcmp uno Y, X) --> fcmp uno Y, X 1645 // (fcmp uno X, NNAN) | (fcmp uno X, Y) --> fcmp uno X, Y 1646 // (fcmp uno X, NNAN) | (fcmp uno Y, X) --> fcmp uno Y, X 1647 if ((isKnownNeverNaN(LHS0) && (LHS1 == RHS0 || LHS1 == RHS1)) || 1648 (isKnownNeverNaN(LHS1) && (LHS0 == RHS0 || LHS0 == RHS1))) 1649 return RHS; 1650 1651 // (fcmp ord X, Y) & (fcmp ord NNAN, X) --> fcmp ord X, Y 1652 // (fcmp ord Y, X) & (fcmp ord NNAN, X) --> fcmp ord Y, X 1653 // (fcmp ord X, Y) & (fcmp ord X, NNAN) --> fcmp ord X, Y 1654 // (fcmp ord Y, X) & (fcmp ord X, NNAN) --> fcmp ord Y, X 1655 // (fcmp uno X, Y) | (fcmp uno NNAN, X) --> fcmp uno X, Y 1656 // (fcmp uno Y, X) | (fcmp uno NNAN, X) --> fcmp uno Y, X 1657 // (fcmp uno X, Y) | (fcmp uno X, NNAN) --> fcmp uno X, Y 1658 // (fcmp uno Y, X) | (fcmp uno X, NNAN) --> fcmp uno Y, X 1659 if ((isKnownNeverNaN(RHS0) && (RHS1 == LHS0 || RHS1 == LHS1)) || 1660 (isKnownNeverNaN(RHS1) && (RHS0 == LHS0 || RHS0 == LHS1))) 1661 return LHS; 1662 } 1663 1664 return nullptr; 1665 } 1666 1667 static Value *simplifyAndOrOfCmps(Value *Op0, Value *Op1, bool IsAnd) { 1668 // Look through casts of the 'and' operands to find compares. 1669 auto *Cast0 = dyn_cast<CastInst>(Op0); 1670 auto *Cast1 = dyn_cast<CastInst>(Op1); 1671 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() && 1672 Cast0->getSrcTy() == Cast1->getSrcTy()) { 1673 Op0 = Cast0->getOperand(0); 1674 Op1 = Cast1->getOperand(0); 1675 } 1676 1677 Value *V = nullptr; 1678 auto *ICmp0 = dyn_cast<ICmpInst>(Op0); 1679 auto *ICmp1 = dyn_cast<ICmpInst>(Op1); 1680 if (ICmp0 && ICmp1) 1681 V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1) : 1682 simplifyOrOfICmps(ICmp0, ICmp1); 1683 1684 auto *FCmp0 = dyn_cast<FCmpInst>(Op0); 1685 auto *FCmp1 = dyn_cast<FCmpInst>(Op1); 1686 if (FCmp0 && FCmp1) 1687 V = simplifyAndOrOfFCmps(FCmp0, FCmp1, IsAnd); 1688 1689 if (!V) 1690 return nullptr; 1691 if (!Cast0) 1692 return V; 1693 1694 // If we looked through casts, we can only handle a constant simplification 1695 // because we are not allowed to create a cast instruction here. 1696 if (auto *C = dyn_cast<Constant>(V)) 1697 return ConstantExpr::getCast(Cast0->getOpcode(), C, Cast0->getType()); 1698 1699 return nullptr; 1700 } 1701 1702 /// Given operands for an And, see if we can fold the result. 1703 /// If not, this returns null. 1704 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 1705 unsigned MaxRecurse) { 1706 if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q)) 1707 return C; 1708 1709 // X & undef -> 0 1710 if (match(Op1, m_Undef())) 1711 return Constant::getNullValue(Op0->getType()); 1712 1713 // X & X = X 1714 if (Op0 == Op1) 1715 return Op0; 1716 1717 // X & 0 = 0 1718 if (match(Op1, m_Zero())) 1719 return Constant::getNullValue(Op0->getType()); 1720 1721 // X & -1 = X 1722 if (match(Op1, m_AllOnes())) 1723 return Op0; 1724 1725 // A & ~A = ~A & A = 0 1726 if (match(Op0, m_Not(m_Specific(Op1))) || 1727 match(Op1, m_Not(m_Specific(Op0)))) 1728 return Constant::getNullValue(Op0->getType()); 1729 1730 // (A | ?) & A = A 1731 if (match(Op0, m_c_Or(m_Specific(Op1), m_Value()))) 1732 return Op1; 1733 1734 // A & (A | ?) = A 1735 if (match(Op1, m_c_Or(m_Specific(Op0), m_Value()))) 1736 return Op0; 1737 1738 // A mask that only clears known zeros of a shifted value is a no-op. 1739 Value *X; 1740 const APInt *Mask; 1741 const APInt *ShAmt; 1742 if (match(Op1, m_APInt(Mask))) { 1743 // If all bits in the inverted and shifted mask are clear: 1744 // and (shl X, ShAmt), Mask --> shl X, ShAmt 1745 if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) && 1746 (~(*Mask)).lshr(*ShAmt).isNullValue()) 1747 return Op0; 1748 1749 // If all bits in the inverted and shifted mask are clear: 1750 // and (lshr X, ShAmt), Mask --> lshr X, ShAmt 1751 if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) && 1752 (~(*Mask)).shl(*ShAmt).isNullValue()) 1753 return Op0; 1754 } 1755 1756 // A & (-A) = A if A is a power of two or zero. 1757 if (match(Op0, m_Neg(m_Specific(Op1))) || 1758 match(Op1, m_Neg(m_Specific(Op0)))) { 1759 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, 1760 Q.DT)) 1761 return Op0; 1762 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, 1763 Q.DT)) 1764 return Op1; 1765 } 1766 1767 if (Value *V = simplifyAndOrOfCmps(Op0, Op1, true)) 1768 return V; 1769 1770 // Try some generic simplifications for associative operations. 1771 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q, 1772 MaxRecurse)) 1773 return V; 1774 1775 // And distributes over Or. Try some generic simplifications based on this. 1776 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or, 1777 Q, MaxRecurse)) 1778 return V; 1779 1780 // And distributes over Xor. Try some generic simplifications based on this. 1781 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor, 1782 Q, MaxRecurse)) 1783 return V; 1784 1785 // If the operation is with the result of a select instruction, check whether 1786 // operating on either branch of the select always yields the same value. 1787 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1788 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q, 1789 MaxRecurse)) 1790 return V; 1791 1792 // If the operation is with the result of a phi instruction, check whether 1793 // operating on all incoming values of the phi always yields the same value. 1794 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1795 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q, 1796 MaxRecurse)) 1797 return V; 1798 1799 return nullptr; 1800 } 1801 1802 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 1803 return ::SimplifyAndInst(Op0, Op1, Q, RecursionLimit); 1804 } 1805 1806 /// Given operands for an Or, see if we can fold the result. 1807 /// If not, this returns null. 1808 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 1809 unsigned MaxRecurse) { 1810 if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q)) 1811 return C; 1812 1813 // X | undef -> -1 1814 // X | -1 = -1 1815 // Do not return Op1 because it may contain undef elements if it's a vector. 1816 if (match(Op1, m_Undef()) || match(Op1, m_AllOnes())) 1817 return Constant::getAllOnesValue(Op0->getType()); 1818 1819 // X | X = X 1820 // X | 0 = X 1821 if (Op0 == Op1 || match(Op1, m_Zero())) 1822 return Op0; 1823 1824 // A | ~A = ~A | A = -1 1825 if (match(Op0, m_Not(m_Specific(Op1))) || 1826 match(Op1, m_Not(m_Specific(Op0)))) 1827 return Constant::getAllOnesValue(Op0->getType()); 1828 1829 // (A & ?) | A = A 1830 if (match(Op0, m_c_And(m_Specific(Op1), m_Value()))) 1831 return Op1; 1832 1833 // A | (A & ?) = A 1834 if (match(Op1, m_c_And(m_Specific(Op0), m_Value()))) 1835 return Op0; 1836 1837 // ~(A & ?) | A = -1 1838 if (match(Op0, m_Not(m_c_And(m_Specific(Op1), m_Value())))) 1839 return Constant::getAllOnesValue(Op1->getType()); 1840 1841 // A | ~(A & ?) = -1 1842 if (match(Op1, m_Not(m_c_And(m_Specific(Op1), m_Value())))) 1843 return Constant::getAllOnesValue(Op0->getType()); 1844 1845 Value *A, *B; 1846 // (A & ~B) | (A ^ B) -> (A ^ B) 1847 // (~B & A) | (A ^ B) -> (A ^ B) 1848 // (A & ~B) | (B ^ A) -> (B ^ A) 1849 // (~B & A) | (B ^ A) -> (B ^ A) 1850 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && 1851 (match(Op0, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) || 1852 match(Op0, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))) 1853 return Op1; 1854 1855 // Commute the 'or' operands. 1856 // (A ^ B) | (A & ~B) -> (A ^ B) 1857 // (A ^ B) | (~B & A) -> (A ^ B) 1858 // (B ^ A) | (A & ~B) -> (B ^ A) 1859 // (B ^ A) | (~B & A) -> (B ^ A) 1860 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) && 1861 (match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) || 1862 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B))))) 1863 return Op0; 1864 1865 // (A & B) | (~A ^ B) -> (~A ^ B) 1866 // (B & A) | (~A ^ B) -> (~A ^ B) 1867 // (A & B) | (B ^ ~A) -> (B ^ ~A) 1868 // (B & A) | (B ^ ~A) -> (B ^ ~A) 1869 if (match(Op0, m_And(m_Value(A), m_Value(B))) && 1870 (match(Op1, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) || 1871 match(Op1, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B))))) 1872 return Op1; 1873 1874 // (~A ^ B) | (A & B) -> (~A ^ B) 1875 // (~A ^ B) | (B & A) -> (~A ^ B) 1876 // (B ^ ~A) | (A & B) -> (B ^ ~A) 1877 // (B ^ ~A) | (B & A) -> (B ^ ~A) 1878 if (match(Op1, m_And(m_Value(A), m_Value(B))) && 1879 (match(Op0, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) || 1880 match(Op0, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B))))) 1881 return Op0; 1882 1883 if (Value *V = simplifyAndOrOfCmps(Op0, Op1, false)) 1884 return V; 1885 1886 // Try some generic simplifications for associative operations. 1887 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q, 1888 MaxRecurse)) 1889 return V; 1890 1891 // Or distributes over And. Try some generic simplifications based on this. 1892 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q, 1893 MaxRecurse)) 1894 return V; 1895 1896 // If the operation is with the result of a select instruction, check whether 1897 // operating on either branch of the select always yields the same value. 1898 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1899 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q, 1900 MaxRecurse)) 1901 return V; 1902 1903 // (A & C1)|(B & C2) 1904 const APInt *C1, *C2; 1905 if (match(Op0, m_And(m_Value(A), m_APInt(C1))) && 1906 match(Op1, m_And(m_Value(B), m_APInt(C2)))) { 1907 if (*C1 == ~*C2) { 1908 // (A & C1)|(B & C2) 1909 // If we have: ((V + N) & C1) | (V & C2) 1910 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0 1911 // replace with V+N. 1912 Value *N; 1913 if (C2->isMask() && // C2 == 0+1+ 1914 match(A, m_c_Add(m_Specific(B), m_Value(N)))) { 1915 // Add commutes, try both ways. 1916 if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) 1917 return A; 1918 } 1919 // Or commutes, try both ways. 1920 if (C1->isMask() && 1921 match(B, m_c_Add(m_Specific(A), m_Value(N)))) { 1922 // Add commutes, try both ways. 1923 if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) 1924 return B; 1925 } 1926 } 1927 } 1928 1929 // If the operation is with the result of a phi instruction, check whether 1930 // operating on all incoming values of the phi always yields the same value. 1931 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1932 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse)) 1933 return V; 1934 1935 return nullptr; 1936 } 1937 1938 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 1939 return ::SimplifyOrInst(Op0, Op1, Q, RecursionLimit); 1940 } 1941 1942 /// Given operands for a Xor, see if we can fold the result. 1943 /// If not, this returns null. 1944 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 1945 unsigned MaxRecurse) { 1946 if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q)) 1947 return C; 1948 1949 // A ^ undef -> undef 1950 if (match(Op1, m_Undef())) 1951 return Op1; 1952 1953 // A ^ 0 = A 1954 if (match(Op1, m_Zero())) 1955 return Op0; 1956 1957 // A ^ A = 0 1958 if (Op0 == Op1) 1959 return Constant::getNullValue(Op0->getType()); 1960 1961 // A ^ ~A = ~A ^ A = -1 1962 if (match(Op0, m_Not(m_Specific(Op1))) || 1963 match(Op1, m_Not(m_Specific(Op0)))) 1964 return Constant::getAllOnesValue(Op0->getType()); 1965 1966 // Try some generic simplifications for associative operations. 1967 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q, 1968 MaxRecurse)) 1969 return V; 1970 1971 // Threading Xor over selects and phi nodes is pointless, so don't bother. 1972 // Threading over the select in "A ^ select(cond, B, C)" means evaluating 1973 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and 1974 // only if B and C are equal. If B and C are equal then (since we assume 1975 // that operands have already been simplified) "select(cond, B, C)" should 1976 // have been simplified to the common value of B and C already. Analysing 1977 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly 1978 // for threading over phi nodes. 1979 1980 return nullptr; 1981 } 1982 1983 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 1984 return ::SimplifyXorInst(Op0, Op1, Q, RecursionLimit); 1985 } 1986 1987 1988 static Type *GetCompareTy(Value *Op) { 1989 return CmpInst::makeCmpResultType(Op->getType()); 1990 } 1991 1992 /// Rummage around inside V looking for something equivalent to the comparison 1993 /// "LHS Pred RHS". Return such a value if found, otherwise return null. 1994 /// Helper function for analyzing max/min idioms. 1995 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred, 1996 Value *LHS, Value *RHS) { 1997 SelectInst *SI = dyn_cast<SelectInst>(V); 1998 if (!SI) 1999 return nullptr; 2000 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); 2001 if (!Cmp) 2002 return nullptr; 2003 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1); 2004 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS) 2005 return Cmp; 2006 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) && 2007 LHS == CmpRHS && RHS == CmpLHS) 2008 return Cmp; 2009 return nullptr; 2010 } 2011 2012 // A significant optimization not implemented here is assuming that alloca 2013 // addresses are not equal to incoming argument values. They don't *alias*, 2014 // as we say, but that doesn't mean they aren't equal, so we take a 2015 // conservative approach. 2016 // 2017 // This is inspired in part by C++11 5.10p1: 2018 // "Two pointers of the same type compare equal if and only if they are both 2019 // null, both point to the same function, or both represent the same 2020 // address." 2021 // 2022 // This is pretty permissive. 2023 // 2024 // It's also partly due to C11 6.5.9p6: 2025 // "Two pointers compare equal if and only if both are null pointers, both are 2026 // pointers to the same object (including a pointer to an object and a 2027 // subobject at its beginning) or function, both are pointers to one past the 2028 // last element of the same array object, or one is a pointer to one past the 2029 // end of one array object and the other is a pointer to the start of a 2030 // different array object that happens to immediately follow the first array 2031 // object in the address space.) 2032 // 2033 // C11's version is more restrictive, however there's no reason why an argument 2034 // couldn't be a one-past-the-end value for a stack object in the caller and be 2035 // equal to the beginning of a stack object in the callee. 2036 // 2037 // If the C and C++ standards are ever made sufficiently restrictive in this 2038 // area, it may be possible to update LLVM's semantics accordingly and reinstate 2039 // this optimization. 2040 static Constant * 2041 computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI, 2042 const DominatorTree *DT, CmpInst::Predicate Pred, 2043 AssumptionCache *AC, const Instruction *CxtI, 2044 Value *LHS, Value *RHS) { 2045 // First, skip past any trivial no-ops. 2046 LHS = LHS->stripPointerCasts(); 2047 RHS = RHS->stripPointerCasts(); 2048 2049 // A non-null pointer is not equal to a null pointer. 2050 if (llvm::isKnownNonZero(LHS, DL) && isa<ConstantPointerNull>(RHS) && 2051 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE)) 2052 return ConstantInt::get(GetCompareTy(LHS), 2053 !CmpInst::isTrueWhenEqual(Pred)); 2054 2055 // We can only fold certain predicates on pointer comparisons. 2056 switch (Pred) { 2057 default: 2058 return nullptr; 2059 2060 // Equality comaprisons are easy to fold. 2061 case CmpInst::ICMP_EQ: 2062 case CmpInst::ICMP_NE: 2063 break; 2064 2065 // We can only handle unsigned relational comparisons because 'inbounds' on 2066 // a GEP only protects against unsigned wrapping. 2067 case CmpInst::ICMP_UGT: 2068 case CmpInst::ICMP_UGE: 2069 case CmpInst::ICMP_ULT: 2070 case CmpInst::ICMP_ULE: 2071 // However, we have to switch them to their signed variants to handle 2072 // negative indices from the base pointer. 2073 Pred = ICmpInst::getSignedPredicate(Pred); 2074 break; 2075 } 2076 2077 // Strip off any constant offsets so that we can reason about them. 2078 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets 2079 // here and compare base addresses like AliasAnalysis does, however there are 2080 // numerous hazards. AliasAnalysis and its utilities rely on special rules 2081 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis 2082 // doesn't need to guarantee pointer inequality when it says NoAlias. 2083 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS); 2084 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS); 2085 2086 // If LHS and RHS are related via constant offsets to the same base 2087 // value, we can replace it with an icmp which just compares the offsets. 2088 if (LHS == RHS) 2089 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset); 2090 2091 // Various optimizations for (in)equality comparisons. 2092 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) { 2093 // Different non-empty allocations that exist at the same time have 2094 // different addresses (if the program can tell). Global variables always 2095 // exist, so they always exist during the lifetime of each other and all 2096 // allocas. Two different allocas usually have different addresses... 2097 // 2098 // However, if there's an @llvm.stackrestore dynamically in between two 2099 // allocas, they may have the same address. It's tempting to reduce the 2100 // scope of the problem by only looking at *static* allocas here. That would 2101 // cover the majority of allocas while significantly reducing the likelihood 2102 // of having an @llvm.stackrestore pop up in the middle. However, it's not 2103 // actually impossible for an @llvm.stackrestore to pop up in the middle of 2104 // an entry block. Also, if we have a block that's not attached to a 2105 // function, we can't tell if it's "static" under the current definition. 2106 // Theoretically, this problem could be fixed by creating a new kind of 2107 // instruction kind specifically for static allocas. Such a new instruction 2108 // could be required to be at the top of the entry block, thus preventing it 2109 // from being subject to a @llvm.stackrestore. Instcombine could even 2110 // convert regular allocas into these special allocas. It'd be nifty. 2111 // However, until then, this problem remains open. 2112 // 2113 // So, we'll assume that two non-empty allocas have different addresses 2114 // for now. 2115 // 2116 // With all that, if the offsets are within the bounds of their allocations 2117 // (and not one-past-the-end! so we can't use inbounds!), and their 2118 // allocations aren't the same, the pointers are not equal. 2119 // 2120 // Note that it's not necessary to check for LHS being a global variable 2121 // address, due to canonicalization and constant folding. 2122 if (isa<AllocaInst>(LHS) && 2123 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) { 2124 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset); 2125 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset); 2126 uint64_t LHSSize, RHSSize; 2127 ObjectSizeOpts Opts; 2128 Opts.NullIsUnknownSize = 2129 NullPointerIsDefined(cast<AllocaInst>(LHS)->getFunction()); 2130 if (LHSOffsetCI && RHSOffsetCI && 2131 getObjectSize(LHS, LHSSize, DL, TLI, Opts) && 2132 getObjectSize(RHS, RHSSize, DL, TLI, Opts)) { 2133 const APInt &LHSOffsetValue = LHSOffsetCI->getValue(); 2134 const APInt &RHSOffsetValue = RHSOffsetCI->getValue(); 2135 if (!LHSOffsetValue.isNegative() && 2136 !RHSOffsetValue.isNegative() && 2137 LHSOffsetValue.ult(LHSSize) && 2138 RHSOffsetValue.ult(RHSSize)) { 2139 return ConstantInt::get(GetCompareTy(LHS), 2140 !CmpInst::isTrueWhenEqual(Pred)); 2141 } 2142 } 2143 2144 // Repeat the above check but this time without depending on DataLayout 2145 // or being able to compute a precise size. 2146 if (!cast<PointerType>(LHS->getType())->isEmptyTy() && 2147 !cast<PointerType>(RHS->getType())->isEmptyTy() && 2148 LHSOffset->isNullValue() && 2149 RHSOffset->isNullValue()) 2150 return ConstantInt::get(GetCompareTy(LHS), 2151 !CmpInst::isTrueWhenEqual(Pred)); 2152 } 2153 2154 // Even if an non-inbounds GEP occurs along the path we can still optimize 2155 // equality comparisons concerning the result. We avoid walking the whole 2156 // chain again by starting where the last calls to 2157 // stripAndComputeConstantOffsets left off and accumulate the offsets. 2158 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true); 2159 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true); 2160 if (LHS == RHS) 2161 return ConstantExpr::getICmp(Pred, 2162 ConstantExpr::getAdd(LHSOffset, LHSNoBound), 2163 ConstantExpr::getAdd(RHSOffset, RHSNoBound)); 2164 2165 // If one side of the equality comparison must come from a noalias call 2166 // (meaning a system memory allocation function), and the other side must 2167 // come from a pointer that cannot overlap with dynamically-allocated 2168 // memory within the lifetime of the current function (allocas, byval 2169 // arguments, globals), then determine the comparison result here. 2170 SmallVector<Value *, 8> LHSUObjs, RHSUObjs; 2171 GetUnderlyingObjects(LHS, LHSUObjs, DL); 2172 GetUnderlyingObjects(RHS, RHSUObjs, DL); 2173 2174 // Is the set of underlying objects all noalias calls? 2175 auto IsNAC = [](ArrayRef<Value *> Objects) { 2176 return all_of(Objects, isNoAliasCall); 2177 }; 2178 2179 // Is the set of underlying objects all things which must be disjoint from 2180 // noalias calls. For allocas, we consider only static ones (dynamic 2181 // allocas might be transformed into calls to malloc not simultaneously 2182 // live with the compared-to allocation). For globals, we exclude symbols 2183 // that might be resolve lazily to symbols in another dynamically-loaded 2184 // library (and, thus, could be malloc'ed by the implementation). 2185 auto IsAllocDisjoint = [](ArrayRef<Value *> Objects) { 2186 return all_of(Objects, [](Value *V) { 2187 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) 2188 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca(); 2189 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) 2190 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() || 2191 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) && 2192 !GV->isThreadLocal(); 2193 if (const Argument *A = dyn_cast<Argument>(V)) 2194 return A->hasByValAttr(); 2195 return false; 2196 }); 2197 }; 2198 2199 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) || 2200 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs))) 2201 return ConstantInt::get(GetCompareTy(LHS), 2202 !CmpInst::isTrueWhenEqual(Pred)); 2203 2204 // Fold comparisons for non-escaping pointer even if the allocation call 2205 // cannot be elided. We cannot fold malloc comparison to null. Also, the 2206 // dynamic allocation call could be either of the operands. 2207 Value *MI = nullptr; 2208 if (isAllocLikeFn(LHS, TLI) && 2209 llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT)) 2210 MI = LHS; 2211 else if (isAllocLikeFn(RHS, TLI) && 2212 llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT)) 2213 MI = RHS; 2214 // FIXME: We should also fold the compare when the pointer escapes, but the 2215 // compare dominates the pointer escape 2216 if (MI && !PointerMayBeCaptured(MI, true, true)) 2217 return ConstantInt::get(GetCompareTy(LHS), 2218 CmpInst::isFalseWhenEqual(Pred)); 2219 } 2220 2221 // Otherwise, fail. 2222 return nullptr; 2223 } 2224 2225 /// Fold an icmp when its operands have i1 scalar type. 2226 static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS, 2227 Value *RHS, const SimplifyQuery &Q) { 2228 Type *ITy = GetCompareTy(LHS); // The return type. 2229 Type *OpTy = LHS->getType(); // The operand type. 2230 if (!OpTy->isIntOrIntVectorTy(1)) 2231 return nullptr; 2232 2233 // A boolean compared to true/false can be simplified in 14 out of the 20 2234 // (10 predicates * 2 constants) possible combinations. Cases not handled here 2235 // require a 'not' of the LHS, so those must be transformed in InstCombine. 2236 if (match(RHS, m_Zero())) { 2237 switch (Pred) { 2238 case CmpInst::ICMP_NE: // X != 0 -> X 2239 case CmpInst::ICMP_UGT: // X >u 0 -> X 2240 case CmpInst::ICMP_SLT: // X <s 0 -> X 2241 return LHS; 2242 2243 case CmpInst::ICMP_ULT: // X <u 0 -> false 2244 case CmpInst::ICMP_SGT: // X >s 0 -> false 2245 return getFalse(ITy); 2246 2247 case CmpInst::ICMP_UGE: // X >=u 0 -> true 2248 case CmpInst::ICMP_SLE: // X <=s 0 -> true 2249 return getTrue(ITy); 2250 2251 default: break; 2252 } 2253 } else if (match(RHS, m_One())) { 2254 switch (Pred) { 2255 case CmpInst::ICMP_EQ: // X == 1 -> X 2256 case CmpInst::ICMP_UGE: // X >=u 1 -> X 2257 case CmpInst::ICMP_SLE: // X <=s -1 -> X 2258 return LHS; 2259 2260 case CmpInst::ICMP_UGT: // X >u 1 -> false 2261 case CmpInst::ICMP_SLT: // X <s -1 -> false 2262 return getFalse(ITy); 2263 2264 case CmpInst::ICMP_ULE: // X <=u 1 -> true 2265 case CmpInst::ICMP_SGE: // X >=s -1 -> true 2266 return getTrue(ITy); 2267 2268 default: break; 2269 } 2270 } 2271 2272 switch (Pred) { 2273 default: 2274 break; 2275 case ICmpInst::ICMP_UGE: 2276 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false)) 2277 return getTrue(ITy); 2278 break; 2279 case ICmpInst::ICMP_SGE: 2280 /// For signed comparison, the values for an i1 are 0 and -1 2281 /// respectively. This maps into a truth table of: 2282 /// LHS | RHS | LHS >=s RHS | LHS implies RHS 2283 /// 0 | 0 | 1 (0 >= 0) | 1 2284 /// 0 | 1 | 1 (0 >= -1) | 1 2285 /// 1 | 0 | 0 (-1 >= 0) | 0 2286 /// 1 | 1 | 1 (-1 >= -1) | 1 2287 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false)) 2288 return getTrue(ITy); 2289 break; 2290 case ICmpInst::ICMP_ULE: 2291 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false)) 2292 return getTrue(ITy); 2293 break; 2294 } 2295 2296 return nullptr; 2297 } 2298 2299 /// Try hard to fold icmp with zero RHS because this is a common case. 2300 static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS, 2301 Value *RHS, const SimplifyQuery &Q) { 2302 if (!match(RHS, m_Zero())) 2303 return nullptr; 2304 2305 Type *ITy = GetCompareTy(LHS); // The return type. 2306 switch (Pred) { 2307 default: 2308 llvm_unreachable("Unknown ICmp predicate!"); 2309 case ICmpInst::ICMP_ULT: 2310 return getFalse(ITy); 2311 case ICmpInst::ICMP_UGE: 2312 return getTrue(ITy); 2313 case ICmpInst::ICMP_EQ: 2314 case ICmpInst::ICMP_ULE: 2315 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) 2316 return getFalse(ITy); 2317 break; 2318 case ICmpInst::ICMP_NE: 2319 case ICmpInst::ICMP_UGT: 2320 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) 2321 return getTrue(ITy); 2322 break; 2323 case ICmpInst::ICMP_SLT: { 2324 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2325 if (LHSKnown.isNegative()) 2326 return getTrue(ITy); 2327 if (LHSKnown.isNonNegative()) 2328 return getFalse(ITy); 2329 break; 2330 } 2331 case ICmpInst::ICMP_SLE: { 2332 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2333 if (LHSKnown.isNegative()) 2334 return getTrue(ITy); 2335 if (LHSKnown.isNonNegative() && 2336 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) 2337 return getFalse(ITy); 2338 break; 2339 } 2340 case ICmpInst::ICMP_SGE: { 2341 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2342 if (LHSKnown.isNegative()) 2343 return getFalse(ITy); 2344 if (LHSKnown.isNonNegative()) 2345 return getTrue(ITy); 2346 break; 2347 } 2348 case ICmpInst::ICMP_SGT: { 2349 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2350 if (LHSKnown.isNegative()) 2351 return getFalse(ITy); 2352 if (LHSKnown.isNonNegative() && 2353 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) 2354 return getTrue(ITy); 2355 break; 2356 } 2357 } 2358 2359 return nullptr; 2360 } 2361 2362 /// Many binary operators with a constant operand have an easy-to-compute 2363 /// range of outputs. This can be used to fold a comparison to always true or 2364 /// always false. 2365 static void setLimitsForBinOp(BinaryOperator &BO, APInt &Lower, APInt &Upper) { 2366 unsigned Width = Lower.getBitWidth(); 2367 const APInt *C; 2368 switch (BO.getOpcode()) { 2369 case Instruction::Add: 2370 if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) { 2371 // FIXME: If we have both nuw and nsw, we should reduce the range further. 2372 if (BO.hasNoUnsignedWrap()) { 2373 // 'add nuw x, C' produces [C, UINT_MAX]. 2374 Lower = *C; 2375 } else if (BO.hasNoSignedWrap()) { 2376 if (C->isNegative()) { 2377 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C]. 2378 Lower = APInt::getSignedMinValue(Width); 2379 Upper = APInt::getSignedMaxValue(Width) + *C + 1; 2380 } else { 2381 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX]. 2382 Lower = APInt::getSignedMinValue(Width) + *C; 2383 Upper = APInt::getSignedMaxValue(Width) + 1; 2384 } 2385 } 2386 } 2387 break; 2388 2389 case Instruction::And: 2390 if (match(BO.getOperand(1), m_APInt(C))) 2391 // 'and x, C' produces [0, C]. 2392 Upper = *C + 1; 2393 break; 2394 2395 case Instruction::Or: 2396 if (match(BO.getOperand(1), m_APInt(C))) 2397 // 'or x, C' produces [C, UINT_MAX]. 2398 Lower = *C; 2399 break; 2400 2401 case Instruction::AShr: 2402 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) { 2403 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C]. 2404 Lower = APInt::getSignedMinValue(Width).ashr(*C); 2405 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1; 2406 } else if (match(BO.getOperand(0), m_APInt(C))) { 2407 unsigned ShiftAmount = Width - 1; 2408 if (!C->isNullValue() && BO.isExact()) 2409 ShiftAmount = C->countTrailingZeros(); 2410 if (C->isNegative()) { 2411 // 'ashr C, x' produces [C, C >> (Width-1)] 2412 Lower = *C; 2413 Upper = C->ashr(ShiftAmount) + 1; 2414 } else { 2415 // 'ashr C, x' produces [C >> (Width-1), C] 2416 Lower = C->ashr(ShiftAmount); 2417 Upper = *C + 1; 2418 } 2419 } 2420 break; 2421 2422 case Instruction::LShr: 2423 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) { 2424 // 'lshr x, C' produces [0, UINT_MAX >> C]. 2425 Upper = APInt::getAllOnesValue(Width).lshr(*C) + 1; 2426 } else if (match(BO.getOperand(0), m_APInt(C))) { 2427 // 'lshr C, x' produces [C >> (Width-1), C]. 2428 unsigned ShiftAmount = Width - 1; 2429 if (!C->isNullValue() && BO.isExact()) 2430 ShiftAmount = C->countTrailingZeros(); 2431 Lower = C->lshr(ShiftAmount); 2432 Upper = *C + 1; 2433 } 2434 break; 2435 2436 case Instruction::Shl: 2437 if (match(BO.getOperand(0), m_APInt(C))) { 2438 if (BO.hasNoUnsignedWrap()) { 2439 // 'shl nuw C, x' produces [C, C << CLZ(C)] 2440 Lower = *C; 2441 Upper = Lower.shl(Lower.countLeadingZeros()) + 1; 2442 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw? 2443 if (C->isNegative()) { 2444 // 'shl nsw C, x' produces [C << CLO(C)-1, C] 2445 unsigned ShiftAmount = C->countLeadingOnes() - 1; 2446 Lower = C->shl(ShiftAmount); 2447 Upper = *C + 1; 2448 } else { 2449 // 'shl nsw C, x' produces [C, C << CLZ(C)-1] 2450 unsigned ShiftAmount = C->countLeadingZeros() - 1; 2451 Lower = *C; 2452 Upper = C->shl(ShiftAmount) + 1; 2453 } 2454 } 2455 } 2456 break; 2457 2458 case Instruction::SDiv: 2459 if (match(BO.getOperand(1), m_APInt(C))) { 2460 APInt IntMin = APInt::getSignedMinValue(Width); 2461 APInt IntMax = APInt::getSignedMaxValue(Width); 2462 if (C->isAllOnesValue()) { 2463 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX] 2464 // where C != -1 and C != 0 and C != 1 2465 Lower = IntMin + 1; 2466 Upper = IntMax + 1; 2467 } else if (C->countLeadingZeros() < Width - 1) { 2468 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C] 2469 // where C != -1 and C != 0 and C != 1 2470 Lower = IntMin.sdiv(*C); 2471 Upper = IntMax.sdiv(*C); 2472 if (Lower.sgt(Upper)) 2473 std::swap(Lower, Upper); 2474 Upper = Upper + 1; 2475 assert(Upper != Lower && "Upper part of range has wrapped!"); 2476 } 2477 } else if (match(BO.getOperand(0), m_APInt(C))) { 2478 if (C->isMinSignedValue()) { 2479 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2]. 2480 Lower = *C; 2481 Upper = Lower.lshr(1) + 1; 2482 } else { 2483 // 'sdiv C, x' produces [-|C|, |C|]. 2484 Upper = C->abs() + 1; 2485 Lower = (-Upper) + 1; 2486 } 2487 } 2488 break; 2489 2490 case Instruction::UDiv: 2491 if (match(BO.getOperand(1), m_APInt(C)) && !C->isNullValue()) { 2492 // 'udiv x, C' produces [0, UINT_MAX / C]. 2493 Upper = APInt::getMaxValue(Width).udiv(*C) + 1; 2494 } else if (match(BO.getOperand(0), m_APInt(C))) { 2495 // 'udiv C, x' produces [0, C]. 2496 Upper = *C + 1; 2497 } 2498 break; 2499 2500 case Instruction::SRem: 2501 if (match(BO.getOperand(1), m_APInt(C))) { 2502 // 'srem x, C' produces (-|C|, |C|). 2503 Upper = C->abs(); 2504 Lower = (-Upper) + 1; 2505 } 2506 break; 2507 2508 case Instruction::URem: 2509 if (match(BO.getOperand(1), m_APInt(C))) 2510 // 'urem x, C' produces [0, C). 2511 Upper = *C; 2512 break; 2513 2514 default: 2515 break; 2516 } 2517 } 2518 2519 static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS, 2520 Value *RHS) { 2521 Type *ITy = GetCompareTy(RHS); // The return type. 2522 2523 Value *X; 2524 // Sign-bit checks can be optimized to true/false after unsigned 2525 // floating-point casts: 2526 // icmp slt (bitcast (uitofp X)), 0 --> false 2527 // icmp sgt (bitcast (uitofp X)), -1 --> true 2528 if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) { 2529 if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero())) 2530 return ConstantInt::getFalse(ITy); 2531 if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes())) 2532 return ConstantInt::getTrue(ITy); 2533 } 2534 2535 const APInt *C; 2536 if (!match(RHS, m_APInt(C))) 2537 return nullptr; 2538 2539 // Rule out tautological comparisons (eg., ult 0 or uge 0). 2540 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C); 2541 if (RHS_CR.isEmptySet()) 2542 return ConstantInt::getFalse(ITy); 2543 if (RHS_CR.isFullSet()) 2544 return ConstantInt::getTrue(ITy); 2545 2546 // Find the range of possible values for binary operators. 2547 unsigned Width = C->getBitWidth(); 2548 APInt Lower = APInt(Width, 0); 2549 APInt Upper = APInt(Width, 0); 2550 if (auto *BO = dyn_cast<BinaryOperator>(LHS)) 2551 setLimitsForBinOp(*BO, Lower, Upper); 2552 2553 ConstantRange LHS_CR = 2554 Lower != Upper ? ConstantRange(Lower, Upper) : ConstantRange(Width, true); 2555 2556 if (auto *I = dyn_cast<Instruction>(LHS)) 2557 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range)) 2558 LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges)); 2559 2560 if (!LHS_CR.isFullSet()) { 2561 if (RHS_CR.contains(LHS_CR)) 2562 return ConstantInt::getTrue(ITy); 2563 if (RHS_CR.inverse().contains(LHS_CR)) 2564 return ConstantInt::getFalse(ITy); 2565 } 2566 2567 return nullptr; 2568 } 2569 2570 /// TODO: A large part of this logic is duplicated in InstCombine's 2571 /// foldICmpBinOp(). We should be able to share that and avoid the code 2572 /// duplication. 2573 static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS, 2574 Value *RHS, const SimplifyQuery &Q, 2575 unsigned MaxRecurse) { 2576 Type *ITy = GetCompareTy(LHS); // The return type. 2577 2578 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS); 2579 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS); 2580 if (MaxRecurse && (LBO || RBO)) { 2581 // Analyze the case when either LHS or RHS is an add instruction. 2582 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr; 2583 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null). 2584 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false; 2585 if (LBO && LBO->getOpcode() == Instruction::Add) { 2586 A = LBO->getOperand(0); 2587 B = LBO->getOperand(1); 2588 NoLHSWrapProblem = 2589 ICmpInst::isEquality(Pred) || 2590 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) || 2591 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap()); 2592 } 2593 if (RBO && RBO->getOpcode() == Instruction::Add) { 2594 C = RBO->getOperand(0); 2595 D = RBO->getOperand(1); 2596 NoRHSWrapProblem = 2597 ICmpInst::isEquality(Pred) || 2598 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) || 2599 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap()); 2600 } 2601 2602 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow. 2603 if ((A == RHS || B == RHS) && NoLHSWrapProblem) 2604 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A, 2605 Constant::getNullValue(RHS->getType()), Q, 2606 MaxRecurse - 1)) 2607 return V; 2608 2609 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow. 2610 if ((C == LHS || D == LHS) && NoRHSWrapProblem) 2611 if (Value *V = 2612 SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()), 2613 C == LHS ? D : C, Q, MaxRecurse - 1)) 2614 return V; 2615 2616 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow. 2617 if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem && 2618 NoRHSWrapProblem) { 2619 // Determine Y and Z in the form icmp (X+Y), (X+Z). 2620 Value *Y, *Z; 2621 if (A == C) { 2622 // C + B == C + D -> B == D 2623 Y = B; 2624 Z = D; 2625 } else if (A == D) { 2626 // D + B == C + D -> B == C 2627 Y = B; 2628 Z = C; 2629 } else if (B == C) { 2630 // A + C == C + D -> A == D 2631 Y = A; 2632 Z = D; 2633 } else { 2634 assert(B == D); 2635 // A + D == C + D -> A == C 2636 Y = A; 2637 Z = C; 2638 } 2639 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1)) 2640 return V; 2641 } 2642 } 2643 2644 { 2645 Value *Y = nullptr; 2646 // icmp pred (or X, Y), X 2647 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) { 2648 if (Pred == ICmpInst::ICMP_ULT) 2649 return getFalse(ITy); 2650 if (Pred == ICmpInst::ICMP_UGE) 2651 return getTrue(ITy); 2652 2653 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) { 2654 KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2655 KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2656 if (RHSKnown.isNonNegative() && YKnown.isNegative()) 2657 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy); 2658 if (RHSKnown.isNegative() || YKnown.isNonNegative()) 2659 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy); 2660 } 2661 } 2662 // icmp pred X, (or X, Y) 2663 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) { 2664 if (Pred == ICmpInst::ICMP_ULE) 2665 return getTrue(ITy); 2666 if (Pred == ICmpInst::ICMP_UGT) 2667 return getFalse(ITy); 2668 2669 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) { 2670 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2671 KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2672 if (LHSKnown.isNonNegative() && YKnown.isNegative()) 2673 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy); 2674 if (LHSKnown.isNegative() || YKnown.isNonNegative()) 2675 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy); 2676 } 2677 } 2678 } 2679 2680 // icmp pred (and X, Y), X 2681 if (LBO && match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) { 2682 if (Pred == ICmpInst::ICMP_UGT) 2683 return getFalse(ITy); 2684 if (Pred == ICmpInst::ICMP_ULE) 2685 return getTrue(ITy); 2686 } 2687 // icmp pred X, (and X, Y) 2688 if (RBO && match(RBO, m_c_And(m_Value(), m_Specific(LHS)))) { 2689 if (Pred == ICmpInst::ICMP_UGE) 2690 return getTrue(ITy); 2691 if (Pred == ICmpInst::ICMP_ULT) 2692 return getFalse(ITy); 2693 } 2694 2695 // 0 - (zext X) pred C 2696 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) { 2697 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) { 2698 if (RHSC->getValue().isStrictlyPositive()) { 2699 if (Pred == ICmpInst::ICMP_SLT) 2700 return ConstantInt::getTrue(RHSC->getContext()); 2701 if (Pred == ICmpInst::ICMP_SGE) 2702 return ConstantInt::getFalse(RHSC->getContext()); 2703 if (Pred == ICmpInst::ICMP_EQ) 2704 return ConstantInt::getFalse(RHSC->getContext()); 2705 if (Pred == ICmpInst::ICMP_NE) 2706 return ConstantInt::getTrue(RHSC->getContext()); 2707 } 2708 if (RHSC->getValue().isNonNegative()) { 2709 if (Pred == ICmpInst::ICMP_SLE) 2710 return ConstantInt::getTrue(RHSC->getContext()); 2711 if (Pred == ICmpInst::ICMP_SGT) 2712 return ConstantInt::getFalse(RHSC->getContext()); 2713 } 2714 } 2715 } 2716 2717 // icmp pred (urem X, Y), Y 2718 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) { 2719 switch (Pred) { 2720 default: 2721 break; 2722 case ICmpInst::ICMP_SGT: 2723 case ICmpInst::ICMP_SGE: { 2724 KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2725 if (!Known.isNonNegative()) 2726 break; 2727 LLVM_FALLTHROUGH; 2728 } 2729 case ICmpInst::ICMP_EQ: 2730 case ICmpInst::ICMP_UGT: 2731 case ICmpInst::ICMP_UGE: 2732 return getFalse(ITy); 2733 case ICmpInst::ICMP_SLT: 2734 case ICmpInst::ICMP_SLE: { 2735 KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2736 if (!Known.isNonNegative()) 2737 break; 2738 LLVM_FALLTHROUGH; 2739 } 2740 case ICmpInst::ICMP_NE: 2741 case ICmpInst::ICMP_ULT: 2742 case ICmpInst::ICMP_ULE: 2743 return getTrue(ITy); 2744 } 2745 } 2746 2747 // icmp pred X, (urem Y, X) 2748 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) { 2749 switch (Pred) { 2750 default: 2751 break; 2752 case ICmpInst::ICMP_SGT: 2753 case ICmpInst::ICMP_SGE: { 2754 KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2755 if (!Known.isNonNegative()) 2756 break; 2757 LLVM_FALLTHROUGH; 2758 } 2759 case ICmpInst::ICMP_NE: 2760 case ICmpInst::ICMP_UGT: 2761 case ICmpInst::ICMP_UGE: 2762 return getTrue(ITy); 2763 case ICmpInst::ICMP_SLT: 2764 case ICmpInst::ICMP_SLE: { 2765 KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2766 if (!Known.isNonNegative()) 2767 break; 2768 LLVM_FALLTHROUGH; 2769 } 2770 case ICmpInst::ICMP_EQ: 2771 case ICmpInst::ICMP_ULT: 2772 case ICmpInst::ICMP_ULE: 2773 return getFalse(ITy); 2774 } 2775 } 2776 2777 // x >> y <=u x 2778 // x udiv y <=u x. 2779 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) || 2780 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) { 2781 // icmp pred (X op Y), X 2782 if (Pred == ICmpInst::ICMP_UGT) 2783 return getFalse(ITy); 2784 if (Pred == ICmpInst::ICMP_ULE) 2785 return getTrue(ITy); 2786 } 2787 2788 // x >=u x >> y 2789 // x >=u x udiv y. 2790 if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) || 2791 match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) { 2792 // icmp pred X, (X op Y) 2793 if (Pred == ICmpInst::ICMP_ULT) 2794 return getFalse(ITy); 2795 if (Pred == ICmpInst::ICMP_UGE) 2796 return getTrue(ITy); 2797 } 2798 2799 // handle: 2800 // CI2 << X == CI 2801 // CI2 << X != CI 2802 // 2803 // where CI2 is a power of 2 and CI isn't 2804 if (auto *CI = dyn_cast<ConstantInt>(RHS)) { 2805 const APInt *CI2Val, *CIVal = &CI->getValue(); 2806 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) && 2807 CI2Val->isPowerOf2()) { 2808 if (!CIVal->isPowerOf2()) { 2809 // CI2 << X can equal zero in some circumstances, 2810 // this simplification is unsafe if CI is zero. 2811 // 2812 // We know it is safe if: 2813 // - The shift is nsw, we can't shift out the one bit. 2814 // - The shift is nuw, we can't shift out the one bit. 2815 // - CI2 is one 2816 // - CI isn't zero 2817 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() || 2818 CI2Val->isOneValue() || !CI->isZero()) { 2819 if (Pred == ICmpInst::ICMP_EQ) 2820 return ConstantInt::getFalse(RHS->getContext()); 2821 if (Pred == ICmpInst::ICMP_NE) 2822 return ConstantInt::getTrue(RHS->getContext()); 2823 } 2824 } 2825 if (CIVal->isSignMask() && CI2Val->isOneValue()) { 2826 if (Pred == ICmpInst::ICMP_UGT) 2827 return ConstantInt::getFalse(RHS->getContext()); 2828 if (Pred == ICmpInst::ICMP_ULE) 2829 return ConstantInt::getTrue(RHS->getContext()); 2830 } 2831 } 2832 } 2833 2834 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() && 2835 LBO->getOperand(1) == RBO->getOperand(1)) { 2836 switch (LBO->getOpcode()) { 2837 default: 2838 break; 2839 case Instruction::UDiv: 2840 case Instruction::LShr: 2841 if (ICmpInst::isSigned(Pred) || !LBO->isExact() || !RBO->isExact()) 2842 break; 2843 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 2844 RBO->getOperand(0), Q, MaxRecurse - 1)) 2845 return V; 2846 break; 2847 case Instruction::SDiv: 2848 if (!ICmpInst::isEquality(Pred) || !LBO->isExact() || !RBO->isExact()) 2849 break; 2850 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 2851 RBO->getOperand(0), Q, MaxRecurse - 1)) 2852 return V; 2853 break; 2854 case Instruction::AShr: 2855 if (!LBO->isExact() || !RBO->isExact()) 2856 break; 2857 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 2858 RBO->getOperand(0), Q, MaxRecurse - 1)) 2859 return V; 2860 break; 2861 case Instruction::Shl: { 2862 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap(); 2863 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap(); 2864 if (!NUW && !NSW) 2865 break; 2866 if (!NSW && ICmpInst::isSigned(Pred)) 2867 break; 2868 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 2869 RBO->getOperand(0), Q, MaxRecurse - 1)) 2870 return V; 2871 break; 2872 } 2873 } 2874 } 2875 return nullptr; 2876 } 2877 2878 /// Simplify integer comparisons where at least one operand of the compare 2879 /// matches an integer min/max idiom. 2880 static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS, 2881 Value *RHS, const SimplifyQuery &Q, 2882 unsigned MaxRecurse) { 2883 Type *ITy = GetCompareTy(LHS); // The return type. 2884 Value *A, *B; 2885 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE; 2886 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B". 2887 2888 // Signed variants on "max(a,b)>=a -> true". 2889 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) { 2890 if (A != RHS) 2891 std::swap(A, B); // smax(A, B) pred A. 2892 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B". 2893 // We analyze this as smax(A, B) pred A. 2894 P = Pred; 2895 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) && 2896 (A == LHS || B == LHS)) { 2897 if (A != LHS) 2898 std::swap(A, B); // A pred smax(A, B). 2899 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B". 2900 // We analyze this as smax(A, B) swapped-pred A. 2901 P = CmpInst::getSwappedPredicate(Pred); 2902 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) && 2903 (A == RHS || B == RHS)) { 2904 if (A != RHS) 2905 std::swap(A, B); // smin(A, B) pred A. 2906 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B". 2907 // We analyze this as smax(-A, -B) swapped-pred -A. 2908 // Note that we do not need to actually form -A or -B thanks to EqP. 2909 P = CmpInst::getSwappedPredicate(Pred); 2910 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) && 2911 (A == LHS || B == LHS)) { 2912 if (A != LHS) 2913 std::swap(A, B); // A pred smin(A, B). 2914 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B". 2915 // We analyze this as smax(-A, -B) pred -A. 2916 // Note that we do not need to actually form -A or -B thanks to EqP. 2917 P = Pred; 2918 } 2919 if (P != CmpInst::BAD_ICMP_PREDICATE) { 2920 // Cases correspond to "max(A, B) p A". 2921 switch (P) { 2922 default: 2923 break; 2924 case CmpInst::ICMP_EQ: 2925 case CmpInst::ICMP_SLE: 2926 // Equivalent to "A EqP B". This may be the same as the condition tested 2927 // in the max/min; if so, we can just return that. 2928 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B)) 2929 return V; 2930 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B)) 2931 return V; 2932 // Otherwise, see if "A EqP B" simplifies. 2933 if (MaxRecurse) 2934 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1)) 2935 return V; 2936 break; 2937 case CmpInst::ICMP_NE: 2938 case CmpInst::ICMP_SGT: { 2939 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP); 2940 // Equivalent to "A InvEqP B". This may be the same as the condition 2941 // tested in the max/min; if so, we can just return that. 2942 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B)) 2943 return V; 2944 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B)) 2945 return V; 2946 // Otherwise, see if "A InvEqP B" simplifies. 2947 if (MaxRecurse) 2948 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1)) 2949 return V; 2950 break; 2951 } 2952 case CmpInst::ICMP_SGE: 2953 // Always true. 2954 return getTrue(ITy); 2955 case CmpInst::ICMP_SLT: 2956 // Always false. 2957 return getFalse(ITy); 2958 } 2959 } 2960 2961 // Unsigned variants on "max(a,b)>=a -> true". 2962 P = CmpInst::BAD_ICMP_PREDICATE; 2963 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) { 2964 if (A != RHS) 2965 std::swap(A, B); // umax(A, B) pred A. 2966 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B". 2967 // We analyze this as umax(A, B) pred A. 2968 P = Pred; 2969 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) && 2970 (A == LHS || B == LHS)) { 2971 if (A != LHS) 2972 std::swap(A, B); // A pred umax(A, B). 2973 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B". 2974 // We analyze this as umax(A, B) swapped-pred A. 2975 P = CmpInst::getSwappedPredicate(Pred); 2976 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) && 2977 (A == RHS || B == RHS)) { 2978 if (A != RHS) 2979 std::swap(A, B); // umin(A, B) pred A. 2980 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B". 2981 // We analyze this as umax(-A, -B) swapped-pred -A. 2982 // Note that we do not need to actually form -A or -B thanks to EqP. 2983 P = CmpInst::getSwappedPredicate(Pred); 2984 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) && 2985 (A == LHS || B == LHS)) { 2986 if (A != LHS) 2987 std::swap(A, B); // A pred umin(A, B). 2988 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B". 2989 // We analyze this as umax(-A, -B) pred -A. 2990 // Note that we do not need to actually form -A or -B thanks to EqP. 2991 P = Pred; 2992 } 2993 if (P != CmpInst::BAD_ICMP_PREDICATE) { 2994 // Cases correspond to "max(A, B) p A". 2995 switch (P) { 2996 default: 2997 break; 2998 case CmpInst::ICMP_EQ: 2999 case CmpInst::ICMP_ULE: 3000 // Equivalent to "A EqP B". This may be the same as the condition tested 3001 // in the max/min; if so, we can just return that. 3002 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B)) 3003 return V; 3004 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B)) 3005 return V; 3006 // Otherwise, see if "A EqP B" simplifies. 3007 if (MaxRecurse) 3008 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1)) 3009 return V; 3010 break; 3011 case CmpInst::ICMP_NE: 3012 case CmpInst::ICMP_UGT: { 3013 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP); 3014 // Equivalent to "A InvEqP B". This may be the same as the condition 3015 // tested in the max/min; if so, we can just return that. 3016 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B)) 3017 return V; 3018 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B)) 3019 return V; 3020 // Otherwise, see if "A InvEqP B" simplifies. 3021 if (MaxRecurse) 3022 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1)) 3023 return V; 3024 break; 3025 } 3026 case CmpInst::ICMP_UGE: 3027 // Always true. 3028 return getTrue(ITy); 3029 case CmpInst::ICMP_ULT: 3030 // Always false. 3031 return getFalse(ITy); 3032 } 3033 } 3034 3035 // Variants on "max(x,y) >= min(x,z)". 3036 Value *C, *D; 3037 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && 3038 match(RHS, m_SMin(m_Value(C), m_Value(D))) && 3039 (A == C || A == D || B == C || B == D)) { 3040 // max(x, ?) pred min(x, ?). 3041 if (Pred == CmpInst::ICMP_SGE) 3042 // Always true. 3043 return getTrue(ITy); 3044 if (Pred == CmpInst::ICMP_SLT) 3045 // Always false. 3046 return getFalse(ITy); 3047 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) && 3048 match(RHS, m_SMax(m_Value(C), m_Value(D))) && 3049 (A == C || A == D || B == C || B == D)) { 3050 // min(x, ?) pred max(x, ?). 3051 if (Pred == CmpInst::ICMP_SLE) 3052 // Always true. 3053 return getTrue(ITy); 3054 if (Pred == CmpInst::ICMP_SGT) 3055 // Always false. 3056 return getFalse(ITy); 3057 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && 3058 match(RHS, m_UMin(m_Value(C), m_Value(D))) && 3059 (A == C || A == D || B == C || B == D)) { 3060 // max(x, ?) pred min(x, ?). 3061 if (Pred == CmpInst::ICMP_UGE) 3062 // Always true. 3063 return getTrue(ITy); 3064 if (Pred == CmpInst::ICMP_ULT) 3065 // Always false. 3066 return getFalse(ITy); 3067 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) && 3068 match(RHS, m_UMax(m_Value(C), m_Value(D))) && 3069 (A == C || A == D || B == C || B == D)) { 3070 // min(x, ?) pred max(x, ?). 3071 if (Pred == CmpInst::ICMP_ULE) 3072 // Always true. 3073 return getTrue(ITy); 3074 if (Pred == CmpInst::ICMP_UGT) 3075 // Always false. 3076 return getFalse(ITy); 3077 } 3078 3079 return nullptr; 3080 } 3081 3082 /// Given operands for an ICmpInst, see if we can fold the result. 3083 /// If not, this returns null. 3084 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, 3085 const SimplifyQuery &Q, unsigned MaxRecurse) { 3086 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate; 3087 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!"); 3088 3089 if (Constant *CLHS = dyn_cast<Constant>(LHS)) { 3090 if (Constant *CRHS = dyn_cast<Constant>(RHS)) 3091 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI); 3092 3093 // If we have a constant, make sure it is on the RHS. 3094 std::swap(LHS, RHS); 3095 Pred = CmpInst::getSwappedPredicate(Pred); 3096 } 3097 3098 Type *ITy = GetCompareTy(LHS); // The return type. 3099 3100 // icmp X, X -> true/false 3101 // icmp X, undef -> true/false because undef could be X. 3102 if (LHS == RHS || isa<UndefValue>(RHS)) 3103 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred)); 3104 3105 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q)) 3106 return V; 3107 3108 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q)) 3109 return V; 3110 3111 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS)) 3112 return V; 3113 3114 // If both operands have range metadata, use the metadata 3115 // to simplify the comparison. 3116 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) { 3117 auto RHS_Instr = cast<Instruction>(RHS); 3118 auto LHS_Instr = cast<Instruction>(LHS); 3119 3120 if (RHS_Instr->getMetadata(LLVMContext::MD_range) && 3121 LHS_Instr->getMetadata(LLVMContext::MD_range)) { 3122 auto RHS_CR = getConstantRangeFromMetadata( 3123 *RHS_Instr->getMetadata(LLVMContext::MD_range)); 3124 auto LHS_CR = getConstantRangeFromMetadata( 3125 *LHS_Instr->getMetadata(LLVMContext::MD_range)); 3126 3127 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR); 3128 if (Satisfied_CR.contains(LHS_CR)) 3129 return ConstantInt::getTrue(RHS->getContext()); 3130 3131 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion( 3132 CmpInst::getInversePredicate(Pred), RHS_CR); 3133 if (InversedSatisfied_CR.contains(LHS_CR)) 3134 return ConstantInt::getFalse(RHS->getContext()); 3135 } 3136 } 3137 3138 // Compare of cast, for example (zext X) != 0 -> X != 0 3139 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) { 3140 Instruction *LI = cast<CastInst>(LHS); 3141 Value *SrcOp = LI->getOperand(0); 3142 Type *SrcTy = SrcOp->getType(); 3143 Type *DstTy = LI->getType(); 3144 3145 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input 3146 // if the integer type is the same size as the pointer type. 3147 if (MaxRecurse && isa<PtrToIntInst>(LI) && 3148 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) { 3149 if (Constant *RHSC = dyn_cast<Constant>(RHS)) { 3150 // Transfer the cast to the constant. 3151 if (Value *V = SimplifyICmpInst(Pred, SrcOp, 3152 ConstantExpr::getIntToPtr(RHSC, SrcTy), 3153 Q, MaxRecurse-1)) 3154 return V; 3155 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) { 3156 if (RI->getOperand(0)->getType() == SrcTy) 3157 // Compare without the cast. 3158 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0), 3159 Q, MaxRecurse-1)) 3160 return V; 3161 } 3162 } 3163 3164 if (isa<ZExtInst>(LHS)) { 3165 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the 3166 // same type. 3167 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) { 3168 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType()) 3169 // Compare X and Y. Note that signed predicates become unsigned. 3170 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), 3171 SrcOp, RI->getOperand(0), Q, 3172 MaxRecurse-1)) 3173 return V; 3174 } 3175 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended 3176 // too. If not, then try to deduce the result of the comparison. 3177 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 3178 // Compute the constant that would happen if we truncated to SrcTy then 3179 // reextended to DstTy. 3180 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy); 3181 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy); 3182 3183 // If the re-extended constant didn't change then this is effectively 3184 // also a case of comparing two zero-extended values. 3185 if (RExt == CI && MaxRecurse) 3186 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), 3187 SrcOp, Trunc, Q, MaxRecurse-1)) 3188 return V; 3189 3190 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit 3191 // there. Use this to work out the result of the comparison. 3192 if (RExt != CI) { 3193 switch (Pred) { 3194 default: llvm_unreachable("Unknown ICmp predicate!"); 3195 // LHS <u RHS. 3196 case ICmpInst::ICMP_EQ: 3197 case ICmpInst::ICMP_UGT: 3198 case ICmpInst::ICMP_UGE: 3199 return ConstantInt::getFalse(CI->getContext()); 3200 3201 case ICmpInst::ICMP_NE: 3202 case ICmpInst::ICMP_ULT: 3203 case ICmpInst::ICMP_ULE: 3204 return ConstantInt::getTrue(CI->getContext()); 3205 3206 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS 3207 // is non-negative then LHS <s RHS. 3208 case ICmpInst::ICMP_SGT: 3209 case ICmpInst::ICMP_SGE: 3210 return CI->getValue().isNegative() ? 3211 ConstantInt::getTrue(CI->getContext()) : 3212 ConstantInt::getFalse(CI->getContext()); 3213 3214 case ICmpInst::ICMP_SLT: 3215 case ICmpInst::ICMP_SLE: 3216 return CI->getValue().isNegative() ? 3217 ConstantInt::getFalse(CI->getContext()) : 3218 ConstantInt::getTrue(CI->getContext()); 3219 } 3220 } 3221 } 3222 } 3223 3224 if (isa<SExtInst>(LHS)) { 3225 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the 3226 // same type. 3227 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) { 3228 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType()) 3229 // Compare X and Y. Note that the predicate does not change. 3230 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0), 3231 Q, MaxRecurse-1)) 3232 return V; 3233 } 3234 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended 3235 // too. If not, then try to deduce the result of the comparison. 3236 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 3237 // Compute the constant that would happen if we truncated to SrcTy then 3238 // reextended to DstTy. 3239 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy); 3240 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy); 3241 3242 // If the re-extended constant didn't change then this is effectively 3243 // also a case of comparing two sign-extended values. 3244 if (RExt == CI && MaxRecurse) 3245 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1)) 3246 return V; 3247 3248 // Otherwise the upper bits of LHS are all equal, while RHS has varying 3249 // bits there. Use this to work out the result of the comparison. 3250 if (RExt != CI) { 3251 switch (Pred) { 3252 default: llvm_unreachable("Unknown ICmp predicate!"); 3253 case ICmpInst::ICMP_EQ: 3254 return ConstantInt::getFalse(CI->getContext()); 3255 case ICmpInst::ICMP_NE: 3256 return ConstantInt::getTrue(CI->getContext()); 3257 3258 // If RHS is non-negative then LHS <s RHS. If RHS is negative then 3259 // LHS >s RHS. 3260 case ICmpInst::ICMP_SGT: 3261 case ICmpInst::ICMP_SGE: 3262 return CI->getValue().isNegative() ? 3263 ConstantInt::getTrue(CI->getContext()) : 3264 ConstantInt::getFalse(CI->getContext()); 3265 case ICmpInst::ICMP_SLT: 3266 case ICmpInst::ICMP_SLE: 3267 return CI->getValue().isNegative() ? 3268 ConstantInt::getFalse(CI->getContext()) : 3269 ConstantInt::getTrue(CI->getContext()); 3270 3271 // If LHS is non-negative then LHS <u RHS. If LHS is negative then 3272 // LHS >u RHS. 3273 case ICmpInst::ICMP_UGT: 3274 case ICmpInst::ICMP_UGE: 3275 // Comparison is true iff the LHS <s 0. 3276 if (MaxRecurse) 3277 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp, 3278 Constant::getNullValue(SrcTy), 3279 Q, MaxRecurse-1)) 3280 return V; 3281 break; 3282 case ICmpInst::ICMP_ULT: 3283 case ICmpInst::ICMP_ULE: 3284 // Comparison is true iff the LHS >=s 0. 3285 if (MaxRecurse) 3286 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp, 3287 Constant::getNullValue(SrcTy), 3288 Q, MaxRecurse-1)) 3289 return V; 3290 break; 3291 } 3292 } 3293 } 3294 } 3295 } 3296 3297 // icmp eq|ne X, Y -> false|true if X != Y 3298 if (ICmpInst::isEquality(Pred) && 3299 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) { 3300 return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy); 3301 } 3302 3303 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse)) 3304 return V; 3305 3306 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse)) 3307 return V; 3308 3309 // Simplify comparisons of related pointers using a powerful, recursive 3310 // GEP-walk when we have target data available.. 3311 if (LHS->getType()->isPointerTy()) 3312 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI, LHS, 3313 RHS)) 3314 return C; 3315 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS)) 3316 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS)) 3317 if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) == 3318 Q.DL.getTypeSizeInBits(CLHS->getType()) && 3319 Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) == 3320 Q.DL.getTypeSizeInBits(CRHS->getType())) 3321 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI, 3322 CLHS->getPointerOperand(), 3323 CRHS->getPointerOperand())) 3324 return C; 3325 3326 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) { 3327 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) { 3328 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() && 3329 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() && 3330 (ICmpInst::isEquality(Pred) || 3331 (GLHS->isInBounds() && GRHS->isInBounds() && 3332 Pred == ICmpInst::getSignedPredicate(Pred)))) { 3333 // The bases are equal and the indices are constant. Build a constant 3334 // expression GEP with the same indices and a null base pointer to see 3335 // what constant folding can make out of it. 3336 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType()); 3337 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end()); 3338 Constant *NewLHS = ConstantExpr::getGetElementPtr( 3339 GLHS->getSourceElementType(), Null, IndicesLHS); 3340 3341 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end()); 3342 Constant *NewRHS = ConstantExpr::getGetElementPtr( 3343 GLHS->getSourceElementType(), Null, IndicesRHS); 3344 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS); 3345 } 3346 } 3347 } 3348 3349 // If the comparison is with the result of a select instruction, check whether 3350 // comparing with either branch of the select always yields the same value. 3351 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)) 3352 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse)) 3353 return V; 3354 3355 // If the comparison is with the result of a phi instruction, check whether 3356 // doing the compare with each incoming phi value yields a common result. 3357 if (isa<PHINode>(LHS) || isa<PHINode>(RHS)) 3358 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse)) 3359 return V; 3360 3361 return nullptr; 3362 } 3363 3364 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, 3365 const SimplifyQuery &Q) { 3366 return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit); 3367 } 3368 3369 /// Given operands for an FCmpInst, see if we can fold the result. 3370 /// If not, this returns null. 3371 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 3372 FastMathFlags FMF, const SimplifyQuery &Q, 3373 unsigned MaxRecurse) { 3374 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate; 3375 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!"); 3376 3377 if (Constant *CLHS = dyn_cast<Constant>(LHS)) { 3378 if (Constant *CRHS = dyn_cast<Constant>(RHS)) 3379 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI); 3380 3381 // If we have a constant, make sure it is on the RHS. 3382 std::swap(LHS, RHS); 3383 Pred = CmpInst::getSwappedPredicate(Pred); 3384 } 3385 3386 // Fold trivial predicates. 3387 Type *RetTy = GetCompareTy(LHS); 3388 if (Pred == FCmpInst::FCMP_FALSE) 3389 return getFalse(RetTy); 3390 if (Pred == FCmpInst::FCMP_TRUE) 3391 return getTrue(RetTy); 3392 3393 // UNO/ORD predicates can be trivially folded if NaNs are ignored. 3394 if (FMF.noNaNs()) { 3395 if (Pred == FCmpInst::FCMP_UNO) 3396 return getFalse(RetTy); 3397 if (Pred == FCmpInst::FCMP_ORD) 3398 return getTrue(RetTy); 3399 } 3400 3401 // NaN is unordered; NaN is not ordered. 3402 assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) && 3403 "Comparison must be either ordered or unordered"); 3404 if (match(RHS, m_NaN())) 3405 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred)); 3406 3407 // fcmp pred x, undef and fcmp pred undef, x 3408 // fold to true if unordered, false if ordered 3409 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) { 3410 // Choosing NaN for the undef will always make unordered comparison succeed 3411 // and ordered comparison fail. 3412 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred)); 3413 } 3414 3415 // fcmp x,x -> true/false. Not all compares are foldable. 3416 if (LHS == RHS) { 3417 if (CmpInst::isTrueWhenEqual(Pred)) 3418 return getTrue(RetTy); 3419 if (CmpInst::isFalseWhenEqual(Pred)) 3420 return getFalse(RetTy); 3421 } 3422 3423 // Handle fcmp with constant RHS. 3424 const APFloat *C; 3425 if (match(RHS, m_APFloat(C))) { 3426 // Check whether the constant is an infinity. 3427 if (C->isInfinity()) { 3428 if (C->isNegative()) { 3429 switch (Pred) { 3430 case FCmpInst::FCMP_OLT: 3431 // No value is ordered and less than negative infinity. 3432 return getFalse(RetTy); 3433 case FCmpInst::FCMP_UGE: 3434 // All values are unordered with or at least negative infinity. 3435 return getTrue(RetTy); 3436 default: 3437 break; 3438 } 3439 } else { 3440 switch (Pred) { 3441 case FCmpInst::FCMP_OGT: 3442 // No value is ordered and greater than infinity. 3443 return getFalse(RetTy); 3444 case FCmpInst::FCMP_ULE: 3445 // All values are unordered with and at most infinity. 3446 return getTrue(RetTy); 3447 default: 3448 break; 3449 } 3450 } 3451 } 3452 if (C->isZero()) { 3453 switch (Pred) { 3454 case FCmpInst::FCMP_UGE: 3455 if (CannotBeOrderedLessThanZero(LHS, Q.TLI)) 3456 return getTrue(RetTy); 3457 break; 3458 case FCmpInst::FCMP_OLT: 3459 // X < 0 3460 if (CannotBeOrderedLessThanZero(LHS, Q.TLI)) 3461 return getFalse(RetTy); 3462 break; 3463 default: 3464 break; 3465 } 3466 } else if (C->isNegative()) { 3467 assert(!C->isNaN() && "Unexpected NaN constant!"); 3468 // TODO: We can catch more cases by using a range check rather than 3469 // relying on CannotBeOrderedLessThanZero. 3470 switch (Pred) { 3471 case FCmpInst::FCMP_UGE: 3472 case FCmpInst::FCMP_UGT: 3473 case FCmpInst::FCMP_UNE: 3474 // (X >= 0) implies (X > C) when (C < 0) 3475 if (CannotBeOrderedLessThanZero(LHS, Q.TLI)) 3476 return getTrue(RetTy); 3477 break; 3478 case FCmpInst::FCMP_OEQ: 3479 case FCmpInst::FCMP_OLE: 3480 case FCmpInst::FCMP_OLT: 3481 // (X >= 0) implies !(X < C) when (C < 0) 3482 if (CannotBeOrderedLessThanZero(LHS, Q.TLI)) 3483 return getFalse(RetTy); 3484 break; 3485 default: 3486 break; 3487 } 3488 } 3489 } 3490 3491 // If the comparison is with the result of a select instruction, check whether 3492 // comparing with either branch of the select always yields the same value. 3493 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)) 3494 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse)) 3495 return V; 3496 3497 // If the comparison is with the result of a phi instruction, check whether 3498 // doing the compare with each incoming phi value yields a common result. 3499 if (isa<PHINode>(LHS) || isa<PHINode>(RHS)) 3500 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse)) 3501 return V; 3502 3503 return nullptr; 3504 } 3505 3506 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 3507 FastMathFlags FMF, const SimplifyQuery &Q) { 3508 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit); 3509 } 3510 3511 /// See if V simplifies when its operand Op is replaced with RepOp. 3512 static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp, 3513 const SimplifyQuery &Q, 3514 unsigned MaxRecurse) { 3515 // Trivial replacement. 3516 if (V == Op) 3517 return RepOp; 3518 3519 // We cannot replace a constant, and shouldn't even try. 3520 if (isa<Constant>(Op)) 3521 return nullptr; 3522 3523 auto *I = dyn_cast<Instruction>(V); 3524 if (!I) 3525 return nullptr; 3526 3527 // If this is a binary operator, try to simplify it with the replaced op. 3528 if (auto *B = dyn_cast<BinaryOperator>(I)) { 3529 // Consider: 3530 // %cmp = icmp eq i32 %x, 2147483647 3531 // %add = add nsw i32 %x, 1 3532 // %sel = select i1 %cmp, i32 -2147483648, i32 %add 3533 // 3534 // We can't replace %sel with %add unless we strip away the flags. 3535 if (isa<OverflowingBinaryOperator>(B)) 3536 if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap()) 3537 return nullptr; 3538 if (isa<PossiblyExactOperator>(B)) 3539 if (B->isExact()) 3540 return nullptr; 3541 3542 if (MaxRecurse) { 3543 if (B->getOperand(0) == Op) 3544 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q, 3545 MaxRecurse - 1); 3546 if (B->getOperand(1) == Op) 3547 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q, 3548 MaxRecurse - 1); 3549 } 3550 } 3551 3552 // Same for CmpInsts. 3553 if (CmpInst *C = dyn_cast<CmpInst>(I)) { 3554 if (MaxRecurse) { 3555 if (C->getOperand(0) == Op) 3556 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q, 3557 MaxRecurse - 1); 3558 if (C->getOperand(1) == Op) 3559 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q, 3560 MaxRecurse - 1); 3561 } 3562 } 3563 3564 // Same for GEPs. 3565 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) { 3566 if (MaxRecurse) { 3567 SmallVector<Value *, 8> NewOps(GEP->getNumOperands()); 3568 transform(GEP->operands(), NewOps.begin(), 3569 [&](Value *V) { return V == Op ? RepOp : V; }); 3570 return SimplifyGEPInst(GEP->getSourceElementType(), NewOps, Q, 3571 MaxRecurse - 1); 3572 } 3573 } 3574 3575 // TODO: We could hand off more cases to instsimplify here. 3576 3577 // If all operands are constant after substituting Op for RepOp then we can 3578 // constant fold the instruction. 3579 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) { 3580 // Build a list of all constant operands. 3581 SmallVector<Constant *, 8> ConstOps; 3582 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 3583 if (I->getOperand(i) == Op) 3584 ConstOps.push_back(CRepOp); 3585 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i))) 3586 ConstOps.push_back(COp); 3587 else 3588 break; 3589 } 3590 3591 // All operands were constants, fold it. 3592 if (ConstOps.size() == I->getNumOperands()) { 3593 if (CmpInst *C = dyn_cast<CmpInst>(I)) 3594 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0], 3595 ConstOps[1], Q.DL, Q.TLI); 3596 3597 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 3598 if (!LI->isVolatile()) 3599 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL); 3600 3601 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI); 3602 } 3603 } 3604 3605 return nullptr; 3606 } 3607 3608 /// Try to simplify a select instruction when its condition operand is an 3609 /// integer comparison where one operand of the compare is a constant. 3610 static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X, 3611 const APInt *Y, bool TrueWhenUnset) { 3612 const APInt *C; 3613 3614 // (X & Y) == 0 ? X & ~Y : X --> X 3615 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y 3616 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) && 3617 *Y == ~*C) 3618 return TrueWhenUnset ? FalseVal : TrueVal; 3619 3620 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y 3621 // (X & Y) != 0 ? X : X & ~Y --> X 3622 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) && 3623 *Y == ~*C) 3624 return TrueWhenUnset ? FalseVal : TrueVal; 3625 3626 if (Y->isPowerOf2()) { 3627 // (X & Y) == 0 ? X | Y : X --> X | Y 3628 // (X & Y) != 0 ? X | Y : X --> X 3629 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) && 3630 *Y == *C) 3631 return TrueWhenUnset ? TrueVal : FalseVal; 3632 3633 // (X & Y) == 0 ? X : X | Y --> X 3634 // (X & Y) != 0 ? X : X | Y --> X | Y 3635 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) && 3636 *Y == *C) 3637 return TrueWhenUnset ? TrueVal : FalseVal; 3638 } 3639 3640 return nullptr; 3641 } 3642 3643 /// An alternative way to test if a bit is set or not uses sgt/slt instead of 3644 /// eq/ne. 3645 static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS, 3646 ICmpInst::Predicate Pred, 3647 Value *TrueVal, Value *FalseVal) { 3648 Value *X; 3649 APInt Mask; 3650 if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask)) 3651 return nullptr; 3652 3653 return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask, 3654 Pred == ICmpInst::ICMP_EQ); 3655 } 3656 3657 /// Try to simplify a select instruction when its condition operand is an 3658 /// integer comparison. 3659 static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal, 3660 Value *FalseVal, const SimplifyQuery &Q, 3661 unsigned MaxRecurse) { 3662 ICmpInst::Predicate Pred; 3663 Value *CmpLHS, *CmpRHS; 3664 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS)))) 3665 return nullptr; 3666 3667 if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) { 3668 Value *X; 3669 const APInt *Y; 3670 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y)))) 3671 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y, 3672 Pred == ICmpInst::ICMP_EQ)) 3673 return V; 3674 } 3675 3676 // Check for other compares that behave like bit test. 3677 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred, 3678 TrueVal, FalseVal)) 3679 return V; 3680 3681 // If we have an equality comparison, then we know the value in one of the 3682 // arms of the select. See if substituting this value into the arm and 3683 // simplifying the result yields the same value as the other arm. 3684 if (Pred == ICmpInst::ICMP_EQ) { 3685 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) == 3686 TrueVal || 3687 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) == 3688 TrueVal) 3689 return FalseVal; 3690 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) == 3691 FalseVal || 3692 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) == 3693 FalseVal) 3694 return FalseVal; 3695 } else if (Pred == ICmpInst::ICMP_NE) { 3696 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) == 3697 FalseVal || 3698 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) == 3699 FalseVal) 3700 return TrueVal; 3701 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) == 3702 TrueVal || 3703 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) == 3704 TrueVal) 3705 return TrueVal; 3706 } 3707 3708 return nullptr; 3709 } 3710 3711 /// Given operands for a SelectInst, see if we can fold the result. 3712 /// If not, this returns null. 3713 static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal, 3714 const SimplifyQuery &Q, unsigned MaxRecurse) { 3715 if (auto *CondC = dyn_cast<Constant>(Cond)) { 3716 if (auto *TrueC = dyn_cast<Constant>(TrueVal)) 3717 if (auto *FalseC = dyn_cast<Constant>(FalseVal)) 3718 return ConstantFoldSelectInstruction(CondC, TrueC, FalseC); 3719 3720 // select undef, X, Y -> X or Y 3721 if (isa<UndefValue>(CondC)) 3722 return isa<Constant>(FalseVal) ? FalseVal : TrueVal; 3723 3724 // TODO: Vector constants with undef elements don't simplify. 3725 3726 // select true, X, Y -> X 3727 if (CondC->isAllOnesValue()) 3728 return TrueVal; 3729 // select false, X, Y -> Y 3730 if (CondC->isNullValue()) 3731 return FalseVal; 3732 } 3733 3734 // select ?, X, X -> X 3735 if (TrueVal == FalseVal) 3736 return TrueVal; 3737 3738 if (isa<UndefValue>(TrueVal)) // select ?, undef, X -> X 3739 return FalseVal; 3740 if (isa<UndefValue>(FalseVal)) // select ?, X, undef -> X 3741 return TrueVal; 3742 3743 if (Value *V = 3744 simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse)) 3745 return V; 3746 3747 return nullptr; 3748 } 3749 3750 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal, 3751 const SimplifyQuery &Q) { 3752 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit); 3753 } 3754 3755 /// Given operands for an GetElementPtrInst, see if we can fold the result. 3756 /// If not, this returns null. 3757 static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops, 3758 const SimplifyQuery &Q, unsigned) { 3759 // The type of the GEP pointer operand. 3760 unsigned AS = 3761 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace(); 3762 3763 // getelementptr P -> P. 3764 if (Ops.size() == 1) 3765 return Ops[0]; 3766 3767 // Compute the (pointer) type returned by the GEP instruction. 3768 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1)); 3769 Type *GEPTy = PointerType::get(LastType, AS); 3770 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType())) 3771 GEPTy = VectorType::get(GEPTy, VT->getNumElements()); 3772 else if (VectorType *VT = dyn_cast<VectorType>(Ops[1]->getType())) 3773 GEPTy = VectorType::get(GEPTy, VT->getNumElements()); 3774 3775 if (isa<UndefValue>(Ops[0])) 3776 return UndefValue::get(GEPTy); 3777 3778 if (Ops.size() == 2) { 3779 // getelementptr P, 0 -> P. 3780 if (match(Ops[1], m_Zero()) && Ops[0]->getType() == GEPTy) 3781 return Ops[0]; 3782 3783 Type *Ty = SrcTy; 3784 if (Ty->isSized()) { 3785 Value *P; 3786 uint64_t C; 3787 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty); 3788 // getelementptr P, N -> P if P points to a type of zero size. 3789 if (TyAllocSize == 0 && Ops[0]->getType() == GEPTy) 3790 return Ops[0]; 3791 3792 // The following transforms are only safe if the ptrtoint cast 3793 // doesn't truncate the pointers. 3794 if (Ops[1]->getType()->getScalarSizeInBits() == 3795 Q.DL.getIndexSizeInBits(AS)) { 3796 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * { 3797 if (match(P, m_Zero())) 3798 return Constant::getNullValue(GEPTy); 3799 Value *Temp; 3800 if (match(P, m_PtrToInt(m_Value(Temp)))) 3801 if (Temp->getType() == GEPTy) 3802 return Temp; 3803 return nullptr; 3804 }; 3805 3806 // getelementptr V, (sub P, V) -> P if P points to a type of size 1. 3807 if (TyAllocSize == 1 && 3808 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))))) 3809 if (Value *R = PtrToIntOrZero(P)) 3810 return R; 3811 3812 // getelementptr V, (ashr (sub P, V), C) -> Q 3813 // if P points to a type of size 1 << C. 3814 if (match(Ops[1], 3815 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))), 3816 m_ConstantInt(C))) && 3817 TyAllocSize == 1ULL << C) 3818 if (Value *R = PtrToIntOrZero(P)) 3819 return R; 3820 3821 // getelementptr V, (sdiv (sub P, V), C) -> Q 3822 // if P points to a type of size C. 3823 if (match(Ops[1], 3824 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))), 3825 m_SpecificInt(TyAllocSize)))) 3826 if (Value *R = PtrToIntOrZero(P)) 3827 return R; 3828 } 3829 } 3830 } 3831 3832 if (Q.DL.getTypeAllocSize(LastType) == 1 && 3833 all_of(Ops.slice(1).drop_back(1), 3834 [](Value *Idx) { return match(Idx, m_Zero()); })) { 3835 unsigned IdxWidth = 3836 Q.DL.getIndexSizeInBits(Ops[0]->getType()->getPointerAddressSpace()); 3837 if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == IdxWidth) { 3838 APInt BasePtrOffset(IdxWidth, 0); 3839 Value *StrippedBasePtr = 3840 Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL, 3841 BasePtrOffset); 3842 3843 // gep (gep V, C), (sub 0, V) -> C 3844 if (match(Ops.back(), 3845 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) { 3846 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset); 3847 return ConstantExpr::getIntToPtr(CI, GEPTy); 3848 } 3849 // gep (gep V, C), (xor V, -1) -> C-1 3850 if (match(Ops.back(), 3851 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) { 3852 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1); 3853 return ConstantExpr::getIntToPtr(CI, GEPTy); 3854 } 3855 } 3856 } 3857 3858 // Check to see if this is constant foldable. 3859 if (!all_of(Ops, [](Value *V) { return isa<Constant>(V); })) 3860 return nullptr; 3861 3862 auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]), 3863 Ops.slice(1)); 3864 if (auto *CEFolded = ConstantFoldConstant(CE, Q.DL)) 3865 return CEFolded; 3866 return CE; 3867 } 3868 3869 Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops, 3870 const SimplifyQuery &Q) { 3871 return ::SimplifyGEPInst(SrcTy, Ops, Q, RecursionLimit); 3872 } 3873 3874 /// Given operands for an InsertValueInst, see if we can fold the result. 3875 /// If not, this returns null. 3876 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val, 3877 ArrayRef<unsigned> Idxs, const SimplifyQuery &Q, 3878 unsigned) { 3879 if (Constant *CAgg = dyn_cast<Constant>(Agg)) 3880 if (Constant *CVal = dyn_cast<Constant>(Val)) 3881 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs); 3882 3883 // insertvalue x, undef, n -> x 3884 if (match(Val, m_Undef())) 3885 return Agg; 3886 3887 // insertvalue x, (extractvalue y, n), n 3888 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val)) 3889 if (EV->getAggregateOperand()->getType() == Agg->getType() && 3890 EV->getIndices() == Idxs) { 3891 // insertvalue undef, (extractvalue y, n), n -> y 3892 if (match(Agg, m_Undef())) 3893 return EV->getAggregateOperand(); 3894 3895 // insertvalue y, (extractvalue y, n), n -> y 3896 if (Agg == EV->getAggregateOperand()) 3897 return Agg; 3898 } 3899 3900 return nullptr; 3901 } 3902 3903 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val, 3904 ArrayRef<unsigned> Idxs, 3905 const SimplifyQuery &Q) { 3906 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit); 3907 } 3908 3909 Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx, 3910 const SimplifyQuery &Q) { 3911 // Try to constant fold. 3912 auto *VecC = dyn_cast<Constant>(Vec); 3913 auto *ValC = dyn_cast<Constant>(Val); 3914 auto *IdxC = dyn_cast<Constant>(Idx); 3915 if (VecC && ValC && IdxC) 3916 return ConstantFoldInsertElementInstruction(VecC, ValC, IdxC); 3917 3918 // Fold into undef if index is out of bounds. 3919 if (auto *CI = dyn_cast<ConstantInt>(Idx)) { 3920 uint64_t NumElements = cast<VectorType>(Vec->getType())->getNumElements(); 3921 if (CI->uge(NumElements)) 3922 return UndefValue::get(Vec->getType()); 3923 } 3924 3925 // If index is undef, it might be out of bounds (see above case) 3926 if (isa<UndefValue>(Idx)) 3927 return UndefValue::get(Vec->getType()); 3928 3929 return nullptr; 3930 } 3931 3932 /// Given operands for an ExtractValueInst, see if we can fold the result. 3933 /// If not, this returns null. 3934 static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs, 3935 const SimplifyQuery &, unsigned) { 3936 if (auto *CAgg = dyn_cast<Constant>(Agg)) 3937 return ConstantFoldExtractValueInstruction(CAgg, Idxs); 3938 3939 // extractvalue x, (insertvalue y, elt, n), n -> elt 3940 unsigned NumIdxs = Idxs.size(); 3941 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr; 3942 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) { 3943 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices(); 3944 unsigned NumInsertValueIdxs = InsertValueIdxs.size(); 3945 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs); 3946 if (InsertValueIdxs.slice(0, NumCommonIdxs) == 3947 Idxs.slice(0, NumCommonIdxs)) { 3948 if (NumIdxs == NumInsertValueIdxs) 3949 return IVI->getInsertedValueOperand(); 3950 break; 3951 } 3952 } 3953 3954 return nullptr; 3955 } 3956 3957 Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs, 3958 const SimplifyQuery &Q) { 3959 return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit); 3960 } 3961 3962 /// Given operands for an ExtractElementInst, see if we can fold the result. 3963 /// If not, this returns null. 3964 static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const SimplifyQuery &, 3965 unsigned) { 3966 if (auto *CVec = dyn_cast<Constant>(Vec)) { 3967 if (auto *CIdx = dyn_cast<Constant>(Idx)) 3968 return ConstantFoldExtractElementInstruction(CVec, CIdx); 3969 3970 // The index is not relevant if our vector is a splat. 3971 if (auto *Splat = CVec->getSplatValue()) 3972 return Splat; 3973 3974 if (isa<UndefValue>(Vec)) 3975 return UndefValue::get(Vec->getType()->getVectorElementType()); 3976 } 3977 3978 // If extracting a specified index from the vector, see if we can recursively 3979 // find a previously computed scalar that was inserted into the vector. 3980 if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) { 3981 if (IdxC->getValue().uge(Vec->getType()->getVectorNumElements())) 3982 // definitely out of bounds, thus undefined result 3983 return UndefValue::get(Vec->getType()->getVectorElementType()); 3984 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue())) 3985 return Elt; 3986 } 3987 3988 // An undef extract index can be arbitrarily chosen to be an out-of-range 3989 // index value, which would result in the instruction being undef. 3990 if (isa<UndefValue>(Idx)) 3991 return UndefValue::get(Vec->getType()->getVectorElementType()); 3992 3993 return nullptr; 3994 } 3995 3996 Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx, 3997 const SimplifyQuery &Q) { 3998 return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit); 3999 } 4000 4001 /// See if we can fold the given phi. If not, returns null. 4002 static Value *SimplifyPHINode(PHINode *PN, const SimplifyQuery &Q) { 4003 // If all of the PHI's incoming values are the same then replace the PHI node 4004 // with the common value. 4005 Value *CommonValue = nullptr; 4006 bool HasUndefInput = false; 4007 for (Value *Incoming : PN->incoming_values()) { 4008 // If the incoming value is the phi node itself, it can safely be skipped. 4009 if (Incoming == PN) continue; 4010 if (isa<UndefValue>(Incoming)) { 4011 // Remember that we saw an undef value, but otherwise ignore them. 4012 HasUndefInput = true; 4013 continue; 4014 } 4015 if (CommonValue && Incoming != CommonValue) 4016 return nullptr; // Not the same, bail out. 4017 CommonValue = Incoming; 4018 } 4019 4020 // If CommonValue is null then all of the incoming values were either undef or 4021 // equal to the phi node itself. 4022 if (!CommonValue) 4023 return UndefValue::get(PN->getType()); 4024 4025 // If we have a PHI node like phi(X, undef, X), where X is defined by some 4026 // instruction, we cannot return X as the result of the PHI node unless it 4027 // dominates the PHI block. 4028 if (HasUndefInput) 4029 return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr; 4030 4031 return CommonValue; 4032 } 4033 4034 static Value *SimplifyCastInst(unsigned CastOpc, Value *Op, 4035 Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) { 4036 if (auto *C = dyn_cast<Constant>(Op)) 4037 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL); 4038 4039 if (auto *CI = dyn_cast<CastInst>(Op)) { 4040 auto *Src = CI->getOperand(0); 4041 Type *SrcTy = Src->getType(); 4042 Type *MidTy = CI->getType(); 4043 Type *DstTy = Ty; 4044 if (Src->getType() == Ty) { 4045 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode()); 4046 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc); 4047 Type *SrcIntPtrTy = 4048 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr; 4049 Type *MidIntPtrTy = 4050 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr; 4051 Type *DstIntPtrTy = 4052 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr; 4053 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy, 4054 SrcIntPtrTy, MidIntPtrTy, 4055 DstIntPtrTy) == Instruction::BitCast) 4056 return Src; 4057 } 4058 } 4059 4060 // bitcast x -> x 4061 if (CastOpc == Instruction::BitCast) 4062 if (Op->getType() == Ty) 4063 return Op; 4064 4065 return nullptr; 4066 } 4067 4068 Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty, 4069 const SimplifyQuery &Q) { 4070 return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit); 4071 } 4072 4073 /// For the given destination element of a shuffle, peek through shuffles to 4074 /// match a root vector source operand that contains that element in the same 4075 /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s). 4076 static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1, 4077 int MaskVal, Value *RootVec, 4078 unsigned MaxRecurse) { 4079 if (!MaxRecurse--) 4080 return nullptr; 4081 4082 // Bail out if any mask value is undefined. That kind of shuffle may be 4083 // simplified further based on demanded bits or other folds. 4084 if (MaskVal == -1) 4085 return nullptr; 4086 4087 // The mask value chooses which source operand we need to look at next. 4088 int InVecNumElts = Op0->getType()->getVectorNumElements(); 4089 int RootElt = MaskVal; 4090 Value *SourceOp = Op0; 4091 if (MaskVal >= InVecNumElts) { 4092 RootElt = MaskVal - InVecNumElts; 4093 SourceOp = Op1; 4094 } 4095 4096 // If the source operand is a shuffle itself, look through it to find the 4097 // matching root vector. 4098 if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) { 4099 return foldIdentityShuffles( 4100 DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1), 4101 SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse); 4102 } 4103 4104 // TODO: Look through bitcasts? What if the bitcast changes the vector element 4105 // size? 4106 4107 // The source operand is not a shuffle. Initialize the root vector value for 4108 // this shuffle if that has not been done yet. 4109 if (!RootVec) 4110 RootVec = SourceOp; 4111 4112 // Give up as soon as a source operand does not match the existing root value. 4113 if (RootVec != SourceOp) 4114 return nullptr; 4115 4116 // The element must be coming from the same lane in the source vector 4117 // (although it may have crossed lanes in intermediate shuffles). 4118 if (RootElt != DestElt) 4119 return nullptr; 4120 4121 return RootVec; 4122 } 4123 4124 static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask, 4125 Type *RetTy, const SimplifyQuery &Q, 4126 unsigned MaxRecurse) { 4127 if (isa<UndefValue>(Mask)) 4128 return UndefValue::get(RetTy); 4129 4130 Type *InVecTy = Op0->getType(); 4131 unsigned MaskNumElts = Mask->getType()->getVectorNumElements(); 4132 unsigned InVecNumElts = InVecTy->getVectorNumElements(); 4133 4134 SmallVector<int, 32> Indices; 4135 ShuffleVectorInst::getShuffleMask(Mask, Indices); 4136 assert(MaskNumElts == Indices.size() && 4137 "Size of Indices not same as number of mask elements?"); 4138 4139 // Canonicalization: If mask does not select elements from an input vector, 4140 // replace that input vector with undef. 4141 bool MaskSelects0 = false, MaskSelects1 = false; 4142 for (unsigned i = 0; i != MaskNumElts; ++i) { 4143 if (Indices[i] == -1) 4144 continue; 4145 if ((unsigned)Indices[i] < InVecNumElts) 4146 MaskSelects0 = true; 4147 else 4148 MaskSelects1 = true; 4149 } 4150 if (!MaskSelects0) 4151 Op0 = UndefValue::get(InVecTy); 4152 if (!MaskSelects1) 4153 Op1 = UndefValue::get(InVecTy); 4154 4155 auto *Op0Const = dyn_cast<Constant>(Op0); 4156 auto *Op1Const = dyn_cast<Constant>(Op1); 4157 4158 // If all operands are constant, constant fold the shuffle. 4159 if (Op0Const && Op1Const) 4160 return ConstantFoldShuffleVectorInstruction(Op0Const, Op1Const, Mask); 4161 4162 // Canonicalization: if only one input vector is constant, it shall be the 4163 // second one. 4164 if (Op0Const && !Op1Const) { 4165 std::swap(Op0, Op1); 4166 ShuffleVectorInst::commuteShuffleMask(Indices, InVecNumElts); 4167 } 4168 4169 // A shuffle of a splat is always the splat itself. Legal if the shuffle's 4170 // value type is same as the input vectors' type. 4171 if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0)) 4172 if (isa<UndefValue>(Op1) && RetTy == InVecTy && 4173 OpShuf->getMask()->getSplatValue()) 4174 return Op0; 4175 4176 // Don't fold a shuffle with undef mask elements. This may get folded in a 4177 // better way using demanded bits or other analysis. 4178 // TODO: Should we allow this? 4179 if (find(Indices, -1) != Indices.end()) 4180 return nullptr; 4181 4182 // Check if every element of this shuffle can be mapped back to the 4183 // corresponding element of a single root vector. If so, we don't need this 4184 // shuffle. This handles simple identity shuffles as well as chains of 4185 // shuffles that may widen/narrow and/or move elements across lanes and back. 4186 Value *RootVec = nullptr; 4187 for (unsigned i = 0; i != MaskNumElts; ++i) { 4188 // Note that recursion is limited for each vector element, so if any element 4189 // exceeds the limit, this will fail to simplify. 4190 RootVec = 4191 foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse); 4192 4193 // We can't replace a widening/narrowing shuffle with one of its operands. 4194 if (!RootVec || RootVec->getType() != RetTy) 4195 return nullptr; 4196 } 4197 return RootVec; 4198 } 4199 4200 /// Given operands for a ShuffleVectorInst, fold the result or return null. 4201 Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask, 4202 Type *RetTy, const SimplifyQuery &Q) { 4203 return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit); 4204 } 4205 4206 static Constant *propagateNaN(Constant *In) { 4207 // If the input is a vector with undef elements, just return a default NaN. 4208 if (!In->isNaN()) 4209 return ConstantFP::getNaN(In->getType()); 4210 4211 // Propagate the existing NaN constant when possible. 4212 // TODO: Should we quiet a signaling NaN? 4213 return In; 4214 } 4215 4216 static Constant *simplifyFPBinop(Value *Op0, Value *Op1) { 4217 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1)) 4218 return ConstantFP::getNaN(Op0->getType()); 4219 4220 if (match(Op0, m_NaN())) 4221 return propagateNaN(cast<Constant>(Op0)); 4222 if (match(Op1, m_NaN())) 4223 return propagateNaN(cast<Constant>(Op1)); 4224 4225 return nullptr; 4226 } 4227 4228 /// Given operands for an FAdd, see if we can fold the result. If not, this 4229 /// returns null. 4230 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF, 4231 const SimplifyQuery &Q, unsigned MaxRecurse) { 4232 if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q)) 4233 return C; 4234 4235 if (Constant *C = simplifyFPBinop(Op0, Op1)) 4236 return C; 4237 4238 // fadd X, -0 ==> X 4239 if (match(Op1, m_NegZeroFP())) 4240 return Op0; 4241 4242 // fadd X, 0 ==> X, when we know X is not -0 4243 if (match(Op1, m_PosZeroFP()) && 4244 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI))) 4245 return Op0; 4246 4247 // With nnan: (+/-0.0 - X) + X --> 0.0 (and commuted variant) 4248 // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN. 4249 // Negative zeros are allowed because we always end up with positive zero: 4250 // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0 4251 // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0 4252 // X = 0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0 4253 // X = 0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0 4254 if (FMF.noNaNs() && (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) || 4255 match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0))))) 4256 return ConstantFP::getNullValue(Op0->getType()); 4257 4258 return nullptr; 4259 } 4260 4261 /// Given operands for an FSub, see if we can fold the result. If not, this 4262 /// returns null. 4263 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF, 4264 const SimplifyQuery &Q, unsigned MaxRecurse) { 4265 if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q)) 4266 return C; 4267 4268 if (Constant *C = simplifyFPBinop(Op0, Op1)) 4269 return C; 4270 4271 // fsub X, +0 ==> X 4272 if (match(Op1, m_PosZeroFP())) 4273 return Op0; 4274 4275 // fsub X, -0 ==> X, when we know X is not -0 4276 if (match(Op1, m_NegZeroFP()) && 4277 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI))) 4278 return Op0; 4279 4280 // fsub -0.0, (fsub -0.0, X) ==> X 4281 Value *X; 4282 if (match(Op0, m_NegZeroFP()) && 4283 match(Op1, m_FSub(m_NegZeroFP(), m_Value(X)))) 4284 return X; 4285 4286 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored. 4287 if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) && 4288 match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X)))) 4289 return X; 4290 4291 // fsub nnan x, x ==> 0.0 4292 if (FMF.noNaNs() && Op0 == Op1) 4293 return Constant::getNullValue(Op0->getType()); 4294 4295 return nullptr; 4296 } 4297 4298 /// Given the operands for an FMul, see if we can fold the result 4299 static Value *SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF, 4300 const SimplifyQuery &Q, unsigned MaxRecurse) { 4301 if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q)) 4302 return C; 4303 4304 if (Constant *C = simplifyFPBinop(Op0, Op1)) 4305 return C; 4306 4307 // fmul X, 1.0 ==> X 4308 if (match(Op1, m_FPOne())) 4309 return Op0; 4310 4311 // fmul nnan nsz X, 0 ==> 0 4312 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP())) 4313 return ConstantFP::getNullValue(Op0->getType()); 4314 4315 // sqrt(X) * sqrt(X) --> X, if we can: 4316 // 1. Remove the intermediate rounding (reassociate). 4317 // 2. Ignore non-zero negative numbers because sqrt would produce NAN. 4318 // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0. 4319 Value *X; 4320 if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) && 4321 FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros()) 4322 return X; 4323 4324 return nullptr; 4325 } 4326 4327 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF, 4328 const SimplifyQuery &Q) { 4329 return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit); 4330 } 4331 4332 4333 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF, 4334 const SimplifyQuery &Q) { 4335 return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit); 4336 } 4337 4338 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF, 4339 const SimplifyQuery &Q) { 4340 return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit); 4341 } 4342 4343 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF, 4344 const SimplifyQuery &Q, unsigned) { 4345 if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q)) 4346 return C; 4347 4348 if (Constant *C = simplifyFPBinop(Op0, Op1)) 4349 return C; 4350 4351 // X / 1.0 -> X 4352 if (match(Op1, m_FPOne())) 4353 return Op0; 4354 4355 // 0 / X -> 0 4356 // Requires that NaNs are off (X could be zero) and signed zeroes are 4357 // ignored (X could be positive or negative, so the output sign is unknown). 4358 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP())) 4359 return ConstantFP::getNullValue(Op0->getType()); 4360 4361 if (FMF.noNaNs()) { 4362 // X / X -> 1.0 is legal when NaNs are ignored. 4363 // We can ignore infinities because INF/INF is NaN. 4364 if (Op0 == Op1) 4365 return ConstantFP::get(Op0->getType(), 1.0); 4366 4367 // (X * Y) / Y --> X if we can reassociate to the above form. 4368 Value *X; 4369 if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1)))) 4370 return X; 4371 4372 // -X / X -> -1.0 and 4373 // X / -X -> -1.0 are legal when NaNs are ignored. 4374 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored. 4375 if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) && 4376 BinaryOperator::getFNegArgument(Op0) == Op1) || 4377 (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) && 4378 BinaryOperator::getFNegArgument(Op1) == Op0)) 4379 return ConstantFP::get(Op0->getType(), -1.0); 4380 } 4381 4382 return nullptr; 4383 } 4384 4385 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF, 4386 const SimplifyQuery &Q) { 4387 return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit); 4388 } 4389 4390 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF, 4391 const SimplifyQuery &Q, unsigned) { 4392 if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q)) 4393 return C; 4394 4395 if (Constant *C = simplifyFPBinop(Op0, Op1)) 4396 return C; 4397 4398 // Unlike fdiv, the result of frem always matches the sign of the dividend. 4399 // The constant match may include undef elements in a vector, so return a full 4400 // zero constant as the result. 4401 if (FMF.noNaNs()) { 4402 // +0 % X -> 0 4403 if (match(Op0, m_PosZeroFP())) 4404 return ConstantFP::getNullValue(Op0->getType()); 4405 // -0 % X -> -0 4406 if (match(Op0, m_NegZeroFP())) 4407 return ConstantFP::getNegativeZero(Op0->getType()); 4408 } 4409 4410 return nullptr; 4411 } 4412 4413 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF, 4414 const SimplifyQuery &Q) { 4415 return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit); 4416 } 4417 4418 //=== Helper functions for higher up the class hierarchy. 4419 4420 /// Given operands for a BinaryOperator, see if we can fold the result. 4421 /// If not, this returns null. 4422 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, 4423 const SimplifyQuery &Q, unsigned MaxRecurse) { 4424 switch (Opcode) { 4425 case Instruction::Add: 4426 return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse); 4427 case Instruction::Sub: 4428 return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse); 4429 case Instruction::Mul: 4430 return SimplifyMulInst(LHS, RHS, Q, MaxRecurse); 4431 case Instruction::SDiv: 4432 return SimplifySDivInst(LHS, RHS, Q, MaxRecurse); 4433 case Instruction::UDiv: 4434 return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse); 4435 case Instruction::SRem: 4436 return SimplifySRemInst(LHS, RHS, Q, MaxRecurse); 4437 case Instruction::URem: 4438 return SimplifyURemInst(LHS, RHS, Q, MaxRecurse); 4439 case Instruction::Shl: 4440 return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse); 4441 case Instruction::LShr: 4442 return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse); 4443 case Instruction::AShr: 4444 return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse); 4445 case Instruction::And: 4446 return SimplifyAndInst(LHS, RHS, Q, MaxRecurse); 4447 case Instruction::Or: 4448 return SimplifyOrInst(LHS, RHS, Q, MaxRecurse); 4449 case Instruction::Xor: 4450 return SimplifyXorInst(LHS, RHS, Q, MaxRecurse); 4451 case Instruction::FAdd: 4452 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 4453 case Instruction::FSub: 4454 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 4455 case Instruction::FMul: 4456 return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 4457 case Instruction::FDiv: 4458 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 4459 case Instruction::FRem: 4460 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 4461 default: 4462 llvm_unreachable("Unexpected opcode"); 4463 } 4464 } 4465 4466 /// Given operands for a BinaryOperator, see if we can fold the result. 4467 /// If not, this returns null. 4468 /// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the 4469 /// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp. 4470 static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS, 4471 const FastMathFlags &FMF, const SimplifyQuery &Q, 4472 unsigned MaxRecurse) { 4473 switch (Opcode) { 4474 case Instruction::FAdd: 4475 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse); 4476 case Instruction::FSub: 4477 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse); 4478 case Instruction::FMul: 4479 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse); 4480 case Instruction::FDiv: 4481 return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse); 4482 default: 4483 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse); 4484 } 4485 } 4486 4487 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, 4488 const SimplifyQuery &Q) { 4489 return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit); 4490 } 4491 4492 Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS, 4493 FastMathFlags FMF, const SimplifyQuery &Q) { 4494 return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit); 4495 } 4496 4497 /// Given operands for a CmpInst, see if we can fold the result. 4498 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 4499 const SimplifyQuery &Q, unsigned MaxRecurse) { 4500 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate)) 4501 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse); 4502 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse); 4503 } 4504 4505 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 4506 const SimplifyQuery &Q) { 4507 return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit); 4508 } 4509 4510 static bool IsIdempotent(Intrinsic::ID ID) { 4511 switch (ID) { 4512 default: return false; 4513 4514 // Unary idempotent: f(f(x)) = f(x) 4515 case Intrinsic::fabs: 4516 case Intrinsic::floor: 4517 case Intrinsic::ceil: 4518 case Intrinsic::trunc: 4519 case Intrinsic::rint: 4520 case Intrinsic::nearbyint: 4521 case Intrinsic::round: 4522 case Intrinsic::canonicalize: 4523 return true; 4524 } 4525 } 4526 4527 static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset, 4528 const DataLayout &DL) { 4529 GlobalValue *PtrSym; 4530 APInt PtrOffset; 4531 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL)) 4532 return nullptr; 4533 4534 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext()); 4535 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext()); 4536 Type *Int32PtrTy = Int32Ty->getPointerTo(); 4537 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext()); 4538 4539 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset); 4540 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64) 4541 return nullptr; 4542 4543 uint64_t OffsetInt = OffsetConstInt->getSExtValue(); 4544 if (OffsetInt % 4 != 0) 4545 return nullptr; 4546 4547 Constant *C = ConstantExpr::getGetElementPtr( 4548 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy), 4549 ConstantInt::get(Int64Ty, OffsetInt / 4)); 4550 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL); 4551 if (!Loaded) 4552 return nullptr; 4553 4554 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded); 4555 if (!LoadedCE) 4556 return nullptr; 4557 4558 if (LoadedCE->getOpcode() == Instruction::Trunc) { 4559 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0)); 4560 if (!LoadedCE) 4561 return nullptr; 4562 } 4563 4564 if (LoadedCE->getOpcode() != Instruction::Sub) 4565 return nullptr; 4566 4567 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0)); 4568 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt) 4569 return nullptr; 4570 auto *LoadedLHSPtr = LoadedLHS->getOperand(0); 4571 4572 Constant *LoadedRHS = LoadedCE->getOperand(1); 4573 GlobalValue *LoadedRHSSym; 4574 APInt LoadedRHSOffset; 4575 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset, 4576 DL) || 4577 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset) 4578 return nullptr; 4579 4580 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy); 4581 } 4582 4583 static bool maskIsAllZeroOrUndef(Value *Mask) { 4584 auto *ConstMask = dyn_cast<Constant>(Mask); 4585 if (!ConstMask) 4586 return false; 4587 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask)) 4588 return true; 4589 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E; 4590 ++I) { 4591 if (auto *MaskElt = ConstMask->getAggregateElement(I)) 4592 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt)) 4593 continue; 4594 return false; 4595 } 4596 return true; 4597 } 4598 4599 template <typename IterTy> 4600 static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd, 4601 const SimplifyQuery &Q, unsigned MaxRecurse) { 4602 Intrinsic::ID IID = F->getIntrinsicID(); 4603 unsigned NumOperands = std::distance(ArgBegin, ArgEnd); 4604 4605 // Unary Ops 4606 if (NumOperands == 1) { 4607 // Perform idempotent optimizations 4608 if (IsIdempotent(IID)) { 4609 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin)) { 4610 if (II->getIntrinsicID() == IID) 4611 return II; 4612 } 4613 } 4614 4615 Value *IIOperand = *ArgBegin; 4616 Value *X; 4617 switch (IID) { 4618 case Intrinsic::fabs: { 4619 if (SignBitMustBeZero(IIOperand, Q.TLI)) 4620 return IIOperand; 4621 return nullptr; 4622 } 4623 case Intrinsic::bswap: { 4624 // bswap(bswap(x)) -> x 4625 if (match(IIOperand, m_BSwap(m_Value(X)))) 4626 return X; 4627 return nullptr; 4628 } 4629 case Intrinsic::bitreverse: { 4630 // bitreverse(bitreverse(x)) -> x 4631 if (match(IIOperand, m_BitReverse(m_Value(X)))) 4632 return X; 4633 return nullptr; 4634 } 4635 case Intrinsic::exp: { 4636 // exp(log(x)) -> x 4637 if (Q.CxtI->hasAllowReassoc() && 4638 match(IIOperand, m_Intrinsic<Intrinsic::log>(m_Value(X)))) 4639 return X; 4640 return nullptr; 4641 } 4642 case Intrinsic::exp2: { 4643 // exp2(log2(x)) -> x 4644 if (Q.CxtI->hasAllowReassoc() && 4645 match(IIOperand, m_Intrinsic<Intrinsic::log2>(m_Value(X)))) 4646 return X; 4647 return nullptr; 4648 } 4649 case Intrinsic::log: { 4650 // log(exp(x)) -> x 4651 if (Q.CxtI->hasAllowReassoc() && 4652 match(IIOperand, m_Intrinsic<Intrinsic::exp>(m_Value(X)))) 4653 return X; 4654 return nullptr; 4655 } 4656 case Intrinsic::log2: { 4657 // log2(exp2(x)) -> x 4658 if (Q.CxtI->hasAllowReassoc() && 4659 match(IIOperand, m_Intrinsic<Intrinsic::exp2>(m_Value(X)))) { 4660 return X; 4661 } 4662 return nullptr; 4663 } 4664 default: 4665 return nullptr; 4666 } 4667 } 4668 4669 // Binary Ops 4670 if (NumOperands == 2) { 4671 Value *LHS = *ArgBegin; 4672 Value *RHS = *(ArgBegin + 1); 4673 Type *ReturnType = F->getReturnType(); 4674 4675 switch (IID) { 4676 case Intrinsic::usub_with_overflow: 4677 case Intrinsic::ssub_with_overflow: { 4678 // X - X -> { 0, false } 4679 if (LHS == RHS) 4680 return Constant::getNullValue(ReturnType); 4681 4682 // X - undef -> undef 4683 // undef - X -> undef 4684 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) 4685 return UndefValue::get(ReturnType); 4686 4687 return nullptr; 4688 } 4689 case Intrinsic::uadd_with_overflow: 4690 case Intrinsic::sadd_with_overflow: { 4691 // X + undef -> undef 4692 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) 4693 return UndefValue::get(ReturnType); 4694 4695 return nullptr; 4696 } 4697 case Intrinsic::umul_with_overflow: 4698 case Intrinsic::smul_with_overflow: { 4699 // 0 * X -> { 0, false } 4700 // X * 0 -> { 0, false } 4701 if (match(LHS, m_Zero()) || match(RHS, m_Zero())) 4702 return Constant::getNullValue(ReturnType); 4703 4704 // undef * X -> { 0, false } 4705 // X * undef -> { 0, false } 4706 if (match(LHS, m_Undef()) || match(RHS, m_Undef())) 4707 return Constant::getNullValue(ReturnType); 4708 4709 return nullptr; 4710 } 4711 case Intrinsic::load_relative: { 4712 Constant *C0 = dyn_cast<Constant>(LHS); 4713 Constant *C1 = dyn_cast<Constant>(RHS); 4714 if (C0 && C1) 4715 return SimplifyRelativeLoad(C0, C1, Q.DL); 4716 return nullptr; 4717 } 4718 case Intrinsic::powi: 4719 if (ConstantInt *Power = dyn_cast<ConstantInt>(RHS)) { 4720 // powi(x, 0) -> 1.0 4721 if (Power->isZero()) 4722 return ConstantFP::get(LHS->getType(), 1.0); 4723 // powi(x, 1) -> x 4724 if (Power->isOne()) 4725 return LHS; 4726 } 4727 return nullptr; 4728 case Intrinsic::maxnum: 4729 case Intrinsic::minnum: 4730 // If one argument is NaN, return the other argument. 4731 if (match(LHS, m_NaN())) 4732 return RHS; 4733 if (match(RHS, m_NaN())) 4734 return LHS; 4735 return nullptr; 4736 default: 4737 return nullptr; 4738 } 4739 } 4740 4741 // Simplify calls to llvm.masked.load.* 4742 switch (IID) { 4743 case Intrinsic::masked_load: { 4744 Value *MaskArg = ArgBegin[2]; 4745 Value *PassthruArg = ArgBegin[3]; 4746 // If the mask is all zeros or undef, the "passthru" argument is the result. 4747 if (maskIsAllZeroOrUndef(MaskArg)) 4748 return PassthruArg; 4749 return nullptr; 4750 } 4751 default: 4752 return nullptr; 4753 } 4754 } 4755 4756 template <typename IterTy> 4757 static Value *SimplifyCall(ImmutableCallSite CS, Value *V, IterTy ArgBegin, 4758 IterTy ArgEnd, const SimplifyQuery &Q, 4759 unsigned MaxRecurse) { 4760 Type *Ty = V->getType(); 4761 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) 4762 Ty = PTy->getElementType(); 4763 FunctionType *FTy = cast<FunctionType>(Ty); 4764 4765 // call undef -> undef 4766 // call null -> undef 4767 if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V)) 4768 return UndefValue::get(FTy->getReturnType()); 4769 4770 Function *F = dyn_cast<Function>(V); 4771 if (!F) 4772 return nullptr; 4773 4774 if (F->isIntrinsic()) 4775 if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse)) 4776 return Ret; 4777 4778 if (!canConstantFoldCallTo(CS, F)) 4779 return nullptr; 4780 4781 SmallVector<Constant *, 4> ConstantArgs; 4782 ConstantArgs.reserve(ArgEnd - ArgBegin); 4783 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) { 4784 Constant *C = dyn_cast<Constant>(*I); 4785 if (!C) 4786 return nullptr; 4787 ConstantArgs.push_back(C); 4788 } 4789 4790 return ConstantFoldCall(CS, F, ConstantArgs, Q.TLI); 4791 } 4792 4793 Value *llvm::SimplifyCall(ImmutableCallSite CS, Value *V, 4794 User::op_iterator ArgBegin, User::op_iterator ArgEnd, 4795 const SimplifyQuery &Q) { 4796 return ::SimplifyCall(CS, V, ArgBegin, ArgEnd, Q, RecursionLimit); 4797 } 4798 4799 Value *llvm::SimplifyCall(ImmutableCallSite CS, Value *V, 4800 ArrayRef<Value *> Args, const SimplifyQuery &Q) { 4801 return ::SimplifyCall(CS, V, Args.begin(), Args.end(), Q, RecursionLimit); 4802 } 4803 4804 Value *llvm::SimplifyCall(ImmutableCallSite ICS, const SimplifyQuery &Q) { 4805 CallSite CS(const_cast<Instruction*>(ICS.getInstruction())); 4806 return ::SimplifyCall(CS, CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), 4807 Q, RecursionLimit); 4808 } 4809 4810 /// See if we can compute a simplified version of this instruction. 4811 /// If not, this returns null. 4812 4813 Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &SQ, 4814 OptimizationRemarkEmitter *ORE) { 4815 const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I); 4816 Value *Result; 4817 4818 switch (I->getOpcode()) { 4819 default: 4820 Result = ConstantFoldInstruction(I, Q.DL, Q.TLI); 4821 break; 4822 case Instruction::FAdd: 4823 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1), 4824 I->getFastMathFlags(), Q); 4825 break; 4826 case Instruction::Add: 4827 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1), 4828 cast<BinaryOperator>(I)->hasNoSignedWrap(), 4829 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), Q); 4830 break; 4831 case Instruction::FSub: 4832 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1), 4833 I->getFastMathFlags(), Q); 4834 break; 4835 case Instruction::Sub: 4836 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1), 4837 cast<BinaryOperator>(I)->hasNoSignedWrap(), 4838 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), Q); 4839 break; 4840 case Instruction::FMul: 4841 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1), 4842 I->getFastMathFlags(), Q); 4843 break; 4844 case Instruction::Mul: 4845 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), Q); 4846 break; 4847 case Instruction::SDiv: 4848 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), Q); 4849 break; 4850 case Instruction::UDiv: 4851 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), Q); 4852 break; 4853 case Instruction::FDiv: 4854 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), 4855 I->getFastMathFlags(), Q); 4856 break; 4857 case Instruction::SRem: 4858 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), Q); 4859 break; 4860 case Instruction::URem: 4861 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), Q); 4862 break; 4863 case Instruction::FRem: 4864 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), 4865 I->getFastMathFlags(), Q); 4866 break; 4867 case Instruction::Shl: 4868 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1), 4869 cast<BinaryOperator>(I)->hasNoSignedWrap(), 4870 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), Q); 4871 break; 4872 case Instruction::LShr: 4873 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1), 4874 cast<BinaryOperator>(I)->isExact(), Q); 4875 break; 4876 case Instruction::AShr: 4877 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1), 4878 cast<BinaryOperator>(I)->isExact(), Q); 4879 break; 4880 case Instruction::And: 4881 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), Q); 4882 break; 4883 case Instruction::Or: 4884 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), Q); 4885 break; 4886 case Instruction::Xor: 4887 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), Q); 4888 break; 4889 case Instruction::ICmp: 4890 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), 4891 I->getOperand(0), I->getOperand(1), Q); 4892 break; 4893 case Instruction::FCmp: 4894 Result = 4895 SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), I->getOperand(0), 4896 I->getOperand(1), I->getFastMathFlags(), Q); 4897 break; 4898 case Instruction::Select: 4899 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1), 4900 I->getOperand(2), Q); 4901 break; 4902 case Instruction::GetElementPtr: { 4903 SmallVector<Value *, 8> Ops(I->op_begin(), I->op_end()); 4904 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(), 4905 Ops, Q); 4906 break; 4907 } 4908 case Instruction::InsertValue: { 4909 InsertValueInst *IV = cast<InsertValueInst>(I); 4910 Result = SimplifyInsertValueInst(IV->getAggregateOperand(), 4911 IV->getInsertedValueOperand(), 4912 IV->getIndices(), Q); 4913 break; 4914 } 4915 case Instruction::InsertElement: { 4916 auto *IE = cast<InsertElementInst>(I); 4917 Result = SimplifyInsertElementInst(IE->getOperand(0), IE->getOperand(1), 4918 IE->getOperand(2), Q); 4919 break; 4920 } 4921 case Instruction::ExtractValue: { 4922 auto *EVI = cast<ExtractValueInst>(I); 4923 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(), 4924 EVI->getIndices(), Q); 4925 break; 4926 } 4927 case Instruction::ExtractElement: { 4928 auto *EEI = cast<ExtractElementInst>(I); 4929 Result = SimplifyExtractElementInst(EEI->getVectorOperand(), 4930 EEI->getIndexOperand(), Q); 4931 break; 4932 } 4933 case Instruction::ShuffleVector: { 4934 auto *SVI = cast<ShuffleVectorInst>(I); 4935 Result = SimplifyShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1), 4936 SVI->getMask(), SVI->getType(), Q); 4937 break; 4938 } 4939 case Instruction::PHI: 4940 Result = SimplifyPHINode(cast<PHINode>(I), Q); 4941 break; 4942 case Instruction::Call: { 4943 CallSite CS(cast<CallInst>(I)); 4944 Result = SimplifyCall(CS, Q); 4945 break; 4946 } 4947 #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc: 4948 #include "llvm/IR/Instruction.def" 4949 #undef HANDLE_CAST_INST 4950 Result = 4951 SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(), Q); 4952 break; 4953 case Instruction::Alloca: 4954 // No simplifications for Alloca and it can't be constant folded. 4955 Result = nullptr; 4956 break; 4957 } 4958 4959 // In general, it is possible for computeKnownBits to determine all bits in a 4960 // value even when the operands are not all constants. 4961 if (!Result && I->getType()->isIntOrIntVectorTy()) { 4962 KnownBits Known = computeKnownBits(I, Q.DL, /*Depth*/ 0, Q.AC, I, Q.DT, ORE); 4963 if (Known.isConstant()) 4964 Result = ConstantInt::get(I->getType(), Known.getConstant()); 4965 } 4966 4967 /// If called on unreachable code, the above logic may report that the 4968 /// instruction simplified to itself. Make life easier for users by 4969 /// detecting that case here, returning a safe value instead. 4970 return Result == I ? UndefValue::get(I->getType()) : Result; 4971 } 4972 4973 /// Implementation of recursive simplification through an instruction's 4974 /// uses. 4975 /// 4976 /// This is the common implementation of the recursive simplification routines. 4977 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to 4978 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of 4979 /// instructions to process and attempt to simplify it using 4980 /// InstructionSimplify. 4981 /// 4982 /// This routine returns 'true' only when *it* simplifies something. The passed 4983 /// in simplified value does not count toward this. 4984 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV, 4985 const TargetLibraryInfo *TLI, 4986 const DominatorTree *DT, 4987 AssumptionCache *AC) { 4988 bool Simplified = false; 4989 SmallSetVector<Instruction *, 8> Worklist; 4990 const DataLayout &DL = I->getModule()->getDataLayout(); 4991 4992 // If we have an explicit value to collapse to, do that round of the 4993 // simplification loop by hand initially. 4994 if (SimpleV) { 4995 for (User *U : I->users()) 4996 if (U != I) 4997 Worklist.insert(cast<Instruction>(U)); 4998 4999 // Replace the instruction with its simplified value. 5000 I->replaceAllUsesWith(SimpleV); 5001 5002 // Gracefully handle edge cases where the instruction is not wired into any 5003 // parent block. 5004 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) && 5005 !I->mayHaveSideEffects()) 5006 I->eraseFromParent(); 5007 } else { 5008 Worklist.insert(I); 5009 } 5010 5011 // Note that we must test the size on each iteration, the worklist can grow. 5012 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) { 5013 I = Worklist[Idx]; 5014 5015 // See if this instruction simplifies. 5016 SimpleV = SimplifyInstruction(I, {DL, TLI, DT, AC}); 5017 if (!SimpleV) 5018 continue; 5019 5020 Simplified = true; 5021 5022 // Stash away all the uses of the old instruction so we can check them for 5023 // recursive simplifications after a RAUW. This is cheaper than checking all 5024 // uses of To on the recursive step in most cases. 5025 for (User *U : I->users()) 5026 Worklist.insert(cast<Instruction>(U)); 5027 5028 // Replace the instruction with its simplified value. 5029 I->replaceAllUsesWith(SimpleV); 5030 5031 // Gracefully handle edge cases where the instruction is not wired into any 5032 // parent block. 5033 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) && 5034 !I->mayHaveSideEffects()) 5035 I->eraseFromParent(); 5036 } 5037 return Simplified; 5038 } 5039 5040 bool llvm::recursivelySimplifyInstruction(Instruction *I, 5041 const TargetLibraryInfo *TLI, 5042 const DominatorTree *DT, 5043 AssumptionCache *AC) { 5044 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC); 5045 } 5046 5047 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV, 5048 const TargetLibraryInfo *TLI, 5049 const DominatorTree *DT, 5050 AssumptionCache *AC) { 5051 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!"); 5052 assert(SimpleV && "Must provide a simplified value."); 5053 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC); 5054 } 5055 5056 namespace llvm { 5057 const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) { 5058 auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 5059 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr; 5060 auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 5061 auto *TLI = TLIWP ? &TLIWP->getTLI() : nullptr; 5062 auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>(); 5063 auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr; 5064 return {F.getParent()->getDataLayout(), TLI, DT, AC}; 5065 } 5066 5067 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR, 5068 const DataLayout &DL) { 5069 return {DL, &AR.TLI, &AR.DT, &AR.AC}; 5070 } 5071 5072 template <class T, class... TArgs> 5073 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM, 5074 Function &F) { 5075 auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F); 5076 auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F); 5077 auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F); 5078 return {F.getParent()->getDataLayout(), TLI, DT, AC}; 5079 } 5080 template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &, 5081 Function &); 5082 } 5083