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