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