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