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