LLVM  mainline
ValueTracking.cpp
Go to the documentation of this file.
00001 //===- ValueTracking.cpp - Walk computations to compute properties --------===//
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 contains routines that help analyze properties that chains of
00011 // computations have.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Analysis/ValueTracking.h"
00016 #include "llvm/ADT/Optional.h"
00017 #include "llvm/ADT/SmallPtrSet.h"
00018 #include "llvm/Analysis/AssumptionCache.h"
00019 #include "llvm/Analysis/InstructionSimplify.h"
00020 #include "llvm/Analysis/MemoryBuiltins.h"
00021 #include "llvm/Analysis/LoopInfo.h"
00022 #include "llvm/IR/CallSite.h"
00023 #include "llvm/IR/ConstantRange.h"
00024 #include "llvm/IR/Constants.h"
00025 #include "llvm/IR/DataLayout.h"
00026 #include "llvm/IR/Dominators.h"
00027 #include "llvm/IR/GetElementPtrTypeIterator.h"
00028 #include "llvm/IR/GlobalAlias.h"
00029 #include "llvm/IR/GlobalVariable.h"
00030 #include "llvm/IR/Instructions.h"
00031 #include "llvm/IR/IntrinsicInst.h"
00032 #include "llvm/IR/LLVMContext.h"
00033 #include "llvm/IR/Metadata.h"
00034 #include "llvm/IR/Operator.h"
00035 #include "llvm/IR/PatternMatch.h"
00036 #include "llvm/IR/Statepoint.h"
00037 #include "llvm/Support/Debug.h"
00038 #include "llvm/Support/MathExtras.h"
00039 #include <cstring>
00040 using namespace llvm;
00041 using namespace llvm::PatternMatch;
00042 
00043 const unsigned MaxDepth = 6;
00044 
00045 /// Enable an experimental feature to leverage information about dominating
00046 /// conditions to compute known bits.  The individual options below control how
00047 /// hard we search.  The defaults are chosen to be fairly aggressive.  If you
00048 /// run into compile time problems when testing, scale them back and report
00049 /// your findings.
00050 static cl::opt<bool> EnableDomConditions("value-tracking-dom-conditions",
00051                                          cl::Hidden, cl::init(false));
00052 
00053 // This is expensive, so we only do it for the top level query value.
00054 // (TODO: evaluate cost vs profit, consider higher thresholds)
00055 static cl::opt<unsigned> DomConditionsMaxDepth("dom-conditions-max-depth",
00056                                                cl::Hidden, cl::init(1));
00057 
00058 /// How many dominating blocks should be scanned looking for dominating
00059 /// conditions?
00060 static cl::opt<unsigned> DomConditionsMaxDomBlocks("dom-conditions-dom-blocks",
00061                                                    cl::Hidden,
00062                                                    cl::init(20));
00063 
00064 // Controls the number of uses of the value searched for possible
00065 // dominating comparisons.
00066 static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
00067                                               cl::Hidden, cl::init(20));
00068 
00069 // If true, don't consider only compares whose only use is a branch.
00070 static cl::opt<bool> DomConditionsSingleCmpUse("dom-conditions-single-cmp-use",
00071                                                cl::Hidden, cl::init(false));
00072 
00073 /// Returns the bitwidth of the given scalar or pointer type (if unknown returns
00074 /// 0). For vector types, returns the element type's bitwidth.
00075 static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
00076   if (unsigned BitWidth = Ty->getScalarSizeInBits())
00077     return BitWidth;
00078 
00079   return DL.getPointerTypeSizeInBits(Ty);
00080 }
00081 
00082 // Many of these functions have internal versions that take an assumption
00083 // exclusion set. This is because of the potential for mutual recursion to
00084 // cause computeKnownBits to repeatedly visit the same assume intrinsic. The
00085 // classic case of this is assume(x = y), which will attempt to determine
00086 // bits in x from bits in y, which will attempt to determine bits in y from
00087 // bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
00088 // isKnownNonZero, which calls computeKnownBits and ComputeSignBit and
00089 // isKnownToBeAPowerOfTwo (all of which can call computeKnownBits), and so on.
00090 typedef SmallPtrSet<const Value *, 8> ExclInvsSet;
00091 
00092 namespace {
00093 // Simplifying using an assume can only be done in a particular control-flow
00094 // context (the context instruction provides that context). If an assume and
00095 // the context instruction are not in the same block then the DT helps in
00096 // figuring out if we can use it.
00097 struct Query {
00098   ExclInvsSet ExclInvs;
00099   const DataLayout &DL;
00100   AssumptionCache *AC;
00101   const Instruction *CxtI;
00102   const DominatorTree *DT;
00103 
00104   Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
00105         const DominatorTree *DT)
00106       : DL(DL), AC(AC), CxtI(CxtI), DT(DT) {}
00107 
00108   Query(const Query &Q, const Value *NewExcl)
00109       : ExclInvs(Q.ExclInvs), DL(Q.DL), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT) {
00110     ExclInvs.insert(NewExcl);
00111   }
00112 };
00113 } // end anonymous namespace
00114 
00115 // Given the provided Value and, potentially, a context instruction, return
00116 // the preferred context instruction (if any).
00117 static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
00118   // If we've been provided with a context instruction, then use that (provided
00119   // it has been inserted).
00120   if (CxtI && CxtI->getParent())
00121     return CxtI;
00122 
00123   // If the value is really an already-inserted instruction, then use that.
00124   CxtI = dyn_cast<Instruction>(V);
00125   if (CxtI && CxtI->getParent())
00126     return CxtI;
00127 
00128   return nullptr;
00129 }
00130 
00131 static void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
00132                              unsigned Depth, const Query &Q);
00133 
00134 void llvm::computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
00135                             const DataLayout &DL, unsigned Depth,
00136                             AssumptionCache *AC, const Instruction *CxtI,
00137                             const DominatorTree *DT) {
00138   ::computeKnownBits(V, KnownZero, KnownOne, Depth,
00139                      Query(DL, AC, safeCxtI(V, CxtI), DT));
00140 }
00141 
00142 bool llvm::haveNoCommonBitsSet(Value *LHS, Value *RHS, const DataLayout &DL,
00143                                AssumptionCache *AC, const Instruction *CxtI,
00144                                const DominatorTree *DT) {
00145   assert(LHS->getType() == RHS->getType() &&
00146          "LHS and RHS should have the same type");
00147   assert(LHS->getType()->isIntOrIntVectorTy() &&
00148          "LHS and RHS should be integers");
00149   IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
00150   APInt LHSKnownZero(IT->getBitWidth(), 0), LHSKnownOne(IT->getBitWidth(), 0);
00151   APInt RHSKnownZero(IT->getBitWidth(), 0), RHSKnownOne(IT->getBitWidth(), 0);
00152   computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, 0, AC, CxtI, DT);
00153   computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, 0, AC, CxtI, DT);
00154   return (LHSKnownZero | RHSKnownZero).isAllOnesValue();
00155 }
00156 
00157 static void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
00158                            unsigned Depth, const Query &Q);
00159 
00160 void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
00161                           const DataLayout &DL, unsigned Depth,
00162                           AssumptionCache *AC, const Instruction *CxtI,
00163                           const DominatorTree *DT) {
00164   ::ComputeSignBit(V, KnownZero, KnownOne, Depth,
00165                    Query(DL, AC, safeCxtI(V, CxtI), DT));
00166 }
00167 
00168 static bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
00169                                    const Query &Q);
00170 
00171 bool llvm::isKnownToBeAPowerOfTwo(Value *V, const DataLayout &DL, bool OrZero,
00172                                   unsigned Depth, AssumptionCache *AC,
00173                                   const Instruction *CxtI,
00174                                   const DominatorTree *DT) {
00175   return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
00176                                   Query(DL, AC, safeCxtI(V, CxtI), DT));
00177 }
00178 
00179 static bool isKnownNonZero(Value *V, unsigned Depth, const Query &Q);
00180 
00181 bool llvm::isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
00182                           AssumptionCache *AC, const Instruction *CxtI,
00183                           const DominatorTree *DT) {
00184   return ::isKnownNonZero(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
00185 }
00186 
00187 bool llvm::isKnownNonNegative(Value *V, const DataLayout &DL, unsigned Depth,
00188                               AssumptionCache *AC, const Instruction *CxtI,
00189                               const DominatorTree *DT) {
00190   bool NonNegative, Negative;
00191   ComputeSignBit(V, NonNegative, Negative, DL, Depth, AC, CxtI, DT);
00192   return NonNegative;
00193 }
00194 
00195 static bool isKnownNonEqual(Value *V1, Value *V2, const Query &Q);
00196 
00197 bool llvm::isKnownNonEqual(Value *V1, Value *V2, const DataLayout &DL,
00198                           AssumptionCache *AC, const Instruction *CxtI,
00199                           const DominatorTree *DT) {
00200   return ::isKnownNonEqual(V1, V2, Query(DL, AC,
00201                                          safeCxtI(V1, safeCxtI(V2, CxtI)),
00202                                          DT));
00203 }
00204 
00205 static bool MaskedValueIsZero(Value *V, const APInt &Mask, unsigned Depth,
00206                               const Query &Q);
00207 
00208 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
00209                              unsigned Depth, AssumptionCache *AC,
00210                              const Instruction *CxtI, const DominatorTree *DT) {
00211   return ::MaskedValueIsZero(V, Mask, Depth,
00212                              Query(DL, AC, safeCxtI(V, CxtI), DT));
00213 }
00214 
00215 static unsigned ComputeNumSignBits(Value *V, unsigned Depth, const Query &Q);
00216 
00217 unsigned llvm::ComputeNumSignBits(Value *V, const DataLayout &DL,
00218                                   unsigned Depth, AssumptionCache *AC,
00219                                   const Instruction *CxtI,
00220                                   const DominatorTree *DT) {
00221   return ::ComputeNumSignBits(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
00222 }
00223 
00224 static void computeKnownBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
00225                                    APInt &KnownZero, APInt &KnownOne,
00226                                    APInt &KnownZero2, APInt &KnownOne2,
00227                                    unsigned Depth, const Query &Q) {
00228   if (!Add) {
00229     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
00230       // We know that the top bits of C-X are clear if X contains less bits
00231       // than C (i.e. no wrap-around can happen).  For example, 20-X is
00232       // positive if we can prove that X is >= 0 and < 16.
00233       if (!CLHS->getValue().isNegative()) {
00234         unsigned BitWidth = KnownZero.getBitWidth();
00235         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
00236         // NLZ can't be BitWidth with no sign bit
00237         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
00238         computeKnownBits(Op1, KnownZero2, KnownOne2, Depth + 1, Q);
00239 
00240         // If all of the MaskV bits are known to be zero, then we know the
00241         // output top bits are zero, because we now know that the output is
00242         // from [0-C].
00243         if ((KnownZero2 & MaskV) == MaskV) {
00244           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
00245           // Top bits known zero.
00246           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
00247         }
00248       }
00249     }
00250   }
00251 
00252   unsigned BitWidth = KnownZero.getBitWidth();
00253 
00254   // If an initial sequence of bits in the result is not needed, the
00255   // corresponding bits in the operands are not needed.
00256   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
00257   computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, Depth + 1, Q);
00258   computeKnownBits(Op1, KnownZero2, KnownOne2, Depth + 1, Q);
00259 
00260   // Carry in a 1 for a subtract, rather than a 0.
00261   APInt CarryIn(BitWidth, 0);
00262   if (!Add) {
00263     // Sum = LHS + ~RHS + 1
00264     std::swap(KnownZero2, KnownOne2);
00265     CarryIn.setBit(0);
00266   }
00267 
00268   APInt PossibleSumZero = ~LHSKnownZero + ~KnownZero2 + CarryIn;
00269   APInt PossibleSumOne = LHSKnownOne + KnownOne2 + CarryIn;
00270 
00271   // Compute known bits of the carry.
00272   APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnownZero ^ KnownZero2);
00273   APInt CarryKnownOne = PossibleSumOne ^ LHSKnownOne ^ KnownOne2;
00274 
00275   // Compute set of known bits (where all three relevant bits are known).
00276   APInt LHSKnown = LHSKnownZero | LHSKnownOne;
00277   APInt RHSKnown = KnownZero2 | KnownOne2;
00278   APInt CarryKnown = CarryKnownZero | CarryKnownOne;
00279   APInt Known = LHSKnown & RHSKnown & CarryKnown;
00280 
00281   assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
00282          "known bits of sum differ");
00283 
00284   // Compute known bits of the result.
00285   KnownZero = ~PossibleSumOne & Known;
00286   KnownOne = PossibleSumOne & Known;
00287 
00288   // Are we still trying to solve for the sign bit?
00289   if (!Known.isNegative()) {
00290     if (NSW) {
00291       // Adding two non-negative numbers, or subtracting a negative number from
00292       // a non-negative one, can't wrap into negative.
00293       if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
00294         KnownZero |= APInt::getSignBit(BitWidth);
00295       // Adding two negative numbers, or subtracting a non-negative number from
00296       // a negative one, can't wrap into non-negative.
00297       else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
00298         KnownOne |= APInt::getSignBit(BitWidth);
00299     }
00300   }
00301 }
00302 
00303 static void computeKnownBitsMul(Value *Op0, Value *Op1, bool NSW,
00304                                 APInt &KnownZero, APInt &KnownOne,
00305                                 APInt &KnownZero2, APInt &KnownOne2,
00306                                 unsigned Depth, const Query &Q) {
00307   unsigned BitWidth = KnownZero.getBitWidth();
00308   computeKnownBits(Op1, KnownZero, KnownOne, Depth + 1, Q);
00309   computeKnownBits(Op0, KnownZero2, KnownOne2, Depth + 1, Q);
00310 
00311   bool isKnownNegative = false;
00312   bool isKnownNonNegative = false;
00313   // If the multiplication is known not to overflow, compute the sign bit.
00314   if (NSW) {
00315     if (Op0 == Op1) {
00316       // The product of a number with itself is non-negative.
00317       isKnownNonNegative = true;
00318     } else {
00319       bool isKnownNonNegativeOp1 = KnownZero.isNegative();
00320       bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
00321       bool isKnownNegativeOp1 = KnownOne.isNegative();
00322       bool isKnownNegativeOp0 = KnownOne2.isNegative();
00323       // The product of two numbers with the same sign is non-negative.
00324       isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
00325         (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
00326       // The product of a negative number and a non-negative number is either
00327       // negative or zero.
00328       if (!isKnownNonNegative)
00329         isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
00330                            isKnownNonZero(Op0, Depth, Q)) ||
00331                           (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
00332                            isKnownNonZero(Op1, Depth, Q));
00333     }
00334   }
00335 
00336   // If low bits are zero in either operand, output low known-0 bits.
00337   // Also compute a conservative estimate for high known-0 bits.
00338   // More trickiness is possible, but this is sufficient for the
00339   // interesting case of alignment computation.
00340   KnownOne.clearAllBits();
00341   unsigned TrailZ = KnownZero.countTrailingOnes() +
00342                     KnownZero2.countTrailingOnes();
00343   unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
00344                              KnownZero2.countLeadingOnes(),
00345                              BitWidth) - BitWidth;
00346 
00347   TrailZ = std::min(TrailZ, BitWidth);
00348   LeadZ = std::min(LeadZ, BitWidth);
00349   KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
00350               APInt::getHighBitsSet(BitWidth, LeadZ);
00351 
00352   // Only make use of no-wrap flags if we failed to compute the sign bit
00353   // directly.  This matters if the multiplication always overflows, in
00354   // which case we prefer to follow the result of the direct computation,
00355   // though as the program is invoking undefined behaviour we can choose
00356   // whatever we like here.
00357   if (isKnownNonNegative && !KnownOne.isNegative())
00358     KnownZero.setBit(BitWidth - 1);
00359   else if (isKnownNegative && !KnownZero.isNegative())
00360     KnownOne.setBit(BitWidth - 1);
00361 }
00362 
00363 void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
00364                                              APInt &KnownZero,
00365                                              APInt &KnownOne) {
00366   unsigned BitWidth = KnownZero.getBitWidth();
00367   unsigned NumRanges = Ranges.getNumOperands() / 2;
00368   assert(NumRanges >= 1);
00369 
00370   KnownZero.setAllBits();
00371   KnownOne.setAllBits();
00372 
00373   for (unsigned i = 0; i < NumRanges; ++i) {
00374     ConstantInt *Lower =
00375         mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
00376     ConstantInt *Upper =
00377         mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
00378     ConstantRange Range(Lower->getValue(), Upper->getValue());
00379 
00380     // The first CommonPrefixBits of all values in Range are equal.
00381     unsigned CommonPrefixBits =
00382         (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
00383 
00384     APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
00385     KnownOne &= Range.getUnsignedMax() & Mask;
00386     KnownZero &= ~Range.getUnsignedMax() & Mask;
00387   }
00388 }
00389 
00390 static bool isEphemeralValueOf(Instruction *I, const Value *E) {
00391   SmallVector<const Value *, 16> WorkSet(1, I);
00392   SmallPtrSet<const Value *, 32> Visited;
00393   SmallPtrSet<const Value *, 16> EphValues;
00394 
00395   // The instruction defining an assumption's condition itself is always
00396   // considered ephemeral to that assumption (even if it has other
00397   // non-ephemeral users). See r246696's test case for an example.
00398   if (std::find(I->op_begin(), I->op_end(), E) != I->op_end())
00399     return true;
00400 
00401   while (!WorkSet.empty()) {
00402     const Value *V = WorkSet.pop_back_val();
00403     if (!Visited.insert(V).second)
00404       continue;
00405 
00406     // If all uses of this value are ephemeral, then so is this value.
00407     if (std::all_of(V->user_begin(), V->user_end(),
00408                     [&](const User *U) { return EphValues.count(U); })) {
00409       if (V == E)
00410         return true;
00411 
00412       EphValues.insert(V);
00413       if (const User *U = dyn_cast<User>(V))
00414         for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
00415              J != JE; ++J) {
00416           if (isSafeToSpeculativelyExecute(*J))
00417             WorkSet.push_back(*J);
00418         }
00419     }
00420   }
00421 
00422   return false;
00423 }
00424 
00425 // Is this an intrinsic that cannot be speculated but also cannot trap?
00426 static bool isAssumeLikeIntrinsic(const Instruction *I) {
00427   if (const CallInst *CI = dyn_cast<CallInst>(I))
00428     if (Function *F = CI->getCalledFunction())
00429       switch (F->getIntrinsicID()) {
00430       default: break;
00431       // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
00432       case Intrinsic::assume:
00433       case Intrinsic::dbg_declare:
00434       case Intrinsic::dbg_value:
00435       case Intrinsic::invariant_start:
00436       case Intrinsic::invariant_end:
00437       case Intrinsic::lifetime_start:
00438       case Intrinsic::lifetime_end:
00439       case Intrinsic::objectsize:
00440       case Intrinsic::ptr_annotation:
00441       case Intrinsic::var_annotation:
00442         return true;
00443       }
00444 
00445   return false;
00446 }
00447 
00448 static bool isValidAssumeForContext(Value *V, const Instruction *CxtI,
00449                                     const DominatorTree *DT) {
00450   Instruction *Inv = cast<Instruction>(V);
00451 
00452   // There are two restrictions on the use of an assume:
00453   //  1. The assume must dominate the context (or the control flow must
00454   //     reach the assume whenever it reaches the context).
00455   //  2. The context must not be in the assume's set of ephemeral values
00456   //     (otherwise we will use the assume to prove that the condition
00457   //     feeding the assume is trivially true, thus causing the removal of
00458   //     the assume).
00459 
00460   if (DT) {
00461     if (DT->dominates(Inv, CxtI)) {
00462       return true;
00463     } else if (Inv->getParent() == CxtI->getParent()) {
00464       // The context comes first, but they're both in the same block. Make sure
00465       // there is nothing in between that might interrupt the control flow.
00466       for (BasicBlock::const_iterator I =
00467              std::next(BasicBlock::const_iterator(CxtI)),
00468                                       IE(Inv); I != IE; ++I)
00469         if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
00470           return false;
00471 
00472       return !isEphemeralValueOf(Inv, CxtI);
00473     }
00474 
00475     return false;
00476   }
00477 
00478   // When we don't have a DT, we do a limited search...
00479   if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
00480     return true;
00481   } else if (Inv->getParent() == CxtI->getParent()) {
00482     // Search forward from the assume until we reach the context (or the end
00483     // of the block); the common case is that the assume will come first.
00484     for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
00485          IE = Inv->getParent()->end(); I != IE; ++I)
00486       if (&*I == CxtI)
00487         return true;
00488 
00489     // The context must come first...
00490     for (BasicBlock::const_iterator I =
00491            std::next(BasicBlock::const_iterator(CxtI)),
00492                                     IE(Inv); I != IE; ++I)
00493       if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
00494         return false;
00495 
00496     return !isEphemeralValueOf(Inv, CxtI);
00497   }
00498 
00499   return false;
00500 }
00501 
00502 bool llvm::isValidAssumeForContext(const Instruction *I,
00503                                    const Instruction *CxtI,
00504                                    const DominatorTree *DT) {
00505   return ::isValidAssumeForContext(const_cast<Instruction *>(I), CxtI, DT);
00506 }
00507 
00508 template<typename LHS, typename RHS>
00509 inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
00510                         CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
00511 m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
00512   return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
00513 }
00514 
00515 template<typename LHS, typename RHS>
00516 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
00517                         BinaryOp_match<RHS, LHS, Instruction::And>>
00518 m_c_And(const LHS &L, const RHS &R) {
00519   return m_CombineOr(m_And(L, R), m_And(R, L));
00520 }
00521 
00522 template<typename LHS, typename RHS>
00523 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Or>,
00524                         BinaryOp_match<RHS, LHS, Instruction::Or>>
00525 m_c_Or(const LHS &L, const RHS &R) {
00526   return m_CombineOr(m_Or(L, R), m_Or(R, L));
00527 }
00528 
00529 template<typename LHS, typename RHS>
00530 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Xor>,
00531                         BinaryOp_match<RHS, LHS, Instruction::Xor>>
00532 m_c_Xor(const LHS &L, const RHS &R) {
00533   return m_CombineOr(m_Xor(L, R), m_Xor(R, L));
00534 }
00535 
00536 /// Compute known bits in 'V' under the assumption that the condition 'Cmp' is
00537 /// true (at the context instruction.)  This is mostly a utility function for
00538 /// the prototype dominating conditions reasoning below.
00539 static void computeKnownBitsFromTrueCondition(Value *V, ICmpInst *Cmp,
00540                                               APInt &KnownZero,
00541                                               APInt &KnownOne,
00542                                               unsigned Depth, const Query &Q) {
00543   Value *LHS = Cmp->getOperand(0);
00544   Value *RHS = Cmp->getOperand(1);
00545   // TODO: We could potentially be more aggressive here.  This would be worth
00546   // evaluating.  If we can, explore commoning this code with the assume
00547   // handling logic.
00548   if (LHS != V && RHS != V)
00549     return;
00550 
00551   const unsigned BitWidth = KnownZero.getBitWidth();
00552 
00553   switch (Cmp->getPredicate()) {
00554   default:
00555     // We know nothing from this condition
00556     break;
00557   // TODO: implement unsigned bound from below (known one bits)
00558   // TODO: common condition check implementations with assumes
00559   // TODO: implement other patterns from assume (e.g. V & B == A)
00560   case ICmpInst::ICMP_SGT:
00561     if (LHS == V) {
00562       APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
00563       computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, Depth + 1, Q);
00564       if (KnownOneTemp.isAllOnesValue() || KnownZeroTemp.isNegative()) {
00565         // We know that the sign bit is zero.
00566         KnownZero |= APInt::getSignBit(BitWidth);
00567       }
00568     }
00569     break;
00570   case ICmpInst::ICMP_EQ:
00571     {
00572       APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
00573       if (LHS == V)
00574         computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, Depth + 1, Q);
00575       else if (RHS == V)
00576         computeKnownBits(LHS, KnownZeroTemp, KnownOneTemp, Depth + 1, Q);
00577       else
00578         llvm_unreachable("missing use?");
00579       KnownZero |= KnownZeroTemp;
00580       KnownOne |= KnownOneTemp;
00581     }
00582     break;
00583   case ICmpInst::ICMP_ULE:
00584     if (LHS == V) {
00585       APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
00586       computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, Depth + 1, Q);
00587       // The known zero bits carry over
00588       unsigned SignBits = KnownZeroTemp.countLeadingOnes();
00589       KnownZero |= APInt::getHighBitsSet(BitWidth, SignBits);
00590     }
00591     break;
00592   case ICmpInst::ICMP_ULT:
00593     if (LHS == V) {
00594       APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
00595       computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, Depth + 1, Q);
00596       // Whatever high bits in rhs are zero are known to be zero (if rhs is a
00597       // power of 2, then one more).
00598       unsigned SignBits = KnownZeroTemp.countLeadingOnes();
00599       if (isKnownToBeAPowerOfTwo(RHS, false, Depth + 1, Query(Q, Cmp)))
00600         SignBits++;
00601       KnownZero |= APInt::getHighBitsSet(BitWidth, SignBits);
00602     }
00603     break;
00604   };
00605 }
00606 
00607 /// Compute known bits in 'V' from conditions which are known to be true along
00608 /// all paths leading to the context instruction.  In particular, look for
00609 /// cases where one branch of an interesting condition dominates the context
00610 /// instruction.  This does not do general dataflow.
00611 /// NOTE: This code is EXPERIMENTAL and currently off by default.
00612 static void computeKnownBitsFromDominatingCondition(Value *V, APInt &KnownZero,
00613                                                     APInt &KnownOne,
00614                                                     unsigned Depth,
00615                                                     const Query &Q) {
00616   // Need both the dominator tree and the query location to do anything useful
00617   if (!Q.DT || !Q.CxtI)
00618     return;
00619   Instruction *Cxt = const_cast<Instruction *>(Q.CxtI);
00620   // The context instruction might be in a statically unreachable block.  If
00621   // so, asking dominator queries may yield suprising results.  (e.g. the block
00622   // may not have a dom tree node)
00623   if (!Q.DT->isReachableFromEntry(Cxt->getParent()))
00624     return;
00625 
00626   // Avoid useless work
00627   if (auto VI = dyn_cast<Instruction>(V))
00628     if (VI->getParent() == Cxt->getParent())
00629       return;
00630 
00631   // Note: We currently implement two options.  It's not clear which of these
00632   // will survive long term, we need data for that.
00633   // Option 1 - Try walking the dominator tree looking for conditions which
00634   // might apply.  This works well for local conditions (loop guards, etc..),
00635   // but not as well for things far from the context instruction (presuming a
00636   // low max blocks explored).  If we can set an high enough limit, this would
00637   // be all we need.
00638   // Option 2 - We restrict out search to those conditions which are uses of
00639   // the value we're interested in.  This is independent of dom structure,
00640   // but is slightly less powerful without looking through lots of use chains.
00641   // It does handle conditions far from the context instruction (e.g. early
00642   // function exits on entry) really well though.
00643 
00644   // Option 1 - Search the dom tree
00645   unsigned NumBlocksExplored = 0;
00646   BasicBlock *Current = Cxt->getParent();
00647   while (true) {
00648     // Stop searching if we've gone too far up the chain
00649     if (NumBlocksExplored >= DomConditionsMaxDomBlocks)
00650       break;
00651     NumBlocksExplored++;
00652 
00653     if (!Q.DT->getNode(Current)->getIDom())
00654       break;
00655     Current = Q.DT->getNode(Current)->getIDom()->getBlock();
00656     if (!Current)
00657       // found function entry
00658       break;
00659 
00660     BranchInst *BI = dyn_cast<BranchInst>(Current->getTerminator());
00661     if (!BI || BI->isUnconditional())
00662       continue;
00663     ICmpInst *Cmp = dyn_cast<ICmpInst>(BI->getCondition());
00664     if (!Cmp)
00665       continue;
00666 
00667     // We're looking for conditions that are guaranteed to hold at the context
00668     // instruction.  Finding a condition where one path dominates the context
00669     // isn't enough because both the true and false cases could merge before
00670     // the context instruction we're actually interested in.  Instead, we need
00671     // to ensure that the taken *edge* dominates the context instruction.  We
00672     // know that the edge must be reachable since we started from a reachable
00673     // block.
00674     BasicBlock *BB0 = BI->getSuccessor(0);
00675     BasicBlockEdge Edge(BI->getParent(), BB0);
00676     if (!Edge.isSingleEdge() || !Q.DT->dominates(Edge, Q.CxtI->getParent()))
00677       continue;
00678 
00679     computeKnownBitsFromTrueCondition(V, Cmp, KnownZero, KnownOne, Depth, Q);
00680   }
00681 
00682   // Option 2 - Search the other uses of V
00683   unsigned NumUsesExplored = 0;
00684   for (auto U : V->users()) {
00685     // Avoid massive lists
00686     if (NumUsesExplored >= DomConditionsMaxUses)
00687       break;
00688     NumUsesExplored++;
00689     // Consider only compare instructions uniquely controlling a branch
00690     ICmpInst *Cmp = dyn_cast<ICmpInst>(U);
00691     if (!Cmp)
00692       continue;
00693 
00694     if (DomConditionsSingleCmpUse && !Cmp->hasOneUse())
00695       continue;
00696 
00697     for (auto *CmpU : Cmp->users()) {
00698       BranchInst *BI = dyn_cast<BranchInst>(CmpU);
00699       if (!BI || BI->isUnconditional())
00700         continue;
00701       // We're looking for conditions that are guaranteed to hold at the
00702       // context instruction.  Finding a condition where one path dominates
00703       // the context isn't enough because both the true and false cases could
00704       // merge before the context instruction we're actually interested in.
00705       // Instead, we need to ensure that the taken *edge* dominates the context
00706       // instruction. 
00707       BasicBlock *BB0 = BI->getSuccessor(0);
00708       BasicBlockEdge Edge(BI->getParent(), BB0);
00709       if (!Edge.isSingleEdge() || !Q.DT->dominates(Edge, Q.CxtI->getParent()))
00710         continue;
00711 
00712       computeKnownBitsFromTrueCondition(V, Cmp, KnownZero, KnownOne, Depth, Q);
00713     }
00714   }
00715 }
00716 
00717 static void computeKnownBitsFromAssume(Value *V, APInt &KnownZero,
00718                                        APInt &KnownOne, unsigned Depth,
00719                                        const Query &Q) {
00720   // Use of assumptions is context-sensitive. If we don't have a context, we
00721   // cannot use them!
00722   if (!Q.AC || !Q.CxtI)
00723     return;
00724 
00725   unsigned BitWidth = KnownZero.getBitWidth();
00726 
00727   for (auto &AssumeVH : Q.AC->assumptions()) {
00728     if (!AssumeVH)
00729       continue;
00730     CallInst *I = cast<CallInst>(AssumeVH);
00731     assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
00732            "Got assumption for the wrong function!");
00733     if (Q.ExclInvs.count(I))
00734       continue;
00735 
00736     // Warning: This loop can end up being somewhat performance sensetive.
00737     // We're running this loop for once for each value queried resulting in a
00738     // runtime of ~O(#assumes * #values).
00739 
00740     assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
00741            "must be an assume intrinsic");
00742 
00743     Value *Arg = I->getArgOperand(0);
00744 
00745     if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
00746       assert(BitWidth == 1 && "assume operand is not i1?");
00747       KnownZero.clearAllBits();
00748       KnownOne.setAllBits();
00749       return;
00750     }
00751 
00752     // The remaining tests are all recursive, so bail out if we hit the limit.
00753     if (Depth == MaxDepth)
00754       continue;
00755 
00756     Value *A, *B;
00757     auto m_V = m_CombineOr(m_Specific(V),
00758                            m_CombineOr(m_PtrToInt(m_Specific(V)),
00759                            m_BitCast(m_Specific(V))));
00760 
00761     CmpInst::Predicate Pred;
00762     ConstantInt *C;
00763     // assume(v = a)
00764     if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
00765         Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
00766       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00767       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
00768       KnownZero |= RHSKnownZero;
00769       KnownOne  |= RHSKnownOne;
00770     // assume(v & b = a)
00771     } else if (match(Arg,
00772                      m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
00773                Pred == ICmpInst::ICMP_EQ &&
00774                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
00775       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00776       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
00777       APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
00778       computeKnownBits(B, MaskKnownZero, MaskKnownOne, Depth+1, Query(Q, I));
00779 
00780       // For those bits in the mask that are known to be one, we can propagate
00781       // known bits from the RHS to V.
00782       KnownZero |= RHSKnownZero & MaskKnownOne;
00783       KnownOne  |= RHSKnownOne  & MaskKnownOne;
00784     // assume(~(v & b) = a)
00785     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
00786                                    m_Value(A))) &&
00787                Pred == ICmpInst::ICMP_EQ &&
00788                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
00789       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00790       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
00791       APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
00792       computeKnownBits(B, MaskKnownZero, MaskKnownOne, Depth+1, Query(Q, I));
00793 
00794       // For those bits in the mask that are known to be one, we can propagate
00795       // inverted known bits from the RHS to V.
00796       KnownZero |= RHSKnownOne  & MaskKnownOne;
00797       KnownOne  |= RHSKnownZero & MaskKnownOne;
00798     // assume(v | b = a)
00799     } else if (match(Arg,
00800                      m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
00801                Pred == ICmpInst::ICMP_EQ &&
00802                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
00803       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00804       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
00805       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
00806       computeKnownBits(B, BKnownZero, BKnownOne, Depth+1, Query(Q, I));
00807 
00808       // For those bits in B that are known to be zero, we can propagate known
00809       // bits from the RHS to V.
00810       KnownZero |= RHSKnownZero & BKnownZero;
00811       KnownOne  |= RHSKnownOne  & BKnownZero;
00812     // assume(~(v | b) = a)
00813     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
00814                                    m_Value(A))) &&
00815                Pred == ICmpInst::ICMP_EQ &&
00816                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
00817       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00818       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
00819       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
00820       computeKnownBits(B, BKnownZero, BKnownOne, Depth+1, Query(Q, I));
00821 
00822       // For those bits in B that are known to be zero, we can propagate
00823       // inverted known bits from the RHS to V.
00824       KnownZero |= RHSKnownOne  & BKnownZero;
00825       KnownOne  |= RHSKnownZero & BKnownZero;
00826     // assume(v ^ b = a)
00827     } else if (match(Arg,
00828                      m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
00829                Pred == ICmpInst::ICMP_EQ &&
00830                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
00831       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00832       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
00833       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
00834       computeKnownBits(B, BKnownZero, BKnownOne, Depth+1, Query(Q, I));
00835 
00836       // For those bits in B that are known to be zero, we can propagate known
00837       // bits from the RHS to V. For those bits in B that are known to be one,
00838       // we can propagate inverted known bits from the RHS to V.
00839       KnownZero |= RHSKnownZero & BKnownZero;
00840       KnownOne  |= RHSKnownOne  & BKnownZero;
00841       KnownZero |= RHSKnownOne  & BKnownOne;
00842       KnownOne  |= RHSKnownZero & BKnownOne;
00843     // assume(~(v ^ b) = a)
00844     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
00845                                    m_Value(A))) &&
00846                Pred == ICmpInst::ICMP_EQ &&
00847                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
00848       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00849       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
00850       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
00851       computeKnownBits(B, BKnownZero, BKnownOne, Depth+1, Query(Q, I));
00852 
00853       // For those bits in B that are known to be zero, we can propagate
00854       // inverted known bits from the RHS to V. For those bits in B that are
00855       // known to be one, we can propagate known bits from the RHS to V.
00856       KnownZero |= RHSKnownOne  & BKnownZero;
00857       KnownOne  |= RHSKnownZero & BKnownZero;
00858       KnownZero |= RHSKnownZero & BKnownOne;
00859       KnownOne  |= RHSKnownOne  & BKnownOne;
00860     // assume(v << c = a)
00861     } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
00862                                    m_Value(A))) &&
00863                Pred == ICmpInst::ICMP_EQ &&
00864                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
00865       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00866       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
00867       // For those bits in RHS that are known, we can propagate them to known
00868       // bits in V shifted to the right by C.
00869       KnownZero |= RHSKnownZero.lshr(C->getZExtValue());
00870       KnownOne  |= RHSKnownOne.lshr(C->getZExtValue());
00871     // assume(~(v << c) = a)
00872     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
00873                                    m_Value(A))) &&
00874                Pred == ICmpInst::ICMP_EQ &&
00875                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
00876       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00877       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
00878       // For those bits in RHS that are known, we can propagate them inverted
00879       // to known bits in V shifted to the right by C.
00880       KnownZero |= RHSKnownOne.lshr(C->getZExtValue());
00881       KnownOne  |= RHSKnownZero.lshr(C->getZExtValue());
00882     // assume(v >> c = a)
00883     } else if (match(Arg,
00884                      m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
00885                                                 m_AShr(m_V, m_ConstantInt(C))),
00886                               m_Value(A))) &&
00887                Pred == ICmpInst::ICMP_EQ &&
00888                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
00889       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00890       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
00891       // For those bits in RHS that are known, we can propagate them to known
00892       // bits in V shifted to the right by C.
00893       KnownZero |= RHSKnownZero << C->getZExtValue();
00894       KnownOne  |= RHSKnownOne  << C->getZExtValue();
00895     // assume(~(v >> c) = a)
00896     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_CombineOr(
00897                                              m_LShr(m_V, m_ConstantInt(C)),
00898                                              m_AShr(m_V, m_ConstantInt(C)))),
00899                                    m_Value(A))) &&
00900                Pred == ICmpInst::ICMP_EQ &&
00901                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
00902       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00903       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
00904       // For those bits in RHS that are known, we can propagate them inverted
00905       // to known bits in V shifted to the right by C.
00906       KnownZero |= RHSKnownOne  << C->getZExtValue();
00907       KnownOne  |= RHSKnownZero << C->getZExtValue();
00908     // assume(v >=_s c) where c is non-negative
00909     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
00910                Pred == ICmpInst::ICMP_SGE &&
00911                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
00912       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00913       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
00914 
00915       if (RHSKnownZero.isNegative()) {
00916         // We know that the sign bit is zero.
00917         KnownZero |= APInt::getSignBit(BitWidth);
00918       }
00919     // assume(v >_s c) where c is at least -1.
00920     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
00921                Pred == ICmpInst::ICMP_SGT &&
00922                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
00923       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00924       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
00925 
00926       if (RHSKnownOne.isAllOnesValue() || RHSKnownZero.isNegative()) {
00927         // We know that the sign bit is zero.
00928         KnownZero |= APInt::getSignBit(BitWidth);
00929       }
00930     // assume(v <=_s c) where c is negative
00931     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
00932                Pred == ICmpInst::ICMP_SLE &&
00933                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
00934       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00935       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
00936 
00937       if (RHSKnownOne.isNegative()) {
00938         // We know that the sign bit is one.
00939         KnownOne |= APInt::getSignBit(BitWidth);
00940       }
00941     // assume(v <_s c) where c is non-positive
00942     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
00943                Pred == ICmpInst::ICMP_SLT &&
00944                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
00945       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00946       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
00947 
00948       if (RHSKnownZero.isAllOnesValue() || RHSKnownOne.isNegative()) {
00949         // We know that the sign bit is one.
00950         KnownOne |= APInt::getSignBit(BitWidth);
00951       }
00952     // assume(v <=_u c)
00953     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
00954                Pred == ICmpInst::ICMP_ULE &&
00955                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
00956       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00957       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
00958 
00959       // Whatever high bits in c are zero are known to be zero.
00960       KnownZero |=
00961         APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
00962     // assume(v <_u c)
00963     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
00964                Pred == ICmpInst::ICMP_ULT &&
00965                isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
00966       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00967       computeKnownBits(A, RHSKnownZero, RHSKnownOne, Depth+1, Query(Q, I));
00968 
00969       // Whatever high bits in c are zero are known to be zero (if c is a power
00970       // of 2, then one more).
00971       if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
00972         KnownZero |=
00973           APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()+1);
00974       else
00975         KnownZero |=
00976           APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
00977     }
00978   }
00979 }
00980 
00981 // Compute known bits from a shift operator, including those with a
00982 // non-constant shift amount. KnownZero and KnownOne are the outputs of this
00983 // function. KnownZero2 and KnownOne2 are pre-allocated temporaries with the
00984 // same bit width as KnownZero and KnownOne. KZF and KOF are operator-specific
00985 // functors that, given the known-zero or known-one bits respectively, and a
00986 // shift amount, compute the implied known-zero or known-one bits of the shift
00987 // operator's result respectively for that shift amount. The results from calling
00988 // KZF and KOF are conservatively combined for all permitted shift amounts.
00989 template <typename KZFunctor, typename KOFunctor>
00990 static void computeKnownBitsFromShiftOperator(Operator *I,
00991               APInt &KnownZero, APInt &KnownOne,
00992               APInt &KnownZero2, APInt &KnownOne2,
00993               unsigned Depth, const Query &Q, KZFunctor KZF, KOFunctor KOF) {
00994   unsigned BitWidth = KnownZero.getBitWidth();
00995 
00996   if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
00997     unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
00998 
00999     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
01000     KnownZero = KZF(KnownZero, ShiftAmt);
01001     KnownOne  = KOF(KnownOne, ShiftAmt);
01002     return;
01003   }
01004 
01005   computeKnownBits(I->getOperand(1), KnownZero, KnownOne, Depth + 1, Q);
01006 
01007   // Note: We cannot use KnownZero.getLimitedValue() here, because if
01008   // BitWidth > 64 and any upper bits are known, we'll end up returning the
01009   // limit value (which implies all bits are known).
01010   uint64_t ShiftAmtKZ = KnownZero.zextOrTrunc(64).getZExtValue();
01011   uint64_t ShiftAmtKO = KnownOne.zextOrTrunc(64).getZExtValue();
01012 
01013   // It would be more-clearly correct to use the two temporaries for this
01014   // calculation. Reusing the APInts here to prevent unnecessary allocations.
01015   KnownZero.clearAllBits(), KnownOne.clearAllBits();
01016 
01017   // If we know the shifter operand is nonzero, we can sometimes infer more
01018   // known bits. However this is expensive to compute, so be lazy about it and
01019   // only compute it when absolutely necessary.
01020   Optional<bool> ShifterOperandIsNonZero;
01021 
01022   // Early exit if we can't constrain any well-defined shift amount.
01023   if (!(ShiftAmtKZ & (BitWidth - 1)) && !(ShiftAmtKO & (BitWidth - 1))) {
01024     ShifterOperandIsNonZero =
01025         isKnownNonZero(I->getOperand(1), Depth + 1, Q);
01026     if (!*ShifterOperandIsNonZero)
01027       return;
01028   }
01029 
01030   computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
01031 
01032   KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
01033   for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
01034     // Combine the shifted known input bits only for those shift amounts
01035     // compatible with its known constraints.
01036     if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
01037       continue;
01038     if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
01039       continue;
01040     // If we know the shifter is nonzero, we may be able to infer more known
01041     // bits. This check is sunk down as far as possible to avoid the expensive
01042     // call to isKnownNonZero if the cheaper checks above fail.
01043     if (ShiftAmt == 0) {
01044       if (!ShifterOperandIsNonZero.hasValue())
01045         ShifterOperandIsNonZero =
01046             isKnownNonZero(I->getOperand(1), Depth + 1, Q);
01047       if (*ShifterOperandIsNonZero)
01048         continue;
01049     }
01050 
01051     KnownZero &= KZF(KnownZero2, ShiftAmt);
01052     KnownOne  &= KOF(KnownOne2, ShiftAmt);
01053   }
01054 
01055   // If there are no compatible shift amounts, then we've proven that the shift
01056   // amount must be >= the BitWidth, and the result is undefined. We could
01057   // return anything we'd like, but we need to make sure the sets of known bits
01058   // stay disjoint (it should be better for some other code to actually
01059   // propagate the undef than to pick a value here using known bits).
01060   if ((KnownZero & KnownOne) != 0)
01061     KnownZero.clearAllBits(), KnownOne.clearAllBits();
01062 }
01063 
01064 static void computeKnownBitsFromOperator(Operator *I, APInt &KnownZero,
01065                                          APInt &KnownOne, unsigned Depth,
01066                                          const Query &Q) {
01067   unsigned BitWidth = KnownZero.getBitWidth();
01068 
01069   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
01070   switch (I->getOpcode()) {
01071   default: break;
01072   case Instruction::Load:
01073     if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
01074       computeKnownBitsFromRangeMetadata(*MD, KnownZero, KnownOne);
01075     break;
01076   case Instruction::And: {
01077     // If either the LHS or the RHS are Zero, the result is zero.
01078     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, Depth + 1, Q);
01079     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
01080 
01081     // Output known-1 bits are only known if set in both the LHS & RHS.
01082     KnownOne &= KnownOne2;
01083     // Output known-0 are known to be clear if zero in either the LHS | RHS.
01084     KnownZero |= KnownZero2;
01085 
01086     // and(x, add (x, -1)) is a common idiom that always clears the low bit;
01087     // here we handle the more general case of adding any odd number by
01088     // matching the form add(x, add(x, y)) where y is odd.
01089     // TODO: This could be generalized to clearing any bit set in y where the
01090     // following bit is known to be unset in y.
01091     Value *Y = nullptr;
01092     if (match(I->getOperand(0), m_Add(m_Specific(I->getOperand(1)),
01093                                       m_Value(Y))) ||
01094         match(I->getOperand(1), m_Add(m_Specific(I->getOperand(0)),
01095                                       m_Value(Y)))) {
01096       APInt KnownZero3(BitWidth, 0), KnownOne3(BitWidth, 0);
01097       computeKnownBits(Y, KnownZero3, KnownOne3, Depth + 1, Q);
01098       if (KnownOne3.countTrailingOnes() > 0)
01099         KnownZero |= APInt::getLowBitsSet(BitWidth, 1);
01100     }
01101     break;
01102   }
01103   case Instruction::Or: {
01104     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, Depth + 1, Q);
01105     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
01106 
01107     // Output known-0 bits are only known if clear in both the LHS & RHS.
01108     KnownZero &= KnownZero2;
01109     // Output known-1 are known to be set if set in either the LHS | RHS.
01110     KnownOne |= KnownOne2;
01111     break;
01112   }
01113   case Instruction::Xor: {
01114     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, Depth + 1, Q);
01115     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
01116 
01117     // Output known-0 bits are known if clear or set in both the LHS & RHS.
01118     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
01119     // Output known-1 are known to be set if set in only one of the LHS, RHS.
01120     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
01121     KnownZero = KnownZeroOut;
01122     break;
01123   }
01124   case Instruction::Mul: {
01125     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
01126     computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, KnownZero,
01127                         KnownOne, KnownZero2, KnownOne2, Depth, Q);
01128     break;
01129   }
01130   case Instruction::UDiv: {
01131     // For the purposes of computing leading zeros we can conservatively
01132     // treat a udiv as a logical right shift by the power of 2 known to
01133     // be less than the denominator.
01134     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
01135     unsigned LeadZ = KnownZero2.countLeadingOnes();
01136 
01137     KnownOne2.clearAllBits();
01138     KnownZero2.clearAllBits();
01139     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, Depth + 1, Q);
01140     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
01141     if (RHSUnknownLeadingOnes != BitWidth)
01142       LeadZ = std::min(BitWidth,
01143                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
01144 
01145     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
01146     break;
01147   }
01148   case Instruction::Select:
01149     computeKnownBits(I->getOperand(2), KnownZero, KnownOne, Depth + 1, Q);
01150     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, Depth + 1, Q);
01151 
01152     // Only known if known in both the LHS and RHS.
01153     KnownOne &= KnownOne2;
01154     KnownZero &= KnownZero2;
01155     break;
01156   case Instruction::FPTrunc:
01157   case Instruction::FPExt:
01158   case Instruction::FPToUI:
01159   case Instruction::FPToSI:
01160   case Instruction::SIToFP:
01161   case Instruction::UIToFP:
01162     break; // Can't work with floating point.
01163   case Instruction::PtrToInt:
01164   case Instruction::IntToPtr:
01165   case Instruction::AddrSpaceCast: // Pointers could be different sizes.
01166     // FALL THROUGH and handle them the same as zext/trunc.
01167   case Instruction::ZExt:
01168   case Instruction::Trunc: {
01169     Type *SrcTy = I->getOperand(0)->getType();
01170 
01171     unsigned SrcBitWidth;
01172     // Note that we handle pointer operands here because of inttoptr/ptrtoint
01173     // which fall through here.
01174     SrcBitWidth = Q.DL.getTypeSizeInBits(SrcTy->getScalarType());
01175 
01176     assert(SrcBitWidth && "SrcBitWidth can't be zero");
01177     KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
01178     KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
01179     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
01180     KnownZero = KnownZero.zextOrTrunc(BitWidth);
01181     KnownOne = KnownOne.zextOrTrunc(BitWidth);
01182     // Any top bits are known to be zero.
01183     if (BitWidth > SrcBitWidth)
01184       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
01185     break;
01186   }
01187   case Instruction::BitCast: {
01188     Type *SrcTy = I->getOperand(0)->getType();
01189     if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy() ||
01190          SrcTy->isFloatingPointTy()) &&
01191         // TODO: For now, not handling conversions like:
01192         // (bitcast i64 %x to <2 x i32>)
01193         !I->getType()->isVectorTy()) {
01194       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
01195       break;
01196     }
01197     break;
01198   }
01199   case Instruction::SExt: {
01200     // Compute the bits in the result that are not present in the input.
01201     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
01202 
01203     KnownZero = KnownZero.trunc(SrcBitWidth);
01204     KnownOne = KnownOne.trunc(SrcBitWidth);
01205     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
01206     KnownZero = KnownZero.zext(BitWidth);
01207     KnownOne = KnownOne.zext(BitWidth);
01208 
01209     // If the sign bit of the input is known set or clear, then we know the
01210     // top bits of the result.
01211     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
01212       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
01213     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
01214       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
01215     break;
01216   }
01217   case Instruction::Shl: {
01218     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
01219     auto KZF = [BitWidth](const APInt &KnownZero, unsigned ShiftAmt) {
01220       return (KnownZero << ShiftAmt) |
01221              APInt::getLowBitsSet(BitWidth, ShiftAmt); // Low bits known 0.
01222     };
01223 
01224     auto KOF = [BitWidth](const APInt &KnownOne, unsigned ShiftAmt) {
01225       return KnownOne << ShiftAmt;
01226     };
01227 
01228     computeKnownBitsFromShiftOperator(I, KnownZero, KnownOne,
01229                                       KnownZero2, KnownOne2, Depth, Q, KZF,
01230                                       KOF);
01231     break;
01232   }
01233   case Instruction::LShr: {
01234     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
01235     auto KZF = [BitWidth](const APInt &KnownZero, unsigned ShiftAmt) {
01236       return APIntOps::lshr(KnownZero, ShiftAmt) |
01237              // High bits known zero.
01238              APInt::getHighBitsSet(BitWidth, ShiftAmt);
01239     };
01240 
01241     auto KOF = [BitWidth](const APInt &KnownOne, unsigned ShiftAmt) {
01242       return APIntOps::lshr(KnownOne, ShiftAmt);
01243     };
01244 
01245     computeKnownBitsFromShiftOperator(I, KnownZero, KnownOne,
01246                                       KnownZero2, KnownOne2, Depth, Q, KZF,
01247                                       KOF);
01248     break;
01249   }
01250   case Instruction::AShr: {
01251     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
01252     auto KZF = [BitWidth](const APInt &KnownZero, unsigned ShiftAmt) {
01253       return APIntOps::ashr(KnownZero, ShiftAmt);
01254     };
01255 
01256     auto KOF = [BitWidth](const APInt &KnownOne, unsigned ShiftAmt) {
01257       return APIntOps::ashr(KnownOne, ShiftAmt);
01258     };
01259 
01260     computeKnownBitsFromShiftOperator(I, KnownZero, KnownOne,
01261                                       KnownZero2, KnownOne2, Depth, Q, KZF,
01262                                       KOF);
01263     break;
01264   }
01265   case Instruction::Sub: {
01266     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
01267     computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
01268                            KnownZero, KnownOne, KnownZero2, KnownOne2, Depth,
01269                            Q);
01270     break;
01271   }
01272   case Instruction::Add: {
01273     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
01274     computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
01275                            KnownZero, KnownOne, KnownZero2, KnownOne2, Depth,
01276                            Q);
01277     break;
01278   }
01279   case Instruction::SRem:
01280     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
01281       APInt RA = Rem->getValue().abs();
01282       if (RA.isPowerOf2()) {
01283         APInt LowBits = RA - 1;
01284         computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1,
01285                          Q);
01286 
01287         // The low bits of the first operand are unchanged by the srem.
01288         KnownZero = KnownZero2 & LowBits;
01289         KnownOne = KnownOne2 & LowBits;
01290 
01291         // If the first operand is non-negative or has all low bits zero, then
01292         // the upper bits are all zero.
01293         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
01294           KnownZero |= ~LowBits;
01295 
01296         // If the first operand is negative and not all low bits are zero, then
01297         // the upper bits are all one.
01298         if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
01299           KnownOne |= ~LowBits;
01300 
01301         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
01302       }
01303     }
01304 
01305     // The sign bit is the LHS's sign bit, except when the result of the
01306     // remainder is zero.
01307     if (KnownZero.isNonNegative()) {
01308       APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
01309       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, Depth + 1,
01310                        Q);
01311       // If it's known zero, our sign bit is also zero.
01312       if (LHSKnownZero.isNegative())
01313         KnownZero.setBit(BitWidth - 1);
01314     }
01315 
01316     break;
01317   case Instruction::URem: {
01318     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
01319       APInt RA = Rem->getValue();
01320       if (RA.isPowerOf2()) {
01321         APInt LowBits = (RA - 1);
01322         computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
01323         KnownZero |= ~LowBits;
01324         KnownOne &= LowBits;
01325         break;
01326       }
01327     }
01328 
01329     // Since the result is less than or equal to either operand, any leading
01330     // zero bits in either operand must also exist in the result.
01331     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
01332     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, Depth + 1, Q);
01333 
01334     unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
01335                                 KnownZero2.countLeadingOnes());
01336     KnownOne.clearAllBits();
01337     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
01338     break;
01339   }
01340 
01341   case Instruction::Alloca: {
01342     AllocaInst *AI = cast<AllocaInst>(I);
01343     unsigned Align = AI->getAlignment();
01344     if (Align == 0)
01345       Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
01346 
01347     if (Align > 0)
01348       KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
01349     break;
01350   }
01351   case Instruction::GetElementPtr: {
01352     // Analyze all of the subscripts of this getelementptr instruction
01353     // to determine if we can prove known low zero bits.
01354     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
01355     computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, Depth + 1,
01356                      Q);
01357     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
01358 
01359     gep_type_iterator GTI = gep_type_begin(I);
01360     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
01361       Value *Index = I->getOperand(i);
01362       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
01363         // Handle struct member offset arithmetic.
01364 
01365         // Handle case when index is vector zeroinitializer
01366         Constant *CIndex = cast<Constant>(Index);
01367         if (CIndex->isZeroValue())
01368           continue;
01369 
01370         if (CIndex->getType()->isVectorTy())
01371           Index = CIndex->getSplatValue();
01372 
01373         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
01374         const StructLayout *SL = Q.DL.getStructLayout(STy);
01375         uint64_t Offset = SL->getElementOffset(Idx);
01376         TrailZ = std::min<unsigned>(TrailZ,
01377                                     countTrailingZeros(Offset));
01378       } else {
01379         // Handle array index arithmetic.
01380         Type *IndexedTy = GTI.getIndexedType();
01381         if (!IndexedTy->isSized()) {
01382           TrailZ = 0;
01383           break;
01384         }
01385         unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
01386         uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
01387         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
01388         computeKnownBits(Index, LocalKnownZero, LocalKnownOne, Depth + 1, Q);
01389         TrailZ = std::min(TrailZ,
01390                           unsigned(countTrailingZeros(TypeSize) +
01391                                    LocalKnownZero.countTrailingOnes()));
01392       }
01393     }
01394 
01395     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
01396     break;
01397   }
01398   case Instruction::PHI: {
01399     PHINode *P = cast<PHINode>(I);
01400     // Handle the case of a simple two-predecessor recurrence PHI.
01401     // There's a lot more that could theoretically be done here, but
01402     // this is sufficient to catch some interesting cases.
01403     if (P->getNumIncomingValues() == 2) {
01404       for (unsigned i = 0; i != 2; ++i) {
01405         Value *L = P->getIncomingValue(i);
01406         Value *R = P->getIncomingValue(!i);
01407         Operator *LU = dyn_cast<Operator>(L);
01408         if (!LU)
01409           continue;
01410         unsigned Opcode = LU->getOpcode();
01411         // Check for operations that have the property that if
01412         // both their operands have low zero bits, the result
01413         // will have low zero bits.
01414         if (Opcode == Instruction::Add ||
01415             Opcode == Instruction::Sub ||
01416             Opcode == Instruction::And ||
01417             Opcode == Instruction::Or ||
01418             Opcode == Instruction::Mul) {
01419           Value *LL = LU->getOperand(0);
01420           Value *LR = LU->getOperand(1);
01421           // Find a recurrence.
01422           if (LL == I)
01423             L = LR;
01424           else if (LR == I)
01425             L = LL;
01426           else
01427             break;
01428           // Ok, we have a PHI of the form L op= R. Check for low
01429           // zero bits.
01430           computeKnownBits(R, KnownZero2, KnownOne2, Depth + 1, Q);
01431 
01432           // We need to take the minimum number of known bits
01433           APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
01434           computeKnownBits(L, KnownZero3, KnownOne3, Depth + 1, Q);
01435 
01436           KnownZero = APInt::getLowBitsSet(BitWidth,
01437                                            std::min(KnownZero2.countTrailingOnes(),
01438                                                     KnownZero3.countTrailingOnes()));
01439           break;
01440         }
01441       }
01442     }
01443 
01444     // Unreachable blocks may have zero-operand PHI nodes.
01445     if (P->getNumIncomingValues() == 0)
01446       break;
01447 
01448     // Otherwise take the unions of the known bit sets of the operands,
01449     // taking conservative care to avoid excessive recursion.
01450     if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
01451       // Skip if every incoming value references to ourself.
01452       if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
01453         break;
01454 
01455       KnownZero = APInt::getAllOnesValue(BitWidth);
01456       KnownOne = APInt::getAllOnesValue(BitWidth);
01457       for (Value *IncValue : P->incoming_values()) {
01458         // Skip direct self references.
01459         if (IncValue == P) continue;
01460 
01461         KnownZero2 = APInt(BitWidth, 0);
01462         KnownOne2 = APInt(BitWidth, 0);
01463         // Recurse, but cap the recursion to one level, because we don't
01464         // want to waste time spinning around in loops.
01465         computeKnownBits(IncValue, KnownZero2, KnownOne2, MaxDepth - 1, Q);
01466         KnownZero &= KnownZero2;
01467         KnownOne &= KnownOne2;
01468         // If all bits have been ruled out, there's no need to check
01469         // more operands.
01470         if (!KnownZero && !KnownOne)
01471           break;
01472       }
01473     }
01474     break;
01475   }
01476   case Instruction::Call:
01477   case Instruction::Invoke:
01478     if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
01479       computeKnownBitsFromRangeMetadata(*MD, KnownZero, KnownOne);
01480     // If a range metadata is attached to this IntrinsicInst, intersect the
01481     // explicit range specified by the metadata and the implicit range of
01482     // the intrinsic.
01483     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
01484       switch (II->getIntrinsicID()) {
01485       default: break;
01486       case Intrinsic::bswap:
01487         computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
01488         KnownZero |= KnownZero2.byteSwap();
01489         KnownOne |= KnownOne2.byteSwap();
01490         break;
01491       case Intrinsic::ctlz:
01492       case Intrinsic::cttz: {
01493         unsigned LowBits = Log2_32(BitWidth)+1;
01494         // If this call is undefined for 0, the result will be less than 2^n.
01495         if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
01496           LowBits -= 1;
01497         KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
01498         break;
01499       }
01500       case Intrinsic::ctpop: {
01501         computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, Depth + 1, Q);
01502         // We can bound the space the count needs.  Also, bits known to be zero
01503         // can't contribute to the population.
01504         unsigned BitsPossiblySet = BitWidth - KnownZero2.countPopulation();
01505         unsigned LeadingZeros =
01506           APInt(BitWidth, BitsPossiblySet).countLeadingZeros();
01507         assert(LeadingZeros <= BitWidth);
01508         KnownZero |= APInt::getHighBitsSet(BitWidth, LeadingZeros);
01509         KnownOne &= ~KnownZero;
01510         // TODO: we could bound KnownOne using the lower bound on the number
01511         // of bits which might be set provided by popcnt KnownOne2.
01512         break;
01513       }
01514       case Intrinsic::fabs: {
01515         Type *Ty = II->getType();
01516         APInt SignBit = APInt::getSignBit(Ty->getScalarSizeInBits());
01517         KnownZero |= APInt::getSplat(Ty->getPrimitiveSizeInBits(), SignBit);
01518         break;
01519       }
01520       case Intrinsic::x86_sse42_crc32_64_64:
01521         KnownZero |= APInt::getHighBitsSet(64, 32);
01522         break;
01523       }
01524     }
01525     break;
01526   case Instruction::ExtractValue:
01527     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
01528       ExtractValueInst *EVI = cast<ExtractValueInst>(I);
01529       if (EVI->getNumIndices() != 1) break;
01530       if (EVI->getIndices()[0] == 0) {
01531         switch (II->getIntrinsicID()) {
01532         default: break;
01533         case Intrinsic::uadd_with_overflow:
01534         case Intrinsic::sadd_with_overflow:
01535           computeKnownBitsAddSub(true, II->getArgOperand(0),
01536                                  II->getArgOperand(1), false, KnownZero,
01537                                  KnownOne, KnownZero2, KnownOne2, Depth, Q);
01538           break;
01539         case Intrinsic::usub_with_overflow:
01540         case Intrinsic::ssub_with_overflow:
01541           computeKnownBitsAddSub(false, II->getArgOperand(0),
01542                                  II->getArgOperand(1), false, KnownZero,
01543                                  KnownOne, KnownZero2, KnownOne2, Depth, Q);
01544           break;
01545         case Intrinsic::umul_with_overflow:
01546         case Intrinsic::smul_with_overflow:
01547           computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
01548                               KnownZero, KnownOne, KnownZero2, KnownOne2, Depth,
01549                               Q);
01550           break;
01551         }
01552       }
01553     }
01554   }
01555 }
01556 
01557 static unsigned getAlignment(const Value *V, const DataLayout &DL) {
01558   unsigned Align = 0;
01559   if (auto *GO = dyn_cast<GlobalObject>(V)) {
01560     Align = GO->getAlignment();
01561     if (Align == 0) {
01562       if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
01563         Type *ObjectType = GVar->getValueType();
01564         if (ObjectType->isSized()) {
01565           // If the object is defined in the current Module, we'll be giving
01566           // it the preferred alignment. Otherwise, we have to assume that it
01567           // may only have the minimum ABI alignment.
01568           if (GVar->isStrongDefinitionForLinker())
01569             Align = DL.getPreferredAlignment(GVar);
01570           else
01571             Align = DL.getABITypeAlignment(ObjectType);
01572         }
01573       }
01574     }
01575   } else if (const Argument *A = dyn_cast<Argument>(V)) {
01576     Align = A->getType()->isPointerTy() ? A->getParamAlignment() : 0;
01577 
01578     if (!Align && A->hasStructRetAttr()) {
01579       // An sret parameter has at least the ABI alignment of the return type.
01580       Type *EltTy = cast<PointerType>(A->getType())->getElementType();
01581       if (EltTy->isSized())
01582         Align = DL.getABITypeAlignment(EltTy);
01583     }
01584   } else if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
01585     Align = AI->getAlignment();
01586   else if (auto CS = ImmutableCallSite(V))
01587     Align = CS.getAttributes().getParamAlignment(AttributeSet::ReturnIndex);
01588   else if (const LoadInst *LI = dyn_cast<LoadInst>(V))
01589     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_align)) {
01590       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
01591       Align = CI->getLimitedValue();
01592     }
01593 
01594   return Align;
01595 }
01596 
01597 /// Determine which bits of V are known to be either zero or one and return
01598 /// them in the KnownZero/KnownOne bit sets.
01599 ///
01600 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
01601 /// we cannot optimize based on the assumption that it is zero without changing
01602 /// it to be an explicit zero.  If we don't change it to zero, other code could
01603 /// optimized based on the contradictory assumption that it is non-zero.
01604 /// Because instcombine aggressively folds operations with undef args anyway,
01605 /// this won't lose us code quality.
01606 ///
01607 /// This function is defined on values with integer type, values with pointer
01608 /// type, and vectors of integers.  In the case
01609 /// where V is a vector, known zero, and known one values are the
01610 /// same width as the vector element, and the bit is set only if it is true
01611 /// for all of the elements in the vector.
01612 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
01613                       unsigned Depth, const Query &Q) {
01614   assert(V && "No Value?");
01615   assert(Depth <= MaxDepth && "Limit Search Depth");
01616   unsigned BitWidth = KnownZero.getBitWidth();
01617 
01618   assert((V->getType()->isIntOrIntVectorTy() ||
01619           V->getType()->isFPOrFPVectorTy() ||
01620           V->getType()->getScalarType()->isPointerTy()) &&
01621          "Not integer, floating point, or pointer type!");
01622   assert((Q.DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
01623          (!V->getType()->isIntOrIntVectorTy() ||
01624           V->getType()->getScalarSizeInBits() == BitWidth) &&
01625          KnownZero.getBitWidth() == BitWidth &&
01626          KnownOne.getBitWidth() == BitWidth &&
01627          "V, KnownOne and KnownZero should have same BitWidth");
01628 
01629   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
01630     // We know all of the bits for a constant!
01631     KnownOne = CI->getValue();
01632     KnownZero = ~KnownOne;
01633     return;
01634   }
01635   // Null and aggregate-zero are all-zeros.
01636   if (isa<ConstantPointerNull>(V) ||
01637       isa<ConstantAggregateZero>(V)) {
01638     KnownOne.clearAllBits();
01639     KnownZero = APInt::getAllOnesValue(BitWidth);
01640     return;
01641   }
01642   // Handle a constant vector by taking the intersection of the known bits of
01643   // each element.  There is no real need to handle ConstantVector here, because
01644   // we don't handle undef in any particularly useful way.
01645   if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
01646     // We know that CDS must be a vector of integers. Take the intersection of
01647     // each element.
01648     KnownZero.setAllBits(); KnownOne.setAllBits();
01649     APInt Elt(KnownZero.getBitWidth(), 0);
01650     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
01651       Elt = CDS->getElementAsInteger(i);
01652       KnownZero &= ~Elt;
01653       KnownOne &= Elt;
01654     }
01655     return;
01656   }
01657 
01658   // Start out not knowing anything.
01659   KnownZero.clearAllBits(); KnownOne.clearAllBits();
01660 
01661   // Limit search depth.
01662   // All recursive calls that increase depth must come after this.
01663   if (Depth == MaxDepth)
01664     return;
01665 
01666   // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
01667   // the bits of its aliasee.
01668   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
01669     if (!GA->mayBeOverridden())
01670       computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, Depth + 1, Q);
01671     return;
01672   }
01673 
01674   if (Operator *I = dyn_cast<Operator>(V))
01675     computeKnownBitsFromOperator(I, KnownZero, KnownOne, Depth, Q);
01676 
01677   // Aligned pointers have trailing zeros - refine KnownZero set
01678   if (V->getType()->isPointerTy()) {
01679     unsigned Align = getAlignment(V, Q.DL);
01680     if (Align)
01681       KnownZero |= APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
01682   }
01683 
01684   // computeKnownBitsFromAssume and computeKnownBitsFromDominatingCondition
01685   // strictly refines KnownZero and KnownOne. Therefore, we run them after
01686   // computeKnownBitsFromOperator.
01687 
01688   // Check whether a nearby assume intrinsic can determine some known bits.
01689   computeKnownBitsFromAssume(V, KnownZero, KnownOne, Depth, Q);
01690 
01691   // Check whether there's a dominating condition which implies something about
01692   // this value at the given context.
01693   if (EnableDomConditions && Depth <= DomConditionsMaxDepth)
01694     computeKnownBitsFromDominatingCondition(V, KnownZero, KnownOne, Depth, Q);
01695 
01696   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
01697 }
01698 
01699 /// Determine whether the sign bit is known to be zero or one.
01700 /// Convenience wrapper around computeKnownBits.
01701 void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
01702                     unsigned Depth, const Query &Q) {
01703   unsigned BitWidth = getBitWidth(V->getType(), Q.DL);
01704   if (!BitWidth) {
01705     KnownZero = false;
01706     KnownOne = false;
01707     return;
01708   }
01709   APInt ZeroBits(BitWidth, 0);
01710   APInt OneBits(BitWidth, 0);
01711   computeKnownBits(V, ZeroBits, OneBits, Depth, Q);
01712   KnownOne = OneBits[BitWidth - 1];
01713   KnownZero = ZeroBits[BitWidth - 1];
01714 }
01715 
01716 /// Return true if the given value is known to have exactly one
01717 /// bit set when defined. For vectors return true if every element is known to
01718 /// be a power of two when defined. Supports values with integer or pointer
01719 /// types and vectors of integers.
01720 bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
01721                             const Query &Q) {
01722   if (Constant *C = dyn_cast<Constant>(V)) {
01723     if (C->isNullValue())
01724       return OrZero;
01725     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
01726       return CI->getValue().isPowerOf2();
01727     // TODO: Handle vector constants.
01728   }
01729 
01730   // 1 << X is clearly a power of two if the one is not shifted off the end.  If
01731   // it is shifted off the end then the result is undefined.
01732   if (match(V, m_Shl(m_One(), m_Value())))
01733     return true;
01734 
01735   // (signbit) >>l X is clearly a power of two if the one is not shifted off the
01736   // bottom.  If it is shifted off the bottom then the result is undefined.
01737   if (match(V, m_LShr(m_SignBit(), m_Value())))
01738     return true;
01739 
01740   // The remaining tests are all recursive, so bail out if we hit the limit.
01741   if (Depth++ == MaxDepth)
01742     return false;
01743 
01744   Value *X = nullptr, *Y = nullptr;
01745   // A shift left or a logical shift right of a power of two is a power of two
01746   // or zero.
01747   if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
01748                  match(V, m_LShr(m_Value(X), m_Value()))))
01749     return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
01750 
01751   if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
01752     return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
01753 
01754   if (SelectInst *SI = dyn_cast<SelectInst>(V))
01755     return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
01756            isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
01757 
01758   if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
01759     // A power of two and'd with anything is a power of two or zero.
01760     if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
01761         isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
01762       return true;
01763     // X & (-X) is always a power of two or zero.
01764     if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
01765       return true;
01766     return false;
01767   }
01768 
01769   // Adding a power-of-two or zero to the same power-of-two or zero yields
01770   // either the original power-of-two, a larger power-of-two or zero.
01771   if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
01772     OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
01773     if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
01774       if (match(X, m_And(m_Specific(Y), m_Value())) ||
01775           match(X, m_And(m_Value(), m_Specific(Y))))
01776         if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
01777           return true;
01778       if (match(Y, m_And(m_Specific(X), m_Value())) ||
01779           match(Y, m_And(m_Value(), m_Specific(X))))
01780         if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
01781           return true;
01782 
01783       unsigned BitWidth = V->getType()->getScalarSizeInBits();
01784       APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
01785       computeKnownBits(X, LHSZeroBits, LHSOneBits, Depth, Q);
01786 
01787       APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
01788       computeKnownBits(Y, RHSZeroBits, RHSOneBits, Depth, Q);
01789       // If i8 V is a power of two or zero:
01790       //  ZeroBits: 1 1 1 0 1 1 1 1
01791       // ~ZeroBits: 0 0 0 1 0 0 0 0
01792       if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
01793         // If OrZero isn't set, we cannot give back a zero result.
01794         // Make sure either the LHS or RHS has a bit set.
01795         if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
01796           return true;
01797     }
01798   }
01799 
01800   // An exact divide or right shift can only shift off zero bits, so the result
01801   // is a power of two only if the first operand is a power of two and not
01802   // copying a sign bit (sdiv int_min, 2).
01803   if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
01804       match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
01805     return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
01806                                   Depth, Q);
01807   }
01808 
01809   return false;
01810 }
01811 
01812 /// \brief Test whether a GEP's result is known to be non-null.
01813 ///
01814 /// Uses properties inherent in a GEP to try to determine whether it is known
01815 /// to be non-null.
01816 ///
01817 /// Currently this routine does not support vector GEPs.
01818 static bool isGEPKnownNonNull(GEPOperator *GEP, unsigned Depth,
01819                               const Query &Q) {
01820   if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
01821     return false;
01822 
01823   // FIXME: Support vector-GEPs.
01824   assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
01825 
01826   // If the base pointer is non-null, we cannot walk to a null address with an
01827   // inbounds GEP in address space zero.
01828   if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
01829     return true;
01830 
01831   // Walk the GEP operands and see if any operand introduces a non-zero offset.
01832   // If so, then the GEP cannot produce a null pointer, as doing so would
01833   // inherently violate the inbounds contract within address space zero.
01834   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
01835        GTI != GTE; ++GTI) {
01836     // Struct types are easy -- they must always be indexed by a constant.
01837     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
01838       ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
01839       unsigned ElementIdx = OpC->getZExtValue();
01840       const StructLayout *SL = Q.DL.getStructLayout(STy);
01841       uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
01842       if (ElementOffset > 0)
01843         return true;
01844       continue;
01845     }
01846 
01847     // If we have a zero-sized type, the index doesn't matter. Keep looping.
01848     if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
01849       continue;
01850 
01851     // Fast path the constant operand case both for efficiency and so we don't
01852     // increment Depth when just zipping down an all-constant GEP.
01853     if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
01854       if (!OpC->isZero())
01855         return true;
01856       continue;
01857     }
01858 
01859     // We post-increment Depth here because while isKnownNonZero increments it
01860     // as well, when we pop back up that increment won't persist. We don't want
01861     // to recurse 10k times just because we have 10k GEP operands. We don't
01862     // bail completely out because we want to handle constant GEPs regardless
01863     // of depth.
01864     if (Depth++ >= MaxDepth)
01865       continue;
01866 
01867     if (isKnownNonZero(GTI.getOperand(), Depth, Q))
01868       return true;
01869   }
01870 
01871   return false;
01872 }
01873 
01874 /// Does the 'Range' metadata (which must be a valid MD_range operand list)
01875 /// ensure that the value it's attached to is never Value?  'RangeType' is
01876 /// is the type of the value described by the range.
01877 static bool rangeMetadataExcludesValue(MDNode* Ranges,
01878                                        const APInt& Value) {
01879   const unsigned NumRanges = Ranges->getNumOperands() / 2;
01880   assert(NumRanges >= 1);
01881   for (unsigned i = 0; i < NumRanges; ++i) {
01882     ConstantInt *Lower =
01883         mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
01884     ConstantInt *Upper =
01885         mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
01886     ConstantRange Range(Lower->getValue(), Upper->getValue());
01887     if (Range.contains(Value))
01888       return false;
01889   }
01890   return true;
01891 }
01892 
01893 /// Return true if the given value is known to be non-zero when defined.
01894 /// For vectors return true if every element is known to be non-zero when
01895 /// defined. Supports values with integer or pointer type and vectors of
01896 /// integers.
01897 bool isKnownNonZero(Value *V, unsigned Depth, const Query &Q) {
01898   if (Constant *C = dyn_cast<Constant>(V)) {
01899     if (C->isNullValue())
01900       return false;
01901     if (isa<ConstantInt>(C))
01902       // Must be non-zero due to null test above.
01903       return true;
01904     // TODO: Handle vectors
01905     return false;
01906   }
01907 
01908   if (Instruction* I = dyn_cast<Instruction>(V)) {
01909     if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
01910       // If the possible ranges don't contain zero, then the value is
01911       // definitely non-zero.
01912       if (IntegerType* Ty = dyn_cast<IntegerType>(V->getType())) {
01913         const APInt ZeroValue(Ty->getBitWidth(), 0);
01914         if (rangeMetadataExcludesValue(Ranges, ZeroValue))
01915           return true;
01916       }
01917     }
01918   }
01919 
01920   // The remaining tests are all recursive, so bail out if we hit the limit.
01921   if (Depth++ >= MaxDepth)
01922     return false;
01923 
01924   // Check for pointer simplifications.
01925   if (V->getType()->isPointerTy()) {
01926     if (isKnownNonNull(V))
01927       return true; 
01928     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
01929       if (isGEPKnownNonNull(GEP, Depth, Q))
01930         return true;
01931   }
01932 
01933   unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
01934 
01935   // X | Y != 0 if X != 0 or Y != 0.
01936   Value *X = nullptr, *Y = nullptr;
01937   if (match(V, m_Or(m_Value(X), m_Value(Y))))
01938     return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
01939 
01940   // ext X != 0 if X != 0.
01941   if (isa<SExtInst>(V) || isa<ZExtInst>(V))
01942     return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
01943 
01944   // shl X, Y != 0 if X is odd.  Note that the value of the shift is undefined
01945   // if the lowest bit is shifted off the end.
01946   if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
01947     // shl nuw can't remove any non-zero bits.
01948     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
01949     if (BO->hasNoUnsignedWrap())
01950       return isKnownNonZero(X, Depth, Q);
01951 
01952     APInt KnownZero(BitWidth, 0);
01953     APInt KnownOne(BitWidth, 0);
01954     computeKnownBits(X, KnownZero, KnownOne, Depth, Q);
01955     if (KnownOne[0])
01956       return true;
01957   }
01958   // shr X, Y != 0 if X is negative.  Note that the value of the shift is not
01959   // defined if the sign bit is shifted off the end.
01960   else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
01961     // shr exact can only shift out zero bits.
01962     PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
01963     if (BO->isExact())
01964       return isKnownNonZero(X, Depth, Q);
01965 
01966     bool XKnownNonNegative, XKnownNegative;
01967     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, Depth, Q);
01968     if (XKnownNegative)
01969       return true;
01970 
01971     // If the shifter operand is a constant, and all of the bits shifted
01972     // out are known to be zero, and X is known non-zero then at least one
01973     // non-zero bit must remain.
01974     if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
01975       APInt KnownZero(BitWidth, 0);
01976       APInt KnownOne(BitWidth, 0);
01977       computeKnownBits(X, KnownZero, KnownOne, Depth, Q);
01978       
01979       auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
01980       // Is there a known one in the portion not shifted out?
01981       if (KnownOne.countLeadingZeros() < BitWidth - ShiftVal)
01982         return true;
01983       // Are all the bits to be shifted out known zero?
01984       if (KnownZero.countTrailingOnes() >= ShiftVal)
01985         return isKnownNonZero(X, Depth, Q);
01986     }
01987   }
01988   // div exact can only produce a zero if the dividend is zero.
01989   else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
01990     return isKnownNonZero(X, Depth, Q);
01991   }
01992   // X + Y.
01993   else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
01994     bool XKnownNonNegative, XKnownNegative;
01995     bool YKnownNonNegative, YKnownNegative;
01996     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, Depth, Q);
01997     ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Depth, Q);
01998 
01999     // If X and Y are both non-negative (as signed values) then their sum is not
02000     // zero unless both X and Y are zero.
02001     if (XKnownNonNegative && YKnownNonNegative)
02002       if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
02003         return true;
02004 
02005     // If X and Y are both negative (as signed values) then their sum is not
02006     // zero unless both X and Y equal INT_MIN.
02007     if (BitWidth && XKnownNegative && YKnownNegative) {
02008       APInt KnownZero(BitWidth, 0);
02009       APInt KnownOne(BitWidth, 0);
02010       APInt Mask = APInt::getSignedMaxValue(BitWidth);
02011       // The sign bit of X is set.  If some other bit is set then X is not equal
02012       // to INT_MIN.
02013       computeKnownBits(X, KnownZero, KnownOne, Depth, Q);
02014       if ((KnownOne & Mask) != 0)
02015         return true;
02016       // The sign bit of Y is set.  If some other bit is set then Y is not equal
02017       // to INT_MIN.
02018       computeKnownBits(Y, KnownZero, KnownOne, Depth, Q);
02019       if ((KnownOne & Mask) != 0)
02020         return true;
02021     }
02022 
02023     // The sum of a non-negative number and a power of two is not zero.
02024     if (XKnownNonNegative &&
02025         isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
02026       return true;
02027     if (YKnownNonNegative &&
02028         isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
02029       return true;
02030   }
02031   // X * Y.
02032   else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
02033     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
02034     // If X and Y are non-zero then so is X * Y as long as the multiplication
02035     // does not overflow.
02036     if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
02037         isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
02038       return true;
02039   }
02040   // (C ? X : Y) != 0 if X != 0 and Y != 0.
02041   else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
02042     if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
02043         isKnownNonZero(SI->getFalseValue(), Depth, Q))
02044       return true;
02045   }
02046   // PHI
02047   else if (PHINode *PN = dyn_cast<PHINode>(V)) {
02048     // Try and detect a recurrence that monotonically increases from a
02049     // starting value, as these are common as induction variables.
02050     if (PN->getNumIncomingValues() == 2) {
02051       Value *Start = PN->getIncomingValue(0);
02052       Value *Induction = PN->getIncomingValue(1);
02053       if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
02054         std::swap(Start, Induction);
02055       if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
02056         if (!C->isZero() && !C->isNegative()) {
02057           ConstantInt *X;
02058           if ((match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
02059                match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
02060               !X->isNegative())
02061             return true;
02062         }
02063       }
02064     }
02065   }
02066 
02067   if (!BitWidth) return false;
02068   APInt KnownZero(BitWidth, 0);
02069   APInt KnownOne(BitWidth, 0);
02070   computeKnownBits(V, KnownZero, KnownOne, Depth, Q);
02071   return KnownOne != 0;
02072 }
02073 
02074 /// Return true if V2 == V1 + X, where X is known non-zero.
02075 static bool isAddOfNonZero(Value *V1, Value *V2, const Query &Q) {
02076   BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
02077   if (!BO || BO->getOpcode() != Instruction::Add)
02078     return false;
02079   Value *Op = nullptr;
02080   if (V2 == BO->getOperand(0))
02081     Op = BO->getOperand(1);
02082   else if (V2 == BO->getOperand(1))
02083     Op = BO->getOperand(0);
02084   else
02085     return false;
02086   return isKnownNonZero(Op, 0, Q);
02087 }
02088 
02089 /// Return true if it is known that V1 != V2.
02090 static bool isKnownNonEqual(Value *V1, Value *V2, const Query &Q) {
02091   if (V1->getType()->isVectorTy() || V1 == V2)
02092     return false;
02093   if (V1->getType() != V2->getType())
02094     // We can't look through casts yet.
02095     return false;
02096   if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
02097     return true;
02098 
02099   if (IntegerType *Ty = dyn_cast<IntegerType>(V1->getType())) {
02100     // Are any known bits in V1 contradictory to known bits in V2? If V1
02101     // has a known zero where V2 has a known one, they must not be equal.
02102     auto BitWidth = Ty->getBitWidth();
02103     APInt KnownZero1(BitWidth, 0);
02104     APInt KnownOne1(BitWidth, 0);
02105     computeKnownBits(V1, KnownZero1, KnownOne1, 0, Q);
02106     APInt KnownZero2(BitWidth, 0);
02107     APInt KnownOne2(BitWidth, 0);
02108     computeKnownBits(V2, KnownZero2, KnownOne2, 0, Q);
02109 
02110     auto OppositeBits = (KnownZero1 & KnownOne2) | (KnownZero2 & KnownOne1);
02111     if (OppositeBits.getBoolValue())
02112       return true;
02113   }
02114   return false;
02115 }
02116 
02117 /// Return true if 'V & Mask' is known to be zero.  We use this predicate to
02118 /// simplify operations downstream. Mask is known to be zero for bits that V
02119 /// cannot have.
02120 ///
02121 /// This function is defined on values with integer type, values with pointer
02122 /// type, and vectors of integers.  In the case
02123 /// where V is a vector, the mask, known zero, and known one values are the
02124 /// same width as the vector element, and the bit is set only if it is true
02125 /// for all of the elements in the vector.
02126 bool MaskedValueIsZero(Value *V, const APInt &Mask, unsigned Depth,
02127                        const Query &Q) {
02128   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
02129   computeKnownBits(V, KnownZero, KnownOne, Depth, Q);
02130   return (KnownZero & Mask) == Mask;
02131 }
02132 
02133 
02134 
02135 /// Return the number of times the sign bit of the register is replicated into
02136 /// the other bits. We know that at least 1 bit is always equal to the sign bit
02137 /// (itself), but other cases can give us information. For example, immediately
02138 /// after an "ashr X, 2", we know that the top 3 bits are all equal to each
02139 /// other, so we return 3.
02140 ///
02141 /// 'Op' must have a scalar integer type.
02142 ///
02143 unsigned ComputeNumSignBits(Value *V, unsigned Depth, const Query &Q) {
02144   unsigned TyBits = Q.DL.getTypeSizeInBits(V->getType()->getScalarType());
02145   unsigned Tmp, Tmp2;
02146   unsigned FirstAnswer = 1;
02147 
02148   // Note that ConstantInt is handled by the general computeKnownBits case
02149   // below.
02150 
02151   if (Depth == 6)
02152     return 1;  // Limit search depth.
02153 
02154   Operator *U = dyn_cast<Operator>(V);
02155   switch (Operator::getOpcode(V)) {
02156   default: break;
02157   case Instruction::SExt:
02158     Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
02159     return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
02160 
02161   case Instruction::SDiv: {
02162     const APInt *Denominator;
02163     // sdiv X, C -> adds log(C) sign bits.
02164     if (match(U->getOperand(1), m_APInt(Denominator))) {
02165 
02166       // Ignore non-positive denominator.
02167       if (!Denominator->isStrictlyPositive())
02168         break;
02169 
02170       // Calculate the incoming numerator bits.
02171       unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
02172 
02173       // Add floor(log(C)) bits to the numerator bits.
02174       return std::min(TyBits, NumBits + Denominator->logBase2());
02175     }
02176     break;
02177   }
02178 
02179   case Instruction::SRem: {
02180     const APInt *Denominator;
02181     // srem X, C -> we know that the result is within [-C+1,C) when C is a
02182     // positive constant.  This let us put a lower bound on the number of sign
02183     // bits.
02184     if (match(U->getOperand(1), m_APInt(Denominator))) {
02185 
02186       // Ignore non-positive denominator.
02187       if (!Denominator->isStrictlyPositive())
02188         break;
02189 
02190       // Calculate the incoming numerator bits. SRem by a positive constant
02191       // can't lower the number of sign bits.
02192       unsigned NumrBits =
02193           ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
02194 
02195       // Calculate the leading sign bit constraints by examining the
02196       // denominator.  Given that the denominator is positive, there are two
02197       // cases:
02198       //
02199       //  1. the numerator is positive.  The result range is [0,C) and [0,C) u<
02200       //     (1 << ceilLogBase2(C)).
02201       //
02202       //  2. the numerator is negative.  Then the result range is (-C,0] and
02203       //     integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
02204       //
02205       // Thus a lower bound on the number of sign bits is `TyBits -
02206       // ceilLogBase2(C)`.
02207 
02208       unsigned ResBits = TyBits - Denominator->ceilLogBase2();
02209       return std::max(NumrBits, ResBits);
02210     }
02211     break;
02212   }
02213 
02214   case Instruction::AShr: {
02215     Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
02216     // ashr X, C   -> adds C sign bits.  Vectors too.
02217     const APInt *ShAmt;
02218     if (match(U->getOperand(1), m_APInt(ShAmt))) {
02219       Tmp += ShAmt->getZExtValue();
02220       if (Tmp > TyBits) Tmp = TyBits;
02221     }
02222     return Tmp;
02223   }
02224   case Instruction::Shl: {
02225     const APInt *ShAmt;
02226     if (match(U->getOperand(1), m_APInt(ShAmt))) {
02227       // shl destroys sign bits.
02228       Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
02229       Tmp2 = ShAmt->getZExtValue();
02230       if (Tmp2 >= TyBits ||      // Bad shift.
02231           Tmp2 >= Tmp) break;    // Shifted all sign bits out.
02232       return Tmp - Tmp2;
02233     }
02234     break;
02235   }
02236   case Instruction::And:
02237   case Instruction::Or:
02238   case Instruction::Xor:    // NOT is handled here.
02239     // Logical binary ops preserve the number of sign bits at the worst.
02240     Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
02241     if (Tmp != 1) {
02242       Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
02243       FirstAnswer = std::min(Tmp, Tmp2);
02244       // We computed what we know about the sign bits as our first
02245       // answer. Now proceed to the generic code that uses
02246       // computeKnownBits, and pick whichever answer is better.
02247     }
02248     break;
02249 
02250   case Instruction::Select:
02251     Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
02252     if (Tmp == 1) return 1;  // Early out.
02253     Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
02254     return std::min(Tmp, Tmp2);
02255 
02256   case Instruction::Add:
02257     // Add can have at most one carry bit.  Thus we know that the output
02258     // is, at worst, one more bit than the inputs.
02259     Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
02260     if (Tmp == 1) return 1;  // Early out.
02261 
02262     // Special case decrementing a value (ADD X, -1):
02263     if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
02264       if (CRHS->isAllOnesValue()) {
02265         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
02266         computeKnownBits(U->getOperand(0), KnownZero, KnownOne, Depth + 1, Q);
02267 
02268         // If the input is known to be 0 or 1, the output is 0/-1, which is all
02269         // sign bits set.
02270         if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
02271           return TyBits;
02272 
02273         // If we are subtracting one from a positive number, there is no carry
02274         // out of the result.
02275         if (KnownZero.isNegative())
02276           return Tmp;
02277       }
02278 
02279     Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
02280     if (Tmp2 == 1) return 1;
02281     return std::min(Tmp, Tmp2)-1;
02282 
02283   case Instruction::Sub:
02284     Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
02285     if (Tmp2 == 1) return 1;
02286 
02287     // Handle NEG.
02288     if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
02289       if (CLHS->isNullValue()) {
02290         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
02291         computeKnownBits(U->getOperand(1), KnownZero, KnownOne, Depth + 1, Q);
02292         // If the input is known to be 0 or 1, the output is 0/-1, which is all
02293         // sign bits set.
02294         if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
02295           return TyBits;
02296 
02297         // If the input is known to be positive (the sign bit is known clear),
02298         // the output of the NEG has the same number of sign bits as the input.
02299         if (KnownZero.isNegative())
02300           return Tmp2;
02301 
02302         // Otherwise, we treat this like a SUB.
02303       }
02304 
02305     // Sub can have at most one carry bit.  Thus we know that the output
02306     // is, at worst, one more bit than the inputs.
02307     Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
02308     if (Tmp == 1) return 1;  // Early out.
02309     return std::min(Tmp, Tmp2)-1;
02310 
02311   case Instruction::PHI: {
02312     PHINode *PN = cast<PHINode>(U);
02313     unsigned NumIncomingValues = PN->getNumIncomingValues();
02314     // Don't analyze large in-degree PHIs.
02315     if (NumIncomingValues > 4) break;
02316     // Unreachable blocks may have zero-operand PHI nodes.
02317     if (NumIncomingValues == 0) break;
02318 
02319     // Take the minimum of all incoming values.  This can't infinitely loop
02320     // because of our depth threshold.
02321     Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
02322     for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
02323       if (Tmp == 1) return Tmp;
02324       Tmp = std::min(
02325           Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
02326     }
02327     return Tmp;
02328   }
02329 
02330   case Instruction::Trunc:
02331     // FIXME: it's tricky to do anything useful for this, but it is an important
02332     // case for targets like X86.
02333     break;
02334   }
02335 
02336   // Finally, if we can prove that the top bits of the result are 0's or 1's,
02337   // use this information.
02338   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
02339   APInt Mask;
02340   computeKnownBits(V, KnownZero, KnownOne, Depth, Q);
02341 
02342   if (KnownZero.isNegative()) {        // sign bit is 0
02343     Mask = KnownZero;
02344   } else if (KnownOne.isNegative()) {  // sign bit is 1;
02345     Mask = KnownOne;
02346   } else {
02347     // Nothing known.
02348     return FirstAnswer;
02349   }
02350 
02351   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
02352   // the number of identical bits in the top of the input value.
02353   Mask = ~Mask;
02354   Mask <<= Mask.getBitWidth()-TyBits;
02355   // Return # leading zeros.  We use 'min' here in case Val was zero before
02356   // shifting.  We don't want to return '64' as for an i32 "0".
02357   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
02358 }
02359 
02360 /// This function computes the integer multiple of Base that equals V.
02361 /// If successful, it returns true and returns the multiple in
02362 /// Multiple. If unsuccessful, it returns false. It looks
02363 /// through SExt instructions only if LookThroughSExt is true.
02364 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
02365                            bool LookThroughSExt, unsigned Depth) {
02366   const unsigned MaxDepth = 6;
02367 
02368   assert(V && "No Value?");
02369   assert(Depth <= MaxDepth && "Limit Search Depth");
02370   assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
02371 
02372   Type *T = V->getType();
02373 
02374   ConstantInt *CI = dyn_cast<ConstantInt>(V);
02375 
02376   if (Base == 0)
02377     return false;
02378 
02379   if (Base == 1) {
02380     Multiple = V;
02381     return true;
02382   }
02383 
02384   ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
02385   Constant *BaseVal = ConstantInt::get(T, Base);
02386   if (CO && CO == BaseVal) {
02387     // Multiple is 1.
02388     Multiple = ConstantInt::get(T, 1);
02389     return true;
02390   }
02391 
02392   if (CI && CI->getZExtValue() % Base == 0) {
02393     Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
02394     return true;
02395   }
02396 
02397   if (Depth == MaxDepth) return false;  // Limit search depth.
02398 
02399   Operator *I = dyn_cast<Operator>(V);
02400   if (!I) return false;
02401 
02402   switch (I->getOpcode()) {
02403   default: break;
02404   case Instruction::SExt:
02405     if (!LookThroughSExt) return false;
02406     // otherwise fall through to ZExt
02407   case Instruction::ZExt:
02408     return ComputeMultiple(I->getOperand(0), Base, Multiple,
02409                            LookThroughSExt, Depth+1);
02410   case Instruction::Shl:
02411   case Instruction::Mul: {
02412     Value *Op0 = I->getOperand(0);
02413     Value *Op1 = I->getOperand(1);
02414 
02415     if (I->getOpcode() == Instruction::Shl) {
02416       ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
02417       if (!Op1CI) return false;
02418       // Turn Op0 << Op1 into Op0 * 2^Op1
02419       APInt Op1Int = Op1CI->getValue();
02420       uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
02421       APInt API(Op1Int.getBitWidth(), 0);
02422       API.setBit(BitToSet);
02423       Op1 = ConstantInt::get(V->getContext(), API);
02424     }
02425 
02426     Value *Mul0 = nullptr;
02427     if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
02428       if (Constant *Op1C = dyn_cast<Constant>(Op1))
02429         if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
02430           if (Op1C->getType()->getPrimitiveSizeInBits() <
02431               MulC->getType()->getPrimitiveSizeInBits())
02432             Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
02433           if (Op1C->getType()->getPrimitiveSizeInBits() >
02434               MulC->getType()->getPrimitiveSizeInBits())
02435             MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
02436 
02437           // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
02438           Multiple = ConstantExpr::getMul(MulC, Op1C);
02439           return true;
02440         }
02441 
02442       if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
02443         if (Mul0CI->getValue() == 1) {
02444           // V == Base * Op1, so return Op1
02445           Multiple = Op1;
02446           return true;
02447         }
02448     }
02449 
02450     Value *Mul1 = nullptr;
02451     if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
02452       if (Constant *Op0C = dyn_cast<Constant>(Op0))
02453         if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
02454           if (Op0C->getType()->getPrimitiveSizeInBits() <
02455               MulC->getType()->getPrimitiveSizeInBits())
02456             Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
02457           if (Op0C->getType()->getPrimitiveSizeInBits() >
02458               MulC->getType()->getPrimitiveSizeInBits())
02459             MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
02460 
02461           // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
02462           Multiple = ConstantExpr::getMul(MulC, Op0C);
02463           return true;
02464         }
02465 
02466       if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
02467         if (Mul1CI->getValue() == 1) {
02468           // V == Base * Op0, so return Op0
02469           Multiple = Op0;
02470           return true;
02471         }
02472     }
02473   }
02474   }
02475 
02476   // We could not determine if V is a multiple of Base.
02477   return false;
02478 }
02479 
02480 /// Return true if we can prove that the specified FP value is never equal to
02481 /// -0.0.
02482 ///
02483 /// NOTE: this function will need to be revisited when we support non-default
02484 /// rounding modes!
02485 ///
02486 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
02487   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
02488     return !CFP->getValueAPF().isNegZero();
02489 
02490   // FIXME: Magic number! At the least, this should be given a name because it's
02491   // used similarly in CannotBeOrderedLessThanZero(). A better fix may be to
02492   // expose it as a parameter, so it can be used for testing / experimenting.
02493   if (Depth == 6)
02494     return false;  // Limit search depth.
02495 
02496   const Operator *I = dyn_cast<Operator>(V);
02497   if (!I) return false;
02498 
02499   // Check if the nsz fast-math flag is set
02500   if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
02501     if (FPO->hasNoSignedZeros())
02502       return true;
02503 
02504   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
02505   if (I->getOpcode() == Instruction::FAdd)
02506     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
02507       if (CFP->isNullValue())
02508         return true;
02509 
02510   // sitofp and uitofp turn into +0.0 for zero.
02511   if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
02512     return true;
02513 
02514   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
02515     // sqrt(-0.0) = -0.0, no other negative results are possible.
02516     if (II->getIntrinsicID() == Intrinsic::sqrt)
02517       return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
02518 
02519   if (const CallInst *CI = dyn_cast<CallInst>(I))
02520     if (const Function *F = CI->getCalledFunction()) {
02521       if (F->isDeclaration()) {
02522         // abs(x) != -0.0
02523         if (F->getName() == "abs") return true;
02524         // fabs[lf](x) != -0.0
02525         if (F->getName() == "fabs") return true;
02526         if (F->getName() == "fabsf") return true;
02527         if (F->getName() == "fabsl") return true;
02528         if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
02529             F->getName() == "sqrtl")
02530           return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
02531       }
02532     }
02533 
02534   return false;
02535 }
02536 
02537 bool llvm::CannotBeOrderedLessThanZero(const Value *V, unsigned Depth) {
02538   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
02539     return !CFP->getValueAPF().isNegative() || CFP->getValueAPF().isZero();
02540 
02541   // FIXME: Magic number! At the least, this should be given a name because it's
02542   // used similarly in CannotBeNegativeZero(). A better fix may be to
02543   // expose it as a parameter, so it can be used for testing / experimenting.
02544   if (Depth == 6)
02545     return false;  // Limit search depth.
02546 
02547   const Operator *I = dyn_cast<Operator>(V);
02548   if (!I) return false;
02549 
02550   switch (I->getOpcode()) {
02551   default: break;
02552   // Unsigned integers are always nonnegative.
02553   case Instruction::UIToFP:
02554     return true;
02555   case Instruction::FMul:
02556     // x*x is always non-negative or a NaN.
02557     if (I->getOperand(0) == I->getOperand(1)) 
02558       return true;
02559     // Fall through
02560   case Instruction::FAdd:
02561   case Instruction::FDiv:
02562   case Instruction::FRem:
02563     return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1) &&
02564            CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1);
02565   case Instruction::Select:
02566     return CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1) &&
02567            CannotBeOrderedLessThanZero(I->getOperand(2), Depth+1);
02568   case Instruction::FPExt:
02569   case Instruction::FPTrunc:
02570     // Widening/narrowing never change sign.
02571     return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
02572   case Instruction::Call: 
02573     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) 
02574       switch (II->getIntrinsicID()) {
02575       default: break;
02576       case Intrinsic::maxnum:
02577         return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1) ||
02578                CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1);
02579       case Intrinsic::minnum:
02580         return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1) &&
02581                CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1);
02582       case Intrinsic::exp:
02583       case Intrinsic::exp2:
02584       case Intrinsic::fabs:
02585       case Intrinsic::sqrt:
02586         return true;
02587       case Intrinsic::powi: 
02588         if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
02589           // powi(x,n) is non-negative if n is even.
02590           if (CI->getBitWidth() <= 64 && CI->getSExtValue() % 2u == 0)
02591             return true;
02592         }
02593         return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
02594       case Intrinsic::fma:
02595       case Intrinsic::fmuladd:
02596         // x*x+y is non-negative if y is non-negative.
02597         return I->getOperand(0) == I->getOperand(1) && 
02598                CannotBeOrderedLessThanZero(I->getOperand(2), Depth+1);
02599       }
02600     break;
02601   }
02602   return false; 
02603 }
02604 
02605 /// If the specified value can be set by repeating the same byte in memory,
02606 /// return the i8 value that it is represented with.  This is
02607 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
02608 /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
02609 /// byte store (e.g. i16 0x1234), return null.
02610 Value *llvm::isBytewiseValue(Value *V) {
02611   // All byte-wide stores are splatable, even of arbitrary variables.
02612   if (V->getType()->isIntegerTy(8)) return V;
02613 
02614   // Handle 'null' ConstantArrayZero etc.
02615   if (Constant *C = dyn_cast<Constant>(V))
02616     if (C->isNullValue())
02617       return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
02618 
02619   // Constant float and double values can be handled as integer values if the
02620   // corresponding integer value is "byteable".  An important case is 0.0.
02621   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
02622     if (CFP->getType()->isFloatTy())
02623       V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
02624     if (CFP->getType()->isDoubleTy())
02625       V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
02626     // Don't handle long double formats, which have strange constraints.
02627   }
02628 
02629   // We can handle constant integers that are multiple of 8 bits.
02630   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
02631     if (CI->getBitWidth() % 8 == 0) {
02632       assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
02633 
02634       if (!CI->getValue().isSplat(8))
02635         return nullptr;
02636       return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
02637     }
02638   }
02639 
02640   // A ConstantDataArray/Vector is splatable if all its members are equal and
02641   // also splatable.
02642   if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
02643     Value *Elt = CA->getElementAsConstant(0);
02644     Value *Val = isBytewiseValue(Elt);
02645     if (!Val)
02646       return nullptr;
02647 
02648     for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
02649       if (CA->getElementAsConstant(I) != Elt)
02650         return nullptr;
02651 
02652     return Val;
02653   }
02654 
02655   // Conceptually, we could handle things like:
02656   //   %a = zext i8 %X to i16
02657   //   %b = shl i16 %a, 8
02658   //   %c = or i16 %a, %b
02659   // but until there is an example that actually needs this, it doesn't seem
02660   // worth worrying about.
02661   return nullptr;
02662 }
02663 
02664 
02665 // This is the recursive version of BuildSubAggregate. It takes a few different
02666 // arguments. Idxs is the index within the nested struct From that we are
02667 // looking at now (which is of type IndexedType). IdxSkip is the number of
02668 // indices from Idxs that should be left out when inserting into the resulting
02669 // struct. To is the result struct built so far, new insertvalue instructions
02670 // build on that.
02671 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
02672                                 SmallVectorImpl<unsigned> &Idxs,
02673                                 unsigned IdxSkip,
02674                                 Instruction *InsertBefore) {
02675   llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
02676   if (STy) {
02677     // Save the original To argument so we can modify it
02678     Value *OrigTo = To;
02679     // General case, the type indexed by Idxs is a struct
02680     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
02681       // Process each struct element recursively
02682       Idxs.push_back(i);
02683       Value *PrevTo = To;
02684       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
02685                              InsertBefore);
02686       Idxs.pop_back();
02687       if (!To) {
02688         // Couldn't find any inserted value for this index? Cleanup
02689         while (PrevTo != OrigTo) {
02690           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
02691           PrevTo = Del->getAggregateOperand();
02692           Del->eraseFromParent();
02693         }
02694         // Stop processing elements
02695         break;
02696       }
02697     }
02698     // If we successfully found a value for each of our subaggregates
02699     if (To)
02700       return To;
02701   }
02702   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
02703   // the struct's elements had a value that was inserted directly. In the latter
02704   // case, perhaps we can't determine each of the subelements individually, but
02705   // we might be able to find the complete struct somewhere.
02706 
02707   // Find the value that is at that particular spot
02708   Value *V = FindInsertedValue(From, Idxs);
02709 
02710   if (!V)
02711     return nullptr;
02712 
02713   // Insert the value in the new (sub) aggregrate
02714   return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
02715                                        "tmp", InsertBefore);
02716 }
02717 
02718 // This helper takes a nested struct and extracts a part of it (which is again a
02719 // struct) into a new value. For example, given the struct:
02720 // { a, { b, { c, d }, e } }
02721 // and the indices "1, 1" this returns
02722 // { c, d }.
02723 //
02724 // It does this by inserting an insertvalue for each element in the resulting
02725 // struct, as opposed to just inserting a single struct. This will only work if
02726 // each of the elements of the substruct are known (ie, inserted into From by an
02727 // insertvalue instruction somewhere).
02728 //
02729 // All inserted insertvalue instructions are inserted before InsertBefore
02730 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
02731                                 Instruction *InsertBefore) {
02732   assert(InsertBefore && "Must have someplace to insert!");
02733   Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
02734                                                              idx_range);
02735   Value *To = UndefValue::get(IndexedType);
02736   SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
02737   unsigned IdxSkip = Idxs.size();
02738 
02739   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
02740 }
02741 
02742 /// Given an aggregrate and an sequence of indices, see if
02743 /// the scalar value indexed is already around as a register, for example if it
02744 /// were inserted directly into the aggregrate.
02745 ///
02746 /// If InsertBefore is not null, this function will duplicate (modified)
02747 /// insertvalues when a part of a nested struct is extracted.
02748 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
02749                                Instruction *InsertBefore) {
02750   // Nothing to index? Just return V then (this is useful at the end of our
02751   // recursion).
02752   if (idx_range.empty())
02753     return V;
02754   // We have indices, so V should have an indexable type.
02755   assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
02756          "Not looking at a struct or array?");
02757   assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
02758          "Invalid indices for type?");
02759 
02760   if (Constant *C = dyn_cast<Constant>(V)) {
02761     C = C->getAggregateElement(idx_range[0]);
02762     if (!C) return nullptr;
02763     return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
02764   }
02765 
02766   if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
02767     // Loop the indices for the insertvalue instruction in parallel with the
02768     // requested indices
02769     const unsigned *req_idx = idx_range.begin();
02770     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
02771          i != e; ++i, ++req_idx) {
02772       if (req_idx == idx_range.end()) {
02773         // We can't handle this without inserting insertvalues
02774         if (!InsertBefore)
02775           return nullptr;
02776 
02777         // The requested index identifies a part of a nested aggregate. Handle
02778         // this specially. For example,
02779         // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
02780         // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
02781         // %C = extractvalue {i32, { i32, i32 } } %B, 1
02782         // This can be changed into
02783         // %A = insertvalue {i32, i32 } undef, i32 10, 0
02784         // %C = insertvalue {i32, i32 } %A, i32 11, 1
02785         // which allows the unused 0,0 element from the nested struct to be
02786         // removed.
02787         return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
02788                                  InsertBefore);
02789       }
02790 
02791       // This insert value inserts something else than what we are looking for.
02792       // See if the (aggregate) value inserted into has the value we are
02793       // looking for, then.
02794       if (*req_idx != *i)
02795         return FindInsertedValue(I->getAggregateOperand(), idx_range,
02796                                  InsertBefore);
02797     }
02798     // If we end up here, the indices of the insertvalue match with those
02799     // requested (though possibly only partially). Now we recursively look at
02800     // the inserted value, passing any remaining indices.
02801     return FindInsertedValue(I->getInsertedValueOperand(),
02802                              makeArrayRef(req_idx, idx_range.end()),
02803                              InsertBefore);
02804   }
02805 
02806   if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
02807     // If we're extracting a value from an aggregate that was extracted from
02808     // something else, we can extract from that something else directly instead.
02809     // However, we will need to chain I's indices with the requested indices.
02810 
02811     // Calculate the number of indices required
02812     unsigned size = I->getNumIndices() + idx_range.size();
02813     // Allocate some space to put the new indices in
02814     SmallVector<unsigned, 5> Idxs;
02815     Idxs.reserve(size);
02816     // Add indices from the extract value instruction
02817     Idxs.append(I->idx_begin(), I->idx_end());
02818 
02819     // Add requested indices
02820     Idxs.append(idx_range.begin(), idx_range.end());
02821 
02822     assert(Idxs.size() == size
02823            && "Number of indices added not correct?");
02824 
02825     return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
02826   }
02827   // Otherwise, we don't know (such as, extracting from a function return value
02828   // or load instruction)
02829   return nullptr;
02830 }
02831 
02832 /// Analyze the specified pointer to see if it can be expressed as a base
02833 /// pointer plus a constant offset. Return the base and offset to the caller.
02834 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
02835                                               const DataLayout &DL) {
02836   unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType());
02837   APInt ByteOffset(BitWidth, 0);
02838 
02839   // We walk up the defs but use a visited set to handle unreachable code. In
02840   // that case, we stop after accumulating the cycle once (not that it
02841   // matters).
02842   SmallPtrSet<Value *, 16> Visited;
02843   while (Visited.insert(Ptr).second) {
02844     if (Ptr->getType()->isVectorTy())
02845       break;
02846 
02847     if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
02848       APInt GEPOffset(BitWidth, 0);
02849       if (!GEP->accumulateConstantOffset(DL, GEPOffset))
02850         break;
02851 
02852       ByteOffset += GEPOffset;
02853 
02854       Ptr = GEP->getPointerOperand();
02855     } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
02856                Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
02857       Ptr = cast<Operator>(Ptr)->getOperand(0);
02858     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
02859       if (GA->mayBeOverridden())
02860         break;
02861       Ptr = GA->getAliasee();
02862     } else {
02863       break;
02864     }
02865   }
02866   Offset = ByteOffset.getSExtValue();
02867   return Ptr;
02868 }
02869 
02870 
02871 /// This function computes the length of a null-terminated C string pointed to
02872 /// by V. If successful, it returns true and returns the string in Str.
02873 /// If unsuccessful, it returns false.
02874 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
02875                                  uint64_t Offset, bool TrimAtNul) {
02876   assert(V);
02877 
02878   // Look through bitcast instructions and geps.
02879   V = V->stripPointerCasts();
02880 
02881   // If the value is a GEP instruction or constant expression, treat it as an
02882   // offset.
02883   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
02884     // Make sure the GEP has exactly three arguments.
02885     if (GEP->getNumOperands() != 3)
02886       return false;
02887 
02888     // Make sure the index-ee is a pointer to array of i8.
02889     ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
02890     if (!AT || !AT->getElementType()->isIntegerTy(8))
02891       return false;
02892 
02893     // Check to make sure that the first operand of the GEP is an integer and
02894     // has value 0 so that we are sure we're indexing into the initializer.
02895     const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
02896     if (!FirstIdx || !FirstIdx->isZero())
02897       return false;
02898 
02899     // If the second index isn't a ConstantInt, then this is a variable index
02900     // into the array.  If this occurs, we can't say anything meaningful about
02901     // the string.
02902     uint64_t StartIdx = 0;
02903     if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
02904       StartIdx = CI->getZExtValue();
02905     else
02906       return false;
02907     return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx + Offset,
02908                                  TrimAtNul);
02909   }
02910 
02911   // The GEP instruction, constant or instruction, must reference a global
02912   // variable that is a constant and is initialized. The referenced constant
02913   // initializer is the array that we'll use for optimization.
02914   const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
02915   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
02916     return false;
02917 
02918   // Handle the all-zeros case
02919   if (GV->getInitializer()->isNullValue()) {
02920     // This is a degenerate case. The initializer is constant zero so the
02921     // length of the string must be zero.
02922     Str = "";
02923     return true;
02924   }
02925 
02926   // Must be a Constant Array
02927   const ConstantDataArray *Array =
02928     dyn_cast<ConstantDataArray>(GV->getInitializer());
02929   if (!Array || !Array->isString())
02930     return false;
02931 
02932   // Get the number of elements in the array
02933   uint64_t NumElts = Array->getType()->getArrayNumElements();
02934 
02935   // Start out with the entire array in the StringRef.
02936   Str = Array->getAsString();
02937 
02938   if (Offset > NumElts)
02939     return false;
02940 
02941   // Skip over 'offset' bytes.
02942   Str = Str.substr(Offset);
02943 
02944   if (TrimAtNul) {
02945     // Trim off the \0 and anything after it.  If the array is not nul
02946     // terminated, we just return the whole end of string.  The client may know
02947     // some other way that the string is length-bound.
02948     Str = Str.substr(0, Str.find('\0'));
02949   }
02950   return true;
02951 }
02952 
02953 // These next two are very similar to the above, but also look through PHI
02954 // nodes.
02955 // TODO: See if we can integrate these two together.
02956 
02957 /// If we can compute the length of the string pointed to by
02958 /// the specified pointer, return 'len+1'.  If we can't, return 0.
02959 static uint64_t GetStringLengthH(Value *V, SmallPtrSetImpl<PHINode*> &PHIs) {
02960   // Look through noop bitcast instructions.
02961   V = V->stripPointerCasts();
02962 
02963   // If this is a PHI node, there are two cases: either we have already seen it
02964   // or we haven't.
02965   if (PHINode *PN = dyn_cast<PHINode>(V)) {
02966     if (!PHIs.insert(PN).second)
02967       return ~0ULL;  // already in the set.
02968 
02969     // If it was new, see if all the input strings are the same length.
02970     uint64_t LenSoFar = ~0ULL;
02971     for (Value *IncValue : PN->incoming_values()) {
02972       uint64_t Len = GetStringLengthH(IncValue, PHIs);
02973       if (Len == 0) return 0; // Unknown length -> unknown.
02974 
02975       if (Len == ~0ULL) continue;
02976 
02977       if (Len != LenSoFar && LenSoFar != ~0ULL)
02978         return 0;    // Disagree -> unknown.
02979       LenSoFar = Len;
02980     }
02981 
02982     // Success, all agree.
02983     return LenSoFar;
02984   }
02985 
02986   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
02987   if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
02988     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
02989     if (Len1 == 0) return 0;
02990     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
02991     if (Len2 == 0) return 0;
02992     if (Len1 == ~0ULL) return Len2;
02993     if (Len2 == ~0ULL) return Len1;
02994     if (Len1 != Len2) return 0;
02995     return Len1;
02996   }
02997 
02998   // Otherwise, see if we can read the string.
02999   StringRef StrData;
03000   if (!getConstantStringInfo(V, StrData))
03001     return 0;
03002 
03003   return StrData.size()+1;
03004 }
03005 
03006 /// If we can compute the length of the string pointed to by
03007 /// the specified pointer, return 'len+1'.  If we can't, return 0.
03008 uint64_t llvm::GetStringLength(Value *V) {
03009   if (!V->getType()->isPointerTy()) return 0;
03010 
03011   SmallPtrSet<PHINode*, 32> PHIs;
03012   uint64_t Len = GetStringLengthH(V, PHIs);
03013   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
03014   // an empty string as a length.
03015   return Len == ~0ULL ? 1 : Len;
03016 }
03017 
03018 /// \brief \p PN defines a loop-variant pointer to an object.  Check if the
03019 /// previous iteration of the loop was referring to the same object as \p PN.
03020 static bool isSameUnderlyingObjectInLoop(PHINode *PN, LoopInfo *LI) {
03021   // Find the loop-defined value.
03022   Loop *L = LI->getLoopFor(PN->getParent());
03023   if (PN->getNumIncomingValues() != 2)
03024     return true;
03025 
03026   // Find the value from previous iteration.
03027   auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
03028   if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
03029     PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
03030   if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
03031     return true;
03032 
03033   // If a new pointer is loaded in the loop, the pointer references a different
03034   // object in every iteration.  E.g.:
03035   //    for (i)
03036   //       int *p = a[i];
03037   //       ...
03038   if (auto *Load = dyn_cast<LoadInst>(PrevValue))
03039     if (!L->isLoopInvariant(Load->getPointerOperand()))
03040       return false;
03041   return true;
03042 }
03043 
03044 Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
03045                                  unsigned MaxLookup) {
03046   if (!V->getType()->isPointerTy())
03047     return V;
03048   for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
03049     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
03050       V = GEP->getPointerOperand();
03051     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
03052                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
03053       V = cast<Operator>(V)->getOperand(0);
03054     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
03055       if (GA->mayBeOverridden())
03056         return V;
03057       V = GA->getAliasee();
03058     } else {
03059       // See if InstructionSimplify knows any relevant tricks.
03060       if (Instruction *I = dyn_cast<Instruction>(V))
03061         // TODO: Acquire a DominatorTree and AssumptionCache and use them.
03062         if (Value *Simplified = SimplifyInstruction(I, DL, nullptr)) {
03063           V = Simplified;
03064           continue;
03065         }
03066 
03067       return V;
03068     }
03069     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
03070   }
03071   return V;
03072 }
03073 
03074 void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
03075                                 const DataLayout &DL, LoopInfo *LI,
03076                                 unsigned MaxLookup) {
03077   SmallPtrSet<Value *, 4> Visited;
03078   SmallVector<Value *, 4> Worklist;
03079   Worklist.push_back(V);
03080   do {
03081     Value *P = Worklist.pop_back_val();
03082     P = GetUnderlyingObject(P, DL, MaxLookup);
03083 
03084     if (!Visited.insert(P).second)
03085       continue;
03086 
03087     if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
03088       Worklist.push_back(SI->getTrueValue());
03089       Worklist.push_back(SI->getFalseValue());
03090       continue;
03091     }
03092 
03093     if (PHINode *PN = dyn_cast<PHINode>(P)) {
03094       // If this PHI changes the underlying object in every iteration of the
03095       // loop, don't look through it.  Consider:
03096       //   int **A;
03097       //   for (i) {
03098       //     Prev = Curr;     // Prev = PHI (Prev_0, Curr)
03099       //     Curr = A[i];
03100       //     *Prev, *Curr;
03101       //
03102       // Prev is tracking Curr one iteration behind so they refer to different
03103       // underlying objects.
03104       if (!LI || !LI->isLoopHeader(PN->getParent()) ||
03105           isSameUnderlyingObjectInLoop(PN, LI))
03106         for (Value *IncValue : PN->incoming_values())
03107           Worklist.push_back(IncValue);
03108       continue;
03109     }
03110 
03111     Objects.push_back(P);
03112   } while (!Worklist.empty());
03113 }
03114 
03115 /// Return true if the only users of this pointer are lifetime markers.
03116 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
03117   for (const User *U : V->users()) {
03118     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
03119     if (!II) return false;
03120 
03121     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
03122         II->getIntrinsicID() != Intrinsic::lifetime_end)
03123       return false;
03124   }
03125   return true;
03126 }
03127 
03128 static bool isDereferenceableFromAttribute(const Value *BV, APInt Offset,
03129                                            Type *Ty, const DataLayout &DL,
03130                                            const Instruction *CtxI,
03131                                            const DominatorTree *DT,
03132                                            const TargetLibraryInfo *TLI) {
03133   assert(Offset.isNonNegative() && "offset can't be negative");
03134   assert(Ty->isSized() && "must be sized");
03135   
03136   APInt DerefBytes(Offset.getBitWidth(), 0);
03137   bool CheckForNonNull = false;
03138   if (const Argument *A = dyn_cast<Argument>(BV)) {
03139     DerefBytes = A->getDereferenceableBytes();
03140     if (!DerefBytes.getBoolValue()) {
03141       DerefBytes = A->getDereferenceableOrNullBytes();
03142       CheckForNonNull = true;
03143     }
03144   } else if (auto CS = ImmutableCallSite(BV)) {
03145     DerefBytes = CS.getDereferenceableBytes(0);
03146     if (!DerefBytes.getBoolValue()) {
03147       DerefBytes = CS.getDereferenceableOrNullBytes(0);
03148       CheckForNonNull = true;
03149     }
03150   } else if (const LoadInst *LI = dyn_cast<LoadInst>(BV)) {
03151     if (MDNode *MD = LI->getMetadata(LLVMContext::MD_dereferenceable)) {
03152       ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
03153       DerefBytes = CI->getLimitedValue();
03154     }
03155     if (!DerefBytes.getBoolValue()) {
03156       if (MDNode *MD = 
03157               LI->getMetadata(LLVMContext::MD_dereferenceable_or_null)) {
03158         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(0));
03159         DerefBytes = CI->getLimitedValue();
03160       }
03161       CheckForNonNull = true;
03162     }
03163   }
03164   
03165   if (DerefBytes.getBoolValue())
03166     if (DerefBytes.uge(Offset + DL.getTypeStoreSize(Ty)))
03167       if (!CheckForNonNull || isKnownNonNullAt(BV, CtxI, DT, TLI))
03168         return true;
03169 
03170   return false;
03171 }
03172 
03173 static bool isDereferenceableFromAttribute(const Value *V, const DataLayout &DL,
03174                                            const Instruction *CtxI,
03175                                            const DominatorTree *DT,
03176                                            const TargetLibraryInfo *TLI) {
03177   Type *VTy = V->getType();
03178   Type *Ty = VTy->getPointerElementType();
03179   if (!Ty->isSized())
03180     return false;
03181   
03182   APInt Offset(DL.getTypeStoreSizeInBits(VTy), 0);
03183   return isDereferenceableFromAttribute(V, Offset, Ty, DL, CtxI, DT, TLI);
03184 }
03185 
03186 static bool isAligned(const Value *Base, APInt Offset, unsigned Align,
03187                       const DataLayout &DL) {
03188   APInt BaseAlign(Offset.getBitWidth(), getAlignment(Base, DL));
03189 
03190   if (!BaseAlign) {
03191     Type *Ty = Base->getType()->getPointerElementType();
03192     if (!Ty->isSized())
03193       return false;
03194     BaseAlign = DL.getABITypeAlignment(Ty);
03195   }
03196 
03197   APInt Alignment(Offset.getBitWidth(), Align);
03198 
03199   assert(Alignment.isPowerOf2() && "must be a power of 2!");
03200   return BaseAlign.uge(Alignment) && !(Offset & (Alignment-1));
03201 }
03202 
03203 static bool isAligned(const Value *Base, unsigned Align, const DataLayout &DL) {
03204   Type *Ty = Base->getType();
03205   assert(Ty->isSized() && "must be sized");
03206   APInt Offset(DL.getTypeStoreSizeInBits(Ty), 0);
03207   return isAligned(Base, Offset, Align, DL);
03208 }
03209 
03210 /// Test if V is always a pointer to allocated and suitably aligned memory for
03211 /// a simple load or store.
03212 static bool isDereferenceableAndAlignedPointer(
03213     const Value *V, unsigned Align, const DataLayout &DL,
03214     const Instruction *CtxI, const DominatorTree *DT,
03215     const TargetLibraryInfo *TLI, SmallPtrSetImpl<const Value *> &Visited) {
03216   // Note that it is not safe to speculate into a malloc'd region because
03217   // malloc may return null.
03218 
03219   // These are obviously ok if aligned.
03220   if (isa<AllocaInst>(V))
03221     return isAligned(V, Align, DL);
03222 
03223   // It's not always safe to follow a bitcast, for example:
03224   //   bitcast i8* (alloca i8) to i32*
03225   // would result in a 4-byte load from a 1-byte alloca. However,
03226   // if we're casting from a pointer from a type of larger size
03227   // to a type of smaller size (or the same size), and the alignment
03228   // is at least as large as for the resulting pointer type, then
03229   // we can look through the bitcast.
03230   if (const BitCastOperator *BC = dyn_cast<BitCastOperator>(V)) {
03231     Type *STy = BC->getSrcTy()->getPointerElementType(),
03232          *DTy = BC->getDestTy()->getPointerElementType();
03233     if (STy->isSized() && DTy->isSized() &&
03234         (DL.getTypeStoreSize(STy) >= DL.getTypeStoreSize(DTy)) &&
03235         (DL.getABITypeAlignment(STy) >= DL.getABITypeAlignment(DTy)))
03236       return isDereferenceableAndAlignedPointer(BC->getOperand(0), Align, DL,
03237                                                 CtxI, DT, TLI, Visited);
03238   }
03239 
03240   // Global variables which can't collapse to null are ok.
03241   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
03242     if (!GV->hasExternalWeakLinkage())
03243       return isAligned(V, Align, DL);
03244 
03245   // byval arguments are okay.
03246   if (const Argument *A = dyn_cast<Argument>(V))
03247     if (A->hasByValAttr())
03248       return isAligned(V, Align, DL);
03249 
03250   if (isDereferenceableFromAttribute(V, DL, CtxI, DT, TLI))
03251     return isAligned(V, Align, DL);
03252 
03253   // For GEPs, determine if the indexing lands within the allocated object.
03254   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
03255     Type *Ty = GEP->getResultElementType();
03256     const Value *Base = GEP->getPointerOperand();
03257 
03258     // Conservatively require that the base pointer be fully dereferenceable
03259     // and aligned.
03260     if (!Visited.insert(Base).second)
03261       return false;
03262     if (!isDereferenceableAndAlignedPointer(Base, Align, DL, CtxI, DT, TLI,
03263                                             Visited))
03264       return false;
03265 
03266     APInt Offset(DL.getPointerTypeSizeInBits(GEP->getType()), 0);
03267     if (!GEP->accumulateConstantOffset(DL, Offset))
03268       return false;
03269 
03270     // Check if the load is within the bounds of the underlying object
03271     // and offset is aligned.
03272     uint64_t LoadSize = DL.getTypeStoreSize(Ty);
03273     Type *BaseType = GEP->getSourceElementType();
03274     assert(isPowerOf2_32(Align) && "must be a power of 2!");
03275     return (Offset + LoadSize).ule(DL.getTypeAllocSize(BaseType)) && 
03276            !(Offset & APInt(Offset.getBitWidth(), Align-1));
03277   }
03278 
03279   // For gc.relocate, look through relocations
03280   if (const GCRelocateInst *RelocateInst = dyn_cast<GCRelocateInst>(V))
03281     return isDereferenceableAndAlignedPointer(
03282         RelocateInst->getDerivedPtr(), Align, DL, CtxI, DT, TLI, Visited);
03283 
03284   if (const AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(V))
03285     return isDereferenceableAndAlignedPointer(ASC->getOperand(0), Align, DL,
03286                                               CtxI, DT, TLI, Visited);
03287 
03288   // If we don't know, assume the worst.
03289   return false;
03290 }
03291 
03292 bool llvm::isDereferenceableAndAlignedPointer(const Value *V, unsigned Align,
03293                                               const DataLayout &DL,
03294                                               const Instruction *CtxI,
03295                                               const DominatorTree *DT,
03296                                               const TargetLibraryInfo *TLI) {
03297   // When dereferenceability information is provided by a dereferenceable
03298   // attribute, we know exactly how many bytes are dereferenceable. If we can
03299   // determine the exact offset to the attributed variable, we can use that
03300   // information here.
03301   Type *VTy = V->getType();
03302   Type *Ty = VTy->getPointerElementType();
03303 
03304   // Require ABI alignment for loads without alignment specification
03305   if (Align == 0)
03306     Align = DL.getABITypeAlignment(Ty);
03307 
03308   if (Ty->isSized()) {
03309     APInt Offset(DL.getTypeStoreSizeInBits(VTy), 0);
03310     const Value *BV = V->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
03311 
03312     if (Offset.isNonNegative())
03313       if (isDereferenceableFromAttribute(BV, Offset, Ty, DL, CtxI, DT, TLI) &&
03314           isAligned(BV, Offset, Align, DL))
03315         return true;
03316   }
03317 
03318   SmallPtrSet<const Value *, 32> Visited;
03319   return ::isDereferenceableAndAlignedPointer(V, Align, DL, CtxI, DT, TLI,
03320                                               Visited);
03321 }
03322 
03323 bool llvm::isDereferenceablePointer(const Value *V, const DataLayout &DL,
03324                                     const Instruction *CtxI,
03325                                     const DominatorTree *DT,
03326                                     const TargetLibraryInfo *TLI) {
03327   return isDereferenceableAndAlignedPointer(V, 1, DL, CtxI, DT, TLI);
03328 }
03329 
03330 bool llvm::isSafeToSpeculativelyExecute(const Value *V,
03331                                         const Instruction *CtxI,
03332                                         const DominatorTree *DT,
03333                                         const TargetLibraryInfo *TLI) {
03334   const Operator *Inst = dyn_cast<Operator>(V);
03335   if (!Inst)
03336     return false;
03337 
03338   for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
03339     if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
03340       if (C->canTrap())
03341         return false;
03342 
03343   switch (Inst->getOpcode()) {
03344   default:
03345     return true;
03346   case Instruction::UDiv:
03347   case Instruction::URem: {
03348     // x / y is undefined if y == 0.
03349     const APInt *V;
03350     if (match(Inst->getOperand(1), m_APInt(V)))
03351       return *V != 0;
03352     return false;
03353   }
03354   case Instruction::SDiv:
03355   case Instruction::SRem: {
03356     // x / y is undefined if y == 0 or x == INT_MIN and y == -1
03357     const APInt *Numerator, *Denominator;
03358     if (!match(Inst->getOperand(1), m_APInt(Denominator)))
03359       return false;
03360     // We cannot hoist this division if the denominator is 0.
03361     if (*Denominator == 0)
03362       return false;
03363     // It's safe to hoist if the denominator is not 0 or -1.
03364     if (*Denominator != -1)
03365       return true;
03366     // At this point we know that the denominator is -1.  It is safe to hoist as
03367     // long we know that the numerator is not INT_MIN.
03368     if (match(Inst->getOperand(0), m_APInt(Numerator)))
03369       return !Numerator->isMinSignedValue();
03370     // The numerator *might* be MinSignedValue.
03371     return false;
03372   }
03373   case Instruction::Load: {
03374     const LoadInst *LI = cast<LoadInst>(Inst);
03375     if (!LI->isUnordered() ||
03376         // Speculative load may create a race that did not exist in the source.
03377         LI->getParent()->getParent()->hasFnAttribute(
03378             Attribute::SanitizeThread) ||
03379         // Speculative load may load data from dirty regions.
03380         LI->getParent()->getParent()->hasFnAttribute(
03381             Attribute::SanitizeAddress))
03382       return false;
03383     const DataLayout &DL = LI->getModule()->getDataLayout();
03384     return isDereferenceableAndAlignedPointer(
03385         LI->getPointerOperand(), LI->getAlignment(), DL, CtxI, DT, TLI);
03386   }
03387   case Instruction::Call: {
03388     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
03389       switch (II->getIntrinsicID()) {
03390       // These synthetic intrinsics have no side-effects and just mark
03391       // information about their operands.
03392       // FIXME: There are other no-op synthetic instructions that potentially
03393       // should be considered at least *safe* to speculate...
03394       case Intrinsic::dbg_declare:
03395       case Intrinsic::dbg_value:
03396         return true;
03397 
03398       case Intrinsic::bswap:
03399       case Intrinsic::ctlz:
03400       case Intrinsic::ctpop:
03401       case Intrinsic::cttz:
03402       case Intrinsic::objectsize:
03403       case Intrinsic::sadd_with_overflow:
03404       case Intrinsic::smul_with_overflow:
03405       case Intrinsic::ssub_with_overflow:
03406       case Intrinsic::uadd_with_overflow:
03407       case Intrinsic::umul_with_overflow:
03408       case Intrinsic::usub_with_overflow:
03409         return true;
03410       // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
03411       // errno like libm sqrt would.
03412       case Intrinsic::sqrt:
03413       case Intrinsic::fma:
03414       case Intrinsic::fmuladd:
03415       case Intrinsic::fabs:
03416       case Intrinsic::minnum:
03417       case Intrinsic::maxnum:
03418         return true;
03419       // TODO: some fp intrinsics are marked as having the same error handling
03420       // as libm. They're safe to speculate when they won't error.
03421       // TODO: are convert_{from,to}_fp16 safe?
03422       // TODO: can we list target-specific intrinsics here?
03423       default: break;
03424       }
03425     }
03426     return false; // The called function could have undefined behavior or
03427                   // side-effects, even if marked readnone nounwind.
03428   }
03429   case Instruction::VAArg:
03430   case Instruction::Alloca:
03431   case Instruction::Invoke:
03432   case Instruction::PHI:
03433   case Instruction::Store:
03434   case Instruction::Ret:
03435   case Instruction::Br:
03436   case Instruction::IndirectBr:
03437   case Instruction::Switch:
03438   case Instruction::Unreachable:
03439   case Instruction::Fence:
03440   case Instruction::AtomicRMW:
03441   case Instruction::AtomicCmpXchg:
03442   case Instruction::LandingPad:
03443   case Instruction::Resume:
03444   case Instruction::CatchSwitch:
03445   case Instruction::CatchPad:
03446   case Instruction::CatchRet:
03447   case Instruction::CleanupPad:
03448   case Instruction::CleanupRet:
03449     return false; // Misc instructions which have effects
03450   }
03451 }
03452 
03453 bool llvm::mayBeMemoryDependent(const Instruction &I) {
03454   return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
03455 }
03456 
03457 /// Return true if we know that the specified value is never null.
03458 bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
03459   assert(V->getType()->isPointerTy() && "V must be pointer type");
03460 
03461   // Alloca never returns null, malloc might.
03462   if (isa<AllocaInst>(V)) return true;
03463 
03464   // A byval, inalloca, or nonnull argument is never null.
03465   if (const Argument *A = dyn_cast<Argument>(V))
03466     return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
03467 
03468   // A global variable in address space 0 is non null unless extern weak.
03469   // Other address spaces may have null as a valid address for a global,
03470   // so we can't assume anything.
03471   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
03472     return !GV->hasExternalWeakLinkage() &&
03473            GV->getType()->getAddressSpace() == 0;
03474 
03475   // A Load tagged w/nonnull metadata is never null. 
03476   if (const LoadInst *LI = dyn_cast<LoadInst>(V))
03477     return LI->getMetadata(LLVMContext::MD_nonnull);
03478 
03479   if (auto CS = ImmutableCallSite(V))
03480     if (CS.isReturnNonNull())
03481       return true;
03482 
03483   return false;
03484 }
03485 
03486 static bool isKnownNonNullFromDominatingCondition(const Value *V,
03487                                                   const Instruction *CtxI,
03488                                                   const DominatorTree *DT) {
03489   assert(V->getType()->isPointerTy() && "V must be pointer type");
03490 
03491   unsigned NumUsesExplored = 0;
03492   for (auto U : V->users()) {
03493     // Avoid massive lists
03494     if (NumUsesExplored >= DomConditionsMaxUses)
03495       break;
03496     NumUsesExplored++;
03497     // Consider only compare instructions uniquely controlling a branch
03498     const ICmpInst *Cmp = dyn_cast<ICmpInst>(U);
03499     if (!Cmp)
03500       continue;
03501 
03502     if (DomConditionsSingleCmpUse && !Cmp->hasOneUse())
03503       continue;
03504 
03505     for (auto *CmpU : Cmp->users()) {
03506       const BranchInst *BI = dyn_cast<BranchInst>(CmpU);
03507       if (!BI)
03508         continue;
03509       
03510       assert(BI->isConditional() && "uses a comparison!");
03511 
03512       BasicBlock *NonNullSuccessor = nullptr;
03513       CmpInst::Predicate Pred;
03514 
03515       if (match(const_cast<ICmpInst*>(Cmp),
03516                 m_c_ICmp(Pred, m_Specific(V), m_Zero()))) {
03517         if (Pred == ICmpInst::ICMP_EQ)
03518           NonNullSuccessor = BI->getSuccessor(1);
03519         else if (Pred == ICmpInst::ICMP_NE)
03520           NonNullSuccessor = BI->getSuccessor(0);
03521       }
03522 
03523       if (NonNullSuccessor) {
03524         BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
03525         if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
03526           return true;
03527       }
03528     }
03529   }
03530 
03531   return false;
03532 }
03533 
03534 bool llvm::isKnownNonNullAt(const Value *V, const Instruction *CtxI,
03535                    const DominatorTree *DT, const TargetLibraryInfo *TLI) {
03536   if (isKnownNonNull(V, TLI))
03537     return true;
03538 
03539   return CtxI ? ::isKnownNonNullFromDominatingCondition(V, CtxI, DT) : false;
03540 }
03541 
03542 OverflowResult llvm::computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
03543                                                    const DataLayout &DL,
03544                                                    AssumptionCache *AC,
03545                                                    const Instruction *CxtI,
03546                                                    const DominatorTree *DT) {
03547   // Multiplying n * m significant bits yields a result of n + m significant
03548   // bits. If the total number of significant bits does not exceed the
03549   // result bit width (minus 1), there is no overflow.
03550   // This means if we have enough leading zero bits in the operands
03551   // we can guarantee that the result does not overflow.
03552   // Ref: "Hacker's Delight" by Henry Warren
03553   unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
03554   APInt LHSKnownZero(BitWidth, 0);
03555   APInt LHSKnownOne(BitWidth, 0);
03556   APInt RHSKnownZero(BitWidth, 0);
03557   APInt RHSKnownOne(BitWidth, 0);
03558   computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
03559                    DT);
03560   computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
03561                    DT);
03562   // Note that underestimating the number of zero bits gives a more
03563   // conservative answer.
03564   unsigned ZeroBits = LHSKnownZero.countLeadingOnes() +
03565                       RHSKnownZero.countLeadingOnes();
03566   // First handle the easy case: if we have enough zero bits there's
03567   // definitely no overflow.
03568   if (ZeroBits >= BitWidth)
03569     return OverflowResult::NeverOverflows;
03570 
03571   // Get the largest possible values for each operand.
03572   APInt LHSMax = ~LHSKnownZero;
03573   APInt RHSMax = ~RHSKnownZero;
03574 
03575   // We know the multiply operation doesn't overflow if the maximum values for
03576   // each operand will not overflow after we multiply them together.
03577   bool MaxOverflow;
03578   LHSMax.umul_ov(RHSMax, MaxOverflow);
03579   if (!MaxOverflow)
03580     return OverflowResult::NeverOverflows;
03581 
03582   // We know it always overflows if multiplying the smallest possible values for
03583   // the operands also results in overflow.
03584   bool MinOverflow;
03585   LHSKnownOne.umul_ov(RHSKnownOne, MinOverflow);
03586   if (MinOverflow)
03587     return OverflowResult::AlwaysOverflows;
03588 
03589   return OverflowResult::MayOverflow;
03590 }
03591 
03592 OverflowResult llvm::computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
03593                                                    const DataLayout &DL,
03594                                                    AssumptionCache *AC,
03595                                                    const Instruction *CxtI,
03596                                                    const DominatorTree *DT) {
03597   bool LHSKnownNonNegative, LHSKnownNegative;
03598   ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
03599                  AC, CxtI, DT);
03600   if (LHSKnownNonNegative || LHSKnownNegative) {
03601     bool RHSKnownNonNegative, RHSKnownNegative;
03602     ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
03603                    AC, CxtI, DT);
03604 
03605     if (LHSKnownNegative && RHSKnownNegative) {
03606       // The sign bit is set in both cases: this MUST overflow.
03607       // Create a simple add instruction, and insert it into the struct.
03608       return OverflowResult::AlwaysOverflows;
03609     }
03610 
03611     if (LHSKnownNonNegative && RHSKnownNonNegative) {
03612       // The sign bit is clear in both cases: this CANNOT overflow.
03613       // Create a simple add instruction, and insert it into the struct.
03614       return OverflowResult::NeverOverflows;
03615     }
03616   }
03617 
03618   return OverflowResult::MayOverflow;
03619 }
03620 
03621 static OverflowResult computeOverflowForSignedAdd(
03622     Value *LHS, Value *RHS, AddOperator *Add, const DataLayout &DL,
03623     AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT) {
03624   if (Add && Add->hasNoSignedWrap()) {
03625     return OverflowResult::NeverOverflows;
03626   }
03627 
03628   bool LHSKnownNonNegative, LHSKnownNegative;
03629   bool RHSKnownNonNegative, RHSKnownNegative;
03630   ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
03631                  AC, CxtI, DT);
03632   ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
03633                  AC, CxtI, DT);
03634 
03635   if ((LHSKnownNonNegative && RHSKnownNegative) ||
03636       (LHSKnownNegative && RHSKnownNonNegative)) {
03637     // The sign bits are opposite: this CANNOT overflow.
03638     return OverflowResult::NeverOverflows;
03639   }
03640 
03641   // The remaining code needs Add to be available. Early returns if not so.
03642   if (!Add)
03643     return OverflowResult::MayOverflow;
03644 
03645   // If the sign of Add is the same as at least one of the operands, this add
03646   // CANNOT overflow. This is particularly useful when the sum is
03647   // @llvm.assume'ed non-negative rather than proved so from analyzing its
03648   // operands.
03649   bool LHSOrRHSKnownNonNegative =
03650       (LHSKnownNonNegative || RHSKnownNonNegative);
03651   bool LHSOrRHSKnownNegative = (LHSKnownNegative || RHSKnownNegative);
03652   if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
03653     bool AddKnownNonNegative, AddKnownNegative;
03654     ComputeSignBit(Add, AddKnownNonNegative, AddKnownNegative, DL,
03655                    /*Depth=*/0, AC, CxtI, DT);
03656     if ((AddKnownNonNegative && LHSOrRHSKnownNonNegative) ||
03657         (AddKnownNegative && LHSOrRHSKnownNegative)) {
03658       return OverflowResult::NeverOverflows;
03659     }
03660   }
03661 
03662   return OverflowResult::MayOverflow;
03663 }
03664 
03665 OverflowResult llvm::computeOverflowForSignedAdd(AddOperator *Add,
03666                                                  const DataLayout &DL,
03667                                                  AssumptionCache *AC,
03668                                                  const Instruction *CxtI,
03669                                                  const DominatorTree *DT) {
03670   return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
03671                                        Add, DL, AC, CxtI, DT);
03672 }
03673 
03674 OverflowResult llvm::computeOverflowForSignedAdd(Value *LHS, Value *RHS,
03675                                                  const DataLayout &DL,
03676                                                  AssumptionCache *AC,
03677                                                  const Instruction *CxtI,
03678                                                  const DominatorTree *DT) {
03679   return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
03680 }
03681 
03682 bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
03683   // FIXME: This conservative implementation can be relaxed. E.g. most
03684   // atomic operations are guaranteed to terminate on most platforms
03685   // and most functions terminate.
03686 
03687   return !I->isAtomic() &&       // atomics may never succeed on some platforms
03688          !isa<CallInst>(I) &&    // could throw and might not terminate
03689          !isa<InvokeInst>(I) &&  // might not terminate and could throw to
03690                                  //   non-successor (see bug 24185 for details).
03691          !isa<ResumeInst>(I) &&  // has no successors
03692          !isa<ReturnInst>(I);    // has no successors
03693 }
03694 
03695 bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
03696                                                   const Loop *L) {
03697   // The loop header is guaranteed to be executed for every iteration.
03698   //
03699   // FIXME: Relax this constraint to cover all basic blocks that are
03700   // guaranteed to be executed at every iteration.
03701   if (I->getParent() != L->getHeader()) return false;
03702 
03703   for (const Instruction &LI : *L->getHeader()) {
03704     if (&LI == I) return true;
03705     if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
03706   }
03707   llvm_unreachable("Instruction not contained in its own parent basic block.");
03708 }
03709 
03710 bool llvm::propagatesFullPoison(const Instruction *I) {
03711   switch (I->getOpcode()) {
03712     case Instruction::Add:
03713     case Instruction::Sub:
03714     case Instruction::Xor:
03715     case Instruction::Trunc:
03716     case Instruction::BitCast:
03717     case Instruction::AddrSpaceCast:
03718       // These operations all propagate poison unconditionally. Note that poison
03719       // is not any particular value, so xor or subtraction of poison with
03720       // itself still yields poison, not zero.
03721       return true;
03722 
03723     case Instruction::AShr:
03724     case Instruction::SExt:
03725       // For these operations, one bit of the input is replicated across
03726       // multiple output bits. A replicated poison bit is still poison.
03727       return true;
03728 
03729     case Instruction::Shl: {
03730       // Left shift *by* a poison value is poison. The number of
03731       // positions to shift is unsigned, so no negative values are
03732       // possible there. Left shift by zero places preserves poison. So
03733       // it only remains to consider left shift of poison by a positive
03734       // number of places.
03735       //
03736       // A left shift by a positive number of places leaves the lowest order bit
03737       // non-poisoned. However, if such a shift has a no-wrap flag, then we can
03738       // make the poison operand violate that flag, yielding a fresh full-poison
03739       // value.
03740       auto *OBO = cast<OverflowingBinaryOperator>(I);
03741       return OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap();
03742     }
03743 
03744     case Instruction::Mul: {
03745       // A multiplication by zero yields a non-poison zero result, so we need to
03746       // rule out zero as an operand. Conservatively, multiplication by a
03747       // non-zero constant is not multiplication by zero.
03748       //
03749       // Multiplication by a non-zero constant can leave some bits
03750       // non-poisoned. For example, a multiplication by 2 leaves the lowest
03751       // order bit unpoisoned. So we need to consider that.
03752       //
03753       // Multiplication by 1 preserves poison. If the multiplication has a
03754       // no-wrap flag, then we can make the poison operand violate that flag
03755       // when multiplied by any integer other than 0 and 1.
03756       auto *OBO = cast<OverflowingBinaryOperator>(I);
03757       if (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) {
03758         for (Value *V : OBO->operands()) {
03759           if (auto *CI = dyn_cast<ConstantInt>(V)) {
03760             // A ConstantInt cannot yield poison, so we can assume that it is
03761             // the other operand that is poison.
03762             return !CI->isZero();
03763           }
03764         }
03765       }
03766       return false;
03767     }
03768 
03769     case Instruction::GetElementPtr:
03770       // A GEP implicitly represents a sequence of additions, subtractions,
03771       // truncations, sign extensions and multiplications. The multiplications
03772       // are by the non-zero sizes of some set of types, so we do not have to be
03773       // concerned with multiplication by zero. If the GEP is in-bounds, then
03774       // these operations are implicitly no-signed-wrap so poison is propagated
03775       // by the arguments above for Add, Sub, Trunc, SExt and Mul.
03776       return cast<GEPOperator>(I)->isInBounds();
03777 
03778     default:
03779       return false;
03780   }
03781 }
03782 
03783 const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
03784   switch (I->getOpcode()) {
03785     case Instruction::Store:
03786       return cast<StoreInst>(I)->getPointerOperand();
03787 
03788     case Instruction::Load:
03789       return cast<LoadInst>(I)->getPointerOperand();
03790 
03791     case Instruction::AtomicCmpXchg:
03792       return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
03793 
03794     case Instruction::AtomicRMW:
03795       return cast<AtomicRMWInst>(I)->getPointerOperand();
03796 
03797     case Instruction::UDiv:
03798     case Instruction::SDiv:
03799     case Instruction::URem:
03800     case Instruction::SRem:
03801       return I->getOperand(1);
03802 
03803     default:
03804       return nullptr;
03805   }
03806 }
03807 
03808 bool llvm::isKnownNotFullPoison(const Instruction *PoisonI) {
03809   // We currently only look for uses of poison values within the same basic
03810   // block, as that makes it easier to guarantee that the uses will be
03811   // executed given that PoisonI is executed.
03812   //
03813   // FIXME: Expand this to consider uses beyond the same basic block. To do
03814   // this, look out for the distinction between post-dominance and strong
03815   // post-dominance.
03816   const BasicBlock *BB = PoisonI->getParent();
03817 
03818   // Set of instructions that we have proved will yield poison if PoisonI
03819   // does.
03820   SmallSet<const Value *, 16> YieldsPoison;
03821   YieldsPoison.insert(PoisonI);
03822 
03823   for (BasicBlock::const_iterator I = PoisonI->getIterator(), E = BB->end();
03824        I != E; ++I) {
03825     if (&*I != PoisonI) {
03826       const Value *NotPoison = getGuaranteedNonFullPoisonOp(&*I);
03827       if (NotPoison != nullptr && YieldsPoison.count(NotPoison)) return true;
03828       if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
03829         return false;
03830     }
03831 
03832     // Mark poison that propagates from I through uses of I.
03833     if (YieldsPoison.count(&*I)) {
03834       for (const User *User : I->users()) {
03835         const Instruction *UserI = cast<Instruction>(User);
03836         if (UserI->getParent() == BB && propagatesFullPoison(UserI))
03837           YieldsPoison.insert(User);
03838       }
03839     }
03840   }
03841   return false;
03842 }
03843 
03844 static bool isKnownNonNaN(Value *V, FastMathFlags FMF) {
03845   if (FMF.noNaNs())
03846     return true;
03847 
03848   if (auto *C = dyn_cast<ConstantFP>(V))
03849     return !C->isNaN();
03850   return false;
03851 }
03852 
03853 static bool isKnownNonZero(Value *V) {
03854   if (auto *C = dyn_cast<ConstantFP>(V))
03855     return !C->isZero();
03856   return false;
03857 }
03858 
03859 static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
03860                                               FastMathFlags FMF,
03861                                               Value *CmpLHS, Value *CmpRHS,
03862                                               Value *TrueVal, Value *FalseVal,
03863                                               Value *&LHS, Value *&RHS) {
03864   LHS = CmpLHS;
03865   RHS = CmpRHS;
03866 
03867   // If the predicate is an "or-equal"  (FP) predicate, then signed zeroes may
03868   // return inconsistent results between implementations.
03869   //   (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
03870   //   minNum(0.0, -0.0)          // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
03871   // Therefore we behave conservatively and only proceed if at least one of the
03872   // operands is known to not be zero, or if we don't care about signed zeroes.
03873   switch (Pred) {
03874   default: break;
03875   case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
03876   case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
03877     if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
03878         !isKnownNonZero(CmpRHS))
03879       return {SPF_UNKNOWN, SPNB_NA, false};
03880   }
03881 
03882   SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
03883   bool Ordered = false;
03884 
03885   // When given one NaN and one non-NaN input:
03886   //   - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
03887   //   - A simple C99 (a < b ? a : b) construction will return 'b' (as the
03888   //     ordered comparison fails), which could be NaN or non-NaN.
03889   // so here we discover exactly what NaN behavior is required/accepted.
03890   if (CmpInst::isFPPredicate(Pred)) {
03891     bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
03892     bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
03893 
03894     if (LHSSafe && RHSSafe) {
03895       // Both operands are known non-NaN.
03896       NaNBehavior = SPNB_RETURNS_ANY;
03897     } else if (CmpInst::isOrdered(Pred)) {
03898       // An ordered comparison will return false when given a NaN, so it
03899       // returns the RHS.
03900       Ordered = true;
03901       if (LHSSafe)
03902         // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
03903         NaNBehavior = SPNB_RETURNS_NAN;
03904       else if (RHSSafe)
03905         NaNBehavior = SPNB_RETURNS_OTHER;
03906       else
03907         // Completely unsafe.
03908         return {SPF_UNKNOWN, SPNB_NA, false};
03909     } else {
03910       Ordered = false;
03911       // An unordered comparison will return true when given a NaN, so it
03912       // returns the LHS.
03913       if (LHSSafe)
03914         // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
03915         NaNBehavior = SPNB_RETURNS_OTHER;
03916       else if (RHSSafe)
03917         NaNBehavior = SPNB_RETURNS_NAN;
03918       else
03919         // Completely unsafe.
03920         return {SPF_UNKNOWN, SPNB_NA, false};
03921     }
03922   }
03923 
03924   if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
03925     std::swap(CmpLHS, CmpRHS);
03926     Pred = CmpInst::getSwappedPredicate(Pred);
03927     if (NaNBehavior == SPNB_RETURNS_NAN)
03928       NaNBehavior = SPNB_RETURNS_OTHER;
03929     else if (NaNBehavior == SPNB_RETURNS_OTHER)
03930       NaNBehavior = SPNB_RETURNS_NAN;
03931     Ordered = !Ordered;
03932   }
03933 
03934   // ([if]cmp X, Y) ? X : Y
03935   if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
03936     switch (Pred) {
03937     default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
03938     case ICmpInst::ICMP_UGT:
03939     case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
03940     case ICmpInst::ICMP_SGT:
03941     case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
03942     case ICmpInst::ICMP_ULT:
03943     case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
03944     case ICmpInst::ICMP_SLT:
03945     case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
03946     case FCmpInst::FCMP_UGT:
03947     case FCmpInst::FCMP_UGE:
03948     case FCmpInst::FCMP_OGT:
03949     case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
03950     case FCmpInst::FCMP_ULT:
03951     case FCmpInst::FCMP_ULE:
03952     case FCmpInst::FCMP_OLT:
03953     case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
03954     }
03955   }
03956 
03957   if (ConstantInt *C1 = dyn_cast<ConstantInt>(CmpRHS)) {
03958     if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
03959         (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
03960 
03961       // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
03962       // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
03963       if (Pred == ICmpInst::ICMP_SGT && (C1->isZero() || C1->isMinusOne())) {
03964         return {(CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
03965       }
03966 
03967       // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
03968       // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
03969       if (Pred == ICmpInst::ICMP_SLT && (C1->isZero() || C1->isOne())) {
03970         return {(CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
03971       }
03972     }
03973     
03974     // Y >s C ? ~Y : ~C == ~Y <s ~C ? ~Y : ~C = SMIN(~Y, ~C)
03975     if (const auto *C2 = dyn_cast<ConstantInt>(FalseVal)) {
03976       if (C1->getType() == C2->getType() && ~C1->getValue() == C2->getValue() &&
03977           (match(TrueVal, m_Not(m_Specific(CmpLHS))) ||
03978            match(CmpLHS, m_Not(m_Specific(TrueVal))))) {
03979         LHS = TrueVal;
03980         RHS = FalseVal;
03981         return {SPF_SMIN, SPNB_NA, false};
03982       }
03983     }
03984   }
03985 
03986   // TODO: (X > 4) ? X : 5   -->  (X >= 5) ? X : 5  -->  MAX(X, 5)
03987 
03988   return {SPF_UNKNOWN, SPNB_NA, false};
03989 }
03990 
03991 static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
03992                               Instruction::CastOps *CastOp) {
03993   CastInst *CI = dyn_cast<CastInst>(V1);
03994   Constant *C = dyn_cast<Constant>(V2);
03995   CastInst *CI2 = dyn_cast<CastInst>(V2);
03996   if (!CI)
03997     return nullptr;
03998   *CastOp = CI->getOpcode();
03999 
04000   if (CI2) {
04001     // If V1 and V2 are both the same cast from the same type, we can look
04002     // through V1.
04003     if (CI2->getOpcode() == CI->getOpcode() &&
04004         CI2->getSrcTy() == CI->getSrcTy())
04005       return CI2->getOperand(0);
04006     return nullptr;
04007   } else if (!C) {
04008     return nullptr;
04009   }
04010 
04011   if (isa<SExtInst>(CI) && CmpI->isSigned()) {
04012     Constant *T = ConstantExpr::getTrunc(C, CI->getSrcTy());
04013     // This is only valid if the truncated value can be sign-extended
04014     // back to the original value.
04015     if (ConstantExpr::getSExt(T, C->getType()) == C)
04016       return T;
04017     return nullptr;
04018   }
04019   if (isa<ZExtInst>(CI) && CmpI->isUnsigned())
04020     return ConstantExpr::getTrunc(C, CI->getSrcTy());
04021 
04022   if (isa<TruncInst>(CI))
04023     return ConstantExpr::getIntegerCast(C, CI->getSrcTy(), CmpI->isSigned());
04024 
04025   if (isa<FPToUIInst>(CI))
04026     return ConstantExpr::getUIToFP(C, CI->getSrcTy(), true);
04027 
04028   if (isa<FPToSIInst>(CI))
04029     return ConstantExpr::getSIToFP(C, CI->getSrcTy(), true);
04030 
04031   if (isa<UIToFPInst>(CI))
04032     return ConstantExpr::getFPToUI(C, CI->getSrcTy(), true);
04033 
04034   if (isa<SIToFPInst>(CI))
04035     return ConstantExpr::getFPToSI(C, CI->getSrcTy(), true);
04036 
04037   if (isa<FPTruncInst>(CI))
04038     return ConstantExpr::getFPExtend(C, CI->getSrcTy(), true);
04039 
04040   if (isa<FPExtInst>(CI))
04041     return ConstantExpr::getFPTrunc(C, CI->getSrcTy(), true);
04042 
04043   return nullptr;
04044 }
04045 
04046 SelectPatternResult llvm::matchSelectPattern(Value *V,
04047                                              Value *&LHS, Value *&RHS,
04048                                              Instruction::CastOps *CastOp) {
04049   SelectInst *SI = dyn_cast<SelectInst>(V);
04050   if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
04051 
04052   CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
04053   if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
04054 
04055   CmpInst::Predicate Pred = CmpI->getPredicate();
04056   Value *CmpLHS = CmpI->getOperand(0);
04057   Value *CmpRHS = CmpI->getOperand(1);
04058   Value *TrueVal = SI->getTrueValue();
04059   Value *FalseVal = SI->getFalseValue();
04060   FastMathFlags FMF;
04061   if (isa<FPMathOperator>(CmpI))
04062     FMF = CmpI->getFastMathFlags();
04063 
04064   // Bail out early.
04065   if (CmpI->isEquality())
04066     return {SPF_UNKNOWN, SPNB_NA, false};
04067 
04068   // Deal with type mismatches.
04069   if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
04070     if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp))
04071       return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
04072                                   cast<CastInst>(TrueVal)->getOperand(0), C,
04073                                   LHS, RHS);
04074     if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp))
04075       return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
04076                                   C, cast<CastInst>(FalseVal)->getOperand(0),
04077                                   LHS, RHS);
04078   }
04079   return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
04080                               LHS, RHS);
04081 }
04082 
04083 ConstantRange llvm::getConstantRangeFromMetadata(MDNode &Ranges) {
04084   const unsigned NumRanges = Ranges.getNumOperands() / 2;
04085   assert(NumRanges >= 1 && "Must have at least one range!");
04086   assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
04087 
04088   auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));
04089   auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));
04090 
04091   ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
04092 
04093   for (unsigned i = 1; i < NumRanges; ++i) {
04094     auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
04095     auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
04096 
04097     // Note: unionWith will potentially create a range that contains values not
04098     // contained in any of the original N ranges.
04099     CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));
04100   }
04101 
04102   return CR;
04103 }
04104 
04105 /// Return true if "icmp Pred LHS RHS" is always true.
04106 static bool isTruePredicate(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
04107                             const DataLayout &DL, unsigned Depth,
04108                             AssumptionCache *AC, const Instruction *CxtI,
04109                             const DominatorTree *DT) {
04110   assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
04111   if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
04112     return true;
04113 
04114   switch (Pred) {
04115   default:
04116     return false;
04117 
04118   case CmpInst::ICMP_SLE: {
04119     const APInt *C;
04120 
04121     // LHS s<= LHS +_{nsw} C   if C >= 0
04122     if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
04123       return !C->isNegative();
04124     return false;
04125   }
04126 
04127   case CmpInst::ICMP_ULE: {
04128     const APInt *C;
04129 
04130     // LHS u<= LHS +_{nuw} C   for any C
04131     if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
04132       return true;
04133 
04134     // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
04135     auto MatchNUWAddsToSameValue = [&](Value *A, Value *B, Value *&X,
04136                                        const APInt *&CA, const APInt *&CB) {
04137       if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
04138           match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
04139         return true;
04140 
04141       // If X & C == 0 then (X | C) == X +_{nuw} C
04142       if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
04143           match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
04144         unsigned BitWidth = CA->getBitWidth();
04145         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
04146         computeKnownBits(X, KnownZero, KnownOne, DL, Depth + 1, AC, CxtI, DT);
04147 
04148         if ((KnownZero & *CA) == *CA && (KnownZero & *CB) == *CB)
04149           return true;
04150       }
04151 
04152       return false;
04153     };
04154 
04155     Value *X;
04156     const APInt *CLHS, *CRHS;
04157     if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
04158       return CLHS->ule(*CRHS);
04159 
04160     return false;
04161   }
04162   }
04163 }
04164 
04165 /// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
04166 /// ALHS ARHS" is true.
04167 static bool isImpliedCondOperands(CmpInst::Predicate Pred, Value *ALHS,
04168                                   Value *ARHS, Value *BLHS, Value *BRHS,
04169                                   const DataLayout &DL, unsigned Depth,
04170                                   AssumptionCache *AC, const Instruction *CxtI,
04171                                   const DominatorTree *DT) {
04172   switch (Pred) {
04173   default:
04174     return false;
04175 
04176   case CmpInst::ICMP_SLT:
04177   case CmpInst::ICMP_SLE:
04178     return isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth, AC, CxtI,
04179                            DT) &&
04180            isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth, AC, CxtI,
04181                            DT);
04182 
04183   case CmpInst::ICMP_ULT:
04184   case CmpInst::ICMP_ULE:
04185     return isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth, AC, CxtI,
04186                            DT) &&
04187            isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth, AC, CxtI,
04188                            DT);
04189   }
04190 }
04191 
04192 bool llvm::isImpliedCondition(Value *LHS, Value *RHS, const DataLayout &DL,
04193                               unsigned Depth, AssumptionCache *AC,
04194                               const Instruction *CxtI,
04195                               const DominatorTree *DT) {
04196   assert(LHS->getType() == RHS->getType() && "mismatched type");
04197   Type *OpTy = LHS->getType();
04198   assert(OpTy->getScalarType()->isIntegerTy(1));
04199 
04200   // LHS ==> RHS by definition
04201   if (LHS == RHS) return true;
04202 
04203   if (OpTy->isVectorTy())
04204     // TODO: extending the code below to handle vectors
04205     return false;
04206   assert(OpTy->isIntegerTy(1) && "implied by above");
04207 
04208   ICmpInst::Predicate APred, BPred;
04209   Value *ALHS, *ARHS;
04210   Value *BLHS, *BRHS;
04211 
04212   if (!match(LHS, m_ICmp(APred, m_Value(ALHS), m_Value(ARHS))) ||
04213       !match(RHS, m_ICmp(BPred, m_Value(BLHS), m_Value(BRHS))))
04214     return false;
04215 
04216   if (APred == BPred)
04217     return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth, AC,
04218                                  CxtI, DT);
04219 
04220   return false;
04221 }