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