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