LLVM  mainline
InstructionSimplify.cpp
Go to the documentation of this file.
00001 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements routines for folding instructions into simpler forms
00011 // that do not require creating new instructions.  This does constant folding
00012 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
00013 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
00014 // ("and i32 %x, %x" -> "%x").  All operands are assumed to have already been
00015 // simplified: This is usually true and assuming it simplifies the logic (if
00016 // they have not been simplified then results are correct but maybe suboptimal).
00017 //
00018 //===----------------------------------------------------------------------===//
00019 
00020 #include "llvm/Analysis/InstructionSimplify.h"
00021 #include "llvm/ADT/SetVector.h"
00022 #include "llvm/ADT/Statistic.h"
00023 #include "llvm/Analysis/AliasAnalysis.h"
00024 #include "llvm/Analysis/ConstantFolding.h"
00025 #include "llvm/Analysis/MemoryBuiltins.h"
00026 #include "llvm/Analysis/ValueTracking.h"
00027 #include "llvm/IR/ConstantRange.h"
00028 #include "llvm/IR/DataLayout.h"
00029 #include "llvm/IR/Dominators.h"
00030 #include "llvm/IR/GetElementPtrTypeIterator.h"
00031 #include "llvm/IR/GlobalAlias.h"
00032 #include "llvm/IR/Operator.h"
00033 #include "llvm/IR/PatternMatch.h"
00034 #include "llvm/IR/ValueHandle.h"
00035 #include <algorithm>
00036 using namespace llvm;
00037 using namespace llvm::PatternMatch;
00038 
00039 #define DEBUG_TYPE "instsimplify"
00040 
00041 enum { RecursionLimit = 3 };
00042 
00043 STATISTIC(NumExpand,  "Number of expansions");
00044 STATISTIC(NumReassoc, "Number of reassociations");
00045 
00046 namespace {
00047 struct Query {
00048   const DataLayout &DL;
00049   const TargetLibraryInfo *TLI;
00050   const DominatorTree *DT;
00051   AssumptionCache *AC;
00052   const Instruction *CxtI;
00053 
00054   Query(const DataLayout &DL, const TargetLibraryInfo *tli,
00055         const DominatorTree *dt, AssumptionCache *ac = nullptr,
00056         const Instruction *cxti = nullptr)
00057       : DL(DL), TLI(tli), DT(dt), AC(ac), CxtI(cxti) {}
00058 };
00059 } // end anonymous namespace
00060 
00061 static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
00062 static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
00063                             unsigned);
00064 static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &,
00065                               const Query &, unsigned);
00066 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
00067                               unsigned);
00068 static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
00069 static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
00070 static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
00071 
00072 /// getFalse - For a boolean type, or a vector of boolean type, return false, or
00073 /// a vector with every element false, as appropriate for the type.
00074 static Constant *getFalse(Type *Ty) {
00075   assert(Ty->getScalarType()->isIntegerTy(1) &&
00076          "Expected i1 type or a vector of i1!");
00077   return Constant::getNullValue(Ty);
00078 }
00079 
00080 /// getTrue - For a boolean type, or a vector of boolean type, return true, or
00081 /// a vector with every element true, as appropriate for the type.
00082 static Constant *getTrue(Type *Ty) {
00083   assert(Ty->getScalarType()->isIntegerTy(1) &&
00084          "Expected i1 type or a vector of i1!");
00085   return Constant::getAllOnesValue(Ty);
00086 }
00087 
00088 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
00089 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
00090                           Value *RHS) {
00091   CmpInst *Cmp = dyn_cast<CmpInst>(V);
00092   if (!Cmp)
00093     return false;
00094   CmpInst::Predicate CPred = Cmp->getPredicate();
00095   Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
00096   if (CPred == Pred && CLHS == LHS && CRHS == RHS)
00097     return true;
00098   return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
00099     CRHS == LHS;
00100 }
00101 
00102 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
00103 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
00104   Instruction *I = dyn_cast<Instruction>(V);
00105   if (!I)
00106     // Arguments and constants dominate all instructions.
00107     return true;
00108 
00109   // If we are processing instructions (and/or basic blocks) that have not been
00110   // fully added to a function, the parent nodes may still be null. Simply
00111   // return the conservative answer in these cases.
00112   if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
00113     return false;
00114 
00115   // If we have a DominatorTree then do a precise test.
00116   if (DT) {
00117     if (!DT->isReachableFromEntry(P->getParent()))
00118       return true;
00119     if (!DT->isReachableFromEntry(I->getParent()))
00120       return false;
00121     return DT->dominates(I, P);
00122   }
00123 
00124   // Otherwise, if the instruction is in the entry block, and is not an invoke,
00125   // then it obviously dominates all phi nodes.
00126   if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
00127       !isa<InvokeInst>(I))
00128     return true;
00129 
00130   return false;
00131 }
00132 
00133 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
00134 /// it into "(A op B) op' (A op C)".  Here "op" is given by Opcode and "op'" is
00135 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
00136 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
00137 /// Returns the simplified value, or null if no simplification was performed.
00138 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
00139                           unsigned OpcToExpand, const Query &Q,
00140                           unsigned MaxRecurse) {
00141   Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
00142   // Recursion is always used, so bail out at once if we already hit the limit.
00143   if (!MaxRecurse--)
00144     return nullptr;
00145 
00146   // Check whether the expression has the form "(A op' B) op C".
00147   if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
00148     if (Op0->getOpcode() == OpcodeToExpand) {
00149       // It does!  Try turning it into "(A op C) op' (B op C)".
00150       Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
00151       // Do "A op C" and "B op C" both simplify?
00152       if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
00153         if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
00154           // They do! Return "L op' R" if it simplifies or is already available.
00155           // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
00156           if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
00157                                      && L == B && R == A)) {
00158             ++NumExpand;
00159             return LHS;
00160           }
00161           // Otherwise return "L op' R" if it simplifies.
00162           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
00163             ++NumExpand;
00164             return V;
00165           }
00166         }
00167     }
00168 
00169   // Check whether the expression has the form "A op (B op' C)".
00170   if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
00171     if (Op1->getOpcode() == OpcodeToExpand) {
00172       // It does!  Try turning it into "(A op B) op' (A op C)".
00173       Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
00174       // Do "A op B" and "A op C" both simplify?
00175       if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
00176         if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
00177           // They do! Return "L op' R" if it simplifies or is already available.
00178           // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
00179           if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
00180                                      && L == C && R == B)) {
00181             ++NumExpand;
00182             return RHS;
00183           }
00184           // Otherwise return "L op' R" if it simplifies.
00185           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
00186             ++NumExpand;
00187             return V;
00188           }
00189         }
00190     }
00191 
00192   return nullptr;
00193 }
00194 
00195 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
00196 /// operations.  Returns the simpler value, or null if none was found.
00197 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
00198                                        const Query &Q, unsigned MaxRecurse) {
00199   Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
00200   assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
00201 
00202   // Recursion is always used, so bail out at once if we already hit the limit.
00203   if (!MaxRecurse--)
00204     return nullptr;
00205 
00206   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
00207   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
00208 
00209   // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
00210   if (Op0 && Op0->getOpcode() == Opcode) {
00211     Value *A = Op0->getOperand(0);
00212     Value *B = Op0->getOperand(1);
00213     Value *C = RHS;
00214 
00215     // Does "B op C" simplify?
00216     if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
00217       // It does!  Return "A op V" if it simplifies or is already available.
00218       // If V equals B then "A op V" is just the LHS.
00219       if (V == B) return LHS;
00220       // Otherwise return "A op V" if it simplifies.
00221       if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
00222         ++NumReassoc;
00223         return W;
00224       }
00225     }
00226   }
00227 
00228   // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
00229   if (Op1 && Op1->getOpcode() == Opcode) {
00230     Value *A = LHS;
00231     Value *B = Op1->getOperand(0);
00232     Value *C = Op1->getOperand(1);
00233 
00234     // Does "A op B" simplify?
00235     if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
00236       // It does!  Return "V op C" if it simplifies or is already available.
00237       // If V equals B then "V op C" is just the RHS.
00238       if (V == B) return RHS;
00239       // Otherwise return "V op C" if it simplifies.
00240       if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
00241         ++NumReassoc;
00242         return W;
00243       }
00244     }
00245   }
00246 
00247   // The remaining transforms require commutativity as well as associativity.
00248   if (!Instruction::isCommutative(Opcode))
00249     return nullptr;
00250 
00251   // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
00252   if (Op0 && Op0->getOpcode() == Opcode) {
00253     Value *A = Op0->getOperand(0);
00254     Value *B = Op0->getOperand(1);
00255     Value *C = RHS;
00256 
00257     // Does "C op A" simplify?
00258     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
00259       // It does!  Return "V op B" if it simplifies or is already available.
00260       // If V equals A then "V op B" is just the LHS.
00261       if (V == A) return LHS;
00262       // Otherwise return "V op B" if it simplifies.
00263       if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
00264         ++NumReassoc;
00265         return W;
00266       }
00267     }
00268   }
00269 
00270   // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
00271   if (Op1 && Op1->getOpcode() == Opcode) {
00272     Value *A = LHS;
00273     Value *B = Op1->getOperand(0);
00274     Value *C = Op1->getOperand(1);
00275 
00276     // Does "C op A" simplify?
00277     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
00278       // It does!  Return "B op V" if it simplifies or is already available.
00279       // If V equals C then "B op V" is just the RHS.
00280       if (V == C) return RHS;
00281       // Otherwise return "B op V" if it simplifies.
00282       if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
00283         ++NumReassoc;
00284         return W;
00285       }
00286     }
00287   }
00288 
00289   return nullptr;
00290 }
00291 
00292 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
00293 /// instruction as an operand, try to simplify the binop by seeing whether
00294 /// evaluating it on both branches of the select results in the same value.
00295 /// Returns the common value if so, otherwise returns null.
00296 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
00297                                     const Query &Q, unsigned MaxRecurse) {
00298   // Recursion is always used, so bail out at once if we already hit the limit.
00299   if (!MaxRecurse--)
00300     return nullptr;
00301 
00302   SelectInst *SI;
00303   if (isa<SelectInst>(LHS)) {
00304     SI = cast<SelectInst>(LHS);
00305   } else {
00306     assert(isa<SelectInst>(RHS) && "No select instruction operand!");
00307     SI = cast<SelectInst>(RHS);
00308   }
00309 
00310   // Evaluate the BinOp on the true and false branches of the select.
00311   Value *TV;
00312   Value *FV;
00313   if (SI == LHS) {
00314     TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
00315     FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
00316   } else {
00317     TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
00318     FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
00319   }
00320 
00321   // If they simplified to the same value, then return the common value.
00322   // If they both failed to simplify then return null.
00323   if (TV == FV)
00324     return TV;
00325 
00326   // If one branch simplified to undef, return the other one.
00327   if (TV && isa<UndefValue>(TV))
00328     return FV;
00329   if (FV && isa<UndefValue>(FV))
00330     return TV;
00331 
00332   // If applying the operation did not change the true and false select values,
00333   // then the result of the binop is the select itself.
00334   if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
00335     return SI;
00336 
00337   // If one branch simplified and the other did not, and the simplified
00338   // value is equal to the unsimplified one, return the simplified value.
00339   // For example, select (cond, X, X & Z) & Z -> X & Z.
00340   if ((FV && !TV) || (TV && !FV)) {
00341     // Check that the simplified value has the form "X op Y" where "op" is the
00342     // same as the original operation.
00343     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
00344     if (Simplified && Simplified->getOpcode() == Opcode) {
00345       // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
00346       // We already know that "op" is the same as for the simplified value.  See
00347       // if the operands match too.  If so, return the simplified value.
00348       Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
00349       Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
00350       Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
00351       if (Simplified->getOperand(0) == UnsimplifiedLHS &&
00352           Simplified->getOperand(1) == UnsimplifiedRHS)
00353         return Simplified;
00354       if (Simplified->isCommutative() &&
00355           Simplified->getOperand(1) == UnsimplifiedLHS &&
00356           Simplified->getOperand(0) == UnsimplifiedRHS)
00357         return Simplified;
00358     }
00359   }
00360 
00361   return nullptr;
00362 }
00363 
00364 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
00365 /// try to simplify the comparison by seeing whether both branches of the select
00366 /// result in the same value.  Returns the common value if so, otherwise returns
00367 /// null.
00368 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
00369                                   Value *RHS, const Query &Q,
00370                                   unsigned MaxRecurse) {
00371   // Recursion is always used, so bail out at once if we already hit the limit.
00372   if (!MaxRecurse--)
00373     return nullptr;
00374 
00375   // Make sure the select is on the LHS.
00376   if (!isa<SelectInst>(LHS)) {
00377     std::swap(LHS, RHS);
00378     Pred = CmpInst::getSwappedPredicate(Pred);
00379   }
00380   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
00381   SelectInst *SI = cast<SelectInst>(LHS);
00382   Value *Cond = SI->getCondition();
00383   Value *TV = SI->getTrueValue();
00384   Value *FV = SI->getFalseValue();
00385 
00386   // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
00387   // Does "cmp TV, RHS" simplify?
00388   Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
00389   if (TCmp == Cond) {
00390     // It not only simplified, it simplified to the select condition.  Replace
00391     // it with 'true'.
00392     TCmp = getTrue(Cond->getType());
00393   } else if (!TCmp) {
00394     // It didn't simplify.  However if "cmp TV, RHS" is equal to the select
00395     // condition then we can replace it with 'true'.  Otherwise give up.
00396     if (!isSameCompare(Cond, Pred, TV, RHS))
00397       return nullptr;
00398     TCmp = getTrue(Cond->getType());
00399   }
00400 
00401   // Does "cmp FV, RHS" simplify?
00402   Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
00403   if (FCmp == Cond) {
00404     // It not only simplified, it simplified to the select condition.  Replace
00405     // it with 'false'.
00406     FCmp = getFalse(Cond->getType());
00407   } else if (!FCmp) {
00408     // It didn't simplify.  However if "cmp FV, RHS" is equal to the select
00409     // condition then we can replace it with 'false'.  Otherwise give up.
00410     if (!isSameCompare(Cond, Pred, FV, RHS))
00411       return nullptr;
00412     FCmp = getFalse(Cond->getType());
00413   }
00414 
00415   // If both sides simplified to the same value, then use it as the result of
00416   // the original comparison.
00417   if (TCmp == FCmp)
00418     return TCmp;
00419 
00420   // The remaining cases only make sense if the select condition has the same
00421   // type as the result of the comparison, so bail out if this is not so.
00422   if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
00423     return nullptr;
00424   // If the false value simplified to false, then the result of the compare
00425   // is equal to "Cond && TCmp".  This also catches the case when the false
00426   // value simplified to false and the true value to true, returning "Cond".
00427   if (match(FCmp, m_Zero()))
00428     if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
00429       return V;
00430   // If the true value simplified to true, then the result of the compare
00431   // is equal to "Cond || FCmp".
00432   if (match(TCmp, m_One()))
00433     if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
00434       return V;
00435   // Finally, if the false value simplified to true and the true value to
00436   // false, then the result of the compare is equal to "!Cond".
00437   if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
00438     if (Value *V =
00439         SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
00440                         Q, MaxRecurse))
00441       return V;
00442 
00443   return nullptr;
00444 }
00445 
00446 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
00447 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
00448 /// it on the incoming phi values yields the same result for every value.  If so
00449 /// returns the common value, otherwise returns null.
00450 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
00451                                  const Query &Q, unsigned MaxRecurse) {
00452   // Recursion is always used, so bail out at once if we already hit the limit.
00453   if (!MaxRecurse--)
00454     return nullptr;
00455 
00456   PHINode *PI;
00457   if (isa<PHINode>(LHS)) {
00458     PI = cast<PHINode>(LHS);
00459     // Bail out if RHS and the phi may be mutually interdependent due to a loop.
00460     if (!ValueDominatesPHI(RHS, PI, Q.DT))
00461       return nullptr;
00462   } else {
00463     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
00464     PI = cast<PHINode>(RHS);
00465     // Bail out if LHS and the phi may be mutually interdependent due to a loop.
00466     if (!ValueDominatesPHI(LHS, PI, Q.DT))
00467       return nullptr;
00468   }
00469 
00470   // Evaluate the BinOp on the incoming phi values.
00471   Value *CommonValue = nullptr;
00472   for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
00473     Value *Incoming = PI->getIncomingValue(i);
00474     // If the incoming value is the phi node itself, it can safely be skipped.
00475     if (Incoming == PI) continue;
00476     Value *V = PI == LHS ?
00477       SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
00478       SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
00479     // If the operation failed to simplify, or simplified to a different value
00480     // to previously, then give up.
00481     if (!V || (CommonValue && V != CommonValue))
00482       return nullptr;
00483     CommonValue = V;
00484   }
00485 
00486   return CommonValue;
00487 }
00488 
00489 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
00490 /// try to simplify the comparison by seeing whether comparing with all of the
00491 /// incoming phi values yields the same result every time.  If so returns the
00492 /// common result, otherwise returns null.
00493 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
00494                                const Query &Q, unsigned MaxRecurse) {
00495   // Recursion is always used, so bail out at once if we already hit the limit.
00496   if (!MaxRecurse--)
00497     return nullptr;
00498 
00499   // Make sure the phi is on the LHS.
00500   if (!isa<PHINode>(LHS)) {
00501     std::swap(LHS, RHS);
00502     Pred = CmpInst::getSwappedPredicate(Pred);
00503   }
00504   assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
00505   PHINode *PI = cast<PHINode>(LHS);
00506 
00507   // Bail out if RHS and the phi may be mutually interdependent due to a loop.
00508   if (!ValueDominatesPHI(RHS, PI, Q.DT))
00509     return nullptr;
00510 
00511   // Evaluate the BinOp on the incoming phi values.
00512   Value *CommonValue = nullptr;
00513   for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
00514     Value *Incoming = PI->getIncomingValue(i);
00515     // If the incoming value is the phi node itself, it can safely be skipped.
00516     if (Incoming == PI) continue;
00517     Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
00518     // If the operation failed to simplify, or simplified to a different value
00519     // to previously, then give up.
00520     if (!V || (CommonValue && V != CommonValue))
00521       return nullptr;
00522     CommonValue = V;
00523   }
00524 
00525   return CommonValue;
00526 }
00527 
00528 /// SimplifyAddInst - Given operands for an Add, see if we can
00529 /// fold the result.  If not, this returns null.
00530 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
00531                               const Query &Q, unsigned MaxRecurse) {
00532   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
00533     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
00534       Constant *Ops[] = { CLHS, CRHS };
00535       return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops,
00536                                       Q.DL, Q.TLI);
00537     }
00538 
00539     // Canonicalize the constant to the RHS.
00540     std::swap(Op0, Op1);
00541   }
00542 
00543   // X + undef -> undef
00544   if (match(Op1, m_Undef()))
00545     return Op1;
00546 
00547   // X + 0 -> X
00548   if (match(Op1, m_Zero()))
00549     return Op0;
00550 
00551   // X + (Y - X) -> Y
00552   // (Y - X) + X -> Y
00553   // Eg: X + -X -> 0
00554   Value *Y = nullptr;
00555   if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
00556       match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
00557     return Y;
00558 
00559   // X + ~X -> -1   since   ~X = -X-1
00560   if (match(Op0, m_Not(m_Specific(Op1))) ||
00561       match(Op1, m_Not(m_Specific(Op0))))
00562     return Constant::getAllOnesValue(Op0->getType());
00563 
00564   /// i1 add -> xor.
00565   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
00566     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
00567       return V;
00568 
00569   // Try some generic simplifications for associative operations.
00570   if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
00571                                           MaxRecurse))
00572     return V;
00573 
00574   // Threading Add over selects and phi nodes is pointless, so don't bother.
00575   // Threading over the select in "A + select(cond, B, C)" means evaluating
00576   // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
00577   // only if B and C are equal.  If B and C are equal then (since we assume
00578   // that operands have already been simplified) "select(cond, B, C)" should
00579   // have been simplified to the common value of B and C already.  Analysing
00580   // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
00581   // for threading over phi nodes.
00582 
00583   return nullptr;
00584 }
00585 
00586 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
00587                              const DataLayout &DL, const TargetLibraryInfo *TLI,
00588                              const DominatorTree *DT, AssumptionCache *AC,
00589                              const Instruction *CxtI) {
00590   return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
00591                            RecursionLimit);
00592 }
00593 
00594 /// \brief Compute the base pointer and cumulative constant offsets for V.
00595 ///
00596 /// This strips all constant offsets off of V, leaving it the base pointer, and
00597 /// accumulates the total constant offset applied in the returned constant. It
00598 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
00599 /// no constant offsets applied.
00600 ///
00601 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
00602 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
00603 /// folding.
00604 static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
00605                                                 bool AllowNonInbounds = false) {
00606   assert(V->getType()->getScalarType()->isPointerTy());
00607 
00608   Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
00609   APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
00610 
00611   // Even though we don't look through PHI nodes, we could be called on an
00612   // instruction in an unreachable block, which may be on a cycle.
00613   SmallPtrSet<Value *, 4> Visited;
00614   Visited.insert(V);
00615   do {
00616     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00617       if ((!AllowNonInbounds && !GEP->isInBounds()) ||
00618           !GEP->accumulateConstantOffset(DL, Offset))
00619         break;
00620       V = GEP->getPointerOperand();
00621     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
00622       V = cast<Operator>(V)->getOperand(0);
00623     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
00624       if (GA->mayBeOverridden())
00625         break;
00626       V = GA->getAliasee();
00627     } else {
00628       break;
00629     }
00630     assert(V->getType()->getScalarType()->isPointerTy() &&
00631            "Unexpected operand type!");
00632   } while (Visited.insert(V).second);
00633 
00634   Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
00635   if (V->getType()->isVectorTy())
00636     return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
00637                                     OffsetIntPtr);
00638   return OffsetIntPtr;
00639 }
00640 
00641 /// \brief Compute the constant difference between two pointer values.
00642 /// If the difference is not a constant, returns zero.
00643 static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
00644                                           Value *RHS) {
00645   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
00646   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
00647 
00648   // If LHS and RHS are not related via constant offsets to the same base
00649   // value, there is nothing we can do here.
00650   if (LHS != RHS)
00651     return nullptr;
00652 
00653   // Otherwise, the difference of LHS - RHS can be computed as:
00654   //    LHS - RHS
00655   //  = (LHSOffset + Base) - (RHSOffset + Base)
00656   //  = LHSOffset - RHSOffset
00657   return ConstantExpr::getSub(LHSOffset, RHSOffset);
00658 }
00659 
00660 /// SimplifySubInst - Given operands for a Sub, see if we can
00661 /// fold the result.  If not, this returns null.
00662 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
00663                               const Query &Q, unsigned MaxRecurse) {
00664   if (Constant *CLHS = dyn_cast<Constant>(Op0))
00665     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
00666       Constant *Ops[] = { CLHS, CRHS };
00667       return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
00668                                       Ops, Q.DL, Q.TLI);
00669     }
00670 
00671   // X - undef -> undef
00672   // undef - X -> undef
00673   if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
00674     return UndefValue::get(Op0->getType());
00675 
00676   // X - 0 -> X
00677   if (match(Op1, m_Zero()))
00678     return Op0;
00679 
00680   // X - X -> 0
00681   if (Op0 == Op1)
00682     return Constant::getNullValue(Op0->getType());
00683 
00684   // 0 - X -> 0 if the sub is NUW.
00685   if (isNUW && match(Op0, m_Zero()))
00686     return Op0;
00687 
00688   // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
00689   // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
00690   Value *X = nullptr, *Y = nullptr, *Z = Op1;
00691   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
00692     // See if "V === Y - Z" simplifies.
00693     if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
00694       // It does!  Now see if "X + V" simplifies.
00695       if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
00696         // It does, we successfully reassociated!
00697         ++NumReassoc;
00698         return W;
00699       }
00700     // See if "V === X - Z" simplifies.
00701     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
00702       // It does!  Now see if "Y + V" simplifies.
00703       if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
00704         // It does, we successfully reassociated!
00705         ++NumReassoc;
00706         return W;
00707       }
00708   }
00709 
00710   // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
00711   // For example, X - (X + 1) -> -1
00712   X = Op0;
00713   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
00714     // See if "V === X - Y" simplifies.
00715     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
00716       // It does!  Now see if "V - Z" simplifies.
00717       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
00718         // It does, we successfully reassociated!
00719         ++NumReassoc;
00720         return W;
00721       }
00722     // See if "V === X - Z" simplifies.
00723     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
00724       // It does!  Now see if "V - Y" simplifies.
00725       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
00726         // It does, we successfully reassociated!
00727         ++NumReassoc;
00728         return W;
00729       }
00730   }
00731 
00732   // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
00733   // For example, X - (X - Y) -> Y.
00734   Z = Op0;
00735   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
00736     // See if "V === Z - X" simplifies.
00737     if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
00738       // It does!  Now see if "V + Y" simplifies.
00739       if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
00740         // It does, we successfully reassociated!
00741         ++NumReassoc;
00742         return W;
00743       }
00744 
00745   // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
00746   if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
00747       match(Op1, m_Trunc(m_Value(Y))))
00748     if (X->getType() == Y->getType())
00749       // See if "V === X - Y" simplifies.
00750       if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
00751         // It does!  Now see if "trunc V" simplifies.
00752         if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
00753           // It does, return the simplified "trunc V".
00754           return W;
00755 
00756   // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
00757   if (match(Op0, m_PtrToInt(m_Value(X))) &&
00758       match(Op1, m_PtrToInt(m_Value(Y))))
00759     if (Constant *Result = computePointerDifference(Q.DL, X, Y))
00760       return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
00761 
00762   // i1 sub -> xor.
00763   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
00764     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
00765       return V;
00766 
00767   // Threading Sub over selects and phi nodes is pointless, so don't bother.
00768   // Threading over the select in "A - select(cond, B, C)" means evaluating
00769   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
00770   // only if B and C are equal.  If B and C are equal then (since we assume
00771   // that operands have already been simplified) "select(cond, B, C)" should
00772   // have been simplified to the common value of B and C already.  Analysing
00773   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
00774   // for threading over phi nodes.
00775 
00776   return nullptr;
00777 }
00778 
00779 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
00780                              const DataLayout &DL, const TargetLibraryInfo *TLI,
00781                              const DominatorTree *DT, AssumptionCache *AC,
00782                              const Instruction *CxtI) {
00783   return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
00784                            RecursionLimit);
00785 }
00786 
00787 /// Given operands for an FAdd, see if we can fold the result.  If not, this
00788 /// returns null.
00789 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
00790                               const Query &Q, unsigned MaxRecurse) {
00791   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
00792     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
00793       Constant *Ops[] = { CLHS, CRHS };
00794       return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(),
00795                                       Ops, Q.DL, Q.TLI);
00796     }
00797 
00798     // Canonicalize the constant to the RHS.
00799     std::swap(Op0, Op1);
00800   }
00801 
00802   // fadd X, -0 ==> X
00803   if (match(Op1, m_NegZero()))
00804     return Op0;
00805 
00806   // fadd X, 0 ==> X, when we know X is not -0
00807   if (match(Op1, m_Zero()) &&
00808       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
00809     return Op0;
00810 
00811   // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
00812   //   where nnan and ninf have to occur at least once somewhere in this
00813   //   expression
00814   Value *SubOp = nullptr;
00815   if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
00816     SubOp = Op1;
00817   else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
00818     SubOp = Op0;
00819   if (SubOp) {
00820     Instruction *FSub = cast<Instruction>(SubOp);
00821     if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
00822         (FMF.noInfs() || FSub->hasNoInfs()))
00823       return Constant::getNullValue(Op0->getType());
00824   }
00825 
00826   return nullptr;
00827 }
00828 
00829 /// Given operands for an FSub, see if we can fold the result.  If not, this
00830 /// returns null.
00831 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
00832                               const Query &Q, unsigned MaxRecurse) {
00833   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
00834     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
00835       Constant *Ops[] = { CLHS, CRHS };
00836       return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(),
00837                                       Ops, Q.DL, Q.TLI);
00838     }
00839   }
00840 
00841   // fsub X, 0 ==> X
00842   if (match(Op1, m_Zero()))
00843     return Op0;
00844 
00845   // fsub X, -0 ==> X, when we know X is not -0
00846   if (match(Op1, m_NegZero()) &&
00847       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
00848     return Op0;
00849 
00850   // fsub 0, (fsub -0.0, X) ==> X
00851   Value *X;
00852   if (match(Op0, m_AnyZero())) {
00853     if (match(Op1, m_FSub(m_NegZero(), m_Value(X))))
00854       return X;
00855     if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
00856       return X;
00857   }
00858 
00859   // fsub nnan ninf x, x ==> 0.0
00860   if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1)
00861     return Constant::getNullValue(Op0->getType());
00862 
00863   return nullptr;
00864 }
00865 
00866 /// Given the operands for an FMul, see if we can fold the result
00867 static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
00868                                FastMathFlags FMF,
00869                                const Query &Q,
00870                                unsigned MaxRecurse) {
00871  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
00872     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
00873       Constant *Ops[] = { CLHS, CRHS };
00874       return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(),
00875                                       Ops, Q.DL, Q.TLI);
00876     }
00877 
00878     // Canonicalize the constant to the RHS.
00879     std::swap(Op0, Op1);
00880  }
00881 
00882  // fmul X, 1.0 ==> X
00883  if (match(Op1, m_FPOne()))
00884    return Op0;
00885 
00886  // fmul nnan nsz X, 0 ==> 0
00887  if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
00888    return Op1;
00889 
00890  return nullptr;
00891 }
00892 
00893 /// SimplifyMulInst - Given operands for a Mul, see if we can
00894 /// fold the result.  If not, this returns null.
00895 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
00896                               unsigned MaxRecurse) {
00897   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
00898     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
00899       Constant *Ops[] = { CLHS, CRHS };
00900       return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
00901                                       Ops, Q.DL, Q.TLI);
00902     }
00903 
00904     // Canonicalize the constant to the RHS.
00905     std::swap(Op0, Op1);
00906   }
00907 
00908   // X * undef -> 0
00909   if (match(Op1, m_Undef()))
00910     return Constant::getNullValue(Op0->getType());
00911 
00912   // X * 0 -> 0
00913   if (match(Op1, m_Zero()))
00914     return Op1;
00915 
00916   // X * 1 -> X
00917   if (match(Op1, m_One()))
00918     return Op0;
00919 
00920   // (X / Y) * Y -> X if the division is exact.
00921   Value *X = nullptr;
00922   if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
00923       match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))   // Y * (X / Y)
00924     return X;
00925 
00926   // i1 mul -> and.
00927   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
00928     if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
00929       return V;
00930 
00931   // Try some generic simplifications for associative operations.
00932   if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
00933                                           MaxRecurse))
00934     return V;
00935 
00936   // Mul distributes over Add.  Try some generic simplifications based on this.
00937   if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
00938                              Q, MaxRecurse))
00939     return V;
00940 
00941   // If the operation is with the result of a select instruction, check whether
00942   // operating on either branch of the select always yields the same value.
00943   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
00944     if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
00945                                          MaxRecurse))
00946       return V;
00947 
00948   // If the operation is with the result of a phi instruction, check whether
00949   // operating on all incoming values of the phi always yields the same value.
00950   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
00951     if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
00952                                       MaxRecurse))
00953       return V;
00954 
00955   return nullptr;
00956 }
00957 
00958 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
00959                               const DataLayout &DL,
00960                               const TargetLibraryInfo *TLI,
00961                               const DominatorTree *DT, AssumptionCache *AC,
00962                               const Instruction *CxtI) {
00963   return ::SimplifyFAddInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
00964                             RecursionLimit);
00965 }
00966 
00967 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
00968                               const DataLayout &DL,
00969                               const TargetLibraryInfo *TLI,
00970                               const DominatorTree *DT, AssumptionCache *AC,
00971                               const Instruction *CxtI) {
00972   return ::SimplifyFSubInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
00973                             RecursionLimit);
00974 }
00975 
00976 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
00977                               const DataLayout &DL,
00978                               const TargetLibraryInfo *TLI,
00979                               const DominatorTree *DT, AssumptionCache *AC,
00980                               const Instruction *CxtI) {
00981   return ::SimplifyFMulInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
00982                             RecursionLimit);
00983 }
00984 
00985 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout &DL,
00986                              const TargetLibraryInfo *TLI,
00987                              const DominatorTree *DT, AssumptionCache *AC,
00988                              const Instruction *CxtI) {
00989   return ::SimplifyMulInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
00990                            RecursionLimit);
00991 }
00992 
00993 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
00994 /// fold the result.  If not, this returns null.
00995 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
00996                           const Query &Q, unsigned MaxRecurse) {
00997   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
00998     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
00999       Constant *Ops[] = { C0, C1 };
01000       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
01001     }
01002   }
01003 
01004   bool isSigned = Opcode == Instruction::SDiv;
01005 
01006   // X / undef -> undef
01007   if (match(Op1, m_Undef()))
01008     return Op1;
01009 
01010   // X / 0 -> undef, we don't need to preserve faults!
01011   if (match(Op1, m_Zero()))
01012     return UndefValue::get(Op1->getType());
01013 
01014   // undef / X -> 0
01015   if (match(Op0, m_Undef()))
01016     return Constant::getNullValue(Op0->getType());
01017 
01018   // 0 / X -> 0, we don't need to preserve faults!
01019   if (match(Op0, m_Zero()))
01020     return Op0;
01021 
01022   // X / 1 -> X
01023   if (match(Op1, m_One()))
01024     return Op0;
01025 
01026   if (Op0->getType()->isIntegerTy(1))
01027     // It can't be division by zero, hence it must be division by one.
01028     return Op0;
01029 
01030   // X / X -> 1
01031   if (Op0 == Op1)
01032     return ConstantInt::get(Op0->getType(), 1);
01033 
01034   // (X * Y) / Y -> X if the multiplication does not overflow.
01035   Value *X = nullptr, *Y = nullptr;
01036   if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
01037     if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
01038     OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
01039     // If the Mul knows it does not overflow, then we are good to go.
01040     if ((isSigned && Mul->hasNoSignedWrap()) ||
01041         (!isSigned && Mul->hasNoUnsignedWrap()))
01042       return X;
01043     // If X has the form X = A / Y then X * Y cannot overflow.
01044     if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
01045       if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
01046         return X;
01047   }
01048 
01049   // (X rem Y) / Y -> 0
01050   if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
01051       (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
01052     return Constant::getNullValue(Op0->getType());
01053 
01054   // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
01055   ConstantInt *C1, *C2;
01056   if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
01057       match(Op1, m_ConstantInt(C2))) {
01058     bool Overflow;
01059     C1->getValue().umul_ov(C2->getValue(), Overflow);
01060     if (Overflow)
01061       return Constant::getNullValue(Op0->getType());
01062   }
01063 
01064   // If the operation is with the result of a select instruction, check whether
01065   // operating on either branch of the select always yields the same value.
01066   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
01067     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
01068       return V;
01069 
01070   // If the operation is with the result of a phi instruction, check whether
01071   // operating on all incoming values of the phi always yields the same value.
01072   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
01073     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
01074       return V;
01075 
01076   return nullptr;
01077 }
01078 
01079 /// SimplifySDivInst - Given operands for an SDiv, see if we can
01080 /// fold the result.  If not, this returns null.
01081 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
01082                                unsigned MaxRecurse) {
01083   if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
01084     return V;
01085 
01086   return nullptr;
01087 }
01088 
01089 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
01090                               const TargetLibraryInfo *TLI,
01091                               const DominatorTree *DT, AssumptionCache *AC,
01092                               const Instruction *CxtI) {
01093   return ::SimplifySDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
01094                             RecursionLimit);
01095 }
01096 
01097 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
01098 /// fold the result.  If not, this returns null.
01099 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
01100                                unsigned MaxRecurse) {
01101   if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
01102     return V;
01103 
01104   return nullptr;
01105 }
01106 
01107 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
01108                               const TargetLibraryInfo *TLI,
01109                               const DominatorTree *DT, AssumptionCache *AC,
01110                               const Instruction *CxtI) {
01111   return ::SimplifyUDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
01112                             RecursionLimit);
01113 }
01114 
01115 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
01116                                const Query &Q, unsigned) {
01117   // undef / X -> undef    (the undef could be a snan).
01118   if (match(Op0, m_Undef()))
01119     return Op0;
01120 
01121   // X / undef -> undef
01122   if (match(Op1, m_Undef()))
01123     return Op1;
01124 
01125   // 0 / X -> 0
01126   // Requires that NaNs are off (X could be zero) and signed zeroes are
01127   // ignored (X could be positive or negative, so the output sign is unknown).
01128   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
01129     return Op0;
01130 
01131   return nullptr;
01132 }
01133 
01134 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
01135                               const DataLayout &DL,
01136                               const TargetLibraryInfo *TLI,
01137                               const DominatorTree *DT, AssumptionCache *AC,
01138                               const Instruction *CxtI) {
01139   return ::SimplifyFDivInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
01140                             RecursionLimit);
01141 }
01142 
01143 /// SimplifyRem - Given operands for an SRem or URem, see if we can
01144 /// fold the result.  If not, this returns null.
01145 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
01146                           const Query &Q, unsigned MaxRecurse) {
01147   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
01148     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
01149       Constant *Ops[] = { C0, C1 };
01150       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
01151     }
01152   }
01153 
01154   // X % undef -> undef
01155   if (match(Op1, m_Undef()))
01156     return Op1;
01157 
01158   // undef % X -> 0
01159   if (match(Op0, m_Undef()))
01160     return Constant::getNullValue(Op0->getType());
01161 
01162   // 0 % X -> 0, we don't need to preserve faults!
01163   if (match(Op0, m_Zero()))
01164     return Op0;
01165 
01166   // X % 0 -> undef, we don't need to preserve faults!
01167   if (match(Op1, m_Zero()))
01168     return UndefValue::get(Op0->getType());
01169 
01170   // X % 1 -> 0
01171   if (match(Op1, m_One()))
01172     return Constant::getNullValue(Op0->getType());
01173 
01174   if (Op0->getType()->isIntegerTy(1))
01175     // It can't be remainder by zero, hence it must be remainder by one.
01176     return Constant::getNullValue(Op0->getType());
01177 
01178   // X % X -> 0
01179   if (Op0 == Op1)
01180     return Constant::getNullValue(Op0->getType());
01181 
01182   // (X % Y) % Y -> X % Y
01183   if ((Opcode == Instruction::SRem &&
01184        match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
01185       (Opcode == Instruction::URem &&
01186        match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
01187     return Op0;
01188 
01189   // If the operation is with the result of a select instruction, check whether
01190   // operating on either branch of the select always yields the same value.
01191   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
01192     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
01193       return V;
01194 
01195   // If the operation is with the result of a phi instruction, check whether
01196   // operating on all incoming values of the phi always yields the same value.
01197   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
01198     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
01199       return V;
01200 
01201   return nullptr;
01202 }
01203 
01204 /// SimplifySRemInst - Given operands for an SRem, see if we can
01205 /// fold the result.  If not, this returns null.
01206 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
01207                                unsigned MaxRecurse) {
01208   if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
01209     return V;
01210 
01211   return nullptr;
01212 }
01213 
01214 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout &DL,
01215                               const TargetLibraryInfo *TLI,
01216                               const DominatorTree *DT, AssumptionCache *AC,
01217                               const Instruction *CxtI) {
01218   return ::SimplifySRemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
01219                             RecursionLimit);
01220 }
01221 
01222 /// SimplifyURemInst - Given operands for a URem, see if we can
01223 /// fold the result.  If not, this returns null.
01224 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
01225                                unsigned MaxRecurse) {
01226   if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
01227     return V;
01228 
01229   return nullptr;
01230 }
01231 
01232 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout &DL,
01233                               const TargetLibraryInfo *TLI,
01234                               const DominatorTree *DT, AssumptionCache *AC,
01235                               const Instruction *CxtI) {
01236   return ::SimplifyURemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
01237                             RecursionLimit);
01238 }
01239 
01240 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
01241                                const Query &, unsigned) {
01242   // undef % X -> undef    (the undef could be a snan).
01243   if (match(Op0, m_Undef()))
01244     return Op0;
01245 
01246   // X % undef -> undef
01247   if (match(Op1, m_Undef()))
01248     return Op1;
01249 
01250   // 0 % X -> 0
01251   // Requires that NaNs are off (X could be zero) and signed zeroes are
01252   // ignored (X could be positive or negative, so the output sign is unknown).
01253   if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
01254     return Op0;
01255 
01256   return nullptr;
01257 }
01258 
01259 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
01260                               const DataLayout &DL,
01261                               const TargetLibraryInfo *TLI,
01262                               const DominatorTree *DT, AssumptionCache *AC,
01263                               const Instruction *CxtI) {
01264   return ::SimplifyFRemInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
01265                             RecursionLimit);
01266 }
01267 
01268 /// isUndefShift - Returns true if a shift by \c Amount always yields undef.
01269 static bool isUndefShift(Value *Amount) {
01270   Constant *C = dyn_cast<Constant>(Amount);
01271   if (!C)
01272     return false;
01273 
01274   // X shift by undef -> undef because it may shift by the bitwidth.
01275   if (isa<UndefValue>(C))
01276     return true;
01277 
01278   // Shifting by the bitwidth or more is undefined.
01279   if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
01280     if (CI->getValue().getLimitedValue() >=
01281         CI->getType()->getScalarSizeInBits())
01282       return true;
01283 
01284   // If all lanes of a vector shift are undefined the whole shift is.
01285   if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
01286     for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
01287       if (!isUndefShift(C->getAggregateElement(I)))
01288         return false;
01289     return true;
01290   }
01291 
01292   return false;
01293 }
01294 
01295 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
01296 /// fold the result.  If not, this returns null.
01297 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
01298                             const Query &Q, unsigned MaxRecurse) {
01299   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
01300     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
01301       Constant *Ops[] = { C0, C1 };
01302       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
01303     }
01304   }
01305 
01306   // 0 shift by X -> 0
01307   if (match(Op0, m_Zero()))
01308     return Op0;
01309 
01310   // X shift by 0 -> X
01311   if (match(Op1, m_Zero()))
01312     return Op0;
01313 
01314   // Fold undefined shifts.
01315   if (isUndefShift(Op1))
01316     return UndefValue::get(Op0->getType());
01317 
01318   // If the operation is with the result of a select instruction, check whether
01319   // operating on either branch of the select always yields the same value.
01320   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
01321     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
01322       return V;
01323 
01324   // If the operation is with the result of a phi instruction, check whether
01325   // operating on all incoming values of the phi always yields the same value.
01326   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
01327     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
01328       return V;
01329 
01330   return nullptr;
01331 }
01332 
01333 /// \brief Given operands for an Shl, LShr or AShr, see if we can
01334 /// fold the result.  If not, this returns null.
01335 static Value *SimplifyRightShift(unsigned Opcode, Value *Op0, Value *Op1,
01336                                  bool isExact, const Query &Q,
01337                                  unsigned MaxRecurse) {
01338   if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
01339     return V;
01340 
01341   // X >> X -> 0
01342   if (Op0 == Op1)
01343     return Constant::getNullValue(Op0->getType());
01344 
01345   // undef >> X -> 0
01346   // undef >> X -> undef (if it's exact)
01347   if (match(Op0, m_Undef()))
01348     return isExact ? Op0 : Constant::getNullValue(Op0->getType());
01349 
01350   // The low bit cannot be shifted out of an exact shift if it is set.
01351   if (isExact) {
01352     unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
01353     APInt Op0KnownZero(BitWidth, 0);
01354     APInt Op0KnownOne(BitWidth, 0);
01355     computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.AC,
01356                      Q.CxtI, Q.DT);
01357     if (Op0KnownOne[0])
01358       return Op0;
01359   }
01360 
01361   return nullptr;
01362 }
01363 
01364 /// SimplifyShlInst - Given operands for an Shl, see if we can
01365 /// fold the result.  If not, this returns null.
01366 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
01367                               const Query &Q, unsigned MaxRecurse) {
01368   if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
01369     return V;
01370 
01371   // undef << X -> 0
01372   // undef << X -> undef if (if it's NSW/NUW)
01373   if (match(Op0, m_Undef()))
01374     return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
01375 
01376   // (X >> A) << A -> X
01377   Value *X;
01378   if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
01379     return X;
01380   return nullptr;
01381 }
01382 
01383 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
01384                              const DataLayout &DL, const TargetLibraryInfo *TLI,
01385                              const DominatorTree *DT, AssumptionCache *AC,
01386                              const Instruction *CxtI) {
01387   return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
01388                            RecursionLimit);
01389 }
01390 
01391 /// SimplifyLShrInst - Given operands for an LShr, see if we can
01392 /// fold the result.  If not, this returns null.
01393 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
01394                                const Query &Q, unsigned MaxRecurse) {
01395   if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
01396                                     MaxRecurse))
01397       return V;
01398 
01399   // (X << A) >> A -> X
01400   Value *X;
01401   if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
01402     return X;
01403 
01404   return nullptr;
01405 }
01406 
01407 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
01408                               const DataLayout &DL,
01409                               const TargetLibraryInfo *TLI,
01410                               const DominatorTree *DT, AssumptionCache *AC,
01411                               const Instruction *CxtI) {
01412   return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
01413                             RecursionLimit);
01414 }
01415 
01416 /// SimplifyAShrInst - Given operands for an AShr, see if we can
01417 /// fold the result.  If not, this returns null.
01418 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
01419                                const Query &Q, unsigned MaxRecurse) {
01420   if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
01421                                     MaxRecurse))
01422     return V;
01423 
01424   // all ones >>a X -> all ones
01425   if (match(Op0, m_AllOnes()))
01426     return Op0;
01427 
01428   // (X << A) >> A -> X
01429   Value *X;
01430   if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
01431     return X;
01432 
01433   // Arithmetic shifting an all-sign-bit value is a no-op.
01434   unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
01435   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
01436     return Op0;
01437 
01438   return nullptr;
01439 }
01440 
01441 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
01442                               const DataLayout &DL,
01443                               const TargetLibraryInfo *TLI,
01444                               const DominatorTree *DT, AssumptionCache *AC,
01445                               const Instruction *CxtI) {
01446   return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
01447                             RecursionLimit);
01448 }
01449 
01450 static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
01451                                          ICmpInst *UnsignedICmp, bool IsAnd) {
01452   Value *X, *Y;
01453 
01454   ICmpInst::Predicate EqPred;
01455   if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
01456       !ICmpInst::isEquality(EqPred))
01457     return nullptr;
01458 
01459   ICmpInst::Predicate UnsignedPred;
01460   if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
01461       ICmpInst::isUnsigned(UnsignedPred))
01462     ;
01463   else if (match(UnsignedICmp,
01464                  m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
01465            ICmpInst::isUnsigned(UnsignedPred))
01466     UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
01467   else
01468     return nullptr;
01469 
01470   // X < Y && Y != 0  -->  X < Y
01471   // X < Y || Y != 0  -->  Y != 0
01472   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
01473     return IsAnd ? UnsignedICmp : ZeroICmp;
01474 
01475   // X >= Y || Y != 0  -->  true
01476   // X >= Y || Y == 0  -->  X >= Y
01477   if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
01478     if (EqPred == ICmpInst::ICMP_NE)
01479       return getTrue(UnsignedICmp->getType());
01480     return UnsignedICmp;
01481   }
01482 
01483   // X < Y && Y == 0  -->  false
01484   if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
01485       IsAnd)
01486     return getFalse(UnsignedICmp->getType());
01487 
01488   return nullptr;
01489 }
01490 
01491 // Simplify (and (icmp ...) (icmp ...)) to true when we can tell that the range
01492 // of possible values cannot be satisfied.
01493 static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
01494   ICmpInst::Predicate Pred0, Pred1;
01495   ConstantInt *CI1, *CI2;
01496   Value *V;
01497 
01498   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
01499     return X;
01500 
01501   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
01502                          m_ConstantInt(CI2))))
01503    return nullptr;
01504 
01505   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
01506     return nullptr;
01507 
01508   Type *ITy = Op0->getType();
01509 
01510   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
01511   bool isNSW = AddInst->hasNoSignedWrap();
01512   bool isNUW = AddInst->hasNoUnsignedWrap();
01513 
01514   const APInt &CI1V = CI1->getValue();
01515   const APInt &CI2V = CI2->getValue();
01516   const APInt Delta = CI2V - CI1V;
01517   if (CI1V.isStrictlyPositive()) {
01518     if (Delta == 2) {
01519       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
01520         return getFalse(ITy);
01521       if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
01522         return getFalse(ITy);
01523     }
01524     if (Delta == 1) {
01525       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
01526         return getFalse(ITy);
01527       if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
01528         return getFalse(ITy);
01529     }
01530   }
01531   if (CI1V.getBoolValue() && isNUW) {
01532     if (Delta == 2)
01533       if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
01534         return getFalse(ITy);
01535     if (Delta == 1)
01536       if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
01537         return getFalse(ITy);
01538   }
01539 
01540   return nullptr;
01541 }
01542 
01543 /// SimplifyAndInst - Given operands for an And, see if we can
01544 /// fold the result.  If not, this returns null.
01545 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
01546                               unsigned MaxRecurse) {
01547   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
01548     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
01549       Constant *Ops[] = { CLHS, CRHS };
01550       return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
01551                                       Ops, Q.DL, Q.TLI);
01552     }
01553 
01554     // Canonicalize the constant to the RHS.
01555     std::swap(Op0, Op1);
01556   }
01557 
01558   // X & undef -> 0
01559   if (match(Op1, m_Undef()))
01560     return Constant::getNullValue(Op0->getType());
01561 
01562   // X & X = X
01563   if (Op0 == Op1)
01564     return Op0;
01565 
01566   // X & 0 = 0
01567   if (match(Op1, m_Zero()))
01568     return Op1;
01569 
01570   // X & -1 = X
01571   if (match(Op1, m_AllOnes()))
01572     return Op0;
01573 
01574   // A & ~A  =  ~A & A  =  0
01575   if (match(Op0, m_Not(m_Specific(Op1))) ||
01576       match(Op1, m_Not(m_Specific(Op0))))
01577     return Constant::getNullValue(Op0->getType());
01578 
01579   // (A | ?) & A = A
01580   Value *A = nullptr, *B = nullptr;
01581   if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
01582       (A == Op1 || B == Op1))
01583     return Op1;
01584 
01585   // A & (A | ?) = A
01586   if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
01587       (A == Op0 || B == Op0))
01588     return Op0;
01589 
01590   // A & (-A) = A if A is a power of two or zero.
01591   if (match(Op0, m_Neg(m_Specific(Op1))) ||
01592       match(Op1, m_Neg(m_Specific(Op0)))) {
01593     if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
01594                                Q.DT))
01595       return Op0;
01596     if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
01597                                Q.DT))
01598       return Op1;
01599   }
01600 
01601   if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
01602     if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
01603       if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
01604         return V;
01605       if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
01606         return V;
01607     }
01608   }
01609 
01610   // Try some generic simplifications for associative operations.
01611   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
01612                                           MaxRecurse))
01613     return V;
01614 
01615   // And distributes over Or.  Try some generic simplifications based on this.
01616   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
01617                              Q, MaxRecurse))
01618     return V;
01619 
01620   // And distributes over Xor.  Try some generic simplifications based on this.
01621   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
01622                              Q, MaxRecurse))
01623     return V;
01624 
01625   // If the operation is with the result of a select instruction, check whether
01626   // operating on either branch of the select always yields the same value.
01627   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
01628     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
01629                                          MaxRecurse))
01630       return V;
01631 
01632   // If the operation is with the result of a phi instruction, check whether
01633   // operating on all incoming values of the phi always yields the same value.
01634   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
01635     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
01636                                       MaxRecurse))
01637       return V;
01638 
01639   return nullptr;
01640 }
01641 
01642 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout &DL,
01643                              const TargetLibraryInfo *TLI,
01644                              const DominatorTree *DT, AssumptionCache *AC,
01645                              const Instruction *CxtI) {
01646   return ::SimplifyAndInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
01647                            RecursionLimit);
01648 }
01649 
01650 // Simplify (or (icmp ...) (icmp ...)) to true when we can tell that the union
01651 // contains all possible values.
01652 static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
01653   ICmpInst::Predicate Pred0, Pred1;
01654   ConstantInt *CI1, *CI2;
01655   Value *V;
01656 
01657   if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
01658     return X;
01659 
01660   if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
01661                          m_ConstantInt(CI2))))
01662    return nullptr;
01663 
01664   if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
01665     return nullptr;
01666 
01667   Type *ITy = Op0->getType();
01668 
01669   auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
01670   bool isNSW = AddInst->hasNoSignedWrap();
01671   bool isNUW = AddInst->hasNoUnsignedWrap();
01672 
01673   const APInt &CI1V = CI1->getValue();
01674   const APInt &CI2V = CI2->getValue();
01675   const APInt Delta = CI2V - CI1V;
01676   if (CI1V.isStrictlyPositive()) {
01677     if (Delta == 2) {
01678       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
01679         return getTrue(ITy);
01680       if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
01681         return getTrue(ITy);
01682     }
01683     if (Delta == 1) {
01684       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
01685         return getTrue(ITy);
01686       if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
01687         return getTrue(ITy);
01688     }
01689   }
01690   if (CI1V.getBoolValue() && isNUW) {
01691     if (Delta == 2)
01692       if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
01693         return getTrue(ITy);
01694     if (Delta == 1)
01695       if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
01696         return getTrue(ITy);
01697   }
01698 
01699   return nullptr;
01700 }
01701 
01702 /// SimplifyOrInst - Given operands for an Or, see if we can
01703 /// fold the result.  If not, this returns null.
01704 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
01705                              unsigned MaxRecurse) {
01706   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
01707     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
01708       Constant *Ops[] = { CLHS, CRHS };
01709       return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
01710                                       Ops, Q.DL, Q.TLI);
01711     }
01712 
01713     // Canonicalize the constant to the RHS.
01714     std::swap(Op0, Op1);
01715   }
01716 
01717   // X | undef -> -1
01718   if (match(Op1, m_Undef()))
01719     return Constant::getAllOnesValue(Op0->getType());
01720 
01721   // X | X = X
01722   if (Op0 == Op1)
01723     return Op0;
01724 
01725   // X | 0 = X
01726   if (match(Op1, m_Zero()))
01727     return Op0;
01728 
01729   // X | -1 = -1
01730   if (match(Op1, m_AllOnes()))
01731     return Op1;
01732 
01733   // A | ~A  =  ~A | A  =  -1
01734   if (match(Op0, m_Not(m_Specific(Op1))) ||
01735       match(Op1, m_Not(m_Specific(Op0))))
01736     return Constant::getAllOnesValue(Op0->getType());
01737 
01738   // (A & ?) | A = A
01739   Value *A = nullptr, *B = nullptr;
01740   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
01741       (A == Op1 || B == Op1))
01742     return Op1;
01743 
01744   // A | (A & ?) = A
01745   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
01746       (A == Op0 || B == Op0))
01747     return Op0;
01748 
01749   // ~(A & ?) | A = -1
01750   if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
01751       (A == Op1 || B == Op1))
01752     return Constant::getAllOnesValue(Op1->getType());
01753 
01754   // A | ~(A & ?) = -1
01755   if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
01756       (A == Op0 || B == Op0))
01757     return Constant::getAllOnesValue(Op0->getType());
01758 
01759   if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
01760     if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
01761       if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
01762         return V;
01763       if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
01764         return V;
01765     }
01766   }
01767 
01768   // Try some generic simplifications for associative operations.
01769   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
01770                                           MaxRecurse))
01771     return V;
01772 
01773   // Or distributes over And.  Try some generic simplifications based on this.
01774   if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
01775                              MaxRecurse))
01776     return V;
01777 
01778   // If the operation is with the result of a select instruction, check whether
01779   // operating on either branch of the select always yields the same value.
01780   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
01781     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
01782                                          MaxRecurse))
01783       return V;
01784 
01785   // (A & C)|(B & D)
01786   Value *C = nullptr, *D = nullptr;
01787   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
01788       match(Op1, m_And(m_Value(B), m_Value(D)))) {
01789     ConstantInt *C1 = dyn_cast<ConstantInt>(C);
01790     ConstantInt *C2 = dyn_cast<ConstantInt>(D);
01791     if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
01792       // (A & C1)|(B & C2)
01793       // If we have: ((V + N) & C1) | (V & C2)
01794       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
01795       // replace with V+N.
01796       Value *V1, *V2;
01797       if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
01798           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
01799         // Add commutes, try both ways.
01800         if (V1 == B &&
01801             MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
01802           return A;
01803         if (V2 == B &&
01804             MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
01805           return A;
01806       }
01807       // Or commutes, try both ways.
01808       if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
01809           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
01810         // Add commutes, try both ways.
01811         if (V1 == A &&
01812             MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
01813           return B;
01814         if (V2 == A &&
01815             MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
01816           return B;
01817       }
01818     }
01819   }
01820 
01821   // If the operation is with the result of a phi instruction, check whether
01822   // operating on all incoming values of the phi always yields the same value.
01823   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
01824     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
01825       return V;
01826 
01827   return nullptr;
01828 }
01829 
01830 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
01831                             const TargetLibraryInfo *TLI,
01832                             const DominatorTree *DT, AssumptionCache *AC,
01833                             const Instruction *CxtI) {
01834   return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
01835                           RecursionLimit);
01836 }
01837 
01838 /// SimplifyXorInst - Given operands for a Xor, see if we can
01839 /// fold the result.  If not, this returns null.
01840 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
01841                               unsigned MaxRecurse) {
01842   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
01843     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
01844       Constant *Ops[] = { CLHS, CRHS };
01845       return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
01846                                       Ops, Q.DL, Q.TLI);
01847     }
01848 
01849     // Canonicalize the constant to the RHS.
01850     std::swap(Op0, Op1);
01851   }
01852 
01853   // A ^ undef -> undef
01854   if (match(Op1, m_Undef()))
01855     return Op1;
01856 
01857   // A ^ 0 = A
01858   if (match(Op1, m_Zero()))
01859     return Op0;
01860 
01861   // A ^ A = 0
01862   if (Op0 == Op1)
01863     return Constant::getNullValue(Op0->getType());
01864 
01865   // A ^ ~A  =  ~A ^ A  =  -1
01866   if (match(Op0, m_Not(m_Specific(Op1))) ||
01867       match(Op1, m_Not(m_Specific(Op0))))
01868     return Constant::getAllOnesValue(Op0->getType());
01869 
01870   // Try some generic simplifications for associative operations.
01871   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
01872                                           MaxRecurse))
01873     return V;
01874 
01875   // Threading Xor over selects and phi nodes is pointless, so don't bother.
01876   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
01877   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
01878   // only if B and C are equal.  If B and C are equal then (since we assume
01879   // that operands have already been simplified) "select(cond, B, C)" should
01880   // have been simplified to the common value of B and C already.  Analysing
01881   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
01882   // for threading over phi nodes.
01883 
01884   return nullptr;
01885 }
01886 
01887 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
01888                              const TargetLibraryInfo *TLI,
01889                              const DominatorTree *DT, AssumptionCache *AC,
01890                              const Instruction *CxtI) {
01891   return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
01892                            RecursionLimit);
01893 }
01894 
01895 static Type *GetCompareTy(Value *Op) {
01896   return CmpInst::makeCmpResultType(Op->getType());
01897 }
01898 
01899 /// ExtractEquivalentCondition - Rummage around inside V looking for something
01900 /// equivalent to the comparison "LHS Pred RHS".  Return such a value if found,
01901 /// otherwise return null.  Helper function for analyzing max/min idioms.
01902 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
01903                                          Value *LHS, Value *RHS) {
01904   SelectInst *SI = dyn_cast<SelectInst>(V);
01905   if (!SI)
01906     return nullptr;
01907   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
01908   if (!Cmp)
01909     return nullptr;
01910   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
01911   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
01912     return Cmp;
01913   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
01914       LHS == CmpRHS && RHS == CmpLHS)
01915     return Cmp;
01916   return nullptr;
01917 }
01918 
01919 // A significant optimization not implemented here is assuming that alloca
01920 // addresses are not equal to incoming argument values. They don't *alias*,
01921 // as we say, but that doesn't mean they aren't equal, so we take a
01922 // conservative approach.
01923 //
01924 // This is inspired in part by C++11 5.10p1:
01925 //   "Two pointers of the same type compare equal if and only if they are both
01926 //    null, both point to the same function, or both represent the same
01927 //    address."
01928 //
01929 // This is pretty permissive.
01930 //
01931 // It's also partly due to C11 6.5.9p6:
01932 //   "Two pointers compare equal if and only if both are null pointers, both are
01933 //    pointers to the same object (including a pointer to an object and a
01934 //    subobject at its beginning) or function, both are pointers to one past the
01935 //    last element of the same array object, or one is a pointer to one past the
01936 //    end of one array object and the other is a pointer to the start of a
01937 //    different array object that happens to immediately follow the first array
01938 //    object in the address space.)
01939 //
01940 // C11's version is more restrictive, however there's no reason why an argument
01941 // couldn't be a one-past-the-end value for a stack object in the caller and be
01942 // equal to the beginning of a stack object in the callee.
01943 //
01944 // If the C and C++ standards are ever made sufficiently restrictive in this
01945 // area, it may be possible to update LLVM's semantics accordingly and reinstate
01946 // this optimization.
01947 static Constant *computePointerICmp(const DataLayout &DL,
01948                                     const TargetLibraryInfo *TLI,
01949                                     CmpInst::Predicate Pred, Value *LHS,
01950                                     Value *RHS) {
01951   // First, skip past any trivial no-ops.
01952   LHS = LHS->stripPointerCasts();
01953   RHS = RHS->stripPointerCasts();
01954 
01955   // A non-null pointer is not equal to a null pointer.
01956   if (llvm::isKnownNonNull(LHS, TLI) && isa<ConstantPointerNull>(RHS) &&
01957       (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
01958     return ConstantInt::get(GetCompareTy(LHS),
01959                             !CmpInst::isTrueWhenEqual(Pred));
01960 
01961   // We can only fold certain predicates on pointer comparisons.
01962   switch (Pred) {
01963   default:
01964     return nullptr;
01965 
01966     // Equality comaprisons are easy to fold.
01967   case CmpInst::ICMP_EQ:
01968   case CmpInst::ICMP_NE:
01969     break;
01970 
01971     // We can only handle unsigned relational comparisons because 'inbounds' on
01972     // a GEP only protects against unsigned wrapping.
01973   case CmpInst::ICMP_UGT:
01974   case CmpInst::ICMP_UGE:
01975   case CmpInst::ICMP_ULT:
01976   case CmpInst::ICMP_ULE:
01977     // However, we have to switch them to their signed variants to handle
01978     // negative indices from the base pointer.
01979     Pred = ICmpInst::getSignedPredicate(Pred);
01980     break;
01981   }
01982 
01983   // Strip off any constant offsets so that we can reason about them.
01984   // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
01985   // here and compare base addresses like AliasAnalysis does, however there are
01986   // numerous hazards. AliasAnalysis and its utilities rely on special rules
01987   // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
01988   // doesn't need to guarantee pointer inequality when it says NoAlias.
01989   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
01990   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
01991 
01992   // If LHS and RHS are related via constant offsets to the same base
01993   // value, we can replace it with an icmp which just compares the offsets.
01994   if (LHS == RHS)
01995     return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
01996 
01997   // Various optimizations for (in)equality comparisons.
01998   if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
01999     // Different non-empty allocations that exist at the same time have
02000     // different addresses (if the program can tell). Global variables always
02001     // exist, so they always exist during the lifetime of each other and all
02002     // allocas. Two different allocas usually have different addresses...
02003     //
02004     // However, if there's an @llvm.stackrestore dynamically in between two
02005     // allocas, they may have the same address. It's tempting to reduce the
02006     // scope of the problem by only looking at *static* allocas here. That would
02007     // cover the majority of allocas while significantly reducing the likelihood
02008     // of having an @llvm.stackrestore pop up in the middle. However, it's not
02009     // actually impossible for an @llvm.stackrestore to pop up in the middle of
02010     // an entry block. Also, if we have a block that's not attached to a
02011     // function, we can't tell if it's "static" under the current definition.
02012     // Theoretically, this problem could be fixed by creating a new kind of
02013     // instruction kind specifically for static allocas. Such a new instruction
02014     // could be required to be at the top of the entry block, thus preventing it
02015     // from being subject to a @llvm.stackrestore. Instcombine could even
02016     // convert regular allocas into these special allocas. It'd be nifty.
02017     // However, until then, this problem remains open.
02018     //
02019     // So, we'll assume that two non-empty allocas have different addresses
02020     // for now.
02021     //
02022     // With all that, if the offsets are within the bounds of their allocations
02023     // (and not one-past-the-end! so we can't use inbounds!), and their
02024     // allocations aren't the same, the pointers are not equal.
02025     //
02026     // Note that it's not necessary to check for LHS being a global variable
02027     // address, due to canonicalization and constant folding.
02028     if (isa<AllocaInst>(LHS) &&
02029         (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
02030       ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
02031       ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
02032       uint64_t LHSSize, RHSSize;
02033       if (LHSOffsetCI && RHSOffsetCI &&
02034           getObjectSize(LHS, LHSSize, DL, TLI) &&
02035           getObjectSize(RHS, RHSSize, DL, TLI)) {
02036         const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
02037         const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
02038         if (!LHSOffsetValue.isNegative() &&
02039             !RHSOffsetValue.isNegative() &&
02040             LHSOffsetValue.ult(LHSSize) &&
02041             RHSOffsetValue.ult(RHSSize)) {
02042           return ConstantInt::get(GetCompareTy(LHS),
02043                                   !CmpInst::isTrueWhenEqual(Pred));
02044         }
02045       }
02046 
02047       // Repeat the above check but this time without depending on DataLayout
02048       // or being able to compute a precise size.
02049       if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
02050           !cast<PointerType>(RHS->getType())->isEmptyTy() &&
02051           LHSOffset->isNullValue() &&
02052           RHSOffset->isNullValue())
02053         return ConstantInt::get(GetCompareTy(LHS),
02054                                 !CmpInst::isTrueWhenEqual(Pred));
02055     }
02056 
02057     // Even if an non-inbounds GEP occurs along the path we can still optimize
02058     // equality comparisons concerning the result. We avoid walking the whole
02059     // chain again by starting where the last calls to
02060     // stripAndComputeConstantOffsets left off and accumulate the offsets.
02061     Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
02062     Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
02063     if (LHS == RHS)
02064       return ConstantExpr::getICmp(Pred,
02065                                    ConstantExpr::getAdd(LHSOffset, LHSNoBound),
02066                                    ConstantExpr::getAdd(RHSOffset, RHSNoBound));
02067 
02068     // If one side of the equality comparison must come from a noalias call
02069     // (meaning a system memory allocation function), and the other side must
02070     // come from a pointer that cannot overlap with dynamically-allocated
02071     // memory within the lifetime of the current function (allocas, byval
02072     // arguments, globals), then determine the comparison result here.
02073     SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
02074     GetUnderlyingObjects(LHS, LHSUObjs, DL);
02075     GetUnderlyingObjects(RHS, RHSUObjs, DL);
02076 
02077     // Is the set of underlying objects all noalias calls?
02078     auto IsNAC = [](SmallVectorImpl<Value *> &Objects) {
02079       return std::all_of(Objects.begin(), Objects.end(),
02080                          [](Value *V){ return isNoAliasCall(V); });
02081     };
02082 
02083     // Is the set of underlying objects all things which must be disjoint from
02084     // noalias calls. For allocas, we consider only static ones (dynamic
02085     // allocas might be transformed into calls to malloc not simultaneously
02086     // live with the compared-to allocation). For globals, we exclude symbols
02087     // that might be resolve lazily to symbols in another dynamically-loaded
02088     // library (and, thus, could be malloc'ed by the implementation).
02089     auto IsAllocDisjoint = [](SmallVectorImpl<Value *> &Objects) {
02090       return std::all_of(Objects.begin(), Objects.end(),
02091                          [](Value *V){
02092                            if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
02093                              return AI->getParent() && AI->getParent()->getParent() &&
02094                                     AI->isStaticAlloca();
02095                            if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
02096                              return (GV->hasLocalLinkage() ||
02097                                      GV->hasHiddenVisibility() ||
02098                                      GV->hasProtectedVisibility() ||
02099                                      GV->hasUnnamedAddr()) &&
02100                                     !GV->isThreadLocal();
02101                            if (const Argument *A = dyn_cast<Argument>(V))
02102                              return A->hasByValAttr();
02103                            return false;
02104                          });
02105     };
02106 
02107     if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
02108         (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
02109         return ConstantInt::get(GetCompareTy(LHS),
02110                                 !CmpInst::isTrueWhenEqual(Pred));
02111   }
02112 
02113   // Otherwise, fail.
02114   return nullptr;
02115 }
02116 
02117 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
02118 /// fold the result.  If not, this returns null.
02119 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
02120                                const Query &Q, unsigned MaxRecurse) {
02121   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
02122   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
02123 
02124   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
02125     if (Constant *CRHS = dyn_cast<Constant>(RHS))
02126       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
02127 
02128     // If we have a constant, make sure it is on the RHS.
02129     std::swap(LHS, RHS);
02130     Pred = CmpInst::getSwappedPredicate(Pred);
02131   }
02132 
02133   Type *ITy = GetCompareTy(LHS); // The return type.
02134   Type *OpTy = LHS->getType();   // The operand type.
02135 
02136   // icmp X, X -> true/false
02137   // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
02138   // because X could be 0.
02139   if (LHS == RHS || isa<UndefValue>(RHS))
02140     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
02141 
02142   // Special case logic when the operands have i1 type.
02143   if (OpTy->getScalarType()->isIntegerTy(1)) {
02144     switch (Pred) {
02145     default: break;
02146     case ICmpInst::ICMP_EQ:
02147       // X == 1 -> X
02148       if (match(RHS, m_One()))
02149         return LHS;
02150       break;
02151     case ICmpInst::ICMP_NE:
02152       // X != 0 -> X
02153       if (match(RHS, m_Zero()))
02154         return LHS;
02155       break;
02156     case ICmpInst::ICMP_UGT:
02157       // X >u 0 -> X
02158       if (match(RHS, m_Zero()))
02159         return LHS;
02160       break;
02161     case ICmpInst::ICMP_UGE:
02162       // X >=u 1 -> X
02163       if (match(RHS, m_One()))
02164         return LHS;
02165       break;
02166     case ICmpInst::ICMP_SLT:
02167       // X <s 0 -> X
02168       if (match(RHS, m_Zero()))
02169         return LHS;
02170       break;
02171     case ICmpInst::ICMP_SLE:
02172       // X <=s -1 -> X
02173       if (match(RHS, m_One()))
02174         return LHS;
02175       break;
02176     }
02177   }
02178 
02179   // If we are comparing with zero then try hard since this is a common case.
02180   if (match(RHS, m_Zero())) {
02181     bool LHSKnownNonNegative, LHSKnownNegative;
02182     switch (Pred) {
02183     default: llvm_unreachable("Unknown ICmp predicate!");
02184     case ICmpInst::ICMP_ULT:
02185       return getFalse(ITy);
02186     case ICmpInst::ICMP_UGE:
02187       return getTrue(ITy);
02188     case ICmpInst::ICMP_EQ:
02189     case ICmpInst::ICMP_ULE:
02190       if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
02191         return getFalse(ITy);
02192       break;
02193     case ICmpInst::ICMP_NE:
02194     case ICmpInst::ICMP_UGT:
02195       if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
02196         return getTrue(ITy);
02197       break;
02198     case ICmpInst::ICMP_SLT:
02199       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
02200                      Q.CxtI, Q.DT);
02201       if (LHSKnownNegative)
02202         return getTrue(ITy);
02203       if (LHSKnownNonNegative)
02204         return getFalse(ITy);
02205       break;
02206     case ICmpInst::ICMP_SLE:
02207       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
02208                      Q.CxtI, Q.DT);
02209       if (LHSKnownNegative)
02210         return getTrue(ITy);
02211       if (LHSKnownNonNegative &&
02212           isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
02213         return getFalse(ITy);
02214       break;
02215     case ICmpInst::ICMP_SGE:
02216       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
02217                      Q.CxtI, Q.DT);
02218       if (LHSKnownNegative)
02219         return getFalse(ITy);
02220       if (LHSKnownNonNegative)
02221         return getTrue(ITy);
02222       break;
02223     case ICmpInst::ICMP_SGT:
02224       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
02225                      Q.CxtI, Q.DT);
02226       if (LHSKnownNegative)
02227         return getFalse(ITy);
02228       if (LHSKnownNonNegative &&
02229           isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
02230         return getTrue(ITy);
02231       break;
02232     }
02233   }
02234 
02235   // See if we are doing a comparison with a constant integer.
02236   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
02237     // Rule out tautological comparisons (eg., ult 0 or uge 0).
02238     ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
02239     if (RHS_CR.isEmptySet())
02240       return ConstantInt::getFalse(CI->getContext());
02241     if (RHS_CR.isFullSet())
02242       return ConstantInt::getTrue(CI->getContext());
02243 
02244     // Many binary operators with constant RHS have easy to compute constant
02245     // range.  Use them to check whether the comparison is a tautology.
02246     unsigned Width = CI->getBitWidth();
02247     APInt Lower = APInt(Width, 0);
02248     APInt Upper = APInt(Width, 0);
02249     ConstantInt *CI2;
02250     if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
02251       // 'urem x, CI2' produces [0, CI2).
02252       Upper = CI2->getValue();
02253     } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
02254       // 'srem x, CI2' produces (-|CI2|, |CI2|).
02255       Upper = CI2->getValue().abs();
02256       Lower = (-Upper) + 1;
02257     } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
02258       // 'udiv CI2, x' produces [0, CI2].
02259       Upper = CI2->getValue() + 1;
02260     } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
02261       // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
02262       APInt NegOne = APInt::getAllOnesValue(Width);
02263       if (!CI2->isZero())
02264         Upper = NegOne.udiv(CI2->getValue()) + 1;
02265     } else if (match(LHS, m_SDiv(m_ConstantInt(CI2), m_Value()))) {
02266       if (CI2->isMinSignedValue()) {
02267         // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
02268         Lower = CI2->getValue();
02269         Upper = Lower.lshr(1) + 1;
02270       } else {
02271         // 'sdiv CI2, x' produces [-|CI2|, |CI2|].
02272         Upper = CI2->getValue().abs() + 1;
02273         Lower = (-Upper) + 1;
02274       }
02275     } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
02276       APInt IntMin = APInt::getSignedMinValue(Width);
02277       APInt IntMax = APInt::getSignedMaxValue(Width);
02278       APInt Val = CI2->getValue();
02279       if (Val.isAllOnesValue()) {
02280         // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
02281         //    where CI2 != -1 and CI2 != 0 and CI2 != 1
02282         Lower = IntMin + 1;
02283         Upper = IntMax + 1;
02284       } else if (Val.countLeadingZeros() < Width - 1) {
02285         // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2]
02286         //    where CI2 != -1 and CI2 != 0 and CI2 != 1
02287         Lower = IntMin.sdiv(Val);
02288         Upper = IntMax.sdiv(Val);
02289         if (Lower.sgt(Upper))
02290           std::swap(Lower, Upper);
02291         Upper = Upper + 1;
02292         assert(Upper != Lower && "Upper part of range has wrapped!");
02293       }
02294     } else if (match(LHS, m_NUWShl(m_ConstantInt(CI2), m_Value()))) {
02295       // 'shl nuw CI2, x' produces [CI2, CI2 << CLZ(CI2)]
02296       Lower = CI2->getValue();
02297       Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
02298     } else if (match(LHS, m_NSWShl(m_ConstantInt(CI2), m_Value()))) {
02299       if (CI2->isNegative()) {
02300         // 'shl nsw CI2, x' produces [CI2 << CLO(CI2)-1, CI2]
02301         unsigned ShiftAmount = CI2->getValue().countLeadingOnes() - 1;
02302         Lower = CI2->getValue().shl(ShiftAmount);
02303         Upper = CI2->getValue() + 1;
02304       } else {
02305         // 'shl nsw CI2, x' produces [CI2, CI2 << CLZ(CI2)-1]
02306         unsigned ShiftAmount = CI2->getValue().countLeadingZeros() - 1;
02307         Lower = CI2->getValue();
02308         Upper = CI2->getValue().shl(ShiftAmount) + 1;
02309       }
02310     } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
02311       // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
02312       APInt NegOne = APInt::getAllOnesValue(Width);
02313       if (CI2->getValue().ult(Width))
02314         Upper = NegOne.lshr(CI2->getValue()) + 1;
02315     } else if (match(LHS, m_LShr(m_ConstantInt(CI2), m_Value()))) {
02316       // 'lshr CI2, x' produces [CI2 >> (Width-1), CI2].
02317       unsigned ShiftAmount = Width - 1;
02318       if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
02319         ShiftAmount = CI2->getValue().countTrailingZeros();
02320       Lower = CI2->getValue().lshr(ShiftAmount);
02321       Upper = CI2->getValue() + 1;
02322     } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
02323       // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
02324       APInt IntMin = APInt::getSignedMinValue(Width);
02325       APInt IntMax = APInt::getSignedMaxValue(Width);
02326       if (CI2->getValue().ult(Width)) {
02327         Lower = IntMin.ashr(CI2->getValue());
02328         Upper = IntMax.ashr(CI2->getValue()) + 1;
02329       }
02330     } else if (match(LHS, m_AShr(m_ConstantInt(CI2), m_Value()))) {
02331       unsigned ShiftAmount = Width - 1;
02332       if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
02333         ShiftAmount = CI2->getValue().countTrailingZeros();
02334       if (CI2->isNegative()) {
02335         // 'ashr CI2, x' produces [CI2, CI2 >> (Width-1)]
02336         Lower = CI2->getValue();
02337         Upper = CI2->getValue().ashr(ShiftAmount) + 1;
02338       } else {
02339         // 'ashr CI2, x' produces [CI2 >> (Width-1), CI2]
02340         Lower = CI2->getValue().ashr(ShiftAmount);
02341         Upper = CI2->getValue() + 1;
02342       }
02343     } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
02344       // 'or x, CI2' produces [CI2, UINT_MAX].
02345       Lower = CI2->getValue();
02346     } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
02347       // 'and x, CI2' produces [0, CI2].
02348       Upper = CI2->getValue() + 1;
02349     }
02350     if (Lower != Upper) {
02351       ConstantRange LHS_CR = ConstantRange(Lower, Upper);
02352       if (RHS_CR.contains(LHS_CR))
02353         return ConstantInt::getTrue(RHS->getContext());
02354       if (RHS_CR.inverse().contains(LHS_CR))
02355         return ConstantInt::getFalse(RHS->getContext());
02356     }
02357   }
02358 
02359   // Compare of cast, for example (zext X) != 0 -> X != 0
02360   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
02361     Instruction *LI = cast<CastInst>(LHS);
02362     Value *SrcOp = LI->getOperand(0);
02363     Type *SrcTy = SrcOp->getType();
02364     Type *DstTy = LI->getType();
02365 
02366     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
02367     // if the integer type is the same size as the pointer type.
02368     if (MaxRecurse && isa<PtrToIntInst>(LI) &&
02369         Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
02370       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
02371         // Transfer the cast to the constant.
02372         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
02373                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
02374                                         Q, MaxRecurse-1))
02375           return V;
02376       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
02377         if (RI->getOperand(0)->getType() == SrcTy)
02378           // Compare without the cast.
02379           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
02380                                           Q, MaxRecurse-1))
02381             return V;
02382       }
02383     }
02384 
02385     if (isa<ZExtInst>(LHS)) {
02386       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
02387       // same type.
02388       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
02389         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
02390           // Compare X and Y.  Note that signed predicates become unsigned.
02391           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
02392                                           SrcOp, RI->getOperand(0), Q,
02393                                           MaxRecurse-1))
02394             return V;
02395       }
02396       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
02397       // too.  If not, then try to deduce the result of the comparison.
02398       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
02399         // Compute the constant that would happen if we truncated to SrcTy then
02400         // reextended to DstTy.
02401         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
02402         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
02403 
02404         // If the re-extended constant didn't change then this is effectively
02405         // also a case of comparing two zero-extended values.
02406         if (RExt == CI && MaxRecurse)
02407           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
02408                                         SrcOp, Trunc, Q, MaxRecurse-1))
02409             return V;
02410 
02411         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
02412         // there.  Use this to work out the result of the comparison.
02413         if (RExt != CI) {
02414           switch (Pred) {
02415           default: llvm_unreachable("Unknown ICmp predicate!");
02416           // LHS <u RHS.
02417           case ICmpInst::ICMP_EQ:
02418           case ICmpInst::ICMP_UGT:
02419           case ICmpInst::ICMP_UGE:
02420             return ConstantInt::getFalse(CI->getContext());
02421 
02422           case ICmpInst::ICMP_NE:
02423           case ICmpInst::ICMP_ULT:
02424           case ICmpInst::ICMP_ULE:
02425             return ConstantInt::getTrue(CI->getContext());
02426 
02427           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
02428           // is non-negative then LHS <s RHS.
02429           case ICmpInst::ICMP_SGT:
02430           case ICmpInst::ICMP_SGE:
02431             return CI->getValue().isNegative() ?
02432               ConstantInt::getTrue(CI->getContext()) :
02433               ConstantInt::getFalse(CI->getContext());
02434 
02435           case ICmpInst::ICMP_SLT:
02436           case ICmpInst::ICMP_SLE:
02437             return CI->getValue().isNegative() ?
02438               ConstantInt::getFalse(CI->getContext()) :
02439               ConstantInt::getTrue(CI->getContext());
02440           }
02441         }
02442       }
02443     }
02444 
02445     if (isa<SExtInst>(LHS)) {
02446       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
02447       // same type.
02448       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
02449         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
02450           // Compare X and Y.  Note that the predicate does not change.
02451           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
02452                                           Q, MaxRecurse-1))
02453             return V;
02454       }
02455       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
02456       // too.  If not, then try to deduce the result of the comparison.
02457       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
02458         // Compute the constant that would happen if we truncated to SrcTy then
02459         // reextended to DstTy.
02460         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
02461         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
02462 
02463         // If the re-extended constant didn't change then this is effectively
02464         // also a case of comparing two sign-extended values.
02465         if (RExt == CI && MaxRecurse)
02466           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
02467             return V;
02468 
02469         // Otherwise the upper bits of LHS are all equal, while RHS has varying
02470         // bits there.  Use this to work out the result of the comparison.
02471         if (RExt != CI) {
02472           switch (Pred) {
02473           default: llvm_unreachable("Unknown ICmp predicate!");
02474           case ICmpInst::ICMP_EQ:
02475             return ConstantInt::getFalse(CI->getContext());
02476           case ICmpInst::ICMP_NE:
02477             return ConstantInt::getTrue(CI->getContext());
02478 
02479           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
02480           // LHS >s RHS.
02481           case ICmpInst::ICMP_SGT:
02482           case ICmpInst::ICMP_SGE:
02483             return CI->getValue().isNegative() ?
02484               ConstantInt::getTrue(CI->getContext()) :
02485               ConstantInt::getFalse(CI->getContext());
02486           case ICmpInst::ICMP_SLT:
02487           case ICmpInst::ICMP_SLE:
02488             return CI->getValue().isNegative() ?
02489               ConstantInt::getFalse(CI->getContext()) :
02490               ConstantInt::getTrue(CI->getContext());
02491 
02492           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
02493           // LHS >u RHS.
02494           case ICmpInst::ICMP_UGT:
02495           case ICmpInst::ICMP_UGE:
02496             // Comparison is true iff the LHS <s 0.
02497             if (MaxRecurse)
02498               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
02499                                               Constant::getNullValue(SrcTy),
02500                                               Q, MaxRecurse-1))
02501                 return V;
02502             break;
02503           case ICmpInst::ICMP_ULT:
02504           case ICmpInst::ICMP_ULE:
02505             // Comparison is true iff the LHS >=s 0.
02506             if (MaxRecurse)
02507               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
02508                                               Constant::getNullValue(SrcTy),
02509                                               Q, MaxRecurse-1))
02510                 return V;
02511             break;
02512           }
02513         }
02514       }
02515     }
02516   }
02517 
02518   // Special logic for binary operators.
02519   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
02520   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
02521   if (MaxRecurse && (LBO || RBO)) {
02522     // Analyze the case when either LHS or RHS is an add instruction.
02523     Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
02524     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
02525     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
02526     if (LBO && LBO->getOpcode() == Instruction::Add) {
02527       A = LBO->getOperand(0); B = LBO->getOperand(1);
02528       NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
02529         (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
02530         (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
02531     }
02532     if (RBO && RBO->getOpcode() == Instruction::Add) {
02533       C = RBO->getOperand(0); D = RBO->getOperand(1);
02534       NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
02535         (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
02536         (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
02537     }
02538 
02539     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
02540     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
02541       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
02542                                       Constant::getNullValue(RHS->getType()),
02543                                       Q, MaxRecurse-1))
02544         return V;
02545 
02546     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
02547     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
02548       if (Value *V = SimplifyICmpInst(Pred,
02549                                       Constant::getNullValue(LHS->getType()),
02550                                       C == LHS ? D : C, Q, MaxRecurse-1))
02551         return V;
02552 
02553     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
02554     if (A && C && (A == C || A == D || B == C || B == D) &&
02555         NoLHSWrapProblem && NoRHSWrapProblem) {
02556       // Determine Y and Z in the form icmp (X+Y), (X+Z).
02557       Value *Y, *Z;
02558       if (A == C) {
02559         // C + B == C + D  ->  B == D
02560         Y = B;
02561         Z = D;
02562       } else if (A == D) {
02563         // D + B == C + D  ->  B == C
02564         Y = B;
02565         Z = C;
02566       } else if (B == C) {
02567         // A + C == C + D  ->  A == D
02568         Y = A;
02569         Z = D;
02570       } else {
02571         assert(B == D);
02572         // A + D == C + D  ->  A == C
02573         Y = A;
02574         Z = C;
02575       }
02576       if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
02577         return V;
02578     }
02579   }
02580 
02581   // icmp pred (or X, Y), X
02582   if (LBO && match(LBO, m_CombineOr(m_Or(m_Value(), m_Specific(RHS)),
02583                                     m_Or(m_Specific(RHS), m_Value())))) {
02584     if (Pred == ICmpInst::ICMP_ULT)
02585       return getFalse(ITy);
02586     if (Pred == ICmpInst::ICMP_UGE)
02587       return getTrue(ITy);
02588   }
02589   // icmp pred X, (or X, Y)
02590   if (RBO && match(RBO, m_CombineOr(m_Or(m_Value(), m_Specific(LHS)),
02591                                     m_Or(m_Specific(LHS), m_Value())))) {
02592     if (Pred == ICmpInst::ICMP_ULE)
02593       return getTrue(ITy);
02594     if (Pred == ICmpInst::ICMP_UGT)
02595       return getFalse(ITy);
02596   }
02597 
02598   // icmp pred (and X, Y), X
02599   if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
02600                                     m_And(m_Specific(RHS), m_Value())))) {
02601     if (Pred == ICmpInst::ICMP_UGT)
02602       return getFalse(ITy);
02603     if (Pred == ICmpInst::ICMP_ULE)
02604       return getTrue(ITy);
02605   }
02606   // icmp pred X, (and X, Y)
02607   if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
02608                                     m_And(m_Specific(LHS), m_Value())))) {
02609     if (Pred == ICmpInst::ICMP_UGE)
02610       return getTrue(ITy);
02611     if (Pred == ICmpInst::ICMP_ULT)
02612       return getFalse(ITy);
02613   }
02614 
02615   // 0 - (zext X) pred C
02616   if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
02617     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
02618       if (RHSC->getValue().isStrictlyPositive()) {
02619         if (Pred == ICmpInst::ICMP_SLT)
02620           return ConstantInt::getTrue(RHSC->getContext());
02621         if (Pred == ICmpInst::ICMP_SGE)
02622           return ConstantInt::getFalse(RHSC->getContext());
02623         if (Pred == ICmpInst::ICMP_EQ)
02624           return ConstantInt::getFalse(RHSC->getContext());
02625         if (Pred == ICmpInst::ICMP_NE)
02626           return ConstantInt::getTrue(RHSC->getContext());
02627       }
02628       if (RHSC->getValue().isNonNegative()) {
02629         if (Pred == ICmpInst::ICMP_SLE)
02630           return ConstantInt::getTrue(RHSC->getContext());
02631         if (Pred == ICmpInst::ICMP_SGT)
02632           return ConstantInt::getFalse(RHSC->getContext());
02633       }
02634     }
02635   }
02636 
02637   // icmp pred (urem X, Y), Y
02638   if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
02639     bool KnownNonNegative, KnownNegative;
02640     switch (Pred) {
02641     default:
02642       break;
02643     case ICmpInst::ICMP_SGT:
02644     case ICmpInst::ICMP_SGE:
02645       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
02646                      Q.CxtI, Q.DT);
02647       if (!KnownNonNegative)
02648         break;
02649       // fall-through
02650     case ICmpInst::ICMP_EQ:
02651     case ICmpInst::ICMP_UGT:
02652     case ICmpInst::ICMP_UGE:
02653       return getFalse(ITy);
02654     case ICmpInst::ICMP_SLT:
02655     case ICmpInst::ICMP_SLE:
02656       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
02657                      Q.CxtI, Q.DT);
02658       if (!KnownNonNegative)
02659         break;
02660       // fall-through
02661     case ICmpInst::ICMP_NE:
02662     case ICmpInst::ICMP_ULT:
02663     case ICmpInst::ICMP_ULE:
02664       return getTrue(ITy);
02665     }
02666   }
02667 
02668   // icmp pred X, (urem Y, X)
02669   if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
02670     bool KnownNonNegative, KnownNegative;
02671     switch (Pred) {
02672     default:
02673       break;
02674     case ICmpInst::ICMP_SGT:
02675     case ICmpInst::ICMP_SGE:
02676       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
02677                      Q.CxtI, Q.DT);
02678       if (!KnownNonNegative)
02679         break;
02680       // fall-through
02681     case ICmpInst::ICMP_NE:
02682     case ICmpInst::ICMP_UGT:
02683     case ICmpInst::ICMP_UGE:
02684       return getTrue(ITy);
02685     case ICmpInst::ICMP_SLT:
02686     case ICmpInst::ICMP_SLE:
02687       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
02688                      Q.CxtI, Q.DT);
02689       if (!KnownNonNegative)
02690         break;
02691       // fall-through
02692     case ICmpInst::ICMP_EQ:
02693     case ICmpInst::ICMP_ULT:
02694     case ICmpInst::ICMP_ULE:
02695       return getFalse(ITy);
02696     }
02697   }
02698 
02699   // x udiv y <=u x.
02700   if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
02701     // icmp pred (X /u Y), X
02702     if (Pred == ICmpInst::ICMP_UGT)
02703       return getFalse(ITy);
02704     if (Pred == ICmpInst::ICMP_ULE)
02705       return getTrue(ITy);
02706   }
02707 
02708   // handle:
02709   //   CI2 << X == CI
02710   //   CI2 << X != CI
02711   //
02712   //   where CI2 is a power of 2 and CI isn't
02713   if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
02714     const APInt *CI2Val, *CIVal = &CI->getValue();
02715     if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
02716         CI2Val->isPowerOf2()) {
02717       if (!CIVal->isPowerOf2()) {
02718         // CI2 << X can equal zero in some circumstances,
02719         // this simplification is unsafe if CI is zero.
02720         //
02721         // We know it is safe if:
02722         // - The shift is nsw, we can't shift out the one bit.
02723         // - The shift is nuw, we can't shift out the one bit.
02724         // - CI2 is one
02725         // - CI isn't zero
02726         if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
02727             *CI2Val == 1 || !CI->isZero()) {
02728           if (Pred == ICmpInst::ICMP_EQ)
02729             return ConstantInt::getFalse(RHS->getContext());
02730           if (Pred == ICmpInst::ICMP_NE)
02731             return ConstantInt::getTrue(RHS->getContext());
02732         }
02733       }
02734       if (CIVal->isSignBit() && *CI2Val == 1) {
02735         if (Pred == ICmpInst::ICMP_UGT)
02736           return ConstantInt::getFalse(RHS->getContext());
02737         if (Pred == ICmpInst::ICMP_ULE)
02738           return ConstantInt::getTrue(RHS->getContext());
02739       }
02740     }
02741   }
02742 
02743   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
02744       LBO->getOperand(1) == RBO->getOperand(1)) {
02745     switch (LBO->getOpcode()) {
02746     default: break;
02747     case Instruction::UDiv:
02748     case Instruction::LShr:
02749       if (ICmpInst::isSigned(Pred))
02750         break;
02751       // fall-through
02752     case Instruction::SDiv:
02753     case Instruction::AShr:
02754       if (!LBO->isExact() || !RBO->isExact())
02755         break;
02756       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
02757                                       RBO->getOperand(0), Q, MaxRecurse-1))
02758         return V;
02759       break;
02760     case Instruction::Shl: {
02761       bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
02762       bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
02763       if (!NUW && !NSW)
02764         break;
02765       if (!NSW && ICmpInst::isSigned(Pred))
02766         break;
02767       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
02768                                       RBO->getOperand(0), Q, MaxRecurse-1))
02769         return V;
02770       break;
02771     }
02772     }
02773   }
02774 
02775   // Simplify comparisons involving max/min.
02776   Value *A, *B;
02777   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
02778   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
02779 
02780   // Signed variants on "max(a,b)>=a -> true".
02781   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
02782     if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
02783     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
02784     // We analyze this as smax(A, B) pred A.
02785     P = Pred;
02786   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
02787              (A == LHS || B == LHS)) {
02788     if (A != LHS) std::swap(A, B); // A pred smax(A, B).
02789     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
02790     // We analyze this as smax(A, B) swapped-pred A.
02791     P = CmpInst::getSwappedPredicate(Pred);
02792   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
02793              (A == RHS || B == RHS)) {
02794     if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
02795     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
02796     // We analyze this as smax(-A, -B) swapped-pred -A.
02797     // Note that we do not need to actually form -A or -B thanks to EqP.
02798     P = CmpInst::getSwappedPredicate(Pred);
02799   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
02800              (A == LHS || B == LHS)) {
02801     if (A != LHS) std::swap(A, B); // A pred smin(A, B).
02802     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
02803     // We analyze this as smax(-A, -B) pred -A.
02804     // Note that we do not need to actually form -A or -B thanks to EqP.
02805     P = Pred;
02806   }
02807   if (P != CmpInst::BAD_ICMP_PREDICATE) {
02808     // Cases correspond to "max(A, B) p A".
02809     switch (P) {
02810     default:
02811       break;
02812     case CmpInst::ICMP_EQ:
02813     case CmpInst::ICMP_SLE:
02814       // Equivalent to "A EqP B".  This may be the same as the condition tested
02815       // in the max/min; if so, we can just return that.
02816       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
02817         return V;
02818       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
02819         return V;
02820       // Otherwise, see if "A EqP B" simplifies.
02821       if (MaxRecurse)
02822         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
02823           return V;
02824       break;
02825     case CmpInst::ICMP_NE:
02826     case CmpInst::ICMP_SGT: {
02827       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
02828       // Equivalent to "A InvEqP B".  This may be the same as the condition
02829       // tested in the max/min; if so, we can just return that.
02830       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
02831         return V;
02832       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
02833         return V;
02834       // Otherwise, see if "A InvEqP B" simplifies.
02835       if (MaxRecurse)
02836         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
02837           return V;
02838       break;
02839     }
02840     case CmpInst::ICMP_SGE:
02841       // Always true.
02842       return getTrue(ITy);
02843     case CmpInst::ICMP_SLT:
02844       // Always false.
02845       return getFalse(ITy);
02846     }
02847   }
02848 
02849   // Unsigned variants on "max(a,b)>=a -> true".
02850   P = CmpInst::BAD_ICMP_PREDICATE;
02851   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
02852     if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
02853     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
02854     // We analyze this as umax(A, B) pred A.
02855     P = Pred;
02856   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
02857              (A == LHS || B == LHS)) {
02858     if (A != LHS) std::swap(A, B); // A pred umax(A, B).
02859     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
02860     // We analyze this as umax(A, B) swapped-pred A.
02861     P = CmpInst::getSwappedPredicate(Pred);
02862   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
02863              (A == RHS || B == RHS)) {
02864     if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
02865     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
02866     // We analyze this as umax(-A, -B) swapped-pred -A.
02867     // Note that we do not need to actually form -A or -B thanks to EqP.
02868     P = CmpInst::getSwappedPredicate(Pred);
02869   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
02870              (A == LHS || B == LHS)) {
02871     if (A != LHS) std::swap(A, B); // A pred umin(A, B).
02872     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
02873     // We analyze this as umax(-A, -B) pred -A.
02874     // Note that we do not need to actually form -A or -B thanks to EqP.
02875     P = Pred;
02876   }
02877   if (P != CmpInst::BAD_ICMP_PREDICATE) {
02878     // Cases correspond to "max(A, B) p A".
02879     switch (P) {
02880     default:
02881       break;
02882     case CmpInst::ICMP_EQ:
02883     case CmpInst::ICMP_ULE:
02884       // Equivalent to "A EqP B".  This may be the same as the condition tested
02885       // in the max/min; if so, we can just return that.
02886       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
02887         return V;
02888       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
02889         return V;
02890       // Otherwise, see if "A EqP B" simplifies.
02891       if (MaxRecurse)
02892         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
02893           return V;
02894       break;
02895     case CmpInst::ICMP_NE:
02896     case CmpInst::ICMP_UGT: {
02897       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
02898       // Equivalent to "A InvEqP B".  This may be the same as the condition
02899       // tested in the max/min; if so, we can just return that.
02900       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
02901         return V;
02902       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
02903         return V;
02904       // Otherwise, see if "A InvEqP B" simplifies.
02905       if (MaxRecurse)
02906         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
02907           return V;
02908       break;
02909     }
02910     case CmpInst::ICMP_UGE:
02911       // Always true.
02912       return getTrue(ITy);
02913     case CmpInst::ICMP_ULT:
02914       // Always false.
02915       return getFalse(ITy);
02916     }
02917   }
02918 
02919   // Variants on "max(x,y) >= min(x,z)".
02920   Value *C, *D;
02921   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
02922       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
02923       (A == C || A == D || B == C || B == D)) {
02924     // max(x, ?) pred min(x, ?).
02925     if (Pred == CmpInst::ICMP_SGE)
02926       // Always true.
02927       return getTrue(ITy);
02928     if (Pred == CmpInst::ICMP_SLT)
02929       // Always false.
02930       return getFalse(ITy);
02931   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
02932              match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
02933              (A == C || A == D || B == C || B == D)) {
02934     // min(x, ?) pred max(x, ?).
02935     if (Pred == CmpInst::ICMP_SLE)
02936       // Always true.
02937       return getTrue(ITy);
02938     if (Pred == CmpInst::ICMP_SGT)
02939       // Always false.
02940       return getFalse(ITy);
02941   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
02942              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
02943              (A == C || A == D || B == C || B == D)) {
02944     // max(x, ?) pred min(x, ?).
02945     if (Pred == CmpInst::ICMP_UGE)
02946       // Always true.
02947       return getTrue(ITy);
02948     if (Pred == CmpInst::ICMP_ULT)
02949       // Always false.
02950       return getFalse(ITy);
02951   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
02952              match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
02953              (A == C || A == D || B == C || B == D)) {
02954     // min(x, ?) pred max(x, ?).
02955     if (Pred == CmpInst::ICMP_ULE)
02956       // Always true.
02957       return getTrue(ITy);
02958     if (Pred == CmpInst::ICMP_UGT)
02959       // Always false.
02960       return getFalse(ITy);
02961   }
02962 
02963   // Simplify comparisons of related pointers using a powerful, recursive
02964   // GEP-walk when we have target data available..
02965   if (LHS->getType()->isPointerTy())
02966     if (Constant *C = computePointerICmp(Q.DL, Q.TLI, Pred, LHS, RHS))
02967       return C;
02968 
02969   if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
02970     if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
02971       if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
02972           GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
02973           (ICmpInst::isEquality(Pred) ||
02974            (GLHS->isInBounds() && GRHS->isInBounds() &&
02975             Pred == ICmpInst::getSignedPredicate(Pred)))) {
02976         // The bases are equal and the indices are constant.  Build a constant
02977         // expression GEP with the same indices and a null base pointer to see
02978         // what constant folding can make out of it.
02979         Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
02980         SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
02981         Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
02982 
02983         SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
02984         Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
02985         return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
02986       }
02987     }
02988   }
02989 
02990   // If a bit is known to be zero for A and known to be one for B,
02991   // then A and B cannot be equal.
02992   if (ICmpInst::isEquality(Pred)) {
02993     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
02994       uint32_t BitWidth = CI->getBitWidth();
02995       APInt LHSKnownZero(BitWidth, 0);
02996       APInt LHSKnownOne(BitWidth, 0);
02997       computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0, Q.AC,
02998                        Q.CxtI, Q.DT);
02999       const APInt &RHSVal = CI->getValue();
03000       if (((LHSKnownZero & RHSVal) != 0) || ((LHSKnownOne & ~RHSVal) != 0))
03001         return Pred == ICmpInst::ICMP_EQ
03002                    ? ConstantInt::getFalse(CI->getContext())
03003                    : ConstantInt::getTrue(CI->getContext());
03004     }
03005   }
03006 
03007   // If the comparison is with the result of a select instruction, check whether
03008   // comparing with either branch of the select always yields the same value.
03009   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
03010     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
03011       return V;
03012 
03013   // If the comparison is with the result of a phi instruction, check whether
03014   // doing the compare with each incoming phi value yields a common result.
03015   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
03016     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
03017       return V;
03018 
03019   return nullptr;
03020 }
03021 
03022 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
03023                               const DataLayout &DL,
03024                               const TargetLibraryInfo *TLI,
03025                               const DominatorTree *DT, AssumptionCache *AC,
03026                               Instruction *CxtI) {
03027   return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
03028                             RecursionLimit);
03029 }
03030 
03031 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
03032 /// fold the result.  If not, this returns null.
03033 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
03034                                const Query &Q, unsigned MaxRecurse) {
03035   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
03036   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
03037 
03038   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
03039     if (Constant *CRHS = dyn_cast<Constant>(RHS))
03040       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
03041 
03042     // If we have a constant, make sure it is on the RHS.
03043     std::swap(LHS, RHS);
03044     Pred = CmpInst::getSwappedPredicate(Pred);
03045   }
03046 
03047   // Fold trivial predicates.
03048   if (Pred == FCmpInst::FCMP_FALSE)
03049     return ConstantInt::get(GetCompareTy(LHS), 0);
03050   if (Pred == FCmpInst::FCMP_TRUE)
03051     return ConstantInt::get(GetCompareTy(LHS), 1);
03052 
03053   // fcmp pred x, undef  and  fcmp pred undef, x
03054   // fold to true if unordered, false if ordered
03055   if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
03056     // Choosing NaN for the undef will always make unordered comparison succeed
03057     // and ordered comparison fail.
03058     return ConstantInt::get(GetCompareTy(LHS), CmpInst::isUnordered(Pred));
03059   }
03060 
03061   // fcmp x,x -> true/false.  Not all compares are foldable.
03062   if (LHS == RHS) {
03063     if (CmpInst::isTrueWhenEqual(Pred))
03064       return ConstantInt::get(GetCompareTy(LHS), 1);
03065     if (CmpInst::isFalseWhenEqual(Pred))
03066       return ConstantInt::get(GetCompareTy(LHS), 0);
03067   }
03068 
03069   // Handle fcmp with constant RHS
03070   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
03071     // If the constant is a nan, see if we can fold the comparison based on it.
03072     if (CFP->getValueAPF().isNaN()) {
03073       if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
03074         return ConstantInt::getFalse(CFP->getContext());
03075       assert(FCmpInst::isUnordered(Pred) &&
03076              "Comparison must be either ordered or unordered!");
03077       // True if unordered.
03078       return ConstantInt::getTrue(CFP->getContext());
03079     }
03080     // Check whether the constant is an infinity.
03081     if (CFP->getValueAPF().isInfinity()) {
03082       if (CFP->getValueAPF().isNegative()) {
03083         switch (Pred) {
03084         case FCmpInst::FCMP_OLT:
03085           // No value is ordered and less than negative infinity.
03086           return ConstantInt::getFalse(CFP->getContext());
03087         case FCmpInst::FCMP_UGE:
03088           // All values are unordered with or at least negative infinity.
03089           return ConstantInt::getTrue(CFP->getContext());
03090         default:
03091           break;
03092         }
03093       } else {
03094         switch (Pred) {
03095         case FCmpInst::FCMP_OGT:
03096           // No value is ordered and greater than infinity.
03097           return ConstantInt::getFalse(CFP->getContext());
03098         case FCmpInst::FCMP_ULE:
03099           // All values are unordered with and at most infinity.
03100           return ConstantInt::getTrue(CFP->getContext());
03101         default:
03102           break;
03103         }
03104       }
03105     }
03106     if (CFP->getValueAPF().isZero()) {
03107       switch (Pred) {
03108       case FCmpInst::FCMP_UGE:
03109         if (CannotBeOrderedLessThanZero(LHS))
03110           return ConstantInt::getTrue(CFP->getContext());
03111         break;
03112       case FCmpInst::FCMP_OLT:
03113         // X < 0
03114         if (CannotBeOrderedLessThanZero(LHS))
03115           return ConstantInt::getFalse(CFP->getContext());
03116         break;
03117       default:
03118         break;
03119       }
03120     }
03121   }
03122 
03123   // If the comparison is with the result of a select instruction, check whether
03124   // comparing with either branch of the select always yields the same value.
03125   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
03126     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
03127       return V;
03128 
03129   // If the comparison is with the result of a phi instruction, check whether
03130   // doing the compare with each incoming phi value yields a common result.
03131   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
03132     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
03133       return V;
03134 
03135   return nullptr;
03136 }
03137 
03138 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
03139                               const DataLayout &DL,
03140                               const TargetLibraryInfo *TLI,
03141                               const DominatorTree *DT, AssumptionCache *AC,
03142                               const Instruction *CxtI) {
03143   return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
03144                             RecursionLimit);
03145 }
03146 
03147 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
03148 /// the result.  If not, this returns null.
03149 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
03150                                  Value *FalseVal, const Query &Q,
03151                                  unsigned MaxRecurse) {
03152   // select true, X, Y  -> X
03153   // select false, X, Y -> Y
03154   if (Constant *CB = dyn_cast<Constant>(CondVal)) {
03155     if (CB->isAllOnesValue())
03156       return TrueVal;
03157     if (CB->isNullValue())
03158       return FalseVal;
03159   }
03160 
03161   // select C, X, X -> X
03162   if (TrueVal == FalseVal)
03163     return TrueVal;
03164 
03165   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
03166     if (isa<Constant>(TrueVal))
03167       return TrueVal;
03168     return FalseVal;
03169   }
03170   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
03171     return FalseVal;
03172   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
03173     return TrueVal;
03174 
03175   const auto *ICI = dyn_cast<ICmpInst>(CondVal);
03176   unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
03177   if (ICI && BitWidth) {
03178     ICmpInst::Predicate Pred = ICI->getPredicate();
03179     APInt MinSignedValue = APInt::getSignBit(BitWidth);
03180     Value *X;
03181     const APInt *Y;
03182     bool TrueWhenUnset;
03183     bool IsBitTest = false;
03184     if (ICmpInst::isEquality(Pred) &&
03185         match(ICI->getOperand(0), m_And(m_Value(X), m_APInt(Y))) &&
03186         match(ICI->getOperand(1), m_Zero())) {
03187       IsBitTest = true;
03188       TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
03189     } else if (Pred == ICmpInst::ICMP_SLT &&
03190                match(ICI->getOperand(1), m_Zero())) {
03191       X = ICI->getOperand(0);
03192       Y = &MinSignedValue;
03193       IsBitTest = true;
03194       TrueWhenUnset = false;
03195     } else if (Pred == ICmpInst::ICMP_SGT &&
03196                match(ICI->getOperand(1), m_AllOnes())) {
03197       X = ICI->getOperand(0);
03198       Y = &MinSignedValue;
03199       IsBitTest = true;
03200       TrueWhenUnset = true;
03201     }
03202     if (IsBitTest) {
03203       const APInt *C;
03204       // (X & Y) == 0 ? X & ~Y : X  --> X
03205       // (X & Y) != 0 ? X & ~Y : X  --> X & ~Y
03206       if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
03207           *Y == ~*C)
03208         return TrueWhenUnset ? FalseVal : TrueVal;
03209       // (X & Y) == 0 ? X : X & ~Y  --> X & ~Y
03210       // (X & Y) != 0 ? X : X & ~Y  --> X
03211       if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
03212           *Y == ~*C)
03213         return TrueWhenUnset ? FalseVal : TrueVal;
03214 
03215       if (Y->isPowerOf2()) {
03216         // (X & Y) == 0 ? X | Y : X  --> X | Y
03217         // (X & Y) != 0 ? X | Y : X  --> X
03218         if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
03219             *Y == *C)
03220           return TrueWhenUnset ? TrueVal : FalseVal;
03221         // (X & Y) == 0 ? X : X | Y  --> X
03222         // (X & Y) != 0 ? X : X | Y  --> X | Y
03223         if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
03224             *Y == *C)
03225           return TrueWhenUnset ? TrueVal : FalseVal;
03226       }
03227     }
03228   }
03229 
03230   return nullptr;
03231 }
03232 
03233 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
03234                                 const DataLayout &DL,
03235                                 const TargetLibraryInfo *TLI,
03236                                 const DominatorTree *DT, AssumptionCache *AC,
03237                                 const Instruction *CxtI) {
03238   return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
03239                               Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
03240 }
03241 
03242 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
03243 /// fold the result.  If not, this returns null.
03244 static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
03245   // The type of the GEP pointer operand.
03246   PointerType *PtrTy = cast<PointerType>(Ops[0]->getType()->getScalarType());
03247   unsigned AS = PtrTy->getAddressSpace();
03248 
03249   // getelementptr P -> P.
03250   if (Ops.size() == 1)
03251     return Ops[0];
03252 
03253   // Compute the (pointer) type returned by the GEP instruction.
03254   Type *LastType =
03255       GetElementPtrInst::getIndexedType(PtrTy->getElementType(), Ops.slice(1));
03256   Type *GEPTy = PointerType::get(LastType, AS);
03257   if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
03258     GEPTy = VectorType::get(GEPTy, VT->getNumElements());
03259 
03260   if (isa<UndefValue>(Ops[0]))
03261     return UndefValue::get(GEPTy);
03262 
03263   if (Ops.size() == 2) {
03264     // getelementptr P, 0 -> P.
03265     if (match(Ops[1], m_Zero()))
03266       return Ops[0];
03267 
03268     Type *Ty = PtrTy->getElementType();
03269     if (Ty->isSized()) {
03270       Value *P;
03271       uint64_t C;
03272       uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
03273       // getelementptr P, N -> P if P points to a type of zero size.
03274       if (TyAllocSize == 0)
03275         return Ops[0];
03276 
03277       // The following transforms are only safe if the ptrtoint cast
03278       // doesn't truncate the pointers.
03279       if (Ops[1]->getType()->getScalarSizeInBits() ==
03280           Q.DL.getPointerSizeInBits(AS)) {
03281         auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
03282           if (match(P, m_Zero()))
03283             return Constant::getNullValue(GEPTy);
03284           Value *Temp;
03285           if (match(P, m_PtrToInt(m_Value(Temp))))
03286             if (Temp->getType() == GEPTy)
03287               return Temp;
03288           return nullptr;
03289         };
03290 
03291         // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
03292         if (TyAllocSize == 1 &&
03293             match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
03294           if (Value *R = PtrToIntOrZero(P))
03295             return R;
03296 
03297         // getelementptr V, (ashr (sub P, V), C) -> Q
03298         // if P points to a type of size 1 << C.
03299         if (match(Ops[1],
03300                   m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
03301                          m_ConstantInt(C))) &&
03302             TyAllocSize == 1ULL << C)
03303           if (Value *R = PtrToIntOrZero(P))
03304             return R;
03305 
03306         // getelementptr V, (sdiv (sub P, V), C) -> Q
03307         // if P points to a type of size C.
03308         if (match(Ops[1],
03309                   m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
03310                          m_SpecificInt(TyAllocSize))))
03311           if (Value *R = PtrToIntOrZero(P))
03312             return R;
03313       }
03314     }
03315   }
03316 
03317   // Check to see if this is constant foldable.
03318   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
03319     if (!isa<Constant>(Ops[i]))
03320       return nullptr;
03321 
03322   return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
03323 }
03324 
03325 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout &DL,
03326                              const TargetLibraryInfo *TLI,
03327                              const DominatorTree *DT, AssumptionCache *AC,
03328                              const Instruction *CxtI) {
03329   return ::SimplifyGEPInst(Ops, Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
03330 }
03331 
03332 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
03333 /// can fold the result.  If not, this returns null.
03334 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
03335                                       ArrayRef<unsigned> Idxs, const Query &Q,
03336                                       unsigned) {
03337   if (Constant *CAgg = dyn_cast<Constant>(Agg))
03338     if (Constant *CVal = dyn_cast<Constant>(Val))
03339       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
03340 
03341   // insertvalue x, undef, n -> x
03342   if (match(Val, m_Undef()))
03343     return Agg;
03344 
03345   // insertvalue x, (extractvalue y, n), n
03346   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
03347     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
03348         EV->getIndices() == Idxs) {
03349       // insertvalue undef, (extractvalue y, n), n -> y
03350       if (match(Agg, m_Undef()))
03351         return EV->getAggregateOperand();
03352 
03353       // insertvalue y, (extractvalue y, n), n -> y
03354       if (Agg == EV->getAggregateOperand())
03355         return Agg;
03356     }
03357 
03358   return nullptr;
03359 }
03360 
03361 Value *llvm::SimplifyInsertValueInst(
03362     Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
03363     const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC,
03364     const Instruction *CxtI) {
03365   return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, AC, CxtI),
03366                                    RecursionLimit);
03367 }
03368 
03369 /// SimplifyPHINode - See if we can fold the given phi.  If not, returns null.
03370 static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
03371   // If all of the PHI's incoming values are the same then replace the PHI node
03372   // with the common value.
03373   Value *CommonValue = nullptr;
03374   bool HasUndefInput = false;
03375   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
03376     Value *Incoming = PN->getIncomingValue(i);
03377     // If the incoming value is the phi node itself, it can safely be skipped.
03378     if (Incoming == PN) continue;
03379     if (isa<UndefValue>(Incoming)) {
03380       // Remember that we saw an undef value, but otherwise ignore them.
03381       HasUndefInput = true;
03382       continue;
03383     }
03384     if (CommonValue && Incoming != CommonValue)
03385       return nullptr;  // Not the same, bail out.
03386     CommonValue = Incoming;
03387   }
03388 
03389   // If CommonValue is null then all of the incoming values were either undef or
03390   // equal to the phi node itself.
03391   if (!CommonValue)
03392     return UndefValue::get(PN->getType());
03393 
03394   // If we have a PHI node like phi(X, undef, X), where X is defined by some
03395   // instruction, we cannot return X as the result of the PHI node unless it
03396   // dominates the PHI block.
03397   if (HasUndefInput)
03398     return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
03399 
03400   return CommonValue;
03401 }
03402 
03403 static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
03404   if (Constant *C = dyn_cast<Constant>(Op))
03405     return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.DL, Q.TLI);
03406 
03407   return nullptr;
03408 }
03409 
03410 Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout &DL,
03411                                const TargetLibraryInfo *TLI,
03412                                const DominatorTree *DT, AssumptionCache *AC,
03413                                const Instruction *CxtI) {
03414   return ::SimplifyTruncInst(Op, Ty, Query(DL, TLI, DT, AC, CxtI),
03415                              RecursionLimit);
03416 }
03417 
03418 //=== Helper functions for higher up the class hierarchy.
03419 
03420 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
03421 /// fold the result.  If not, this returns null.
03422 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
03423                             const Query &Q, unsigned MaxRecurse) {
03424   switch (Opcode) {
03425   case Instruction::Add:
03426     return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
03427                            Q, MaxRecurse);
03428   case Instruction::FAdd:
03429     return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
03430 
03431   case Instruction::Sub:
03432     return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
03433                            Q, MaxRecurse);
03434   case Instruction::FSub:
03435     return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
03436 
03437   case Instruction::Mul:  return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
03438   case Instruction::FMul:
03439     return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
03440   case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
03441   case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
03442   case Instruction::FDiv:
03443       return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
03444   case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
03445   case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
03446   case Instruction::FRem:
03447       return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
03448   case Instruction::Shl:
03449     return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
03450                            Q, MaxRecurse);
03451   case Instruction::LShr:
03452     return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
03453   case Instruction::AShr:
03454     return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
03455   case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
03456   case Instruction::Or:  return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
03457   case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
03458   default:
03459     if (Constant *CLHS = dyn_cast<Constant>(LHS))
03460       if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
03461         Constant *COps[] = {CLHS, CRHS};
03462         return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.DL,
03463                                         Q.TLI);
03464       }
03465 
03466     // If the operation is associative, try some generic simplifications.
03467     if (Instruction::isAssociative(Opcode))
03468       if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
03469         return V;
03470 
03471     // If the operation is with the result of a select instruction check whether
03472     // operating on either branch of the select always yields the same value.
03473     if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
03474       if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
03475         return V;
03476 
03477     // If the operation is with the result of a phi instruction, check whether
03478     // operating on all incoming values of the phi always yields the same value.
03479     if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
03480       if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
03481         return V;
03482 
03483     return nullptr;
03484   }
03485 }
03486 
03487 /// SimplifyFPBinOp - Given operands for a BinaryOperator, see if we can
03488 /// fold the result.  If not, this returns null.
03489 /// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
03490 /// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
03491 static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
03492                               const FastMathFlags &FMF, const Query &Q,
03493                               unsigned MaxRecurse) {
03494   switch (Opcode) {
03495   case Instruction::FAdd:
03496     return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
03497   case Instruction::FSub:
03498     return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
03499   case Instruction::FMul:
03500     return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
03501   default:
03502     return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
03503   }
03504 }
03505 
03506 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
03507                            const DataLayout &DL, const TargetLibraryInfo *TLI,
03508                            const DominatorTree *DT, AssumptionCache *AC,
03509                            const Instruction *CxtI) {
03510   return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
03511                          RecursionLimit);
03512 }
03513 
03514 Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
03515                              const FastMathFlags &FMF, const DataLayout &DL,
03516                              const TargetLibraryInfo *TLI,
03517                              const DominatorTree *DT, AssumptionCache *AC,
03518                              const Instruction *CxtI) {
03519   return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, AC, CxtI),
03520                            RecursionLimit);
03521 }
03522 
03523 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
03524 /// fold the result.
03525 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
03526                               const Query &Q, unsigned MaxRecurse) {
03527   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
03528     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
03529   return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
03530 }
03531 
03532 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
03533                              const DataLayout &DL, const TargetLibraryInfo *TLI,
03534                              const DominatorTree *DT, AssumptionCache *AC,
03535                              const Instruction *CxtI) {
03536   return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
03537                            RecursionLimit);
03538 }
03539 
03540 static bool IsIdempotent(Intrinsic::ID ID) {
03541   switch (ID) {
03542   default: return false;
03543 
03544   // Unary idempotent: f(f(x)) = f(x)
03545   case Intrinsic::fabs:
03546   case Intrinsic::floor:
03547   case Intrinsic::ceil:
03548   case Intrinsic::trunc:
03549   case Intrinsic::rint:
03550   case Intrinsic::nearbyint:
03551   case Intrinsic::round:
03552     return true;
03553   }
03554 }
03555 
03556 template <typename IterTy>
03557 static Value *SimplifyIntrinsic(Intrinsic::ID IID, IterTy ArgBegin, IterTy ArgEnd,
03558                                 const Query &Q, unsigned MaxRecurse) {
03559   // Perform idempotent optimizations
03560   if (!IsIdempotent(IID))
03561     return nullptr;
03562 
03563   // Unary Ops
03564   if (std::distance(ArgBegin, ArgEnd) == 1)
03565     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
03566       if (II->getIntrinsicID() == IID)
03567         return II;
03568 
03569   return nullptr;
03570 }
03571 
03572 template <typename IterTy>
03573 static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
03574                            const Query &Q, unsigned MaxRecurse) {
03575   Type *Ty = V->getType();
03576   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
03577     Ty = PTy->getElementType();
03578   FunctionType *FTy = cast<FunctionType>(Ty);
03579 
03580   // call undef -> undef
03581   if (isa<UndefValue>(V))
03582     return UndefValue::get(FTy->getReturnType());
03583 
03584   Function *F = dyn_cast<Function>(V);
03585   if (!F)
03586     return nullptr;
03587 
03588   if (unsigned IID = F->getIntrinsicID())
03589     if (Value *Ret =
03590         SimplifyIntrinsic((Intrinsic::ID) IID, ArgBegin, ArgEnd, Q, MaxRecurse))
03591       return Ret;
03592 
03593   if (!canConstantFoldCallTo(F))
03594     return nullptr;
03595 
03596   SmallVector<Constant *, 4> ConstantArgs;
03597   ConstantArgs.reserve(ArgEnd - ArgBegin);
03598   for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
03599     Constant *C = dyn_cast<Constant>(*I);
03600     if (!C)
03601       return nullptr;
03602     ConstantArgs.push_back(C);
03603   }
03604 
03605   return ConstantFoldCall(F, ConstantArgs, Q.TLI);
03606 }
03607 
03608 Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
03609                           User::op_iterator ArgEnd, const DataLayout &DL,
03610                           const TargetLibraryInfo *TLI, const DominatorTree *DT,
03611                           AssumptionCache *AC, const Instruction *CxtI) {
03612   return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AC, CxtI),
03613                         RecursionLimit);
03614 }
03615 
03616 Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
03617                           const DataLayout &DL, const TargetLibraryInfo *TLI,
03618                           const DominatorTree *DT, AssumptionCache *AC,
03619                           const Instruction *CxtI) {
03620   return ::SimplifyCall(V, Args.begin(), Args.end(),
03621                         Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
03622 }
03623 
03624 /// SimplifyInstruction - See if we can compute a simplified version of this
03625 /// instruction.  If not, this returns null.
03626 Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
03627                                  const TargetLibraryInfo *TLI,
03628                                  const DominatorTree *DT, AssumptionCache *AC) {
03629   Value *Result;
03630 
03631   switch (I->getOpcode()) {
03632   default:
03633     Result = ConstantFoldInstruction(I, DL, TLI);
03634     break;
03635   case Instruction::FAdd:
03636     Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
03637                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
03638     break;
03639   case Instruction::Add:
03640     Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
03641                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
03642                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
03643                              TLI, DT, AC, I);
03644     break;
03645   case Instruction::FSub:
03646     Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
03647                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
03648     break;
03649   case Instruction::Sub:
03650     Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
03651                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
03652                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
03653                              TLI, DT, AC, I);
03654     break;
03655   case Instruction::FMul:
03656     Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
03657                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
03658     break;
03659   case Instruction::Mul:
03660     Result =
03661         SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
03662     break;
03663   case Instruction::SDiv:
03664     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
03665                               AC, I);
03666     break;
03667   case Instruction::UDiv:
03668     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
03669                               AC, I);
03670     break;
03671   case Instruction::FDiv:
03672     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
03673                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
03674     break;
03675   case Instruction::SRem:
03676     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
03677                               AC, I);
03678     break;
03679   case Instruction::URem:
03680     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
03681                               AC, I);
03682     break;
03683   case Instruction::FRem:
03684     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
03685                               I->getFastMathFlags(), DL, TLI, DT, AC, I);
03686     break;
03687   case Instruction::Shl:
03688     Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
03689                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
03690                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
03691                              TLI, DT, AC, I);
03692     break;
03693   case Instruction::LShr:
03694     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
03695                               cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
03696                               AC, I);
03697     break;
03698   case Instruction::AShr:
03699     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
03700                               cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
03701                               AC, I);
03702     break;
03703   case Instruction::And:
03704     Result =
03705         SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
03706     break;
03707   case Instruction::Or:
03708     Result =
03709         SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
03710     break;
03711   case Instruction::Xor:
03712     Result =
03713         SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
03714     break;
03715   case Instruction::ICmp:
03716     Result =
03717         SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
03718                          I->getOperand(1), DL, TLI, DT, AC, I);
03719     break;
03720   case Instruction::FCmp:
03721     Result =
03722         SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), I->getOperand(0),
03723                          I->getOperand(1), DL, TLI, DT, AC, I);
03724     break;
03725   case Instruction::Select:
03726     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
03727                                 I->getOperand(2), DL, TLI, DT, AC, I);
03728     break;
03729   case Instruction::GetElementPtr: {
03730     SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
03731     Result = SimplifyGEPInst(Ops, DL, TLI, DT, AC, I);
03732     break;
03733   }
03734   case Instruction::InsertValue: {
03735     InsertValueInst *IV = cast<InsertValueInst>(I);
03736     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
03737                                      IV->getInsertedValueOperand(),
03738                                      IV->getIndices(), DL, TLI, DT, AC, I);
03739     break;
03740   }
03741   case Instruction::PHI:
03742     Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
03743     break;
03744   case Instruction::Call: {
03745     CallSite CS(cast<CallInst>(I));
03746     Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
03747                           TLI, DT, AC, I);
03748     break;
03749   }
03750   case Instruction::Trunc:
03751     Result =
03752         SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT, AC, I);
03753     break;
03754   }
03755 
03756   /// If called on unreachable code, the above logic may report that the
03757   /// instruction simplified to itself.  Make life easier for users by
03758   /// detecting that case here, returning a safe value instead.
03759   return Result == I ? UndefValue::get(I->getType()) : Result;
03760 }
03761 
03762 /// \brief Implementation of recursive simplification through an instructions
03763 /// uses.
03764 ///
03765 /// This is the common implementation of the recursive simplification routines.
03766 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
03767 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
03768 /// instructions to process and attempt to simplify it using
03769 /// InstructionSimplify.
03770 ///
03771 /// This routine returns 'true' only when *it* simplifies something. The passed
03772 /// in simplified value does not count toward this.
03773 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
03774                                               const TargetLibraryInfo *TLI,
03775                                               const DominatorTree *DT,
03776                                               AssumptionCache *AC) {
03777   bool Simplified = false;
03778   SmallSetVector<Instruction *, 8> Worklist;
03779   const DataLayout &DL = I->getModule()->getDataLayout();
03780 
03781   // If we have an explicit value to collapse to, do that round of the
03782   // simplification loop by hand initially.
03783   if (SimpleV) {
03784     for (User *U : I->users())
03785       if (U != I)
03786         Worklist.insert(cast<Instruction>(U));
03787 
03788     // Replace the instruction with its simplified value.
03789     I->replaceAllUsesWith(SimpleV);
03790 
03791     // Gracefully handle edge cases where the instruction is not wired into any
03792     // parent block.
03793     if (I->getParent())
03794       I->eraseFromParent();
03795   } else {
03796     Worklist.insert(I);
03797   }
03798 
03799   // Note that we must test the size on each iteration, the worklist can grow.
03800   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
03801     I = Worklist[Idx];
03802 
03803     // See if this instruction simplifies.
03804     SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
03805     if (!SimpleV)
03806       continue;
03807 
03808     Simplified = true;
03809 
03810     // Stash away all the uses of the old instruction so we can check them for
03811     // recursive simplifications after a RAUW. This is cheaper than checking all
03812     // uses of To on the recursive step in most cases.
03813     for (User *U : I->users())
03814       Worklist.insert(cast<Instruction>(U));
03815 
03816     // Replace the instruction with its simplified value.
03817     I->replaceAllUsesWith(SimpleV);
03818 
03819     // Gracefully handle edge cases where the instruction is not wired into any
03820     // parent block.
03821     if (I->getParent())
03822       I->eraseFromParent();
03823   }
03824   return Simplified;
03825 }
03826 
03827 bool llvm::recursivelySimplifyInstruction(Instruction *I,
03828                                           const TargetLibraryInfo *TLI,
03829                                           const DominatorTree *DT,
03830                                           AssumptionCache *AC) {
03831   return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
03832 }
03833 
03834 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
03835                                          const TargetLibraryInfo *TLI,
03836                                          const DominatorTree *DT,
03837                                          AssumptionCache *AC) {
03838   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
03839   assert(SimpleV && "Must provide a simplified value.");
03840   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
03841 }