LLVM API Documentation

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/SmallPtrSet.h"
00017 #include "llvm/Analysis/AssumptionCache.h"
00018 #include "llvm/Analysis/InstructionSimplify.h"
00019 #include "llvm/Analysis/MemoryBuiltins.h"
00020 #include "llvm/IR/CallSite.h"
00021 #include "llvm/IR/ConstantRange.h"
00022 #include "llvm/IR/Constants.h"
00023 #include "llvm/IR/DataLayout.h"
00024 #include "llvm/IR/Dominators.h"
00025 #include "llvm/IR/GetElementPtrTypeIterator.h"
00026 #include "llvm/IR/GlobalAlias.h"
00027 #include "llvm/IR/GlobalVariable.h"
00028 #include "llvm/IR/Instructions.h"
00029 #include "llvm/IR/IntrinsicInst.h"
00030 #include "llvm/IR/LLVMContext.h"
00031 #include "llvm/IR/Metadata.h"
00032 #include "llvm/IR/Operator.h"
00033 #include "llvm/IR/PatternMatch.h"
00034 #include "llvm/Support/Debug.h"
00035 #include "llvm/Support/MathExtras.h"
00036 #include <cstring>
00037 using namespace llvm;
00038 using namespace llvm::PatternMatch;
00039 
00040 const unsigned MaxDepth = 6;
00041 
00042 /// Returns the bitwidth of the given scalar or pointer type (if unknown returns
00043 /// 0). For vector types, returns the element type's bitwidth.
00044 static unsigned getBitWidth(Type *Ty, const DataLayout *TD) {
00045   if (unsigned BitWidth = Ty->getScalarSizeInBits())
00046     return BitWidth;
00047 
00048   return TD ? TD->getPointerTypeSizeInBits(Ty) : 0;
00049 }
00050 
00051 // Many of these functions have internal versions that take an assumption
00052 // exclusion set. This is because of the potential for mutual recursion to
00053 // cause computeKnownBits to repeatedly visit the same assume intrinsic. The
00054 // classic case of this is assume(x = y), which will attempt to determine
00055 // bits in x from bits in y, which will attempt to determine bits in y from
00056 // bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
00057 // isKnownNonZero, which calls computeKnownBits and ComputeSignBit and
00058 // isKnownToBeAPowerOfTwo (all of which can call computeKnownBits), and so on.
00059 typedef SmallPtrSet<const Value *, 8> ExclInvsSet;
00060 
00061 namespace {
00062 // Simplifying using an assume can only be done in a particular control-flow
00063 // context (the context instruction provides that context). If an assume and
00064 // the context instruction are not in the same block then the DT helps in
00065 // figuring out if we can use it.
00066 struct Query {
00067   ExclInvsSet ExclInvs;
00068   AssumptionCache *AC;
00069   const Instruction *CxtI;
00070   const DominatorTree *DT;
00071 
00072   Query(AssumptionCache *AC = nullptr, const Instruction *CxtI = nullptr,
00073         const DominatorTree *DT = nullptr)
00074       : AC(AC), CxtI(CxtI), DT(DT) {}
00075 
00076   Query(const Query &Q, const Value *NewExcl)
00077       : ExclInvs(Q.ExclInvs), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT) {
00078     ExclInvs.insert(NewExcl);
00079   }
00080 };
00081 } // end anonymous namespace
00082 
00083 // Given the provided Value and, potentially, a context instruction, return
00084 // the preferred context instruction (if any).
00085 static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
00086   // If we've been provided with a context instruction, then use that (provided
00087   // it has been inserted).
00088   if (CxtI && CxtI->getParent())
00089     return CxtI;
00090 
00091   // If the value is really an already-inserted instruction, then use that.
00092   CxtI = dyn_cast<Instruction>(V);
00093   if (CxtI && CxtI->getParent())
00094     return CxtI;
00095 
00096   return nullptr;
00097 }
00098 
00099 static void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
00100                             const DataLayout *TD, unsigned Depth,
00101                             const Query &Q);
00102 
00103 void llvm::computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
00104                             const DataLayout *TD, unsigned Depth,
00105                             AssumptionCache *AC, const Instruction *CxtI,
00106                             const DominatorTree *DT) {
00107   ::computeKnownBits(V, KnownZero, KnownOne, TD, Depth,
00108                      Query(AC, safeCxtI(V, CxtI), DT));
00109 }
00110 
00111 static void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
00112                           const DataLayout *TD, unsigned Depth,
00113                           const Query &Q);
00114 
00115 void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
00116                           const DataLayout *TD, unsigned Depth,
00117                           AssumptionCache *AC, const Instruction *CxtI,
00118                           const DominatorTree *DT) {
00119   ::ComputeSignBit(V, KnownZero, KnownOne, TD, Depth,
00120                    Query(AC, safeCxtI(V, CxtI), DT));
00121 }
00122 
00123 static bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
00124                                    const Query &Q);
00125 
00126 bool llvm::isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
00127                                   AssumptionCache *AC, const Instruction *CxtI,
00128                                   const DominatorTree *DT) {
00129   return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
00130                                   Query(AC, safeCxtI(V, CxtI), DT));
00131 }
00132 
00133 static bool isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
00134                            const Query &Q);
00135 
00136 bool llvm::isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
00137                           AssumptionCache *AC, const Instruction *CxtI,
00138                           const DominatorTree *DT) {
00139   return ::isKnownNonZero(V, TD, Depth, Query(AC, safeCxtI(V, CxtI), DT));
00140 }
00141 
00142 static bool MaskedValueIsZero(Value *V, const APInt &Mask,
00143                               const DataLayout *TD, unsigned Depth,
00144                               const Query &Q);
00145 
00146 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout *TD,
00147                              unsigned Depth, AssumptionCache *AC,
00148                              const Instruction *CxtI, const DominatorTree *DT) {
00149   return ::MaskedValueIsZero(V, Mask, TD, Depth,
00150                              Query(AC, safeCxtI(V, CxtI), DT));
00151 }
00152 
00153 static unsigned ComputeNumSignBits(Value *V, const DataLayout *TD,
00154                                    unsigned Depth, const Query &Q);
00155 
00156 unsigned llvm::ComputeNumSignBits(Value *V, const DataLayout *TD,
00157                                   unsigned Depth, AssumptionCache *AC,
00158                                   const Instruction *CxtI,
00159                                   const DominatorTree *DT) {
00160   return ::ComputeNumSignBits(V, TD, Depth, Query(AC, safeCxtI(V, CxtI), DT));
00161 }
00162 
00163 static void computeKnownBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
00164                                    APInt &KnownZero, APInt &KnownOne,
00165                                    APInt &KnownZero2, APInt &KnownOne2,
00166                                    const DataLayout *TD, unsigned Depth,
00167                                    const Query &Q) {
00168   if (!Add) {
00169     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
00170       // We know that the top bits of C-X are clear if X contains less bits
00171       // than C (i.e. no wrap-around can happen).  For example, 20-X is
00172       // positive if we can prove that X is >= 0 and < 16.
00173       if (!CLHS->getValue().isNegative()) {
00174         unsigned BitWidth = KnownZero.getBitWidth();
00175         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
00176         // NLZ can't be BitWidth with no sign bit
00177         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
00178         computeKnownBits(Op1, KnownZero2, KnownOne2, TD, Depth+1, Q);
00179 
00180         // If all of the MaskV bits are known to be zero, then we know the
00181         // output top bits are zero, because we now know that the output is
00182         // from [0-C].
00183         if ((KnownZero2 & MaskV) == MaskV) {
00184           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
00185           // Top bits known zero.
00186           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
00187         }
00188       }
00189     }
00190   }
00191 
00192   unsigned BitWidth = KnownZero.getBitWidth();
00193 
00194   // If an initial sequence of bits in the result is not needed, the
00195   // corresponding bits in the operands are not needed.
00196   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
00197   computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, TD, Depth+1, Q);
00198   computeKnownBits(Op1, KnownZero2, KnownOne2, TD, Depth+1, Q);
00199 
00200   // Carry in a 1 for a subtract, rather than a 0.
00201   APInt CarryIn(BitWidth, 0);
00202   if (!Add) {
00203     // Sum = LHS + ~RHS + 1
00204     std::swap(KnownZero2, KnownOne2);
00205     CarryIn.setBit(0);
00206   }
00207 
00208   APInt PossibleSumZero = ~LHSKnownZero + ~KnownZero2 + CarryIn;
00209   APInt PossibleSumOne = LHSKnownOne + KnownOne2 + CarryIn;
00210 
00211   // Compute known bits of the carry.
00212   APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnownZero ^ KnownZero2);
00213   APInt CarryKnownOne = PossibleSumOne ^ LHSKnownOne ^ KnownOne2;
00214 
00215   // Compute set of known bits (where all three relevant bits are known).
00216   APInt LHSKnown = LHSKnownZero | LHSKnownOne;
00217   APInt RHSKnown = KnownZero2 | KnownOne2;
00218   APInt CarryKnown = CarryKnownZero | CarryKnownOne;
00219   APInt Known = LHSKnown & RHSKnown & CarryKnown;
00220 
00221   assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
00222          "known bits of sum differ");
00223 
00224   // Compute known bits of the result.
00225   KnownZero = ~PossibleSumOne & Known;
00226   KnownOne = PossibleSumOne & Known;
00227 
00228   // Are we still trying to solve for the sign bit?
00229   if (!Known.isNegative()) {
00230     if (NSW) {
00231       // Adding two non-negative numbers, or subtracting a negative number from
00232       // a non-negative one, can't wrap into negative.
00233       if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
00234         KnownZero |= APInt::getSignBit(BitWidth);
00235       // Adding two negative numbers, or subtracting a non-negative number from
00236       // a negative one, can't wrap into non-negative.
00237       else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
00238         KnownOne |= APInt::getSignBit(BitWidth);
00239     }
00240   }
00241 }
00242 
00243 static void computeKnownBitsMul(Value *Op0, Value *Op1, bool NSW,
00244                                 APInt &KnownZero, APInt &KnownOne,
00245                                 APInt &KnownZero2, APInt &KnownOne2,
00246                                 const DataLayout *TD, unsigned Depth,
00247                                 const Query &Q) {
00248   unsigned BitWidth = KnownZero.getBitWidth();
00249   computeKnownBits(Op1, KnownZero, KnownOne, TD, Depth+1, Q);
00250   computeKnownBits(Op0, KnownZero2, KnownOne2, TD, Depth+1, Q);
00251 
00252   bool isKnownNegative = false;
00253   bool isKnownNonNegative = false;
00254   // If the multiplication is known not to overflow, compute the sign bit.
00255   if (NSW) {
00256     if (Op0 == Op1) {
00257       // The product of a number with itself is non-negative.
00258       isKnownNonNegative = true;
00259     } else {
00260       bool isKnownNonNegativeOp1 = KnownZero.isNegative();
00261       bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
00262       bool isKnownNegativeOp1 = KnownOne.isNegative();
00263       bool isKnownNegativeOp0 = KnownOne2.isNegative();
00264       // The product of two numbers with the same sign is non-negative.
00265       isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
00266         (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
00267       // The product of a negative number and a non-negative number is either
00268       // negative or zero.
00269       if (!isKnownNonNegative)
00270         isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
00271                            isKnownNonZero(Op0, TD, Depth, Q)) ||
00272                           (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
00273                            isKnownNonZero(Op1, TD, Depth, Q));
00274     }
00275   }
00276 
00277   // If low bits are zero in either operand, output low known-0 bits.
00278   // Also compute a conserative estimate for high known-0 bits.
00279   // More trickiness is possible, but this is sufficient for the
00280   // interesting case of alignment computation.
00281   KnownOne.clearAllBits();
00282   unsigned TrailZ = KnownZero.countTrailingOnes() +
00283                     KnownZero2.countTrailingOnes();
00284   unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
00285                              KnownZero2.countLeadingOnes(),
00286                              BitWidth) - BitWidth;
00287 
00288   TrailZ = std::min(TrailZ, BitWidth);
00289   LeadZ = std::min(LeadZ, BitWidth);
00290   KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
00291               APInt::getHighBitsSet(BitWidth, LeadZ);
00292 
00293   // Only make use of no-wrap flags if we failed to compute the sign bit
00294   // directly.  This matters if the multiplication always overflows, in
00295   // which case we prefer to follow the result of the direct computation,
00296   // though as the program is invoking undefined behaviour we can choose
00297   // whatever we like here.
00298   if (isKnownNonNegative && !KnownOne.isNegative())
00299     KnownZero.setBit(BitWidth - 1);
00300   else if (isKnownNegative && !KnownZero.isNegative())
00301     KnownOne.setBit(BitWidth - 1);
00302 }
00303 
00304 void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
00305                                              APInt &KnownZero) {
00306   unsigned BitWidth = KnownZero.getBitWidth();
00307   unsigned NumRanges = Ranges.getNumOperands() / 2;
00308   assert(NumRanges >= 1);
00309 
00310   // Use the high end of the ranges to find leading zeros.
00311   unsigned MinLeadingZeros = BitWidth;
00312   for (unsigned i = 0; i < NumRanges; ++i) {
00313     ConstantInt *Lower =
00314         mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
00315     ConstantInt *Upper =
00316         mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
00317     ConstantRange Range(Lower->getValue(), Upper->getValue());
00318     if (Range.isWrappedSet())
00319       MinLeadingZeros = 0; // -1 has no zeros
00320     unsigned LeadingZeros = (Upper->getValue() - 1).countLeadingZeros();
00321     MinLeadingZeros = std::min(LeadingZeros, MinLeadingZeros);
00322   }
00323 
00324   KnownZero = APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
00325 }
00326 
00327 static bool isEphemeralValueOf(Instruction *I, const Value *E) {
00328   SmallVector<const Value *, 16> WorkSet(1, I);
00329   SmallPtrSet<const Value *, 32> Visited;
00330   SmallPtrSet<const Value *, 16> EphValues;
00331 
00332   while (!WorkSet.empty()) {
00333     const Value *V = WorkSet.pop_back_val();
00334     if (!Visited.insert(V).second)
00335       continue;
00336 
00337     // If all uses of this value are ephemeral, then so is this value.
00338     bool FoundNEUse = false;
00339     for (const User *I : V->users())
00340       if (!EphValues.count(I)) {
00341         FoundNEUse = true;
00342         break;
00343       }
00344 
00345     if (!FoundNEUse) {
00346       if (V == E)
00347         return true;
00348 
00349       EphValues.insert(V);
00350       if (const User *U = dyn_cast<User>(V))
00351         for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
00352              J != JE; ++J) {
00353           if (isSafeToSpeculativelyExecute(*J))
00354             WorkSet.push_back(*J);
00355         }
00356     }
00357   }
00358 
00359   return false;
00360 }
00361 
00362 // Is this an intrinsic that cannot be speculated but also cannot trap?
00363 static bool isAssumeLikeIntrinsic(const Instruction *I) {
00364   if (const CallInst *CI = dyn_cast<CallInst>(I))
00365     if (Function *F = CI->getCalledFunction())
00366       switch (F->getIntrinsicID()) {
00367       default: break;
00368       // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
00369       case Intrinsic::assume:
00370       case Intrinsic::dbg_declare:
00371       case Intrinsic::dbg_value:
00372       case Intrinsic::invariant_start:
00373       case Intrinsic::invariant_end:
00374       case Intrinsic::lifetime_start:
00375       case Intrinsic::lifetime_end:
00376       case Intrinsic::objectsize:
00377       case Intrinsic::ptr_annotation:
00378       case Intrinsic::var_annotation:
00379         return true;
00380       }
00381 
00382   return false;
00383 }
00384 
00385 static bool isValidAssumeForContext(Value *V, const Query &Q,
00386                                     const DataLayout *DL) {
00387   Instruction *Inv = cast<Instruction>(V);
00388 
00389   // There are two restrictions on the use of an assume:
00390   //  1. The assume must dominate the context (or the control flow must
00391   //     reach the assume whenever it reaches the context).
00392   //  2. The context must not be in the assume's set of ephemeral values
00393   //     (otherwise we will use the assume to prove that the condition
00394   //     feeding the assume is trivially true, thus causing the removal of
00395   //     the assume).
00396 
00397   if (Q.DT) {
00398     if (Q.DT->dominates(Inv, Q.CxtI)) {
00399       return true;
00400     } else if (Inv->getParent() == Q.CxtI->getParent()) {
00401       // The context comes first, but they're both in the same block. Make sure
00402       // there is nothing in between that might interrupt the control flow.
00403       for (BasicBlock::const_iterator I =
00404              std::next(BasicBlock::const_iterator(Q.CxtI)),
00405                                       IE(Inv); I != IE; ++I)
00406         if (!isSafeToSpeculativelyExecute(I, DL) &&
00407             !isAssumeLikeIntrinsic(I))
00408           return false;
00409 
00410       return !isEphemeralValueOf(Inv, Q.CxtI);
00411     }
00412 
00413     return false;
00414   }
00415 
00416   // When we don't have a DT, we do a limited search...
00417   if (Inv->getParent() == Q.CxtI->getParent()->getSinglePredecessor()) {
00418     return true;
00419   } else if (Inv->getParent() == Q.CxtI->getParent()) {
00420     // Search forward from the assume until we reach the context (or the end
00421     // of the block); the common case is that the assume will come first.
00422     for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
00423          IE = Inv->getParent()->end(); I != IE; ++I)
00424       if (I == Q.CxtI)
00425         return true;
00426 
00427     // The context must come first...
00428     for (BasicBlock::const_iterator I =
00429            std::next(BasicBlock::const_iterator(Q.CxtI)),
00430                                     IE(Inv); I != IE; ++I)
00431       if (!isSafeToSpeculativelyExecute(I, DL) &&
00432           !isAssumeLikeIntrinsic(I))
00433         return false;
00434 
00435     return !isEphemeralValueOf(Inv, Q.CxtI);
00436   }
00437 
00438   return false;
00439 }
00440 
00441 bool llvm::isValidAssumeForContext(const Instruction *I,
00442                                    const Instruction *CxtI,
00443                                    const DataLayout *DL,
00444                                    const DominatorTree *DT) {
00445   return ::isValidAssumeForContext(const_cast<Instruction*>(I),
00446                                    Query(nullptr, CxtI, DT), DL);
00447 }
00448 
00449 template<typename LHS, typename RHS>
00450 inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
00451                         CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
00452 m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
00453   return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
00454 }
00455 
00456 template<typename LHS, typename RHS>
00457 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
00458                         BinaryOp_match<RHS, LHS, Instruction::And>>
00459 m_c_And(const LHS &L, const RHS &R) {
00460   return m_CombineOr(m_And(L, R), m_And(R, L));
00461 }
00462 
00463 template<typename LHS, typename RHS>
00464 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Or>,
00465                         BinaryOp_match<RHS, LHS, Instruction::Or>>
00466 m_c_Or(const LHS &L, const RHS &R) {
00467   return m_CombineOr(m_Or(L, R), m_Or(R, L));
00468 }
00469 
00470 template<typename LHS, typename RHS>
00471 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Xor>,
00472                         BinaryOp_match<RHS, LHS, Instruction::Xor>>
00473 m_c_Xor(const LHS &L, const RHS &R) {
00474   return m_CombineOr(m_Xor(L, R), m_Xor(R, L));
00475 }
00476 
00477 static void computeKnownBitsFromAssume(Value *V, APInt &KnownZero,
00478                                        APInt &KnownOne,
00479                                        const DataLayout *DL,
00480                                        unsigned Depth, const Query &Q) {
00481   // Use of assumptions is context-sensitive. If we don't have a context, we
00482   // cannot use them!
00483   if (!Q.AC || !Q.CxtI)
00484     return;
00485 
00486   unsigned BitWidth = KnownZero.getBitWidth();
00487 
00488   for (auto &AssumeVH : Q.AC->assumptions()) {
00489     if (!AssumeVH)
00490       continue;
00491     CallInst *I = cast<CallInst>(AssumeVH);
00492     assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
00493            "Got assumption for the wrong function!");
00494     if (Q.ExclInvs.count(I))
00495       continue;
00496 
00497     // Warning: This loop can end up being somewhat performance sensetive.
00498     // We're running this loop for once for each value queried resulting in a
00499     // runtime of ~O(#assumes * #values).
00500 
00501     assert(isa<IntrinsicInst>(I) &&
00502            dyn_cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::assume &&
00503            "must be an assume intrinsic");
00504     
00505     Value *Arg = I->getArgOperand(0);
00506 
00507     if (Arg == V &&
00508         isValidAssumeForContext(I, Q, DL)) {
00509       assert(BitWidth == 1 && "assume operand is not i1?");
00510       KnownZero.clearAllBits();
00511       KnownOne.setAllBits();
00512       return;
00513     }
00514 
00515     // The remaining tests are all recursive, so bail out if we hit the limit.
00516     if (Depth == MaxDepth)
00517       continue;
00518 
00519     Value *A, *B;
00520     auto m_V = m_CombineOr(m_Specific(V),
00521                            m_CombineOr(m_PtrToInt(m_Specific(V)),
00522                            m_BitCast(m_Specific(V))));
00523 
00524     CmpInst::Predicate Pred;
00525     ConstantInt *C;
00526     // assume(v = a)
00527     if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
00528         Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00529       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00530       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00531       KnownZero |= RHSKnownZero;
00532       KnownOne  |= RHSKnownOne;
00533     // assume(v & b = a)
00534     } else if (match(Arg, m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)),
00535                                    m_Value(A))) &&
00536                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00537       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00538       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00539       APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
00540       computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
00541 
00542       // For those bits in the mask that are known to be one, we can propagate
00543       // known bits from the RHS to V.
00544       KnownZero |= RHSKnownZero & MaskKnownOne;
00545       KnownOne  |= RHSKnownOne  & MaskKnownOne;
00546     // assume(~(v & b) = a)
00547     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
00548                                    m_Value(A))) &&
00549                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00550       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00551       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00552       APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
00553       computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
00554 
00555       // For those bits in the mask that are known to be one, we can propagate
00556       // inverted known bits from the RHS to V.
00557       KnownZero |= RHSKnownOne  & MaskKnownOne;
00558       KnownOne  |= RHSKnownZero & MaskKnownOne;
00559     // assume(v | b = a)
00560     } else if (match(Arg, m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)),
00561                                    m_Value(A))) &&
00562                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00563       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00564       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00565       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
00566       computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
00567 
00568       // For those bits in B that are known to be zero, we can propagate known
00569       // bits from the RHS to V.
00570       KnownZero |= RHSKnownZero & BKnownZero;
00571       KnownOne  |= RHSKnownOne  & BKnownZero;
00572     // assume(~(v | b) = a)
00573     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
00574                                    m_Value(A))) &&
00575                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00576       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00577       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00578       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
00579       computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
00580 
00581       // For those bits in B that are known to be zero, we can propagate
00582       // inverted known bits from the RHS to V.
00583       KnownZero |= RHSKnownOne  & BKnownZero;
00584       KnownOne  |= RHSKnownZero & BKnownZero;
00585     // assume(v ^ b = a)
00586     } else if (match(Arg, m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)),
00587                                    m_Value(A))) &&
00588                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00589       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00590       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00591       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
00592       computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
00593 
00594       // For those bits in B that are known to be zero, we can propagate known
00595       // bits from the RHS to V. For those bits in B that are known to be one,
00596       // we can propagate inverted known bits from the RHS to V.
00597       KnownZero |= RHSKnownZero & BKnownZero;
00598       KnownOne  |= RHSKnownOne  & BKnownZero;
00599       KnownZero |= RHSKnownOne  & BKnownOne;
00600       KnownOne  |= RHSKnownZero & BKnownOne;
00601     // assume(~(v ^ b) = a)
00602     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
00603                                    m_Value(A))) &&
00604                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00605       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00606       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00607       APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
00608       computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
00609 
00610       // For those bits in B that are known to be zero, we can propagate
00611       // inverted known bits from the RHS to V. For those bits in B that are
00612       // known to be one, we can propagate known bits from the RHS to V.
00613       KnownZero |= RHSKnownOne  & BKnownZero;
00614       KnownOne  |= RHSKnownZero & BKnownZero;
00615       KnownZero |= RHSKnownZero & BKnownOne;
00616       KnownOne  |= RHSKnownOne  & BKnownOne;
00617     // assume(v << c = a)
00618     } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
00619                                    m_Value(A))) &&
00620                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00621       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00622       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00623       // For those bits in RHS that are known, we can propagate them to known
00624       // bits in V shifted to the right by C.
00625       KnownZero |= RHSKnownZero.lshr(C->getZExtValue());
00626       KnownOne  |= RHSKnownOne.lshr(C->getZExtValue());
00627     // assume(~(v << c) = a)
00628     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
00629                                    m_Value(A))) &&
00630                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00631       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00632       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00633       // For those bits in RHS that are known, we can propagate them inverted
00634       // to known bits in V shifted to the right by C.
00635       KnownZero |= RHSKnownOne.lshr(C->getZExtValue());
00636       KnownOne  |= RHSKnownZero.lshr(C->getZExtValue());
00637     // assume(v >> c = a)
00638     } else if (match(Arg,
00639                      m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
00640                                                   m_AShr(m_V,
00641                                                          m_ConstantInt(C))),
00642                                      m_Value(A))) &&
00643                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00644       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00645       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00646       // For those bits in RHS that are known, we can propagate them to known
00647       // bits in V shifted to the right by C.
00648       KnownZero |= RHSKnownZero << C->getZExtValue();
00649       KnownOne  |= RHSKnownOne  << C->getZExtValue();
00650     // assume(~(v >> c) = a)
00651     } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_CombineOr(
00652                                               m_LShr(m_V, m_ConstantInt(C)),
00653                                               m_AShr(m_V, m_ConstantInt(C)))),
00654                                    m_Value(A))) &&
00655                Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q, DL)) {
00656       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00657       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00658       // For those bits in RHS that are known, we can propagate them inverted
00659       // to known bits in V shifted to the right by C.
00660       KnownZero |= RHSKnownOne  << C->getZExtValue();
00661       KnownOne  |= RHSKnownZero << C->getZExtValue();
00662     // assume(v >=_s c) where c is non-negative
00663     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
00664                Pred == ICmpInst::ICMP_SGE &&
00665                isValidAssumeForContext(I, Q, DL)) {
00666       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00667       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00668 
00669       if (RHSKnownZero.isNegative()) {
00670         // We know that the sign bit is zero.
00671         KnownZero |= APInt::getSignBit(BitWidth);
00672       }
00673     // assume(v >_s c) where c is at least -1.
00674     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
00675                Pred == ICmpInst::ICMP_SGT &&
00676                isValidAssumeForContext(I, Q, DL)) {
00677       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00678       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00679 
00680       if (RHSKnownOne.isAllOnesValue() || RHSKnownZero.isNegative()) {
00681         // We know that the sign bit is zero.
00682         KnownZero |= APInt::getSignBit(BitWidth);
00683       }
00684     // assume(v <=_s c) where c is negative
00685     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
00686                Pred == ICmpInst::ICMP_SLE &&
00687                isValidAssumeForContext(I, Q, DL)) {
00688       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00689       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00690 
00691       if (RHSKnownOne.isNegative()) {
00692         // We know that the sign bit is one.
00693         KnownOne |= APInt::getSignBit(BitWidth);
00694       }
00695     // assume(v <_s c) where c is non-positive
00696     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
00697                Pred == ICmpInst::ICMP_SLT &&
00698                isValidAssumeForContext(I, Q, DL)) {
00699       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00700       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00701 
00702       if (RHSKnownZero.isAllOnesValue() || RHSKnownOne.isNegative()) {
00703         // We know that the sign bit is one.
00704         KnownOne |= APInt::getSignBit(BitWidth);
00705       }
00706     // assume(v <=_u c)
00707     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
00708                Pred == ICmpInst::ICMP_ULE &&
00709                isValidAssumeForContext(I, Q, DL)) {
00710       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00711       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00712 
00713       // Whatever high bits in c are zero are known to be zero.
00714       KnownZero |=
00715         APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
00716     // assume(v <_u c)
00717     } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
00718                Pred == ICmpInst::ICMP_ULT &&
00719                isValidAssumeForContext(I, Q, DL)) {
00720       APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
00721       computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
00722 
00723       // Whatever high bits in c are zero are known to be zero (if c is a power
00724       // of 2, then one more).
00725       if (isKnownToBeAPowerOfTwo(A, false, Depth+1, Query(Q, I)))
00726         KnownZero |=
00727           APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()+1);
00728       else
00729         KnownZero |=
00730           APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
00731     }
00732   }
00733 }
00734 
00735 /// Determine which bits of V are known to be either zero or one and return
00736 /// them in the KnownZero/KnownOne bit sets.
00737 ///
00738 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
00739 /// we cannot optimize based on the assumption that it is zero without changing
00740 /// it to be an explicit zero.  If we don't change it to zero, other code could
00741 /// optimized based on the contradictory assumption that it is non-zero.
00742 /// Because instcombine aggressively folds operations with undef args anyway,
00743 /// this won't lose us code quality.
00744 ///
00745 /// This function is defined on values with integer type, values with pointer
00746 /// type (but only if TD is non-null), and vectors of integers.  In the case
00747 /// where V is a vector, known zero, and known one values are the
00748 /// same width as the vector element, and the bit is set only if it is true
00749 /// for all of the elements in the vector.
00750 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
00751                       const DataLayout *TD, unsigned Depth,
00752                       const Query &Q) {
00753   assert(V && "No Value?");
00754   assert(Depth <= MaxDepth && "Limit Search Depth");
00755   unsigned BitWidth = KnownZero.getBitWidth();
00756 
00757   assert((V->getType()->isIntOrIntVectorTy() ||
00758           V->getType()->getScalarType()->isPointerTy()) &&
00759          "Not integer or pointer type!");
00760   assert((!TD ||
00761           TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
00762          (!V->getType()->isIntOrIntVectorTy() ||
00763           V->getType()->getScalarSizeInBits() == BitWidth) &&
00764          KnownZero.getBitWidth() == BitWidth &&
00765          KnownOne.getBitWidth() == BitWidth &&
00766          "V, KnownOne and KnownZero should have same BitWidth");
00767 
00768   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00769     // We know all of the bits for a constant!
00770     KnownOne = CI->getValue();
00771     KnownZero = ~KnownOne;
00772     return;
00773   }
00774   // Null and aggregate-zero are all-zeros.
00775   if (isa<ConstantPointerNull>(V) ||
00776       isa<ConstantAggregateZero>(V)) {
00777     KnownOne.clearAllBits();
00778     KnownZero = APInt::getAllOnesValue(BitWidth);
00779     return;
00780   }
00781   // Handle a constant vector by taking the intersection of the known bits of
00782   // each element.  There is no real need to handle ConstantVector here, because
00783   // we don't handle undef in any particularly useful way.
00784   if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
00785     // We know that CDS must be a vector of integers. Take the intersection of
00786     // each element.
00787     KnownZero.setAllBits(); KnownOne.setAllBits();
00788     APInt Elt(KnownZero.getBitWidth(), 0);
00789     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
00790       Elt = CDS->getElementAsInteger(i);
00791       KnownZero &= ~Elt;
00792       KnownOne &= Elt;
00793     }
00794     return;
00795   }
00796 
00797   // The address of an aligned GlobalValue has trailing zeros.
00798   if (auto *GO = dyn_cast<GlobalObject>(V)) {
00799     unsigned Align = GO->getAlignment();
00800     if (Align == 0 && TD) {
00801       if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
00802         Type *ObjectType = GVar->getType()->getElementType();
00803         if (ObjectType->isSized()) {
00804           // If the object is defined in the current Module, we'll be giving
00805           // it the preferred alignment. Otherwise, we have to assume that it
00806           // may only have the minimum ABI alignment.
00807           if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
00808             Align = TD->getPreferredAlignment(GVar);
00809           else
00810             Align = TD->getABITypeAlignment(ObjectType);
00811         }
00812       }
00813     }
00814     if (Align > 0)
00815       KnownZero = APInt::getLowBitsSet(BitWidth,
00816                                        countTrailingZeros(Align));
00817     else
00818       KnownZero.clearAllBits();
00819     KnownOne.clearAllBits();
00820     return;
00821   }
00822 
00823   if (Argument *A = dyn_cast<Argument>(V)) {
00824     unsigned Align = A->getType()->isPointerTy() ? A->getParamAlignment() : 0;
00825 
00826     if (!Align && TD && A->hasStructRetAttr()) {
00827       // An sret parameter has at least the ABI alignment of the return type.
00828       Type *EltTy = cast<PointerType>(A->getType())->getElementType();
00829       if (EltTy->isSized())
00830         Align = TD->getABITypeAlignment(EltTy);
00831     }
00832 
00833     if (Align)
00834       KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
00835     else
00836       KnownZero.clearAllBits();
00837     KnownOne.clearAllBits();
00838 
00839     // Don't give up yet... there might be an assumption that provides more
00840     // information...
00841     computeKnownBitsFromAssume(V, KnownZero, KnownOne, TD, Depth, Q);
00842     return;
00843   }
00844 
00845   // Start out not knowing anything.
00846   KnownZero.clearAllBits(); KnownOne.clearAllBits();
00847 
00848   // Limit search depth.
00849   // All recursive calls that increase depth must come after this.
00850   if (Depth == MaxDepth)
00851     return;  
00852 
00853   // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
00854   // the bits of its aliasee.
00855   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
00856     if (!GA->mayBeOverridden())
00857       computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, TD, Depth + 1, Q);
00858     return;
00859   }
00860 
00861   // Check whether a nearby assume intrinsic can determine some known bits.
00862   computeKnownBitsFromAssume(V, KnownZero, KnownOne, TD, Depth, Q);
00863 
00864   Operator *I = dyn_cast<Operator>(V);
00865   if (!I) return;
00866 
00867   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
00868   switch (I->getOpcode()) {
00869   default: break;
00870   case Instruction::Load:
00871     if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
00872       computeKnownBitsFromRangeMetadata(*MD, KnownZero);
00873     break;
00874   case Instruction::And: {
00875     // If either the LHS or the RHS are Zero, the result is zero.
00876     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
00877     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
00878 
00879     // Output known-1 bits are only known if set in both the LHS & RHS.
00880     KnownOne &= KnownOne2;
00881     // Output known-0 are known to be clear if zero in either the LHS | RHS.
00882     KnownZero |= KnownZero2;
00883     break;
00884   }
00885   case Instruction::Or: {
00886     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
00887     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
00888 
00889     // Output known-0 bits are only known if clear in both the LHS & RHS.
00890     KnownZero &= KnownZero2;
00891     // Output known-1 are known to be set if set in either the LHS | RHS.
00892     KnownOne |= KnownOne2;
00893     break;
00894   }
00895   case Instruction::Xor: {
00896     computeKnownBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
00897     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
00898 
00899     // Output known-0 bits are known if clear or set in both the LHS & RHS.
00900     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
00901     // Output known-1 are known to be set if set in only one of the LHS, RHS.
00902     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
00903     KnownZero = KnownZeroOut;
00904     break;
00905   }
00906   case Instruction::Mul: {
00907     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
00908     computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW,
00909                          KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
00910                          Depth, Q);
00911     break;
00912   }
00913   case Instruction::UDiv: {
00914     // For the purposes of computing leading zeros we can conservatively
00915     // treat a udiv as a logical right shift by the power of 2 known to
00916     // be less than the denominator.
00917     computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1, Q);
00918     unsigned LeadZ = KnownZero2.countLeadingOnes();
00919 
00920     KnownOne2.clearAllBits();
00921     KnownZero2.clearAllBits();
00922     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
00923     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
00924     if (RHSUnknownLeadingOnes != BitWidth)
00925       LeadZ = std::min(BitWidth,
00926                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
00927 
00928     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
00929     break;
00930   }
00931   case Instruction::Select:
00932     computeKnownBits(I->getOperand(2), KnownZero, KnownOne, TD, Depth+1, Q);
00933     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
00934 
00935     // Only known if known in both the LHS and RHS.
00936     KnownOne &= KnownOne2;
00937     KnownZero &= KnownZero2;
00938     break;
00939   case Instruction::FPTrunc:
00940   case Instruction::FPExt:
00941   case Instruction::FPToUI:
00942   case Instruction::FPToSI:
00943   case Instruction::SIToFP:
00944   case Instruction::UIToFP:
00945     break; // Can't work with floating point.
00946   case Instruction::PtrToInt:
00947   case Instruction::IntToPtr:
00948   case Instruction::AddrSpaceCast: // Pointers could be different sizes.
00949     // We can't handle these if we don't know the pointer size.
00950     if (!TD) break;
00951     // FALL THROUGH and handle them the same as zext/trunc.
00952   case Instruction::ZExt:
00953   case Instruction::Trunc: {
00954     Type *SrcTy = I->getOperand(0)->getType();
00955 
00956     unsigned SrcBitWidth;
00957     // Note that we handle pointer operands here because of inttoptr/ptrtoint
00958     // which fall through here.
00959     if(TD) {
00960       SrcBitWidth = TD->getTypeSizeInBits(SrcTy->getScalarType());
00961     } else {
00962       SrcBitWidth = SrcTy->getScalarSizeInBits();
00963       if (!SrcBitWidth) break;
00964     }
00965 
00966     assert(SrcBitWidth && "SrcBitWidth can't be zero");
00967     KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
00968     KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
00969     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
00970     KnownZero = KnownZero.zextOrTrunc(BitWidth);
00971     KnownOne = KnownOne.zextOrTrunc(BitWidth);
00972     // Any top bits are known to be zero.
00973     if (BitWidth > SrcBitWidth)
00974       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
00975     break;
00976   }
00977   case Instruction::BitCast: {
00978     Type *SrcTy = I->getOperand(0)->getType();
00979     if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
00980         // TODO: For now, not handling conversions like:
00981         // (bitcast i64 %x to <2 x i32>)
00982         !I->getType()->isVectorTy()) {
00983       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
00984       break;
00985     }
00986     break;
00987   }
00988   case Instruction::SExt: {
00989     // Compute the bits in the result that are not present in the input.
00990     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
00991 
00992     KnownZero = KnownZero.trunc(SrcBitWidth);
00993     KnownOne = KnownOne.trunc(SrcBitWidth);
00994     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
00995     KnownZero = KnownZero.zext(BitWidth);
00996     KnownOne = KnownOne.zext(BitWidth);
00997 
00998     // If the sign bit of the input is known set or clear, then we know the
00999     // top bits of the result.
01000     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
01001       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
01002     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
01003       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
01004     break;
01005   }
01006   case Instruction::Shl:
01007     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
01008     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
01009       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
01010       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
01011       KnownZero <<= ShiftAmt;
01012       KnownOne  <<= ShiftAmt;
01013       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
01014     }
01015     break;
01016   case Instruction::LShr:
01017     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
01018     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
01019       // Compute the new bits that are at the top now.
01020       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
01021 
01022       // Unsigned shift right.
01023       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
01024       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
01025       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
01026       // high bits known zero.
01027       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
01028     }
01029     break;
01030   case Instruction::AShr:
01031     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
01032     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
01033       // Compute the new bits that are at the top now.
01034       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
01035 
01036       // Signed shift right.
01037       computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
01038       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
01039       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
01040 
01041       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
01042       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
01043         KnownZero |= HighBits;
01044       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
01045         KnownOne |= HighBits;
01046     }
01047     break;
01048   case Instruction::Sub: {
01049     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
01050     computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
01051                             KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
01052                             Depth, Q);
01053     break;
01054   }
01055   case Instruction::Add: {
01056     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
01057     computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
01058                             KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
01059                             Depth, Q);
01060     break;
01061   }
01062   case Instruction::SRem:
01063     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
01064       APInt RA = Rem->getValue().abs();
01065       if (RA.isPowerOf2()) {
01066         APInt LowBits = RA - 1;
01067         computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, TD,
01068                          Depth+1, Q);
01069 
01070         // The low bits of the first operand are unchanged by the srem.
01071         KnownZero = KnownZero2 & LowBits;
01072         KnownOne = KnownOne2 & LowBits;
01073 
01074         // If the first operand is non-negative or has all low bits zero, then
01075         // the upper bits are all zero.
01076         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
01077           KnownZero |= ~LowBits;
01078 
01079         // If the first operand is negative and not all low bits are zero, then
01080         // the upper bits are all one.
01081         if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
01082           KnownOne |= ~LowBits;
01083 
01084         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
01085       }
01086     }
01087 
01088     // The sign bit is the LHS's sign bit, except when the result of the
01089     // remainder is zero.
01090     if (KnownZero.isNonNegative()) {
01091       APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
01092       computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, TD,
01093                        Depth+1, Q);
01094       // If it's known zero, our sign bit is also zero.
01095       if (LHSKnownZero.isNegative())
01096         KnownZero.setBit(BitWidth - 1);
01097     }
01098 
01099     break;
01100   case Instruction::URem: {
01101     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
01102       APInt RA = Rem->getValue();
01103       if (RA.isPowerOf2()) {
01104         APInt LowBits = (RA - 1);
01105         computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD,
01106                          Depth+1, Q);
01107         KnownZero |= ~LowBits;
01108         KnownOne &= LowBits;
01109         break;
01110       }
01111     }
01112 
01113     // Since the result is less than or equal to either operand, any leading
01114     // zero bits in either operand must also exist in the result.
01115     computeKnownBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
01116     computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1, Q);
01117 
01118     unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
01119                                 KnownZero2.countLeadingOnes());
01120     KnownOne.clearAllBits();
01121     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
01122     break;
01123   }
01124 
01125   case Instruction::Alloca: {
01126     AllocaInst *AI = cast<AllocaInst>(V);
01127     unsigned Align = AI->getAlignment();
01128     if (Align == 0 && TD)
01129       Align = TD->getABITypeAlignment(AI->getType()->getElementType());
01130 
01131     if (Align > 0)
01132       KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
01133     break;
01134   }
01135   case Instruction::GetElementPtr: {
01136     // Analyze all of the subscripts of this getelementptr instruction
01137     // to determine if we can prove known low zero bits.
01138     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
01139     computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, TD,
01140                      Depth+1, Q);
01141     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
01142 
01143     gep_type_iterator GTI = gep_type_begin(I);
01144     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
01145       Value *Index = I->getOperand(i);
01146       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
01147         // Handle struct member offset arithmetic.
01148         if (!TD) {
01149           TrailZ = 0;
01150           break;
01151         }
01152 
01153         // Handle case when index is vector zeroinitializer
01154         Constant *CIndex = cast<Constant>(Index);
01155         if (CIndex->isZeroValue())
01156           continue;
01157 
01158         if (CIndex->getType()->isVectorTy())
01159           Index = CIndex->getSplatValue();
01160 
01161         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
01162         const StructLayout *SL = TD->getStructLayout(STy);
01163         uint64_t Offset = SL->getElementOffset(Idx);
01164         TrailZ = std::min<unsigned>(TrailZ,
01165                                     countTrailingZeros(Offset));
01166       } else {
01167         // Handle array index arithmetic.
01168         Type *IndexedTy = GTI.getIndexedType();
01169         if (!IndexedTy->isSized()) {
01170           TrailZ = 0;
01171           break;
01172         }
01173         unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
01174         uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
01175         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
01176         computeKnownBits(Index, LocalKnownZero, LocalKnownOne, TD, Depth+1, Q);
01177         TrailZ = std::min(TrailZ,
01178                           unsigned(countTrailingZeros(TypeSize) +
01179                                    LocalKnownZero.countTrailingOnes()));
01180       }
01181     }
01182 
01183     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
01184     break;
01185   }
01186   case Instruction::PHI: {
01187     PHINode *P = cast<PHINode>(I);
01188     // Handle the case of a simple two-predecessor recurrence PHI.
01189     // There's a lot more that could theoretically be done here, but
01190     // this is sufficient to catch some interesting cases.
01191     if (P->getNumIncomingValues() == 2) {
01192       for (unsigned i = 0; i != 2; ++i) {
01193         Value *L = P->getIncomingValue(i);
01194         Value *R = P->getIncomingValue(!i);
01195         Operator *LU = dyn_cast<Operator>(L);
01196         if (!LU)
01197           continue;
01198         unsigned Opcode = LU->getOpcode();
01199         // Check for operations that have the property that if
01200         // both their operands have low zero bits, the result
01201         // will have low zero bits.
01202         if (Opcode == Instruction::Add ||
01203             Opcode == Instruction::Sub ||
01204             Opcode == Instruction::And ||
01205             Opcode == Instruction::Or ||
01206             Opcode == Instruction::Mul) {
01207           Value *LL = LU->getOperand(0);
01208           Value *LR = LU->getOperand(1);
01209           // Find a recurrence.
01210           if (LL == I)
01211             L = LR;
01212           else if (LR == I)
01213             L = LL;
01214           else
01215             break;
01216           // Ok, we have a PHI of the form L op= R. Check for low
01217           // zero bits.
01218           computeKnownBits(R, KnownZero2, KnownOne2, TD, Depth+1, Q);
01219 
01220           // We need to take the minimum number of known bits
01221           APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
01222           computeKnownBits(L, KnownZero3, KnownOne3, TD, Depth+1, Q);
01223 
01224           KnownZero = APInt::getLowBitsSet(BitWidth,
01225                                            std::min(KnownZero2.countTrailingOnes(),
01226                                                     KnownZero3.countTrailingOnes()));
01227           break;
01228         }
01229       }
01230     }
01231 
01232     // Unreachable blocks may have zero-operand PHI nodes.
01233     if (P->getNumIncomingValues() == 0)
01234       break;
01235 
01236     // Otherwise take the unions of the known bit sets of the operands,
01237     // taking conservative care to avoid excessive recursion.
01238     if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
01239       // Skip if every incoming value references to ourself.
01240       if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
01241         break;
01242 
01243       KnownZero = APInt::getAllOnesValue(BitWidth);
01244       KnownOne = APInt::getAllOnesValue(BitWidth);
01245       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
01246         // Skip direct self references.
01247         if (P->getIncomingValue(i) == P) continue;
01248 
01249         KnownZero2 = APInt(BitWidth, 0);
01250         KnownOne2 = APInt(BitWidth, 0);
01251         // Recurse, but cap the recursion to one level, because we don't
01252         // want to waste time spinning around in loops.
01253         computeKnownBits(P->getIncomingValue(i), KnownZero2, KnownOne2, TD,
01254                          MaxDepth-1, Q);
01255         KnownZero &= KnownZero2;
01256         KnownOne &= KnownOne2;
01257         // If all bits have been ruled out, there's no need to check
01258         // more operands.
01259         if (!KnownZero && !KnownOne)
01260           break;
01261       }
01262     }
01263     break;
01264   }
01265   case Instruction::Call:
01266   case Instruction::Invoke:
01267     if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
01268       computeKnownBitsFromRangeMetadata(*MD, KnownZero);
01269     // If a range metadata is attached to this IntrinsicInst, intersect the
01270     // explicit range specified by the metadata and the implicit range of
01271     // the intrinsic.
01272     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
01273       switch (II->getIntrinsicID()) {
01274       default: break;
01275       case Intrinsic::ctlz:
01276       case Intrinsic::cttz: {
01277         unsigned LowBits = Log2_32(BitWidth)+1;
01278         // If this call is undefined for 0, the result will be less than 2^n.
01279         if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
01280           LowBits -= 1;
01281         KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
01282         break;
01283       }
01284       case Intrinsic::ctpop: {
01285         unsigned LowBits = Log2_32(BitWidth)+1;
01286         KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
01287         break;
01288       }
01289       case Intrinsic::x86_sse42_crc32_64_64:
01290         KnownZero |= APInt::getHighBitsSet(64, 32);
01291         break;
01292       }
01293     }
01294     break;
01295   case Instruction::ExtractValue:
01296     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
01297       ExtractValueInst *EVI = cast<ExtractValueInst>(I);
01298       if (EVI->getNumIndices() != 1) break;
01299       if (EVI->getIndices()[0] == 0) {
01300         switch (II->getIntrinsicID()) {
01301         default: break;
01302         case Intrinsic::uadd_with_overflow:
01303         case Intrinsic::sadd_with_overflow:
01304           computeKnownBitsAddSub(true, II->getArgOperand(0),
01305                                  II->getArgOperand(1), false, KnownZero,
01306                                  KnownOne, KnownZero2, KnownOne2, TD, Depth, Q);
01307           break;
01308         case Intrinsic::usub_with_overflow:
01309         case Intrinsic::ssub_with_overflow:
01310           computeKnownBitsAddSub(false, II->getArgOperand(0),
01311                                  II->getArgOperand(1), false, KnownZero,
01312                                  KnownOne, KnownZero2, KnownOne2, TD, Depth, Q);
01313           break;
01314         case Intrinsic::umul_with_overflow:
01315         case Intrinsic::smul_with_overflow:
01316           computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1),
01317                               false, KnownZero, KnownOne,
01318                               KnownZero2, KnownOne2, TD, Depth, Q);
01319           break;
01320         }
01321       }
01322     }
01323   }
01324 
01325   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
01326 }
01327 
01328 /// Determine whether the sign bit is known to be zero or one.
01329 /// Convenience wrapper around computeKnownBits.
01330 void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
01331                     const DataLayout *TD, unsigned Depth,
01332                     const Query &Q) {
01333   unsigned BitWidth = getBitWidth(V->getType(), TD);
01334   if (!BitWidth) {
01335     KnownZero = false;
01336     KnownOne = false;
01337     return;
01338   }
01339   APInt ZeroBits(BitWidth, 0);
01340   APInt OneBits(BitWidth, 0);
01341   computeKnownBits(V, ZeroBits, OneBits, TD, Depth, Q);
01342   KnownOne = OneBits[BitWidth - 1];
01343   KnownZero = ZeroBits[BitWidth - 1];
01344 }
01345 
01346 /// Return true if the given value is known to have exactly one
01347 /// bit set when defined. For vectors return true if every element is known to
01348 /// be a power of two when defined. Supports values with integer or pointer
01349 /// types and vectors of integers.
01350 bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
01351                             const Query &Q) {
01352   if (Constant *C = dyn_cast<Constant>(V)) {
01353     if (C->isNullValue())
01354       return OrZero;
01355     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
01356       return CI->getValue().isPowerOf2();
01357     // TODO: Handle vector constants.
01358   }
01359 
01360   // 1 << X is clearly a power of two if the one is not shifted off the end.  If
01361   // it is shifted off the end then the result is undefined.
01362   if (match(V, m_Shl(m_One(), m_Value())))
01363     return true;
01364 
01365   // (signbit) >>l X is clearly a power of two if the one is not shifted off the
01366   // bottom.  If it is shifted off the bottom then the result is undefined.
01367   if (match(V, m_LShr(m_SignBit(), m_Value())))
01368     return true;
01369 
01370   // The remaining tests are all recursive, so bail out if we hit the limit.
01371   if (Depth++ == MaxDepth)
01372     return false;
01373 
01374   Value *X = nullptr, *Y = nullptr;
01375   // A shift of a power of two is a power of two or zero.
01376   if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
01377                  match(V, m_Shr(m_Value(X), m_Value()))))
01378     return isKnownToBeAPowerOfTwo(X, /*OrZero*/true, Depth, Q);
01379 
01380   if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
01381     return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
01382 
01383   if (SelectInst *SI = dyn_cast<SelectInst>(V))
01384     return
01385       isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
01386       isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
01387 
01388   if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
01389     // A power of two and'd with anything is a power of two or zero.
01390     if (isKnownToBeAPowerOfTwo(X, /*OrZero*/true, Depth, Q) ||
01391         isKnownToBeAPowerOfTwo(Y, /*OrZero*/true, Depth, Q))
01392       return true;
01393     // X & (-X) is always a power of two or zero.
01394     if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
01395       return true;
01396     return false;
01397   }
01398 
01399   // Adding a power-of-two or zero to the same power-of-two or zero yields
01400   // either the original power-of-two, a larger power-of-two or zero.
01401   if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
01402     OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
01403     if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
01404       if (match(X, m_And(m_Specific(Y), m_Value())) ||
01405           match(X, m_And(m_Value(), m_Specific(Y))))
01406         if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
01407           return true;
01408       if (match(Y, m_And(m_Specific(X), m_Value())) ||
01409           match(Y, m_And(m_Value(), m_Specific(X))))
01410         if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
01411           return true;
01412 
01413       unsigned BitWidth = V->getType()->getScalarSizeInBits();
01414       APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
01415       computeKnownBits(X, LHSZeroBits, LHSOneBits, nullptr, Depth, Q);
01416 
01417       APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
01418       computeKnownBits(Y, RHSZeroBits, RHSOneBits, nullptr, Depth, Q);
01419       // If i8 V is a power of two or zero:
01420       //  ZeroBits: 1 1 1 0 1 1 1 1
01421       // ~ZeroBits: 0 0 0 1 0 0 0 0
01422       if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
01423         // If OrZero isn't set, we cannot give back a zero result.
01424         // Make sure either the LHS or RHS has a bit set.
01425         if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
01426           return true;
01427     }
01428   }
01429 
01430   // An exact divide or right shift can only shift off zero bits, so the result
01431   // is a power of two only if the first operand is a power of two and not
01432   // copying a sign bit (sdiv int_min, 2).
01433   if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
01434       match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
01435     return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
01436                                   Depth, Q);
01437   }
01438 
01439   return false;
01440 }
01441 
01442 /// \brief Test whether a GEP's result is known to be non-null.
01443 ///
01444 /// Uses properties inherent in a GEP to try to determine whether it is known
01445 /// to be non-null.
01446 ///
01447 /// Currently this routine does not support vector GEPs.
01448 static bool isGEPKnownNonNull(GEPOperator *GEP, const DataLayout *DL,
01449                               unsigned Depth, const Query &Q) {
01450   if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
01451     return false;
01452 
01453   // FIXME: Support vector-GEPs.
01454   assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
01455 
01456   // If the base pointer is non-null, we cannot walk to a null address with an
01457   // inbounds GEP in address space zero.
01458   if (isKnownNonZero(GEP->getPointerOperand(), DL, Depth, Q))
01459     return true;
01460 
01461   // Past this, if we don't have DataLayout, we can't do much.
01462   if (!DL)
01463     return false;
01464 
01465   // Walk the GEP operands and see if any operand introduces a non-zero offset.
01466   // If so, then the GEP cannot produce a null pointer, as doing so would
01467   // inherently violate the inbounds contract within address space zero.
01468   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
01469        GTI != GTE; ++GTI) {
01470     // Struct types are easy -- they must always be indexed by a constant.
01471     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
01472       ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
01473       unsigned ElementIdx = OpC->getZExtValue();
01474       const StructLayout *SL = DL->getStructLayout(STy);
01475       uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
01476       if (ElementOffset > 0)
01477         return true;
01478       continue;
01479     }
01480 
01481     // If we have a zero-sized type, the index doesn't matter. Keep looping.
01482     if (DL->getTypeAllocSize(GTI.getIndexedType()) == 0)
01483       continue;
01484 
01485     // Fast path the constant operand case both for efficiency and so we don't
01486     // increment Depth when just zipping down an all-constant GEP.
01487     if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
01488       if (!OpC->isZero())
01489         return true;
01490       continue;
01491     }
01492 
01493     // We post-increment Depth here because while isKnownNonZero increments it
01494     // as well, when we pop back up that increment won't persist. We don't want
01495     // to recurse 10k times just because we have 10k GEP operands. We don't
01496     // bail completely out because we want to handle constant GEPs regardless
01497     // of depth.
01498     if (Depth++ >= MaxDepth)
01499       continue;
01500 
01501     if (isKnownNonZero(GTI.getOperand(), DL, Depth, Q))
01502       return true;
01503   }
01504 
01505   return false;
01506 }
01507 
01508 /// Does the 'Range' metadata (which must be a valid MD_range operand list)
01509 /// ensure that the value it's attached to is never Value?  'RangeType' is
01510 /// is the type of the value described by the range.
01511 static bool rangeMetadataExcludesValue(MDNode* Ranges,
01512                                        const APInt& Value) {
01513   const unsigned NumRanges = Ranges->getNumOperands() / 2;
01514   assert(NumRanges >= 1);
01515   for (unsigned i = 0; i < NumRanges; ++i) {
01516     ConstantInt *Lower =
01517         mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
01518     ConstantInt *Upper =
01519         mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
01520     ConstantRange Range(Lower->getValue(), Upper->getValue());
01521     if (Range.contains(Value))
01522       return false;
01523   }
01524   return true;
01525 }
01526 
01527 /// Return true if the given value is known to be non-zero when defined.
01528 /// For vectors return true if every element is known to be non-zero when
01529 /// defined. Supports values with integer or pointer type and vectors of
01530 /// integers.
01531 bool isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth,
01532                     const Query &Q) {
01533   if (Constant *C = dyn_cast<Constant>(V)) {
01534     if (C->isNullValue())
01535       return false;
01536     if (isa<ConstantInt>(C))
01537       // Must be non-zero due to null test above.
01538       return true;
01539     // TODO: Handle vectors
01540     return false;
01541   }
01542 
01543   if (Instruction* I = dyn_cast<Instruction>(V)) {
01544     if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
01545       // If the possible ranges don't contain zero, then the value is
01546       // definitely non-zero.
01547       if (IntegerType* Ty = dyn_cast<IntegerType>(V->getType())) {
01548         const APInt ZeroValue(Ty->getBitWidth(), 0);
01549         if (rangeMetadataExcludesValue(Ranges, ZeroValue))
01550           return true;
01551       }
01552     }
01553   }
01554 
01555   // The remaining tests are all recursive, so bail out if we hit the limit.
01556   if (Depth++ >= MaxDepth)
01557     return false;
01558 
01559   // Check for pointer simplifications.
01560   if (V->getType()->isPointerTy()) {
01561     if (isKnownNonNull(V))
01562       return true; 
01563     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
01564       if (isGEPKnownNonNull(GEP, TD, Depth, Q))
01565         return true;
01566   }
01567 
01568   unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), TD);
01569 
01570   // X | Y != 0 if X != 0 or Y != 0.
01571   Value *X = nullptr, *Y = nullptr;
01572   if (match(V, m_Or(m_Value(X), m_Value(Y))))
01573     return isKnownNonZero(X, TD, Depth, Q) ||
01574            isKnownNonZero(Y, TD, Depth, Q);
01575 
01576   // ext X != 0 if X != 0.
01577   if (isa<SExtInst>(V) || isa<ZExtInst>(V))
01578     return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth, Q);
01579 
01580   // shl X, Y != 0 if X is odd.  Note that the value of the shift is undefined
01581   // if the lowest bit is shifted off the end.
01582   if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
01583     // shl nuw can't remove any non-zero bits.
01584     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
01585     if (BO->hasNoUnsignedWrap())
01586       return isKnownNonZero(X, TD, Depth, Q);
01587 
01588     APInt KnownZero(BitWidth, 0);
01589     APInt KnownOne(BitWidth, 0);
01590     computeKnownBits(X, KnownZero, KnownOne, TD, Depth, Q);
01591     if (KnownOne[0])
01592       return true;
01593   }
01594   // shr X, Y != 0 if X is negative.  Note that the value of the shift is not
01595   // defined if the sign bit is shifted off the end.
01596   else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
01597     // shr exact can only shift out zero bits.
01598     PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
01599     if (BO->isExact())
01600       return isKnownNonZero(X, TD, Depth, Q);
01601 
01602     bool XKnownNonNegative, XKnownNegative;
01603     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth, Q);
01604     if (XKnownNegative)
01605       return true;
01606   }
01607   // div exact can only produce a zero if the dividend is zero.
01608   else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
01609     return isKnownNonZero(X, TD, Depth, Q);
01610   }
01611   // X + Y.
01612   else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
01613     bool XKnownNonNegative, XKnownNegative;
01614     bool YKnownNonNegative, YKnownNegative;
01615     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth, Q);
01616     ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth, Q);
01617 
01618     // If X and Y are both non-negative (as signed values) then their sum is not
01619     // zero unless both X and Y are zero.
01620     if (XKnownNonNegative && YKnownNonNegative)
01621       if (isKnownNonZero(X, TD, Depth, Q) ||
01622           isKnownNonZero(Y, TD, Depth, Q))
01623         return true;
01624 
01625     // If X and Y are both negative (as signed values) then their sum is not
01626     // zero unless both X and Y equal INT_MIN.
01627     if (BitWidth && XKnownNegative && YKnownNegative) {
01628       APInt KnownZero(BitWidth, 0);
01629       APInt KnownOne(BitWidth, 0);
01630       APInt Mask = APInt::getSignedMaxValue(BitWidth);
01631       // The sign bit of X is set.  If some other bit is set then X is not equal
01632       // to INT_MIN.
01633       computeKnownBits(X, KnownZero, KnownOne, TD, Depth, Q);
01634       if ((KnownOne & Mask) != 0)
01635         return true;
01636       // The sign bit of Y is set.  If some other bit is set then Y is not equal
01637       // to INT_MIN.
01638       computeKnownBits(Y, KnownZero, KnownOne, TD, Depth, Q);
01639       if ((KnownOne & Mask) != 0)
01640         return true;
01641     }
01642 
01643     // The sum of a non-negative number and a power of two is not zero.
01644     if (XKnownNonNegative &&
01645         isKnownToBeAPowerOfTwo(Y, /*OrZero*/false, Depth, Q))
01646       return true;
01647     if (YKnownNonNegative &&
01648         isKnownToBeAPowerOfTwo(X, /*OrZero*/false, Depth, Q))
01649       return true;
01650   }
01651   // X * Y.
01652   else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
01653     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
01654     // If X and Y are non-zero then so is X * Y as long as the multiplication
01655     // does not overflow.
01656     if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
01657         isKnownNonZero(X, TD, Depth, Q) &&
01658         isKnownNonZero(Y, TD, Depth, Q))
01659       return true;
01660   }
01661   // (C ? X : Y) != 0 if X != 0 and Y != 0.
01662   else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
01663     if (isKnownNonZero(SI->getTrueValue(), TD, Depth, Q) &&
01664         isKnownNonZero(SI->getFalseValue(), TD, Depth, Q))
01665       return true;
01666   }
01667 
01668   if (!BitWidth) return false;
01669   APInt KnownZero(BitWidth, 0);
01670   APInt KnownOne(BitWidth, 0);
01671   computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
01672   return KnownOne != 0;
01673 }
01674 
01675 /// Return true if 'V & Mask' is known to be zero.  We use this predicate to
01676 /// simplify operations downstream. Mask is known to be zero for bits that V
01677 /// cannot have.
01678 ///
01679 /// This function is defined on values with integer type, values with pointer
01680 /// type (but only if TD is non-null), and vectors of integers.  In the case
01681 /// where V is a vector, the mask, known zero, and known one values are the
01682 /// same width as the vector element, and the bit is set only if it is true
01683 /// for all of the elements in the vector.
01684 bool MaskedValueIsZero(Value *V, const APInt &Mask,
01685                        const DataLayout *TD, unsigned Depth,
01686                        const Query &Q) {
01687   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
01688   computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
01689   return (KnownZero & Mask) == Mask;
01690 }
01691 
01692 
01693 
01694 /// Return the number of times the sign bit of the register is replicated into
01695 /// the other bits. We know that at least 1 bit is always equal to the sign bit
01696 /// (itself), but other cases can give us information. For example, immediately
01697 /// after an "ashr X, 2", we know that the top 3 bits are all equal to each
01698 /// other, so we return 3.
01699 ///
01700 /// 'Op' must have a scalar integer type.
01701 ///
01702 unsigned ComputeNumSignBits(Value *V, const DataLayout *TD,
01703                             unsigned Depth, const Query &Q) {
01704   assert((TD || V->getType()->isIntOrIntVectorTy()) &&
01705          "ComputeNumSignBits requires a DataLayout object to operate "
01706          "on non-integer values!");
01707   Type *Ty = V->getType();
01708   unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
01709                          Ty->getScalarSizeInBits();
01710   unsigned Tmp, Tmp2;
01711   unsigned FirstAnswer = 1;
01712 
01713   // Note that ConstantInt is handled by the general computeKnownBits case
01714   // below.
01715 
01716   if (Depth == 6)
01717     return 1;  // Limit search depth.
01718 
01719   Operator *U = dyn_cast<Operator>(V);
01720   switch (Operator::getOpcode(V)) {
01721   default: break;
01722   case Instruction::SExt:
01723     Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
01724     return ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q) + Tmp;
01725 
01726   case Instruction::AShr: {
01727     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
01728     // ashr X, C   -> adds C sign bits.  Vectors too.
01729     const APInt *ShAmt;
01730     if (match(U->getOperand(1), m_APInt(ShAmt))) {
01731       Tmp += ShAmt->getZExtValue();
01732       if (Tmp > TyBits) Tmp = TyBits;
01733     }
01734     return Tmp;
01735   }
01736   case Instruction::Shl: {
01737     const APInt *ShAmt;
01738     if (match(U->getOperand(1), m_APInt(ShAmt))) {
01739       // shl destroys sign bits.
01740       Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
01741       Tmp2 = ShAmt->getZExtValue();
01742       if (Tmp2 >= TyBits ||      // Bad shift.
01743           Tmp2 >= Tmp) break;    // Shifted all sign bits out.
01744       return Tmp - Tmp2;
01745     }
01746     break;
01747   }
01748   case Instruction::And:
01749   case Instruction::Or:
01750   case Instruction::Xor:    // NOT is handled here.
01751     // Logical binary ops preserve the number of sign bits at the worst.
01752     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
01753     if (Tmp != 1) {
01754       Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
01755       FirstAnswer = std::min(Tmp, Tmp2);
01756       // We computed what we know about the sign bits as our first
01757       // answer. Now proceed to the generic code that uses
01758       // computeKnownBits, and pick whichever answer is better.
01759     }
01760     break;
01761 
01762   case Instruction::Select:
01763     Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
01764     if (Tmp == 1) return 1;  // Early out.
01765     Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1, Q);
01766     return std::min(Tmp, Tmp2);
01767 
01768   case Instruction::Add:
01769     // Add can have at most one carry bit.  Thus we know that the output
01770     // is, at worst, one more bit than the inputs.
01771     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
01772     if (Tmp == 1) return 1;  // Early out.
01773 
01774     // Special case decrementing a value (ADD X, -1):
01775     if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
01776       if (CRHS->isAllOnesValue()) {
01777         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
01778         computeKnownBits(U->getOperand(0), KnownZero, KnownOne, TD, Depth+1, Q);
01779 
01780         // If the input is known to be 0 or 1, the output is 0/-1, which is all
01781         // sign bits set.
01782         if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
01783           return TyBits;
01784 
01785         // If we are subtracting one from a positive number, there is no carry
01786         // out of the result.
01787         if (KnownZero.isNegative())
01788           return Tmp;
01789       }
01790 
01791     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
01792     if (Tmp2 == 1) return 1;
01793     return std::min(Tmp, Tmp2)-1;
01794 
01795   case Instruction::Sub:
01796     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1, Q);
01797     if (Tmp2 == 1) return 1;
01798 
01799     // Handle NEG.
01800     if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
01801       if (CLHS->isNullValue()) {
01802         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
01803         computeKnownBits(U->getOperand(1), KnownZero, KnownOne, TD, Depth+1, Q);
01804         // If the input is known to be 0 or 1, the output is 0/-1, which is all
01805         // sign bits set.
01806         if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
01807           return TyBits;
01808 
01809         // If the input is known to be positive (the sign bit is known clear),
01810         // the output of the NEG has the same number of sign bits as the input.
01811         if (KnownZero.isNegative())
01812           return Tmp2;
01813 
01814         // Otherwise, we treat this like a SUB.
01815       }
01816 
01817     // Sub can have at most one carry bit.  Thus we know that the output
01818     // is, at worst, one more bit than the inputs.
01819     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1, Q);
01820     if (Tmp == 1) return 1;  // Early out.
01821     return std::min(Tmp, Tmp2)-1;
01822 
01823   case Instruction::PHI: {
01824     PHINode *PN = cast<PHINode>(U);
01825     unsigned NumIncomingValues = PN->getNumIncomingValues();
01826     // Don't analyze large in-degree PHIs.
01827     if (NumIncomingValues > 4) break;
01828     // Unreachable blocks may have zero-operand PHI nodes.
01829     if (NumIncomingValues == 0) break;
01830 
01831     // Take the minimum of all incoming values.  This can't infinitely loop
01832     // because of our depth threshold.
01833     Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1, Q);
01834     for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
01835       if (Tmp == 1) return Tmp;
01836       Tmp = std::min(Tmp,
01837                      ComputeNumSignBits(PN->getIncomingValue(i), TD,
01838                                         Depth+1, Q));
01839     }
01840     return Tmp;
01841   }
01842 
01843   case Instruction::Trunc:
01844     // FIXME: it's tricky to do anything useful for this, but it is an important
01845     // case for targets like X86.
01846     break;
01847   }
01848 
01849   // Finally, if we can prove that the top bits of the result are 0's or 1's,
01850   // use this information.
01851   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
01852   APInt Mask;
01853   computeKnownBits(V, KnownZero, KnownOne, TD, Depth, Q);
01854 
01855   if (KnownZero.isNegative()) {        // sign bit is 0
01856     Mask = KnownZero;
01857   } else if (KnownOne.isNegative()) {  // sign bit is 1;
01858     Mask = KnownOne;
01859   } else {
01860     // Nothing known.
01861     return FirstAnswer;
01862   }
01863 
01864   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
01865   // the number of identical bits in the top of the input value.
01866   Mask = ~Mask;
01867   Mask <<= Mask.getBitWidth()-TyBits;
01868   // Return # leading zeros.  We use 'min' here in case Val was zero before
01869   // shifting.  We don't want to return '64' as for an i32 "0".
01870   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
01871 }
01872 
01873 /// This function computes the integer multiple of Base that equals V.
01874 /// If successful, it returns true and returns the multiple in
01875 /// Multiple. If unsuccessful, it returns false. It looks
01876 /// through SExt instructions only if LookThroughSExt is true.
01877 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
01878                            bool LookThroughSExt, unsigned Depth) {
01879   const unsigned MaxDepth = 6;
01880 
01881   assert(V && "No Value?");
01882   assert(Depth <= MaxDepth && "Limit Search Depth");
01883   assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
01884 
01885   Type *T = V->getType();
01886 
01887   ConstantInt *CI = dyn_cast<ConstantInt>(V);
01888 
01889   if (Base == 0)
01890     return false;
01891 
01892   if (Base == 1) {
01893     Multiple = V;
01894     return true;
01895   }
01896 
01897   ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
01898   Constant *BaseVal = ConstantInt::get(T, Base);
01899   if (CO && CO == BaseVal) {
01900     // Multiple is 1.
01901     Multiple = ConstantInt::get(T, 1);
01902     return true;
01903   }
01904 
01905   if (CI && CI->getZExtValue() % Base == 0) {
01906     Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
01907     return true;
01908   }
01909 
01910   if (Depth == MaxDepth) return false;  // Limit search depth.
01911 
01912   Operator *I = dyn_cast<Operator>(V);
01913   if (!I) return false;
01914 
01915   switch (I->getOpcode()) {
01916   default: break;
01917   case Instruction::SExt:
01918     if (!LookThroughSExt) return false;
01919     // otherwise fall through to ZExt
01920   case Instruction::ZExt:
01921     return ComputeMultiple(I->getOperand(0), Base, Multiple,
01922                            LookThroughSExt, Depth+1);
01923   case Instruction::Shl:
01924   case Instruction::Mul: {
01925     Value *Op0 = I->getOperand(0);
01926     Value *Op1 = I->getOperand(1);
01927 
01928     if (I->getOpcode() == Instruction::Shl) {
01929       ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
01930       if (!Op1CI) return false;
01931       // Turn Op0 << Op1 into Op0 * 2^Op1
01932       APInt Op1Int = Op1CI->getValue();
01933       uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
01934       APInt API(Op1Int.getBitWidth(), 0);
01935       API.setBit(BitToSet);
01936       Op1 = ConstantInt::get(V->getContext(), API);
01937     }
01938 
01939     Value *Mul0 = nullptr;
01940     if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
01941       if (Constant *Op1C = dyn_cast<Constant>(Op1))
01942         if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
01943           if (Op1C->getType()->getPrimitiveSizeInBits() <
01944               MulC->getType()->getPrimitiveSizeInBits())
01945             Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
01946           if (Op1C->getType()->getPrimitiveSizeInBits() >
01947               MulC->getType()->getPrimitiveSizeInBits())
01948             MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
01949 
01950           // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
01951           Multiple = ConstantExpr::getMul(MulC, Op1C);
01952           return true;
01953         }
01954 
01955       if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
01956         if (Mul0CI->getValue() == 1) {
01957           // V == Base * Op1, so return Op1
01958           Multiple = Op1;
01959           return true;
01960         }
01961     }
01962 
01963     Value *Mul1 = nullptr;
01964     if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
01965       if (Constant *Op0C = dyn_cast<Constant>(Op0))
01966         if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
01967           if (Op0C->getType()->getPrimitiveSizeInBits() <
01968               MulC->getType()->getPrimitiveSizeInBits())
01969             Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
01970           if (Op0C->getType()->getPrimitiveSizeInBits() >
01971               MulC->getType()->getPrimitiveSizeInBits())
01972             MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
01973 
01974           // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
01975           Multiple = ConstantExpr::getMul(MulC, Op0C);
01976           return true;
01977         }
01978 
01979       if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
01980         if (Mul1CI->getValue() == 1) {
01981           // V == Base * Op0, so return Op0
01982           Multiple = Op0;
01983           return true;
01984         }
01985     }
01986   }
01987   }
01988 
01989   // We could not determine if V is a multiple of Base.
01990   return false;
01991 }
01992 
01993 /// Return true if we can prove that the specified FP value is never equal to
01994 /// -0.0.
01995 ///
01996 /// NOTE: this function will need to be revisited when we support non-default
01997 /// rounding modes!
01998 ///
01999 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
02000   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
02001     return !CFP->getValueAPF().isNegZero();
02002 
02003   // FIXME: Magic number! At the least, this should be given a name because it's
02004   // used similarly in CannotBeOrderedLessThanZero(). A better fix may be to
02005   // expose it as a parameter, so it can be used for testing / experimenting.
02006   if (Depth == 6)
02007     return false;  // Limit search depth.
02008 
02009   const Operator *I = dyn_cast<Operator>(V);
02010   if (!I) return false;
02011 
02012   // Check if the nsz fast-math flag is set
02013   if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
02014     if (FPO->hasNoSignedZeros())
02015       return true;
02016 
02017   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
02018   if (I->getOpcode() == Instruction::FAdd)
02019     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
02020       if (CFP->isNullValue())
02021         return true;
02022 
02023   // sitofp and uitofp turn into +0.0 for zero.
02024   if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
02025     return true;
02026 
02027   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
02028     // sqrt(-0.0) = -0.0, no other negative results are possible.
02029     if (II->getIntrinsicID() == Intrinsic::sqrt)
02030       return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
02031 
02032   if (const CallInst *CI = dyn_cast<CallInst>(I))
02033     if (const Function *F = CI->getCalledFunction()) {
02034       if (F->isDeclaration()) {
02035         // abs(x) != -0.0
02036         if (F->getName() == "abs") return true;
02037         // fabs[lf](x) != -0.0
02038         if (F->getName() == "fabs") return true;
02039         if (F->getName() == "fabsf") return true;
02040         if (F->getName() == "fabsl") return true;
02041         if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
02042             F->getName() == "sqrtl")
02043           return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
02044       }
02045     }
02046 
02047   return false;
02048 }
02049 
02050 bool llvm::CannotBeOrderedLessThanZero(const Value *V, unsigned Depth) {
02051   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
02052     return !CFP->getValueAPF().isNegative() || CFP->getValueAPF().isZero();
02053 
02054   // FIXME: Magic number! At the least, this should be given a name because it's
02055   // used similarly in CannotBeNegativeZero(). A better fix may be to
02056   // expose it as a parameter, so it can be used for testing / experimenting.
02057   if (Depth == 6)
02058     return false;  // Limit search depth.
02059 
02060   const Operator *I = dyn_cast<Operator>(V);
02061   if (!I) return false;
02062 
02063   switch (I->getOpcode()) {
02064   default: break;
02065   case Instruction::FMul:
02066     // x*x is always non-negative or a NaN.
02067     if (I->getOperand(0) == I->getOperand(1)) 
02068       return true;
02069     // Fall through
02070   case Instruction::FAdd:
02071   case Instruction::FDiv:
02072   case Instruction::FRem:
02073     return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1) &&
02074            CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1);
02075   case Instruction::FPExt:
02076   case Instruction::FPTrunc:
02077     // Widening/narrowing never change sign.
02078     return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
02079   case Instruction::Call: 
02080     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) 
02081       switch (II->getIntrinsicID()) {
02082       default: break;
02083       case Intrinsic::exp:
02084       case Intrinsic::exp2:
02085       case Intrinsic::fabs:
02086       case Intrinsic::sqrt:
02087         return true;
02088       case Intrinsic::powi: 
02089         if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
02090           // powi(x,n) is non-negative if n is even.
02091           if (CI->getBitWidth() <= 64 && CI->getSExtValue() % 2u == 0)
02092             return true;
02093         }
02094         return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
02095       case Intrinsic::fma:
02096       case Intrinsic::fmuladd:
02097         // x*x+y is non-negative if y is non-negative.
02098         return I->getOperand(0) == I->getOperand(1) && 
02099                CannotBeOrderedLessThanZero(I->getOperand(2), Depth+1);
02100       }
02101     break;
02102   }
02103   return false; 
02104 }
02105 
02106 /// If the specified value can be set by repeating the same byte in memory,
02107 /// return the i8 value that it is represented with.  This is
02108 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
02109 /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
02110 /// byte store (e.g. i16 0x1234), return null.
02111 Value *llvm::isBytewiseValue(Value *V) {
02112   // All byte-wide stores are splatable, even of arbitrary variables.
02113   if (V->getType()->isIntegerTy(8)) return V;
02114 
02115   // Handle 'null' ConstantArrayZero etc.
02116   if (Constant *C = dyn_cast<Constant>(V))
02117     if (C->isNullValue())
02118       return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
02119 
02120   // Constant float and double values can be handled as integer values if the
02121   // corresponding integer value is "byteable".  An important case is 0.0.
02122   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
02123     if (CFP->getType()->isFloatTy())
02124       V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
02125     if (CFP->getType()->isDoubleTy())
02126       V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
02127     // Don't handle long double formats, which have strange constraints.
02128   }
02129 
02130   // We can handle constant integers that are multiple of 8 bits.
02131   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
02132     if (CI->getBitWidth() % 8 == 0) {
02133       assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
02134 
02135       // We can check that all bytes of an integer are equal by making use of a
02136       // little trick: rotate by 8 and check if it's still the same value.
02137       if (CI->getValue() != CI->getValue().rotl(8))
02138         return nullptr;
02139       return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
02140     }
02141   }
02142 
02143   // A ConstantDataArray/Vector is splatable if all its members are equal and
02144   // also splatable.
02145   if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
02146     Value *Elt = CA->getElementAsConstant(0);
02147     Value *Val = isBytewiseValue(Elt);
02148     if (!Val)
02149       return nullptr;
02150 
02151     for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
02152       if (CA->getElementAsConstant(I) != Elt)
02153         return nullptr;
02154 
02155     return Val;
02156   }
02157 
02158   // Conceptually, we could handle things like:
02159   //   %a = zext i8 %X to i16
02160   //   %b = shl i16 %a, 8
02161   //   %c = or i16 %a, %b
02162   // but until there is an example that actually needs this, it doesn't seem
02163   // worth worrying about.
02164   return nullptr;
02165 }
02166 
02167 
02168 // This is the recursive version of BuildSubAggregate. It takes a few different
02169 // arguments. Idxs is the index within the nested struct From that we are
02170 // looking at now (which is of type IndexedType). IdxSkip is the number of
02171 // indices from Idxs that should be left out when inserting into the resulting
02172 // struct. To is the result struct built so far, new insertvalue instructions
02173 // build on that.
02174 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
02175                                 SmallVectorImpl<unsigned> &Idxs,
02176                                 unsigned IdxSkip,
02177                                 Instruction *InsertBefore) {
02178   llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
02179   if (STy) {
02180     // Save the original To argument so we can modify it
02181     Value *OrigTo = To;
02182     // General case, the type indexed by Idxs is a struct
02183     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
02184       // Process each struct element recursively
02185       Idxs.push_back(i);
02186       Value *PrevTo = To;
02187       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
02188                              InsertBefore);
02189       Idxs.pop_back();
02190       if (!To) {
02191         // Couldn't find any inserted value for this index? Cleanup
02192         while (PrevTo != OrigTo) {
02193           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
02194           PrevTo = Del->getAggregateOperand();
02195           Del->eraseFromParent();
02196         }
02197         // Stop processing elements
02198         break;
02199       }
02200     }
02201     // If we successfully found a value for each of our subaggregates
02202     if (To)
02203       return To;
02204   }
02205   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
02206   // the struct's elements had a value that was inserted directly. In the latter
02207   // case, perhaps we can't determine each of the subelements individually, but
02208   // we might be able to find the complete struct somewhere.
02209 
02210   // Find the value that is at that particular spot
02211   Value *V = FindInsertedValue(From, Idxs);
02212 
02213   if (!V)
02214     return nullptr;
02215 
02216   // Insert the value in the new (sub) aggregrate
02217   return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
02218                                        "tmp", InsertBefore);
02219 }
02220 
02221 // This helper takes a nested struct and extracts a part of it (which is again a
02222 // struct) into a new value. For example, given the struct:
02223 // { a, { b, { c, d }, e } }
02224 // and the indices "1, 1" this returns
02225 // { c, d }.
02226 //
02227 // It does this by inserting an insertvalue for each element in the resulting
02228 // struct, as opposed to just inserting a single struct. This will only work if
02229 // each of the elements of the substruct are known (ie, inserted into From by an
02230 // insertvalue instruction somewhere).
02231 //
02232 // All inserted insertvalue instructions are inserted before InsertBefore
02233 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
02234                                 Instruction *InsertBefore) {
02235   assert(InsertBefore && "Must have someplace to insert!");
02236   Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
02237                                                              idx_range);
02238   Value *To = UndefValue::get(IndexedType);
02239   SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
02240   unsigned IdxSkip = Idxs.size();
02241 
02242   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
02243 }
02244 
02245 /// Given an aggregrate and an sequence of indices, see if
02246 /// the scalar value indexed is already around as a register, for example if it
02247 /// were inserted directly into the aggregrate.
02248 ///
02249 /// If InsertBefore is not null, this function will duplicate (modified)
02250 /// insertvalues when a part of a nested struct is extracted.
02251 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
02252                                Instruction *InsertBefore) {
02253   // Nothing to index? Just return V then (this is useful at the end of our
02254   // recursion).
02255   if (idx_range.empty())
02256     return V;
02257   // We have indices, so V should have an indexable type.
02258   assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
02259          "Not looking at a struct or array?");
02260   assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
02261          "Invalid indices for type?");
02262 
02263   if (Constant *C = dyn_cast<Constant>(V)) {
02264     C = C->getAggregateElement(idx_range[0]);
02265     if (!C) return nullptr;
02266     return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
02267   }
02268 
02269   if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
02270     // Loop the indices for the insertvalue instruction in parallel with the
02271     // requested indices
02272     const unsigned *req_idx = idx_range.begin();
02273     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
02274          i != e; ++i, ++req_idx) {
02275       if (req_idx == idx_range.end()) {
02276         // We can't handle this without inserting insertvalues
02277         if (!InsertBefore)
02278           return nullptr;
02279 
02280         // The requested index identifies a part of a nested aggregate. Handle
02281         // this specially. For example,
02282         // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
02283         // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
02284         // %C = extractvalue {i32, { i32, i32 } } %B, 1
02285         // This can be changed into
02286         // %A = insertvalue {i32, i32 } undef, i32 10, 0
02287         // %C = insertvalue {i32, i32 } %A, i32 11, 1
02288         // which allows the unused 0,0 element from the nested struct to be
02289         // removed.
02290         return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
02291                                  InsertBefore);
02292       }
02293 
02294       // This insert value inserts something else than what we are looking for.
02295       // See if the (aggregrate) value inserted into has the value we are
02296       // looking for, then.
02297       if (*req_idx != *i)
02298         return FindInsertedValue(I->getAggregateOperand(), idx_range,
02299                                  InsertBefore);
02300     }
02301     // If we end up here, the indices of the insertvalue match with those
02302     // requested (though possibly only partially). Now we recursively look at
02303     // the inserted value, passing any remaining indices.
02304     return FindInsertedValue(I->getInsertedValueOperand(),
02305                              makeArrayRef(req_idx, idx_range.end()),
02306                              InsertBefore);
02307   }
02308 
02309   if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
02310     // If we're extracting a value from an aggregrate that was extracted from
02311     // something else, we can extract from that something else directly instead.
02312     // However, we will need to chain I's indices with the requested indices.
02313 
02314     // Calculate the number of indices required
02315     unsigned size = I->getNumIndices() + idx_range.size();
02316     // Allocate some space to put the new indices in
02317     SmallVector<unsigned, 5> Idxs;
02318     Idxs.reserve(size);
02319     // Add indices from the extract value instruction
02320     Idxs.append(I->idx_begin(), I->idx_end());
02321 
02322     // Add requested indices
02323     Idxs.append(idx_range.begin(), idx_range.end());
02324 
02325     assert(Idxs.size() == size
02326            && "Number of indices added not correct?");
02327 
02328     return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
02329   }
02330   // Otherwise, we don't know (such as, extracting from a function return value
02331   // or load instruction)
02332   return nullptr;
02333 }
02334 
02335 /// Analyze the specified pointer to see if it can be expressed as a base
02336 /// pointer plus a constant offset. Return the base and offset to the caller.
02337 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
02338                                               const DataLayout *DL) {
02339   // Without DataLayout, conservatively assume 64-bit offsets, which is
02340   // the widest we support.
02341   unsigned BitWidth = DL ? DL->getPointerTypeSizeInBits(Ptr->getType()) : 64;
02342   APInt ByteOffset(BitWidth, 0);
02343   while (1) {
02344     if (Ptr->getType()->isVectorTy())
02345       break;
02346 
02347     if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
02348       if (DL) {
02349         APInt GEPOffset(BitWidth, 0);
02350         if (!GEP->accumulateConstantOffset(*DL, GEPOffset))
02351           break;
02352 
02353         ByteOffset += GEPOffset;
02354       }
02355 
02356       Ptr = GEP->getPointerOperand();
02357     } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
02358                Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
02359       Ptr = cast<Operator>(Ptr)->getOperand(0);
02360     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
02361       if (GA->mayBeOverridden())
02362         break;
02363       Ptr = GA->getAliasee();
02364     } else {
02365       break;
02366     }
02367   }
02368   Offset = ByteOffset.getSExtValue();
02369   return Ptr;
02370 }
02371 
02372 
02373 /// This function computes the length of a null-terminated C string pointed to
02374 /// by V. If successful, it returns true and returns the string in Str.
02375 /// If unsuccessful, it returns false.
02376 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
02377                                  uint64_t Offset, bool TrimAtNul) {
02378   assert(V);
02379 
02380   // Look through bitcast instructions and geps.
02381   V = V->stripPointerCasts();
02382 
02383   // If the value is a GEP instructionor  constant expression, treat it as an
02384   // offset.
02385   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
02386     // Make sure the GEP has exactly three arguments.
02387     if (GEP->getNumOperands() != 3)
02388       return false;
02389 
02390     // Make sure the index-ee is a pointer to array of i8.
02391     PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
02392     ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
02393     if (!AT || !AT->getElementType()->isIntegerTy(8))
02394       return false;
02395 
02396     // Check to make sure that the first operand of the GEP is an integer and
02397     // has value 0 so that we are sure we're indexing into the initializer.
02398     const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
02399     if (!FirstIdx || !FirstIdx->isZero())
02400       return false;
02401 
02402     // If the second index isn't a ConstantInt, then this is a variable index
02403     // into the array.  If this occurs, we can't say anything meaningful about
02404     // the string.
02405     uint64_t StartIdx = 0;
02406     if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
02407       StartIdx = CI->getZExtValue();
02408     else
02409       return false;
02410     return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset);
02411   }
02412 
02413   // The GEP instruction, constant or instruction, must reference a global
02414   // variable that is a constant and is initialized. The referenced constant
02415   // initializer is the array that we'll use for optimization.
02416   const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
02417   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
02418     return false;
02419 
02420   // Handle the all-zeros case
02421   if (GV->getInitializer()->isNullValue()) {
02422     // This is a degenerate case. The initializer is constant zero so the
02423     // length of the string must be zero.
02424     Str = "";
02425     return true;
02426   }
02427 
02428   // Must be a Constant Array
02429   const ConstantDataArray *Array =
02430     dyn_cast<ConstantDataArray>(GV->getInitializer());
02431   if (!Array || !Array->isString())
02432     return false;
02433 
02434   // Get the number of elements in the array
02435   uint64_t NumElts = Array->getType()->getArrayNumElements();
02436 
02437   // Start out with the entire array in the StringRef.
02438   Str = Array->getAsString();
02439 
02440   if (Offset > NumElts)
02441     return false;
02442 
02443   // Skip over 'offset' bytes.
02444   Str = Str.substr(Offset);
02445 
02446   if (TrimAtNul) {
02447     // Trim off the \0 and anything after it.  If the array is not nul
02448     // terminated, we just return the whole end of string.  The client may know
02449     // some other way that the string is length-bound.
02450     Str = Str.substr(0, Str.find('\0'));
02451   }
02452   return true;
02453 }
02454 
02455 // These next two are very similar to the above, but also look through PHI
02456 // nodes.
02457 // TODO: See if we can integrate these two together.
02458 
02459 /// If we can compute the length of the string pointed to by
02460 /// the specified pointer, return 'len+1'.  If we can't, return 0.
02461 static uint64_t GetStringLengthH(Value *V, SmallPtrSetImpl<PHINode*> &PHIs) {
02462   // Look through noop bitcast instructions.
02463   V = V->stripPointerCasts();
02464 
02465   // If this is a PHI node, there are two cases: either we have already seen it
02466   // or we haven't.
02467   if (PHINode *PN = dyn_cast<PHINode>(V)) {
02468     if (!PHIs.insert(PN).second)
02469       return ~0ULL;  // already in the set.
02470 
02471     // If it was new, see if all the input strings are the same length.
02472     uint64_t LenSoFar = ~0ULL;
02473     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
02474       uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
02475       if (Len == 0) return 0; // Unknown length -> unknown.
02476 
02477       if (Len == ~0ULL) continue;
02478 
02479       if (Len != LenSoFar && LenSoFar != ~0ULL)
02480         return 0;    // Disagree -> unknown.
02481       LenSoFar = Len;
02482     }
02483 
02484     // Success, all agree.
02485     return LenSoFar;
02486   }
02487 
02488   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
02489   if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
02490     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
02491     if (Len1 == 0) return 0;
02492     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
02493     if (Len2 == 0) return 0;
02494     if (Len1 == ~0ULL) return Len2;
02495     if (Len2 == ~0ULL) return Len1;
02496     if (Len1 != Len2) return 0;
02497     return Len1;
02498   }
02499 
02500   // Otherwise, see if we can read the string.
02501   StringRef StrData;
02502   if (!getConstantStringInfo(V, StrData))
02503     return 0;
02504 
02505   return StrData.size()+1;
02506 }
02507 
02508 /// If we can compute the length of the string pointed to by
02509 /// the specified pointer, return 'len+1'.  If we can't, return 0.
02510 uint64_t llvm::GetStringLength(Value *V) {
02511   if (!V->getType()->isPointerTy()) return 0;
02512 
02513   SmallPtrSet<PHINode*, 32> PHIs;
02514   uint64_t Len = GetStringLengthH(V, PHIs);
02515   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
02516   // an empty string as a length.
02517   return Len == ~0ULL ? 1 : Len;
02518 }
02519 
02520 Value *
02521 llvm::GetUnderlyingObject(Value *V, const DataLayout *TD, unsigned MaxLookup) {
02522   if (!V->getType()->isPointerTy())
02523     return V;
02524   for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
02525     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
02526       V = GEP->getPointerOperand();
02527     } else if (Operator::getOpcode(V) == Instruction::BitCast ||
02528                Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
02529       V = cast<Operator>(V)->getOperand(0);
02530     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
02531       if (GA->mayBeOverridden())
02532         return V;
02533       V = GA->getAliasee();
02534     } else {
02535       // See if InstructionSimplify knows any relevant tricks.
02536       if (Instruction *I = dyn_cast<Instruction>(V))
02537         // TODO: Acquire a DominatorTree and AssumptionCache and use them.
02538         if (Value *Simplified = SimplifyInstruction(I, TD, nullptr)) {
02539           V = Simplified;
02540           continue;
02541         }
02542 
02543       return V;
02544     }
02545     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
02546   }
02547   return V;
02548 }
02549 
02550 void
02551 llvm::GetUnderlyingObjects(Value *V,
02552                            SmallVectorImpl<Value *> &Objects,
02553                            const DataLayout *TD,
02554                            unsigned MaxLookup) {
02555   SmallPtrSet<Value *, 4> Visited;
02556   SmallVector<Value *, 4> Worklist;
02557   Worklist.push_back(V);
02558   do {
02559     Value *P = Worklist.pop_back_val();
02560     P = GetUnderlyingObject(P, TD, MaxLookup);
02561 
02562     if (!Visited.insert(P).second)
02563       continue;
02564 
02565     if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
02566       Worklist.push_back(SI->getTrueValue());
02567       Worklist.push_back(SI->getFalseValue());
02568       continue;
02569     }
02570 
02571     if (PHINode *PN = dyn_cast<PHINode>(P)) {
02572       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
02573         Worklist.push_back(PN->getIncomingValue(i));
02574       continue;
02575     }
02576 
02577     Objects.push_back(P);
02578   } while (!Worklist.empty());
02579 }
02580 
02581 /// Return true if the only users of this pointer are lifetime markers.
02582 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
02583   for (const User *U : V->users()) {
02584     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
02585     if (!II) return false;
02586 
02587     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
02588         II->getIntrinsicID() != Intrinsic::lifetime_end)
02589       return false;
02590   }
02591   return true;
02592 }
02593 
02594 bool llvm::isSafeToSpeculativelyExecute(const Value *V,
02595                                         const DataLayout *TD) {
02596   const Operator *Inst = dyn_cast<Operator>(V);
02597   if (!Inst)
02598     return false;
02599 
02600   for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
02601     if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
02602       if (C->canTrap())
02603         return false;
02604 
02605   switch (Inst->getOpcode()) {
02606   default:
02607     return true;
02608   case Instruction::UDiv:
02609   case Instruction::URem: {
02610     // x / y is undefined if y == 0.
02611     const APInt *V;
02612     if (match(Inst->getOperand(1), m_APInt(V)))
02613       return *V != 0;
02614     return false;
02615   }
02616   case Instruction::SDiv:
02617   case Instruction::SRem: {
02618     // x / y is undefined if y == 0 or x == INT_MIN and y == -1
02619     const APInt *Numerator, *Denominator;
02620     if (!match(Inst->getOperand(1), m_APInt(Denominator)))
02621       return false;
02622     // We cannot hoist this division if the denominator is 0.
02623     if (*Denominator == 0)
02624       return false;
02625     // It's safe to hoist if the denominator is not 0 or -1.
02626     if (*Denominator != -1)
02627       return true;
02628     // At this point we know that the denominator is -1.  It is safe to hoist as
02629     // long we know that the numerator is not INT_MIN.
02630     if (match(Inst->getOperand(0), m_APInt(Numerator)))
02631       return !Numerator->isMinSignedValue();
02632     // The numerator *might* be MinSignedValue.
02633     return false;
02634   }
02635   case Instruction::Load: {
02636     const LoadInst *LI = cast<LoadInst>(Inst);
02637     if (!LI->isUnordered() ||
02638         // Speculative load may create a race that did not exist in the source.
02639         LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
02640       return false;
02641     return LI->getPointerOperand()->isDereferenceablePointer(TD);
02642   }
02643   case Instruction::Call: {
02644     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
02645       switch (II->getIntrinsicID()) {
02646       // These synthetic intrinsics have no side-effects and just mark
02647       // information about their operands.
02648       // FIXME: There are other no-op synthetic instructions that potentially
02649       // should be considered at least *safe* to speculate...
02650       case Intrinsic::dbg_declare:
02651       case Intrinsic::dbg_value:
02652         return true;
02653 
02654       case Intrinsic::bswap:
02655       case Intrinsic::ctlz:
02656       case Intrinsic::ctpop:
02657       case Intrinsic::cttz:
02658       case Intrinsic::objectsize:
02659       case Intrinsic::sadd_with_overflow:
02660       case Intrinsic::smul_with_overflow:
02661       case Intrinsic::ssub_with_overflow:
02662       case Intrinsic::uadd_with_overflow:
02663       case Intrinsic::umul_with_overflow:
02664       case Intrinsic::usub_with_overflow:
02665         return true;
02666       // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
02667       // errno like libm sqrt would.
02668       case Intrinsic::sqrt:
02669       case Intrinsic::fma:
02670       case Intrinsic::fmuladd:
02671       case Intrinsic::fabs:
02672       case Intrinsic::minnum:
02673       case Intrinsic::maxnum:
02674         return true;
02675       // TODO: some fp intrinsics are marked as having the same error handling
02676       // as libm. They're safe to speculate when they won't error.
02677       // TODO: are convert_{from,to}_fp16 safe?
02678       // TODO: can we list target-specific intrinsics here?
02679       default: break;
02680       }
02681     }
02682     return false; // The called function could have undefined behavior or
02683                   // side-effects, even if marked readnone nounwind.
02684   }
02685   case Instruction::VAArg:
02686   case Instruction::Alloca:
02687   case Instruction::Invoke:
02688   case Instruction::PHI:
02689   case Instruction::Store:
02690   case Instruction::Ret:
02691   case Instruction::Br:
02692   case Instruction::IndirectBr:
02693   case Instruction::Switch:
02694   case Instruction::Unreachable:
02695   case Instruction::Fence:
02696   case Instruction::LandingPad:
02697   case Instruction::AtomicRMW:
02698   case Instruction::AtomicCmpXchg:
02699   case Instruction::Resume:
02700     return false; // Misc instructions which have effects
02701   }
02702 }
02703 
02704 /// Return true if we know that the specified value is never null.
02705 bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
02706   // Alloca never returns null, malloc might.
02707   if (isa<AllocaInst>(V)) return true;
02708 
02709   // A byval, inalloca, or nonnull argument is never null.
02710   if (const Argument *A = dyn_cast<Argument>(V))
02711     return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
02712 
02713   // Global values are not null unless extern weak.
02714   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
02715     return !GV->hasExternalWeakLinkage();
02716 
02717   // A Load tagged w/nonnull metadata is never null. 
02718   if (const LoadInst *LI = dyn_cast<LoadInst>(V))
02719     return LI->getMetadata(LLVMContext::MD_nonnull);
02720 
02721   if (ImmutableCallSite CS = V)
02722     if (CS.isReturnNonNull())
02723       return true;
02724 
02725   // operator new never returns null.
02726   if (isOperatorNewLikeFn(V, TLI, /*LookThroughBitCast=*/true))
02727     return true;
02728 
02729   return false;
02730 }
02731 
02732 OverflowResult llvm::computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
02733                                                    const DataLayout *DL,
02734                                                    AssumptionCache *AC,
02735                                                    const Instruction *CxtI,
02736                                                    const DominatorTree *DT) {
02737   // Multiplying n * m significant bits yields a result of n + m significant
02738   // bits. If the total number of significant bits does not exceed the
02739   // result bit width (minus 1), there is no overflow.
02740   // This means if we have enough leading zero bits in the operands
02741   // we can guarantee that the result does not overflow.
02742   // Ref: "Hacker's Delight" by Henry Warren
02743   unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
02744   APInt LHSKnownZero(BitWidth, 0);
02745   APInt LHSKnownOne(BitWidth, 0);
02746   APInt RHSKnownZero(BitWidth, 0);
02747   APInt RHSKnownOne(BitWidth, 0);
02748   computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
02749                    DT);
02750   computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
02751                    DT);
02752   // Note that underestimating the number of zero bits gives a more
02753   // conservative answer.
02754   unsigned ZeroBits = LHSKnownZero.countLeadingOnes() +
02755                       RHSKnownZero.countLeadingOnes();
02756   // First handle the easy case: if we have enough zero bits there's
02757   // definitely no overflow.
02758   if (ZeroBits >= BitWidth)
02759     return OverflowResult::NeverOverflows;
02760 
02761   // Get the largest possible values for each operand.
02762   APInt LHSMax = ~LHSKnownZero;
02763   APInt RHSMax = ~RHSKnownZero;
02764 
02765   // We know the multiply operation doesn't overflow if the maximum values for
02766   // each operand will not overflow after we multiply them together.
02767   bool MaxOverflow;
02768   LHSMax.umul_ov(RHSMax, MaxOverflow);
02769   if (!MaxOverflow)
02770     return OverflowResult::NeverOverflows;
02771 
02772   // We know it always overflows if multiplying the smallest possible values for
02773   // the operands also results in overflow.
02774   bool MinOverflow;
02775   LHSKnownOne.umul_ov(RHSKnownOne, MinOverflow);
02776   if (MinOverflow)
02777     return OverflowResult::AlwaysOverflows;
02778 
02779   return OverflowResult::MayOverflow;
02780 }
02781 
02782 OverflowResult llvm::computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
02783                                                    const DataLayout *DL,
02784                                                    AssumptionCache *AC,
02785                                                    const Instruction *CxtI,
02786                                                    const DominatorTree *DT) {
02787   bool LHSKnownNonNegative, LHSKnownNegative;
02788   ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
02789                  AC, CxtI, DT);
02790   if (LHSKnownNonNegative || LHSKnownNegative) {
02791     bool RHSKnownNonNegative, RHSKnownNegative;
02792     ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
02793                    AC, CxtI, DT);
02794 
02795     if (LHSKnownNegative && RHSKnownNegative) {
02796       // The sign bit is set in both cases: this MUST overflow.
02797       // Create a simple add instruction, and insert it into the struct.
02798       return OverflowResult::AlwaysOverflows;
02799     }
02800 
02801     if (LHSKnownNonNegative && RHSKnownNonNegative) {
02802       // The sign bit is clear in both cases: this CANNOT overflow.
02803       // Create a simple add instruction, and insert it into the struct.
02804       return OverflowResult::NeverOverflows;
02805     }
02806   }
02807 
02808   return OverflowResult::MayOverflow;
02809 }