1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements routines for folding instructions into simpler forms 11 // that do not require creating new instructions. This does constant folding 12 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either 13 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value 14 // ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been 15 // simplified: This is usually true and assuming it simplifies the logic (if 16 // they have not been simplified then results are correct but maybe suboptimal). 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "llvm/Analysis/InstructionSimplify.h" 21 #include "llvm/ADT/SetVector.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/ConstantFolding.h" 24 #include "llvm/Analysis/MemoryBuiltins.h" 25 #include "llvm/Analysis/ValueTracking.h" 26 #include "llvm/IR/ConstantRange.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/Dominators.h" 29 #include "llvm/IR/GetElementPtrTypeIterator.h" 30 #include "llvm/IR/GlobalAlias.h" 31 #include "llvm/IR/Operator.h" 32 #include "llvm/IR/PatternMatch.h" 33 #include "llvm/IR/ValueHandle.h" 34 using namespace llvm; 35 using namespace llvm::PatternMatch; 36 37 #define DEBUG_TYPE "instsimplify" 38 39 enum { RecursionLimit = 3 }; 40 41 STATISTIC(NumExpand, "Number of expansions"); 42 STATISTIC(NumFactor , "Number of factorizations"); 43 STATISTIC(NumReassoc, "Number of reassociations"); 44 45 struct Query { 46 const DataLayout *DL; 47 const TargetLibraryInfo *TLI; 48 const DominatorTree *DT; 49 50 Query(const DataLayout *DL, const TargetLibraryInfo *tli, 51 const DominatorTree *dt) : DL(DL), TLI(tli), DT(dt) {} 52 }; 53 54 static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned); 55 static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &, 56 unsigned); 57 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &, 58 unsigned); 59 static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned); 60 static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned); 61 static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned); 62 63 /// getFalse - For a boolean type, or a vector of boolean type, return false, or 64 /// a vector with every element false, as appropriate for the type. 65 static Constant *getFalse(Type *Ty) { 66 assert(Ty->getScalarType()->isIntegerTy(1) && 67 "Expected i1 type or a vector of i1!"); 68 return Constant::getNullValue(Ty); 69 } 70 71 /// getTrue - For a boolean type, or a vector of boolean type, return true, or 72 /// a vector with every element true, as appropriate for the type. 73 static Constant *getTrue(Type *Ty) { 74 assert(Ty->getScalarType()->isIntegerTy(1) && 75 "Expected i1 type or a vector of i1!"); 76 return Constant::getAllOnesValue(Ty); 77 } 78 79 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"? 80 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS, 81 Value *RHS) { 82 CmpInst *Cmp = dyn_cast<CmpInst>(V); 83 if (!Cmp) 84 return false; 85 CmpInst::Predicate CPred = Cmp->getPredicate(); 86 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1); 87 if (CPred == Pred && CLHS == LHS && CRHS == RHS) 88 return true; 89 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS && 90 CRHS == LHS; 91 } 92 93 /// ValueDominatesPHI - Does the given value dominate the specified phi node? 94 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) { 95 Instruction *I = dyn_cast<Instruction>(V); 96 if (!I) 97 // Arguments and constants dominate all instructions. 98 return true; 99 100 // If we are processing instructions (and/or basic blocks) that have not been 101 // fully added to a function, the parent nodes may still be null. Simply 102 // return the conservative answer in these cases. 103 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent()) 104 return false; 105 106 // If we have a DominatorTree then do a precise test. 107 if (DT) { 108 if (!DT->isReachableFromEntry(P->getParent())) 109 return true; 110 if (!DT->isReachableFromEntry(I->getParent())) 111 return false; 112 return DT->dominates(I, P); 113 } 114 115 // Otherwise, if the instruction is in the entry block, and is not an invoke, 116 // then it obviously dominates all phi nodes. 117 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() && 118 !isa<InvokeInst>(I)) 119 return true; 120 121 return false; 122 } 123 124 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning 125 /// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is 126 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS. 127 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)". 128 /// Returns the simplified value, or null if no simplification was performed. 129 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS, 130 unsigned OpcToExpand, const Query &Q, 131 unsigned MaxRecurse) { 132 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand; 133 // Recursion is always used, so bail out at once if we already hit the limit. 134 if (!MaxRecurse--) 135 return nullptr; 136 137 // Check whether the expression has the form "(A op' B) op C". 138 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS)) 139 if (Op0->getOpcode() == OpcodeToExpand) { 140 // It does! Try turning it into "(A op C) op' (B op C)". 141 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS; 142 // Do "A op C" and "B op C" both simplify? 143 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) 144 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) { 145 // They do! Return "L op' R" if it simplifies or is already available. 146 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS. 147 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand) 148 && L == B && R == A)) { 149 ++NumExpand; 150 return LHS; 151 } 152 // Otherwise return "L op' R" if it simplifies. 153 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) { 154 ++NumExpand; 155 return V; 156 } 157 } 158 } 159 160 // Check whether the expression has the form "A op (B op' C)". 161 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS)) 162 if (Op1->getOpcode() == OpcodeToExpand) { 163 // It does! Try turning it into "(A op B) op' (A op C)". 164 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1); 165 // Do "A op B" and "A op C" both simplify? 166 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) 167 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) { 168 // They do! Return "L op' R" if it simplifies or is already available. 169 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS. 170 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand) 171 && L == C && R == B)) { 172 ++NumExpand; 173 return RHS; 174 } 175 // Otherwise return "L op' R" if it simplifies. 176 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) { 177 ++NumExpand; 178 return V; 179 } 180 } 181 } 182 183 return nullptr; 184 } 185 186 /// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term 187 /// using the operation OpCodeToExtract. For example, when Opcode is Add and 188 /// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)". 189 /// Returns the simplified value, or null if no simplification was performed. 190 static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS, 191 unsigned OpcToExtract, const Query &Q, 192 unsigned MaxRecurse) { 193 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract; 194 // Recursion is always used, so bail out at once if we already hit the limit. 195 if (!MaxRecurse--) 196 return nullptr; 197 198 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS); 199 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS); 200 201 if (!Op0 || Op0->getOpcode() != OpcodeToExtract || 202 !Op1 || Op1->getOpcode() != OpcodeToExtract) 203 return nullptr; 204 205 // The expression has the form "(A op' B) op (C op' D)". 206 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1); 207 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1); 208 209 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)". 210 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the 211 // commutative case, "(A op' B) op (C op' A)"? 212 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) { 213 Value *DD = A == C ? D : C; 214 // Form "A op' (B op DD)" if it simplifies completely. 215 // Does "B op DD" simplify? 216 if (Value *V = SimplifyBinOp(Opcode, B, DD, Q, MaxRecurse)) { 217 // It does! Return "A op' V" if it simplifies or is already available. 218 // If V equals B then "A op' V" is just the LHS. If V equals DD then 219 // "A op' V" is just the RHS. 220 if (V == B || V == DD) { 221 ++NumFactor; 222 return V == B ? LHS : RHS; 223 } 224 // Otherwise return "A op' V" if it simplifies. 225 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, Q, MaxRecurse)) { 226 ++NumFactor; 227 return W; 228 } 229 } 230 } 231 232 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)". 233 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the 234 // commutative case, "(A op' B) op (B op' D)"? 235 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) { 236 Value *CC = B == D ? C : D; 237 // Form "(A op CC) op' B" if it simplifies completely.. 238 // Does "A op CC" simplify? 239 if (Value *V = SimplifyBinOp(Opcode, A, CC, Q, MaxRecurse)) { 240 // It does! Return "V op' B" if it simplifies or is already available. 241 // If V equals A then "V op' B" is just the LHS. If V equals CC then 242 // "V op' B" is just the RHS. 243 if (V == A || V == CC) { 244 ++NumFactor; 245 return V == A ? LHS : RHS; 246 } 247 // Otherwise return "V op' B" if it simplifies. 248 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, Q, MaxRecurse)) { 249 ++NumFactor; 250 return W; 251 } 252 } 253 } 254 255 return nullptr; 256 } 257 258 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary 259 /// operations. Returns the simpler value, or null if none was found. 260 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS, 261 const Query &Q, unsigned MaxRecurse) { 262 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc; 263 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!"); 264 265 // Recursion is always used, so bail out at once if we already hit the limit. 266 if (!MaxRecurse--) 267 return nullptr; 268 269 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS); 270 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS); 271 272 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely. 273 if (Op0 && Op0->getOpcode() == Opcode) { 274 Value *A = Op0->getOperand(0); 275 Value *B = Op0->getOperand(1); 276 Value *C = RHS; 277 278 // Does "B op C" simplify? 279 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) { 280 // It does! Return "A op V" if it simplifies or is already available. 281 // If V equals B then "A op V" is just the LHS. 282 if (V == B) return LHS; 283 // Otherwise return "A op V" if it simplifies. 284 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) { 285 ++NumReassoc; 286 return W; 287 } 288 } 289 } 290 291 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely. 292 if (Op1 && Op1->getOpcode() == Opcode) { 293 Value *A = LHS; 294 Value *B = Op1->getOperand(0); 295 Value *C = Op1->getOperand(1); 296 297 // Does "A op B" simplify? 298 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) { 299 // It does! Return "V op C" if it simplifies or is already available. 300 // If V equals B then "V op C" is just the RHS. 301 if (V == B) return RHS; 302 // Otherwise return "V op C" if it simplifies. 303 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) { 304 ++NumReassoc; 305 return W; 306 } 307 } 308 } 309 310 // The remaining transforms require commutativity as well as associativity. 311 if (!Instruction::isCommutative(Opcode)) 312 return nullptr; 313 314 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely. 315 if (Op0 && Op0->getOpcode() == Opcode) { 316 Value *A = Op0->getOperand(0); 317 Value *B = Op0->getOperand(1); 318 Value *C = RHS; 319 320 // Does "C op A" simplify? 321 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) { 322 // It does! Return "V op B" if it simplifies or is already available. 323 // If V equals A then "V op B" is just the LHS. 324 if (V == A) return LHS; 325 // Otherwise return "V op B" if it simplifies. 326 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) { 327 ++NumReassoc; 328 return W; 329 } 330 } 331 } 332 333 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely. 334 if (Op1 && Op1->getOpcode() == Opcode) { 335 Value *A = LHS; 336 Value *B = Op1->getOperand(0); 337 Value *C = Op1->getOperand(1); 338 339 // Does "C op A" simplify? 340 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) { 341 // It does! Return "B op V" if it simplifies or is already available. 342 // If V equals C then "B op V" is just the RHS. 343 if (V == C) return RHS; 344 // Otherwise return "B op V" if it simplifies. 345 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) { 346 ++NumReassoc; 347 return W; 348 } 349 } 350 } 351 352 return nullptr; 353 } 354 355 /// ThreadBinOpOverSelect - In the case of a binary operation with a select 356 /// instruction as an operand, try to simplify the binop by seeing whether 357 /// evaluating it on both branches of the select results in the same value. 358 /// Returns the common value if so, otherwise returns null. 359 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS, 360 const Query &Q, unsigned MaxRecurse) { 361 // Recursion is always used, so bail out at once if we already hit the limit. 362 if (!MaxRecurse--) 363 return nullptr; 364 365 SelectInst *SI; 366 if (isa<SelectInst>(LHS)) { 367 SI = cast<SelectInst>(LHS); 368 } else { 369 assert(isa<SelectInst>(RHS) && "No select instruction operand!"); 370 SI = cast<SelectInst>(RHS); 371 } 372 373 // Evaluate the BinOp on the true and false branches of the select. 374 Value *TV; 375 Value *FV; 376 if (SI == LHS) { 377 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse); 378 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse); 379 } else { 380 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse); 381 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse); 382 } 383 384 // If they simplified to the same value, then return the common value. 385 // If they both failed to simplify then return null. 386 if (TV == FV) 387 return TV; 388 389 // If one branch simplified to undef, return the other one. 390 if (TV && isa<UndefValue>(TV)) 391 return FV; 392 if (FV && isa<UndefValue>(FV)) 393 return TV; 394 395 // If applying the operation did not change the true and false select values, 396 // then the result of the binop is the select itself. 397 if (TV == SI->getTrueValue() && FV == SI->getFalseValue()) 398 return SI; 399 400 // If one branch simplified and the other did not, and the simplified 401 // value is equal to the unsimplified one, return the simplified value. 402 // For example, select (cond, X, X & Z) & Z -> X & Z. 403 if ((FV && !TV) || (TV && !FV)) { 404 // Check that the simplified value has the form "X op Y" where "op" is the 405 // same as the original operation. 406 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV); 407 if (Simplified && Simplified->getOpcode() == Opcode) { 408 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS". 409 // We already know that "op" is the same as for the simplified value. See 410 // if the operands match too. If so, return the simplified value. 411 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue(); 412 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS; 413 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch; 414 if (Simplified->getOperand(0) == UnsimplifiedLHS && 415 Simplified->getOperand(1) == UnsimplifiedRHS) 416 return Simplified; 417 if (Simplified->isCommutative() && 418 Simplified->getOperand(1) == UnsimplifiedLHS && 419 Simplified->getOperand(0) == UnsimplifiedRHS) 420 return Simplified; 421 } 422 } 423 424 return nullptr; 425 } 426 427 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction, 428 /// try to simplify the comparison by seeing whether both branches of the select 429 /// result in the same value. Returns the common value if so, otherwise returns 430 /// null. 431 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS, 432 Value *RHS, const Query &Q, 433 unsigned MaxRecurse) { 434 // Recursion is always used, so bail out at once if we already hit the limit. 435 if (!MaxRecurse--) 436 return nullptr; 437 438 // Make sure the select is on the LHS. 439 if (!isa<SelectInst>(LHS)) { 440 std::swap(LHS, RHS); 441 Pred = CmpInst::getSwappedPredicate(Pred); 442 } 443 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!"); 444 SelectInst *SI = cast<SelectInst>(LHS); 445 Value *Cond = SI->getCondition(); 446 Value *TV = SI->getTrueValue(); 447 Value *FV = SI->getFalseValue(); 448 449 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it. 450 // Does "cmp TV, RHS" simplify? 451 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse); 452 if (TCmp == Cond) { 453 // It not only simplified, it simplified to the select condition. Replace 454 // it with 'true'. 455 TCmp = getTrue(Cond->getType()); 456 } else if (!TCmp) { 457 // It didn't simplify. However if "cmp TV, RHS" is equal to the select 458 // condition then we can replace it with 'true'. Otherwise give up. 459 if (!isSameCompare(Cond, Pred, TV, RHS)) 460 return nullptr; 461 TCmp = getTrue(Cond->getType()); 462 } 463 464 // Does "cmp FV, RHS" simplify? 465 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse); 466 if (FCmp == Cond) { 467 // It not only simplified, it simplified to the select condition. Replace 468 // it with 'false'. 469 FCmp = getFalse(Cond->getType()); 470 } else if (!FCmp) { 471 // It didn't simplify. However if "cmp FV, RHS" is equal to the select 472 // condition then we can replace it with 'false'. Otherwise give up. 473 if (!isSameCompare(Cond, Pred, FV, RHS)) 474 return nullptr; 475 FCmp = getFalse(Cond->getType()); 476 } 477 478 // If both sides simplified to the same value, then use it as the result of 479 // the original comparison. 480 if (TCmp == FCmp) 481 return TCmp; 482 483 // The remaining cases only make sense if the select condition has the same 484 // type as the result of the comparison, so bail out if this is not so. 485 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy()) 486 return nullptr; 487 // If the false value simplified to false, then the result of the compare 488 // is equal to "Cond && TCmp". This also catches the case when the false 489 // value simplified to false and the true value to true, returning "Cond". 490 if (match(FCmp, m_Zero())) 491 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse)) 492 return V; 493 // If the true value simplified to true, then the result of the compare 494 // is equal to "Cond || FCmp". 495 if (match(TCmp, m_One())) 496 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse)) 497 return V; 498 // Finally, if the false value simplified to true and the true value to 499 // false, then the result of the compare is equal to "!Cond". 500 if (match(FCmp, m_One()) && match(TCmp, m_Zero())) 501 if (Value *V = 502 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()), 503 Q, MaxRecurse)) 504 return V; 505 506 return nullptr; 507 } 508 509 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that 510 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating 511 /// it on the incoming phi values yields the same result for every value. If so 512 /// returns the common value, otherwise returns null. 513 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS, 514 const Query &Q, unsigned MaxRecurse) { 515 // Recursion is always used, so bail out at once if we already hit the limit. 516 if (!MaxRecurse--) 517 return nullptr; 518 519 PHINode *PI; 520 if (isa<PHINode>(LHS)) { 521 PI = cast<PHINode>(LHS); 522 // Bail out if RHS and the phi may be mutually interdependent due to a loop. 523 if (!ValueDominatesPHI(RHS, PI, Q.DT)) 524 return nullptr; 525 } else { 526 assert(isa<PHINode>(RHS) && "No PHI instruction operand!"); 527 PI = cast<PHINode>(RHS); 528 // Bail out if LHS and the phi may be mutually interdependent due to a loop. 529 if (!ValueDominatesPHI(LHS, PI, Q.DT)) 530 return nullptr; 531 } 532 533 // Evaluate the BinOp on the incoming phi values. 534 Value *CommonValue = nullptr; 535 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) { 536 Value *Incoming = PI->getIncomingValue(i); 537 // If the incoming value is the phi node itself, it can safely be skipped. 538 if (Incoming == PI) continue; 539 Value *V = PI == LHS ? 540 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) : 541 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse); 542 // If the operation failed to simplify, or simplified to a different value 543 // to previously, then give up. 544 if (!V || (CommonValue && V != CommonValue)) 545 return nullptr; 546 CommonValue = V; 547 } 548 549 return CommonValue; 550 } 551 552 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try 553 /// try to simplify the comparison by seeing whether comparing with all of the 554 /// incoming phi values yields the same result every time. If so returns the 555 /// common result, otherwise returns null. 556 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS, 557 const Query &Q, unsigned MaxRecurse) { 558 // Recursion is always used, so bail out at once if we already hit the limit. 559 if (!MaxRecurse--) 560 return nullptr; 561 562 // Make sure the phi is on the LHS. 563 if (!isa<PHINode>(LHS)) { 564 std::swap(LHS, RHS); 565 Pred = CmpInst::getSwappedPredicate(Pred); 566 } 567 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!"); 568 PHINode *PI = cast<PHINode>(LHS); 569 570 // Bail out if RHS and the phi may be mutually interdependent due to a loop. 571 if (!ValueDominatesPHI(RHS, PI, Q.DT)) 572 return nullptr; 573 574 // Evaluate the BinOp on the incoming phi values. 575 Value *CommonValue = nullptr; 576 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) { 577 Value *Incoming = PI->getIncomingValue(i); 578 // If the incoming value is the phi node itself, it can safely be skipped. 579 if (Incoming == PI) continue; 580 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse); 581 // If the operation failed to simplify, or simplified to a different value 582 // to previously, then give up. 583 if (!V || (CommonValue && V != CommonValue)) 584 return nullptr; 585 CommonValue = V; 586 } 587 588 return CommonValue; 589 } 590 591 /// SimplifyAddInst - Given operands for an Add, see if we can 592 /// fold the result. If not, this returns null. 593 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 594 const Query &Q, unsigned MaxRecurse) { 595 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 596 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 597 Constant *Ops[] = { CLHS, CRHS }; 598 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops, 599 Q.DL, Q.TLI); 600 } 601 602 // Canonicalize the constant to the RHS. 603 std::swap(Op0, Op1); 604 } 605 606 // X + undef -> undef 607 if (match(Op1, m_Undef())) 608 return Op1; 609 610 // X + 0 -> X 611 if (match(Op1, m_Zero())) 612 return Op0; 613 614 // X + (Y - X) -> Y 615 // (Y - X) + X -> Y 616 // Eg: X + -X -> 0 617 Value *Y = nullptr; 618 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) || 619 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1)))) 620 return Y; 621 622 // X + ~X -> -1 since ~X = -X-1 623 if (match(Op0, m_Not(m_Specific(Op1))) || 624 match(Op1, m_Not(m_Specific(Op0)))) 625 return Constant::getAllOnesValue(Op0->getType()); 626 627 /// i1 add -> xor. 628 if (MaxRecurse && Op0->getType()->isIntegerTy(1)) 629 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1)) 630 return V; 631 632 // Try some generic simplifications for associative operations. 633 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q, 634 MaxRecurse)) 635 return V; 636 637 // Mul distributes over Add. Try some generic simplifications based on this. 638 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul, 639 Q, MaxRecurse)) 640 return V; 641 642 // Threading Add over selects and phi nodes is pointless, so don't bother. 643 // Threading over the select in "A + select(cond, B, C)" means evaluating 644 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and 645 // only if B and C are equal. If B and C are equal then (since we assume 646 // that operands have already been simplified) "select(cond, B, C)" should 647 // have been simplified to the common value of B and C already. Analysing 648 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly 649 // for threading over phi nodes. 650 651 return nullptr; 652 } 653 654 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 655 const DataLayout *DL, const TargetLibraryInfo *TLI, 656 const DominatorTree *DT) { 657 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT), 658 RecursionLimit); 659 } 660 661 /// \brief Compute the base pointer and cumulative constant offsets for V. 662 /// 663 /// This strips all constant offsets off of V, leaving it the base pointer, and 664 /// accumulates the total constant offset applied in the returned constant. It 665 /// returns 0 if V is not a pointer, and returns the constant '0' if there are 666 /// no constant offsets applied. 667 /// 668 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't 669 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc. 670 /// folding. 671 static Constant *stripAndComputeConstantOffsets(const DataLayout *DL, 672 Value *&V, 673 bool AllowNonInbounds = false) { 674 assert(V->getType()->getScalarType()->isPointerTy()); 675 676 // Without DataLayout, just be conservative for now. Theoretically, more could 677 // be done in this case. 678 if (!DL) 679 return ConstantInt::get(IntegerType::get(V->getContext(), 64), 0); 680 681 Type *IntPtrTy = DL->getIntPtrType(V->getType())->getScalarType(); 682 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth()); 683 684 // Even though we don't look through PHI nodes, we could be called on an 685 // instruction in an unreachable block, which may be on a cycle. 686 SmallPtrSet<Value *, 4> Visited; 687 Visited.insert(V); 688 do { 689 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { 690 if ((!AllowNonInbounds && !GEP->isInBounds()) || 691 !GEP->accumulateConstantOffset(*DL, Offset)) 692 break; 693 V = GEP->getPointerOperand(); 694 } else if (Operator::getOpcode(V) == Instruction::BitCast) { 695 V = cast<Operator>(V)->getOperand(0); 696 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 697 if (GA->mayBeOverridden()) 698 break; 699 V = GA->getAliasee(); 700 } else { 701 break; 702 } 703 assert(V->getType()->getScalarType()->isPointerTy() && 704 "Unexpected operand type!"); 705 } while (Visited.insert(V)); 706 707 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset); 708 if (V->getType()->isVectorTy()) 709 return ConstantVector::getSplat(V->getType()->getVectorNumElements(), 710 OffsetIntPtr); 711 return OffsetIntPtr; 712 } 713 714 /// \brief Compute the constant difference between two pointer values. 715 /// If the difference is not a constant, returns zero. 716 static Constant *computePointerDifference(const DataLayout *DL, 717 Value *LHS, Value *RHS) { 718 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS); 719 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS); 720 721 // If LHS and RHS are not related via constant offsets to the same base 722 // value, there is nothing we can do here. 723 if (LHS != RHS) 724 return nullptr; 725 726 // Otherwise, the difference of LHS - RHS can be computed as: 727 // LHS - RHS 728 // = (LHSOffset + Base) - (RHSOffset + Base) 729 // = LHSOffset - RHSOffset 730 return ConstantExpr::getSub(LHSOffset, RHSOffset); 731 } 732 733 /// SimplifySubInst - Given operands for a Sub, see if we can 734 /// fold the result. If not, this returns null. 735 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 736 const Query &Q, unsigned MaxRecurse) { 737 if (Constant *CLHS = dyn_cast<Constant>(Op0)) 738 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 739 Constant *Ops[] = { CLHS, CRHS }; 740 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(), 741 Ops, Q.DL, Q.TLI); 742 } 743 744 // X - undef -> undef 745 // undef - X -> undef 746 if (match(Op0, m_Undef()) || match(Op1, m_Undef())) 747 return UndefValue::get(Op0->getType()); 748 749 // X - 0 -> X 750 if (match(Op1, m_Zero())) 751 return Op0; 752 753 // X - X -> 0 754 if (Op0 == Op1) 755 return Constant::getNullValue(Op0->getType()); 756 757 // (X*2) - X -> X 758 // (X<<1) - X -> X 759 Value *X = nullptr; 760 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) || 761 match(Op0, m_Shl(m_Specific(Op1), m_One()))) 762 return Op1; 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 *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 = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1)) 829 // It does, return the simplified "trunc V". 830 return W; 831 832 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...). 833 if (match(Op0, m_PtrToInt(m_Value(X))) && 834 match(Op1, m_PtrToInt(m_Value(Y)))) 835 if (Constant *Result = computePointerDifference(Q.DL, X, Y)) 836 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true); 837 838 // Mul distributes over Sub. Try some generic simplifications based on this. 839 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul, 840 Q, MaxRecurse)) 841 return V; 842 843 // i1 sub -> xor. 844 if (MaxRecurse && Op0->getType()->isIntegerTy(1)) 845 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1)) 846 return V; 847 848 // Threading Sub over selects and phi nodes is pointless, so don't bother. 849 // Threading over the select in "A - select(cond, B, C)" means evaluating 850 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and 851 // only if B and C are equal. If B and C are equal then (since we assume 852 // that operands have already been simplified) "select(cond, B, C)" should 853 // have been simplified to the common value of B and C already. Analysing 854 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly 855 // for threading over phi nodes. 856 857 return nullptr; 858 } 859 860 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 861 const DataLayout *DL, const TargetLibraryInfo *TLI, 862 const DominatorTree *DT) { 863 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT), 864 RecursionLimit); 865 } 866 867 /// Given operands for an FAdd, see if we can fold the result. If not, this 868 /// returns null. 869 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF, 870 const Query &Q, unsigned MaxRecurse) { 871 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 872 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 873 Constant *Ops[] = { CLHS, CRHS }; 874 return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(), 875 Ops, Q.DL, Q.TLI); 876 } 877 878 // Canonicalize the constant to the RHS. 879 std::swap(Op0, Op1); 880 } 881 882 // fadd X, -0 ==> X 883 if (match(Op1, m_NegZero())) 884 return Op0; 885 886 // fadd X, 0 ==> X, when we know X is not -0 887 if (match(Op1, m_Zero()) && 888 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0))) 889 return Op0; 890 891 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0 892 // where nnan and ninf have to occur at least once somewhere in this 893 // expression 894 Value *SubOp = nullptr; 895 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0)))) 896 SubOp = Op1; 897 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1)))) 898 SubOp = Op0; 899 if (SubOp) { 900 Instruction *FSub = cast<Instruction>(SubOp); 901 if ((FMF.noNaNs() || FSub->hasNoNaNs()) && 902 (FMF.noInfs() || FSub->hasNoInfs())) 903 return Constant::getNullValue(Op0->getType()); 904 } 905 906 return nullptr; 907 } 908 909 /// Given operands for an FSub, see if we can fold the result. If not, this 910 /// returns null. 911 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF, 912 const Query &Q, unsigned MaxRecurse) { 913 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 914 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 915 Constant *Ops[] = { CLHS, CRHS }; 916 return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(), 917 Ops, Q.DL, Q.TLI); 918 } 919 } 920 921 // fsub X, 0 ==> X 922 if (match(Op1, m_Zero())) 923 return Op0; 924 925 // fsub X, -0 ==> X, when we know X is not -0 926 if (match(Op1, m_NegZero()) && 927 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0))) 928 return Op0; 929 930 // fsub 0, (fsub -0.0, X) ==> X 931 Value *X; 932 if (match(Op0, m_AnyZero())) { 933 if (match(Op1, m_FSub(m_NegZero(), m_Value(X)))) 934 return X; 935 if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X)))) 936 return X; 937 } 938 939 // fsub nnan ninf x, x ==> 0.0 940 if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1) 941 return Constant::getNullValue(Op0->getType()); 942 943 return nullptr; 944 } 945 946 /// Given the operands for an FMul, see if we can fold the result 947 static Value *SimplifyFMulInst(Value *Op0, Value *Op1, 948 FastMathFlags FMF, 949 const Query &Q, 950 unsigned MaxRecurse) { 951 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 952 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 953 Constant *Ops[] = { CLHS, CRHS }; 954 return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(), 955 Ops, Q.DL, Q.TLI); 956 } 957 958 // Canonicalize the constant to the RHS. 959 std::swap(Op0, Op1); 960 } 961 962 // fmul X, 1.0 ==> X 963 if (match(Op1, m_FPOne())) 964 return Op0; 965 966 // fmul nnan nsz X, 0 ==> 0 967 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero())) 968 return Op1; 969 970 return nullptr; 971 } 972 973 /// SimplifyMulInst - Given operands for a Mul, see if we can 974 /// fold the result. If not, this returns null. 975 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q, 976 unsigned MaxRecurse) { 977 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 978 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 979 Constant *Ops[] = { CLHS, CRHS }; 980 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(), 981 Ops, Q.DL, Q.TLI); 982 } 983 984 // Canonicalize the constant to the RHS. 985 std::swap(Op0, Op1); 986 } 987 988 // X * undef -> 0 989 if (match(Op1, m_Undef())) 990 return Constant::getNullValue(Op0->getType()); 991 992 // X * 0 -> 0 993 if (match(Op1, m_Zero())) 994 return Op1; 995 996 // X * 1 -> X 997 if (match(Op1, m_One())) 998 return Op0; 999 1000 // (X / Y) * Y -> X if the division is exact. 1001 Value *X = nullptr; 1002 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y 1003 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y) 1004 return X; 1005 1006 // i1 mul -> and. 1007 if (MaxRecurse && Op0->getType()->isIntegerTy(1)) 1008 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1)) 1009 return V; 1010 1011 // Try some generic simplifications for associative operations. 1012 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q, 1013 MaxRecurse)) 1014 return V; 1015 1016 // Mul distributes over Add. Try some generic simplifications based on this. 1017 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add, 1018 Q, MaxRecurse)) 1019 return V; 1020 1021 // If the operation is with the result of a select instruction, check whether 1022 // operating on either branch of the select always yields the same value. 1023 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1024 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q, 1025 MaxRecurse)) 1026 return V; 1027 1028 // If the operation is with the result of a phi instruction, check whether 1029 // operating on all incoming values of the phi always yields the same value. 1030 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1031 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q, 1032 MaxRecurse)) 1033 return V; 1034 1035 return nullptr; 1036 } 1037 1038 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF, 1039 const DataLayout *DL, const TargetLibraryInfo *TLI, 1040 const DominatorTree *DT) { 1041 return ::SimplifyFAddInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit); 1042 } 1043 1044 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF, 1045 const DataLayout *DL, const TargetLibraryInfo *TLI, 1046 const DominatorTree *DT) { 1047 return ::SimplifyFSubInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit); 1048 } 1049 1050 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, 1051 FastMathFlags FMF, 1052 const DataLayout *DL, 1053 const TargetLibraryInfo *TLI, 1054 const DominatorTree *DT) { 1055 return ::SimplifyFMulInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit); 1056 } 1057 1058 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *DL, 1059 const TargetLibraryInfo *TLI, 1060 const DominatorTree *DT) { 1061 return ::SimplifyMulInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit); 1062 } 1063 1064 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can 1065 /// fold the result. If not, this returns null. 1066 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, 1067 const Query &Q, unsigned MaxRecurse) { 1068 if (Constant *C0 = dyn_cast<Constant>(Op0)) { 1069 if (Constant *C1 = dyn_cast<Constant>(Op1)) { 1070 Constant *Ops[] = { C0, C1 }; 1071 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI); 1072 } 1073 } 1074 1075 bool isSigned = Opcode == Instruction::SDiv; 1076 1077 // X / undef -> undef 1078 if (match(Op1, m_Undef())) 1079 return Op1; 1080 1081 // undef / X -> 0 1082 if (match(Op0, m_Undef())) 1083 return Constant::getNullValue(Op0->getType()); 1084 1085 // 0 / X -> 0, we don't need to preserve faults! 1086 if (match(Op0, m_Zero())) 1087 return Op0; 1088 1089 // X / 1 -> X 1090 if (match(Op1, m_One())) 1091 return Op0; 1092 1093 if (Op0->getType()->isIntegerTy(1)) 1094 // It can't be division by zero, hence it must be division by one. 1095 return Op0; 1096 1097 // X / X -> 1 1098 if (Op0 == Op1) 1099 return ConstantInt::get(Op0->getType(), 1); 1100 1101 // (X * Y) / Y -> X if the multiplication does not overflow. 1102 Value *X = nullptr, *Y = nullptr; 1103 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) { 1104 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1 1105 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0); 1106 // If the Mul knows it does not overflow, then we are good to go. 1107 if ((isSigned && Mul->hasNoSignedWrap()) || 1108 (!isSigned && Mul->hasNoUnsignedWrap())) 1109 return X; 1110 // If X has the form X = A / Y then X * Y cannot overflow. 1111 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X)) 1112 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y) 1113 return X; 1114 } 1115 1116 // (X rem Y) / Y -> 0 1117 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) || 1118 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1))))) 1119 return Constant::getNullValue(Op0->getType()); 1120 1121 // If the operation is with the result of a select instruction, check whether 1122 // operating on either branch of the select always yields the same value. 1123 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1124 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) 1125 return V; 1126 1127 // If the operation is with the result of a phi instruction, check whether 1128 // operating on all incoming values of the phi always yields the same value. 1129 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1130 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) 1131 return V; 1132 1133 return nullptr; 1134 } 1135 1136 /// SimplifySDivInst - Given operands for an SDiv, see if we can 1137 /// fold the result. If not, this returns null. 1138 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q, 1139 unsigned MaxRecurse) { 1140 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse)) 1141 return V; 1142 1143 return nullptr; 1144 } 1145 1146 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *DL, 1147 const TargetLibraryInfo *TLI, 1148 const DominatorTree *DT) { 1149 return ::SimplifySDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit); 1150 } 1151 1152 /// SimplifyUDivInst - Given operands for a UDiv, see if we can 1153 /// fold the result. If not, this returns null. 1154 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q, 1155 unsigned MaxRecurse) { 1156 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse)) 1157 return V; 1158 1159 return nullptr; 1160 } 1161 1162 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *DL, 1163 const TargetLibraryInfo *TLI, 1164 const DominatorTree *DT) { 1165 return ::SimplifyUDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit); 1166 } 1167 1168 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q, 1169 unsigned) { 1170 // undef / X -> undef (the undef could be a snan). 1171 if (match(Op0, m_Undef())) 1172 return Op0; 1173 1174 // X / undef -> undef 1175 if (match(Op1, m_Undef())) 1176 return Op1; 1177 1178 return nullptr; 1179 } 1180 1181 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *DL, 1182 const TargetLibraryInfo *TLI, 1183 const DominatorTree *DT) { 1184 return ::SimplifyFDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit); 1185 } 1186 1187 /// SimplifyRem - Given operands for an SRem or URem, see if we can 1188 /// fold the result. If not, this returns null. 1189 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, 1190 const Query &Q, unsigned MaxRecurse) { 1191 if (Constant *C0 = dyn_cast<Constant>(Op0)) { 1192 if (Constant *C1 = dyn_cast<Constant>(Op1)) { 1193 Constant *Ops[] = { C0, C1 }; 1194 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI); 1195 } 1196 } 1197 1198 // X % undef -> undef 1199 if (match(Op1, m_Undef())) 1200 return Op1; 1201 1202 // undef % X -> 0 1203 if (match(Op0, m_Undef())) 1204 return Constant::getNullValue(Op0->getType()); 1205 1206 // 0 % X -> 0, we don't need to preserve faults! 1207 if (match(Op0, m_Zero())) 1208 return Op0; 1209 1210 // X % 0 -> undef, we don't need to preserve faults! 1211 if (match(Op1, m_Zero())) 1212 return UndefValue::get(Op0->getType()); 1213 1214 // X % 1 -> 0 1215 if (match(Op1, m_One())) 1216 return Constant::getNullValue(Op0->getType()); 1217 1218 if (Op0->getType()->isIntegerTy(1)) 1219 // It can't be remainder by zero, hence it must be remainder by one. 1220 return Constant::getNullValue(Op0->getType()); 1221 1222 // X % X -> 0 1223 if (Op0 == Op1) 1224 return Constant::getNullValue(Op0->getType()); 1225 1226 // If the operation is with the result of a select instruction, check whether 1227 // operating on either branch of the select always yields the same value. 1228 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1229 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) 1230 return V; 1231 1232 // If the operation is with the result of a phi instruction, check whether 1233 // operating on all incoming values of the phi always yields the same value. 1234 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1235 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) 1236 return V; 1237 1238 return nullptr; 1239 } 1240 1241 /// SimplifySRemInst - Given operands for an SRem, see if we can 1242 /// fold the result. If not, this returns null. 1243 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q, 1244 unsigned MaxRecurse) { 1245 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse)) 1246 return V; 1247 1248 return nullptr; 1249 } 1250 1251 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *DL, 1252 const TargetLibraryInfo *TLI, 1253 const DominatorTree *DT) { 1254 return ::SimplifySRemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit); 1255 } 1256 1257 /// SimplifyURemInst - Given operands for a URem, see if we can 1258 /// fold the result. If not, this returns null. 1259 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q, 1260 unsigned MaxRecurse) { 1261 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse)) 1262 return V; 1263 1264 return nullptr; 1265 } 1266 1267 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *DL, 1268 const TargetLibraryInfo *TLI, 1269 const DominatorTree *DT) { 1270 return ::SimplifyURemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit); 1271 } 1272 1273 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &, 1274 unsigned) { 1275 // undef % X -> undef (the undef could be a snan). 1276 if (match(Op0, m_Undef())) 1277 return Op0; 1278 1279 // X % undef -> undef 1280 if (match(Op1, m_Undef())) 1281 return Op1; 1282 1283 return nullptr; 1284 } 1285 1286 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *DL, 1287 const TargetLibraryInfo *TLI, 1288 const DominatorTree *DT) { 1289 return ::SimplifyFRemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit); 1290 } 1291 1292 /// isUndefShift - Returns true if a shift by \c Amount always yields undef. 1293 static bool isUndefShift(Value *Amount) { 1294 Constant *C = dyn_cast<Constant>(Amount); 1295 if (!C) 1296 return false; 1297 1298 // X shift by undef -> undef because it may shift by the bitwidth. 1299 if (isa<UndefValue>(C)) 1300 return true; 1301 1302 // Shifting by the bitwidth or more is undefined. 1303 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1304 if (CI->getValue().getLimitedValue() >= 1305 CI->getType()->getScalarSizeInBits()) 1306 return true; 1307 1308 // If all lanes of a vector shift are undefined the whole shift is. 1309 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) { 1310 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I) 1311 if (!isUndefShift(C->getAggregateElement(I))) 1312 return false; 1313 return true; 1314 } 1315 1316 return false; 1317 } 1318 1319 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can 1320 /// fold the result. If not, this returns null. 1321 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1, 1322 const Query &Q, unsigned MaxRecurse) { 1323 if (Constant *C0 = dyn_cast<Constant>(Op0)) { 1324 if (Constant *C1 = dyn_cast<Constant>(Op1)) { 1325 Constant *Ops[] = { C0, C1 }; 1326 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI); 1327 } 1328 } 1329 1330 // 0 shift by X -> 0 1331 if (match(Op0, m_Zero())) 1332 return Op0; 1333 1334 // X shift by 0 -> X 1335 if (match(Op1, m_Zero())) 1336 return Op0; 1337 1338 // Fold undefined shifts. 1339 if (isUndefShift(Op1)) 1340 return UndefValue::get(Op0->getType()); 1341 1342 // If the operation is with the result of a select instruction, check whether 1343 // operating on either branch of the select always yields the same value. 1344 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1345 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) 1346 return V; 1347 1348 // If the operation is with the result of a phi instruction, check whether 1349 // operating on all incoming values of the phi always yields the same value. 1350 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1351 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) 1352 return V; 1353 1354 return nullptr; 1355 } 1356 1357 /// SimplifyShlInst - Given operands for an Shl, see if we can 1358 /// fold the result. If not, this returns null. 1359 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 1360 const Query &Q, unsigned MaxRecurse) { 1361 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse)) 1362 return V; 1363 1364 // undef << X -> 0 1365 if (match(Op0, m_Undef())) 1366 return Constant::getNullValue(Op0->getType()); 1367 1368 // (X >> A) << A -> X 1369 Value *X; 1370 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1))))) 1371 return X; 1372 return nullptr; 1373 } 1374 1375 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 1376 const DataLayout *DL, const TargetLibraryInfo *TLI, 1377 const DominatorTree *DT) { 1378 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT), 1379 RecursionLimit); 1380 } 1381 1382 /// SimplifyLShrInst - Given operands for an LShr, see if we can 1383 /// fold the result. If not, this returns null. 1384 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact, 1385 const Query &Q, unsigned MaxRecurse) { 1386 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse)) 1387 return V; 1388 1389 // X >> X -> 0 1390 if (Op0 == Op1) 1391 return Constant::getNullValue(Op0->getType()); 1392 1393 // undef >>l X -> 0 1394 if (match(Op0, m_Undef())) 1395 return Constant::getNullValue(Op0->getType()); 1396 1397 // (X << A) >> A -> X 1398 Value *X; 1399 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) && 1400 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap()) 1401 return X; 1402 1403 return nullptr; 1404 } 1405 1406 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact, 1407 const DataLayout *DL, 1408 const TargetLibraryInfo *TLI, 1409 const DominatorTree *DT) { 1410 return ::SimplifyLShrInst(Op0, Op1, isExact, Query (DL, TLI, DT), 1411 RecursionLimit); 1412 } 1413 1414 /// SimplifyAShrInst - Given operands for an AShr, see if we can 1415 /// fold the result. If not, this returns null. 1416 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact, 1417 const Query &Q, unsigned MaxRecurse) { 1418 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse)) 1419 return V; 1420 1421 // X >> X -> 0 1422 if (Op0 == Op1) 1423 return Constant::getNullValue(Op0->getType()); 1424 1425 // all ones >>a X -> all ones 1426 if (match(Op0, m_AllOnes())) 1427 return Op0; 1428 1429 // undef >>a X -> all ones 1430 if (match(Op0, m_Undef())) 1431 return Constant::getAllOnesValue(Op0->getType()); 1432 1433 // (X << A) >> A -> X 1434 Value *X; 1435 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) && 1436 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap()) 1437 return X; 1438 1439 return nullptr; 1440 } 1441 1442 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact, 1443 const DataLayout *DL, 1444 const TargetLibraryInfo *TLI, 1445 const DominatorTree *DT) { 1446 return ::SimplifyAShrInst(Op0, Op1, isExact, Query (DL, TLI, DT), 1447 RecursionLimit); 1448 } 1449 1450 /// SimplifyAndInst - Given operands for an And, see if we can 1451 /// fold the result. If not, this returns null. 1452 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q, 1453 unsigned MaxRecurse) { 1454 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 1455 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 1456 Constant *Ops[] = { CLHS, CRHS }; 1457 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(), 1458 Ops, Q.DL, Q.TLI); 1459 } 1460 1461 // Canonicalize the constant to the RHS. 1462 std::swap(Op0, Op1); 1463 } 1464 1465 // X & undef -> 0 1466 if (match(Op1, m_Undef())) 1467 return Constant::getNullValue(Op0->getType()); 1468 1469 // X & X = X 1470 if (Op0 == Op1) 1471 return Op0; 1472 1473 // X & 0 = 0 1474 if (match(Op1, m_Zero())) 1475 return Op1; 1476 1477 // X & -1 = X 1478 if (match(Op1, m_AllOnes())) 1479 return Op0; 1480 1481 // A & ~A = ~A & A = 0 1482 if (match(Op0, m_Not(m_Specific(Op1))) || 1483 match(Op1, m_Not(m_Specific(Op0)))) 1484 return Constant::getNullValue(Op0->getType()); 1485 1486 // (A | ?) & A = A 1487 Value *A = nullptr, *B = nullptr; 1488 if (match(Op0, m_Or(m_Value(A), m_Value(B))) && 1489 (A == Op1 || B == Op1)) 1490 return Op1; 1491 1492 // A & (A | ?) = A 1493 if (match(Op1, m_Or(m_Value(A), m_Value(B))) && 1494 (A == Op0 || B == Op0)) 1495 return Op0; 1496 1497 // A & (-A) = A if A is a power of two or zero. 1498 if (match(Op0, m_Neg(m_Specific(Op1))) || 1499 match(Op1, m_Neg(m_Specific(Op0)))) { 1500 if (isKnownToBeAPowerOfTwo(Op0, /*OrZero*/true)) 1501 return Op0; 1502 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true)) 1503 return Op1; 1504 } 1505 1506 // Try some generic simplifications for associative operations. 1507 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q, 1508 MaxRecurse)) 1509 return V; 1510 1511 // And distributes over Or. Try some generic simplifications based on this. 1512 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or, 1513 Q, MaxRecurse)) 1514 return V; 1515 1516 // And distributes over Xor. Try some generic simplifications based on this. 1517 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor, 1518 Q, MaxRecurse)) 1519 return V; 1520 1521 // Or distributes over And. Try some generic simplifications based on this. 1522 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or, 1523 Q, MaxRecurse)) 1524 return V; 1525 1526 // If the operation is with the result of a select instruction, check whether 1527 // operating on either branch of the select always yields the same value. 1528 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1529 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q, 1530 MaxRecurse)) 1531 return V; 1532 1533 // If the operation is with the result of a phi instruction, check whether 1534 // operating on all incoming values of the phi always yields the same value. 1535 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1536 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q, 1537 MaxRecurse)) 1538 return V; 1539 1540 return nullptr; 1541 } 1542 1543 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *DL, 1544 const TargetLibraryInfo *TLI, 1545 const DominatorTree *DT) { 1546 return ::SimplifyAndInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit); 1547 } 1548 1549 /// SimplifyOrInst - Given operands for an Or, see if we can 1550 /// fold the result. If not, this returns null. 1551 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q, 1552 unsigned MaxRecurse) { 1553 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 1554 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 1555 Constant *Ops[] = { CLHS, CRHS }; 1556 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(), 1557 Ops, Q.DL, Q.TLI); 1558 } 1559 1560 // Canonicalize the constant to the RHS. 1561 std::swap(Op0, Op1); 1562 } 1563 1564 // X | undef -> -1 1565 if (match(Op1, m_Undef())) 1566 return Constant::getAllOnesValue(Op0->getType()); 1567 1568 // X | X = X 1569 if (Op0 == Op1) 1570 return Op0; 1571 1572 // X | 0 = X 1573 if (match(Op1, m_Zero())) 1574 return Op0; 1575 1576 // X | -1 = -1 1577 if (match(Op1, m_AllOnes())) 1578 return Op1; 1579 1580 // A | ~A = ~A | A = -1 1581 if (match(Op0, m_Not(m_Specific(Op1))) || 1582 match(Op1, m_Not(m_Specific(Op0)))) 1583 return Constant::getAllOnesValue(Op0->getType()); 1584 1585 // (A & ?) | A = A 1586 Value *A = nullptr, *B = nullptr; 1587 if (match(Op0, m_And(m_Value(A), m_Value(B))) && 1588 (A == Op1 || B == Op1)) 1589 return Op1; 1590 1591 // A | (A & ?) = A 1592 if (match(Op1, m_And(m_Value(A), m_Value(B))) && 1593 (A == Op0 || B == Op0)) 1594 return Op0; 1595 1596 // ~(A & ?) | A = -1 1597 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) && 1598 (A == Op1 || B == Op1)) 1599 return Constant::getAllOnesValue(Op1->getType()); 1600 1601 // A | ~(A & ?) = -1 1602 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) && 1603 (A == Op0 || B == Op0)) 1604 return Constant::getAllOnesValue(Op0->getType()); 1605 1606 // Try some generic simplifications for associative operations. 1607 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q, 1608 MaxRecurse)) 1609 return V; 1610 1611 // Or distributes over And. Try some generic simplifications based on this. 1612 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q, 1613 MaxRecurse)) 1614 return V; 1615 1616 // And distributes over Or. Try some generic simplifications based on this. 1617 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And, 1618 Q, MaxRecurse)) 1619 return V; 1620 1621 // If the operation is with the result of a select instruction, check whether 1622 // operating on either branch of the select always yields the same value. 1623 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1624 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q, 1625 MaxRecurse)) 1626 return V; 1627 1628 // (A & C)|(B & D) 1629 Value *C = nullptr, *D = nullptr; 1630 if (match(Op0, m_And(m_Value(A), m_Value(C))) && 1631 match(Op1, m_And(m_Value(B), m_Value(D)))) { 1632 ConstantInt *C1 = dyn_cast<ConstantInt>(C); 1633 ConstantInt *C2 = dyn_cast<ConstantInt>(D); 1634 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) { 1635 // (A & C1)|(B & C2) 1636 // If we have: ((V + N) & C1) | (V & C2) 1637 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0 1638 // replace with V+N. 1639 Value *V1, *V2; 1640 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+ 1641 match(A, m_Add(m_Value(V1), m_Value(V2)))) { 1642 // Add commutes, try both ways. 1643 if (V1 == B && MaskedValueIsZero(V2, C2->getValue())) 1644 return A; 1645 if (V2 == B && MaskedValueIsZero(V1, C2->getValue())) 1646 return A; 1647 } 1648 // Or commutes, try both ways. 1649 if ((C1->getValue() & (C1->getValue() + 1)) == 0 && 1650 match(B, m_Add(m_Value(V1), m_Value(V2)))) { 1651 // Add commutes, try both ways. 1652 if (V1 == A && MaskedValueIsZero(V2, C1->getValue())) 1653 return B; 1654 if (V2 == A && MaskedValueIsZero(V1, C1->getValue())) 1655 return B; 1656 } 1657 } 1658 } 1659 1660 // If the operation is with the result of a phi instruction, check whether 1661 // operating on all incoming values of the phi always yields the same value. 1662 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1663 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse)) 1664 return V; 1665 1666 return nullptr; 1667 } 1668 1669 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *DL, 1670 const TargetLibraryInfo *TLI, 1671 const DominatorTree *DT) { 1672 return ::SimplifyOrInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit); 1673 } 1674 1675 /// SimplifyXorInst - Given operands for a Xor, see if we can 1676 /// fold the result. If not, this returns null. 1677 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q, 1678 unsigned MaxRecurse) { 1679 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 1680 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 1681 Constant *Ops[] = { CLHS, CRHS }; 1682 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(), 1683 Ops, Q.DL, Q.TLI); 1684 } 1685 1686 // Canonicalize the constant to the RHS. 1687 std::swap(Op0, Op1); 1688 } 1689 1690 // A ^ undef -> undef 1691 if (match(Op1, m_Undef())) 1692 return Op1; 1693 1694 // A ^ 0 = A 1695 if (match(Op1, m_Zero())) 1696 return Op0; 1697 1698 // A ^ A = 0 1699 if (Op0 == Op1) 1700 return Constant::getNullValue(Op0->getType()); 1701 1702 // A ^ ~A = ~A ^ A = -1 1703 if (match(Op0, m_Not(m_Specific(Op1))) || 1704 match(Op1, m_Not(m_Specific(Op0)))) 1705 return Constant::getAllOnesValue(Op0->getType()); 1706 1707 // Try some generic simplifications for associative operations. 1708 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q, 1709 MaxRecurse)) 1710 return V; 1711 1712 // And distributes over Xor. Try some generic simplifications based on this. 1713 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And, 1714 Q, MaxRecurse)) 1715 return V; 1716 1717 // Threading Xor over selects and phi nodes is pointless, so don't bother. 1718 // Threading over the select in "A ^ select(cond, B, C)" means evaluating 1719 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and 1720 // only if B and C are equal. If B and C are equal then (since we assume 1721 // that operands have already been simplified) "select(cond, B, C)" should 1722 // have been simplified to the common value of B and C already. Analysing 1723 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly 1724 // for threading over phi nodes. 1725 1726 return nullptr; 1727 } 1728 1729 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *DL, 1730 const TargetLibraryInfo *TLI, 1731 const DominatorTree *DT) { 1732 return ::SimplifyXorInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit); 1733 } 1734 1735 static Type *GetCompareTy(Value *Op) { 1736 return CmpInst::makeCmpResultType(Op->getType()); 1737 } 1738 1739 /// ExtractEquivalentCondition - Rummage around inside V looking for something 1740 /// equivalent to the comparison "LHS Pred RHS". Return such a value if found, 1741 /// otherwise return null. Helper function for analyzing max/min idioms. 1742 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred, 1743 Value *LHS, Value *RHS) { 1744 SelectInst *SI = dyn_cast<SelectInst>(V); 1745 if (!SI) 1746 return nullptr; 1747 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); 1748 if (!Cmp) 1749 return nullptr; 1750 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1); 1751 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS) 1752 return Cmp; 1753 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) && 1754 LHS == CmpRHS && RHS == CmpLHS) 1755 return Cmp; 1756 return nullptr; 1757 } 1758 1759 // A significant optimization not implemented here is assuming that alloca 1760 // addresses are not equal to incoming argument values. They don't *alias*, 1761 // as we say, but that doesn't mean they aren't equal, so we take a 1762 // conservative approach. 1763 // 1764 // This is inspired in part by C++11 5.10p1: 1765 // "Two pointers of the same type compare equal if and only if they are both 1766 // null, both point to the same function, or both represent the same 1767 // address." 1768 // 1769 // This is pretty permissive. 1770 // 1771 // It's also partly due to C11 6.5.9p6: 1772 // "Two pointers compare equal if and only if both are null pointers, both are 1773 // pointers to the same object (including a pointer to an object and a 1774 // subobject at its beginning) or function, both are pointers to one past the 1775 // last element of the same array object, or one is a pointer to one past the 1776 // end of one array object and the other is a pointer to the start of a 1777 // different array object that happens to immediately follow the first array 1778 // object in the address space.) 1779 // 1780 // C11's version is more restrictive, however there's no reason why an argument 1781 // couldn't be a one-past-the-end value for a stack object in the caller and be 1782 // equal to the beginning of a stack object in the callee. 1783 // 1784 // If the C and C++ standards are ever made sufficiently restrictive in this 1785 // area, it may be possible to update LLVM's semantics accordingly and reinstate 1786 // this optimization. 1787 static Constant *computePointerICmp(const DataLayout *DL, 1788 const TargetLibraryInfo *TLI, 1789 CmpInst::Predicate Pred, 1790 Value *LHS, Value *RHS) { 1791 // First, skip past any trivial no-ops. 1792 LHS = LHS->stripPointerCasts(); 1793 RHS = RHS->stripPointerCasts(); 1794 1795 // A non-null pointer is not equal to a null pointer. 1796 if (llvm::isKnownNonNull(LHS, TLI) && isa<ConstantPointerNull>(RHS) && 1797 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE)) 1798 return ConstantInt::get(GetCompareTy(LHS), 1799 !CmpInst::isTrueWhenEqual(Pred)); 1800 1801 // We can only fold certain predicates on pointer comparisons. 1802 switch (Pred) { 1803 default: 1804 return nullptr; 1805 1806 // Equality comaprisons are easy to fold. 1807 case CmpInst::ICMP_EQ: 1808 case CmpInst::ICMP_NE: 1809 break; 1810 1811 // We can only handle unsigned relational comparisons because 'inbounds' on 1812 // a GEP only protects against unsigned wrapping. 1813 case CmpInst::ICMP_UGT: 1814 case CmpInst::ICMP_UGE: 1815 case CmpInst::ICMP_ULT: 1816 case CmpInst::ICMP_ULE: 1817 // However, we have to switch them to their signed variants to handle 1818 // negative indices from the base pointer. 1819 Pred = ICmpInst::getSignedPredicate(Pred); 1820 break; 1821 } 1822 1823 // Strip off any constant offsets so that we can reason about them. 1824 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets 1825 // here and compare base addresses like AliasAnalysis does, however there are 1826 // numerous hazards. AliasAnalysis and its utilities rely on special rules 1827 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis 1828 // doesn't need to guarantee pointer inequality when it says NoAlias. 1829 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS); 1830 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS); 1831 1832 // If LHS and RHS are related via constant offsets to the same base 1833 // value, we can replace it with an icmp which just compares the offsets. 1834 if (LHS == RHS) 1835 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset); 1836 1837 // Various optimizations for (in)equality comparisons. 1838 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) { 1839 // Different non-empty allocations that exist at the same time have 1840 // different addresses (if the program can tell). Global variables always 1841 // exist, so they always exist during the lifetime of each other and all 1842 // allocas. Two different allocas usually have different addresses... 1843 // 1844 // However, if there's an @llvm.stackrestore dynamically in between two 1845 // allocas, they may have the same address. It's tempting to reduce the 1846 // scope of the problem by only looking at *static* allocas here. That would 1847 // cover the majority of allocas while significantly reducing the likelihood 1848 // of having an @llvm.stackrestore pop up in the middle. However, it's not 1849 // actually impossible for an @llvm.stackrestore to pop up in the middle of 1850 // an entry block. Also, if we have a block that's not attached to a 1851 // function, we can't tell if it's "static" under the current definition. 1852 // Theoretically, this problem could be fixed by creating a new kind of 1853 // instruction kind specifically for static allocas. Such a new instruction 1854 // could be required to be at the top of the entry block, thus preventing it 1855 // from being subject to a @llvm.stackrestore. Instcombine could even 1856 // convert regular allocas into these special allocas. It'd be nifty. 1857 // However, until then, this problem remains open. 1858 // 1859 // So, we'll assume that two non-empty allocas have different addresses 1860 // for now. 1861 // 1862 // With all that, if the offsets are within the bounds of their allocations 1863 // (and not one-past-the-end! so we can't use inbounds!), and their 1864 // allocations aren't the same, the pointers are not equal. 1865 // 1866 // Note that it's not necessary to check for LHS being a global variable 1867 // address, due to canonicalization and constant folding. 1868 if (isa<AllocaInst>(LHS) && 1869 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) { 1870 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset); 1871 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset); 1872 uint64_t LHSSize, RHSSize; 1873 if (LHSOffsetCI && RHSOffsetCI && 1874 getObjectSize(LHS, LHSSize, DL, TLI) && 1875 getObjectSize(RHS, RHSSize, DL, TLI)) { 1876 const APInt &LHSOffsetValue = LHSOffsetCI->getValue(); 1877 const APInt &RHSOffsetValue = RHSOffsetCI->getValue(); 1878 if (!LHSOffsetValue.isNegative() && 1879 !RHSOffsetValue.isNegative() && 1880 LHSOffsetValue.ult(LHSSize) && 1881 RHSOffsetValue.ult(RHSSize)) { 1882 return ConstantInt::get(GetCompareTy(LHS), 1883 !CmpInst::isTrueWhenEqual(Pred)); 1884 } 1885 } 1886 1887 // Repeat the above check but this time without depending on DataLayout 1888 // or being able to compute a precise size. 1889 if (!cast<PointerType>(LHS->getType())->isEmptyTy() && 1890 !cast<PointerType>(RHS->getType())->isEmptyTy() && 1891 LHSOffset->isNullValue() && 1892 RHSOffset->isNullValue()) 1893 return ConstantInt::get(GetCompareTy(LHS), 1894 !CmpInst::isTrueWhenEqual(Pred)); 1895 } 1896 1897 // Even if an non-inbounds GEP occurs along the path we can still optimize 1898 // equality comparisons concerning the result. We avoid walking the whole 1899 // chain again by starting where the last calls to 1900 // stripAndComputeConstantOffsets left off and accumulate the offsets. 1901 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true); 1902 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true); 1903 if (LHS == RHS) 1904 return ConstantExpr::getICmp(Pred, 1905 ConstantExpr::getAdd(LHSOffset, LHSNoBound), 1906 ConstantExpr::getAdd(RHSOffset, RHSNoBound)); 1907 } 1908 1909 // Otherwise, fail. 1910 return nullptr; 1911 } 1912 1913 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can 1914 /// fold the result. If not, this returns null. 1915 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, 1916 const Query &Q, unsigned MaxRecurse) { 1917 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate; 1918 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!"); 1919 1920 if (Constant *CLHS = dyn_cast<Constant>(LHS)) { 1921 if (Constant *CRHS = dyn_cast<Constant>(RHS)) 1922 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI); 1923 1924 // If we have a constant, make sure it is on the RHS. 1925 std::swap(LHS, RHS); 1926 Pred = CmpInst::getSwappedPredicate(Pred); 1927 } 1928 1929 Type *ITy = GetCompareTy(LHS); // The return type. 1930 Type *OpTy = LHS->getType(); // The operand type. 1931 1932 // icmp X, X -> true/false 1933 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false 1934 // because X could be 0. 1935 if (LHS == RHS || isa<UndefValue>(RHS)) 1936 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred)); 1937 1938 // Special case logic when the operands have i1 type. 1939 if (OpTy->getScalarType()->isIntegerTy(1)) { 1940 switch (Pred) { 1941 default: break; 1942 case ICmpInst::ICMP_EQ: 1943 // X == 1 -> X 1944 if (match(RHS, m_One())) 1945 return LHS; 1946 break; 1947 case ICmpInst::ICMP_NE: 1948 // X != 0 -> X 1949 if (match(RHS, m_Zero())) 1950 return LHS; 1951 break; 1952 case ICmpInst::ICMP_UGT: 1953 // X >u 0 -> X 1954 if (match(RHS, m_Zero())) 1955 return LHS; 1956 break; 1957 case ICmpInst::ICMP_UGE: 1958 // X >=u 1 -> X 1959 if (match(RHS, m_One())) 1960 return LHS; 1961 break; 1962 case ICmpInst::ICMP_SLT: 1963 // X <s 0 -> X 1964 if (match(RHS, m_Zero())) 1965 return LHS; 1966 break; 1967 case ICmpInst::ICMP_SLE: 1968 // X <=s -1 -> X 1969 if (match(RHS, m_One())) 1970 return LHS; 1971 break; 1972 } 1973 } 1974 1975 // If we are comparing with zero then try hard since this is a common case. 1976 if (match(RHS, m_Zero())) { 1977 bool LHSKnownNonNegative, LHSKnownNegative; 1978 switch (Pred) { 1979 default: llvm_unreachable("Unknown ICmp predicate!"); 1980 case ICmpInst::ICMP_ULT: 1981 return getFalse(ITy); 1982 case ICmpInst::ICMP_UGE: 1983 return getTrue(ITy); 1984 case ICmpInst::ICMP_EQ: 1985 case ICmpInst::ICMP_ULE: 1986 if (isKnownNonZero(LHS, Q.DL)) 1987 return getFalse(ITy); 1988 break; 1989 case ICmpInst::ICMP_NE: 1990 case ICmpInst::ICMP_UGT: 1991 if (isKnownNonZero(LHS, Q.DL)) 1992 return getTrue(ITy); 1993 break; 1994 case ICmpInst::ICMP_SLT: 1995 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL); 1996 if (LHSKnownNegative) 1997 return getTrue(ITy); 1998 if (LHSKnownNonNegative) 1999 return getFalse(ITy); 2000 break; 2001 case ICmpInst::ICMP_SLE: 2002 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL); 2003 if (LHSKnownNegative) 2004 return getTrue(ITy); 2005 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL)) 2006 return getFalse(ITy); 2007 break; 2008 case ICmpInst::ICMP_SGE: 2009 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL); 2010 if (LHSKnownNegative) 2011 return getFalse(ITy); 2012 if (LHSKnownNonNegative) 2013 return getTrue(ITy); 2014 break; 2015 case ICmpInst::ICMP_SGT: 2016 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL); 2017 if (LHSKnownNegative) 2018 return getFalse(ITy); 2019 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL)) 2020 return getTrue(ITy); 2021 break; 2022 } 2023 } 2024 2025 // See if we are doing a comparison with a constant integer. 2026 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 2027 // Rule out tautological comparisons (eg., ult 0 or uge 0). 2028 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue()); 2029 if (RHS_CR.isEmptySet()) 2030 return ConstantInt::getFalse(CI->getContext()); 2031 if (RHS_CR.isFullSet()) 2032 return ConstantInt::getTrue(CI->getContext()); 2033 2034 // Many binary operators with constant RHS have easy to compute constant 2035 // range. Use them to check whether the comparison is a tautology. 2036 unsigned Width = CI->getBitWidth(); 2037 APInt Lower = APInt(Width, 0); 2038 APInt Upper = APInt(Width, 0); 2039 ConstantInt *CI2; 2040 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) { 2041 // 'urem x, CI2' produces [0, CI2). 2042 Upper = CI2->getValue(); 2043 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) { 2044 // 'srem x, CI2' produces (-|CI2|, |CI2|). 2045 Upper = CI2->getValue().abs(); 2046 Lower = (-Upper) + 1; 2047 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) { 2048 // 'udiv CI2, x' produces [0, CI2]. 2049 Upper = CI2->getValue() + 1; 2050 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) { 2051 // 'udiv x, CI2' produces [0, UINT_MAX / CI2]. 2052 APInt NegOne = APInt::getAllOnesValue(Width); 2053 if (!CI2->isZero()) 2054 Upper = NegOne.udiv(CI2->getValue()) + 1; 2055 } else if (match(LHS, m_SDiv(m_ConstantInt(CI2), m_Value()))) { 2056 // 'sdiv CI2, x' produces [-|CI2|, |CI2|]. 2057 Upper = CI2->getValue().abs() + 1; 2058 Lower = (-Upper) + 1; 2059 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) { 2060 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2]. 2061 APInt IntMin = APInt::getSignedMinValue(Width); 2062 APInt IntMax = APInt::getSignedMaxValue(Width); 2063 APInt Val = CI2->getValue().abs(); 2064 if (!Val.isMinValue()) { 2065 Lower = IntMin.sdiv(Val); 2066 Upper = IntMax.sdiv(Val) + 1; 2067 } 2068 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) { 2069 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2]. 2070 APInt NegOne = APInt::getAllOnesValue(Width); 2071 if (CI2->getValue().ult(Width)) 2072 Upper = NegOne.lshr(CI2->getValue()) + 1; 2073 } else if (match(LHS, m_LShr(m_ConstantInt(CI2), m_Value()))) { 2074 // 'lshr CI2, x' produces [CI2 >> (Width-1), CI2]. 2075 unsigned ShiftAmount = Width - 1; 2076 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact()) 2077 ShiftAmount = CI2->getValue().countTrailingZeros(); 2078 Lower = CI2->getValue().lshr(ShiftAmount); 2079 Upper = CI2->getValue() + 1; 2080 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) { 2081 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2]. 2082 APInt IntMin = APInt::getSignedMinValue(Width); 2083 APInt IntMax = APInt::getSignedMaxValue(Width); 2084 if (CI2->getValue().ult(Width)) { 2085 Lower = IntMin.ashr(CI2->getValue()); 2086 Upper = IntMax.ashr(CI2->getValue()) + 1; 2087 } 2088 } else if (match(LHS, m_AShr(m_ConstantInt(CI2), m_Value()))) { 2089 unsigned ShiftAmount = Width - 1; 2090 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact()) 2091 ShiftAmount = CI2->getValue().countTrailingZeros(); 2092 if (CI2->isNegative()) { 2093 // 'ashr CI2, x' produces [CI2, CI2 >> (Width-1)] 2094 Lower = CI2->getValue(); 2095 Upper = CI2->getValue().ashr(ShiftAmount) + 1; 2096 } else { 2097 // 'ashr CI2, x' produces [CI2 >> (Width-1), CI2] 2098 Lower = CI2->getValue().ashr(ShiftAmount); 2099 Upper = CI2->getValue() + 1; 2100 } 2101 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) { 2102 // 'or x, CI2' produces [CI2, UINT_MAX]. 2103 Lower = CI2->getValue(); 2104 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) { 2105 // 'and x, CI2' produces [0, CI2]. 2106 Upper = CI2->getValue() + 1; 2107 } 2108 if (Lower != Upper) { 2109 ConstantRange LHS_CR = ConstantRange(Lower, Upper); 2110 if (RHS_CR.contains(LHS_CR)) 2111 return ConstantInt::getTrue(RHS->getContext()); 2112 if (RHS_CR.inverse().contains(LHS_CR)) 2113 return ConstantInt::getFalse(RHS->getContext()); 2114 } 2115 } 2116 2117 // Compare of cast, for example (zext X) != 0 -> X != 0 2118 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) { 2119 Instruction *LI = cast<CastInst>(LHS); 2120 Value *SrcOp = LI->getOperand(0); 2121 Type *SrcTy = SrcOp->getType(); 2122 Type *DstTy = LI->getType(); 2123 2124 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input 2125 // if the integer type is the same size as the pointer type. 2126 if (MaxRecurse && Q.DL && isa<PtrToIntInst>(LI) && 2127 Q.DL->getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) { 2128 if (Constant *RHSC = dyn_cast<Constant>(RHS)) { 2129 // Transfer the cast to the constant. 2130 if (Value *V = SimplifyICmpInst(Pred, SrcOp, 2131 ConstantExpr::getIntToPtr(RHSC, SrcTy), 2132 Q, MaxRecurse-1)) 2133 return V; 2134 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) { 2135 if (RI->getOperand(0)->getType() == SrcTy) 2136 // Compare without the cast. 2137 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0), 2138 Q, MaxRecurse-1)) 2139 return V; 2140 } 2141 } 2142 2143 if (isa<ZExtInst>(LHS)) { 2144 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the 2145 // same type. 2146 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) { 2147 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType()) 2148 // Compare X and Y. Note that signed predicates become unsigned. 2149 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), 2150 SrcOp, RI->getOperand(0), Q, 2151 MaxRecurse-1)) 2152 return V; 2153 } 2154 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended 2155 // too. If not, then try to deduce the result of the comparison. 2156 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 2157 // Compute the constant that would happen if we truncated to SrcTy then 2158 // reextended to DstTy. 2159 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy); 2160 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy); 2161 2162 // If the re-extended constant didn't change then this is effectively 2163 // also a case of comparing two zero-extended values. 2164 if (RExt == CI && MaxRecurse) 2165 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), 2166 SrcOp, Trunc, Q, MaxRecurse-1)) 2167 return V; 2168 2169 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit 2170 // there. Use this to work out the result of the comparison. 2171 if (RExt != CI) { 2172 switch (Pred) { 2173 default: llvm_unreachable("Unknown ICmp predicate!"); 2174 // LHS <u RHS. 2175 case ICmpInst::ICMP_EQ: 2176 case ICmpInst::ICMP_UGT: 2177 case ICmpInst::ICMP_UGE: 2178 return ConstantInt::getFalse(CI->getContext()); 2179 2180 case ICmpInst::ICMP_NE: 2181 case ICmpInst::ICMP_ULT: 2182 case ICmpInst::ICMP_ULE: 2183 return ConstantInt::getTrue(CI->getContext()); 2184 2185 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS 2186 // is non-negative then LHS <s RHS. 2187 case ICmpInst::ICMP_SGT: 2188 case ICmpInst::ICMP_SGE: 2189 return CI->getValue().isNegative() ? 2190 ConstantInt::getTrue(CI->getContext()) : 2191 ConstantInt::getFalse(CI->getContext()); 2192 2193 case ICmpInst::ICMP_SLT: 2194 case ICmpInst::ICMP_SLE: 2195 return CI->getValue().isNegative() ? 2196 ConstantInt::getFalse(CI->getContext()) : 2197 ConstantInt::getTrue(CI->getContext()); 2198 } 2199 } 2200 } 2201 } 2202 2203 if (isa<SExtInst>(LHS)) { 2204 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the 2205 // same type. 2206 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) { 2207 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType()) 2208 // Compare X and Y. Note that the predicate does not change. 2209 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0), 2210 Q, MaxRecurse-1)) 2211 return V; 2212 } 2213 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended 2214 // too. If not, then try to deduce the result of the comparison. 2215 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 2216 // Compute the constant that would happen if we truncated to SrcTy then 2217 // reextended to DstTy. 2218 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy); 2219 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy); 2220 2221 // If the re-extended constant didn't change then this is effectively 2222 // also a case of comparing two sign-extended values. 2223 if (RExt == CI && MaxRecurse) 2224 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1)) 2225 return V; 2226 2227 // Otherwise the upper bits of LHS are all equal, while RHS has varying 2228 // bits there. Use this to work out the result of the comparison. 2229 if (RExt != CI) { 2230 switch (Pred) { 2231 default: llvm_unreachable("Unknown ICmp predicate!"); 2232 case ICmpInst::ICMP_EQ: 2233 return ConstantInt::getFalse(CI->getContext()); 2234 case ICmpInst::ICMP_NE: 2235 return ConstantInt::getTrue(CI->getContext()); 2236 2237 // If RHS is non-negative then LHS <s RHS. If RHS is negative then 2238 // LHS >s RHS. 2239 case ICmpInst::ICMP_SGT: 2240 case ICmpInst::ICMP_SGE: 2241 return CI->getValue().isNegative() ? 2242 ConstantInt::getTrue(CI->getContext()) : 2243 ConstantInt::getFalse(CI->getContext()); 2244 case ICmpInst::ICMP_SLT: 2245 case ICmpInst::ICMP_SLE: 2246 return CI->getValue().isNegative() ? 2247 ConstantInt::getFalse(CI->getContext()) : 2248 ConstantInt::getTrue(CI->getContext()); 2249 2250 // If LHS is non-negative then LHS <u RHS. If LHS is negative then 2251 // LHS >u RHS. 2252 case ICmpInst::ICMP_UGT: 2253 case ICmpInst::ICMP_UGE: 2254 // Comparison is true iff the LHS <s 0. 2255 if (MaxRecurse) 2256 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp, 2257 Constant::getNullValue(SrcTy), 2258 Q, MaxRecurse-1)) 2259 return V; 2260 break; 2261 case ICmpInst::ICMP_ULT: 2262 case ICmpInst::ICMP_ULE: 2263 // Comparison is true iff the LHS >=s 0. 2264 if (MaxRecurse) 2265 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp, 2266 Constant::getNullValue(SrcTy), 2267 Q, MaxRecurse-1)) 2268 return V; 2269 break; 2270 } 2271 } 2272 } 2273 } 2274 } 2275 2276 // If a bit is known to be zero for A and known to be one for B, 2277 // then A and B cannot be equal. 2278 if (ICmpInst::isEquality(Pred)) { 2279 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 2280 uint32_t BitWidth = CI->getBitWidth(); 2281 APInt LHSKnownZero(BitWidth, 0); 2282 APInt LHSKnownOne(BitWidth, 0); 2283 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne); 2284 APInt RHSKnownZero(BitWidth, 0); 2285 APInt RHSKnownOne(BitWidth, 0); 2286 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne); 2287 if (((LHSKnownOne & RHSKnownZero) != 0) || 2288 ((LHSKnownZero & RHSKnownOne) != 0)) 2289 return (Pred == ICmpInst::ICMP_EQ) 2290 ? ConstantInt::getFalse(CI->getContext()) 2291 : ConstantInt::getTrue(CI->getContext()); 2292 } 2293 } 2294 2295 // Special logic for binary operators. 2296 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS); 2297 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS); 2298 if (MaxRecurse && (LBO || RBO)) { 2299 // Analyze the case when either LHS or RHS is an add instruction. 2300 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr; 2301 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null). 2302 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false; 2303 if (LBO && LBO->getOpcode() == Instruction::Add) { 2304 A = LBO->getOperand(0); B = LBO->getOperand(1); 2305 NoLHSWrapProblem = ICmpInst::isEquality(Pred) || 2306 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) || 2307 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap()); 2308 } 2309 if (RBO && RBO->getOpcode() == Instruction::Add) { 2310 C = RBO->getOperand(0); D = RBO->getOperand(1); 2311 NoRHSWrapProblem = ICmpInst::isEquality(Pred) || 2312 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) || 2313 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap()); 2314 } 2315 2316 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow. 2317 if ((A == RHS || B == RHS) && NoLHSWrapProblem) 2318 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A, 2319 Constant::getNullValue(RHS->getType()), 2320 Q, MaxRecurse-1)) 2321 return V; 2322 2323 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow. 2324 if ((C == LHS || D == LHS) && NoRHSWrapProblem) 2325 if (Value *V = SimplifyICmpInst(Pred, 2326 Constant::getNullValue(LHS->getType()), 2327 C == LHS ? D : C, Q, MaxRecurse-1)) 2328 return V; 2329 2330 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow. 2331 if (A && C && (A == C || A == D || B == C || B == D) && 2332 NoLHSWrapProblem && NoRHSWrapProblem) { 2333 // Determine Y and Z in the form icmp (X+Y), (X+Z). 2334 Value *Y, *Z; 2335 if (A == C) { 2336 // C + B == C + D -> B == D 2337 Y = B; 2338 Z = D; 2339 } else if (A == D) { 2340 // D + B == C + D -> B == C 2341 Y = B; 2342 Z = C; 2343 } else if (B == C) { 2344 // A + C == C + D -> A == D 2345 Y = A; 2346 Z = D; 2347 } else { 2348 assert(B == D); 2349 // A + D == C + D -> A == C 2350 Y = A; 2351 Z = C; 2352 } 2353 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1)) 2354 return V; 2355 } 2356 } 2357 2358 // 0 - (zext X) pred C 2359 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) { 2360 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) { 2361 if (RHSC->getValue().isStrictlyPositive()) { 2362 if (Pred == ICmpInst::ICMP_SLT) 2363 return ConstantInt::getTrue(RHSC->getContext()); 2364 if (Pred == ICmpInst::ICMP_SGE) 2365 return ConstantInt::getFalse(RHSC->getContext()); 2366 if (Pred == ICmpInst::ICMP_EQ) 2367 return ConstantInt::getFalse(RHSC->getContext()); 2368 if (Pred == ICmpInst::ICMP_NE) 2369 return ConstantInt::getTrue(RHSC->getContext()); 2370 } 2371 if (RHSC->getValue().isNonNegative()) { 2372 if (Pred == ICmpInst::ICMP_SLE) 2373 return ConstantInt::getTrue(RHSC->getContext()); 2374 if (Pred == ICmpInst::ICMP_SGT) 2375 return ConstantInt::getFalse(RHSC->getContext()); 2376 } 2377 } 2378 } 2379 2380 // icmp pred (urem X, Y), Y 2381 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) { 2382 bool KnownNonNegative, KnownNegative; 2383 switch (Pred) { 2384 default: 2385 break; 2386 case ICmpInst::ICMP_SGT: 2387 case ICmpInst::ICMP_SGE: 2388 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL); 2389 if (!KnownNonNegative) 2390 break; 2391 // fall-through 2392 case ICmpInst::ICMP_EQ: 2393 case ICmpInst::ICMP_UGT: 2394 case ICmpInst::ICMP_UGE: 2395 return getFalse(ITy); 2396 case ICmpInst::ICMP_SLT: 2397 case ICmpInst::ICMP_SLE: 2398 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL); 2399 if (!KnownNonNegative) 2400 break; 2401 // fall-through 2402 case ICmpInst::ICMP_NE: 2403 case ICmpInst::ICMP_ULT: 2404 case ICmpInst::ICMP_ULE: 2405 return getTrue(ITy); 2406 } 2407 } 2408 2409 // icmp pred X, (urem Y, X) 2410 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) { 2411 bool KnownNonNegative, KnownNegative; 2412 switch (Pred) { 2413 default: 2414 break; 2415 case ICmpInst::ICMP_SGT: 2416 case ICmpInst::ICMP_SGE: 2417 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL); 2418 if (!KnownNonNegative) 2419 break; 2420 // fall-through 2421 case ICmpInst::ICMP_NE: 2422 case ICmpInst::ICMP_UGT: 2423 case ICmpInst::ICMP_UGE: 2424 return getTrue(ITy); 2425 case ICmpInst::ICMP_SLT: 2426 case ICmpInst::ICMP_SLE: 2427 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL); 2428 if (!KnownNonNegative) 2429 break; 2430 // fall-through 2431 case ICmpInst::ICMP_EQ: 2432 case ICmpInst::ICMP_ULT: 2433 case ICmpInst::ICMP_ULE: 2434 return getFalse(ITy); 2435 } 2436 } 2437 2438 // x udiv y <=u x. 2439 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) { 2440 // icmp pred (X /u Y), X 2441 if (Pred == ICmpInst::ICMP_UGT) 2442 return getFalse(ITy); 2443 if (Pred == ICmpInst::ICMP_ULE) 2444 return getTrue(ITy); 2445 } 2446 2447 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() && 2448 LBO->getOperand(1) == RBO->getOperand(1)) { 2449 switch (LBO->getOpcode()) { 2450 default: break; 2451 case Instruction::UDiv: 2452 case Instruction::LShr: 2453 if (ICmpInst::isSigned(Pred)) 2454 break; 2455 // fall-through 2456 case Instruction::SDiv: 2457 case Instruction::AShr: 2458 if (!LBO->isExact() || !RBO->isExact()) 2459 break; 2460 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 2461 RBO->getOperand(0), Q, MaxRecurse-1)) 2462 return V; 2463 break; 2464 case Instruction::Shl: { 2465 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap(); 2466 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap(); 2467 if (!NUW && !NSW) 2468 break; 2469 if (!NSW && ICmpInst::isSigned(Pred)) 2470 break; 2471 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 2472 RBO->getOperand(0), Q, MaxRecurse-1)) 2473 return V; 2474 break; 2475 } 2476 } 2477 } 2478 2479 // Simplify comparisons involving max/min. 2480 Value *A, *B; 2481 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE; 2482 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B". 2483 2484 // Signed variants on "max(a,b)>=a -> true". 2485 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) { 2486 if (A != RHS) std::swap(A, B); // smax(A, B) pred A. 2487 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B". 2488 // We analyze this as smax(A, B) pred A. 2489 P = Pred; 2490 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) && 2491 (A == LHS || B == LHS)) { 2492 if (A != LHS) std::swap(A, B); // A pred smax(A, B). 2493 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B". 2494 // We analyze this as smax(A, B) swapped-pred A. 2495 P = CmpInst::getSwappedPredicate(Pred); 2496 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) && 2497 (A == RHS || B == RHS)) { 2498 if (A != RHS) std::swap(A, B); // smin(A, B) pred A. 2499 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B". 2500 // We analyze this as smax(-A, -B) swapped-pred -A. 2501 // Note that we do not need to actually form -A or -B thanks to EqP. 2502 P = CmpInst::getSwappedPredicate(Pred); 2503 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) && 2504 (A == LHS || B == LHS)) { 2505 if (A != LHS) std::swap(A, B); // A pred smin(A, B). 2506 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B". 2507 // We analyze this as smax(-A, -B) pred -A. 2508 // Note that we do not need to actually form -A or -B thanks to EqP. 2509 P = Pred; 2510 } 2511 if (P != CmpInst::BAD_ICMP_PREDICATE) { 2512 // Cases correspond to "max(A, B) p A". 2513 switch (P) { 2514 default: 2515 break; 2516 case CmpInst::ICMP_EQ: 2517 case CmpInst::ICMP_SLE: 2518 // Equivalent to "A EqP B". This may be the same as the condition tested 2519 // in the max/min; if so, we can just return that. 2520 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B)) 2521 return V; 2522 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B)) 2523 return V; 2524 // Otherwise, see if "A EqP B" simplifies. 2525 if (MaxRecurse) 2526 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1)) 2527 return V; 2528 break; 2529 case CmpInst::ICMP_NE: 2530 case CmpInst::ICMP_SGT: { 2531 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP); 2532 // Equivalent to "A InvEqP B". This may be the same as the condition 2533 // tested in the max/min; if so, we can just return that. 2534 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B)) 2535 return V; 2536 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B)) 2537 return V; 2538 // Otherwise, see if "A InvEqP B" simplifies. 2539 if (MaxRecurse) 2540 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1)) 2541 return V; 2542 break; 2543 } 2544 case CmpInst::ICMP_SGE: 2545 // Always true. 2546 return getTrue(ITy); 2547 case CmpInst::ICMP_SLT: 2548 // Always false. 2549 return getFalse(ITy); 2550 } 2551 } 2552 2553 // Unsigned variants on "max(a,b)>=a -> true". 2554 P = CmpInst::BAD_ICMP_PREDICATE; 2555 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) { 2556 if (A != RHS) std::swap(A, B); // umax(A, B) pred A. 2557 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B". 2558 // We analyze this as umax(A, B) pred A. 2559 P = Pred; 2560 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) && 2561 (A == LHS || B == LHS)) { 2562 if (A != LHS) std::swap(A, B); // A pred umax(A, B). 2563 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B". 2564 // We analyze this as umax(A, B) swapped-pred A. 2565 P = CmpInst::getSwappedPredicate(Pred); 2566 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) && 2567 (A == RHS || B == RHS)) { 2568 if (A != RHS) std::swap(A, B); // umin(A, B) pred A. 2569 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B". 2570 // We analyze this as umax(-A, -B) swapped-pred -A. 2571 // Note that we do not need to actually form -A or -B thanks to EqP. 2572 P = CmpInst::getSwappedPredicate(Pred); 2573 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) && 2574 (A == LHS || B == LHS)) { 2575 if (A != LHS) std::swap(A, B); // A pred umin(A, B). 2576 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B". 2577 // We analyze this as umax(-A, -B) pred -A. 2578 // Note that we do not need to actually form -A or -B thanks to EqP. 2579 P = Pred; 2580 } 2581 if (P != CmpInst::BAD_ICMP_PREDICATE) { 2582 // Cases correspond to "max(A, B) p A". 2583 switch (P) { 2584 default: 2585 break; 2586 case CmpInst::ICMP_EQ: 2587 case CmpInst::ICMP_ULE: 2588 // Equivalent to "A EqP B". This may be the same as the condition tested 2589 // in the max/min; if so, we can just return that. 2590 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B)) 2591 return V; 2592 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B)) 2593 return V; 2594 // Otherwise, see if "A EqP B" simplifies. 2595 if (MaxRecurse) 2596 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1)) 2597 return V; 2598 break; 2599 case CmpInst::ICMP_NE: 2600 case CmpInst::ICMP_UGT: { 2601 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP); 2602 // Equivalent to "A InvEqP B". This may be the same as the condition 2603 // tested in the max/min; if so, we can just return that. 2604 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B)) 2605 return V; 2606 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B)) 2607 return V; 2608 // Otherwise, see if "A InvEqP B" simplifies. 2609 if (MaxRecurse) 2610 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1)) 2611 return V; 2612 break; 2613 } 2614 case CmpInst::ICMP_UGE: 2615 // Always true. 2616 return getTrue(ITy); 2617 case CmpInst::ICMP_ULT: 2618 // Always false. 2619 return getFalse(ITy); 2620 } 2621 } 2622 2623 // Variants on "max(x,y) >= min(x,z)". 2624 Value *C, *D; 2625 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && 2626 match(RHS, m_SMin(m_Value(C), m_Value(D))) && 2627 (A == C || A == D || B == C || B == D)) { 2628 // max(x, ?) pred min(x, ?). 2629 if (Pred == CmpInst::ICMP_SGE) 2630 // Always true. 2631 return getTrue(ITy); 2632 if (Pred == CmpInst::ICMP_SLT) 2633 // Always false. 2634 return getFalse(ITy); 2635 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) && 2636 match(RHS, m_SMax(m_Value(C), m_Value(D))) && 2637 (A == C || A == D || B == C || B == D)) { 2638 // min(x, ?) pred max(x, ?). 2639 if (Pred == CmpInst::ICMP_SLE) 2640 // Always true. 2641 return getTrue(ITy); 2642 if (Pred == CmpInst::ICMP_SGT) 2643 // Always false. 2644 return getFalse(ITy); 2645 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && 2646 match(RHS, m_UMin(m_Value(C), m_Value(D))) && 2647 (A == C || A == D || B == C || B == D)) { 2648 // max(x, ?) pred min(x, ?). 2649 if (Pred == CmpInst::ICMP_UGE) 2650 // Always true. 2651 return getTrue(ITy); 2652 if (Pred == CmpInst::ICMP_ULT) 2653 // Always false. 2654 return getFalse(ITy); 2655 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) && 2656 match(RHS, m_UMax(m_Value(C), m_Value(D))) && 2657 (A == C || A == D || B == C || B == D)) { 2658 // min(x, ?) pred max(x, ?). 2659 if (Pred == CmpInst::ICMP_ULE) 2660 // Always true. 2661 return getTrue(ITy); 2662 if (Pred == CmpInst::ICMP_UGT) 2663 // Always false. 2664 return getFalse(ITy); 2665 } 2666 2667 // Simplify comparisons of related pointers using a powerful, recursive 2668 // GEP-walk when we have target data available.. 2669 if (LHS->getType()->isPointerTy()) 2670 if (Constant *C = computePointerICmp(Q.DL, Q.TLI, Pred, LHS, RHS)) 2671 return C; 2672 2673 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) { 2674 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) { 2675 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() && 2676 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() && 2677 (ICmpInst::isEquality(Pred) || 2678 (GLHS->isInBounds() && GRHS->isInBounds() && 2679 Pred == ICmpInst::getSignedPredicate(Pred)))) { 2680 // The bases are equal and the indices are constant. Build a constant 2681 // expression GEP with the same indices and a null base pointer to see 2682 // what constant folding can make out of it. 2683 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType()); 2684 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end()); 2685 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS); 2686 2687 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end()); 2688 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS); 2689 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS); 2690 } 2691 } 2692 } 2693 2694 // If the comparison is with the result of a select instruction, check whether 2695 // comparing with either branch of the select always yields the same value. 2696 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)) 2697 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse)) 2698 return V; 2699 2700 // If the comparison is with the result of a phi instruction, check whether 2701 // doing the compare with each incoming phi value yields a common result. 2702 if (isa<PHINode>(LHS) || isa<PHINode>(RHS)) 2703 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse)) 2704 return V; 2705 2706 return nullptr; 2707 } 2708 2709 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, 2710 const DataLayout *DL, 2711 const TargetLibraryInfo *TLI, 2712 const DominatorTree *DT) { 2713 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT), 2714 RecursionLimit); 2715 } 2716 2717 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can 2718 /// fold the result. If not, this returns null. 2719 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 2720 const Query &Q, unsigned MaxRecurse) { 2721 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate; 2722 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!"); 2723 2724 if (Constant *CLHS = dyn_cast<Constant>(LHS)) { 2725 if (Constant *CRHS = dyn_cast<Constant>(RHS)) 2726 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI); 2727 2728 // If we have a constant, make sure it is on the RHS. 2729 std::swap(LHS, RHS); 2730 Pred = CmpInst::getSwappedPredicate(Pred); 2731 } 2732 2733 // Fold trivial predicates. 2734 if (Pred == FCmpInst::FCMP_FALSE) 2735 return ConstantInt::get(GetCompareTy(LHS), 0); 2736 if (Pred == FCmpInst::FCMP_TRUE) 2737 return ConstantInt::get(GetCompareTy(LHS), 1); 2738 2739 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef 2740 return UndefValue::get(GetCompareTy(LHS)); 2741 2742 // fcmp x,x -> true/false. Not all compares are foldable. 2743 if (LHS == RHS) { 2744 if (CmpInst::isTrueWhenEqual(Pred)) 2745 return ConstantInt::get(GetCompareTy(LHS), 1); 2746 if (CmpInst::isFalseWhenEqual(Pred)) 2747 return ConstantInt::get(GetCompareTy(LHS), 0); 2748 } 2749 2750 // Handle fcmp with constant RHS 2751 if (Constant *RHSC = dyn_cast<Constant>(RHS)) { 2752 // If the constant is a nan, see if we can fold the comparison based on it. 2753 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) { 2754 if (CFP->getValueAPF().isNaN()) { 2755 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo" 2756 return ConstantInt::getFalse(CFP->getContext()); 2757 assert(FCmpInst::isUnordered(Pred) && 2758 "Comparison must be either ordered or unordered!"); 2759 // True if unordered. 2760 return ConstantInt::getTrue(CFP->getContext()); 2761 } 2762 // Check whether the constant is an infinity. 2763 if (CFP->getValueAPF().isInfinity()) { 2764 if (CFP->getValueAPF().isNegative()) { 2765 switch (Pred) { 2766 case FCmpInst::FCMP_OLT: 2767 // No value is ordered and less than negative infinity. 2768 return ConstantInt::getFalse(CFP->getContext()); 2769 case FCmpInst::FCMP_UGE: 2770 // All values are unordered with or at least negative infinity. 2771 return ConstantInt::getTrue(CFP->getContext()); 2772 default: 2773 break; 2774 } 2775 } else { 2776 switch (Pred) { 2777 case FCmpInst::FCMP_OGT: 2778 // No value is ordered and greater than infinity. 2779 return ConstantInt::getFalse(CFP->getContext()); 2780 case FCmpInst::FCMP_ULE: 2781 // All values are unordered with and at most infinity. 2782 return ConstantInt::getTrue(CFP->getContext()); 2783 default: 2784 break; 2785 } 2786 } 2787 } 2788 } 2789 } 2790 2791 // If the comparison is with the result of a select instruction, check whether 2792 // comparing with either branch of the select always yields the same value. 2793 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)) 2794 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse)) 2795 return V; 2796 2797 // If the comparison is with the result of a phi instruction, check whether 2798 // doing the compare with each incoming phi value yields a common result. 2799 if (isa<PHINode>(LHS) || isa<PHINode>(RHS)) 2800 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse)) 2801 return V; 2802 2803 return nullptr; 2804 } 2805 2806 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 2807 const DataLayout *DL, 2808 const TargetLibraryInfo *TLI, 2809 const DominatorTree *DT) { 2810 return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT), 2811 RecursionLimit); 2812 } 2813 2814 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold 2815 /// the result. If not, this returns null. 2816 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal, 2817 Value *FalseVal, const Query &Q, 2818 unsigned MaxRecurse) { 2819 // select true, X, Y -> X 2820 // select false, X, Y -> Y 2821 if (Constant *CB = dyn_cast<Constant>(CondVal)) { 2822 if (CB->isAllOnesValue()) 2823 return TrueVal; 2824 if (CB->isNullValue()) 2825 return FalseVal; 2826 } 2827 2828 // select C, X, X -> X 2829 if (TrueVal == FalseVal) 2830 return TrueVal; 2831 2832 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y 2833 if (isa<Constant>(TrueVal)) 2834 return TrueVal; 2835 return FalseVal; 2836 } 2837 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X 2838 return FalseVal; 2839 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X 2840 return TrueVal; 2841 2842 return nullptr; 2843 } 2844 2845 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal, 2846 const DataLayout *DL, 2847 const TargetLibraryInfo *TLI, 2848 const DominatorTree *DT) { 2849 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (DL, TLI, DT), 2850 RecursionLimit); 2851 } 2852 2853 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can 2854 /// fold the result. If not, this returns null. 2855 static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) { 2856 // The type of the GEP pointer operand. 2857 PointerType *PtrTy = cast<PointerType>(Ops[0]->getType()->getScalarType()); 2858 2859 // getelementptr P -> P. 2860 if (Ops.size() == 1) 2861 return Ops[0]; 2862 2863 if (isa<UndefValue>(Ops[0])) { 2864 // Compute the (pointer) type returned by the GEP instruction. 2865 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1)); 2866 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace()); 2867 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType())) 2868 GEPTy = VectorType::get(GEPTy, VT->getNumElements()); 2869 return UndefValue::get(GEPTy); 2870 } 2871 2872 if (Ops.size() == 2) { 2873 // getelementptr P, 0 -> P. 2874 if (match(Ops[1], m_Zero())) 2875 return Ops[0]; 2876 // getelementptr P, N -> P if P points to a type of zero size. 2877 if (Q.DL) { 2878 Type *Ty = PtrTy->getElementType(); 2879 if (Ty->isSized() && Q.DL->getTypeAllocSize(Ty) == 0) 2880 return Ops[0]; 2881 } 2882 } 2883 2884 // Check to see if this is constant foldable. 2885 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2886 if (!isa<Constant>(Ops[i])) 2887 return nullptr; 2888 2889 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1)); 2890 } 2891 2892 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *DL, 2893 const TargetLibraryInfo *TLI, 2894 const DominatorTree *DT) { 2895 return ::SimplifyGEPInst(Ops, Query (DL, TLI, DT), RecursionLimit); 2896 } 2897 2898 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we 2899 /// can fold the result. If not, this returns null. 2900 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val, 2901 ArrayRef<unsigned> Idxs, const Query &Q, 2902 unsigned) { 2903 if (Constant *CAgg = dyn_cast<Constant>(Agg)) 2904 if (Constant *CVal = dyn_cast<Constant>(Val)) 2905 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs); 2906 2907 // insertvalue x, undef, n -> x 2908 if (match(Val, m_Undef())) 2909 return Agg; 2910 2911 // insertvalue x, (extractvalue y, n), n 2912 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val)) 2913 if (EV->getAggregateOperand()->getType() == Agg->getType() && 2914 EV->getIndices() == Idxs) { 2915 // insertvalue undef, (extractvalue y, n), n -> y 2916 if (match(Agg, m_Undef())) 2917 return EV->getAggregateOperand(); 2918 2919 // insertvalue y, (extractvalue y, n), n -> y 2920 if (Agg == EV->getAggregateOperand()) 2921 return Agg; 2922 } 2923 2924 return nullptr; 2925 } 2926 2927 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val, 2928 ArrayRef<unsigned> Idxs, 2929 const DataLayout *DL, 2930 const TargetLibraryInfo *TLI, 2931 const DominatorTree *DT) { 2932 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (DL, TLI, DT), 2933 RecursionLimit); 2934 } 2935 2936 /// SimplifyPHINode - See if we can fold the given phi. If not, returns null. 2937 static Value *SimplifyPHINode(PHINode *PN, const Query &Q) { 2938 // If all of the PHI's incoming values are the same then replace the PHI node 2939 // with the common value. 2940 Value *CommonValue = nullptr; 2941 bool HasUndefInput = false; 2942 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 2943 Value *Incoming = PN->getIncomingValue(i); 2944 // If the incoming value is the phi node itself, it can safely be skipped. 2945 if (Incoming == PN) continue; 2946 if (isa<UndefValue>(Incoming)) { 2947 // Remember that we saw an undef value, but otherwise ignore them. 2948 HasUndefInput = true; 2949 continue; 2950 } 2951 if (CommonValue && Incoming != CommonValue) 2952 return nullptr; // Not the same, bail out. 2953 CommonValue = Incoming; 2954 } 2955 2956 // If CommonValue is null then all of the incoming values were either undef or 2957 // equal to the phi node itself. 2958 if (!CommonValue) 2959 return UndefValue::get(PN->getType()); 2960 2961 // If we have a PHI node like phi(X, undef, X), where X is defined by some 2962 // instruction, we cannot return X as the result of the PHI node unless it 2963 // dominates the PHI block. 2964 if (HasUndefInput) 2965 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr; 2966 2967 return CommonValue; 2968 } 2969 2970 static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) { 2971 if (Constant *C = dyn_cast<Constant>(Op)) 2972 return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.DL, Q.TLI); 2973 2974 return nullptr; 2975 } 2976 2977 Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *DL, 2978 const TargetLibraryInfo *TLI, 2979 const DominatorTree *DT) { 2980 return ::SimplifyTruncInst(Op, Ty, Query (DL, TLI, DT), RecursionLimit); 2981 } 2982 2983 //=== Helper functions for higher up the class hierarchy. 2984 2985 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can 2986 /// fold the result. If not, this returns null. 2987 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, 2988 const Query &Q, unsigned MaxRecurse) { 2989 switch (Opcode) { 2990 case Instruction::Add: 2991 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false, 2992 Q, MaxRecurse); 2993 case Instruction::FAdd: 2994 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 2995 2996 case Instruction::Sub: 2997 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false, 2998 Q, MaxRecurse); 2999 case Instruction::FSub: 3000 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 3001 3002 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse); 3003 case Instruction::FMul: 3004 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse); 3005 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse); 3006 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse); 3007 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse); 3008 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse); 3009 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse); 3010 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse); 3011 case Instruction::Shl: 3012 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false, 3013 Q, MaxRecurse); 3014 case Instruction::LShr: 3015 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse); 3016 case Instruction::AShr: 3017 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse); 3018 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse); 3019 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse); 3020 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse); 3021 default: 3022 if (Constant *CLHS = dyn_cast<Constant>(LHS)) 3023 if (Constant *CRHS = dyn_cast<Constant>(RHS)) { 3024 Constant *COps[] = {CLHS, CRHS}; 3025 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.DL, 3026 Q.TLI); 3027 } 3028 3029 // If the operation is associative, try some generic simplifications. 3030 if (Instruction::isAssociative(Opcode)) 3031 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse)) 3032 return V; 3033 3034 // If the operation is with the result of a select instruction check whether 3035 // operating on either branch of the select always yields the same value. 3036 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)) 3037 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse)) 3038 return V; 3039 3040 // If the operation is with the result of a phi instruction, check whether 3041 // operating on all incoming values of the phi always yields the same value. 3042 if (isa<PHINode>(LHS) || isa<PHINode>(RHS)) 3043 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse)) 3044 return V; 3045 3046 return nullptr; 3047 } 3048 } 3049 3050 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, 3051 const DataLayout *DL, const TargetLibraryInfo *TLI, 3052 const DominatorTree *DT) { 3053 return ::SimplifyBinOp(Opcode, LHS, RHS, Query (DL, TLI, DT), RecursionLimit); 3054 } 3055 3056 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can 3057 /// fold the result. 3058 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 3059 const Query &Q, unsigned MaxRecurse) { 3060 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate)) 3061 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse); 3062 return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse); 3063 } 3064 3065 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 3066 const DataLayout *DL, const TargetLibraryInfo *TLI, 3067 const DominatorTree *DT) { 3068 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT), 3069 RecursionLimit); 3070 } 3071 3072 static bool IsIdempotent(Intrinsic::ID ID) { 3073 switch (ID) { 3074 default: return false; 3075 3076 // Unary idempotent: f(f(x)) = f(x) 3077 case Intrinsic::fabs: 3078 case Intrinsic::floor: 3079 case Intrinsic::ceil: 3080 case Intrinsic::trunc: 3081 case Intrinsic::rint: 3082 case Intrinsic::nearbyint: 3083 case Intrinsic::round: 3084 return true; 3085 } 3086 } 3087 3088 template <typename IterTy> 3089 static Value *SimplifyIntrinsic(Intrinsic::ID IID, IterTy ArgBegin, IterTy ArgEnd, 3090 const Query &Q, unsigned MaxRecurse) { 3091 // Perform idempotent optimizations 3092 if (!IsIdempotent(IID)) 3093 return nullptr; 3094 3095 // Unary Ops 3096 if (std::distance(ArgBegin, ArgEnd) == 1) 3097 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin)) 3098 if (II->getIntrinsicID() == IID) 3099 return II; 3100 3101 return nullptr; 3102 } 3103 3104 template <typename IterTy> 3105 static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd, 3106 const Query &Q, unsigned MaxRecurse) { 3107 Type *Ty = V->getType(); 3108 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) 3109 Ty = PTy->getElementType(); 3110 FunctionType *FTy = cast<FunctionType>(Ty); 3111 3112 // call undef -> undef 3113 if (isa<UndefValue>(V)) 3114 return UndefValue::get(FTy->getReturnType()); 3115 3116 Function *F = dyn_cast<Function>(V); 3117 if (!F) 3118 return nullptr; 3119 3120 if (unsigned IID = F->getIntrinsicID()) 3121 if (Value *Ret = 3122 SimplifyIntrinsic((Intrinsic::ID) IID, ArgBegin, ArgEnd, Q, MaxRecurse)) 3123 return Ret; 3124 3125 if (!canConstantFoldCallTo(F)) 3126 return nullptr; 3127 3128 SmallVector<Constant *, 4> ConstantArgs; 3129 ConstantArgs.reserve(ArgEnd - ArgBegin); 3130 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) { 3131 Constant *C = dyn_cast<Constant>(*I); 3132 if (!C) 3133 return nullptr; 3134 ConstantArgs.push_back(C); 3135 } 3136 3137 return ConstantFoldCall(F, ConstantArgs, Q.TLI); 3138 } 3139 3140 Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin, 3141 User::op_iterator ArgEnd, const DataLayout *DL, 3142 const TargetLibraryInfo *TLI, 3143 const DominatorTree *DT) { 3144 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT), 3145 RecursionLimit); 3146 } 3147 3148 Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args, 3149 const DataLayout *DL, const TargetLibraryInfo *TLI, 3150 const DominatorTree *DT) { 3151 return ::SimplifyCall(V, Args.begin(), Args.end(), Query(DL, TLI, DT), 3152 RecursionLimit); 3153 } 3154 3155 /// SimplifyInstruction - See if we can compute a simplified version of this 3156 /// instruction. If not, this returns null. 3157 Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *DL, 3158 const TargetLibraryInfo *TLI, 3159 const DominatorTree *DT) { 3160 Value *Result; 3161 3162 switch (I->getOpcode()) { 3163 default: 3164 Result = ConstantFoldInstruction(I, DL, TLI); 3165 break; 3166 case Instruction::FAdd: 3167 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1), 3168 I->getFastMathFlags(), DL, TLI, DT); 3169 break; 3170 case Instruction::Add: 3171 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1), 3172 cast<BinaryOperator>(I)->hasNoSignedWrap(), 3173 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), 3174 DL, TLI, DT); 3175 break; 3176 case Instruction::FSub: 3177 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1), 3178 I->getFastMathFlags(), DL, TLI, DT); 3179 break; 3180 case Instruction::Sub: 3181 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1), 3182 cast<BinaryOperator>(I)->hasNoSignedWrap(), 3183 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), 3184 DL, TLI, DT); 3185 break; 3186 case Instruction::FMul: 3187 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1), 3188 I->getFastMathFlags(), DL, TLI, DT); 3189 break; 3190 case Instruction::Mul: 3191 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3192 break; 3193 case Instruction::SDiv: 3194 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3195 break; 3196 case Instruction::UDiv: 3197 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3198 break; 3199 case Instruction::FDiv: 3200 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3201 break; 3202 case Instruction::SRem: 3203 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3204 break; 3205 case Instruction::URem: 3206 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3207 break; 3208 case Instruction::FRem: 3209 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3210 break; 3211 case Instruction::Shl: 3212 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1), 3213 cast<BinaryOperator>(I)->hasNoSignedWrap(), 3214 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), 3215 DL, TLI, DT); 3216 break; 3217 case Instruction::LShr: 3218 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1), 3219 cast<BinaryOperator>(I)->isExact(), 3220 DL, TLI, DT); 3221 break; 3222 case Instruction::AShr: 3223 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1), 3224 cast<BinaryOperator>(I)->isExact(), 3225 DL, TLI, DT); 3226 break; 3227 case Instruction::And: 3228 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3229 break; 3230 case Instruction::Or: 3231 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3232 break; 3233 case Instruction::Xor: 3234 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3235 break; 3236 case Instruction::ICmp: 3237 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), 3238 I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3239 break; 3240 case Instruction::FCmp: 3241 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), 3242 I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3243 break; 3244 case Instruction::Select: 3245 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1), 3246 I->getOperand(2), DL, TLI, DT); 3247 break; 3248 case Instruction::GetElementPtr: { 3249 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end()); 3250 Result = SimplifyGEPInst(Ops, DL, TLI, DT); 3251 break; 3252 } 3253 case Instruction::InsertValue: { 3254 InsertValueInst *IV = cast<InsertValueInst>(I); 3255 Result = SimplifyInsertValueInst(IV->getAggregateOperand(), 3256 IV->getInsertedValueOperand(), 3257 IV->getIndices(), DL, TLI, DT); 3258 break; 3259 } 3260 case Instruction::PHI: 3261 Result = SimplifyPHINode(cast<PHINode>(I), Query (DL, TLI, DT)); 3262 break; 3263 case Instruction::Call: { 3264 CallSite CS(cast<CallInst>(I)); 3265 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), 3266 DL, TLI, DT); 3267 break; 3268 } 3269 case Instruction::Trunc: 3270 Result = SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT); 3271 break; 3272 } 3273 3274 /// If called on unreachable code, the above logic may report that the 3275 /// instruction simplified to itself. Make life easier for users by 3276 /// detecting that case here, returning a safe value instead. 3277 return Result == I ? UndefValue::get(I->getType()) : Result; 3278 } 3279 3280 /// \brief Implementation of recursive simplification through an instructions 3281 /// uses. 3282 /// 3283 /// This is the common implementation of the recursive simplification routines. 3284 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to 3285 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of 3286 /// instructions to process and attempt to simplify it using 3287 /// InstructionSimplify. 3288 /// 3289 /// This routine returns 'true' only when *it* simplifies something. The passed 3290 /// in simplified value does not count toward this. 3291 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV, 3292 const DataLayout *DL, 3293 const TargetLibraryInfo *TLI, 3294 const DominatorTree *DT) { 3295 bool Simplified = false; 3296 SmallSetVector<Instruction *, 8> Worklist; 3297 3298 // If we have an explicit value to collapse to, do that round of the 3299 // simplification loop by hand initially. 3300 if (SimpleV) { 3301 for (User *U : I->users()) 3302 if (U != I) 3303 Worklist.insert(cast<Instruction>(U)); 3304 3305 // Replace the instruction with its simplified value. 3306 I->replaceAllUsesWith(SimpleV); 3307 3308 // Gracefully handle edge cases where the instruction is not wired into any 3309 // parent block. 3310 if (I->getParent()) 3311 I->eraseFromParent(); 3312 } else { 3313 Worklist.insert(I); 3314 } 3315 3316 // Note that we must test the size on each iteration, the worklist can grow. 3317 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) { 3318 I = Worklist[Idx]; 3319 3320 // See if this instruction simplifies. 3321 SimpleV = SimplifyInstruction(I, DL, TLI, DT); 3322 if (!SimpleV) 3323 continue; 3324 3325 Simplified = true; 3326 3327 // Stash away all the uses of the old instruction so we can check them for 3328 // recursive simplifications after a RAUW. This is cheaper than checking all 3329 // uses of To on the recursive step in most cases. 3330 for (User *U : I->users()) 3331 Worklist.insert(cast<Instruction>(U)); 3332 3333 // Replace the instruction with its simplified value. 3334 I->replaceAllUsesWith(SimpleV); 3335 3336 // Gracefully handle edge cases where the instruction is not wired into any 3337 // parent block. 3338 if (I->getParent()) 3339 I->eraseFromParent(); 3340 } 3341 return Simplified; 3342 } 3343 3344 bool llvm::recursivelySimplifyInstruction(Instruction *I, 3345 const DataLayout *DL, 3346 const TargetLibraryInfo *TLI, 3347 const DominatorTree *DT) { 3348 return replaceAndRecursivelySimplifyImpl(I, nullptr, DL, TLI, DT); 3349 } 3350 3351 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV, 3352 const DataLayout *DL, 3353 const TargetLibraryInfo *TLI, 3354 const DominatorTree *DT) { 3355 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!"); 3356 assert(SimpleV && "Must provide a simplified value."); 3357 return replaceAndRecursivelySimplifyImpl(I, SimpleV, DL, TLI, DT); 3358 } 3359