LLVM API Documentation

ValueTracking.cpp
Go to the documentation of this file.
00001 //===- ValueTracking.cpp - Walk computations to compute properties --------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains routines that help analyze properties that chains of
00011 // computations have.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Analysis/ValueTracking.h"
00016 #include "llvm/ADT/SmallPtrSet.h"
00017 #include "llvm/Analysis/InstructionSimplify.h"
00018 #include "llvm/Analysis/MemoryBuiltins.h"
00019 #include "llvm/IR/ConstantRange.h"
00020 #include "llvm/IR/Constants.h"
00021 #include "llvm/IR/DataLayout.h"
00022 #include "llvm/IR/GetElementPtrTypeIterator.h"
00023 #include "llvm/IR/GlobalAlias.h"
00024 #include "llvm/IR/GlobalVariable.h"
00025 #include "llvm/IR/Instructions.h"
00026 #include "llvm/IR/IntrinsicInst.h"
00027 #include "llvm/IR/LLVMContext.h"
00028 #include "llvm/IR/Metadata.h"
00029 #include "llvm/IR/Operator.h"
00030 #include "llvm/IR/PatternMatch.h"
00031 #include "llvm/Support/MathExtras.h"
00032 #include <cstring>
00033 using namespace llvm;
00034 using namespace llvm::PatternMatch;
00035 
00036 const unsigned MaxDepth = 6;
00037 
00038 /// getBitWidth - Returns the bitwidth of the given scalar or pointer type (if
00039 /// unknown returns 0).  For vector types, returns the element type's bitwidth.
00040 static unsigned getBitWidth(Type *Ty, const DataLayout *TD) {
00041   if (unsigned BitWidth = Ty->getScalarSizeInBits())
00042     return BitWidth;
00043 
00044   return TD ? TD->getPointerTypeSizeInBits(Ty) : 0;
00045 }
00046 
00047 static void ComputeMaskedBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
00048                                     APInt &KnownZero, APInt &KnownOne,
00049                                     APInt &KnownZero2, APInt &KnownOne2,
00050                                     const DataLayout *TD, unsigned Depth) {
00051   if (!Add) {
00052     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
00053       // We know that the top bits of C-X are clear if X contains less bits
00054       // than C (i.e. no wrap-around can happen).  For example, 20-X is
00055       // positive if we can prove that X is >= 0 and < 16.
00056       if (!CLHS->getValue().isNegative()) {
00057         unsigned BitWidth = KnownZero.getBitWidth();
00058         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
00059         // NLZ can't be BitWidth with no sign bit
00060         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
00061         llvm::ComputeMaskedBits(Op1, KnownZero2, KnownOne2, TD, Depth+1);
00062 
00063         // If all of the MaskV bits are known to be zero, then we know the
00064         // output top bits are zero, because we now know that the output is
00065         // from [0-C].
00066         if ((KnownZero2 & MaskV) == MaskV) {
00067           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
00068           // Top bits known zero.
00069           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
00070         }
00071       }
00072     }
00073   }
00074 
00075   unsigned BitWidth = KnownZero.getBitWidth();
00076 
00077   // If one of the operands has trailing zeros, then the bits that the
00078   // other operand has in those bit positions will be preserved in the
00079   // result. For an add, this works with either operand. For a subtract,
00080   // this only works if the known zeros are in the right operand.
00081   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
00082   llvm::ComputeMaskedBits(Op0, LHSKnownZero, LHSKnownOne, TD, Depth+1);
00083   assert((LHSKnownZero & LHSKnownOne) == 0 &&
00084          "Bits known to be one AND zero?");
00085   unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes();
00086 
00087   llvm::ComputeMaskedBits(Op1, KnownZero2, KnownOne2, TD, Depth+1);
00088   assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
00089   unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes();
00090 
00091   // Determine which operand has more trailing zeros, and use that
00092   // many bits from the other operand.
00093   if (LHSKnownZeroOut > RHSKnownZeroOut) {
00094     if (Add) {
00095       APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut);
00096       KnownZero |= KnownZero2 & Mask;
00097       KnownOne  |= KnownOne2 & Mask;
00098     } else {
00099       // If the known zeros are in the left operand for a subtract,
00100       // fall back to the minimum known zeros in both operands.
00101       KnownZero |= APInt::getLowBitsSet(BitWidth,
00102                                         std::min(LHSKnownZeroOut,
00103                                                  RHSKnownZeroOut));
00104     }
00105   } else if (RHSKnownZeroOut >= LHSKnownZeroOut) {
00106     APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut);
00107     KnownZero |= LHSKnownZero & Mask;
00108     KnownOne  |= LHSKnownOne & Mask;
00109   }
00110 
00111   // Are we still trying to solve for the sign bit?
00112   if (!KnownZero.isNegative() && !KnownOne.isNegative()) {
00113     if (NSW) {
00114       if (Add) {
00115         // Adding two positive numbers can't wrap into negative
00116         if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
00117           KnownZero |= APInt::getSignBit(BitWidth);
00118         // and adding two negative numbers can't wrap into positive.
00119         else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
00120           KnownOne |= APInt::getSignBit(BitWidth);
00121       } else {
00122         // Subtracting a negative number from a positive one can't wrap
00123         if (LHSKnownZero.isNegative() && KnownOne2.isNegative())
00124           KnownZero |= APInt::getSignBit(BitWidth);
00125         // neither can subtracting a positive number from a negative one.
00126         else if (LHSKnownOne.isNegative() && KnownZero2.isNegative())
00127           KnownOne |= APInt::getSignBit(BitWidth);
00128       }
00129     }
00130   }
00131 }
00132 
00133 static void ComputeMaskedBitsMul(Value *Op0, Value *Op1, bool NSW,
00134                                  APInt &KnownZero, APInt &KnownOne,
00135                                  APInt &KnownZero2, APInt &KnownOne2,
00136                                  const DataLayout *TD, unsigned Depth) {
00137   unsigned BitWidth = KnownZero.getBitWidth();
00138   ComputeMaskedBits(Op1, KnownZero, KnownOne, TD, Depth+1);
00139   ComputeMaskedBits(Op0, KnownZero2, KnownOne2, TD, Depth+1);
00140   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00141   assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
00142 
00143   bool isKnownNegative = false;
00144   bool isKnownNonNegative = false;
00145   // If the multiplication is known not to overflow, compute the sign bit.
00146   if (NSW) {
00147     if (Op0 == Op1) {
00148       // The product of a number with itself is non-negative.
00149       isKnownNonNegative = true;
00150     } else {
00151       bool isKnownNonNegativeOp1 = KnownZero.isNegative();
00152       bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
00153       bool isKnownNegativeOp1 = KnownOne.isNegative();
00154       bool isKnownNegativeOp0 = KnownOne2.isNegative();
00155       // The product of two numbers with the same sign is non-negative.
00156       isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
00157         (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
00158       // The product of a negative number and a non-negative number is either
00159       // negative or zero.
00160       if (!isKnownNonNegative)
00161         isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
00162                            isKnownNonZero(Op0, TD, Depth)) ||
00163                           (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
00164                            isKnownNonZero(Op1, TD, Depth));
00165     }
00166   }
00167 
00168   // If low bits are zero in either operand, output low known-0 bits.
00169   // Also compute a conserative estimate for high known-0 bits.
00170   // More trickiness is possible, but this is sufficient for the
00171   // interesting case of alignment computation.
00172   KnownOne.clearAllBits();
00173   unsigned TrailZ = KnownZero.countTrailingOnes() +
00174                     KnownZero2.countTrailingOnes();
00175   unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
00176                              KnownZero2.countLeadingOnes(),
00177                              BitWidth) - BitWidth;
00178 
00179   TrailZ = std::min(TrailZ, BitWidth);
00180   LeadZ = std::min(LeadZ, BitWidth);
00181   KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
00182               APInt::getHighBitsSet(BitWidth, LeadZ);
00183 
00184   // Only make use of no-wrap flags if we failed to compute the sign bit
00185   // directly.  This matters if the multiplication always overflows, in
00186   // which case we prefer to follow the result of the direct computation,
00187   // though as the program is invoking undefined behaviour we can choose
00188   // whatever we like here.
00189   if (isKnownNonNegative && !KnownOne.isNegative())
00190     KnownZero.setBit(BitWidth - 1);
00191   else if (isKnownNegative && !KnownZero.isNegative())
00192     KnownOne.setBit(BitWidth - 1);
00193 }
00194 
00195 void llvm::computeMaskedBitsLoad(const MDNode &Ranges, APInt &KnownZero) {
00196   unsigned BitWidth = KnownZero.getBitWidth();
00197   unsigned NumRanges = Ranges.getNumOperands() / 2;
00198   assert(NumRanges >= 1);
00199 
00200   // Use the high end of the ranges to find leading zeros.
00201   unsigned MinLeadingZeros = BitWidth;
00202   for (unsigned i = 0; i < NumRanges; ++i) {
00203     ConstantInt *Lower = cast<ConstantInt>(Ranges.getOperand(2*i + 0));
00204     ConstantInt *Upper = cast<ConstantInt>(Ranges.getOperand(2*i + 1));
00205     ConstantRange Range(Lower->getValue(), Upper->getValue());
00206     if (Range.isWrappedSet())
00207       MinLeadingZeros = 0; // -1 has no zeros
00208     unsigned LeadingZeros = (Upper->getValue() - 1).countLeadingZeros();
00209     MinLeadingZeros = std::min(LeadingZeros, MinLeadingZeros);
00210   }
00211 
00212   KnownZero = APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
00213 }
00214 /// ComputeMaskedBits - Determine which of the bits are known to be either zero
00215 /// or one and return them in the KnownZero/KnownOne bit sets.
00216 ///
00217 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
00218 /// we cannot optimize based on the assumption that it is zero without changing
00219 /// it to be an explicit zero.  If we don't change it to zero, other code could
00220 /// optimized based on the contradictory assumption that it is non-zero.
00221 /// Because instcombine aggressively folds operations with undef args anyway,
00222 /// this won't lose us code quality.
00223 ///
00224 /// This function is defined on values with integer type, values with pointer
00225 /// type (but only if TD is non-null), and vectors of integers.  In the case
00226 /// where V is a vector, known zero, and known one values are the
00227 /// same width as the vector element, and the bit is set only if it is true
00228 /// for all of the elements in the vector.
00229 void llvm::ComputeMaskedBits(Value *V, APInt &KnownZero, APInt &KnownOne,
00230                              const DataLayout *TD, unsigned Depth) {
00231   assert(V && "No Value?");
00232   assert(Depth <= MaxDepth && "Limit Search Depth");
00233   unsigned BitWidth = KnownZero.getBitWidth();
00234 
00235   assert((V->getType()->isIntOrIntVectorTy() ||
00236           V->getType()->getScalarType()->isPointerTy()) &&
00237          "Not integer or pointer type!");
00238   assert((!TD ||
00239           TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
00240          (!V->getType()->isIntOrIntVectorTy() ||
00241           V->getType()->getScalarSizeInBits() == BitWidth) &&
00242          KnownZero.getBitWidth() == BitWidth &&
00243          KnownOne.getBitWidth() == BitWidth &&
00244          "V, Mask, KnownOne and KnownZero should have same BitWidth");
00245 
00246   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00247     // We know all of the bits for a constant!
00248     KnownOne = CI->getValue();
00249     KnownZero = ~KnownOne;
00250     return;
00251   }
00252   // Null and aggregate-zero are all-zeros.
00253   if (isa<ConstantPointerNull>(V) ||
00254       isa<ConstantAggregateZero>(V)) {
00255     KnownOne.clearAllBits();
00256     KnownZero = APInt::getAllOnesValue(BitWidth);
00257     return;
00258   }
00259   // Handle a constant vector by taking the intersection of the known bits of
00260   // each element.  There is no real need to handle ConstantVector here, because
00261   // we don't handle undef in any particularly useful way.
00262   if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
00263     // We know that CDS must be a vector of integers. Take the intersection of
00264     // each element.
00265     KnownZero.setAllBits(); KnownOne.setAllBits();
00266     APInt Elt(KnownZero.getBitWidth(), 0);
00267     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
00268       Elt = CDS->getElementAsInteger(i);
00269       KnownZero &= ~Elt;
00270       KnownOne &= Elt;
00271     }
00272     return;
00273   }
00274 
00275   // The address of an aligned GlobalValue has trailing zeros.
00276   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
00277     unsigned Align = GV->getAlignment();
00278     if (Align == 0 && TD) {
00279       if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
00280         Type *ObjectType = GVar->getType()->getElementType();
00281         if (ObjectType->isSized()) {
00282           // If the object is defined in the current Module, we'll be giving
00283           // it the preferred alignment. Otherwise, we have to assume that it
00284           // may only have the minimum ABI alignment.
00285           if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
00286             Align = TD->getPreferredAlignment(GVar);
00287           else
00288             Align = TD->getABITypeAlignment(ObjectType);
00289         }
00290       }
00291     }
00292     if (Align > 0)
00293       KnownZero = APInt::getLowBitsSet(BitWidth,
00294                                        countTrailingZeros(Align));
00295     else
00296       KnownZero.clearAllBits();
00297     KnownOne.clearAllBits();
00298     return;
00299   }
00300   // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
00301   // the bits of its aliasee.
00302   if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
00303     if (GA->mayBeOverridden()) {
00304       KnownZero.clearAllBits(); KnownOne.clearAllBits();
00305     } else {
00306       ComputeMaskedBits(GA->getAliasee(), KnownZero, KnownOne, TD, Depth+1);
00307     }
00308     return;
00309   }
00310 
00311   if (Argument *A = dyn_cast<Argument>(V)) {
00312     unsigned Align = 0;
00313 
00314     if (A->hasByValOrInAllocaAttr()) {
00315       // Get alignment information off byval/inalloca arguments if specified in
00316       // the IR.
00317       Align = A->getParamAlignment();
00318     } else if (TD && A->hasStructRetAttr()) {
00319       // An sret parameter has at least the ABI alignment of the return type.
00320       Type *EltTy = cast<PointerType>(A->getType())->getElementType();
00321       if (EltTy->isSized())
00322         Align = TD->getABITypeAlignment(EltTy);
00323     }
00324 
00325     if (Align)
00326       KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
00327     return;
00328   }
00329 
00330   // Start out not knowing anything.
00331   KnownZero.clearAllBits(); KnownOne.clearAllBits();
00332 
00333   if (Depth == MaxDepth)
00334     return;  // Limit search depth.
00335 
00336   Operator *I = dyn_cast<Operator>(V);
00337   if (!I) return;
00338 
00339   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
00340   switch (I->getOpcode()) {
00341   default: break;
00342   case Instruction::Load:
00343     if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
00344       computeMaskedBitsLoad(*MD, KnownZero);
00345     return;
00346   case Instruction::And: {
00347     // If either the LHS or the RHS are Zero, the result is zero.
00348     ComputeMaskedBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1);
00349     ComputeMaskedBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1);
00350     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00351     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
00352 
00353     // Output known-1 bits are only known if set in both the LHS & RHS.
00354     KnownOne &= KnownOne2;
00355     // Output known-0 are known to be clear if zero in either the LHS | RHS.
00356     KnownZero |= KnownZero2;
00357     return;
00358   }
00359   case Instruction::Or: {
00360     ComputeMaskedBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1);
00361     ComputeMaskedBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1);
00362     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00363     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
00364 
00365     // Output known-0 bits are only known if clear in both the LHS & RHS.
00366     KnownZero &= KnownZero2;
00367     // Output known-1 are known to be set if set in either the LHS | RHS.
00368     KnownOne |= KnownOne2;
00369     return;
00370   }
00371   case Instruction::Xor: {
00372     ComputeMaskedBits(I->getOperand(1), KnownZero, KnownOne, TD, Depth+1);
00373     ComputeMaskedBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1);
00374     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00375     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
00376 
00377     // Output known-0 bits are known if clear or set in both the LHS & RHS.
00378     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
00379     // Output known-1 are known to be set if set in only one of the LHS, RHS.
00380     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
00381     KnownZero = KnownZeroOut;
00382     return;
00383   }
00384   case Instruction::Mul: {
00385     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
00386     ComputeMaskedBitsMul(I->getOperand(0), I->getOperand(1), NSW,
00387                          KnownZero, KnownOne, KnownZero2, KnownOne2, TD, Depth);
00388     break;
00389   }
00390   case Instruction::UDiv: {
00391     // For the purposes of computing leading zeros we can conservatively
00392     // treat a udiv as a logical right shift by the power of 2 known to
00393     // be less than the denominator.
00394     ComputeMaskedBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1);
00395     unsigned LeadZ = KnownZero2.countLeadingOnes();
00396 
00397     KnownOne2.clearAllBits();
00398     KnownZero2.clearAllBits();
00399     ComputeMaskedBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1);
00400     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
00401     if (RHSUnknownLeadingOnes != BitWidth)
00402       LeadZ = std::min(BitWidth,
00403                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
00404 
00405     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
00406     return;
00407   }
00408   case Instruction::Select:
00409     ComputeMaskedBits(I->getOperand(2), KnownZero, KnownOne, TD, Depth+1);
00410     ComputeMaskedBits(I->getOperand(1), KnownZero2, KnownOne2, TD,
00411                       Depth+1);
00412     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00413     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
00414 
00415     // Only known if known in both the LHS and RHS.
00416     KnownOne &= KnownOne2;
00417     KnownZero &= KnownZero2;
00418     return;
00419   case Instruction::FPTrunc:
00420   case Instruction::FPExt:
00421   case Instruction::FPToUI:
00422   case Instruction::FPToSI:
00423   case Instruction::SIToFP:
00424   case Instruction::UIToFP:
00425     return; // Can't work with floating point.
00426   case Instruction::PtrToInt:
00427   case Instruction::IntToPtr:
00428     // We can't handle these if we don't know the pointer size.
00429     if (!TD) return;
00430     // FALL THROUGH and handle them the same as zext/trunc.
00431   case Instruction::ZExt:
00432   case Instruction::Trunc: {
00433     Type *SrcTy = I->getOperand(0)->getType();
00434 
00435     unsigned SrcBitWidth;
00436     // Note that we handle pointer operands here because of inttoptr/ptrtoint
00437     // which fall through here.
00438     if(TD) {
00439       SrcBitWidth = TD->getTypeSizeInBits(SrcTy->getScalarType());
00440     } else {
00441       SrcBitWidth = SrcTy->getScalarSizeInBits();
00442       if (!SrcBitWidth) return;
00443     }
00444 
00445     assert(SrcBitWidth && "SrcBitWidth can't be zero");
00446     KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
00447     KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
00448     ComputeMaskedBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1);
00449     KnownZero = KnownZero.zextOrTrunc(BitWidth);
00450     KnownOne = KnownOne.zextOrTrunc(BitWidth);
00451     // Any top bits are known to be zero.
00452     if (BitWidth > SrcBitWidth)
00453       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
00454     return;
00455   }
00456   case Instruction::BitCast: {
00457     Type *SrcTy = I->getOperand(0)->getType();
00458     if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
00459         // TODO: For now, not handling conversions like:
00460         // (bitcast i64 %x to <2 x i32>)
00461         !I->getType()->isVectorTy()) {
00462       ComputeMaskedBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1);
00463       return;
00464     }
00465     break;
00466   }
00467   case Instruction::SExt: {
00468     // Compute the bits in the result that are not present in the input.
00469     unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
00470 
00471     KnownZero = KnownZero.trunc(SrcBitWidth);
00472     KnownOne = KnownOne.trunc(SrcBitWidth);
00473     ComputeMaskedBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1);
00474     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00475     KnownZero = KnownZero.zext(BitWidth);
00476     KnownOne = KnownOne.zext(BitWidth);
00477 
00478     // If the sign bit of the input is known set or clear, then we know the
00479     // top bits of the result.
00480     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
00481       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
00482     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
00483       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
00484     return;
00485   }
00486   case Instruction::Shl:
00487     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
00488     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
00489       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
00490       ComputeMaskedBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1);
00491       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00492       KnownZero <<= ShiftAmt;
00493       KnownOne  <<= ShiftAmt;
00494       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
00495       return;
00496     }
00497     break;
00498   case Instruction::LShr:
00499     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
00500     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
00501       // Compute the new bits that are at the top now.
00502       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
00503 
00504       // Unsigned shift right.
00505       ComputeMaskedBits(I->getOperand(0), KnownZero,KnownOne, TD, Depth+1);
00506       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00507       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
00508       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
00509       // high bits known zero.
00510       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
00511       return;
00512     }
00513     break;
00514   case Instruction::AShr:
00515     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
00516     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
00517       // Compute the new bits that are at the top now.
00518       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
00519 
00520       // Signed shift right.
00521       ComputeMaskedBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1);
00522       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00523       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
00524       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
00525 
00526       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
00527       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
00528         KnownZero |= HighBits;
00529       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
00530         KnownOne |= HighBits;
00531       return;
00532     }
00533     break;
00534   case Instruction::Sub: {
00535     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
00536     ComputeMaskedBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
00537                             KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
00538                             Depth);
00539     break;
00540   }
00541   case Instruction::Add: {
00542     bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
00543     ComputeMaskedBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
00544                             KnownZero, KnownOne, KnownZero2, KnownOne2, TD,
00545                             Depth);
00546     break;
00547   }
00548   case Instruction::SRem:
00549     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
00550       APInt RA = Rem->getValue().abs();
00551       if (RA.isPowerOf2()) {
00552         APInt LowBits = RA - 1;
00553         ComputeMaskedBits(I->getOperand(0), KnownZero2, KnownOne2, TD, Depth+1);
00554 
00555         // The low bits of the first operand are unchanged by the srem.
00556         KnownZero = KnownZero2 & LowBits;
00557         KnownOne = KnownOne2 & LowBits;
00558 
00559         // If the first operand is non-negative or has all low bits zero, then
00560         // the upper bits are all zero.
00561         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
00562           KnownZero |= ~LowBits;
00563 
00564         // If the first operand is negative and not all low bits are zero, then
00565         // the upper bits are all one.
00566         if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
00567           KnownOne |= ~LowBits;
00568 
00569         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00570       }
00571     }
00572 
00573     // The sign bit is the LHS's sign bit, except when the result of the
00574     // remainder is zero.
00575     if (KnownZero.isNonNegative()) {
00576       APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
00577       ComputeMaskedBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, TD,
00578                         Depth+1);
00579       // If it's known zero, our sign bit is also zero.
00580       if (LHSKnownZero.isNegative())
00581         KnownZero.setBit(BitWidth - 1);
00582     }
00583 
00584     break;
00585   case Instruction::URem: {
00586     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
00587       APInt RA = Rem->getValue();
00588       if (RA.isPowerOf2()) {
00589         APInt LowBits = (RA - 1);
00590         ComputeMaskedBits(I->getOperand(0), KnownZero, KnownOne, TD,
00591                           Depth+1);
00592         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
00593         KnownZero |= ~LowBits;
00594         KnownOne &= LowBits;
00595         break;
00596       }
00597     }
00598 
00599     // Since the result is less than or equal to either operand, any leading
00600     // zero bits in either operand must also exist in the result.
00601     ComputeMaskedBits(I->getOperand(0), KnownZero, KnownOne, TD, Depth+1);
00602     ComputeMaskedBits(I->getOperand(1), KnownZero2, KnownOne2, TD, Depth+1);
00603 
00604     unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
00605                                 KnownZero2.countLeadingOnes());
00606     KnownOne.clearAllBits();
00607     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
00608     break;
00609   }
00610 
00611   case Instruction::Alloca: {
00612     AllocaInst *AI = cast<AllocaInst>(V);
00613     unsigned Align = AI->getAlignment();
00614     if (Align == 0 && TD)
00615       Align = TD->getABITypeAlignment(AI->getType()->getElementType());
00616 
00617     if (Align > 0)
00618       KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
00619     break;
00620   }
00621   case Instruction::GetElementPtr: {
00622     // Analyze all of the subscripts of this getelementptr instruction
00623     // to determine if we can prove known low zero bits.
00624     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
00625     ComputeMaskedBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, TD,
00626                       Depth+1);
00627     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
00628 
00629     gep_type_iterator GTI = gep_type_begin(I);
00630     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
00631       Value *Index = I->getOperand(i);
00632       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
00633         // Handle struct member offset arithmetic.
00634         if (!TD)
00635           return;
00636 
00637         // Handle case when index is vector zeroinitializer
00638         Constant *CIndex = cast<Constant>(Index);
00639         if (CIndex->isZeroValue())
00640           continue;
00641 
00642         if (CIndex->getType()->isVectorTy())
00643           Index = CIndex->getSplatValue();
00644 
00645         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
00646         const StructLayout *SL = TD->getStructLayout(STy);
00647         uint64_t Offset = SL->getElementOffset(Idx);
00648         TrailZ = std::min<unsigned>(TrailZ,
00649                                     countTrailingZeros(Offset));
00650       } else {
00651         // Handle array index arithmetic.
00652         Type *IndexedTy = GTI.getIndexedType();
00653         if (!IndexedTy->isSized()) return;
00654         unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
00655         uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1;
00656         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
00657         ComputeMaskedBits(Index, LocalKnownZero, LocalKnownOne, TD, Depth+1);
00658         TrailZ = std::min(TrailZ,
00659                           unsigned(countTrailingZeros(TypeSize) +
00660                                    LocalKnownZero.countTrailingOnes()));
00661       }
00662     }
00663 
00664     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
00665     break;
00666   }
00667   case Instruction::PHI: {
00668     PHINode *P = cast<PHINode>(I);
00669     // Handle the case of a simple two-predecessor recurrence PHI.
00670     // There's a lot more that could theoretically be done here, but
00671     // this is sufficient to catch some interesting cases.
00672     if (P->getNumIncomingValues() == 2) {
00673       for (unsigned i = 0; i != 2; ++i) {
00674         Value *L = P->getIncomingValue(i);
00675         Value *R = P->getIncomingValue(!i);
00676         Operator *LU = dyn_cast<Operator>(L);
00677         if (!LU)
00678           continue;
00679         unsigned Opcode = LU->getOpcode();
00680         // Check for operations that have the property that if
00681         // both their operands have low zero bits, the result
00682         // will have low zero bits.
00683         if (Opcode == Instruction::Add ||
00684             Opcode == Instruction::Sub ||
00685             Opcode == Instruction::And ||
00686             Opcode == Instruction::Or ||
00687             Opcode == Instruction::Mul) {
00688           Value *LL = LU->getOperand(0);
00689           Value *LR = LU->getOperand(1);
00690           // Find a recurrence.
00691           if (LL == I)
00692             L = LR;
00693           else if (LR == I)
00694             L = LL;
00695           else
00696             break;
00697           // Ok, we have a PHI of the form L op= R. Check for low
00698           // zero bits.
00699           ComputeMaskedBits(R, KnownZero2, KnownOne2, TD, Depth+1);
00700 
00701           // We need to take the minimum number of known bits
00702           APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
00703           ComputeMaskedBits(L, KnownZero3, KnownOne3, TD, Depth+1);
00704 
00705           KnownZero = APInt::getLowBitsSet(BitWidth,
00706                                            std::min(KnownZero2.countTrailingOnes(),
00707                                                     KnownZero3.countTrailingOnes()));
00708           break;
00709         }
00710       }
00711     }
00712 
00713     // Unreachable blocks may have zero-operand PHI nodes.
00714     if (P->getNumIncomingValues() == 0)
00715       return;
00716 
00717     // Otherwise take the unions of the known bit sets of the operands,
00718     // taking conservative care to avoid excessive recursion.
00719     if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
00720       // Skip if every incoming value references to ourself.
00721       if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
00722         break;
00723 
00724       KnownZero = APInt::getAllOnesValue(BitWidth);
00725       KnownOne = APInt::getAllOnesValue(BitWidth);
00726       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
00727         // Skip direct self references.
00728         if (P->getIncomingValue(i) == P) continue;
00729 
00730         KnownZero2 = APInt(BitWidth, 0);
00731         KnownOne2 = APInt(BitWidth, 0);
00732         // Recurse, but cap the recursion to one level, because we don't
00733         // want to waste time spinning around in loops.
00734         ComputeMaskedBits(P->getIncomingValue(i), KnownZero2, KnownOne2, TD,
00735                           MaxDepth-1);
00736         KnownZero &= KnownZero2;
00737         KnownOne &= KnownOne2;
00738         // If all bits have been ruled out, there's no need to check
00739         // more operands.
00740         if (!KnownZero && !KnownOne)
00741           break;
00742       }
00743     }
00744     break;
00745   }
00746   case Instruction::Call:
00747     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00748       switch (II->getIntrinsicID()) {
00749       default: break;
00750       case Intrinsic::ctlz:
00751       case Intrinsic::cttz: {
00752         unsigned LowBits = Log2_32(BitWidth)+1;
00753         // If this call is undefined for 0, the result will be less than 2^n.
00754         if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
00755           LowBits -= 1;
00756         KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
00757         break;
00758       }
00759       case Intrinsic::ctpop: {
00760         unsigned LowBits = Log2_32(BitWidth)+1;
00761         KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
00762         break;
00763       }
00764       case Intrinsic::x86_sse42_crc32_64_64:
00765         KnownZero = APInt::getHighBitsSet(64, 32);
00766         break;
00767       }
00768     }
00769     break;
00770   case Instruction::ExtractValue:
00771     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
00772       ExtractValueInst *EVI = cast<ExtractValueInst>(I);
00773       if (EVI->getNumIndices() != 1) break;
00774       if (EVI->getIndices()[0] == 0) {
00775         switch (II->getIntrinsicID()) {
00776         default: break;
00777         case Intrinsic::uadd_with_overflow:
00778         case Intrinsic::sadd_with_overflow:
00779           ComputeMaskedBitsAddSub(true, II->getArgOperand(0),
00780                                   II->getArgOperand(1), false, KnownZero,
00781                                   KnownOne, KnownZero2, KnownOne2, TD, Depth);
00782           break;
00783         case Intrinsic::usub_with_overflow:
00784         case Intrinsic::ssub_with_overflow:
00785           ComputeMaskedBitsAddSub(false, II->getArgOperand(0),
00786                                   II->getArgOperand(1), false, KnownZero,
00787                                   KnownOne, KnownZero2, KnownOne2, TD, Depth);
00788           break;
00789         case Intrinsic::umul_with_overflow:
00790         case Intrinsic::smul_with_overflow:
00791           ComputeMaskedBitsMul(II->getArgOperand(0), II->getArgOperand(1),
00792                                false, KnownZero, KnownOne,
00793                                KnownZero2, KnownOne2, TD, Depth);
00794           break;
00795         }
00796       }
00797     }
00798   }
00799 }
00800 
00801 /// ComputeSignBit - Determine whether the sign bit is known to be zero or
00802 /// one.  Convenience wrapper around ComputeMaskedBits.
00803 void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
00804                           const DataLayout *TD, unsigned Depth) {
00805   unsigned BitWidth = getBitWidth(V->getType(), TD);
00806   if (!BitWidth) {
00807     KnownZero = false;
00808     KnownOne = false;
00809     return;
00810   }
00811   APInt ZeroBits(BitWidth, 0);
00812   APInt OneBits(BitWidth, 0);
00813   ComputeMaskedBits(V, ZeroBits, OneBits, TD, Depth);
00814   KnownOne = OneBits[BitWidth - 1];
00815   KnownZero = ZeroBits[BitWidth - 1];
00816 }
00817 
00818 /// isKnownToBeAPowerOfTwo - Return true if the given value is known to have exactly one
00819 /// bit set when defined. For vectors return true if every element is known to
00820 /// be a power of two when defined.  Supports values with integer or pointer
00821 /// types and vectors of integers.
00822 bool llvm::isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth) {
00823   if (Constant *C = dyn_cast<Constant>(V)) {
00824     if (C->isNullValue())
00825       return OrZero;
00826     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
00827       return CI->getValue().isPowerOf2();
00828     // TODO: Handle vector constants.
00829   }
00830 
00831   // 1 << X is clearly a power of two if the one is not shifted off the end.  If
00832   // it is shifted off the end then the result is undefined.
00833   if (match(V, m_Shl(m_One(), m_Value())))
00834     return true;
00835 
00836   // (signbit) >>l X is clearly a power of two if the one is not shifted off the
00837   // bottom.  If it is shifted off the bottom then the result is undefined.
00838   if (match(V, m_LShr(m_SignBit(), m_Value())))
00839     return true;
00840 
00841   // The remaining tests are all recursive, so bail out if we hit the limit.
00842   if (Depth++ == MaxDepth)
00843     return false;
00844 
00845   Value *X = nullptr, *Y = nullptr;
00846   // A shift of a power of two is a power of two or zero.
00847   if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
00848                  match(V, m_Shr(m_Value(X), m_Value()))))
00849     return isKnownToBeAPowerOfTwo(X, /*OrZero*/true, Depth);
00850 
00851   if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
00852     return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth);
00853 
00854   if (SelectInst *SI = dyn_cast<SelectInst>(V))
00855     return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth) &&
00856       isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth);
00857 
00858   if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
00859     // A power of two and'd with anything is a power of two or zero.
00860     if (isKnownToBeAPowerOfTwo(X, /*OrZero*/true, Depth) ||
00861         isKnownToBeAPowerOfTwo(Y, /*OrZero*/true, Depth))
00862       return true;
00863     // X & (-X) is always a power of two or zero.
00864     if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
00865       return true;
00866     return false;
00867   }
00868 
00869   // Adding a power-of-two or zero to the same power-of-two or zero yields
00870   // either the original power-of-two, a larger power-of-two or zero.
00871   if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
00872     OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
00873     if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
00874       if (match(X, m_And(m_Specific(Y), m_Value())) ||
00875           match(X, m_And(m_Value(), m_Specific(Y))))
00876         if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth))
00877           return true;
00878       if (match(Y, m_And(m_Specific(X), m_Value())) ||
00879           match(Y, m_And(m_Value(), m_Specific(X))))
00880         if (isKnownToBeAPowerOfTwo(X, OrZero, Depth))
00881           return true;
00882 
00883       unsigned BitWidth = V->getType()->getScalarSizeInBits();
00884       APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
00885       ComputeMaskedBits(X, LHSZeroBits, LHSOneBits, nullptr, Depth);
00886 
00887       APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
00888       ComputeMaskedBits(Y, RHSZeroBits, RHSOneBits, nullptr, Depth);
00889       // If i8 V is a power of two or zero:
00890       //  ZeroBits: 1 1 1 0 1 1 1 1
00891       // ~ZeroBits: 0 0 0 1 0 0 0 0
00892       if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
00893         // If OrZero isn't set, we cannot give back a zero result.
00894         // Make sure either the LHS or RHS has a bit set.
00895         if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
00896           return true;
00897     }
00898   }
00899 
00900   // An exact divide or right shift can only shift off zero bits, so the result
00901   // is a power of two only if the first operand is a power of two and not
00902   // copying a sign bit (sdiv int_min, 2).
00903   if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
00904       match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
00905     return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero, Depth);
00906   }
00907 
00908   return false;
00909 }
00910 
00911 /// \brief Test whether a GEP's result is known to be non-null.
00912 ///
00913 /// Uses properties inherent in a GEP to try to determine whether it is known
00914 /// to be non-null.
00915 ///
00916 /// Currently this routine does not support vector GEPs.
00917 static bool isGEPKnownNonNull(GEPOperator *GEP, const DataLayout *DL,
00918                               unsigned Depth) {
00919   if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
00920     return false;
00921 
00922   // FIXME: Support vector-GEPs.
00923   assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
00924 
00925   // If the base pointer is non-null, we cannot walk to a null address with an
00926   // inbounds GEP in address space zero.
00927   if (isKnownNonZero(GEP->getPointerOperand(), DL, Depth))
00928     return true;
00929 
00930   // Past this, if we don't have DataLayout, we can't do much.
00931   if (!DL)
00932     return false;
00933 
00934   // Walk the GEP operands and see if any operand introduces a non-zero offset.
00935   // If so, then the GEP cannot produce a null pointer, as doing so would
00936   // inherently violate the inbounds contract within address space zero.
00937   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
00938        GTI != GTE; ++GTI) {
00939     // Struct types are easy -- they must always be indexed by a constant.
00940     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
00941       ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
00942       unsigned ElementIdx = OpC->getZExtValue();
00943       const StructLayout *SL = DL->getStructLayout(STy);
00944       uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
00945       if (ElementOffset > 0)
00946         return true;
00947       continue;
00948     }
00949 
00950     // If we have a zero-sized type, the index doesn't matter. Keep looping.
00951     if (DL->getTypeAllocSize(GTI.getIndexedType()) == 0)
00952       continue;
00953 
00954     // Fast path the constant operand case both for efficiency and so we don't
00955     // increment Depth when just zipping down an all-constant GEP.
00956     if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
00957       if (!OpC->isZero())
00958         return true;
00959       continue;
00960     }
00961 
00962     // We post-increment Depth here because while isKnownNonZero increments it
00963     // as well, when we pop back up that increment won't persist. We don't want
00964     // to recurse 10k times just because we have 10k GEP operands. We don't
00965     // bail completely out because we want to handle constant GEPs regardless
00966     // of depth.
00967     if (Depth++ >= MaxDepth)
00968       continue;
00969 
00970     if (isKnownNonZero(GTI.getOperand(), DL, Depth))
00971       return true;
00972   }
00973 
00974   return false;
00975 }
00976 
00977 /// isKnownNonZero - Return true if the given value is known to be non-zero
00978 /// when defined.  For vectors return true if every element is known to be
00979 /// non-zero when defined.  Supports values with integer or pointer type and
00980 /// vectors of integers.
00981 bool llvm::isKnownNonZero(Value *V, const DataLayout *TD, unsigned Depth) {
00982   if (Constant *C = dyn_cast<Constant>(V)) {
00983     if (C->isNullValue())
00984       return false;
00985     if (isa<ConstantInt>(C))
00986       // Must be non-zero due to null test above.
00987       return true;
00988     // TODO: Handle vectors
00989     return false;
00990   }
00991 
00992   // The remaining tests are all recursive, so bail out if we hit the limit.
00993   if (Depth++ >= MaxDepth)
00994     return false;
00995 
00996   // Check for pointer simplifications.
00997   if (V->getType()->isPointerTy()) {
00998     if (isKnownNonNull(V))
00999       return true; 
01000     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
01001       if (isGEPKnownNonNull(GEP, TD, Depth))
01002         return true;
01003   }
01004 
01005   unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), TD);
01006 
01007   // X | Y != 0 if X != 0 or Y != 0.
01008   Value *X = nullptr, *Y = nullptr;
01009   if (match(V, m_Or(m_Value(X), m_Value(Y))))
01010     return isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth);
01011 
01012   // ext X != 0 if X != 0.
01013   if (isa<SExtInst>(V) || isa<ZExtInst>(V))
01014     return isKnownNonZero(cast<Instruction>(V)->getOperand(0), TD, Depth);
01015 
01016   // shl X, Y != 0 if X is odd.  Note that the value of the shift is undefined
01017   // if the lowest bit is shifted off the end.
01018   if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
01019     // shl nuw can't remove any non-zero bits.
01020     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
01021     if (BO->hasNoUnsignedWrap())
01022       return isKnownNonZero(X, TD, Depth);
01023 
01024     APInt KnownZero(BitWidth, 0);
01025     APInt KnownOne(BitWidth, 0);
01026     ComputeMaskedBits(X, KnownZero, KnownOne, TD, Depth);
01027     if (KnownOne[0])
01028       return true;
01029   }
01030   // shr X, Y != 0 if X is negative.  Note that the value of the shift is not
01031   // defined if the sign bit is shifted off the end.
01032   else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
01033     // shr exact can only shift out zero bits.
01034     PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
01035     if (BO->isExact())
01036       return isKnownNonZero(X, TD, Depth);
01037 
01038     bool XKnownNonNegative, XKnownNegative;
01039     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
01040     if (XKnownNegative)
01041       return true;
01042   }
01043   // div exact can only produce a zero if the dividend is zero.
01044   else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
01045     return isKnownNonZero(X, TD, Depth);
01046   }
01047   // X + Y.
01048   else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
01049     bool XKnownNonNegative, XKnownNegative;
01050     bool YKnownNonNegative, YKnownNegative;
01051     ComputeSignBit(X, XKnownNonNegative, XKnownNegative, TD, Depth);
01052     ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, TD, Depth);
01053 
01054     // If X and Y are both non-negative (as signed values) then their sum is not
01055     // zero unless both X and Y are zero.
01056     if (XKnownNonNegative && YKnownNonNegative)
01057       if (isKnownNonZero(X, TD, Depth) || isKnownNonZero(Y, TD, Depth))
01058         return true;
01059 
01060     // If X and Y are both negative (as signed values) then their sum is not
01061     // zero unless both X and Y equal INT_MIN.
01062     if (BitWidth && XKnownNegative && YKnownNegative) {
01063       APInt KnownZero(BitWidth, 0);
01064       APInt KnownOne(BitWidth, 0);
01065       APInt Mask = APInt::getSignedMaxValue(BitWidth);
01066       // The sign bit of X is set.  If some other bit is set then X is not equal
01067       // to INT_MIN.
01068       ComputeMaskedBits(X, KnownZero, KnownOne, TD, Depth);
01069       if ((KnownOne & Mask) != 0)
01070         return true;
01071       // The sign bit of Y is set.  If some other bit is set then Y is not equal
01072       // to INT_MIN.
01073       ComputeMaskedBits(Y, KnownZero, KnownOne, TD, Depth);
01074       if ((KnownOne & Mask) != 0)
01075         return true;
01076     }
01077 
01078     // The sum of a non-negative number and a power of two is not zero.
01079     if (XKnownNonNegative && isKnownToBeAPowerOfTwo(Y, /*OrZero*/false, Depth))
01080       return true;
01081     if (YKnownNonNegative && isKnownToBeAPowerOfTwo(X, /*OrZero*/false, Depth))
01082       return true;
01083   }
01084   // X * Y.
01085   else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
01086     OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
01087     // If X and Y are non-zero then so is X * Y as long as the multiplication
01088     // does not overflow.
01089     if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
01090         isKnownNonZero(X, TD, Depth) && isKnownNonZero(Y, TD, Depth))
01091       return true;
01092   }
01093   // (C ? X : Y) != 0 if X != 0 and Y != 0.
01094   else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
01095     if (isKnownNonZero(SI->getTrueValue(), TD, Depth) &&
01096         isKnownNonZero(SI->getFalseValue(), TD, Depth))
01097       return true;
01098   }
01099 
01100   if (!BitWidth) return false;
01101   APInt KnownZero(BitWidth, 0);
01102   APInt KnownOne(BitWidth, 0);
01103   ComputeMaskedBits(V, KnownZero, KnownOne, TD, Depth);
01104   return KnownOne != 0;
01105 }
01106 
01107 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
01108 /// this predicate to simplify operations downstream.  Mask is known to be zero
01109 /// for bits that V cannot have.
01110 ///
01111 /// This function is defined on values with integer type, values with pointer
01112 /// type (but only if TD is non-null), and vectors of integers.  In the case
01113 /// where V is a vector, the mask, known zero, and known one values are the
01114 /// same width as the vector element, and the bit is set only if it is true
01115 /// for all of the elements in the vector.
01116 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask,
01117                              const DataLayout *TD, unsigned Depth) {
01118   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
01119   ComputeMaskedBits(V, KnownZero, KnownOne, TD, Depth);
01120   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
01121   return (KnownZero & Mask) == Mask;
01122 }
01123 
01124 
01125 
01126 /// ComputeNumSignBits - Return the number of times the sign bit of the
01127 /// register is replicated into the other bits.  We know that at least 1 bit
01128 /// is always equal to the sign bit (itself), but other cases can give us
01129 /// information.  For example, immediately after an "ashr X, 2", we know that
01130 /// the top 3 bits are all equal to each other, so we return 3.
01131 ///
01132 /// 'Op' must have a scalar integer type.
01133 ///
01134 unsigned llvm::ComputeNumSignBits(Value *V, const DataLayout *TD,
01135                                   unsigned Depth) {
01136   assert((TD || V->getType()->isIntOrIntVectorTy()) &&
01137          "ComputeNumSignBits requires a DataLayout object to operate "
01138          "on non-integer values!");
01139   Type *Ty = V->getType();
01140   unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) :
01141                          Ty->getScalarSizeInBits();
01142   unsigned Tmp, Tmp2;
01143   unsigned FirstAnswer = 1;
01144 
01145   // Note that ConstantInt is handled by the general ComputeMaskedBits case
01146   // below.
01147 
01148   if (Depth == 6)
01149     return 1;  // Limit search depth.
01150 
01151   Operator *U = dyn_cast<Operator>(V);
01152   switch (Operator::getOpcode(V)) {
01153   default: break;
01154   case Instruction::SExt:
01155     Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
01156     return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp;
01157 
01158   case Instruction::AShr: {
01159     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
01160     // ashr X, C   -> adds C sign bits.  Vectors too.
01161     const APInt *ShAmt;
01162     if (match(U->getOperand(1), m_APInt(ShAmt))) {
01163       Tmp += ShAmt->getZExtValue();
01164       if (Tmp > TyBits) Tmp = TyBits;
01165     }
01166     return Tmp;
01167   }
01168   case Instruction::Shl: {
01169     const APInt *ShAmt;
01170     if (match(U->getOperand(1), m_APInt(ShAmt))) {
01171       // shl destroys sign bits.
01172       Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
01173       Tmp2 = ShAmt->getZExtValue();
01174       if (Tmp2 >= TyBits ||      // Bad shift.
01175           Tmp2 >= Tmp) break;    // Shifted all sign bits out.
01176       return Tmp - Tmp2;
01177     }
01178     break;
01179   }
01180   case Instruction::And:
01181   case Instruction::Or:
01182   case Instruction::Xor:    // NOT is handled here.
01183     // Logical binary ops preserve the number of sign bits at the worst.
01184     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
01185     if (Tmp != 1) {
01186       Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
01187       FirstAnswer = std::min(Tmp, Tmp2);
01188       // We computed what we know about the sign bits as our first
01189       // answer. Now proceed to the generic code that uses
01190       // ComputeMaskedBits, and pick whichever answer is better.
01191     }
01192     break;
01193 
01194   case Instruction::Select:
01195     Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
01196     if (Tmp == 1) return 1;  // Early out.
01197     Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1);
01198     return std::min(Tmp, Tmp2);
01199 
01200   case Instruction::Add:
01201     // Add can have at most one carry bit.  Thus we know that the output
01202     // is, at worst, one more bit than the inputs.
01203     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
01204     if (Tmp == 1) return 1;  // Early out.
01205 
01206     // Special case decrementing a value (ADD X, -1):
01207     if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1)))
01208       if (CRHS->isAllOnesValue()) {
01209         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
01210         ComputeMaskedBits(U->getOperand(0), KnownZero, KnownOne, TD, Depth+1);
01211 
01212         // If the input is known to be 0 or 1, the output is 0/-1, which is all
01213         // sign bits set.
01214         if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
01215           return TyBits;
01216 
01217         // If we are subtracting one from a positive number, there is no carry
01218         // out of the result.
01219         if (KnownZero.isNegative())
01220           return Tmp;
01221       }
01222 
01223     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
01224     if (Tmp2 == 1) return 1;
01225     return std::min(Tmp, Tmp2)-1;
01226 
01227   case Instruction::Sub:
01228     Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1);
01229     if (Tmp2 == 1) return 1;
01230 
01231     // Handle NEG.
01232     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
01233       if (CLHS->isNullValue()) {
01234         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
01235         ComputeMaskedBits(U->getOperand(1), KnownZero, KnownOne, TD, Depth+1);
01236         // If the input is known to be 0 or 1, the output is 0/-1, which is all
01237         // sign bits set.
01238         if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
01239           return TyBits;
01240 
01241         // If the input is known to be positive (the sign bit is known clear),
01242         // the output of the NEG has the same number of sign bits as the input.
01243         if (KnownZero.isNegative())
01244           return Tmp2;
01245 
01246         // Otherwise, we treat this like a SUB.
01247       }
01248 
01249     // Sub can have at most one carry bit.  Thus we know that the output
01250     // is, at worst, one more bit than the inputs.
01251     Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1);
01252     if (Tmp == 1) return 1;  // Early out.
01253     return std::min(Tmp, Tmp2)-1;
01254 
01255   case Instruction::PHI: {
01256     PHINode *PN = cast<PHINode>(U);
01257     // Don't analyze large in-degree PHIs.
01258     if (PN->getNumIncomingValues() > 4) break;
01259 
01260     // Take the minimum of all incoming values.  This can't infinitely loop
01261     // because of our depth threshold.
01262     Tmp = ComputeNumSignBits(PN->getIncomingValue(0), TD, Depth+1);
01263     for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
01264       if (Tmp == 1) return Tmp;
01265       Tmp = std::min(Tmp,
01266                      ComputeNumSignBits(PN->getIncomingValue(i), TD, Depth+1));
01267     }
01268     return Tmp;
01269   }
01270 
01271   case Instruction::Trunc:
01272     // FIXME: it's tricky to do anything useful for this, but it is an important
01273     // case for targets like X86.
01274     break;
01275   }
01276 
01277   // Finally, if we can prove that the top bits of the result are 0's or 1's,
01278   // use this information.
01279   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
01280   APInt Mask;
01281   ComputeMaskedBits(V, KnownZero, KnownOne, TD, Depth);
01282 
01283   if (KnownZero.isNegative()) {        // sign bit is 0
01284     Mask = KnownZero;
01285   } else if (KnownOne.isNegative()) {  // sign bit is 1;
01286     Mask = KnownOne;
01287   } else {
01288     // Nothing known.
01289     return FirstAnswer;
01290   }
01291 
01292   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
01293   // the number of identical bits in the top of the input value.
01294   Mask = ~Mask;
01295   Mask <<= Mask.getBitWidth()-TyBits;
01296   // Return # leading zeros.  We use 'min' here in case Val was zero before
01297   // shifting.  We don't want to return '64' as for an i32 "0".
01298   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
01299 }
01300 
01301 /// ComputeMultiple - This function computes the integer multiple of Base that
01302 /// equals V.  If successful, it returns true and returns the multiple in
01303 /// Multiple.  If unsuccessful, it returns false. It looks
01304 /// through SExt instructions only if LookThroughSExt is true.
01305 bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
01306                            bool LookThroughSExt, unsigned Depth) {
01307   const unsigned MaxDepth = 6;
01308 
01309   assert(V && "No Value?");
01310   assert(Depth <= MaxDepth && "Limit Search Depth");
01311   assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
01312 
01313   Type *T = V->getType();
01314 
01315   ConstantInt *CI = dyn_cast<ConstantInt>(V);
01316 
01317   if (Base == 0)
01318     return false;
01319 
01320   if (Base == 1) {
01321     Multiple = V;
01322     return true;
01323   }
01324 
01325   ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
01326   Constant *BaseVal = ConstantInt::get(T, Base);
01327   if (CO && CO == BaseVal) {
01328     // Multiple is 1.
01329     Multiple = ConstantInt::get(T, 1);
01330     return true;
01331   }
01332 
01333   if (CI && CI->getZExtValue() % Base == 0) {
01334     Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
01335     return true;
01336   }
01337 
01338   if (Depth == MaxDepth) return false;  // Limit search depth.
01339 
01340   Operator *I = dyn_cast<Operator>(V);
01341   if (!I) return false;
01342 
01343   switch (I->getOpcode()) {
01344   default: break;
01345   case Instruction::SExt:
01346     if (!LookThroughSExt) return false;
01347     // otherwise fall through to ZExt
01348   case Instruction::ZExt:
01349     return ComputeMultiple(I->getOperand(0), Base, Multiple,
01350                            LookThroughSExt, Depth+1);
01351   case Instruction::Shl:
01352   case Instruction::Mul: {
01353     Value *Op0 = I->getOperand(0);
01354     Value *Op1 = I->getOperand(1);
01355 
01356     if (I->getOpcode() == Instruction::Shl) {
01357       ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
01358       if (!Op1CI) return false;
01359       // Turn Op0 << Op1 into Op0 * 2^Op1
01360       APInt Op1Int = Op1CI->getValue();
01361       uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
01362       APInt API(Op1Int.getBitWidth(), 0);
01363       API.setBit(BitToSet);
01364       Op1 = ConstantInt::get(V->getContext(), API);
01365     }
01366 
01367     Value *Mul0 = nullptr;
01368     if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
01369       if (Constant *Op1C = dyn_cast<Constant>(Op1))
01370         if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
01371           if (Op1C->getType()->getPrimitiveSizeInBits() <
01372               MulC->getType()->getPrimitiveSizeInBits())
01373             Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
01374           if (Op1C->getType()->getPrimitiveSizeInBits() >
01375               MulC->getType()->getPrimitiveSizeInBits())
01376             MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
01377 
01378           // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
01379           Multiple = ConstantExpr::getMul(MulC, Op1C);
01380           return true;
01381         }
01382 
01383       if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
01384         if (Mul0CI->getValue() == 1) {
01385           // V == Base * Op1, so return Op1
01386           Multiple = Op1;
01387           return true;
01388         }
01389     }
01390 
01391     Value *Mul1 = nullptr;
01392     if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
01393       if (Constant *Op0C = dyn_cast<Constant>(Op0))
01394         if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
01395           if (Op0C->getType()->getPrimitiveSizeInBits() <
01396               MulC->getType()->getPrimitiveSizeInBits())
01397             Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
01398           if (Op0C->getType()->getPrimitiveSizeInBits() >
01399               MulC->getType()->getPrimitiveSizeInBits())
01400             MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
01401 
01402           // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
01403           Multiple = ConstantExpr::getMul(MulC, Op0C);
01404           return true;
01405         }
01406 
01407       if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
01408         if (Mul1CI->getValue() == 1) {
01409           // V == Base * Op0, so return Op0
01410           Multiple = Op0;
01411           return true;
01412         }
01413     }
01414   }
01415   }
01416 
01417   // We could not determine if V is a multiple of Base.
01418   return false;
01419 }
01420 
01421 /// CannotBeNegativeZero - Return true if we can prove that the specified FP
01422 /// value is never equal to -0.0.
01423 ///
01424 /// NOTE: this function will need to be revisited when we support non-default
01425 /// rounding modes!
01426 ///
01427 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
01428   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
01429     return !CFP->getValueAPF().isNegZero();
01430 
01431   if (Depth == 6)
01432     return 1;  // Limit search depth.
01433 
01434   const Operator *I = dyn_cast<Operator>(V);
01435   if (!I) return false;
01436 
01437   // Check if the nsz fast-math flag is set
01438   if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
01439     if (FPO->hasNoSignedZeros())
01440       return true;
01441 
01442   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
01443   if (I->getOpcode() == Instruction::FAdd)
01444     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
01445       if (CFP->isNullValue())
01446         return true;
01447 
01448   // sitofp and uitofp turn into +0.0 for zero.
01449   if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
01450     return true;
01451 
01452   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
01453     // sqrt(-0.0) = -0.0, no other negative results are possible.
01454     if (II->getIntrinsicID() == Intrinsic::sqrt)
01455       return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
01456 
01457   if (const CallInst *CI = dyn_cast<CallInst>(I))
01458     if (const Function *F = CI->getCalledFunction()) {
01459       if (F->isDeclaration()) {
01460         // abs(x) != -0.0
01461         if (F->getName() == "abs") return true;
01462         // fabs[lf](x) != -0.0
01463         if (F->getName() == "fabs") return true;
01464         if (F->getName() == "fabsf") return true;
01465         if (F->getName() == "fabsl") return true;
01466         if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
01467             F->getName() == "sqrtl")
01468           return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
01469       }
01470     }
01471 
01472   return false;
01473 }
01474 
01475 /// isBytewiseValue - If the specified value can be set by repeating the same
01476 /// byte in memory, return the i8 value that it is represented with.  This is
01477 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
01478 /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
01479 /// byte store (e.g. i16 0x1234), return null.
01480 Value *llvm::isBytewiseValue(Value *V) {
01481   // All byte-wide stores are splatable, even of arbitrary variables.
01482   if (V->getType()->isIntegerTy(8)) return V;
01483 
01484   // Handle 'null' ConstantArrayZero etc.
01485   if (Constant *C = dyn_cast<Constant>(V))
01486     if (C->isNullValue())
01487       return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
01488 
01489   // Constant float and double values can be handled as integer values if the
01490   // corresponding integer value is "byteable".  An important case is 0.0.
01491   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
01492     if (CFP->getType()->isFloatTy())
01493       V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
01494     if (CFP->getType()->isDoubleTy())
01495       V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
01496     // Don't handle long double formats, which have strange constraints.
01497   }
01498 
01499   // We can handle constant integers that are power of two in size and a
01500   // multiple of 8 bits.
01501   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
01502     unsigned Width = CI->getBitWidth();
01503     if (isPowerOf2_32(Width) && Width > 8) {
01504       // We can handle this value if the recursive binary decomposition is the
01505       // same at all levels.
01506       APInt Val = CI->getValue();
01507       APInt Val2;
01508       while (Val.getBitWidth() != 8) {
01509         unsigned NextWidth = Val.getBitWidth()/2;
01510         Val2  = Val.lshr(NextWidth);
01511         Val2 = Val2.trunc(Val.getBitWidth()/2);
01512         Val = Val.trunc(Val.getBitWidth()/2);
01513 
01514         // If the top/bottom halves aren't the same, reject it.
01515         if (Val != Val2)
01516           return nullptr;
01517       }
01518       return ConstantInt::get(V->getContext(), Val);
01519     }
01520   }
01521 
01522   // A ConstantDataArray/Vector is splatable if all its members are equal and
01523   // also splatable.
01524   if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
01525     Value *Elt = CA->getElementAsConstant(0);
01526     Value *Val = isBytewiseValue(Elt);
01527     if (!Val)
01528       return nullptr;
01529 
01530     for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
01531       if (CA->getElementAsConstant(I) != Elt)
01532         return nullptr;
01533 
01534     return Val;
01535   }
01536 
01537   // Conceptually, we could handle things like:
01538   //   %a = zext i8 %X to i16
01539   //   %b = shl i16 %a, 8
01540   //   %c = or i16 %a, %b
01541   // but until there is an example that actually needs this, it doesn't seem
01542   // worth worrying about.
01543   return nullptr;
01544 }
01545 
01546 
01547 // This is the recursive version of BuildSubAggregate. It takes a few different
01548 // arguments. Idxs is the index within the nested struct From that we are
01549 // looking at now (which is of type IndexedType). IdxSkip is the number of
01550 // indices from Idxs that should be left out when inserting into the resulting
01551 // struct. To is the result struct built so far, new insertvalue instructions
01552 // build on that.
01553 static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
01554                                 SmallVectorImpl<unsigned> &Idxs,
01555                                 unsigned IdxSkip,
01556                                 Instruction *InsertBefore) {
01557   llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
01558   if (STy) {
01559     // Save the original To argument so we can modify it
01560     Value *OrigTo = To;
01561     // General case, the type indexed by Idxs is a struct
01562     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
01563       // Process each struct element recursively
01564       Idxs.push_back(i);
01565       Value *PrevTo = To;
01566       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
01567                              InsertBefore);
01568       Idxs.pop_back();
01569       if (!To) {
01570         // Couldn't find any inserted value for this index? Cleanup
01571         while (PrevTo != OrigTo) {
01572           InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
01573           PrevTo = Del->getAggregateOperand();
01574           Del->eraseFromParent();
01575         }
01576         // Stop processing elements
01577         break;
01578       }
01579     }
01580     // If we successfully found a value for each of our subaggregates
01581     if (To)
01582       return To;
01583   }
01584   // Base case, the type indexed by SourceIdxs is not a struct, or not all of
01585   // the struct's elements had a value that was inserted directly. In the latter
01586   // case, perhaps we can't determine each of the subelements individually, but
01587   // we might be able to find the complete struct somewhere.
01588 
01589   // Find the value that is at that particular spot
01590   Value *V = FindInsertedValue(From, Idxs);
01591 
01592   if (!V)
01593     return nullptr;
01594 
01595   // Insert the value in the new (sub) aggregrate
01596   return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
01597                                        "tmp", InsertBefore);
01598 }
01599 
01600 // This helper takes a nested struct and extracts a part of it (which is again a
01601 // struct) into a new value. For example, given the struct:
01602 // { a, { b, { c, d }, e } }
01603 // and the indices "1, 1" this returns
01604 // { c, d }.
01605 //
01606 // It does this by inserting an insertvalue for each element in the resulting
01607 // struct, as opposed to just inserting a single struct. This will only work if
01608 // each of the elements of the substruct are known (ie, inserted into From by an
01609 // insertvalue instruction somewhere).
01610 //
01611 // All inserted insertvalue instructions are inserted before InsertBefore
01612 static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
01613                                 Instruction *InsertBefore) {
01614   assert(InsertBefore && "Must have someplace to insert!");
01615   Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
01616                                                              idx_range);
01617   Value *To = UndefValue::get(IndexedType);
01618   SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
01619   unsigned IdxSkip = Idxs.size();
01620 
01621   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
01622 }
01623 
01624 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
01625 /// the scalar value indexed is already around as a register, for example if it
01626 /// were inserted directly into the aggregrate.
01627 ///
01628 /// If InsertBefore is not null, this function will duplicate (modified)
01629 /// insertvalues when a part of a nested struct is extracted.
01630 Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
01631                                Instruction *InsertBefore) {
01632   // Nothing to index? Just return V then (this is useful at the end of our
01633   // recursion).
01634   if (idx_range.empty())
01635     return V;
01636   // We have indices, so V should have an indexable type.
01637   assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
01638          "Not looking at a struct or array?");
01639   assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
01640          "Invalid indices for type?");
01641 
01642   if (Constant *C = dyn_cast<Constant>(V)) {
01643     C = C->getAggregateElement(idx_range[0]);
01644     if (!C) return nullptr;
01645     return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
01646   }
01647 
01648   if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
01649     // Loop the indices for the insertvalue instruction in parallel with the
01650     // requested indices
01651     const unsigned *req_idx = idx_range.begin();
01652     for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
01653          i != e; ++i, ++req_idx) {
01654       if (req_idx == idx_range.end()) {
01655         // We can't handle this without inserting insertvalues
01656         if (!InsertBefore)
01657           return nullptr;
01658 
01659         // The requested index identifies a part of a nested aggregate. Handle
01660         // this specially. For example,
01661         // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
01662         // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
01663         // %C = extractvalue {i32, { i32, i32 } } %B, 1
01664         // This can be changed into
01665         // %A = insertvalue {i32, i32 } undef, i32 10, 0
01666         // %C = insertvalue {i32, i32 } %A, i32 11, 1
01667         // which allows the unused 0,0 element from the nested struct to be
01668         // removed.
01669         return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
01670                                  InsertBefore);
01671       }
01672 
01673       // This insert value inserts something else than what we are looking for.
01674       // See if the (aggregrate) value inserted into has the value we are
01675       // looking for, then.
01676       if (*req_idx != *i)
01677         return FindInsertedValue(I->getAggregateOperand(), idx_range,
01678                                  InsertBefore);
01679     }
01680     // If we end up here, the indices of the insertvalue match with those
01681     // requested (though possibly only partially). Now we recursively look at
01682     // the inserted value, passing any remaining indices.
01683     return FindInsertedValue(I->getInsertedValueOperand(),
01684                              makeArrayRef(req_idx, idx_range.end()),
01685                              InsertBefore);
01686   }
01687 
01688   if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
01689     // If we're extracting a value from an aggregrate that was extracted from
01690     // something else, we can extract from that something else directly instead.
01691     // However, we will need to chain I's indices with the requested indices.
01692 
01693     // Calculate the number of indices required
01694     unsigned size = I->getNumIndices() + idx_range.size();
01695     // Allocate some space to put the new indices in
01696     SmallVector<unsigned, 5> Idxs;
01697     Idxs.reserve(size);
01698     // Add indices from the extract value instruction
01699     Idxs.append(I->idx_begin(), I->idx_end());
01700 
01701     // Add requested indices
01702     Idxs.append(idx_range.begin(), idx_range.end());
01703 
01704     assert(Idxs.size() == size
01705            && "Number of indices added not correct?");
01706 
01707     return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
01708   }
01709   // Otherwise, we don't know (such as, extracting from a function return value
01710   // or load instruction)
01711   return nullptr;
01712 }
01713 
01714 /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
01715 /// it can be expressed as a base pointer plus a constant offset.  Return the
01716 /// base and offset to the caller.
01717 Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
01718                                               const DataLayout *DL) {
01719   // Without DataLayout, conservatively assume 64-bit offsets, which is
01720   // the widest we support.
01721   unsigned BitWidth = DL ? DL->getPointerTypeSizeInBits(Ptr->getType()) : 64;
01722   APInt ByteOffset(BitWidth, 0);
01723   while (1) {
01724     if (Ptr->getType()->isVectorTy())
01725       break;
01726 
01727     if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
01728       if (DL) {
01729         APInt GEPOffset(BitWidth, 0);
01730         if (!GEP->accumulateConstantOffset(*DL, GEPOffset))
01731           break;
01732 
01733         ByteOffset += GEPOffset;
01734       }
01735 
01736       Ptr = GEP->getPointerOperand();
01737     } else if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
01738       Ptr = cast<Operator>(Ptr)->getOperand(0);
01739     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
01740       if (GA->mayBeOverridden())
01741         break;
01742       Ptr = GA->getAliasee();
01743     } else {
01744       break;
01745     }
01746   }
01747   Offset = ByteOffset.getSExtValue();
01748   return Ptr;
01749 }
01750 
01751 
01752 /// getConstantStringInfo - This function computes the length of a
01753 /// null-terminated C string pointed to by V.  If successful, it returns true
01754 /// and returns the string in Str.  If unsuccessful, it returns false.
01755 bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
01756                                  uint64_t Offset, bool TrimAtNul) {
01757   assert(V);
01758 
01759   // Look through bitcast instructions and geps.
01760   V = V->stripPointerCasts();
01761 
01762   // If the value is a GEP instructionor  constant expression, treat it as an
01763   // offset.
01764   if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
01765     // Make sure the GEP has exactly three arguments.
01766     if (GEP->getNumOperands() != 3)
01767       return false;
01768 
01769     // Make sure the index-ee is a pointer to array of i8.
01770     PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
01771     ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
01772     if (!AT || !AT->getElementType()->isIntegerTy(8))
01773       return false;
01774 
01775     // Check to make sure that the first operand of the GEP is an integer and
01776     // has value 0 so that we are sure we're indexing into the initializer.
01777     const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
01778     if (!FirstIdx || !FirstIdx->isZero())
01779       return false;
01780 
01781     // If the second index isn't a ConstantInt, then this is a variable index
01782     // into the array.  If this occurs, we can't say anything meaningful about
01783     // the string.
01784     uint64_t StartIdx = 0;
01785     if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
01786       StartIdx = CI->getZExtValue();
01787     else
01788       return false;
01789     return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset);
01790   }
01791 
01792   // The GEP instruction, constant or instruction, must reference a global
01793   // variable that is a constant and is initialized. The referenced constant
01794   // initializer is the array that we'll use for optimization.
01795   const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
01796   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
01797     return false;
01798 
01799   // Handle the all-zeros case
01800   if (GV->getInitializer()->isNullValue()) {
01801     // This is a degenerate case. The initializer is constant zero so the
01802     // length of the string must be zero.
01803     Str = "";
01804     return true;
01805   }
01806 
01807   // Must be a Constant Array
01808   const ConstantDataArray *Array =
01809     dyn_cast<ConstantDataArray>(GV->getInitializer());
01810   if (!Array || !Array->isString())
01811     return false;
01812 
01813   // Get the number of elements in the array
01814   uint64_t NumElts = Array->getType()->getArrayNumElements();
01815 
01816   // Start out with the entire array in the StringRef.
01817   Str = Array->getAsString();
01818 
01819   if (Offset > NumElts)
01820     return false;
01821 
01822   // Skip over 'offset' bytes.
01823   Str = Str.substr(Offset);
01824 
01825   if (TrimAtNul) {
01826     // Trim off the \0 and anything after it.  If the array is not nul
01827     // terminated, we just return the whole end of string.  The client may know
01828     // some other way that the string is length-bound.
01829     Str = Str.substr(0, Str.find('\0'));
01830   }
01831   return true;
01832 }
01833 
01834 // These next two are very similar to the above, but also look through PHI
01835 // nodes.
01836 // TODO: See if we can integrate these two together.
01837 
01838 /// GetStringLengthH - If we can compute the length of the string pointed to by
01839 /// the specified pointer, return 'len+1'.  If we can't, return 0.
01840 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
01841   // Look through noop bitcast instructions.
01842   V = V->stripPointerCasts();
01843 
01844   // If this is a PHI node, there are two cases: either we have already seen it
01845   // or we haven't.
01846   if (PHINode *PN = dyn_cast<PHINode>(V)) {
01847     if (!PHIs.insert(PN))
01848       return ~0ULL;  // already in the set.
01849 
01850     // If it was new, see if all the input strings are the same length.
01851     uint64_t LenSoFar = ~0ULL;
01852     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01853       uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
01854       if (Len == 0) return 0; // Unknown length -> unknown.
01855 
01856       if (Len == ~0ULL) continue;
01857 
01858       if (Len != LenSoFar && LenSoFar != ~0ULL)
01859         return 0;    // Disagree -> unknown.
01860       LenSoFar = Len;
01861     }
01862 
01863     // Success, all agree.
01864     return LenSoFar;
01865   }
01866 
01867   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
01868   if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
01869     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
01870     if (Len1 == 0) return 0;
01871     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
01872     if (Len2 == 0) return 0;
01873     if (Len1 == ~0ULL) return Len2;
01874     if (Len2 == ~0ULL) return Len1;
01875     if (Len1 != Len2) return 0;
01876     return Len1;
01877   }
01878 
01879   // Otherwise, see if we can read the string.
01880   StringRef StrData;
01881   if (!getConstantStringInfo(V, StrData))
01882     return 0;
01883 
01884   return StrData.size()+1;
01885 }
01886 
01887 /// GetStringLength - If we can compute the length of the string pointed to by
01888 /// the specified pointer, return 'len+1'.  If we can't, return 0.
01889 uint64_t llvm::GetStringLength(Value *V) {
01890   if (!V->getType()->isPointerTy()) return 0;
01891 
01892   SmallPtrSet<PHINode*, 32> PHIs;
01893   uint64_t Len = GetStringLengthH(V, PHIs);
01894   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
01895   // an empty string as a length.
01896   return Len == ~0ULL ? 1 : Len;
01897 }
01898 
01899 Value *
01900 llvm::GetUnderlyingObject(Value *V, const DataLayout *TD, unsigned MaxLookup) {
01901   if (!V->getType()->isPointerTy())
01902     return V;
01903   for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
01904     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
01905       V = GEP->getPointerOperand();
01906     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
01907       V = cast<Operator>(V)->getOperand(0);
01908     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
01909       if (GA->mayBeOverridden())
01910         return V;
01911       V = GA->getAliasee();
01912     } else {
01913       // See if InstructionSimplify knows any relevant tricks.
01914       if (Instruction *I = dyn_cast<Instruction>(V))
01915         // TODO: Acquire a DominatorTree and use it.
01916         if (Value *Simplified = SimplifyInstruction(I, TD, nullptr)) {
01917           V = Simplified;
01918           continue;
01919         }
01920 
01921       return V;
01922     }
01923     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
01924   }
01925   return V;
01926 }
01927 
01928 void
01929 llvm::GetUnderlyingObjects(Value *V,
01930                            SmallVectorImpl<Value *> &Objects,
01931                            const DataLayout *TD,
01932                            unsigned MaxLookup) {
01933   SmallPtrSet<Value *, 4> Visited;
01934   SmallVector<Value *, 4> Worklist;
01935   Worklist.push_back(V);
01936   do {
01937     Value *P = Worklist.pop_back_val();
01938     P = GetUnderlyingObject(P, TD, MaxLookup);
01939 
01940     if (!Visited.insert(P))
01941       continue;
01942 
01943     if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
01944       Worklist.push_back(SI->getTrueValue());
01945       Worklist.push_back(SI->getFalseValue());
01946       continue;
01947     }
01948 
01949     if (PHINode *PN = dyn_cast<PHINode>(P)) {
01950       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
01951         Worklist.push_back(PN->getIncomingValue(i));
01952       continue;
01953     }
01954 
01955     Objects.push_back(P);
01956   } while (!Worklist.empty());
01957 }
01958 
01959 /// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
01960 /// are lifetime markers.
01961 ///
01962 bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
01963   for (const User *U : V->users()) {
01964     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
01965     if (!II) return false;
01966 
01967     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
01968         II->getIntrinsicID() != Intrinsic::lifetime_end)
01969       return false;
01970   }
01971   return true;
01972 }
01973 
01974 bool llvm::isSafeToSpeculativelyExecute(const Value *V,
01975                                         const DataLayout *TD) {
01976   const Operator *Inst = dyn_cast<Operator>(V);
01977   if (!Inst)
01978     return false;
01979 
01980   for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
01981     if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
01982       if (C->canTrap())
01983         return false;
01984 
01985   switch (Inst->getOpcode()) {
01986   default:
01987     return true;
01988   case Instruction::UDiv:
01989   case Instruction::URem:
01990     // x / y is undefined if y == 0, but calcuations like x / 3 are safe.
01991     return isKnownNonZero(Inst->getOperand(1), TD);
01992   case Instruction::SDiv:
01993   case Instruction::SRem: {
01994     Value *Op = Inst->getOperand(1);
01995     // x / y is undefined if y == 0
01996     if (!isKnownNonZero(Op, TD))
01997       return false;
01998     // x / y might be undefined if y == -1
01999     unsigned BitWidth = getBitWidth(Op->getType(), TD);
02000     if (BitWidth == 0)
02001       return false;
02002     APInt KnownZero(BitWidth, 0);
02003     APInt KnownOne(BitWidth, 0);
02004     ComputeMaskedBits(Op, KnownZero, KnownOne, TD);
02005     return !!KnownZero;
02006   }
02007   case Instruction::Load: {
02008     const LoadInst *LI = cast<LoadInst>(Inst);
02009     if (!LI->isUnordered() ||
02010         // Speculative load may create a race that did not exist in the source.
02011         LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
02012       return false;
02013     return LI->getPointerOperand()->isDereferenceablePointer();
02014   }
02015   case Instruction::Call: {
02016    if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
02017      switch (II->getIntrinsicID()) {
02018        // These synthetic intrinsics have no side-effects, and just mark
02019        // information about their operands.
02020        // FIXME: There are other no-op synthetic instructions that potentially
02021        // should be considered at least *safe* to speculate...
02022        case Intrinsic::dbg_declare:
02023        case Intrinsic::dbg_value:
02024          return true;
02025 
02026        case Intrinsic::bswap:
02027        case Intrinsic::ctlz:
02028        case Intrinsic::ctpop:
02029        case Intrinsic::cttz:
02030        case Intrinsic::objectsize:
02031        case Intrinsic::sadd_with_overflow:
02032        case Intrinsic::smul_with_overflow:
02033        case Intrinsic::ssub_with_overflow:
02034        case Intrinsic::uadd_with_overflow:
02035        case Intrinsic::umul_with_overflow:
02036        case Intrinsic::usub_with_overflow:
02037          return true;
02038        // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
02039        // errno like libm sqrt would.
02040        case Intrinsic::sqrt:
02041        case Intrinsic::fma:
02042        case Intrinsic::fmuladd:
02043          return true;
02044        // TODO: some fp intrinsics are marked as having the same error handling
02045        // as libm. They're safe to speculate when they won't error.
02046        // TODO: are convert_{from,to}_fp16 safe?
02047        // TODO: can we list target-specific intrinsics here?
02048        default: break;
02049      }
02050    }
02051     return false; // The called function could have undefined behavior or
02052                   // side-effects, even if marked readnone nounwind.
02053   }
02054   case Instruction::VAArg:
02055   case Instruction::Alloca:
02056   case Instruction::Invoke:
02057   case Instruction::PHI:
02058   case Instruction::Store:
02059   case Instruction::Ret:
02060   case Instruction::Br:
02061   case Instruction::IndirectBr:
02062   case Instruction::Switch:
02063   case Instruction::Unreachable:
02064   case Instruction::Fence:
02065   case Instruction::LandingPad:
02066   case Instruction::AtomicRMW:
02067   case Instruction::AtomicCmpXchg:
02068   case Instruction::Resume:
02069     return false; // Misc instructions which have effects
02070   }
02071 }
02072 
02073 /// isKnownNonNull - Return true if we know that the specified value is never
02074 /// null.
02075 bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
02076   // Alloca never returns null, malloc might.
02077   if (isa<AllocaInst>(V)) return true;
02078 
02079   // A byval or inalloca argument is never null.
02080   if (const Argument *A = dyn_cast<Argument>(V))
02081     return A->hasByValOrInAllocaAttr();
02082 
02083   // Global values are not null unless extern weak.
02084   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
02085     return !GV->hasExternalWeakLinkage();
02086 
02087   // operator new never returns null.
02088   if (isOperatorNewLikeFn(V, TLI, /*LookThroughBitCast=*/true))
02089     return true;
02090 
02091   return false;
02092 }