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