LLVM API Documentation

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