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