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