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