LLVM API Documentation
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/Constants.h" 00017 #include "llvm/Instructions.h" 00018 #include "llvm/GlobalVariable.h" 00019 #include "llvm/IntrinsicInst.h" 00020 #include "llvm/LLVMContext.h" 00021 #include "llvm/Operator.h" 00022 #include "llvm/Target/TargetData.h" 00023 #include "llvm/Support/GetElementPtrTypeIterator.h" 00024 #include "llvm/Support/MathExtras.h" 00025 #include <cstring> 00026 using namespace llvm; 00027 00028 /// ComputeMaskedBits - Determine which of the bits specified in Mask are 00029 /// known to be either zero or one and return them in the KnownZero/KnownOne 00030 /// bit sets. This code only analyzes bits in Mask, in order to short-circuit 00031 /// processing. 00032 /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that 00033 /// we cannot optimize based on the assumption that it is zero without changing 00034 /// it to be an explicit zero. If we don't change it to zero, other code could 00035 /// optimized based on the contradictory assumption that it is non-zero. 00036 /// Because instcombine aggressively folds operations with undef args anyway, 00037 /// this won't lose us code quality. 00038 void llvm::ComputeMaskedBits(Value *V, const APInt &Mask, 00039 APInt &KnownZero, APInt &KnownOne, 00040 TargetData *TD, unsigned Depth) { 00041 const unsigned MaxDepth = 6; 00042 assert(V && "No Value?"); 00043 assert(Depth <= MaxDepth && "Limit Search Depth"); 00044 unsigned BitWidth = Mask.getBitWidth(); 00045 assert((V->getType()->isIntOrIntVector() || isa<PointerType>(V->getType())) && 00046 "Not integer or pointer type!"); 00047 assert((!TD || 00048 TD->getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) && 00049 (!V->getType()->isIntOrIntVector() || 00050 V->getType()->getScalarSizeInBits() == BitWidth) && 00051 KnownZero.getBitWidth() == BitWidth && 00052 KnownOne.getBitWidth() == BitWidth && 00053 "V, Mask, KnownOne and KnownZero should have same BitWidth"); 00054 00055 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 00056 // We know all of the bits for a constant! 00057 KnownOne = CI->getValue() & Mask; 00058 KnownZero = ~KnownOne & Mask; 00059 return; 00060 } 00061 // Null and aggregate-zero are all-zeros. 00062 if (isa<ConstantPointerNull>(V) || 00063 isa<ConstantAggregateZero>(V)) { 00064 KnownOne.clear(); 00065 KnownZero = Mask; 00066 return; 00067 } 00068 // Handle a constant vector by taking the intersection of the known bits of 00069 // each element. 00070 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) { 00071 KnownZero.set(); KnownOne.set(); 00072 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) { 00073 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0); 00074 ComputeMaskedBits(CV->getOperand(i), Mask, KnownZero2, KnownOne2, 00075 TD, Depth); 00076 KnownZero &= KnownZero2; 00077 KnownOne &= KnownOne2; 00078 } 00079 return; 00080 } 00081 // The address of an aligned GlobalValue has trailing zeros. 00082 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) { 00083 unsigned Align = GV->getAlignment(); 00084 if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) { 00085 const Type *ObjectType = GV->getType()->getElementType(); 00086 // If the object is defined in the current Module, we'll be giving 00087 // it the preferred alignment. Otherwise, we have to assume that it 00088 // may only have the minimum ABI alignment. 00089 if (!GV->isDeclaration() && !GV->mayBeOverridden()) 00090 Align = TD->getPrefTypeAlignment(ObjectType); 00091 else 00092 Align = TD->getABITypeAlignment(ObjectType); 00093 } 00094 if (Align > 0) 00095 KnownZero = Mask & APInt::getLowBitsSet(BitWidth, 00096 CountTrailingZeros_32(Align)); 00097 else 00098 KnownZero.clear(); 00099 KnownOne.clear(); 00100 return; 00101 } 00102 00103 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything. 00104 00105 if (Depth == MaxDepth || Mask == 0) 00106 return; // Limit search depth. 00107 00108 Operator *I = dyn_cast<Operator>(V); 00109 if (!I) return; 00110 00111 APInt KnownZero2(KnownZero), KnownOne2(KnownOne); 00112 switch (I->getOpcode()) { 00113 default: break; 00114 case Instruction::And: { 00115 // If either the LHS or the RHS are Zero, the result is zero. 00116 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1); 00117 APInt Mask2(Mask & ~KnownZero); 00118 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD, 00119 Depth+1); 00120 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 00121 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 00122 00123 // Output known-1 bits are only known if set in both the LHS & RHS. 00124 KnownOne &= KnownOne2; 00125 // Output known-0 are known to be clear if zero in either the LHS | RHS. 00126 KnownZero |= KnownZero2; 00127 return; 00128 } 00129 case Instruction::Or: { 00130 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1); 00131 APInt Mask2(Mask & ~KnownOne); 00132 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD, 00133 Depth+1); 00134 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 00135 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 00136 00137 // Output known-0 bits are only known if clear in both the LHS & RHS. 00138 KnownZero &= KnownZero2; 00139 // Output known-1 are known to be set if set in either the LHS | RHS. 00140 KnownOne |= KnownOne2; 00141 return; 00142 } 00143 case Instruction::Xor: { 00144 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, TD, Depth+1); 00145 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, TD, 00146 Depth+1); 00147 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 00148 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 00149 00150 // Output known-0 bits are known if clear or set in both the LHS & RHS. 00151 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2); 00152 // Output known-1 are known to be set if set in only one of the LHS, RHS. 00153 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2); 00154 KnownZero = KnownZeroOut; 00155 return; 00156 } 00157 case Instruction::Mul: { 00158 APInt Mask2 = APInt::getAllOnesValue(BitWidth); 00159 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, TD,Depth+1); 00160 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD, 00161 Depth+1); 00162 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 00163 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 00164 00165 // If low bits are zero in either operand, output low known-0 bits. 00166 // Also compute a conserative estimate for high known-0 bits. 00167 // More trickiness is possible, but this is sufficient for the 00168 // interesting case of alignment computation. 00169 KnownOne.clear(); 00170 unsigned TrailZ = KnownZero.countTrailingOnes() + 00171 KnownZero2.countTrailingOnes(); 00172 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() + 00173 KnownZero2.countLeadingOnes(), 00174 BitWidth) - BitWidth; 00175 00176 TrailZ = std::min(TrailZ, BitWidth); 00177 LeadZ = std::min(LeadZ, BitWidth); 00178 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) | 00179 APInt::getHighBitsSet(BitWidth, LeadZ); 00180 KnownZero &= Mask; 00181 return; 00182 } 00183 case Instruction::UDiv: { 00184 // For the purposes of computing leading zeros we can conservatively 00185 // treat a udiv as a logical right shift by the power of 2 known to 00186 // be less than the denominator. 00187 APInt AllOnes = APInt::getAllOnesValue(BitWidth); 00188 ComputeMaskedBits(I->getOperand(0), 00189 AllOnes, KnownZero2, KnownOne2, TD, Depth+1); 00190 unsigned LeadZ = KnownZero2.countLeadingOnes(); 00191 00192 KnownOne2.clear(); 00193 KnownZero2.clear(); 00194 ComputeMaskedBits(I->getOperand(1), 00195 AllOnes, KnownZero2, KnownOne2, TD, Depth+1); 00196 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros(); 00197 if (RHSUnknownLeadingOnes != BitWidth) 00198 LeadZ = std::min(BitWidth, 00199 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1); 00200 00201 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask; 00202 return; 00203 } 00204 case Instruction::Select: 00205 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, TD, Depth+1); 00206 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, TD, 00207 Depth+1); 00208 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 00209 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 00210 00211 // Only known if known in both the LHS and RHS. 00212 KnownOne &= KnownOne2; 00213 KnownZero &= KnownZero2; 00214 return; 00215 case Instruction::FPTrunc: 00216 case Instruction::FPExt: 00217 case Instruction::FPToUI: 00218 case Instruction::FPToSI: 00219 case Instruction::SIToFP: 00220 case Instruction::UIToFP: 00221 return; // Can't work with floating point. 00222 case Instruction::PtrToInt: 00223 case Instruction::IntToPtr: 00224 // We can't handle these if we don't know the pointer size. 00225 if (!TD) return; 00226 // FALL THROUGH and handle them the same as zext/trunc. 00227 case Instruction::ZExt: 00228 case Instruction::Trunc: { 00229 // Note that we handle pointer operands here because of inttoptr/ptrtoint 00230 // which fall through here. 00231 const Type *SrcTy = I->getOperand(0)->getType(); 00232 unsigned SrcBitWidth = TD ? 00233 TD->getTypeSizeInBits(SrcTy) : 00234 SrcTy->getScalarSizeInBits(); 00235 APInt MaskIn(Mask); 00236 MaskIn.zextOrTrunc(SrcBitWidth); 00237 KnownZero.zextOrTrunc(SrcBitWidth); 00238 KnownOne.zextOrTrunc(SrcBitWidth); 00239 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD, 00240 Depth+1); 00241 KnownZero.zextOrTrunc(BitWidth); 00242 KnownOne.zextOrTrunc(BitWidth); 00243 // Any top bits are known to be zero. 00244 if (BitWidth > SrcBitWidth) 00245 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth); 00246 return; 00247 } 00248 case Instruction::BitCast: { 00249 const Type *SrcTy = I->getOperand(0)->getType(); 00250 if ((SrcTy->isInteger() || isa<PointerType>(SrcTy)) && 00251 // TODO: For now, not handling conversions like: 00252 // (bitcast i64 %x to <2 x i32>) 00253 !isa<VectorType>(I->getType())) { 00254 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, TD, 00255 Depth+1); 00256 return; 00257 } 00258 break; 00259 } 00260 case Instruction::SExt: { 00261 // Compute the bits in the result that are not present in the input. 00262 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType()); 00263 unsigned SrcBitWidth = SrcTy->getBitWidth(); 00264 00265 APInt MaskIn(Mask); 00266 MaskIn.trunc(SrcBitWidth); 00267 KnownZero.trunc(SrcBitWidth); 00268 KnownOne.trunc(SrcBitWidth); 00269 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, TD, 00270 Depth+1); 00271 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 00272 KnownZero.zext(BitWidth); 00273 KnownOne.zext(BitWidth); 00274 00275 // If the sign bit of the input is known set or clear, then we know the 00276 // top bits of the result. 00277 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero 00278 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth); 00279 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set 00280 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth); 00281 return; 00282 } 00283 case Instruction::Shl: 00284 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0 00285 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) { 00286 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth); 00287 APInt Mask2(Mask.lshr(ShiftAmt)); 00288 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD, 00289 Depth+1); 00290 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 00291 KnownZero <<= ShiftAmt; 00292 KnownOne <<= ShiftAmt; 00293 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0 00294 return; 00295 } 00296 break; 00297 case Instruction::LShr: 00298 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0 00299 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) { 00300 // Compute the new bits that are at the top now. 00301 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth); 00302 00303 // Unsigned shift right. 00304 APInt Mask2(Mask.shl(ShiftAmt)); 00305 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne, TD, 00306 Depth+1); 00307 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 00308 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt); 00309 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt); 00310 // high bits known zero. 00311 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt); 00312 return; 00313 } 00314 break; 00315 case Instruction::AShr: 00316 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0 00317 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) { 00318 // Compute the new bits that are at the top now. 00319 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth); 00320 00321 // Signed shift right. 00322 APInt Mask2(Mask.shl(ShiftAmt)); 00323 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD, 00324 Depth+1); 00325 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 00326 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt); 00327 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt); 00328 00329 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt)); 00330 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero. 00331 KnownZero |= HighBits; 00332 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one. 00333 KnownOne |= HighBits; 00334 return; 00335 } 00336 break; 00337 case Instruction::Sub: { 00338 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) { 00339 // We know that the top bits of C-X are clear if X contains less bits 00340 // than C (i.e. no wrap-around can happen). For example, 20-X is 00341 // positive if we can prove that X is >= 0 and < 16. 00342 if (!CLHS->getValue().isNegative()) { 00343 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros(); 00344 // NLZ can't be BitWidth with no sign bit 00345 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1); 00346 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2, 00347 TD, Depth+1); 00348 00349 // If all of the MaskV bits are known to be zero, then we know the 00350 // output top bits are zero, because we now know that the output is 00351 // from [0-C]. 00352 if ((KnownZero2 & MaskV) == MaskV) { 00353 unsigned NLZ2 = CLHS->getValue().countLeadingZeros(); 00354 // Top bits known zero. 00355 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask; 00356 } 00357 } 00358 } 00359 } 00360 // fall through 00361 case Instruction::Add: { 00362 // If one of the operands has trailing zeros, than the bits that the 00363 // other operand has in those bit positions will be preserved in the 00364 // result. For an add, this works with either operand. For a subtract, 00365 // this only works if the known zeros are in the right operand. 00366 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0); 00367 APInt Mask2 = APInt::getLowBitsSet(BitWidth, 00368 BitWidth - Mask.countLeadingZeros()); 00369 ComputeMaskedBits(I->getOperand(0), Mask2, LHSKnownZero, LHSKnownOne, TD, 00370 Depth+1); 00371 assert((LHSKnownZero & LHSKnownOne) == 0 && 00372 "Bits known to be one AND zero?"); 00373 unsigned LHSKnownZeroOut = LHSKnownZero.countTrailingOnes(); 00374 00375 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, TD, 00376 Depth+1); 00377 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 00378 unsigned RHSKnownZeroOut = KnownZero2.countTrailingOnes(); 00379 00380 // Determine which operand has more trailing zeros, and use that 00381 // many bits from the other operand. 00382 if (LHSKnownZeroOut > RHSKnownZeroOut) { 00383 if (I->getOpcode() == Instruction::Add) { 00384 APInt Mask = APInt::getLowBitsSet(BitWidth, LHSKnownZeroOut); 00385 KnownZero |= KnownZero2 & Mask; 00386 KnownOne |= KnownOne2 & Mask; 00387 } else { 00388 // If the known zeros are in the left operand for a subtract, 00389 // fall back to the minimum known zeros in both operands. 00390 KnownZero |= APInt::getLowBitsSet(BitWidth, 00391 std::min(LHSKnownZeroOut, 00392 RHSKnownZeroOut)); 00393 } 00394 } else if (RHSKnownZeroOut >= LHSKnownZeroOut) { 00395 APInt Mask = APInt::getLowBitsSet(BitWidth, RHSKnownZeroOut); 00396 KnownZero |= LHSKnownZero & Mask; 00397 KnownOne |= LHSKnownOne & Mask; 00398 } 00399 return; 00400 } 00401 case Instruction::SRem: 00402 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) { 00403 APInt RA = Rem->getValue(); 00404 if (RA.isPowerOf2() || (-RA).isPowerOf2()) { 00405 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA; 00406 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth); 00407 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, TD, 00408 Depth+1); 00409 00410 // If the sign bit of the first operand is zero, the sign bit of 00411 // the result is zero. If the first operand has no one bits below 00412 // the second operand's single 1 bit, its sign will be zero. 00413 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits)) 00414 KnownZero2 |= ~LowBits; 00415 00416 KnownZero |= KnownZero2 & Mask; 00417 00418 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 00419 } 00420 } 00421 break; 00422 case Instruction::URem: { 00423 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) { 00424 APInt RA = Rem->getValue(); 00425 if (RA.isPowerOf2()) { 00426 APInt LowBits = (RA - 1); 00427 APInt Mask2 = LowBits & Mask; 00428 KnownZero |= ~LowBits & Mask; 00429 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, TD, 00430 Depth+1); 00431 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 00432 break; 00433 } 00434 } 00435 00436 // Since the result is less than or equal to either operand, any leading 00437 // zero bits in either operand must also exist in the result. 00438 APInt AllOnes = APInt::getAllOnesValue(BitWidth); 00439 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne, 00440 TD, Depth+1); 00441 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2, 00442 TD, Depth+1); 00443 00444 unsigned Leaders = std::max(KnownZero.countLeadingOnes(), 00445 KnownZero2.countLeadingOnes()); 00446 KnownOne.clear(); 00447 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask; 00448 break; 00449 } 00450 00451 case Instruction::Alloca: 00452 case Instruction::Malloc: { 00453 AllocationInst *AI = cast<AllocationInst>(V); 00454 unsigned Align = AI->getAlignment(); 00455 if (Align == 0 && TD) { 00456 if (isa<AllocaInst>(AI)) 00457 Align = TD->getABITypeAlignment(AI->getType()->getElementType()); 00458 else if (isa<MallocInst>(AI)) { 00459 // Malloc returns maximally aligned memory. 00460 Align = TD->getABITypeAlignment(AI->getType()->getElementType()); 00461 Align = 00462 std::max(Align, 00463 (unsigned)TD->getABITypeAlignment( 00464 Type::getDoubleTy(V->getContext()))); 00465 Align = 00466 std::max(Align, 00467 (unsigned)TD->getABITypeAlignment( 00468 Type::getInt64Ty(V->getContext()))); 00469 } 00470 } 00471 00472 if (Align > 0) 00473 KnownZero = Mask & APInt::getLowBitsSet(BitWidth, 00474 CountTrailingZeros_32(Align)); 00475 break; 00476 } 00477 case Instruction::GetElementPtr: { 00478 // Analyze all of the subscripts of this getelementptr instruction 00479 // to determine if we can prove known low zero bits. 00480 APInt LocalMask = APInt::getAllOnesValue(BitWidth); 00481 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0); 00482 ComputeMaskedBits(I->getOperand(0), LocalMask, 00483 LocalKnownZero, LocalKnownOne, TD, Depth+1); 00484 unsigned TrailZ = LocalKnownZero.countTrailingOnes(); 00485 00486 gep_type_iterator GTI = gep_type_begin(I); 00487 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) { 00488 Value *Index = I->getOperand(i); 00489 if (const StructType *STy = dyn_cast<StructType>(*GTI)) { 00490 // Handle struct member offset arithmetic. 00491 if (!TD) return; 00492 const StructLayout *SL = TD->getStructLayout(STy); 00493 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue(); 00494 uint64_t Offset = SL->getElementOffset(Idx); 00495 TrailZ = std::min(TrailZ, 00496 CountTrailingZeros_64(Offset)); 00497 } else { 00498 // Handle array index arithmetic. 00499 const Type *IndexedTy = GTI.getIndexedType(); 00500 if (!IndexedTy->isSized()) return; 00501 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits(); 00502 uint64_t TypeSize = TD ? TD->getTypeAllocSize(IndexedTy) : 1; 00503 LocalMask = APInt::getAllOnesValue(GEPOpiBits); 00504 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0); 00505 ComputeMaskedBits(Index, LocalMask, 00506 LocalKnownZero, LocalKnownOne, TD, Depth+1); 00507 TrailZ = std::min(TrailZ, 00508 unsigned(CountTrailingZeros_64(TypeSize) + 00509 LocalKnownZero.countTrailingOnes())); 00510 } 00511 } 00512 00513 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask; 00514 break; 00515 } 00516 case Instruction::PHI: { 00517 PHINode *P = cast<PHINode>(I); 00518 // Handle the case of a simple two-predecessor recurrence PHI. 00519 // There's a lot more that could theoretically be done here, but 00520 // this is sufficient to catch some interesting cases. 00521 if (P->getNumIncomingValues() == 2) { 00522 for (unsigned i = 0; i != 2; ++i) { 00523 Value *L = P->getIncomingValue(i); 00524 Value *R = P->getIncomingValue(!i); 00525 Operator *LU = dyn_cast<Operator>(L); 00526 if (!LU) 00527 continue; 00528 unsigned Opcode = LU->getOpcode(); 00529 // Check for operations that have the property that if 00530 // both their operands have low zero bits, the result 00531 // will have low zero bits. 00532 if (Opcode == Instruction::Add || 00533 Opcode == Instruction::Sub || 00534 Opcode == Instruction::And || 00535 Opcode == Instruction::Or || 00536 Opcode == Instruction::Mul) { 00537 Value *LL = LU->getOperand(0); 00538 Value *LR = LU->getOperand(1); 00539 // Find a recurrence. 00540 if (LL == I) 00541 L = LR; 00542 else if (LR == I) 00543 L = LL; 00544 else 00545 break; 00546 // Ok, we have a PHI of the form L op= R. Check for low 00547 // zero bits. 00548 APInt Mask2 = APInt::getAllOnesValue(BitWidth); 00549 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, TD, Depth+1); 00550 Mask2 = APInt::getLowBitsSet(BitWidth, 00551 KnownZero2.countTrailingOnes()); 00552 00553 // We need to take the minimum number of known bits 00554 APInt KnownZero3(KnownZero), KnownOne3(KnownOne); 00555 ComputeMaskedBits(L, Mask2, KnownZero3, KnownOne3, TD, Depth+1); 00556 00557 KnownZero = Mask & 00558 APInt::getLowBitsSet(BitWidth, 00559 std::min(KnownZero2.countTrailingOnes(), 00560 KnownZero3.countTrailingOnes())); 00561 break; 00562 } 00563 } 00564 } 00565 00566 // Otherwise take the unions of the known bit sets of the operands, 00567 // taking conservative care to avoid excessive recursion. 00568 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) { 00569 KnownZero = APInt::getAllOnesValue(BitWidth); 00570 KnownOne = APInt::getAllOnesValue(BitWidth); 00571 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) { 00572 // Skip direct self references. 00573 if (P->getIncomingValue(i) == P) continue; 00574 00575 KnownZero2 = APInt(BitWidth, 0); 00576 KnownOne2 = APInt(BitWidth, 0); 00577 // Recurse, but cap the recursion to one level, because we don't 00578 // want to waste time spinning around in loops. 00579 ComputeMaskedBits(P->getIncomingValue(i), KnownZero | KnownOne, 00580 KnownZero2, KnownOne2, TD, MaxDepth-1); 00581 KnownZero &= KnownZero2; 00582 KnownOne &= KnownOne2; 00583 // If all bits have been ruled out, there's no need to check 00584 // more operands. 00585 if (!KnownZero && !KnownOne) 00586 break; 00587 } 00588 } 00589 break; 00590 } 00591 case Instruction::Call: 00592 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 00593 switch (II->getIntrinsicID()) { 00594 default: break; 00595 case Intrinsic::ctpop: 00596 case Intrinsic::ctlz: 00597 case Intrinsic::cttz: { 00598 unsigned LowBits = Log2_32(BitWidth)+1; 00599 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits); 00600 break; 00601 } 00602 } 00603 } 00604 break; 00605 } 00606 } 00607 00608 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 00609 /// this predicate to simplify operations downstream. Mask is known to be zero 00610 /// for bits that V cannot have. 00611 bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask, 00612 TargetData *TD, unsigned Depth) { 00613 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0); 00614 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth); 00615 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 00616 return (KnownZero & Mask) == Mask; 00617 } 00618 00619 00620 00621 /// ComputeNumSignBits - Return the number of times the sign bit of the 00622 /// register is replicated into the other bits. We know that at least 1 bit 00623 /// is always equal to the sign bit (itself), but other cases can give us 00624 /// information. For example, immediately after an "ashr X, 2", we know that 00625 /// the top 3 bits are all equal to each other, so we return 3. 00626 /// 00627 /// 'Op' must have a scalar integer type. 00628 /// 00629 unsigned llvm::ComputeNumSignBits(Value *V, TargetData *TD, unsigned Depth) { 00630 assert((TD || V->getType()->isIntOrIntVector()) && 00631 "ComputeNumSignBits requires a TargetData object to operate " 00632 "on non-integer values!"); 00633 const Type *Ty = V->getType(); 00634 unsigned TyBits = TD ? TD->getTypeSizeInBits(V->getType()->getScalarType()) : 00635 Ty->getScalarSizeInBits(); 00636 unsigned Tmp, Tmp2; 00637 unsigned FirstAnswer = 1; 00638 00639 // Note that ConstantInt is handled by the general ComputeMaskedBits case 00640 // below. 00641 00642 if (Depth == 6) 00643 return 1; // Limit search depth. 00644 00645 Operator *U = dyn_cast<Operator>(V); 00646 switch (Operator::getOpcode(V)) { 00647 default: break; 00648 case Instruction::SExt: 00649 Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth(); 00650 return ComputeNumSignBits(U->getOperand(0), TD, Depth+1) + Tmp; 00651 00652 case Instruction::AShr: 00653 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1); 00654 // ashr X, C -> adds C sign bits. 00655 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) { 00656 Tmp += C->getZExtValue(); 00657 if (Tmp > TyBits) Tmp = TyBits; 00658 } 00659 return Tmp; 00660 case Instruction::Shl: 00661 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) { 00662 // shl destroys sign bits. 00663 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1); 00664 if (C->getZExtValue() >= TyBits || // Bad shift. 00665 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out. 00666 return Tmp - C->getZExtValue(); 00667 } 00668 break; 00669 case Instruction::And: 00670 case Instruction::Or: 00671 case Instruction::Xor: // NOT is handled here. 00672 // Logical binary ops preserve the number of sign bits at the worst. 00673 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1); 00674 if (Tmp != 1) { 00675 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1); 00676 FirstAnswer = std::min(Tmp, Tmp2); 00677 // We computed what we know about the sign bits as our first 00678 // answer. Now proceed to the generic code that uses 00679 // ComputeMaskedBits, and pick whichever answer is better. 00680 } 00681 break; 00682 00683 case Instruction::Select: 00684 Tmp = ComputeNumSignBits(U->getOperand(1), TD, Depth+1); 00685 if (Tmp == 1) return 1; // Early out. 00686 Tmp2 = ComputeNumSignBits(U->getOperand(2), TD, Depth+1); 00687 return std::min(Tmp, Tmp2); 00688 00689 case Instruction::Add: 00690 // Add can have at most one carry bit. Thus we know that the output 00691 // is, at worst, one more bit than the inputs. 00692 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1); 00693 if (Tmp == 1) return 1; // Early out. 00694 00695 // Special case decrementing a value (ADD X, -1): 00696 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(1))) 00697 if (CRHS->isAllOnesValue()) { 00698 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0); 00699 APInt Mask = APInt::getAllOnesValue(TyBits); 00700 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, TD, 00701 Depth+1); 00702 00703 // If the input is known to be 0 or 1, the output is 0/-1, which is all 00704 // sign bits set. 00705 if ((KnownZero | APInt(TyBits, 1)) == Mask) 00706 return TyBits; 00707 00708 // If we are subtracting one from a positive number, there is no carry 00709 // out of the result. 00710 if (KnownZero.isNegative()) 00711 return Tmp; 00712 } 00713 00714 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1); 00715 if (Tmp2 == 1) return 1; 00716 return std::min(Tmp, Tmp2)-1; 00717 break; 00718 00719 case Instruction::Sub: 00720 Tmp2 = ComputeNumSignBits(U->getOperand(1), TD, Depth+1); 00721 if (Tmp2 == 1) return 1; 00722 00723 // Handle NEG. 00724 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0))) 00725 if (CLHS->isNullValue()) { 00726 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0); 00727 APInt Mask = APInt::getAllOnesValue(TyBits); 00728 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, 00729 TD, Depth+1); 00730 // If the input is known to be 0 or 1, the output is 0/-1, which is all 00731 // sign bits set. 00732 if ((KnownZero | APInt(TyBits, 1)) == Mask) 00733 return TyBits; 00734 00735 // If the input is known to be positive (the sign bit is known clear), 00736 // the output of the NEG has the same number of sign bits as the input. 00737 if (KnownZero.isNegative()) 00738 return Tmp2; 00739 00740 // Otherwise, we treat this like a SUB. 00741 } 00742 00743 // Sub can have at most one carry bit. Thus we know that the output 00744 // is, at worst, one more bit than the inputs. 00745 Tmp = ComputeNumSignBits(U->getOperand(0), TD, Depth+1); 00746 if (Tmp == 1) return 1; // Early out. 00747 return std::min(Tmp, Tmp2)-1; 00748 break; 00749 case Instruction::Trunc: 00750 // FIXME: it's tricky to do anything useful for this, but it is an important 00751 // case for targets like X86. 00752 break; 00753 } 00754 00755 // Finally, if we can prove that the top bits of the result are 0's or 1's, 00756 // use this information. 00757 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0); 00758 APInt Mask = APInt::getAllOnesValue(TyBits); 00759 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth); 00760 00761 if (KnownZero.isNegative()) { // sign bit is 0 00762 Mask = KnownZero; 00763 } else if (KnownOne.isNegative()) { // sign bit is 1; 00764 Mask = KnownOne; 00765 } else { 00766 // Nothing known. 00767 return FirstAnswer; 00768 } 00769 00770 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine 00771 // the number of identical bits in the top of the input value. 00772 Mask = ~Mask; 00773 Mask <<= Mask.getBitWidth()-TyBits; 00774 // Return # leading zeros. We use 'min' here in case Val was zero before 00775 // shifting. We don't want to return '64' as for an i32 "0". 00776 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros())); 00777 } 00778 00779 /// CannotBeNegativeZero - Return true if we can prove that the specified FP 00780 /// value is never equal to -0.0. 00781 /// 00782 /// NOTE: this function will need to be revisited when we support non-default 00783 /// rounding modes! 00784 /// 00785 bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) { 00786 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) 00787 return !CFP->getValueAPF().isNegZero(); 00788 00789 if (Depth == 6) 00790 return 1; // Limit search depth. 00791 00792 const Operator *I = dyn_cast<Operator>(V); 00793 if (I == 0) return false; 00794 00795 // (add x, 0.0) is guaranteed to return +0.0, not -0.0. 00796 if (I->getOpcode() == Instruction::FAdd && 00797 isa<ConstantFP>(I->getOperand(1)) && 00798 cast<ConstantFP>(I->getOperand(1))->isNullValue()) 00799 return true; 00800 00801 // sitofp and uitofp turn into +0.0 for zero. 00802 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I)) 00803 return true; 00804 00805 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) 00806 // sqrt(-0.0) = -0.0, no other negative results are possible. 00807 if (II->getIntrinsicID() == Intrinsic::sqrt) 00808 return CannotBeNegativeZero(II->getOperand(1), Depth+1); 00809 00810 if (const CallInst *CI = dyn_cast<CallInst>(I)) 00811 if (const Function *F = CI->getCalledFunction()) { 00812 if (F->isDeclaration()) { 00813 // abs(x) != -0.0 00814 if (F->getName() == "abs") return true; 00815 // abs[lf](x) != -0.0 00816 if (F->getName() == "absf") return true; 00817 if (F->getName() == "absl") return true; 00818 } 00819 } 00820 00821 return false; 00822 } 00823 00824 // This is the recursive version of BuildSubAggregate. It takes a few different 00825 // arguments. Idxs is the index within the nested struct From that we are 00826 // looking at now (which is of type IndexedType). IdxSkip is the number of 00827 // indices from Idxs that should be left out when inserting into the resulting 00828 // struct. To is the result struct built so far, new insertvalue instructions 00829 // build on that. 00830 static Value *BuildSubAggregate(Value *From, Value* To, const Type *IndexedType, 00831 SmallVector<unsigned, 10> &Idxs, 00832 unsigned IdxSkip, 00833 LLVMContext &Context, 00834 Instruction *InsertBefore) { 00835 const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType); 00836 if (STy) { 00837 // Save the original To argument so we can modify it 00838 Value *OrigTo = To; 00839 // General case, the type indexed by Idxs is a struct 00840 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 00841 // Process each struct element recursively 00842 Idxs.push_back(i); 00843 Value *PrevTo = To; 00844 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip, 00845 Context, InsertBefore); 00846 Idxs.pop_back(); 00847 if (!To) { 00848 // Couldn't find any inserted value for this index? Cleanup 00849 while (PrevTo != OrigTo) { 00850 InsertValueInst* Del = cast<InsertValueInst>(PrevTo); 00851 PrevTo = Del->getAggregateOperand(); 00852 Del->eraseFromParent(); 00853 } 00854 // Stop processing elements 00855 break; 00856 } 00857 } 00858 // If we succesfully found a value for each of our subaggregates 00859 if (To) 00860 return To; 00861 } 00862 // Base case, the type indexed by SourceIdxs is not a struct, or not all of 00863 // the struct's elements had a value that was inserted directly. In the latter 00864 // case, perhaps we can't determine each of the subelements individually, but 00865 // we might be able to find the complete struct somewhere. 00866 00867 // Find the value that is at that particular spot 00868 Value *V = FindInsertedValue(From, Idxs.begin(), Idxs.end(), Context); 00869 00870 if (!V) 00871 return NULL; 00872 00873 // Insert the value in the new (sub) aggregrate 00874 return llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip, 00875 Idxs.end(), "tmp", InsertBefore); 00876 } 00877 00878 // This helper takes a nested struct and extracts a part of it (which is again a 00879 // struct) into a new value. For example, given the struct: 00880 // { a, { b, { c, d }, e } } 00881 // and the indices "1, 1" this returns 00882 // { c, d }. 00883 // 00884 // It does this by inserting an insertvalue for each element in the resulting 00885 // struct, as opposed to just inserting a single struct. This will only work if 00886 // each of the elements of the substruct are known (ie, inserted into From by an 00887 // insertvalue instruction somewhere). 00888 // 00889 // All inserted insertvalue instructions are inserted before InsertBefore 00890 static Value *BuildSubAggregate(Value *From, const unsigned *idx_begin, 00891 const unsigned *idx_end, LLVMContext &Context, 00892 Instruction *InsertBefore) { 00893 assert(InsertBefore && "Must have someplace to insert!"); 00894 const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(), 00895 idx_begin, 00896 idx_end); 00897 Value *To = UndefValue::get(IndexedType); 00898 SmallVector<unsigned, 10> Idxs(idx_begin, idx_end); 00899 unsigned IdxSkip = Idxs.size(); 00900 00901 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, 00902 Context, InsertBefore); 00903 } 00904 00905 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if 00906 /// the scalar value indexed is already around as a register, for example if it 00907 /// were inserted directly into the aggregrate. 00908 /// 00909 /// If InsertBefore is not null, this function will duplicate (modified) 00910 /// insertvalues when a part of a nested struct is extracted. 00911 Value *llvm::FindInsertedValue(Value *V, const unsigned *idx_begin, 00912 const unsigned *idx_end, LLVMContext &Context, 00913 Instruction *InsertBefore) { 00914 // Nothing to index? Just return V then (this is useful at the end of our 00915 // recursion) 00916 if (idx_begin == idx_end) 00917 return V; 00918 // We have indices, so V should have an indexable type 00919 assert((isa<StructType>(V->getType()) || isa<ArrayType>(V->getType())) 00920 && "Not looking at a struct or array?"); 00921 assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end) 00922 && "Invalid indices for type?"); 00923 const CompositeType *PTy = cast<CompositeType>(V->getType()); 00924 00925 if (isa<UndefValue>(V)) 00926 return UndefValue::get(ExtractValueInst::getIndexedType(PTy, 00927 idx_begin, 00928 idx_end)); 00929 else if (isa<ConstantAggregateZero>(V)) 00930 return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy, 00931 idx_begin, 00932 idx_end)); 00933 else if (Constant *C = dyn_cast<Constant>(V)) { 00934 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) 00935 // Recursively process this constant 00936 return FindInsertedValue(C->getOperand(*idx_begin), idx_begin + 1, 00937 idx_end, Context, InsertBefore); 00938 } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) { 00939 // Loop the indices for the insertvalue instruction in parallel with the 00940 // requested indices 00941 const unsigned *req_idx = idx_begin; 00942 for (const unsigned *i = I->idx_begin(), *e = I->idx_end(); 00943 i != e; ++i, ++req_idx) { 00944 if (req_idx == idx_end) { 00945 if (InsertBefore) 00946 // The requested index identifies a part of a nested aggregate. Handle 00947 // this specially. For example, 00948 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0 00949 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1 00950 // %C = extractvalue {i32, { i32, i32 } } %B, 1 00951 // This can be changed into 00952 // %A = insertvalue {i32, i32 } undef, i32 10, 0 00953 // %C = insertvalue {i32, i32 } %A, i32 11, 1 00954 // which allows the unused 0,0 element from the nested struct to be 00955 // removed. 00956 return BuildSubAggregate(V, idx_begin, req_idx, 00957 Context, InsertBefore); 00958 else 00959 // We can't handle this without inserting insertvalues 00960 return 0; 00961 } 00962 00963 // This insert value inserts something else than what we are looking for. 00964 // See if the (aggregrate) value inserted into has the value we are 00965 // looking for, then. 00966 if (*req_idx != *i) 00967 return FindInsertedValue(I->getAggregateOperand(), idx_begin, idx_end, 00968 Context, InsertBefore); 00969 } 00970 // If we end up here, the indices of the insertvalue match with those 00971 // requested (though possibly only partially). Now we recursively look at 00972 // the inserted value, passing any remaining indices. 00973 return FindInsertedValue(I->getInsertedValueOperand(), req_idx, idx_end, 00974 Context, InsertBefore); 00975 } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) { 00976 // If we're extracting a value from an aggregrate that was extracted from 00977 // something else, we can extract from that something else directly instead. 00978 // However, we will need to chain I's indices with the requested indices. 00979 00980 // Calculate the number of indices required 00981 unsigned size = I->getNumIndices() + (idx_end - idx_begin); 00982 // Allocate some space to put the new indices in 00983 SmallVector<unsigned, 5> Idxs; 00984 Idxs.reserve(size); 00985 // Add indices from the extract value instruction 00986 for (const unsigned *i = I->idx_begin(), *e = I->idx_end(); 00987 i != e; ++i) 00988 Idxs.push_back(*i); 00989 00990 // Add requested indices 00991 for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i) 00992 Idxs.push_back(*i); 00993 00994 assert(Idxs.size() == size 00995 && "Number of indices added not correct?"); 00996 00997 return FindInsertedValue(I->getAggregateOperand(), Idxs.begin(), Idxs.end(), 00998 Context, InsertBefore); 00999 } 01000 // Otherwise, we don't know (such as, extracting from a function return value 01001 // or load instruction) 01002 return 0; 01003 } 01004 01005 /// GetConstantStringInfo - This function computes the length of a 01006 /// null-terminated C string pointed to by V. If successful, it returns true 01007 /// and returns the string in Str. If unsuccessful, it returns false. 01008 bool llvm::GetConstantStringInfo(Value *V, std::string &Str, uint64_t Offset, 01009 bool StopAtNul) { 01010 // If V is NULL then return false; 01011 if (V == NULL) return false; 01012 01013 // Look through bitcast instructions. 01014 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) 01015 return GetConstantStringInfo(BCI->getOperand(0), Str, Offset, StopAtNul); 01016 01017 // If the value is not a GEP instruction nor a constant expression with a 01018 // GEP instruction, then return false because ConstantArray can't occur 01019 // any other way 01020 User *GEP = 0; 01021 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) { 01022 GEP = GEPI; 01023 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { 01024 if (CE->getOpcode() == Instruction::BitCast) 01025 return GetConstantStringInfo(CE->getOperand(0), Str, Offset, StopAtNul); 01026 if (CE->getOpcode() != Instruction::GetElementPtr) 01027 return false; 01028 GEP = CE; 01029 } 01030 01031 if (GEP) { 01032 // Make sure the GEP has exactly three arguments. 01033 if (GEP->getNumOperands() != 3) 01034 return false; 01035 01036 // Make sure the index-ee is a pointer to array of i8. 01037 const PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType()); 01038 const ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType()); 01039 if (AT == 0 || AT->getElementType() != Type::getInt8Ty(V->getContext())) 01040 return false; 01041 01042 // Check to make sure that the first operand of the GEP is an integer and 01043 // has value 0 so that we are sure we're indexing into the initializer. 01044 ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1)); 01045 if (FirstIdx == 0 || !FirstIdx->isZero()) 01046 return false; 01047 01048 // If the second index isn't a ConstantInt, then this is a variable index 01049 // into the array. If this occurs, we can't say anything meaningful about 01050 // the string. 01051 uint64_t StartIdx = 0; 01052 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2))) 01053 StartIdx = CI->getZExtValue(); 01054 else 01055 return false; 01056 return GetConstantStringInfo(GEP->getOperand(0), Str, StartIdx+Offset, 01057 StopAtNul); 01058 } 01059 01060 // The GEP instruction, constant or instruction, must reference a global 01061 // variable that is a constant and is initialized. The referenced constant 01062 // initializer is the array that we'll use for optimization. 01063 GlobalVariable* GV = dyn_cast<GlobalVariable>(V); 01064 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer()) 01065 return false; 01066 Constant *GlobalInit = GV->getInitializer(); 01067 01068 // Handle the ConstantAggregateZero case 01069 if (isa<ConstantAggregateZero>(GlobalInit)) { 01070 // This is a degenerate case. The initializer is constant zero so the 01071 // length of the string must be zero. 01072 Str.clear(); 01073 return true; 01074 } 01075 01076 // Must be a Constant Array 01077 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit); 01078 if (Array == 0 || 01079 Array->getType()->getElementType() != Type::getInt8Ty(V->getContext())) 01080 return false; 01081 01082 // Get the number of elements in the array 01083 uint64_t NumElts = Array->getType()->getNumElements(); 01084 01085 if (Offset > NumElts) 01086 return false; 01087 01088 // Traverse the constant array from 'Offset' which is the place the GEP refers 01089 // to in the array. 01090 Str.reserve(NumElts-Offset); 01091 for (unsigned i = Offset; i != NumElts; ++i) { 01092 Constant *Elt = Array->getOperand(i); 01093 ConstantInt *CI = dyn_cast<ConstantInt>(Elt); 01094 if (!CI) // This array isn't suitable, non-int initializer. 01095 return false; 01096 if (StopAtNul && CI->isZero()) 01097 return true; // we found end of string, success! 01098 Str += (char)CI->getZExtValue(); 01099 } 01100 01101 // The array isn't null terminated, but maybe this is a memcpy, not a strcpy. 01102 return true; 01103 }