LLVM API Documentation
00001 //===- ConstantFold.cpp - LLVM constant folder ----------------------------===// 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 implements folding of constants for LLVM. This implements the 00011 // (internal) ConstantFold.h interface, which is used by the 00012 // ConstantExpr::get* methods to automatically fold constants when possible. 00013 // 00014 // The current constant folding implementation is implemented in two pieces: the 00015 // pieces that don't need DataLayout, and the pieces that do. This is to avoid 00016 // a dependence in IR on Target. 00017 // 00018 //===----------------------------------------------------------------------===// 00019 00020 #include "ConstantFold.h" 00021 #include "llvm/ADT/SmallVector.h" 00022 #include "llvm/IR/Constants.h" 00023 #include "llvm/IR/DerivedTypes.h" 00024 #include "llvm/IR/Function.h" 00025 #include "llvm/IR/GlobalAlias.h" 00026 #include "llvm/IR/GlobalVariable.h" 00027 #include "llvm/IR/Instructions.h" 00028 #include "llvm/IR/Operator.h" 00029 #include "llvm/Support/Compiler.h" 00030 #include "llvm/Support/ErrorHandling.h" 00031 #include "llvm/Support/GetElementPtrTypeIterator.h" 00032 #include "llvm/Support/ManagedStatic.h" 00033 #include "llvm/Support/MathExtras.h" 00034 #include <limits> 00035 using namespace llvm; 00036 00037 //===----------------------------------------------------------------------===// 00038 // ConstantFold*Instruction Implementations 00039 //===----------------------------------------------------------------------===// 00040 00041 /// BitCastConstantVector - Convert the specified vector Constant node to the 00042 /// specified vector type. At this point, we know that the elements of the 00043 /// input vector constant are all simple integer or FP values. 00044 static Constant *BitCastConstantVector(Constant *CV, VectorType *DstTy) { 00045 00046 if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy); 00047 if (CV->isNullValue()) return Constant::getNullValue(DstTy); 00048 00049 // If this cast changes element count then we can't handle it here: 00050 // doing so requires endianness information. This should be handled by 00051 // Analysis/ConstantFolding.cpp 00052 unsigned NumElts = DstTy->getNumElements(); 00053 if (NumElts != CV->getType()->getVectorNumElements()) 00054 return 0; 00055 00056 Type *DstEltTy = DstTy->getElementType(); 00057 00058 SmallVector<Constant*, 16> Result; 00059 Type *Ty = IntegerType::get(CV->getContext(), 32); 00060 for (unsigned i = 0; i != NumElts; ++i) { 00061 Constant *C = 00062 ConstantExpr::getExtractElement(CV, ConstantInt::get(Ty, i)); 00063 C = ConstantExpr::getBitCast(C, DstEltTy); 00064 Result.push_back(C); 00065 } 00066 00067 return ConstantVector::get(Result); 00068 } 00069 00070 /// This function determines which opcode to use to fold two constant cast 00071 /// expressions together. It uses CastInst::isEliminableCastPair to determine 00072 /// the opcode. Consequently its just a wrapper around that function. 00073 /// @brief Determine if it is valid to fold a cast of a cast 00074 static unsigned 00075 foldConstantCastPair( 00076 unsigned opc, ///< opcode of the second cast constant expression 00077 ConstantExpr *Op, ///< the first cast constant expression 00078 Type *DstTy ///< desintation type of the first cast 00079 ) { 00080 assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!"); 00081 assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type"); 00082 assert(CastInst::isCast(opc) && "Invalid cast opcode"); 00083 00084 // The the types and opcodes for the two Cast constant expressions 00085 Type *SrcTy = Op->getOperand(0)->getType(); 00086 Type *MidTy = Op->getType(); 00087 Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode()); 00088 Instruction::CastOps secondOp = Instruction::CastOps(opc); 00089 00090 // Assume that pointers are never more than 64 bits wide. 00091 IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext()); 00092 00093 // Let CastInst::isEliminableCastPair do the heavy lifting. 00094 return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy, 00095 FakeIntPtrTy, FakeIntPtrTy, 00096 FakeIntPtrTy); 00097 } 00098 00099 static Constant *FoldBitCast(Constant *V, Type *DestTy) { 00100 Type *SrcTy = V->getType(); 00101 if (SrcTy == DestTy) 00102 return V; // no-op cast 00103 00104 // Check to see if we are casting a pointer to an aggregate to a pointer to 00105 // the first element. If so, return the appropriate GEP instruction. 00106 if (PointerType *PTy = dyn_cast<PointerType>(V->getType())) 00107 if (PointerType *DPTy = dyn_cast<PointerType>(DestTy)) 00108 if (PTy->getAddressSpace() == DPTy->getAddressSpace() 00109 && DPTy->getElementType()->isSized()) { 00110 SmallVector<Value*, 8> IdxList; 00111 Value *Zero = 00112 Constant::getNullValue(Type::getInt32Ty(DPTy->getContext())); 00113 IdxList.push_back(Zero); 00114 Type *ElTy = PTy->getElementType(); 00115 while (ElTy != DPTy->getElementType()) { 00116 if (StructType *STy = dyn_cast<StructType>(ElTy)) { 00117 if (STy->getNumElements() == 0) break; 00118 ElTy = STy->getElementType(0); 00119 IdxList.push_back(Zero); 00120 } else if (SequentialType *STy = 00121 dyn_cast<SequentialType>(ElTy)) { 00122 if (ElTy->isPointerTy()) break; // Can't index into pointers! 00123 ElTy = STy->getElementType(); 00124 IdxList.push_back(Zero); 00125 } else { 00126 break; 00127 } 00128 } 00129 00130 if (ElTy == DPTy->getElementType()) 00131 // This GEP is inbounds because all indices are zero. 00132 return ConstantExpr::getInBoundsGetElementPtr(V, IdxList); 00133 } 00134 00135 // Handle casts from one vector constant to another. We know that the src 00136 // and dest type have the same size (otherwise its an illegal cast). 00137 if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) { 00138 if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) { 00139 assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() && 00140 "Not cast between same sized vectors!"); 00141 SrcTy = NULL; 00142 // First, check for null. Undef is already handled. 00143 if (isa<ConstantAggregateZero>(V)) 00144 return Constant::getNullValue(DestTy); 00145 00146 // Handle ConstantVector and ConstantAggregateVector. 00147 return BitCastConstantVector(V, DestPTy); 00148 } 00149 00150 // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts 00151 // This allows for other simplifications (although some of them 00152 // can only be handled by Analysis/ConstantFolding.cpp). 00153 if (isa<ConstantInt>(V) || isa<ConstantFP>(V)) 00154 return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy); 00155 } 00156 00157 // Finally, implement bitcast folding now. The code below doesn't handle 00158 // bitcast right. 00159 if (isa<ConstantPointerNull>(V)) // ptr->ptr cast. 00160 return ConstantPointerNull::get(cast<PointerType>(DestTy)); 00161 00162 // Handle integral constant input. 00163 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 00164 if (DestTy->isIntegerTy()) 00165 // Integral -> Integral. This is a no-op because the bit widths must 00166 // be the same. Consequently, we just fold to V. 00167 return V; 00168 00169 if (DestTy->isFloatingPointTy()) 00170 return ConstantFP::get(DestTy->getContext(), 00171 APFloat(DestTy->getFltSemantics(), 00172 CI->getValue())); 00173 00174 // Otherwise, can't fold this (vector?) 00175 return 0; 00176 } 00177 00178 // Handle ConstantFP input: FP -> Integral. 00179 if (ConstantFP *FP = dyn_cast<ConstantFP>(V)) 00180 return ConstantInt::get(FP->getContext(), 00181 FP->getValueAPF().bitcastToAPInt()); 00182 00183 return 0; 00184 } 00185 00186 00187 /// ExtractConstantBytes - V is an integer constant which only has a subset of 00188 /// its bytes used. The bytes used are indicated by ByteStart (which is the 00189 /// first byte used, counting from the least significant byte) and ByteSize, 00190 /// which is the number of bytes used. 00191 /// 00192 /// This function analyzes the specified constant to see if the specified byte 00193 /// range can be returned as a simplified constant. If so, the constant is 00194 /// returned, otherwise null is returned. 00195 /// 00196 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart, 00197 unsigned ByteSize) { 00198 assert(C->getType()->isIntegerTy() && 00199 (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 && 00200 "Non-byte sized integer input"); 00201 unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8; 00202 assert(ByteSize && "Must be accessing some piece"); 00203 assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input"); 00204 assert(ByteSize != CSize && "Should not extract everything"); 00205 00206 // Constant Integers are simple. 00207 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) { 00208 APInt V = CI->getValue(); 00209 if (ByteStart) 00210 V = V.lshr(ByteStart*8); 00211 V = V.trunc(ByteSize*8); 00212 return ConstantInt::get(CI->getContext(), V); 00213 } 00214 00215 // In the input is a constant expr, we might be able to recursively simplify. 00216 // If not, we definitely can't do anything. 00217 ConstantExpr *CE = dyn_cast<ConstantExpr>(C); 00218 if (CE == 0) return 0; 00219 00220 switch (CE->getOpcode()) { 00221 default: return 0; 00222 case Instruction::Or: { 00223 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize); 00224 if (RHS == 0) 00225 return 0; 00226 00227 // X | -1 -> -1. 00228 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) 00229 if (RHSC->isAllOnesValue()) 00230 return RHSC; 00231 00232 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize); 00233 if (LHS == 0) 00234 return 0; 00235 return ConstantExpr::getOr(LHS, RHS); 00236 } 00237 case Instruction::And: { 00238 Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize); 00239 if (RHS == 0) 00240 return 0; 00241 00242 // X & 0 -> 0. 00243 if (RHS->isNullValue()) 00244 return RHS; 00245 00246 Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize); 00247 if (LHS == 0) 00248 return 0; 00249 return ConstantExpr::getAnd(LHS, RHS); 00250 } 00251 case Instruction::LShr: { 00252 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1)); 00253 if (Amt == 0) 00254 return 0; 00255 unsigned ShAmt = Amt->getZExtValue(); 00256 // Cannot analyze non-byte shifts. 00257 if ((ShAmt & 7) != 0) 00258 return 0; 00259 ShAmt >>= 3; 00260 00261 // If the extract is known to be all zeros, return zero. 00262 if (ByteStart >= CSize-ShAmt) 00263 return Constant::getNullValue(IntegerType::get(CE->getContext(), 00264 ByteSize*8)); 00265 // If the extract is known to be fully in the input, extract it. 00266 if (ByteStart+ByteSize+ShAmt <= CSize) 00267 return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize); 00268 00269 // TODO: Handle the 'partially zero' case. 00270 return 0; 00271 } 00272 00273 case Instruction::Shl: { 00274 ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1)); 00275 if (Amt == 0) 00276 return 0; 00277 unsigned ShAmt = Amt->getZExtValue(); 00278 // Cannot analyze non-byte shifts. 00279 if ((ShAmt & 7) != 0) 00280 return 0; 00281 ShAmt >>= 3; 00282 00283 // If the extract is known to be all zeros, return zero. 00284 if (ByteStart+ByteSize <= ShAmt) 00285 return Constant::getNullValue(IntegerType::get(CE->getContext(), 00286 ByteSize*8)); 00287 // If the extract is known to be fully in the input, extract it. 00288 if (ByteStart >= ShAmt) 00289 return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize); 00290 00291 // TODO: Handle the 'partially zero' case. 00292 return 0; 00293 } 00294 00295 case Instruction::ZExt: { 00296 unsigned SrcBitSize = 00297 cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth(); 00298 00299 // If extracting something that is completely zero, return 0. 00300 if (ByteStart*8 >= SrcBitSize) 00301 return Constant::getNullValue(IntegerType::get(CE->getContext(), 00302 ByteSize*8)); 00303 00304 // If exactly extracting the input, return it. 00305 if (ByteStart == 0 && ByteSize*8 == SrcBitSize) 00306 return CE->getOperand(0); 00307 00308 // If extracting something completely in the input, if if the input is a 00309 // multiple of 8 bits, recurse. 00310 if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize) 00311 return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize); 00312 00313 // Otherwise, if extracting a subset of the input, which is not multiple of 00314 // 8 bits, do a shift and trunc to get the bits. 00315 if ((ByteStart+ByteSize)*8 < SrcBitSize) { 00316 assert((SrcBitSize&7) && "Shouldn't get byte sized case here"); 00317 Constant *Res = CE->getOperand(0); 00318 if (ByteStart) 00319 Res = ConstantExpr::getLShr(Res, 00320 ConstantInt::get(Res->getType(), ByteStart*8)); 00321 return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(), 00322 ByteSize*8)); 00323 } 00324 00325 // TODO: Handle the 'partially zero' case. 00326 return 0; 00327 } 00328 } 00329 } 00330 00331 /// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof 00332 /// on Ty, with any known factors factored out. If Folded is false, 00333 /// return null if no factoring was possible, to avoid endlessly 00334 /// bouncing an unfoldable expression back into the top-level folder. 00335 /// 00336 static Constant *getFoldedSizeOf(Type *Ty, Type *DestTy, 00337 bool Folded) { 00338 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 00339 Constant *N = ConstantInt::get(DestTy, ATy->getNumElements()); 00340 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true); 00341 return ConstantExpr::getNUWMul(E, N); 00342 } 00343 00344 if (StructType *STy = dyn_cast<StructType>(Ty)) 00345 if (!STy->isPacked()) { 00346 unsigned NumElems = STy->getNumElements(); 00347 // An empty struct has size zero. 00348 if (NumElems == 0) 00349 return ConstantExpr::getNullValue(DestTy); 00350 // Check for a struct with all members having the same size. 00351 Constant *MemberSize = 00352 getFoldedSizeOf(STy->getElementType(0), DestTy, true); 00353 bool AllSame = true; 00354 for (unsigned i = 1; i != NumElems; ++i) 00355 if (MemberSize != 00356 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) { 00357 AllSame = false; 00358 break; 00359 } 00360 if (AllSame) { 00361 Constant *N = ConstantInt::get(DestTy, NumElems); 00362 return ConstantExpr::getNUWMul(MemberSize, N); 00363 } 00364 } 00365 00366 // Pointer size doesn't depend on the pointee type, so canonicalize them 00367 // to an arbitrary pointee. 00368 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) 00369 if (!PTy->getElementType()->isIntegerTy(1)) 00370 return 00371 getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1), 00372 PTy->getAddressSpace()), 00373 DestTy, true); 00374 00375 // If there's no interesting folding happening, bail so that we don't create 00376 // a constant that looks like it needs folding but really doesn't. 00377 if (!Folded) 00378 return 0; 00379 00380 // Base case: Get a regular sizeof expression. 00381 Constant *C = ConstantExpr::getSizeOf(Ty); 00382 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 00383 DestTy, false), 00384 C, DestTy); 00385 return C; 00386 } 00387 00388 /// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof 00389 /// on Ty, with any known factors factored out. If Folded is false, 00390 /// return null if no factoring was possible, to avoid endlessly 00391 /// bouncing an unfoldable expression back into the top-level folder. 00392 /// 00393 static Constant *getFoldedAlignOf(Type *Ty, Type *DestTy, 00394 bool Folded) { 00395 // The alignment of an array is equal to the alignment of the 00396 // array element. Note that this is not always true for vectors. 00397 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 00398 Constant *C = ConstantExpr::getAlignOf(ATy->getElementType()); 00399 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 00400 DestTy, 00401 false), 00402 C, DestTy); 00403 return C; 00404 } 00405 00406 if (StructType *STy = dyn_cast<StructType>(Ty)) { 00407 // Packed structs always have an alignment of 1. 00408 if (STy->isPacked()) 00409 return ConstantInt::get(DestTy, 1); 00410 00411 // Otherwise, struct alignment is the maximum alignment of any member. 00412 // Without target data, we can't compare much, but we can check to see 00413 // if all the members have the same alignment. 00414 unsigned NumElems = STy->getNumElements(); 00415 // An empty struct has minimal alignment. 00416 if (NumElems == 0) 00417 return ConstantInt::get(DestTy, 1); 00418 // Check for a struct with all members having the same alignment. 00419 Constant *MemberAlign = 00420 getFoldedAlignOf(STy->getElementType(0), DestTy, true); 00421 bool AllSame = true; 00422 for (unsigned i = 1; i != NumElems; ++i) 00423 if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) { 00424 AllSame = false; 00425 break; 00426 } 00427 if (AllSame) 00428 return MemberAlign; 00429 } 00430 00431 // Pointer alignment doesn't depend on the pointee type, so canonicalize them 00432 // to an arbitrary pointee. 00433 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) 00434 if (!PTy->getElementType()->isIntegerTy(1)) 00435 return 00436 getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(), 00437 1), 00438 PTy->getAddressSpace()), 00439 DestTy, true); 00440 00441 // If there's no interesting folding happening, bail so that we don't create 00442 // a constant that looks like it needs folding but really doesn't. 00443 if (!Folded) 00444 return 0; 00445 00446 // Base case: Get a regular alignof expression. 00447 Constant *C = ConstantExpr::getAlignOf(Ty); 00448 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 00449 DestTy, false), 00450 C, DestTy); 00451 return C; 00452 } 00453 00454 /// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof 00455 /// on Ty and FieldNo, with any known factors factored out. If Folded is false, 00456 /// return null if no factoring was possible, to avoid endlessly 00457 /// bouncing an unfoldable expression back into the top-level folder. 00458 /// 00459 static Constant *getFoldedOffsetOf(Type *Ty, Constant *FieldNo, 00460 Type *DestTy, 00461 bool Folded) { 00462 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 00463 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false, 00464 DestTy, false), 00465 FieldNo, DestTy); 00466 Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true); 00467 return ConstantExpr::getNUWMul(E, N); 00468 } 00469 00470 if (StructType *STy = dyn_cast<StructType>(Ty)) 00471 if (!STy->isPacked()) { 00472 unsigned NumElems = STy->getNumElements(); 00473 // An empty struct has no members. 00474 if (NumElems == 0) 00475 return 0; 00476 // Check for a struct with all members having the same size. 00477 Constant *MemberSize = 00478 getFoldedSizeOf(STy->getElementType(0), DestTy, true); 00479 bool AllSame = true; 00480 for (unsigned i = 1; i != NumElems; ++i) 00481 if (MemberSize != 00482 getFoldedSizeOf(STy->getElementType(i), DestTy, true)) { 00483 AllSame = false; 00484 break; 00485 } 00486 if (AllSame) { 00487 Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, 00488 false, 00489 DestTy, 00490 false), 00491 FieldNo, DestTy); 00492 return ConstantExpr::getNUWMul(MemberSize, N); 00493 } 00494 } 00495 00496 // If there's no interesting folding happening, bail so that we don't create 00497 // a constant that looks like it needs folding but really doesn't. 00498 if (!Folded) 00499 return 0; 00500 00501 // Base case: Get a regular offsetof expression. 00502 Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo); 00503 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 00504 DestTy, false), 00505 C, DestTy); 00506 return C; 00507 } 00508 00509 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V, 00510 Type *DestTy) { 00511 if (isa<UndefValue>(V)) { 00512 // zext(undef) = 0, because the top bits will be zero. 00513 // sext(undef) = 0, because the top bits will all be the same. 00514 // [us]itofp(undef) = 0, because the result value is bounded. 00515 if (opc == Instruction::ZExt || opc == Instruction::SExt || 00516 opc == Instruction::UIToFP || opc == Instruction::SIToFP) 00517 return Constant::getNullValue(DestTy); 00518 return UndefValue::get(DestTy); 00519 } 00520 00521 if (V->isNullValue() && !DestTy->isX86_MMXTy()) 00522 return Constant::getNullValue(DestTy); 00523 00524 // If the cast operand is a constant expression, there's a few things we can 00525 // do to try to simplify it. 00526 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { 00527 if (CE->isCast()) { 00528 // Try hard to fold cast of cast because they are often eliminable. 00529 if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy)) 00530 return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy); 00531 } else if (CE->getOpcode() == Instruction::GetElementPtr) { 00532 // If all of the indexes in the GEP are null values, there is no pointer 00533 // adjustment going on. We might as well cast the source pointer. 00534 bool isAllNull = true; 00535 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i) 00536 if (!CE->getOperand(i)->isNullValue()) { 00537 isAllNull = false; 00538 break; 00539 } 00540 if (isAllNull) 00541 // This is casting one pointer type to another, always BitCast 00542 return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy); 00543 } 00544 } 00545 00546 // If the cast operand is a constant vector, perform the cast by 00547 // operating on each element. In the cast of bitcasts, the element 00548 // count may be mismatched; don't attempt to handle that here. 00549 if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) && 00550 DestTy->isVectorTy() && 00551 DestTy->getVectorNumElements() == V->getType()->getVectorNumElements()) { 00552 SmallVector<Constant*, 16> res; 00553 VectorType *DestVecTy = cast<VectorType>(DestTy); 00554 Type *DstEltTy = DestVecTy->getElementType(); 00555 Type *Ty = IntegerType::get(V->getContext(), 32); 00556 for (unsigned i = 0, e = V->getType()->getVectorNumElements(); i != e; ++i) { 00557 Constant *C = 00558 ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i)); 00559 res.push_back(ConstantExpr::getCast(opc, C, DstEltTy)); 00560 } 00561 return ConstantVector::get(res); 00562 } 00563 00564 // We actually have to do a cast now. Perform the cast according to the 00565 // opcode specified. 00566 switch (opc) { 00567 default: 00568 llvm_unreachable("Failed to cast constant expression"); 00569 case Instruction::FPTrunc: 00570 case Instruction::FPExt: 00571 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) { 00572 bool ignored; 00573 APFloat Val = FPC->getValueAPF(); 00574 Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf : 00575 DestTy->isFloatTy() ? APFloat::IEEEsingle : 00576 DestTy->isDoubleTy() ? APFloat::IEEEdouble : 00577 DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended : 00578 DestTy->isFP128Ty() ? APFloat::IEEEquad : 00579 DestTy->isPPC_FP128Ty() ? APFloat::PPCDoubleDouble : 00580 APFloat::Bogus, 00581 APFloat::rmNearestTiesToEven, &ignored); 00582 return ConstantFP::get(V->getContext(), Val); 00583 } 00584 return 0; // Can't fold. 00585 case Instruction::FPToUI: 00586 case Instruction::FPToSI: 00587 if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) { 00588 const APFloat &V = FPC->getValueAPF(); 00589 bool ignored; 00590 uint64_t x[2]; 00591 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth(); 00592 (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI, 00593 APFloat::rmTowardZero, &ignored); 00594 APInt Val(DestBitWidth, x); 00595 return ConstantInt::get(FPC->getContext(), Val); 00596 } 00597 return 0; // Can't fold. 00598 case Instruction::IntToPtr: //always treated as unsigned 00599 if (V->isNullValue()) // Is it an integral null value? 00600 return ConstantPointerNull::get(cast<PointerType>(DestTy)); 00601 return 0; // Other pointer types cannot be casted 00602 case Instruction::PtrToInt: // always treated as unsigned 00603 // Is it a null pointer value? 00604 if (V->isNullValue()) 00605 return ConstantInt::get(DestTy, 0); 00606 // If this is a sizeof-like expression, pull out multiplications by 00607 // known factors to expose them to subsequent folding. If it's an 00608 // alignof-like expression, factor out known factors. 00609 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 00610 if (CE->getOpcode() == Instruction::GetElementPtr && 00611 CE->getOperand(0)->isNullValue()) { 00612 Type *Ty = 00613 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 00614 if (CE->getNumOperands() == 2) { 00615 // Handle a sizeof-like expression. 00616 Constant *Idx = CE->getOperand(1); 00617 bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne(); 00618 if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) { 00619 Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true, 00620 DestTy, false), 00621 Idx, DestTy); 00622 return ConstantExpr::getMul(C, Idx); 00623 } 00624 } else if (CE->getNumOperands() == 3 && 00625 CE->getOperand(1)->isNullValue()) { 00626 // Handle an alignof-like expression. 00627 if (StructType *STy = dyn_cast<StructType>(Ty)) 00628 if (!STy->isPacked()) { 00629 ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2)); 00630 if (CI->isOne() && 00631 STy->getNumElements() == 2 && 00632 STy->getElementType(0)->isIntegerTy(1)) { 00633 return getFoldedAlignOf(STy->getElementType(1), DestTy, false); 00634 } 00635 } 00636 // Handle an offsetof-like expression. 00637 if (Ty->isStructTy() || Ty->isArrayTy()) { 00638 if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2), 00639 DestTy, false)) 00640 return C; 00641 } 00642 } 00643 } 00644 // Other pointer types cannot be casted 00645 return 0; 00646 case Instruction::UIToFP: 00647 case Instruction::SIToFP: 00648 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 00649 APInt api = CI->getValue(); 00650 APFloat apf(DestTy->getFltSemantics(), 00651 APInt::getNullValue(DestTy->getPrimitiveSizeInBits())); 00652 (void)apf.convertFromAPInt(api, 00653 opc==Instruction::SIToFP, 00654 APFloat::rmNearestTiesToEven); 00655 return ConstantFP::get(V->getContext(), apf); 00656 } 00657 return 0; 00658 case Instruction::ZExt: 00659 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 00660 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth(); 00661 return ConstantInt::get(V->getContext(), 00662 CI->getValue().zext(BitWidth)); 00663 } 00664 return 0; 00665 case Instruction::SExt: 00666 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 00667 uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth(); 00668 return ConstantInt::get(V->getContext(), 00669 CI->getValue().sext(BitWidth)); 00670 } 00671 return 0; 00672 case Instruction::Trunc: { 00673 uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth(); 00674 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 00675 return ConstantInt::get(V->getContext(), 00676 CI->getValue().trunc(DestBitWidth)); 00677 } 00678 00679 // The input must be a constantexpr. See if we can simplify this based on 00680 // the bytes we are demanding. Only do this if the source and dest are an 00681 // even multiple of a byte. 00682 if ((DestBitWidth & 7) == 0 && 00683 (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0) 00684 if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8)) 00685 return Res; 00686 00687 return 0; 00688 } 00689 case Instruction::BitCast: 00690 return FoldBitCast(V, DestTy); 00691 } 00692 } 00693 00694 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond, 00695 Constant *V1, Constant *V2) { 00696 // Check for i1 and vector true/false conditions. 00697 if (Cond->isNullValue()) return V2; 00698 if (Cond->isAllOnesValue()) return V1; 00699 00700 // If the condition is a vector constant, fold the result elementwise. 00701 if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) { 00702 SmallVector<Constant*, 16> Result; 00703 Type *Ty = IntegerType::get(CondV->getContext(), 32); 00704 for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){ 00705 ConstantInt *Cond = dyn_cast<ConstantInt>(CondV->getOperand(i)); 00706 if (Cond == 0) break; 00707 00708 Constant *V = Cond->isNullValue() ? V2 : V1; 00709 Constant *Res = ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i)); 00710 Result.push_back(Res); 00711 } 00712 00713 // If we were able to build the vector, return it. 00714 if (Result.size() == V1->getType()->getVectorNumElements()) 00715 return ConstantVector::get(Result); 00716 } 00717 00718 if (isa<UndefValue>(Cond)) { 00719 if (isa<UndefValue>(V1)) return V1; 00720 return V2; 00721 } 00722 if (isa<UndefValue>(V1)) return V2; 00723 if (isa<UndefValue>(V2)) return V1; 00724 if (V1 == V2) return V1; 00725 00726 if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) { 00727 if (TrueVal->getOpcode() == Instruction::Select) 00728 if (TrueVal->getOperand(0) == Cond) 00729 return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2); 00730 } 00731 if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) { 00732 if (FalseVal->getOpcode() == Instruction::Select) 00733 if (FalseVal->getOperand(0) == Cond) 00734 return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2)); 00735 } 00736 00737 return 0; 00738 } 00739 00740 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val, 00741 Constant *Idx) { 00742 if (isa<UndefValue>(Val)) // ee(undef, x) -> undef 00743 return UndefValue::get(Val->getType()->getVectorElementType()); 00744 if (Val->isNullValue()) // ee(zero, x) -> zero 00745 return Constant::getNullValue(Val->getType()->getVectorElementType()); 00746 // ee({w,x,y,z}, undef) -> undef 00747 if (isa<UndefValue>(Idx)) 00748 return UndefValue::get(Val->getType()->getVectorElementType()); 00749 00750 if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) { 00751 uint64_t Index = CIdx->getZExtValue(); 00752 // ee({w,x,y,z}, wrong_value) -> undef 00753 if (Index >= Val->getType()->getVectorNumElements()) 00754 return UndefValue::get(Val->getType()->getVectorElementType()); 00755 return Val->getAggregateElement(Index); 00756 } 00757 return 0; 00758 } 00759 00760 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val, 00761 Constant *Elt, 00762 Constant *Idx) { 00763 ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx); 00764 if (!CIdx) return 0; 00765 const APInt &IdxVal = CIdx->getValue(); 00766 00767 SmallVector<Constant*, 16> Result; 00768 Type *Ty = IntegerType::get(Val->getContext(), 32); 00769 for (unsigned i = 0, e = Val->getType()->getVectorNumElements(); i != e; ++i){ 00770 if (i == IdxVal) { 00771 Result.push_back(Elt); 00772 continue; 00773 } 00774 00775 Constant *C = 00776 ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i)); 00777 Result.push_back(C); 00778 } 00779 00780 return ConstantVector::get(Result); 00781 } 00782 00783 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1, 00784 Constant *V2, 00785 Constant *Mask) { 00786 unsigned MaskNumElts = Mask->getType()->getVectorNumElements(); 00787 Type *EltTy = V1->getType()->getVectorElementType(); 00788 00789 // Undefined shuffle mask -> undefined value. 00790 if (isa<UndefValue>(Mask)) 00791 return UndefValue::get(VectorType::get(EltTy, MaskNumElts)); 00792 00793 // Don't break the bitcode reader hack. 00794 if (isa<ConstantExpr>(Mask)) return 0; 00795 00796 unsigned SrcNumElts = V1->getType()->getVectorNumElements(); 00797 00798 // Loop over the shuffle mask, evaluating each element. 00799 SmallVector<Constant*, 32> Result; 00800 for (unsigned i = 0; i != MaskNumElts; ++i) { 00801 int Elt = ShuffleVectorInst::getMaskValue(Mask, i); 00802 if (Elt == -1) { 00803 Result.push_back(UndefValue::get(EltTy)); 00804 continue; 00805 } 00806 Constant *InElt; 00807 if (unsigned(Elt) >= SrcNumElts*2) 00808 InElt = UndefValue::get(EltTy); 00809 else if (unsigned(Elt) >= SrcNumElts) { 00810 Type *Ty = IntegerType::get(V2->getContext(), 32); 00811 InElt = 00812 ConstantExpr::getExtractElement(V2, 00813 ConstantInt::get(Ty, Elt - SrcNumElts)); 00814 } else { 00815 Type *Ty = IntegerType::get(V1->getContext(), 32); 00816 InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt)); 00817 } 00818 Result.push_back(InElt); 00819 } 00820 00821 return ConstantVector::get(Result); 00822 } 00823 00824 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg, 00825 ArrayRef<unsigned> Idxs) { 00826 // Base case: no indices, so return the entire value. 00827 if (Idxs.empty()) 00828 return Agg; 00829 00830 if (Constant *C = Agg->getAggregateElement(Idxs[0])) 00831 return ConstantFoldExtractValueInstruction(C, Idxs.slice(1)); 00832 00833 return 0; 00834 } 00835 00836 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg, 00837 Constant *Val, 00838 ArrayRef<unsigned> Idxs) { 00839 // Base case: no indices, so replace the entire value. 00840 if (Idxs.empty()) 00841 return Val; 00842 00843 unsigned NumElts; 00844 if (StructType *ST = dyn_cast<StructType>(Agg->getType())) 00845 NumElts = ST->getNumElements(); 00846 else if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType())) 00847 NumElts = AT->getNumElements(); 00848 else 00849 NumElts = Agg->getType()->getVectorNumElements(); 00850 00851 SmallVector<Constant*, 32> Result; 00852 for (unsigned i = 0; i != NumElts; ++i) { 00853 Constant *C = Agg->getAggregateElement(i); 00854 if (C == 0) return 0; 00855 00856 if (Idxs[0] == i) 00857 C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1)); 00858 00859 Result.push_back(C); 00860 } 00861 00862 if (StructType *ST = dyn_cast<StructType>(Agg->getType())) 00863 return ConstantStruct::get(ST, Result); 00864 if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType())) 00865 return ConstantArray::get(AT, Result); 00866 return ConstantVector::get(Result); 00867 } 00868 00869 00870 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode, 00871 Constant *C1, Constant *C2) { 00872 // Handle UndefValue up front. 00873 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) { 00874 switch (Opcode) { 00875 case Instruction::Xor: 00876 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) 00877 // Handle undef ^ undef -> 0 special case. This is a common 00878 // idiom (misuse). 00879 return Constant::getNullValue(C1->getType()); 00880 // Fallthrough 00881 case Instruction::Add: 00882 case Instruction::Sub: 00883 return UndefValue::get(C1->getType()); 00884 case Instruction::And: 00885 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef 00886 return C1; 00887 return Constant::getNullValue(C1->getType()); // undef & X -> 0 00888 case Instruction::Mul: { 00889 ConstantInt *CI; 00890 // X * undef -> undef if X is odd or undef 00891 if (((CI = dyn_cast<ConstantInt>(C1)) && CI->getValue()[0]) || 00892 ((CI = dyn_cast<ConstantInt>(C2)) && CI->getValue()[0]) || 00893 (isa<UndefValue>(C1) && isa<UndefValue>(C2))) 00894 return UndefValue::get(C1->getType()); 00895 00896 // X * undef -> 0 otherwise 00897 return Constant::getNullValue(C1->getType()); 00898 } 00899 case Instruction::UDiv: 00900 case Instruction::SDiv: 00901 // undef / 1 -> undef 00902 if (Opcode == Instruction::UDiv || Opcode == Instruction::SDiv) 00903 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) 00904 if (CI2->isOne()) 00905 return C1; 00906 // FALL THROUGH 00907 case Instruction::URem: 00908 case Instruction::SRem: 00909 if (!isa<UndefValue>(C2)) // undef / X -> 0 00910 return Constant::getNullValue(C1->getType()); 00911 return C2; // X / undef -> undef 00912 case Instruction::Or: // X | undef -> -1 00913 if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef 00914 return C1; 00915 return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0 00916 case Instruction::LShr: 00917 if (isa<UndefValue>(C2) && isa<UndefValue>(C1)) 00918 return C1; // undef lshr undef -> undef 00919 return Constant::getNullValue(C1->getType()); // X lshr undef -> 0 00920 // undef lshr X -> 0 00921 case Instruction::AShr: 00922 if (!isa<UndefValue>(C2)) // undef ashr X --> all ones 00923 return Constant::getAllOnesValue(C1->getType()); 00924 else if (isa<UndefValue>(C1)) 00925 return C1; // undef ashr undef -> undef 00926 else 00927 return C1; // X ashr undef --> X 00928 case Instruction::Shl: 00929 if (isa<UndefValue>(C2) && isa<UndefValue>(C1)) 00930 return C1; // undef shl undef -> undef 00931 // undef << X -> 0 or X << undef -> 0 00932 return Constant::getNullValue(C1->getType()); 00933 } 00934 } 00935 00936 // Handle simplifications when the RHS is a constant int. 00937 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) { 00938 switch (Opcode) { 00939 case Instruction::Add: 00940 if (CI2->equalsInt(0)) return C1; // X + 0 == X 00941 break; 00942 case Instruction::Sub: 00943 if (CI2->equalsInt(0)) return C1; // X - 0 == X 00944 break; 00945 case Instruction::Mul: 00946 if (CI2->equalsInt(0)) return C2; // X * 0 == 0 00947 if (CI2->equalsInt(1)) 00948 return C1; // X * 1 == X 00949 break; 00950 case Instruction::UDiv: 00951 case Instruction::SDiv: 00952 if (CI2->equalsInt(1)) 00953 return C1; // X / 1 == X 00954 if (CI2->equalsInt(0)) 00955 return UndefValue::get(CI2->getType()); // X / 0 == undef 00956 break; 00957 case Instruction::URem: 00958 case Instruction::SRem: 00959 if (CI2->equalsInt(1)) 00960 return Constant::getNullValue(CI2->getType()); // X % 1 == 0 00961 if (CI2->equalsInt(0)) 00962 return UndefValue::get(CI2->getType()); // X % 0 == undef 00963 break; 00964 case Instruction::And: 00965 if (CI2->isZero()) return C2; // X & 0 == 0 00966 if (CI2->isAllOnesValue()) 00967 return C1; // X & -1 == X 00968 00969 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 00970 // (zext i32 to i64) & 4294967295 -> (zext i32 to i64) 00971 if (CE1->getOpcode() == Instruction::ZExt) { 00972 unsigned DstWidth = CI2->getType()->getBitWidth(); 00973 unsigned SrcWidth = 00974 CE1->getOperand(0)->getType()->getPrimitiveSizeInBits(); 00975 APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth)); 00976 if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits) 00977 return C1; 00978 } 00979 00980 // If and'ing the address of a global with a constant, fold it. 00981 if (CE1->getOpcode() == Instruction::PtrToInt && 00982 isa<GlobalValue>(CE1->getOperand(0))) { 00983 GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0)); 00984 00985 // Functions are at least 4-byte aligned. 00986 unsigned GVAlign = GV->getAlignment(); 00987 if (isa<Function>(GV)) 00988 GVAlign = std::max(GVAlign, 4U); 00989 00990 if (GVAlign > 1) { 00991 unsigned DstWidth = CI2->getType()->getBitWidth(); 00992 unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign)); 00993 APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth)); 00994 00995 // If checking bits we know are clear, return zero. 00996 if ((CI2->getValue() & BitsNotSet) == CI2->getValue()) 00997 return Constant::getNullValue(CI2->getType()); 00998 } 00999 } 01000 } 01001 break; 01002 case Instruction::Or: 01003 if (CI2->equalsInt(0)) return C1; // X | 0 == X 01004 if (CI2->isAllOnesValue()) 01005 return C2; // X | -1 == -1 01006 break; 01007 case Instruction::Xor: 01008 if (CI2->equalsInt(0)) return C1; // X ^ 0 == X 01009 01010 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 01011 switch (CE1->getOpcode()) { 01012 default: break; 01013 case Instruction::ICmp: 01014 case Instruction::FCmp: 01015 // cmp pred ^ true -> cmp !pred 01016 assert(CI2->equalsInt(1)); 01017 CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate(); 01018 pred = CmpInst::getInversePredicate(pred); 01019 return ConstantExpr::getCompare(pred, CE1->getOperand(0), 01020 CE1->getOperand(1)); 01021 } 01022 } 01023 break; 01024 case Instruction::AShr: 01025 // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2 01026 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) 01027 if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero. 01028 return ConstantExpr::getLShr(C1, C2); 01029 break; 01030 } 01031 } else if (isa<ConstantInt>(C1)) { 01032 // If C1 is a ConstantInt and C2 is not, swap the operands. 01033 if (Instruction::isCommutative(Opcode)) 01034 return ConstantExpr::get(Opcode, C2, C1); 01035 } 01036 01037 // At this point we know neither constant is an UndefValue. 01038 if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) { 01039 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) { 01040 const APInt &C1V = CI1->getValue(); 01041 const APInt &C2V = CI2->getValue(); 01042 switch (Opcode) { 01043 default: 01044 break; 01045 case Instruction::Add: 01046 return ConstantInt::get(CI1->getContext(), C1V + C2V); 01047 case Instruction::Sub: 01048 return ConstantInt::get(CI1->getContext(), C1V - C2V); 01049 case Instruction::Mul: 01050 return ConstantInt::get(CI1->getContext(), C1V * C2V); 01051 case Instruction::UDiv: 01052 assert(!CI2->isNullValue() && "Div by zero handled above"); 01053 return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V)); 01054 case Instruction::SDiv: 01055 assert(!CI2->isNullValue() && "Div by zero handled above"); 01056 if (C2V.isAllOnesValue() && C1V.isMinSignedValue()) 01057 return UndefValue::get(CI1->getType()); // MIN_INT / -1 -> undef 01058 return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V)); 01059 case Instruction::URem: 01060 assert(!CI2->isNullValue() && "Div by zero handled above"); 01061 return ConstantInt::get(CI1->getContext(), C1V.urem(C2V)); 01062 case Instruction::SRem: 01063 assert(!CI2->isNullValue() && "Div by zero handled above"); 01064 if (C2V.isAllOnesValue() && C1V.isMinSignedValue()) 01065 return UndefValue::get(CI1->getType()); // MIN_INT % -1 -> undef 01066 return ConstantInt::get(CI1->getContext(), C1V.srem(C2V)); 01067 case Instruction::And: 01068 return ConstantInt::get(CI1->getContext(), C1V & C2V); 01069 case Instruction::Or: 01070 return ConstantInt::get(CI1->getContext(), C1V | C2V); 01071 case Instruction::Xor: 01072 return ConstantInt::get(CI1->getContext(), C1V ^ C2V); 01073 case Instruction::Shl: { 01074 uint32_t shiftAmt = C2V.getZExtValue(); 01075 if (shiftAmt < C1V.getBitWidth()) 01076 return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt)); 01077 else 01078 return UndefValue::get(C1->getType()); // too big shift is undef 01079 } 01080 case Instruction::LShr: { 01081 uint32_t shiftAmt = C2V.getZExtValue(); 01082 if (shiftAmt < C1V.getBitWidth()) 01083 return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt)); 01084 else 01085 return UndefValue::get(C1->getType()); // too big shift is undef 01086 } 01087 case Instruction::AShr: { 01088 uint32_t shiftAmt = C2V.getZExtValue(); 01089 if (shiftAmt < C1V.getBitWidth()) 01090 return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt)); 01091 else 01092 return UndefValue::get(C1->getType()); // too big shift is undef 01093 } 01094 } 01095 } 01096 01097 switch (Opcode) { 01098 case Instruction::SDiv: 01099 case Instruction::UDiv: 01100 case Instruction::URem: 01101 case Instruction::SRem: 01102 case Instruction::LShr: 01103 case Instruction::AShr: 01104 case Instruction::Shl: 01105 if (CI1->equalsInt(0)) return C1; 01106 break; 01107 default: 01108 break; 01109 } 01110 } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) { 01111 if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) { 01112 APFloat C1V = CFP1->getValueAPF(); 01113 APFloat C2V = CFP2->getValueAPF(); 01114 APFloat C3V = C1V; // copy for modification 01115 switch (Opcode) { 01116 default: 01117 break; 01118 case Instruction::FAdd: 01119 (void)C3V.add(C2V, APFloat::rmNearestTiesToEven); 01120 return ConstantFP::get(C1->getContext(), C3V); 01121 case Instruction::FSub: 01122 (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven); 01123 return ConstantFP::get(C1->getContext(), C3V); 01124 case Instruction::FMul: 01125 (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven); 01126 return ConstantFP::get(C1->getContext(), C3V); 01127 case Instruction::FDiv: 01128 (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven); 01129 return ConstantFP::get(C1->getContext(), C3V); 01130 case Instruction::FRem: 01131 (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven); 01132 return ConstantFP::get(C1->getContext(), C3V); 01133 } 01134 } 01135 } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) { 01136 // Perform elementwise folding. 01137 SmallVector<Constant*, 16> Result; 01138 Type *Ty = IntegerType::get(VTy->getContext(), 32); 01139 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) { 01140 Constant *LHS = 01141 ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i)); 01142 Constant *RHS = 01143 ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i)); 01144 01145 Result.push_back(ConstantExpr::get(Opcode, LHS, RHS)); 01146 } 01147 01148 return ConstantVector::get(Result); 01149 } 01150 01151 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 01152 // There are many possible foldings we could do here. We should probably 01153 // at least fold add of a pointer with an integer into the appropriate 01154 // getelementptr. This will improve alias analysis a bit. 01155 01156 // Given ((a + b) + c), if (b + c) folds to something interesting, return 01157 // (a + (b + c)). 01158 if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) { 01159 Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2); 01160 if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode) 01161 return ConstantExpr::get(Opcode, CE1->getOperand(0), T); 01162 } 01163 } else if (isa<ConstantExpr>(C2)) { 01164 // If C2 is a constant expr and C1 isn't, flop them around and fold the 01165 // other way if possible. 01166 if (Instruction::isCommutative(Opcode)) 01167 return ConstantFoldBinaryInstruction(Opcode, C2, C1); 01168 } 01169 01170 // i1 can be simplified in many cases. 01171 if (C1->getType()->isIntegerTy(1)) { 01172 switch (Opcode) { 01173 case Instruction::Add: 01174 case Instruction::Sub: 01175 return ConstantExpr::getXor(C1, C2); 01176 case Instruction::Mul: 01177 return ConstantExpr::getAnd(C1, C2); 01178 case Instruction::Shl: 01179 case Instruction::LShr: 01180 case Instruction::AShr: 01181 // We can assume that C2 == 0. If it were one the result would be 01182 // undefined because the shift value is as large as the bitwidth. 01183 return C1; 01184 case Instruction::SDiv: 01185 case Instruction::UDiv: 01186 // We can assume that C2 == 1. If it were zero the result would be 01187 // undefined through division by zero. 01188 return C1; 01189 case Instruction::URem: 01190 case Instruction::SRem: 01191 // We can assume that C2 == 1. If it were zero the result would be 01192 // undefined through division by zero. 01193 return ConstantInt::getFalse(C1->getContext()); 01194 default: 01195 break; 01196 } 01197 } 01198 01199 // We don't know how to fold this. 01200 return 0; 01201 } 01202 01203 /// isZeroSizedType - This type is zero sized if its an array or structure of 01204 /// zero sized types. The only leaf zero sized type is an empty structure. 01205 static bool isMaybeZeroSizedType(Type *Ty) { 01206 if (StructType *STy = dyn_cast<StructType>(Ty)) { 01207 if (STy->isOpaque()) return true; // Can't say. 01208 01209 // If all of elements have zero size, this does too. 01210 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 01211 if (!isMaybeZeroSizedType(STy->getElementType(i))) return false; 01212 return true; 01213 01214 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 01215 return isMaybeZeroSizedType(ATy->getElementType()); 01216 } 01217 return false; 01218 } 01219 01220 /// IdxCompare - Compare the two constants as though they were getelementptr 01221 /// indices. This allows coersion of the types to be the same thing. 01222 /// 01223 /// If the two constants are the "same" (after coersion), return 0. If the 01224 /// first is less than the second, return -1, if the second is less than the 01225 /// first, return 1. If the constants are not integral, return -2. 01226 /// 01227 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) { 01228 if (C1 == C2) return 0; 01229 01230 // Ok, we found a different index. If they are not ConstantInt, we can't do 01231 // anything with them. 01232 if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2)) 01233 return -2; // don't know! 01234 01235 // Ok, we have two differing integer indices. Sign extend them to be the same 01236 // type. Long is always big enough, so we use it. 01237 if (!C1->getType()->isIntegerTy(64)) 01238 C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext())); 01239 01240 if (!C2->getType()->isIntegerTy(64)) 01241 C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext())); 01242 01243 if (C1 == C2) return 0; // They are equal 01244 01245 // If the type being indexed over is really just a zero sized type, there is 01246 // no pointer difference being made here. 01247 if (isMaybeZeroSizedType(ElTy)) 01248 return -2; // dunno. 01249 01250 // If they are really different, now that they are the same type, then we 01251 // found a difference! 01252 if (cast<ConstantInt>(C1)->getSExtValue() < 01253 cast<ConstantInt>(C2)->getSExtValue()) 01254 return -1; 01255 else 01256 return 1; 01257 } 01258 01259 /// evaluateFCmpRelation - This function determines if there is anything we can 01260 /// decide about the two constants provided. This doesn't need to handle simple 01261 /// things like ConstantFP comparisons, but should instead handle ConstantExprs. 01262 /// If we can determine that the two constants have a particular relation to 01263 /// each other, we should return the corresponding FCmpInst predicate, 01264 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in 01265 /// ConstantFoldCompareInstruction. 01266 /// 01267 /// To simplify this code we canonicalize the relation so that the first 01268 /// operand is always the most "complex" of the two. We consider ConstantFP 01269 /// to be the simplest, and ConstantExprs to be the most complex. 01270 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) { 01271 assert(V1->getType() == V2->getType() && 01272 "Cannot compare values of different types!"); 01273 01274 // Handle degenerate case quickly 01275 if (V1 == V2) return FCmpInst::FCMP_OEQ; 01276 01277 if (!isa<ConstantExpr>(V1)) { 01278 if (!isa<ConstantExpr>(V2)) { 01279 // We distilled thisUse the standard constant folder for a few cases 01280 ConstantInt *R = 0; 01281 R = dyn_cast<ConstantInt>( 01282 ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2)); 01283 if (R && !R->isZero()) 01284 return FCmpInst::FCMP_OEQ; 01285 R = dyn_cast<ConstantInt>( 01286 ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2)); 01287 if (R && !R->isZero()) 01288 return FCmpInst::FCMP_OLT; 01289 R = dyn_cast<ConstantInt>( 01290 ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2)); 01291 if (R && !R->isZero()) 01292 return FCmpInst::FCMP_OGT; 01293 01294 // Nothing more we can do 01295 return FCmpInst::BAD_FCMP_PREDICATE; 01296 } 01297 01298 // If the first operand is simple and second is ConstantExpr, swap operands. 01299 FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1); 01300 if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE) 01301 return FCmpInst::getSwappedPredicate(SwappedRelation); 01302 } else { 01303 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a 01304 // constantexpr or a simple constant. 01305 ConstantExpr *CE1 = cast<ConstantExpr>(V1); 01306 switch (CE1->getOpcode()) { 01307 case Instruction::FPTrunc: 01308 case Instruction::FPExt: 01309 case Instruction::UIToFP: 01310 case Instruction::SIToFP: 01311 // We might be able to do something with these but we don't right now. 01312 break; 01313 default: 01314 break; 01315 } 01316 } 01317 // There are MANY other foldings that we could perform here. They will 01318 // probably be added on demand, as they seem needed. 01319 return FCmpInst::BAD_FCMP_PREDICATE; 01320 } 01321 01322 /// evaluateICmpRelation - This function determines if there is anything we can 01323 /// decide about the two constants provided. This doesn't need to handle simple 01324 /// things like integer comparisons, but should instead handle ConstantExprs 01325 /// and GlobalValues. If we can determine that the two constants have a 01326 /// particular relation to each other, we should return the corresponding ICmp 01327 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE. 01328 /// 01329 /// To simplify this code we canonicalize the relation so that the first 01330 /// operand is always the most "complex" of the two. We consider simple 01331 /// constants (like ConstantInt) to be the simplest, followed by 01332 /// GlobalValues, followed by ConstantExpr's (the most complex). 01333 /// 01334 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2, 01335 bool isSigned) { 01336 assert(V1->getType() == V2->getType() && 01337 "Cannot compare different types of values!"); 01338 if (V1 == V2) return ICmpInst::ICMP_EQ; 01339 01340 if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) && 01341 !isa<BlockAddress>(V1)) { 01342 if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) && 01343 !isa<BlockAddress>(V2)) { 01344 // We distilled this down to a simple case, use the standard constant 01345 // folder. 01346 ConstantInt *R = 0; 01347 ICmpInst::Predicate pred = ICmpInst::ICMP_EQ; 01348 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2)); 01349 if (R && !R->isZero()) 01350 return pred; 01351 pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 01352 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2)); 01353 if (R && !R->isZero()) 01354 return pred; 01355 pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 01356 R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2)); 01357 if (R && !R->isZero()) 01358 return pred; 01359 01360 // If we couldn't figure it out, bail. 01361 return ICmpInst::BAD_ICMP_PREDICATE; 01362 } 01363 01364 // If the first operand is simple, swap operands. 01365 ICmpInst::Predicate SwappedRelation = 01366 evaluateICmpRelation(V2, V1, isSigned); 01367 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE) 01368 return ICmpInst::getSwappedPredicate(SwappedRelation); 01369 01370 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) { 01371 if (isa<ConstantExpr>(V2)) { // Swap as necessary. 01372 ICmpInst::Predicate SwappedRelation = 01373 evaluateICmpRelation(V2, V1, isSigned); 01374 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE) 01375 return ICmpInst::getSwappedPredicate(SwappedRelation); 01376 return ICmpInst::BAD_ICMP_PREDICATE; 01377 } 01378 01379 // Now we know that the RHS is a GlobalValue, BlockAddress or simple 01380 // constant (which, since the types must match, means that it's a 01381 // ConstantPointerNull). 01382 if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) { 01383 // Don't try to decide equality of aliases. 01384 if (!isa<GlobalAlias>(GV) && !isa<GlobalAlias>(GV2)) 01385 if (!GV->hasExternalWeakLinkage() || !GV2->hasExternalWeakLinkage()) 01386 return ICmpInst::ICMP_NE; 01387 } else if (isa<BlockAddress>(V2)) { 01388 return ICmpInst::ICMP_NE; // Globals never equal labels. 01389 } else { 01390 assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!"); 01391 // GlobalVals can never be null unless they have external weak linkage. 01392 // We don't try to evaluate aliases here. 01393 if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV)) 01394 return ICmpInst::ICMP_NE; 01395 } 01396 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) { 01397 if (isa<ConstantExpr>(V2)) { // Swap as necessary. 01398 ICmpInst::Predicate SwappedRelation = 01399 evaluateICmpRelation(V2, V1, isSigned); 01400 if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE) 01401 return ICmpInst::getSwappedPredicate(SwappedRelation); 01402 return ICmpInst::BAD_ICMP_PREDICATE; 01403 } 01404 01405 // Now we know that the RHS is a GlobalValue, BlockAddress or simple 01406 // constant (which, since the types must match, means that it is a 01407 // ConstantPointerNull). 01408 if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) { 01409 // Block address in another function can't equal this one, but block 01410 // addresses in the current function might be the same if blocks are 01411 // empty. 01412 if (BA2->getFunction() != BA->getFunction()) 01413 return ICmpInst::ICMP_NE; 01414 } else { 01415 // Block addresses aren't null, don't equal the address of globals. 01416 assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) && 01417 "Canonicalization guarantee!"); 01418 return ICmpInst::ICMP_NE; 01419 } 01420 } else { 01421 // Ok, the LHS is known to be a constantexpr. The RHS can be any of a 01422 // constantexpr, a global, block address, or a simple constant. 01423 ConstantExpr *CE1 = cast<ConstantExpr>(V1); 01424 Constant *CE1Op0 = CE1->getOperand(0); 01425 01426 switch (CE1->getOpcode()) { 01427 case Instruction::Trunc: 01428 case Instruction::FPTrunc: 01429 case Instruction::FPExt: 01430 case Instruction::FPToUI: 01431 case Instruction::FPToSI: 01432 break; // We can't evaluate floating point casts or truncations. 01433 01434 case Instruction::UIToFP: 01435 case Instruction::SIToFP: 01436 case Instruction::BitCast: 01437 case Instruction::ZExt: 01438 case Instruction::SExt: 01439 // If the cast is not actually changing bits, and the second operand is a 01440 // null pointer, do the comparison with the pre-casted value. 01441 if (V2->isNullValue() && 01442 (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) { 01443 if (CE1->getOpcode() == Instruction::ZExt) isSigned = false; 01444 if (CE1->getOpcode() == Instruction::SExt) isSigned = true; 01445 return evaluateICmpRelation(CE1Op0, 01446 Constant::getNullValue(CE1Op0->getType()), 01447 isSigned); 01448 } 01449 break; 01450 01451 case Instruction::GetElementPtr: 01452 // Ok, since this is a getelementptr, we know that the constant has a 01453 // pointer type. Check the various cases. 01454 if (isa<ConstantPointerNull>(V2)) { 01455 // If we are comparing a GEP to a null pointer, check to see if the base 01456 // of the GEP equals the null pointer. 01457 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) { 01458 if (GV->hasExternalWeakLinkage()) 01459 // Weak linkage GVals could be zero or not. We're comparing that 01460 // to null pointer so its greater-or-equal 01461 return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 01462 else 01463 // If its not weak linkage, the GVal must have a non-zero address 01464 // so the result is greater-than 01465 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 01466 } else if (isa<ConstantPointerNull>(CE1Op0)) { 01467 // If we are indexing from a null pointer, check to see if we have any 01468 // non-zero indices. 01469 for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i) 01470 if (!CE1->getOperand(i)->isNullValue()) 01471 // Offsetting from null, must not be equal. 01472 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 01473 // Only zero indexes from null, must still be zero. 01474 return ICmpInst::ICMP_EQ; 01475 } 01476 // Otherwise, we can't really say if the first operand is null or not. 01477 } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) { 01478 if (isa<ConstantPointerNull>(CE1Op0)) { 01479 if (GV2->hasExternalWeakLinkage()) 01480 // Weak linkage GVals could be zero or not. We're comparing it to 01481 // a null pointer, so its less-or-equal 01482 return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 01483 else 01484 // If its not weak linkage, the GVal must have a non-zero address 01485 // so the result is less-than 01486 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 01487 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) { 01488 if (GV == GV2) { 01489 // If this is a getelementptr of the same global, then it must be 01490 // different. Because the types must match, the getelementptr could 01491 // only have at most one index, and because we fold getelementptr's 01492 // with a single zero index, it must be nonzero. 01493 assert(CE1->getNumOperands() == 2 && 01494 !CE1->getOperand(1)->isNullValue() && 01495 "Surprising getelementptr!"); 01496 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 01497 } else { 01498 // If they are different globals, we don't know what the value is. 01499 return ICmpInst::BAD_ICMP_PREDICATE; 01500 } 01501 } 01502 } else { 01503 ConstantExpr *CE2 = cast<ConstantExpr>(V2); 01504 Constant *CE2Op0 = CE2->getOperand(0); 01505 01506 // There are MANY other foldings that we could perform here. They will 01507 // probably be added on demand, as they seem needed. 01508 switch (CE2->getOpcode()) { 01509 default: break; 01510 case Instruction::GetElementPtr: 01511 // By far the most common case to handle is when the base pointers are 01512 // obviously to the same global. 01513 if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) { 01514 if (CE1Op0 != CE2Op0) // Don't know relative ordering. 01515 return ICmpInst::BAD_ICMP_PREDICATE; 01516 // Ok, we know that both getelementptr instructions are based on the 01517 // same global. From this, we can precisely determine the relative 01518 // ordering of the resultant pointers. 01519 unsigned i = 1; 01520 01521 // The logic below assumes that the result of the comparison 01522 // can be determined by finding the first index that differs. 01523 // This doesn't work if there is over-indexing in any 01524 // subsequent indices, so check for that case first. 01525 if (!CE1->isGEPWithNoNotionalOverIndexing() || 01526 !CE2->isGEPWithNoNotionalOverIndexing()) 01527 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal. 01528 01529 // Compare all of the operands the GEP's have in common. 01530 gep_type_iterator GTI = gep_type_begin(CE1); 01531 for (;i != CE1->getNumOperands() && i != CE2->getNumOperands(); 01532 ++i, ++GTI) 01533 switch (IdxCompare(CE1->getOperand(i), 01534 CE2->getOperand(i), GTI.getIndexedType())) { 01535 case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT; 01536 case 1: return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT; 01537 case -2: return ICmpInst::BAD_ICMP_PREDICATE; 01538 } 01539 01540 // Ok, we ran out of things they have in common. If any leftovers 01541 // are non-zero then we have a difference, otherwise we are equal. 01542 for (; i < CE1->getNumOperands(); ++i) 01543 if (!CE1->getOperand(i)->isNullValue()) { 01544 if (isa<ConstantInt>(CE1->getOperand(i))) 01545 return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 01546 else 01547 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal. 01548 } 01549 01550 for (; i < CE2->getNumOperands(); ++i) 01551 if (!CE2->getOperand(i)->isNullValue()) { 01552 if (isa<ConstantInt>(CE2->getOperand(i))) 01553 return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 01554 else 01555 return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal. 01556 } 01557 return ICmpInst::ICMP_EQ; 01558 } 01559 } 01560 } 01561 default: 01562 break; 01563 } 01564 } 01565 01566 return ICmpInst::BAD_ICMP_PREDICATE; 01567 } 01568 01569 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred, 01570 Constant *C1, Constant *C2) { 01571 Type *ResultTy; 01572 if (VectorType *VT = dyn_cast<VectorType>(C1->getType())) 01573 ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()), 01574 VT->getNumElements()); 01575 else 01576 ResultTy = Type::getInt1Ty(C1->getContext()); 01577 01578 // Fold FCMP_FALSE/FCMP_TRUE unconditionally. 01579 if (pred == FCmpInst::FCMP_FALSE) 01580 return Constant::getNullValue(ResultTy); 01581 01582 if (pred == FCmpInst::FCMP_TRUE) 01583 return Constant::getAllOnesValue(ResultTy); 01584 01585 // Handle some degenerate cases first 01586 if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) { 01587 // For EQ and NE, we can always pick a value for the undef to make the 01588 // predicate pass or fail, so we can return undef. 01589 // Also, if both operands are undef, we can return undef. 01590 if (ICmpInst::isEquality(ICmpInst::Predicate(pred)) || 01591 (isa<UndefValue>(C1) && isa<UndefValue>(C2))) 01592 return UndefValue::get(ResultTy); 01593 // Otherwise, pick the same value as the non-undef operand, and fold 01594 // it to true or false. 01595 return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred)); 01596 } 01597 01598 // icmp eq/ne(null,GV) -> false/true 01599 if (C1->isNullValue()) { 01600 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2)) 01601 // Don't try to evaluate aliases. External weak GV can be null. 01602 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) { 01603 if (pred == ICmpInst::ICMP_EQ) 01604 return ConstantInt::getFalse(C1->getContext()); 01605 else if (pred == ICmpInst::ICMP_NE) 01606 return ConstantInt::getTrue(C1->getContext()); 01607 } 01608 // icmp eq/ne(GV,null) -> false/true 01609 } else if (C2->isNullValue()) { 01610 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1)) 01611 // Don't try to evaluate aliases. External weak GV can be null. 01612 if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) { 01613 if (pred == ICmpInst::ICMP_EQ) 01614 return ConstantInt::getFalse(C1->getContext()); 01615 else if (pred == ICmpInst::ICMP_NE) 01616 return ConstantInt::getTrue(C1->getContext()); 01617 } 01618 } 01619 01620 // If the comparison is a comparison between two i1's, simplify it. 01621 if (C1->getType()->isIntegerTy(1)) { 01622 switch(pred) { 01623 case ICmpInst::ICMP_EQ: 01624 if (isa<ConstantInt>(C2)) 01625 return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2)); 01626 return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2); 01627 case ICmpInst::ICMP_NE: 01628 return ConstantExpr::getXor(C1, C2); 01629 default: 01630 break; 01631 } 01632 } 01633 01634 if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) { 01635 APInt V1 = cast<ConstantInt>(C1)->getValue(); 01636 APInt V2 = cast<ConstantInt>(C2)->getValue(); 01637 switch (pred) { 01638 default: llvm_unreachable("Invalid ICmp Predicate"); 01639 case ICmpInst::ICMP_EQ: return ConstantInt::get(ResultTy, V1 == V2); 01640 case ICmpInst::ICMP_NE: return ConstantInt::get(ResultTy, V1 != V2); 01641 case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2)); 01642 case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2)); 01643 case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2)); 01644 case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2)); 01645 case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2)); 01646 case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2)); 01647 case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2)); 01648 case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2)); 01649 } 01650 } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) { 01651 APFloat C1V = cast<ConstantFP>(C1)->getValueAPF(); 01652 APFloat C2V = cast<ConstantFP>(C2)->getValueAPF(); 01653 APFloat::cmpResult R = C1V.compare(C2V); 01654 switch (pred) { 01655 default: llvm_unreachable("Invalid FCmp Predicate"); 01656 case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy); 01657 case FCmpInst::FCMP_TRUE: return Constant::getAllOnesValue(ResultTy); 01658 case FCmpInst::FCMP_UNO: 01659 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered); 01660 case FCmpInst::FCMP_ORD: 01661 return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered); 01662 case FCmpInst::FCMP_UEQ: 01663 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered || 01664 R==APFloat::cmpEqual); 01665 case FCmpInst::FCMP_OEQ: 01666 return ConstantInt::get(ResultTy, R==APFloat::cmpEqual); 01667 case FCmpInst::FCMP_UNE: 01668 return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual); 01669 case FCmpInst::FCMP_ONE: 01670 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan || 01671 R==APFloat::cmpGreaterThan); 01672 case FCmpInst::FCMP_ULT: 01673 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered || 01674 R==APFloat::cmpLessThan); 01675 case FCmpInst::FCMP_OLT: 01676 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan); 01677 case FCmpInst::FCMP_UGT: 01678 return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered || 01679 R==APFloat::cmpGreaterThan); 01680 case FCmpInst::FCMP_OGT: 01681 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan); 01682 case FCmpInst::FCMP_ULE: 01683 return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan); 01684 case FCmpInst::FCMP_OLE: 01685 return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan || 01686 R==APFloat::cmpEqual); 01687 case FCmpInst::FCMP_UGE: 01688 return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan); 01689 case FCmpInst::FCMP_OGE: 01690 return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan || 01691 R==APFloat::cmpEqual); 01692 } 01693 } else if (C1->getType()->isVectorTy()) { 01694 // If we can constant fold the comparison of each element, constant fold 01695 // the whole vector comparison. 01696 SmallVector<Constant*, 4> ResElts; 01697 Type *Ty = IntegerType::get(C1->getContext(), 32); 01698 // Compare the elements, producing an i1 result or constant expr. 01699 for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){ 01700 Constant *C1E = 01701 ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i)); 01702 Constant *C2E = 01703 ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i)); 01704 01705 ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E)); 01706 } 01707 01708 return ConstantVector::get(ResElts); 01709 } 01710 01711 if (C1->getType()->isFloatingPointTy()) { 01712 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true. 01713 switch (evaluateFCmpRelation(C1, C2)) { 01714 default: llvm_unreachable("Unknown relation!"); 01715 case FCmpInst::FCMP_UNO: 01716 case FCmpInst::FCMP_ORD: 01717 case FCmpInst::FCMP_UEQ: 01718 case FCmpInst::FCMP_UNE: 01719 case FCmpInst::FCMP_ULT: 01720 case FCmpInst::FCMP_UGT: 01721 case FCmpInst::FCMP_ULE: 01722 case FCmpInst::FCMP_UGE: 01723 case FCmpInst::FCMP_TRUE: 01724 case FCmpInst::FCMP_FALSE: 01725 case FCmpInst::BAD_FCMP_PREDICATE: 01726 break; // Couldn't determine anything about these constants. 01727 case FCmpInst::FCMP_OEQ: // We know that C1 == C2 01728 Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ || 01729 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE || 01730 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE); 01731 break; 01732 case FCmpInst::FCMP_OLT: // We know that C1 < C2 01733 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE || 01734 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT || 01735 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE); 01736 break; 01737 case FCmpInst::FCMP_OGT: // We know that C1 > C2 01738 Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE || 01739 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT || 01740 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE); 01741 break; 01742 case FCmpInst::FCMP_OLE: // We know that C1 <= C2 01743 // We can only partially decide this relation. 01744 if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 01745 Result = 0; 01746 else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 01747 Result = 1; 01748 break; 01749 case FCmpInst::FCMP_OGE: // We known that C1 >= C2 01750 // We can only partially decide this relation. 01751 if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 01752 Result = 0; 01753 else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 01754 Result = 1; 01755 break; 01756 case FCmpInst::FCMP_ONE: // We know that C1 != C2 01757 // We can only partially decide this relation. 01758 if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 01759 Result = 0; 01760 else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 01761 Result = 1; 01762 break; 01763 } 01764 01765 // If we evaluated the result, return it now. 01766 if (Result != -1) 01767 return ConstantInt::get(ResultTy, Result); 01768 01769 } else { 01770 // Evaluate the relation between the two constants, per the predicate. 01771 int Result = -1; // -1 = unknown, 0 = known false, 1 = known true. 01772 switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) { 01773 default: llvm_unreachable("Unknown relational!"); 01774 case ICmpInst::BAD_ICMP_PREDICATE: 01775 break; // Couldn't determine anything about these constants. 01776 case ICmpInst::ICMP_EQ: // We know the constants are equal! 01777 // If we know the constants are equal, we can decide the result of this 01778 // computation precisely. 01779 Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred); 01780 break; 01781 case ICmpInst::ICMP_ULT: 01782 switch (pred) { 01783 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE: 01784 Result = 1; break; 01785 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE: 01786 Result = 0; break; 01787 } 01788 break; 01789 case ICmpInst::ICMP_SLT: 01790 switch (pred) { 01791 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE: 01792 Result = 1; break; 01793 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE: 01794 Result = 0; break; 01795 } 01796 break; 01797 case ICmpInst::ICMP_UGT: 01798 switch (pred) { 01799 case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE: 01800 Result = 1; break; 01801 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE: 01802 Result = 0; break; 01803 } 01804 break; 01805 case ICmpInst::ICMP_SGT: 01806 switch (pred) { 01807 case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE: 01808 Result = 1; break; 01809 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE: 01810 Result = 0; break; 01811 } 01812 break; 01813 case ICmpInst::ICMP_ULE: 01814 if (pred == ICmpInst::ICMP_UGT) Result = 0; 01815 if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1; 01816 break; 01817 case ICmpInst::ICMP_SLE: 01818 if (pred == ICmpInst::ICMP_SGT) Result = 0; 01819 if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1; 01820 break; 01821 case ICmpInst::ICMP_UGE: 01822 if (pred == ICmpInst::ICMP_ULT) Result = 0; 01823 if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1; 01824 break; 01825 case ICmpInst::ICMP_SGE: 01826 if (pred == ICmpInst::ICMP_SLT) Result = 0; 01827 if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1; 01828 break; 01829 case ICmpInst::ICMP_NE: 01830 if (pred == ICmpInst::ICMP_EQ) Result = 0; 01831 if (pred == ICmpInst::ICMP_NE) Result = 1; 01832 break; 01833 } 01834 01835 // If we evaluated the result, return it now. 01836 if (Result != -1) 01837 return ConstantInt::get(ResultTy, Result); 01838 01839 // If the right hand side is a bitcast, try using its inverse to simplify 01840 // it by moving it to the left hand side. We can't do this if it would turn 01841 // a vector compare into a scalar compare or visa versa. 01842 if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) { 01843 Constant *CE2Op0 = CE2->getOperand(0); 01844 if (CE2->getOpcode() == Instruction::BitCast && 01845 CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) { 01846 Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType()); 01847 return ConstantExpr::getICmp(pred, Inverse, CE2Op0); 01848 } 01849 } 01850 01851 // If the left hand side is an extension, try eliminating it. 01852 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) { 01853 if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) || 01854 (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){ 01855 Constant *CE1Op0 = CE1->getOperand(0); 01856 Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType()); 01857 if (CE1Inverse == CE1Op0) { 01858 // Check whether we can safely truncate the right hand side. 01859 Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType()); 01860 if (ConstantExpr::getZExt(C2Inverse, C2->getType()) == C2) { 01861 return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse); 01862 } 01863 } 01864 } 01865 } 01866 01867 if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) || 01868 (C1->isNullValue() && !C2->isNullValue())) { 01869 // If C2 is a constant expr and C1 isn't, flip them around and fold the 01870 // other way if possible. 01871 // Also, if C1 is null and C2 isn't, flip them around. 01872 pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred); 01873 return ConstantExpr::getICmp(pred, C2, C1); 01874 } 01875 } 01876 return 0; 01877 } 01878 01879 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices 01880 /// is "inbounds". 01881 template<typename IndexTy> 01882 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) { 01883 // No indices means nothing that could be out of bounds. 01884 if (Idxs.empty()) return true; 01885 01886 // If the first index is zero, it's in bounds. 01887 if (cast<Constant>(Idxs[0])->isNullValue()) return true; 01888 01889 // If the first index is one and all the rest are zero, it's in bounds, 01890 // by the one-past-the-end rule. 01891 if (!cast<ConstantInt>(Idxs[0])->isOne()) 01892 return false; 01893 for (unsigned i = 1, e = Idxs.size(); i != e; ++i) 01894 if (!cast<Constant>(Idxs[i])->isNullValue()) 01895 return false; 01896 return true; 01897 } 01898 01899 template<typename IndexTy> 01900 static Constant *ConstantFoldGetElementPtrImpl(Constant *C, 01901 bool inBounds, 01902 ArrayRef<IndexTy> Idxs) { 01903 if (Idxs.empty()) return C; 01904 Constant *Idx0 = cast<Constant>(Idxs[0]); 01905 if ((Idxs.size() == 1 && Idx0->isNullValue())) 01906 return C; 01907 01908 if (isa<UndefValue>(C)) { 01909 PointerType *Ptr = cast<PointerType>(C->getType()); 01910 Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs); 01911 assert(Ty != 0 && "Invalid indices for GEP!"); 01912 return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace())); 01913 } 01914 01915 if (C->isNullValue()) { 01916 bool isNull = true; 01917 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) 01918 if (!cast<Constant>(Idxs[i])->isNullValue()) { 01919 isNull = false; 01920 break; 01921 } 01922 if (isNull) { 01923 PointerType *Ptr = cast<PointerType>(C->getType()); 01924 Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs); 01925 assert(Ty != 0 && "Invalid indices for GEP!"); 01926 return ConstantPointerNull::get(PointerType::get(Ty, 01927 Ptr->getAddressSpace())); 01928 } 01929 } 01930 01931 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 01932 // Combine Indices - If the source pointer to this getelementptr instruction 01933 // is a getelementptr instruction, combine the indices of the two 01934 // getelementptr instructions into a single instruction. 01935 // 01936 if (CE->getOpcode() == Instruction::GetElementPtr) { 01937 Type *LastTy = 0; 01938 for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE); 01939 I != E; ++I) 01940 LastTy = *I; 01941 01942 if ((LastTy && isa<SequentialType>(LastTy)) || Idx0->isNullValue()) { 01943 SmallVector<Value*, 16> NewIndices; 01944 NewIndices.reserve(Idxs.size() + CE->getNumOperands()); 01945 for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i) 01946 NewIndices.push_back(CE->getOperand(i)); 01947 01948 // Add the last index of the source with the first index of the new GEP. 01949 // Make sure to handle the case when they are actually different types. 01950 Constant *Combined = CE->getOperand(CE->getNumOperands()-1); 01951 // Otherwise it must be an array. 01952 if (!Idx0->isNullValue()) { 01953 Type *IdxTy = Combined->getType(); 01954 if (IdxTy != Idx0->getType()) { 01955 Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext()); 01956 Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty); 01957 Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty); 01958 Combined = ConstantExpr::get(Instruction::Add, C1, C2); 01959 } else { 01960 Combined = 01961 ConstantExpr::get(Instruction::Add, Idx0, Combined); 01962 } 01963 } 01964 01965 NewIndices.push_back(Combined); 01966 NewIndices.append(Idxs.begin() + 1, Idxs.end()); 01967 return 01968 ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices, 01969 inBounds && 01970 cast<GEPOperator>(CE)->isInBounds()); 01971 } 01972 } 01973 01974 // Attempt to fold casts to the same type away. For example, folding: 01975 // 01976 // i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*), 01977 // i64 0, i64 0) 01978 // into: 01979 // 01980 // i32* getelementptr ([3 x i32]* %X, i64 0, i64 0) 01981 // 01982 // Don't fold if the cast is changing address spaces. 01983 if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) { 01984 PointerType *SrcPtrTy = 01985 dyn_cast<PointerType>(CE->getOperand(0)->getType()); 01986 PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType()); 01987 if (SrcPtrTy && DstPtrTy) { 01988 ArrayType *SrcArrayTy = 01989 dyn_cast<ArrayType>(SrcPtrTy->getElementType()); 01990 ArrayType *DstArrayTy = 01991 dyn_cast<ArrayType>(DstPtrTy->getElementType()); 01992 if (SrcArrayTy && DstArrayTy 01993 && SrcArrayTy->getElementType() == DstArrayTy->getElementType() 01994 && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace()) 01995 return ConstantExpr::getGetElementPtr((Constant*)CE->getOperand(0), 01996 Idxs, inBounds); 01997 } 01998 } 01999 } 02000 02001 // Check to see if any array indices are not within the corresponding 02002 // notional array bounds. If so, try to determine if they can be factored 02003 // out into preceding dimensions. 02004 bool Unknown = false; 02005 SmallVector<Constant *, 8> NewIdxs; 02006 Type *Ty = C->getType(); 02007 Type *Prev = 0; 02008 for (unsigned i = 0, e = Idxs.size(); i != e; 02009 Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) { 02010 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) { 02011 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) 02012 if (ATy->getNumElements() <= INT64_MAX && 02013 ATy->getNumElements() != 0 && 02014 CI->getSExtValue() >= (int64_t)ATy->getNumElements()) { 02015 if (isa<SequentialType>(Prev)) { 02016 // It's out of range, but we can factor it into the prior 02017 // dimension. 02018 NewIdxs.resize(Idxs.size()); 02019 ConstantInt *Factor = ConstantInt::get(CI->getType(), 02020 ATy->getNumElements()); 02021 NewIdxs[i] = ConstantExpr::getSRem(CI, Factor); 02022 02023 Constant *PrevIdx = cast<Constant>(Idxs[i-1]); 02024 Constant *Div = ConstantExpr::getSDiv(CI, Factor); 02025 02026 // Before adding, extend both operands to i64 to avoid 02027 // overflow trouble. 02028 if (!PrevIdx->getType()->isIntegerTy(64)) 02029 PrevIdx = ConstantExpr::getSExt(PrevIdx, 02030 Type::getInt64Ty(Div->getContext())); 02031 if (!Div->getType()->isIntegerTy(64)) 02032 Div = ConstantExpr::getSExt(Div, 02033 Type::getInt64Ty(Div->getContext())); 02034 02035 NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div); 02036 } else { 02037 // It's out of range, but the prior dimension is a struct 02038 // so we can't do anything about it. 02039 Unknown = true; 02040 } 02041 } 02042 } else { 02043 // We don't know if it's in range or not. 02044 Unknown = true; 02045 } 02046 } 02047 02048 // If we did any factoring, start over with the adjusted indices. 02049 if (!NewIdxs.empty()) { 02050 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) 02051 if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]); 02052 return ConstantExpr::getGetElementPtr(C, NewIdxs, inBounds); 02053 } 02054 02055 // If all indices are known integers and normalized, we can do a simple 02056 // check for the "inbounds" property. 02057 if (!Unknown && !inBounds && 02058 isa<GlobalVariable>(C) && isInBoundsIndices(Idxs)) 02059 return ConstantExpr::getInBoundsGetElementPtr(C, Idxs); 02060 02061 return 0; 02062 } 02063 02064 Constant *llvm::ConstantFoldGetElementPtr(Constant *C, 02065 bool inBounds, 02066 ArrayRef<Constant *> Idxs) { 02067 return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs); 02068 } 02069 02070 Constant *llvm::ConstantFoldGetElementPtr(Constant *C, 02071 bool inBounds, 02072 ArrayRef<Value *> Idxs) { 02073 return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs); 02074 }