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