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