LLVM API Documentation
00001 //===-- Constants.cpp - Implement Constant nodes --------------------------===// 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 the Constant* classes. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "llvm/IR/Constants.h" 00015 #include "ConstantFold.h" 00016 #include "LLVMContextImpl.h" 00017 #include "llvm/ADT/DenseMap.h" 00018 #include "llvm/ADT/FoldingSet.h" 00019 #include "llvm/ADT/STLExtras.h" 00020 #include "llvm/ADT/SmallVector.h" 00021 #include "llvm/ADT/StringExtras.h" 00022 #include "llvm/ADT/StringMap.h" 00023 #include "llvm/IR/DerivedTypes.h" 00024 #include "llvm/IR/GlobalValue.h" 00025 #include "llvm/IR/Instructions.h" 00026 #include "llvm/IR/Module.h" 00027 #include "llvm/IR/Operator.h" 00028 #include "llvm/Support/Compiler.h" 00029 #include "llvm/Support/Debug.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 "llvm/Support/raw_ostream.h" 00035 #include <algorithm> 00036 #include <cstdarg> 00037 using namespace llvm; 00038 00039 //===----------------------------------------------------------------------===// 00040 // Constant Class 00041 //===----------------------------------------------------------------------===// 00042 00043 void Constant::anchor() { } 00044 00045 bool Constant::isNegativeZeroValue() const { 00046 // Floating point values have an explicit -0.0 value. 00047 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this)) 00048 return CFP->isZero() && CFP->isNegative(); 00049 00050 // Equivalent for a vector of -0.0's. 00051 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) 00052 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue())) 00053 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative()) 00054 return true; 00055 00056 // We've already handled true FP case; any other FP vectors can't represent -0.0. 00057 if (getType()->isFPOrFPVectorTy()) 00058 return false; 00059 00060 // Otherwise, just use +0.0. 00061 return isNullValue(); 00062 } 00063 00064 // Return true iff this constant is positive zero (floating point), negative 00065 // zero (floating point), or a null value. 00066 bool Constant::isZeroValue() const { 00067 // Floating point values have an explicit -0.0 value. 00068 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this)) 00069 return CFP->isZero(); 00070 00071 // Otherwise, just use +0.0. 00072 return isNullValue(); 00073 } 00074 00075 bool Constant::isNullValue() const { 00076 // 0 is null. 00077 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this)) 00078 return CI->isZero(); 00079 00080 // +0.0 is null. 00081 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this)) 00082 return CFP->isZero() && !CFP->isNegative(); 00083 00084 // constant zero is zero for aggregates and cpnull is null for pointers. 00085 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this); 00086 } 00087 00088 bool Constant::isAllOnesValue() const { 00089 // Check for -1 integers 00090 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this)) 00091 return CI->isMinusOne(); 00092 00093 // Check for FP which are bitcasted from -1 integers 00094 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this)) 00095 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue(); 00096 00097 // Check for constant vectors which are splats of -1 values. 00098 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) 00099 if (Constant *Splat = CV->getSplatValue()) 00100 return Splat->isAllOnesValue(); 00101 00102 // Check for constant vectors which are splats of -1 values. 00103 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) 00104 if (Constant *Splat = CV->getSplatValue()) 00105 return Splat->isAllOnesValue(); 00106 00107 return false; 00108 } 00109 00110 // Constructor to create a '0' constant of arbitrary type... 00111 Constant *Constant::getNullValue(Type *Ty) { 00112 switch (Ty->getTypeID()) { 00113 case Type::IntegerTyID: 00114 return ConstantInt::get(Ty, 0); 00115 case Type::HalfTyID: 00116 return ConstantFP::get(Ty->getContext(), 00117 APFloat::getZero(APFloat::IEEEhalf)); 00118 case Type::FloatTyID: 00119 return ConstantFP::get(Ty->getContext(), 00120 APFloat::getZero(APFloat::IEEEsingle)); 00121 case Type::DoubleTyID: 00122 return ConstantFP::get(Ty->getContext(), 00123 APFloat::getZero(APFloat::IEEEdouble)); 00124 case Type::X86_FP80TyID: 00125 return ConstantFP::get(Ty->getContext(), 00126 APFloat::getZero(APFloat::x87DoubleExtended)); 00127 case Type::FP128TyID: 00128 return ConstantFP::get(Ty->getContext(), 00129 APFloat::getZero(APFloat::IEEEquad)); 00130 case Type::PPC_FP128TyID: 00131 return ConstantFP::get(Ty->getContext(), 00132 APFloat(APFloat::PPCDoubleDouble, 00133 APInt::getNullValue(128))); 00134 case Type::PointerTyID: 00135 return ConstantPointerNull::get(cast<PointerType>(Ty)); 00136 case Type::StructTyID: 00137 case Type::ArrayTyID: 00138 case Type::VectorTyID: 00139 return ConstantAggregateZero::get(Ty); 00140 default: 00141 // Function, Label, or Opaque type? 00142 llvm_unreachable("Cannot create a null constant of that type!"); 00143 } 00144 } 00145 00146 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) { 00147 Type *ScalarTy = Ty->getScalarType(); 00148 00149 // Create the base integer constant. 00150 Constant *C = ConstantInt::get(Ty->getContext(), V); 00151 00152 // Convert an integer to a pointer, if necessary. 00153 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy)) 00154 C = ConstantExpr::getIntToPtr(C, PTy); 00155 00156 // Broadcast a scalar to a vector, if necessary. 00157 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 00158 C = ConstantVector::getSplat(VTy->getNumElements(), C); 00159 00160 return C; 00161 } 00162 00163 Constant *Constant::getAllOnesValue(Type *Ty) { 00164 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty)) 00165 return ConstantInt::get(Ty->getContext(), 00166 APInt::getAllOnesValue(ITy->getBitWidth())); 00167 00168 if (Ty->isFloatingPointTy()) { 00169 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(), 00170 !Ty->isPPC_FP128Ty()); 00171 return ConstantFP::get(Ty->getContext(), FL); 00172 } 00173 00174 VectorType *VTy = cast<VectorType>(Ty); 00175 return ConstantVector::getSplat(VTy->getNumElements(), 00176 getAllOnesValue(VTy->getElementType())); 00177 } 00178 00179 /// getAggregateElement - For aggregates (struct/array/vector) return the 00180 /// constant that corresponds to the specified element if possible, or null if 00181 /// not. This can return null if the element index is a ConstantExpr, or if 00182 /// 'this' is a constant expr. 00183 Constant *Constant::getAggregateElement(unsigned Elt) const { 00184 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this)) 00185 return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : 0; 00186 00187 if (const ConstantArray *CA = dyn_cast<ConstantArray>(this)) 00188 return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : 0; 00189 00190 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) 00191 return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : 0; 00192 00193 if (const ConstantAggregateZero *CAZ =dyn_cast<ConstantAggregateZero>(this)) 00194 return CAZ->getElementValue(Elt); 00195 00196 if (const UndefValue *UV = dyn_cast<UndefValue>(this)) 00197 return UV->getElementValue(Elt); 00198 00199 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this)) 00200 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt) : 0; 00201 return 0; 00202 } 00203 00204 Constant *Constant::getAggregateElement(Constant *Elt) const { 00205 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer"); 00206 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) 00207 return getAggregateElement(CI->getZExtValue()); 00208 return 0; 00209 } 00210 00211 00212 void Constant::destroyConstantImpl() { 00213 // When a Constant is destroyed, there may be lingering 00214 // references to the constant by other constants in the constant pool. These 00215 // constants are implicitly dependent on the module that is being deleted, 00216 // but they don't know that. Because we only find out when the CPV is 00217 // deleted, we must now notify all of our users (that should only be 00218 // Constants) that they are, in fact, invalid now and should be deleted. 00219 // 00220 while (!use_empty()) { 00221 Value *V = use_back(); 00222 #ifndef NDEBUG // Only in -g mode... 00223 if (!isa<Constant>(V)) { 00224 dbgs() << "While deleting: " << *this 00225 << "\n\nUse still stuck around after Def is destroyed: " 00226 << *V << "\n\n"; 00227 } 00228 #endif 00229 assert(isa<Constant>(V) && "References remain to Constant being destroyed"); 00230 cast<Constant>(V)->destroyConstant(); 00231 00232 // The constant should remove itself from our use list... 00233 assert((use_empty() || use_back() != V) && "Constant not removed!"); 00234 } 00235 00236 // Value has no outstanding references it is safe to delete it now... 00237 delete this; 00238 } 00239 00240 static bool canTrapImpl(const Constant *C, 00241 SmallPtrSet<const ConstantExpr *, 4> &NonTrappingOps) { 00242 assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!"); 00243 // The only thing that could possibly trap are constant exprs. 00244 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C); 00245 if (!CE) 00246 return false; 00247 00248 // ConstantExpr traps if any operands can trap. 00249 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) { 00250 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) { 00251 if (NonTrappingOps.insert(Op) && canTrapImpl(Op, NonTrappingOps)) 00252 return true; 00253 } 00254 } 00255 00256 // Otherwise, only specific operations can trap. 00257 switch (CE->getOpcode()) { 00258 default: 00259 return false; 00260 case Instruction::UDiv: 00261 case Instruction::SDiv: 00262 case Instruction::FDiv: 00263 case Instruction::URem: 00264 case Instruction::SRem: 00265 case Instruction::FRem: 00266 // Div and rem can trap if the RHS is not known to be non-zero. 00267 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue()) 00268 return true; 00269 return false; 00270 } 00271 } 00272 00273 /// canTrap - Return true if evaluation of this constant could trap. This is 00274 /// true for things like constant expressions that could divide by zero. 00275 bool Constant::canTrap() const { 00276 SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps; 00277 return canTrapImpl(this, NonTrappingOps); 00278 } 00279 00280 /// isThreadDependent - Return true if the value can vary between threads. 00281 bool Constant::isThreadDependent() const { 00282 SmallPtrSet<const Constant*, 64> Visited; 00283 SmallVector<const Constant*, 64> WorkList; 00284 WorkList.push_back(this); 00285 Visited.insert(this); 00286 00287 while (!WorkList.empty()) { 00288 const Constant *C = WorkList.pop_back_val(); 00289 00290 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) { 00291 if (GV->isThreadLocal()) 00292 return true; 00293 } 00294 00295 for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I) { 00296 const Constant *D = dyn_cast<Constant>(C->getOperand(I)); 00297 if (!D) 00298 continue; 00299 if (Visited.insert(D)) 00300 WorkList.push_back(D); 00301 } 00302 } 00303 00304 return false; 00305 } 00306 00307 /// isConstantUsed - Return true if the constant has users other than constant 00308 /// exprs and other dangling things. 00309 bool Constant::isConstantUsed() const { 00310 for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 00311 const Constant *UC = dyn_cast<Constant>(*UI); 00312 if (UC == 0 || isa<GlobalValue>(UC)) 00313 return true; 00314 00315 if (UC->isConstantUsed()) 00316 return true; 00317 } 00318 return false; 00319 } 00320 00321 00322 00323 /// getRelocationInfo - This method classifies the entry according to 00324 /// whether or not it may generate a relocation entry. This must be 00325 /// conservative, so if it might codegen to a relocatable entry, it should say 00326 /// so. The return values are: 00327 /// 00328 /// NoRelocation: This constant pool entry is guaranteed to never have a 00329 /// relocation applied to it (because it holds a simple constant like 00330 /// '4'). 00331 /// LocalRelocation: This entry has relocations, but the entries are 00332 /// guaranteed to be resolvable by the static linker, so the dynamic 00333 /// linker will never see them. 00334 /// GlobalRelocations: This entry may have arbitrary relocations. 00335 /// 00336 /// FIXME: This really should not be in IR. 00337 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const { 00338 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) { 00339 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility()) 00340 return LocalRelocation; // Local to this file/library. 00341 return GlobalRelocations; // Global reference. 00342 } 00343 00344 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this)) 00345 return BA->getFunction()->getRelocationInfo(); 00346 00347 // While raw uses of blockaddress need to be relocated, differences between 00348 // two of them don't when they are for labels in the same function. This is a 00349 // common idiom when creating a table for the indirect goto extension, so we 00350 // handle it efficiently here. 00351 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) 00352 if (CE->getOpcode() == Instruction::Sub) { 00353 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0)); 00354 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1)); 00355 if (LHS && RHS && 00356 LHS->getOpcode() == Instruction::PtrToInt && 00357 RHS->getOpcode() == Instruction::PtrToInt && 00358 isa<BlockAddress>(LHS->getOperand(0)) && 00359 isa<BlockAddress>(RHS->getOperand(0)) && 00360 cast<BlockAddress>(LHS->getOperand(0))->getFunction() == 00361 cast<BlockAddress>(RHS->getOperand(0))->getFunction()) 00362 return NoRelocation; 00363 } 00364 00365 PossibleRelocationsTy Result = NoRelocation; 00366 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 00367 Result = std::max(Result, 00368 cast<Constant>(getOperand(i))->getRelocationInfo()); 00369 00370 return Result; 00371 } 00372 00373 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove 00374 /// it. This involves recursively eliminating any dead users of the 00375 /// constantexpr. 00376 static bool removeDeadUsersOfConstant(const Constant *C) { 00377 if (isa<GlobalValue>(C)) return false; // Cannot remove this 00378 00379 while (!C->use_empty()) { 00380 const Constant *User = dyn_cast<Constant>(C->use_back()); 00381 if (!User) return false; // Non-constant usage; 00382 if (!removeDeadUsersOfConstant(User)) 00383 return false; // Constant wasn't dead 00384 } 00385 00386 const_cast<Constant*>(C)->destroyConstant(); 00387 return true; 00388 } 00389 00390 00391 /// removeDeadConstantUsers - If there are any dead constant users dangling 00392 /// off of this constant, remove them. This method is useful for clients 00393 /// that want to check to see if a global is unused, but don't want to deal 00394 /// with potentially dead constants hanging off of the globals. 00395 void Constant::removeDeadConstantUsers() const { 00396 Value::const_use_iterator I = use_begin(), E = use_end(); 00397 Value::const_use_iterator LastNonDeadUser = E; 00398 while (I != E) { 00399 const Constant *User = dyn_cast<Constant>(*I); 00400 if (User == 0) { 00401 LastNonDeadUser = I; 00402 ++I; 00403 continue; 00404 } 00405 00406 if (!removeDeadUsersOfConstant(User)) { 00407 // If the constant wasn't dead, remember that this was the last live use 00408 // and move on to the next constant. 00409 LastNonDeadUser = I; 00410 ++I; 00411 continue; 00412 } 00413 00414 // If the constant was dead, then the iterator is invalidated. 00415 if (LastNonDeadUser == E) { 00416 I = use_begin(); 00417 if (I == E) break; 00418 } else { 00419 I = LastNonDeadUser; 00420 ++I; 00421 } 00422 } 00423 } 00424 00425 00426 00427 //===----------------------------------------------------------------------===// 00428 // ConstantInt 00429 //===----------------------------------------------------------------------===// 00430 00431 void ConstantInt::anchor() { } 00432 00433 ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V) 00434 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) { 00435 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type"); 00436 } 00437 00438 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) { 00439 LLVMContextImpl *pImpl = Context.pImpl; 00440 if (!pImpl->TheTrueVal) 00441 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1); 00442 return pImpl->TheTrueVal; 00443 } 00444 00445 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) { 00446 LLVMContextImpl *pImpl = Context.pImpl; 00447 if (!pImpl->TheFalseVal) 00448 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0); 00449 return pImpl->TheFalseVal; 00450 } 00451 00452 Constant *ConstantInt::getTrue(Type *Ty) { 00453 VectorType *VTy = dyn_cast<VectorType>(Ty); 00454 if (!VTy) { 00455 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1."); 00456 return ConstantInt::getTrue(Ty->getContext()); 00457 } 00458 assert(VTy->getElementType()->isIntegerTy(1) && 00459 "True must be vector of i1 or i1."); 00460 return ConstantVector::getSplat(VTy->getNumElements(), 00461 ConstantInt::getTrue(Ty->getContext())); 00462 } 00463 00464 Constant *ConstantInt::getFalse(Type *Ty) { 00465 VectorType *VTy = dyn_cast<VectorType>(Ty); 00466 if (!VTy) { 00467 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1."); 00468 return ConstantInt::getFalse(Ty->getContext()); 00469 } 00470 assert(VTy->getElementType()->isIntegerTy(1) && 00471 "False must be vector of i1 or i1."); 00472 return ConstantVector::getSplat(VTy->getNumElements(), 00473 ConstantInt::getFalse(Ty->getContext())); 00474 } 00475 00476 00477 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap 00478 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the 00479 // operator== and operator!= to ensure that the DenseMap doesn't attempt to 00480 // compare APInt's of different widths, which would violate an APInt class 00481 // invariant which generates an assertion. 00482 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) { 00483 // Get the corresponding integer type for the bit width of the value. 00484 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth()); 00485 // get an existing value or the insertion position 00486 LLVMContextImpl *pImpl = Context.pImpl; 00487 ConstantInt *&Slot = pImpl->IntConstants[DenseMapAPIntKeyInfo::KeyTy(V, ITy)]; 00488 if (!Slot) Slot = new ConstantInt(ITy, V); 00489 return Slot; 00490 } 00491 00492 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) { 00493 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned); 00494 00495 // For vectors, broadcast the value. 00496 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 00497 return ConstantVector::getSplat(VTy->getNumElements(), C); 00498 00499 return C; 00500 } 00501 00502 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, 00503 bool isSigned) { 00504 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned)); 00505 } 00506 00507 ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) { 00508 return get(Ty, V, true); 00509 } 00510 00511 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) { 00512 return get(Ty, V, true); 00513 } 00514 00515 Constant *ConstantInt::get(Type *Ty, const APInt& V) { 00516 ConstantInt *C = get(Ty->getContext(), V); 00517 assert(C->getType() == Ty->getScalarType() && 00518 "ConstantInt type doesn't match the type implied by its value!"); 00519 00520 // For vectors, broadcast the value. 00521 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 00522 return ConstantVector::getSplat(VTy->getNumElements(), C); 00523 00524 return C; 00525 } 00526 00527 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, 00528 uint8_t radix) { 00529 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix)); 00530 } 00531 00532 //===----------------------------------------------------------------------===// 00533 // ConstantFP 00534 //===----------------------------------------------------------------------===// 00535 00536 static const fltSemantics *TypeToFloatSemantics(Type *Ty) { 00537 if (Ty->isHalfTy()) 00538 return &APFloat::IEEEhalf; 00539 if (Ty->isFloatTy()) 00540 return &APFloat::IEEEsingle; 00541 if (Ty->isDoubleTy()) 00542 return &APFloat::IEEEdouble; 00543 if (Ty->isX86_FP80Ty()) 00544 return &APFloat::x87DoubleExtended; 00545 else if (Ty->isFP128Ty()) 00546 return &APFloat::IEEEquad; 00547 00548 assert(Ty->isPPC_FP128Ty() && "Unknown FP format"); 00549 return &APFloat::PPCDoubleDouble; 00550 } 00551 00552 void ConstantFP::anchor() { } 00553 00554 /// get() - This returns a constant fp for the specified value in the 00555 /// specified type. This should only be used for simple constant values like 00556 /// 2.0/1.0 etc, that are known-valid both as double and as the target format. 00557 Constant *ConstantFP::get(Type *Ty, double V) { 00558 LLVMContext &Context = Ty->getContext(); 00559 00560 APFloat FV(V); 00561 bool ignored; 00562 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()), 00563 APFloat::rmNearestTiesToEven, &ignored); 00564 Constant *C = get(Context, FV); 00565 00566 // For vectors, broadcast the value. 00567 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 00568 return ConstantVector::getSplat(VTy->getNumElements(), C); 00569 00570 return C; 00571 } 00572 00573 00574 Constant *ConstantFP::get(Type *Ty, StringRef Str) { 00575 LLVMContext &Context = Ty->getContext(); 00576 00577 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str); 00578 Constant *C = get(Context, FV); 00579 00580 // For vectors, broadcast the value. 00581 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 00582 return ConstantVector::getSplat(VTy->getNumElements(), C); 00583 00584 return C; 00585 } 00586 00587 00588 ConstantFP *ConstantFP::getNegativeZero(Type *Ty) { 00589 LLVMContext &Context = Ty->getContext(); 00590 APFloat apf = cast<ConstantFP>(Constant::getNullValue(Ty))->getValueAPF(); 00591 apf.changeSign(); 00592 return get(Context, apf); 00593 } 00594 00595 00596 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) { 00597 Type *ScalarTy = Ty->getScalarType(); 00598 if (ScalarTy->isFloatingPointTy()) { 00599 Constant *C = getNegativeZero(ScalarTy); 00600 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 00601 return ConstantVector::getSplat(VTy->getNumElements(), C); 00602 return C; 00603 } 00604 00605 return Constant::getNullValue(Ty); 00606 } 00607 00608 00609 // ConstantFP accessors. 00610 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) { 00611 LLVMContextImpl* pImpl = Context.pImpl; 00612 00613 ConstantFP *&Slot = pImpl->FPConstants[DenseMapAPFloatKeyInfo::KeyTy(V)]; 00614 00615 if (!Slot) { 00616 Type *Ty; 00617 if (&V.getSemantics() == &APFloat::IEEEhalf) 00618 Ty = Type::getHalfTy(Context); 00619 else if (&V.getSemantics() == &APFloat::IEEEsingle) 00620 Ty = Type::getFloatTy(Context); 00621 else if (&V.getSemantics() == &APFloat::IEEEdouble) 00622 Ty = Type::getDoubleTy(Context); 00623 else if (&V.getSemantics() == &APFloat::x87DoubleExtended) 00624 Ty = Type::getX86_FP80Ty(Context); 00625 else if (&V.getSemantics() == &APFloat::IEEEquad) 00626 Ty = Type::getFP128Ty(Context); 00627 else { 00628 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble && 00629 "Unknown FP format"); 00630 Ty = Type::getPPC_FP128Ty(Context); 00631 } 00632 Slot = new ConstantFP(Ty, V); 00633 } 00634 00635 return Slot; 00636 } 00637 00638 ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) { 00639 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty); 00640 return ConstantFP::get(Ty->getContext(), 00641 APFloat::getInf(Semantics, Negative)); 00642 } 00643 00644 ConstantFP::ConstantFP(Type *Ty, const APFloat& V) 00645 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) { 00646 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) && 00647 "FP type Mismatch"); 00648 } 00649 00650 bool ConstantFP::isExactlyValue(const APFloat &V) const { 00651 return Val.bitwiseIsEqual(V); 00652 } 00653 00654 //===----------------------------------------------------------------------===// 00655 // ConstantAggregateZero Implementation 00656 //===----------------------------------------------------------------------===// 00657 00658 /// getSequentialElement - If this CAZ has array or vector type, return a zero 00659 /// with the right element type. 00660 Constant *ConstantAggregateZero::getSequentialElement() const { 00661 return Constant::getNullValue(getType()->getSequentialElementType()); 00662 } 00663 00664 /// getStructElement - If this CAZ has struct type, return a zero with the 00665 /// right element type for the specified element. 00666 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const { 00667 return Constant::getNullValue(getType()->getStructElementType(Elt)); 00668 } 00669 00670 /// getElementValue - Return a zero of the right value for the specified GEP 00671 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr). 00672 Constant *ConstantAggregateZero::getElementValue(Constant *C) const { 00673 if (isa<SequentialType>(getType())) 00674 return getSequentialElement(); 00675 return getStructElement(cast<ConstantInt>(C)->getZExtValue()); 00676 } 00677 00678 /// getElementValue - Return a zero of the right value for the specified GEP 00679 /// index. 00680 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const { 00681 if (isa<SequentialType>(getType())) 00682 return getSequentialElement(); 00683 return getStructElement(Idx); 00684 } 00685 00686 00687 //===----------------------------------------------------------------------===// 00688 // UndefValue Implementation 00689 //===----------------------------------------------------------------------===// 00690 00691 /// getSequentialElement - If this undef has array or vector type, return an 00692 /// undef with the right element type. 00693 UndefValue *UndefValue::getSequentialElement() const { 00694 return UndefValue::get(getType()->getSequentialElementType()); 00695 } 00696 00697 /// getStructElement - If this undef has struct type, return a zero with the 00698 /// right element type for the specified element. 00699 UndefValue *UndefValue::getStructElement(unsigned Elt) const { 00700 return UndefValue::get(getType()->getStructElementType(Elt)); 00701 } 00702 00703 /// getElementValue - Return an undef of the right value for the specified GEP 00704 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr). 00705 UndefValue *UndefValue::getElementValue(Constant *C) const { 00706 if (isa<SequentialType>(getType())) 00707 return getSequentialElement(); 00708 return getStructElement(cast<ConstantInt>(C)->getZExtValue()); 00709 } 00710 00711 /// getElementValue - Return an undef of the right value for the specified GEP 00712 /// index. 00713 UndefValue *UndefValue::getElementValue(unsigned Idx) const { 00714 if (isa<SequentialType>(getType())) 00715 return getSequentialElement(); 00716 return getStructElement(Idx); 00717 } 00718 00719 00720 00721 //===----------------------------------------------------------------------===// 00722 // ConstantXXX Classes 00723 //===----------------------------------------------------------------------===// 00724 00725 template <typename ItTy, typename EltTy> 00726 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) { 00727 for (; Start != End; ++Start) 00728 if (*Start != Elt) 00729 return false; 00730 return true; 00731 } 00732 00733 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V) 00734 : Constant(T, ConstantArrayVal, 00735 OperandTraits<ConstantArray>::op_end(this) - V.size(), 00736 V.size()) { 00737 assert(V.size() == T->getNumElements() && 00738 "Invalid initializer vector for constant array"); 00739 for (unsigned i = 0, e = V.size(); i != e; ++i) 00740 assert(V[i]->getType() == T->getElementType() && 00741 "Initializer for array element doesn't match array element type!"); 00742 std::copy(V.begin(), V.end(), op_begin()); 00743 } 00744 00745 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) { 00746 // Empty arrays are canonicalized to ConstantAggregateZero. 00747 if (V.empty()) 00748 return ConstantAggregateZero::get(Ty); 00749 00750 for (unsigned i = 0, e = V.size(); i != e; ++i) { 00751 assert(V[i]->getType() == Ty->getElementType() && 00752 "Wrong type in array element initializer"); 00753 } 00754 LLVMContextImpl *pImpl = Ty->getContext().pImpl; 00755 00756 // If this is an all-zero array, return a ConstantAggregateZero object. If 00757 // all undef, return an UndefValue, if "all simple", then return a 00758 // ConstantDataArray. 00759 Constant *C = V[0]; 00760 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C)) 00761 return UndefValue::get(Ty); 00762 00763 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C)) 00764 return ConstantAggregateZero::get(Ty); 00765 00766 // Check to see if all of the elements are ConstantFP or ConstantInt and if 00767 // the element type is compatible with ConstantDataVector. If so, use it. 00768 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) { 00769 // We speculatively build the elements here even if it turns out that there 00770 // is a constantexpr or something else weird in the array, since it is so 00771 // uncommon for that to happen. 00772 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) { 00773 if (CI->getType()->isIntegerTy(8)) { 00774 SmallVector<uint8_t, 16> Elts; 00775 for (unsigned i = 0, e = V.size(); i != e; ++i) 00776 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i])) 00777 Elts.push_back(CI->getZExtValue()); 00778 else 00779 break; 00780 if (Elts.size() == V.size()) 00781 return ConstantDataArray::get(C->getContext(), Elts); 00782 } else if (CI->getType()->isIntegerTy(16)) { 00783 SmallVector<uint16_t, 16> Elts; 00784 for (unsigned i = 0, e = V.size(); i != e; ++i) 00785 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i])) 00786 Elts.push_back(CI->getZExtValue()); 00787 else 00788 break; 00789 if (Elts.size() == V.size()) 00790 return ConstantDataArray::get(C->getContext(), Elts); 00791 } else if (CI->getType()->isIntegerTy(32)) { 00792 SmallVector<uint32_t, 16> Elts; 00793 for (unsigned i = 0, e = V.size(); i != e; ++i) 00794 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i])) 00795 Elts.push_back(CI->getZExtValue()); 00796 else 00797 break; 00798 if (Elts.size() == V.size()) 00799 return ConstantDataArray::get(C->getContext(), Elts); 00800 } else if (CI->getType()->isIntegerTy(64)) { 00801 SmallVector<uint64_t, 16> Elts; 00802 for (unsigned i = 0, e = V.size(); i != e; ++i) 00803 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i])) 00804 Elts.push_back(CI->getZExtValue()); 00805 else 00806 break; 00807 if (Elts.size() == V.size()) 00808 return ConstantDataArray::get(C->getContext(), Elts); 00809 } 00810 } 00811 00812 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 00813 if (CFP->getType()->isFloatTy()) { 00814 SmallVector<float, 16> Elts; 00815 for (unsigned i = 0, e = V.size(); i != e; ++i) 00816 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i])) 00817 Elts.push_back(CFP->getValueAPF().convertToFloat()); 00818 else 00819 break; 00820 if (Elts.size() == V.size()) 00821 return ConstantDataArray::get(C->getContext(), Elts); 00822 } else if (CFP->getType()->isDoubleTy()) { 00823 SmallVector<double, 16> Elts; 00824 for (unsigned i = 0, e = V.size(); i != e; ++i) 00825 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i])) 00826 Elts.push_back(CFP->getValueAPF().convertToDouble()); 00827 else 00828 break; 00829 if (Elts.size() == V.size()) 00830 return ConstantDataArray::get(C->getContext(), Elts); 00831 } 00832 } 00833 } 00834 00835 // Otherwise, we really do want to create a ConstantArray. 00836 return pImpl->ArrayConstants.getOrCreate(Ty, V); 00837 } 00838 00839 /// getTypeForElements - Return an anonymous struct type to use for a constant 00840 /// with the specified set of elements. The list must not be empty. 00841 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context, 00842 ArrayRef<Constant*> V, 00843 bool Packed) { 00844 unsigned VecSize = V.size(); 00845 SmallVector<Type*, 16> EltTypes(VecSize); 00846 for (unsigned i = 0; i != VecSize; ++i) 00847 EltTypes[i] = V[i]->getType(); 00848 00849 return StructType::get(Context, EltTypes, Packed); 00850 } 00851 00852 00853 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V, 00854 bool Packed) { 00855 assert(!V.empty() && 00856 "ConstantStruct::getTypeForElements cannot be called on empty list"); 00857 return getTypeForElements(V[0]->getContext(), V, Packed); 00858 } 00859 00860 00861 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V) 00862 : Constant(T, ConstantStructVal, 00863 OperandTraits<ConstantStruct>::op_end(this) - V.size(), 00864 V.size()) { 00865 assert(V.size() == T->getNumElements() && 00866 "Invalid initializer vector for constant structure"); 00867 for (unsigned i = 0, e = V.size(); i != e; ++i) 00868 assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) && 00869 "Initializer for struct element doesn't match struct element type!"); 00870 std::copy(V.begin(), V.end(), op_begin()); 00871 } 00872 00873 // ConstantStruct accessors. 00874 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) { 00875 assert((ST->isOpaque() || ST->getNumElements() == V.size()) && 00876 "Incorrect # elements specified to ConstantStruct::get"); 00877 00878 // Create a ConstantAggregateZero value if all elements are zeros. 00879 bool isZero = true; 00880 bool isUndef = false; 00881 00882 if (!V.empty()) { 00883 isUndef = isa<UndefValue>(V[0]); 00884 isZero = V[0]->isNullValue(); 00885 if (isUndef || isZero) { 00886 for (unsigned i = 0, e = V.size(); i != e; ++i) { 00887 if (!V[i]->isNullValue()) 00888 isZero = false; 00889 if (!isa<UndefValue>(V[i])) 00890 isUndef = false; 00891 } 00892 } 00893 } 00894 if (isZero) 00895 return ConstantAggregateZero::get(ST); 00896 if (isUndef) 00897 return UndefValue::get(ST); 00898 00899 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V); 00900 } 00901 00902 Constant *ConstantStruct::get(StructType *T, ...) { 00903 va_list ap; 00904 SmallVector<Constant*, 8> Values; 00905 va_start(ap, T); 00906 while (Constant *Val = va_arg(ap, llvm::Constant*)) 00907 Values.push_back(Val); 00908 va_end(ap); 00909 return get(T, Values); 00910 } 00911 00912 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V) 00913 : Constant(T, ConstantVectorVal, 00914 OperandTraits<ConstantVector>::op_end(this) - V.size(), 00915 V.size()) { 00916 for (size_t i = 0, e = V.size(); i != e; i++) 00917 assert(V[i]->getType() == T->getElementType() && 00918 "Initializer for vector element doesn't match vector element type!"); 00919 std::copy(V.begin(), V.end(), op_begin()); 00920 } 00921 00922 // ConstantVector accessors. 00923 Constant *ConstantVector::get(ArrayRef<Constant*> V) { 00924 assert(!V.empty() && "Vectors can't be empty"); 00925 VectorType *T = VectorType::get(V.front()->getType(), V.size()); 00926 LLVMContextImpl *pImpl = T->getContext().pImpl; 00927 00928 // If this is an all-undef or all-zero vector, return a 00929 // ConstantAggregateZero or UndefValue. 00930 Constant *C = V[0]; 00931 bool isZero = C->isNullValue(); 00932 bool isUndef = isa<UndefValue>(C); 00933 00934 if (isZero || isUndef) { 00935 for (unsigned i = 1, e = V.size(); i != e; ++i) 00936 if (V[i] != C) { 00937 isZero = isUndef = false; 00938 break; 00939 } 00940 } 00941 00942 if (isZero) 00943 return ConstantAggregateZero::get(T); 00944 if (isUndef) 00945 return UndefValue::get(T); 00946 00947 // Check to see if all of the elements are ConstantFP or ConstantInt and if 00948 // the element type is compatible with ConstantDataVector. If so, use it. 00949 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) { 00950 // We speculatively build the elements here even if it turns out that there 00951 // is a constantexpr or something else weird in the array, since it is so 00952 // uncommon for that to happen. 00953 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) { 00954 if (CI->getType()->isIntegerTy(8)) { 00955 SmallVector<uint8_t, 16> Elts; 00956 for (unsigned i = 0, e = V.size(); i != e; ++i) 00957 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i])) 00958 Elts.push_back(CI->getZExtValue()); 00959 else 00960 break; 00961 if (Elts.size() == V.size()) 00962 return ConstantDataVector::get(C->getContext(), Elts); 00963 } else if (CI->getType()->isIntegerTy(16)) { 00964 SmallVector<uint16_t, 16> Elts; 00965 for (unsigned i = 0, e = V.size(); i != e; ++i) 00966 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i])) 00967 Elts.push_back(CI->getZExtValue()); 00968 else 00969 break; 00970 if (Elts.size() == V.size()) 00971 return ConstantDataVector::get(C->getContext(), Elts); 00972 } else if (CI->getType()->isIntegerTy(32)) { 00973 SmallVector<uint32_t, 16> Elts; 00974 for (unsigned i = 0, e = V.size(); i != e; ++i) 00975 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i])) 00976 Elts.push_back(CI->getZExtValue()); 00977 else 00978 break; 00979 if (Elts.size() == V.size()) 00980 return ConstantDataVector::get(C->getContext(), Elts); 00981 } else if (CI->getType()->isIntegerTy(64)) { 00982 SmallVector<uint64_t, 16> Elts; 00983 for (unsigned i = 0, e = V.size(); i != e; ++i) 00984 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i])) 00985 Elts.push_back(CI->getZExtValue()); 00986 else 00987 break; 00988 if (Elts.size() == V.size()) 00989 return ConstantDataVector::get(C->getContext(), Elts); 00990 } 00991 } 00992 00993 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 00994 if (CFP->getType()->isFloatTy()) { 00995 SmallVector<float, 16> Elts; 00996 for (unsigned i = 0, e = V.size(); i != e; ++i) 00997 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i])) 00998 Elts.push_back(CFP->getValueAPF().convertToFloat()); 00999 else 01000 break; 01001 if (Elts.size() == V.size()) 01002 return ConstantDataVector::get(C->getContext(), Elts); 01003 } else if (CFP->getType()->isDoubleTy()) { 01004 SmallVector<double, 16> Elts; 01005 for (unsigned i = 0, e = V.size(); i != e; ++i) 01006 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i])) 01007 Elts.push_back(CFP->getValueAPF().convertToDouble()); 01008 else 01009 break; 01010 if (Elts.size() == V.size()) 01011 return ConstantDataVector::get(C->getContext(), Elts); 01012 } 01013 } 01014 } 01015 01016 // Otherwise, the element type isn't compatible with ConstantDataVector, or 01017 // the operand list constants a ConstantExpr or something else strange. 01018 return pImpl->VectorConstants.getOrCreate(T, V); 01019 } 01020 01021 Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) { 01022 // If this splat is compatible with ConstantDataVector, use it instead of 01023 // ConstantVector. 01024 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) && 01025 ConstantDataSequential::isElementTypeCompatible(V->getType())) 01026 return ConstantDataVector::getSplat(NumElts, V); 01027 01028 SmallVector<Constant*, 32> Elts(NumElts, V); 01029 return get(Elts); 01030 } 01031 01032 01033 // Utility function for determining if a ConstantExpr is a CastOp or not. This 01034 // can't be inline because we don't want to #include Instruction.h into 01035 // Constant.h 01036 bool ConstantExpr::isCast() const { 01037 return Instruction::isCast(getOpcode()); 01038 } 01039 01040 bool ConstantExpr::isCompare() const { 01041 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp; 01042 } 01043 01044 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const { 01045 if (getOpcode() != Instruction::GetElementPtr) return false; 01046 01047 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this); 01048 User::const_op_iterator OI = llvm::next(this->op_begin()); 01049 01050 // Skip the first index, as it has no static limit. 01051 ++GEPI; 01052 ++OI; 01053 01054 // The remaining indices must be compile-time known integers within the 01055 // bounds of the corresponding notional static array types. 01056 for (; GEPI != E; ++GEPI, ++OI) { 01057 ConstantInt *CI = dyn_cast<ConstantInt>(*OI); 01058 if (!CI) return false; 01059 if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI)) 01060 if (CI->getValue().getActiveBits() > 64 || 01061 CI->getZExtValue() >= ATy->getNumElements()) 01062 return false; 01063 } 01064 01065 // All the indices checked out. 01066 return true; 01067 } 01068 01069 bool ConstantExpr::hasIndices() const { 01070 return getOpcode() == Instruction::ExtractValue || 01071 getOpcode() == Instruction::InsertValue; 01072 } 01073 01074 ArrayRef<unsigned> ConstantExpr::getIndices() const { 01075 if (const ExtractValueConstantExpr *EVCE = 01076 dyn_cast<ExtractValueConstantExpr>(this)) 01077 return EVCE->Indices; 01078 01079 return cast<InsertValueConstantExpr>(this)->Indices; 01080 } 01081 01082 unsigned ConstantExpr::getPredicate() const { 01083 assert(isCompare()); 01084 return ((const CompareConstantExpr*)this)->predicate; 01085 } 01086 01087 /// getWithOperandReplaced - Return a constant expression identical to this 01088 /// one, but with the specified operand set to the specified value. 01089 Constant * 01090 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const { 01091 assert(Op->getType() == getOperand(OpNo)->getType() && 01092 "Replacing operand with value of different type!"); 01093 if (getOperand(OpNo) == Op) 01094 return const_cast<ConstantExpr*>(this); 01095 01096 SmallVector<Constant*, 8> NewOps; 01097 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 01098 NewOps.push_back(i == OpNo ? Op : getOperand(i)); 01099 01100 return getWithOperands(NewOps); 01101 } 01102 01103 /// getWithOperands - This returns the current constant expression with the 01104 /// operands replaced with the specified values. The specified array must 01105 /// have the same number of operands as our current one. 01106 Constant *ConstantExpr:: 01107 getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const { 01108 assert(Ops.size() == getNumOperands() && "Operand count mismatch!"); 01109 bool AnyChange = Ty != getType(); 01110 for (unsigned i = 0; i != Ops.size(); ++i) 01111 AnyChange |= Ops[i] != getOperand(i); 01112 01113 if (!AnyChange) // No operands changed, return self. 01114 return const_cast<ConstantExpr*>(this); 01115 01116 switch (getOpcode()) { 01117 case Instruction::Trunc: 01118 case Instruction::ZExt: 01119 case Instruction::SExt: 01120 case Instruction::FPTrunc: 01121 case Instruction::FPExt: 01122 case Instruction::UIToFP: 01123 case Instruction::SIToFP: 01124 case Instruction::FPToUI: 01125 case Instruction::FPToSI: 01126 case Instruction::PtrToInt: 01127 case Instruction::IntToPtr: 01128 case Instruction::BitCast: 01129 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty); 01130 case Instruction::Select: 01131 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]); 01132 case Instruction::InsertElement: 01133 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]); 01134 case Instruction::ExtractElement: 01135 return ConstantExpr::getExtractElement(Ops[0], Ops[1]); 01136 case Instruction::InsertValue: 01137 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices()); 01138 case Instruction::ExtractValue: 01139 return ConstantExpr::getExtractValue(Ops[0], getIndices()); 01140 case Instruction::ShuffleVector: 01141 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]); 01142 case Instruction::GetElementPtr: 01143 return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1), 01144 cast<GEPOperator>(this)->isInBounds()); 01145 case Instruction::ICmp: 01146 case Instruction::FCmp: 01147 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]); 01148 default: 01149 assert(getNumOperands() == 2 && "Must be binary operator?"); 01150 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData); 01151 } 01152 } 01153 01154 01155 //===----------------------------------------------------------------------===// 01156 // isValueValidForType implementations 01157 01158 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) { 01159 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay 01160 if (Ty->isIntegerTy(1)) 01161 return Val == 0 || Val == 1; 01162 if (NumBits >= 64) 01163 return true; // always true, has to fit in largest type 01164 uint64_t Max = (1ll << NumBits) - 1; 01165 return Val <= Max; 01166 } 01167 01168 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) { 01169 unsigned NumBits = Ty->getIntegerBitWidth(); 01170 if (Ty->isIntegerTy(1)) 01171 return Val == 0 || Val == 1 || Val == -1; 01172 if (NumBits >= 64) 01173 return true; // always true, has to fit in largest type 01174 int64_t Min = -(1ll << (NumBits-1)); 01175 int64_t Max = (1ll << (NumBits-1)) - 1; 01176 return (Val >= Min && Val <= Max); 01177 } 01178 01179 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) { 01180 // convert modifies in place, so make a copy. 01181 APFloat Val2 = APFloat(Val); 01182 bool losesInfo; 01183 switch (Ty->getTypeID()) { 01184 default: 01185 return false; // These can't be represented as floating point! 01186 01187 // FIXME rounding mode needs to be more flexible 01188 case Type::HalfTyID: { 01189 if (&Val2.getSemantics() == &APFloat::IEEEhalf) 01190 return true; 01191 Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo); 01192 return !losesInfo; 01193 } 01194 case Type::FloatTyID: { 01195 if (&Val2.getSemantics() == &APFloat::IEEEsingle) 01196 return true; 01197 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo); 01198 return !losesInfo; 01199 } 01200 case Type::DoubleTyID: { 01201 if (&Val2.getSemantics() == &APFloat::IEEEhalf || 01202 &Val2.getSemantics() == &APFloat::IEEEsingle || 01203 &Val2.getSemantics() == &APFloat::IEEEdouble) 01204 return true; 01205 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo); 01206 return !losesInfo; 01207 } 01208 case Type::X86_FP80TyID: 01209 return &Val2.getSemantics() == &APFloat::IEEEhalf || 01210 &Val2.getSemantics() == &APFloat::IEEEsingle || 01211 &Val2.getSemantics() == &APFloat::IEEEdouble || 01212 &Val2.getSemantics() == &APFloat::x87DoubleExtended; 01213 case Type::FP128TyID: 01214 return &Val2.getSemantics() == &APFloat::IEEEhalf || 01215 &Val2.getSemantics() == &APFloat::IEEEsingle || 01216 &Val2.getSemantics() == &APFloat::IEEEdouble || 01217 &Val2.getSemantics() == &APFloat::IEEEquad; 01218 case Type::PPC_FP128TyID: 01219 return &Val2.getSemantics() == &APFloat::IEEEhalf || 01220 &Val2.getSemantics() == &APFloat::IEEEsingle || 01221 &Val2.getSemantics() == &APFloat::IEEEdouble || 01222 &Val2.getSemantics() == &APFloat::PPCDoubleDouble; 01223 } 01224 } 01225 01226 01227 //===----------------------------------------------------------------------===// 01228 // Factory Function Implementation 01229 01230 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) { 01231 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) && 01232 "Cannot create an aggregate zero of non-aggregate type!"); 01233 01234 ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty]; 01235 if (Entry == 0) 01236 Entry = new ConstantAggregateZero(Ty); 01237 01238 return Entry; 01239 } 01240 01241 /// destroyConstant - Remove the constant from the constant table. 01242 /// 01243 void ConstantAggregateZero::destroyConstant() { 01244 getContext().pImpl->CAZConstants.erase(getType()); 01245 destroyConstantImpl(); 01246 } 01247 01248 /// destroyConstant - Remove the constant from the constant table... 01249 /// 01250 void ConstantArray::destroyConstant() { 01251 getType()->getContext().pImpl->ArrayConstants.remove(this); 01252 destroyConstantImpl(); 01253 } 01254 01255 01256 //---- ConstantStruct::get() implementation... 01257 // 01258 01259 // destroyConstant - Remove the constant from the constant table... 01260 // 01261 void ConstantStruct::destroyConstant() { 01262 getType()->getContext().pImpl->StructConstants.remove(this); 01263 destroyConstantImpl(); 01264 } 01265 01266 // destroyConstant - Remove the constant from the constant table... 01267 // 01268 void ConstantVector::destroyConstant() { 01269 getType()->getContext().pImpl->VectorConstants.remove(this); 01270 destroyConstantImpl(); 01271 } 01272 01273 /// getSplatValue - If this is a splat vector constant, meaning that all of 01274 /// the elements have the same value, return that value. Otherwise return 0. 01275 Constant *Constant::getSplatValue() const { 01276 assert(this->getType()->isVectorTy() && "Only valid for vectors!"); 01277 if (isa<ConstantAggregateZero>(this)) 01278 return getNullValue(this->getType()->getVectorElementType()); 01279 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) 01280 return CV->getSplatValue(); 01281 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) 01282 return CV->getSplatValue(); 01283 return 0; 01284 } 01285 01286 /// getSplatValue - If this is a splat constant, where all of the 01287 /// elements have the same value, return that value. Otherwise return null. 01288 Constant *ConstantVector::getSplatValue() const { 01289 // Check out first element. 01290 Constant *Elt = getOperand(0); 01291 // Then make sure all remaining elements point to the same value. 01292 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) 01293 if (getOperand(I) != Elt) 01294 return 0; 01295 return Elt; 01296 } 01297 01298 /// If C is a constant integer then return its value, otherwise C must be a 01299 /// vector of constant integers, all equal, and the common value is returned. 01300 const APInt &Constant::getUniqueInteger() const { 01301 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this)) 01302 return CI->getValue(); 01303 assert(this->getSplatValue() && "Doesn't contain a unique integer!"); 01304 const Constant *C = this->getAggregateElement(0U); 01305 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!"); 01306 return cast<ConstantInt>(C)->getValue(); 01307 } 01308 01309 01310 //---- ConstantPointerNull::get() implementation. 01311 // 01312 01313 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) { 01314 ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty]; 01315 if (Entry == 0) 01316 Entry = new ConstantPointerNull(Ty); 01317 01318 return Entry; 01319 } 01320 01321 // destroyConstant - Remove the constant from the constant table... 01322 // 01323 void ConstantPointerNull::destroyConstant() { 01324 getContext().pImpl->CPNConstants.erase(getType()); 01325 // Free the constant and any dangling references to it. 01326 destroyConstantImpl(); 01327 } 01328 01329 01330 //---- UndefValue::get() implementation. 01331 // 01332 01333 UndefValue *UndefValue::get(Type *Ty) { 01334 UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty]; 01335 if (Entry == 0) 01336 Entry = new UndefValue(Ty); 01337 01338 return Entry; 01339 } 01340 01341 // destroyConstant - Remove the constant from the constant table. 01342 // 01343 void UndefValue::destroyConstant() { 01344 // Free the constant and any dangling references to it. 01345 getContext().pImpl->UVConstants.erase(getType()); 01346 destroyConstantImpl(); 01347 } 01348 01349 //---- BlockAddress::get() implementation. 01350 // 01351 01352 BlockAddress *BlockAddress::get(BasicBlock *BB) { 01353 assert(BB->getParent() != 0 && "Block must have a parent"); 01354 return get(BB->getParent(), BB); 01355 } 01356 01357 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) { 01358 BlockAddress *&BA = 01359 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)]; 01360 if (BA == 0) 01361 BA = new BlockAddress(F, BB); 01362 01363 assert(BA->getFunction() == F && "Basic block moved between functions"); 01364 return BA; 01365 } 01366 01367 BlockAddress::BlockAddress(Function *F, BasicBlock *BB) 01368 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal, 01369 &Op<0>(), 2) { 01370 setOperand(0, F); 01371 setOperand(1, BB); 01372 BB->AdjustBlockAddressRefCount(1); 01373 } 01374 01375 01376 // destroyConstant - Remove the constant from the constant table. 01377 // 01378 void BlockAddress::destroyConstant() { 01379 getFunction()->getType()->getContext().pImpl 01380 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock())); 01381 getBasicBlock()->AdjustBlockAddressRefCount(-1); 01382 destroyConstantImpl(); 01383 } 01384 01385 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) { 01386 // This could be replacing either the Basic Block or the Function. In either 01387 // case, we have to remove the map entry. 01388 Function *NewF = getFunction(); 01389 BasicBlock *NewBB = getBasicBlock(); 01390 01391 if (U == &Op<0>()) 01392 NewF = cast<Function>(To->stripPointerCasts()); 01393 else 01394 NewBB = cast<BasicBlock>(To); 01395 01396 // See if the 'new' entry already exists, if not, just update this in place 01397 // and return early. 01398 BlockAddress *&NewBA = 01399 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)]; 01400 if (NewBA == 0) { 01401 getBasicBlock()->AdjustBlockAddressRefCount(-1); 01402 01403 // Remove the old entry, this can't cause the map to rehash (just a 01404 // tombstone will get added). 01405 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(), 01406 getBasicBlock())); 01407 NewBA = this; 01408 setOperand(0, NewF); 01409 setOperand(1, NewBB); 01410 getBasicBlock()->AdjustBlockAddressRefCount(1); 01411 return; 01412 } 01413 01414 // Otherwise, I do need to replace this with an existing value. 01415 assert(NewBA != this && "I didn't contain From!"); 01416 01417 // Everyone using this now uses the replacement. 01418 replaceAllUsesWith(NewBA); 01419 01420 destroyConstant(); 01421 } 01422 01423 //---- ConstantExpr::get() implementations. 01424 // 01425 01426 /// This is a utility function to handle folding of casts and lookup of the 01427 /// cast in the ExprConstants map. It is used by the various get* methods below. 01428 static inline Constant *getFoldedCast( 01429 Instruction::CastOps opc, Constant *C, Type *Ty) { 01430 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!"); 01431 // Fold a few common cases 01432 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty)) 01433 return FC; 01434 01435 LLVMContextImpl *pImpl = Ty->getContext().pImpl; 01436 01437 // Look up the constant in the table first to ensure uniqueness. 01438 ExprMapKeyType Key(opc, C); 01439 01440 return pImpl->ExprConstants.getOrCreate(Ty, Key); 01441 } 01442 01443 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty) { 01444 Instruction::CastOps opc = Instruction::CastOps(oc); 01445 assert(Instruction::isCast(opc) && "opcode out of range"); 01446 assert(C && Ty && "Null arguments to getCast"); 01447 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!"); 01448 01449 switch (opc) { 01450 default: 01451 llvm_unreachable("Invalid cast opcode"); 01452 case Instruction::Trunc: return getTrunc(C, Ty); 01453 case Instruction::ZExt: return getZExt(C, Ty); 01454 case Instruction::SExt: return getSExt(C, Ty); 01455 case Instruction::FPTrunc: return getFPTrunc(C, Ty); 01456 case Instruction::FPExt: return getFPExtend(C, Ty); 01457 case Instruction::UIToFP: return getUIToFP(C, Ty); 01458 case Instruction::SIToFP: return getSIToFP(C, Ty); 01459 case Instruction::FPToUI: return getFPToUI(C, Ty); 01460 case Instruction::FPToSI: return getFPToSI(C, Ty); 01461 case Instruction::PtrToInt: return getPtrToInt(C, Ty); 01462 case Instruction::IntToPtr: return getIntToPtr(C, Ty); 01463 case Instruction::BitCast: return getBitCast(C, Ty); 01464 } 01465 } 01466 01467 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) { 01468 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 01469 return getBitCast(C, Ty); 01470 return getZExt(C, Ty); 01471 } 01472 01473 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) { 01474 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 01475 return getBitCast(C, Ty); 01476 return getSExt(C, Ty); 01477 } 01478 01479 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) { 01480 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 01481 return getBitCast(C, Ty); 01482 return getTrunc(C, Ty); 01483 } 01484 01485 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) { 01486 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 01487 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) && 01488 "Invalid cast"); 01489 01490 if (Ty->isIntOrIntVectorTy()) 01491 return getPtrToInt(S, Ty); 01492 return getBitCast(S, Ty); 01493 } 01494 01495 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, 01496 bool isSigned) { 01497 assert(C->getType()->isIntOrIntVectorTy() && 01498 Ty->isIntOrIntVectorTy() && "Invalid cast"); 01499 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 01500 unsigned DstBits = Ty->getScalarSizeInBits(); 01501 Instruction::CastOps opcode = 01502 (SrcBits == DstBits ? Instruction::BitCast : 01503 (SrcBits > DstBits ? Instruction::Trunc : 01504 (isSigned ? Instruction::SExt : Instruction::ZExt))); 01505 return getCast(opcode, C, Ty); 01506 } 01507 01508 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) { 01509 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 01510 "Invalid cast"); 01511 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 01512 unsigned DstBits = Ty->getScalarSizeInBits(); 01513 if (SrcBits == DstBits) 01514 return C; // Avoid a useless cast 01515 Instruction::CastOps opcode = 01516 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt); 01517 return getCast(opcode, C, Ty); 01518 } 01519 01520 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty) { 01521 #ifndef NDEBUG 01522 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 01523 bool toVec = Ty->getTypeID() == Type::VectorTyID; 01524 #endif 01525 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 01526 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer"); 01527 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral"); 01528 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&& 01529 "SrcTy must be larger than DestTy for Trunc!"); 01530 01531 return getFoldedCast(Instruction::Trunc, C, Ty); 01532 } 01533 01534 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty) { 01535 #ifndef NDEBUG 01536 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 01537 bool toVec = Ty->getTypeID() == Type::VectorTyID; 01538 #endif 01539 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 01540 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral"); 01541 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer"); 01542 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&& 01543 "SrcTy must be smaller than DestTy for SExt!"); 01544 01545 return getFoldedCast(Instruction::SExt, C, Ty); 01546 } 01547 01548 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty) { 01549 #ifndef NDEBUG 01550 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 01551 bool toVec = Ty->getTypeID() == Type::VectorTyID; 01552 #endif 01553 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 01554 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral"); 01555 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer"); 01556 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&& 01557 "SrcTy must be smaller than DestTy for ZExt!"); 01558 01559 return getFoldedCast(Instruction::ZExt, C, Ty); 01560 } 01561 01562 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty) { 01563 #ifndef NDEBUG 01564 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 01565 bool toVec = Ty->getTypeID() == Type::VectorTyID; 01566 #endif 01567 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 01568 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 01569 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&& 01570 "This is an illegal floating point truncation!"); 01571 return getFoldedCast(Instruction::FPTrunc, C, Ty); 01572 } 01573 01574 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty) { 01575 #ifndef NDEBUG 01576 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 01577 bool toVec = Ty->getTypeID() == Type::VectorTyID; 01578 #endif 01579 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 01580 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 01581 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&& 01582 "This is an illegal floating point extension!"); 01583 return getFoldedCast(Instruction::FPExt, C, Ty); 01584 } 01585 01586 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty) { 01587 #ifndef NDEBUG 01588 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 01589 bool toVec = Ty->getTypeID() == Type::VectorTyID; 01590 #endif 01591 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 01592 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() && 01593 "This is an illegal uint to floating point cast!"); 01594 return getFoldedCast(Instruction::UIToFP, C, Ty); 01595 } 01596 01597 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty) { 01598 #ifndef NDEBUG 01599 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 01600 bool toVec = Ty->getTypeID() == Type::VectorTyID; 01601 #endif 01602 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 01603 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() && 01604 "This is an illegal sint to floating point cast!"); 01605 return getFoldedCast(Instruction::SIToFP, C, Ty); 01606 } 01607 01608 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty) { 01609 #ifndef NDEBUG 01610 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 01611 bool toVec = Ty->getTypeID() == Type::VectorTyID; 01612 #endif 01613 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 01614 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() && 01615 "This is an illegal floating point to uint cast!"); 01616 return getFoldedCast(Instruction::FPToUI, C, Ty); 01617 } 01618 01619 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty) { 01620 #ifndef NDEBUG 01621 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID; 01622 bool toVec = Ty->getTypeID() == Type::VectorTyID; 01623 #endif 01624 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector"); 01625 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() && 01626 "This is an illegal floating point to sint cast!"); 01627 return getFoldedCast(Instruction::FPToSI, C, Ty); 01628 } 01629 01630 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy) { 01631 assert(C->getType()->getScalarType()->isPointerTy() && 01632 "PtrToInt source must be pointer or pointer vector"); 01633 assert(DstTy->getScalarType()->isIntegerTy() && 01634 "PtrToInt destination must be integer or integer vector"); 01635 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy)); 01636 if (isa<VectorType>(C->getType())) 01637 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&& 01638 "Invalid cast between a different number of vector elements"); 01639 return getFoldedCast(Instruction::PtrToInt, C, DstTy); 01640 } 01641 01642 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy) { 01643 assert(C->getType()->getScalarType()->isIntegerTy() && 01644 "IntToPtr source must be integer or integer vector"); 01645 assert(DstTy->getScalarType()->isPointerTy() && 01646 "IntToPtr destination must be a pointer or pointer vector"); 01647 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy)); 01648 if (isa<VectorType>(C->getType())) 01649 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&& 01650 "Invalid cast between a different number of vector elements"); 01651 return getFoldedCast(Instruction::IntToPtr, C, DstTy); 01652 } 01653 01654 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy) { 01655 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) && 01656 "Invalid constantexpr bitcast!"); 01657 01658 // It is common to ask for a bitcast of a value to its own type, handle this 01659 // speedily. 01660 if (C->getType() == DstTy) return C; 01661 01662 return getFoldedCast(Instruction::BitCast, C, DstTy); 01663 } 01664 01665 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2, 01666 unsigned Flags) { 01667 // Check the operands for consistency first. 01668 assert(Opcode >= Instruction::BinaryOpsBegin && 01669 Opcode < Instruction::BinaryOpsEnd && 01670 "Invalid opcode in binary constant expression"); 01671 assert(C1->getType() == C2->getType() && 01672 "Operand types in binary constant expression should match"); 01673 01674 #ifndef NDEBUG 01675 switch (Opcode) { 01676 case Instruction::Add: 01677 case Instruction::Sub: 01678 case Instruction::Mul: 01679 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 01680 assert(C1->getType()->isIntOrIntVectorTy() && 01681 "Tried to create an integer operation on a non-integer type!"); 01682 break; 01683 case Instruction::FAdd: 01684 case Instruction::FSub: 01685 case Instruction::FMul: 01686 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 01687 assert(C1->getType()->isFPOrFPVectorTy() && 01688 "Tried to create a floating-point operation on a " 01689 "non-floating-point type!"); 01690 break; 01691 case Instruction::UDiv: 01692 case Instruction::SDiv: 01693 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 01694 assert(C1->getType()->isIntOrIntVectorTy() && 01695 "Tried to create an arithmetic operation on a non-arithmetic type!"); 01696 break; 01697 case Instruction::FDiv: 01698 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 01699 assert(C1->getType()->isFPOrFPVectorTy() && 01700 "Tried to create an arithmetic operation on a non-arithmetic type!"); 01701 break; 01702 case Instruction::URem: 01703 case Instruction::SRem: 01704 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 01705 assert(C1->getType()->isIntOrIntVectorTy() && 01706 "Tried to create an arithmetic operation on a non-arithmetic type!"); 01707 break; 01708 case Instruction::FRem: 01709 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 01710 assert(C1->getType()->isFPOrFPVectorTy() && 01711 "Tried to create an arithmetic operation on a non-arithmetic type!"); 01712 break; 01713 case Instruction::And: 01714 case Instruction::Or: 01715 case Instruction::Xor: 01716 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 01717 assert(C1->getType()->isIntOrIntVectorTy() && 01718 "Tried to create a logical operation on a non-integral type!"); 01719 break; 01720 case Instruction::Shl: 01721 case Instruction::LShr: 01722 case Instruction::AShr: 01723 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 01724 assert(C1->getType()->isIntOrIntVectorTy() && 01725 "Tried to create a shift operation on a non-integer type!"); 01726 break; 01727 default: 01728 break; 01729 } 01730 #endif 01731 01732 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2)) 01733 return FC; // Fold a few common cases. 01734 01735 Constant *ArgVec[] = { C1, C2 }; 01736 ExprMapKeyType Key(Opcode, ArgVec, 0, Flags); 01737 01738 LLVMContextImpl *pImpl = C1->getContext().pImpl; 01739 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key); 01740 } 01741 01742 Constant *ConstantExpr::getSizeOf(Type* Ty) { 01743 // sizeof is implemented as: (i64) gep (Ty*)null, 1 01744 // Note that a non-inbounds gep is used, as null isn't within any object. 01745 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1); 01746 Constant *GEP = getGetElementPtr( 01747 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx); 01748 return getPtrToInt(GEP, 01749 Type::getInt64Ty(Ty->getContext())); 01750 } 01751 01752 Constant *ConstantExpr::getAlignOf(Type* Ty) { 01753 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1 01754 // Note that a non-inbounds gep is used, as null isn't within any object. 01755 Type *AligningTy = 01756 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL); 01757 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo()); 01758 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0); 01759 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1); 01760 Constant *Indices[2] = { Zero, One }; 01761 Constant *GEP = getGetElementPtr(NullPtr, Indices); 01762 return getPtrToInt(GEP, 01763 Type::getInt64Ty(Ty->getContext())); 01764 } 01765 01766 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) { 01767 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()), 01768 FieldNo)); 01769 } 01770 01771 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) { 01772 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo 01773 // Note that a non-inbounds gep is used, as null isn't within any object. 01774 Constant *GEPIdx[] = { 01775 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0), 01776 FieldNo 01777 }; 01778 Constant *GEP = getGetElementPtr( 01779 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx); 01780 return getPtrToInt(GEP, 01781 Type::getInt64Ty(Ty->getContext())); 01782 } 01783 01784 Constant *ConstantExpr::getCompare(unsigned short Predicate, 01785 Constant *C1, Constant *C2) { 01786 assert(C1->getType() == C2->getType() && "Op types should be identical!"); 01787 01788 switch (Predicate) { 01789 default: llvm_unreachable("Invalid CmpInst predicate"); 01790 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT: 01791 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE: 01792 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO: 01793 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE: 01794 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE: 01795 case CmpInst::FCMP_TRUE: 01796 return getFCmp(Predicate, C1, C2); 01797 01798 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT: 01799 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE: 01800 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT: 01801 case CmpInst::ICMP_SLE: 01802 return getICmp(Predicate, C1, C2); 01803 } 01804 } 01805 01806 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) { 01807 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands"); 01808 01809 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2)) 01810 return SC; // Fold common cases 01811 01812 Constant *ArgVec[] = { C, V1, V2 }; 01813 ExprMapKeyType Key(Instruction::Select, ArgVec); 01814 01815 LLVMContextImpl *pImpl = C->getContext().pImpl; 01816 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key); 01817 } 01818 01819 Constant *ConstantExpr::getGetElementPtr(Constant *C, ArrayRef<Value *> Idxs, 01820 bool InBounds) { 01821 assert(C->getType()->isPtrOrPtrVectorTy() && 01822 "Non-pointer type for constant GetElementPtr expression"); 01823 01824 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs)) 01825 return FC; // Fold a few common cases. 01826 01827 // Get the result type of the getelementptr! 01828 Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), Idxs); 01829 assert(Ty && "GEP indices invalid!"); 01830 unsigned AS = C->getType()->getPointerAddressSpace(); 01831 Type *ReqTy = Ty->getPointerTo(AS); 01832 if (VectorType *VecTy = dyn_cast<VectorType>(C->getType())) 01833 ReqTy = VectorType::get(ReqTy, VecTy->getNumElements()); 01834 01835 // Look up the constant in the table first to ensure uniqueness 01836 std::vector<Constant*> ArgVec; 01837 ArgVec.reserve(1 + Idxs.size()); 01838 ArgVec.push_back(C); 01839 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) { 01840 assert(Idxs[i]->getType()->isVectorTy() == ReqTy->isVectorTy() && 01841 "getelementptr index type missmatch"); 01842 assert((!Idxs[i]->getType()->isVectorTy() || 01843 ReqTy->getVectorNumElements() == 01844 Idxs[i]->getType()->getVectorNumElements()) && 01845 "getelementptr index type missmatch"); 01846 ArgVec.push_back(cast<Constant>(Idxs[i])); 01847 } 01848 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0, 01849 InBounds ? GEPOperator::IsInBounds : 0); 01850 01851 LLVMContextImpl *pImpl = C->getContext().pImpl; 01852 return pImpl->ExprConstants.getOrCreate(ReqTy, Key); 01853 } 01854 01855 Constant * 01856 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) { 01857 assert(LHS->getType() == RHS->getType()); 01858 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 01859 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate"); 01860 01861 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS)) 01862 return FC; // Fold a few common cases... 01863 01864 // Look up the constant in the table first to ensure uniqueness 01865 Constant *ArgVec[] = { LHS, RHS }; 01866 // Get the key type with both the opcode and predicate 01867 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred); 01868 01869 Type *ResultTy = Type::getInt1Ty(LHS->getContext()); 01870 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType())) 01871 ResultTy = VectorType::get(ResultTy, VT->getNumElements()); 01872 01873 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl; 01874 return pImpl->ExprConstants.getOrCreate(ResultTy, Key); 01875 } 01876 01877 Constant * 01878 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) { 01879 assert(LHS->getType() == RHS->getType()); 01880 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate"); 01881 01882 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS)) 01883 return FC; // Fold a few common cases... 01884 01885 // Look up the constant in the table first to ensure uniqueness 01886 Constant *ArgVec[] = { LHS, RHS }; 01887 // Get the key type with both the opcode and predicate 01888 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred); 01889 01890 Type *ResultTy = Type::getInt1Ty(LHS->getContext()); 01891 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType())) 01892 ResultTy = VectorType::get(ResultTy, VT->getNumElements()); 01893 01894 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl; 01895 return pImpl->ExprConstants.getOrCreate(ResultTy, Key); 01896 } 01897 01898 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) { 01899 assert(Val->getType()->isVectorTy() && 01900 "Tried to create extractelement operation on non-vector type!"); 01901 assert(Idx->getType()->isIntegerTy(32) && 01902 "Extractelement index must be i32 type!"); 01903 01904 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx)) 01905 return FC; // Fold a few common cases. 01906 01907 // Look up the constant in the table first to ensure uniqueness 01908 Constant *ArgVec[] = { Val, Idx }; 01909 const ExprMapKeyType Key(Instruction::ExtractElement, ArgVec); 01910 01911 LLVMContextImpl *pImpl = Val->getContext().pImpl; 01912 Type *ReqTy = Val->getType()->getVectorElementType(); 01913 return pImpl->ExprConstants.getOrCreate(ReqTy, Key); 01914 } 01915 01916 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 01917 Constant *Idx) { 01918 assert(Val->getType()->isVectorTy() && 01919 "Tried to create insertelement operation on non-vector type!"); 01920 assert(Elt->getType() == Val->getType()->getVectorElementType() && 01921 "Insertelement types must match!"); 01922 assert(Idx->getType()->isIntegerTy(32) && 01923 "Insertelement index must be i32 type!"); 01924 01925 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx)) 01926 return FC; // Fold a few common cases. 01927 // Look up the constant in the table first to ensure uniqueness 01928 Constant *ArgVec[] = { Val, Elt, Idx }; 01929 const ExprMapKeyType Key(Instruction::InsertElement, ArgVec); 01930 01931 LLVMContextImpl *pImpl = Val->getContext().pImpl; 01932 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key); 01933 } 01934 01935 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 01936 Constant *Mask) { 01937 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) && 01938 "Invalid shuffle vector constant expr operands!"); 01939 01940 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask)) 01941 return FC; // Fold a few common cases. 01942 01943 unsigned NElts = Mask->getType()->getVectorNumElements(); 01944 Type *EltTy = V1->getType()->getVectorElementType(); 01945 Type *ShufTy = VectorType::get(EltTy, NElts); 01946 01947 // Look up the constant in the table first to ensure uniqueness 01948 Constant *ArgVec[] = { V1, V2, Mask }; 01949 const ExprMapKeyType Key(Instruction::ShuffleVector, ArgVec); 01950 01951 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl; 01952 return pImpl->ExprConstants.getOrCreate(ShufTy, Key); 01953 } 01954 01955 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val, 01956 ArrayRef<unsigned> Idxs) { 01957 assert(ExtractValueInst::getIndexedType(Agg->getType(), 01958 Idxs) == Val->getType() && 01959 "insertvalue indices invalid!"); 01960 assert(Agg->getType()->isFirstClassType() && 01961 "Non-first-class type for constant insertvalue expression"); 01962 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs); 01963 assert(FC && "insertvalue constant expr couldn't be folded!"); 01964 return FC; 01965 } 01966 01967 Constant *ConstantExpr::getExtractValue(Constant *Agg, 01968 ArrayRef<unsigned> Idxs) { 01969 assert(Agg->getType()->isFirstClassType() && 01970 "Tried to create extractelement operation on non-first-class type!"); 01971 01972 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs); 01973 (void)ReqTy; 01974 assert(ReqTy && "extractvalue indices invalid!"); 01975 01976 assert(Agg->getType()->isFirstClassType() && 01977 "Non-first-class type for constant extractvalue expression"); 01978 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs); 01979 assert(FC && "ExtractValue constant expr couldn't be folded!"); 01980 return FC; 01981 } 01982 01983 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) { 01984 assert(C->getType()->isIntOrIntVectorTy() && 01985 "Cannot NEG a nonintegral value!"); 01986 return getSub(ConstantFP::getZeroValueForNegation(C->getType()), 01987 C, HasNUW, HasNSW); 01988 } 01989 01990 Constant *ConstantExpr::getFNeg(Constant *C) { 01991 assert(C->getType()->isFPOrFPVectorTy() && 01992 "Cannot FNEG a non-floating-point value!"); 01993 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C); 01994 } 01995 01996 Constant *ConstantExpr::getNot(Constant *C) { 01997 assert(C->getType()->isIntOrIntVectorTy() && 01998 "Cannot NOT a nonintegral value!"); 01999 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType())); 02000 } 02001 02002 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2, 02003 bool HasNUW, bool HasNSW) { 02004 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) | 02005 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0); 02006 return get(Instruction::Add, C1, C2, Flags); 02007 } 02008 02009 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) { 02010 return get(Instruction::FAdd, C1, C2); 02011 } 02012 02013 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2, 02014 bool HasNUW, bool HasNSW) { 02015 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) | 02016 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0); 02017 return get(Instruction::Sub, C1, C2, Flags); 02018 } 02019 02020 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) { 02021 return get(Instruction::FSub, C1, C2); 02022 } 02023 02024 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2, 02025 bool HasNUW, bool HasNSW) { 02026 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) | 02027 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0); 02028 return get(Instruction::Mul, C1, C2, Flags); 02029 } 02030 02031 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) { 02032 return get(Instruction::FMul, C1, C2); 02033 } 02034 02035 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) { 02036 return get(Instruction::UDiv, C1, C2, 02037 isExact ? PossiblyExactOperator::IsExact : 0); 02038 } 02039 02040 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) { 02041 return get(Instruction::SDiv, C1, C2, 02042 isExact ? PossiblyExactOperator::IsExact : 0); 02043 } 02044 02045 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) { 02046 return get(Instruction::FDiv, C1, C2); 02047 } 02048 02049 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) { 02050 return get(Instruction::URem, C1, C2); 02051 } 02052 02053 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) { 02054 return get(Instruction::SRem, C1, C2); 02055 } 02056 02057 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) { 02058 return get(Instruction::FRem, C1, C2); 02059 } 02060 02061 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) { 02062 return get(Instruction::And, C1, C2); 02063 } 02064 02065 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) { 02066 return get(Instruction::Or, C1, C2); 02067 } 02068 02069 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) { 02070 return get(Instruction::Xor, C1, C2); 02071 } 02072 02073 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2, 02074 bool HasNUW, bool HasNSW) { 02075 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) | 02076 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0); 02077 return get(Instruction::Shl, C1, C2, Flags); 02078 } 02079 02080 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) { 02081 return get(Instruction::LShr, C1, C2, 02082 isExact ? PossiblyExactOperator::IsExact : 0); 02083 } 02084 02085 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) { 02086 return get(Instruction::AShr, C1, C2, 02087 isExact ? PossiblyExactOperator::IsExact : 0); 02088 } 02089 02090 /// getBinOpIdentity - Return the identity for the given binary operation, 02091 /// i.e. a constant C such that X op C = X and C op X = X for every X. It 02092 /// returns null if the operator doesn't have an identity. 02093 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) { 02094 switch (Opcode) { 02095 default: 02096 // Doesn't have an identity. 02097 return 0; 02098 02099 case Instruction::Add: 02100 case Instruction::Or: 02101 case Instruction::Xor: 02102 return Constant::getNullValue(Ty); 02103 02104 case Instruction::Mul: 02105 return ConstantInt::get(Ty, 1); 02106 02107 case Instruction::And: 02108 return Constant::getAllOnesValue(Ty); 02109 } 02110 } 02111 02112 /// getBinOpAbsorber - Return the absorbing element for the given binary 02113 /// operation, i.e. a constant C such that X op C = C and C op X = C for 02114 /// every X. For example, this returns zero for integer multiplication. 02115 /// It returns null if the operator doesn't have an absorbing element. 02116 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) { 02117 switch (Opcode) { 02118 default: 02119 // Doesn't have an absorber. 02120 return 0; 02121 02122 case Instruction::Or: 02123 return Constant::getAllOnesValue(Ty); 02124 02125 case Instruction::And: 02126 case Instruction::Mul: 02127 return Constant::getNullValue(Ty); 02128 } 02129 } 02130 02131 // destroyConstant - Remove the constant from the constant table... 02132 // 02133 void ConstantExpr::destroyConstant() { 02134 getType()->getContext().pImpl->ExprConstants.remove(this); 02135 destroyConstantImpl(); 02136 } 02137 02138 const char *ConstantExpr::getOpcodeName() const { 02139 return Instruction::getOpcodeName(getOpcode()); 02140 } 02141 02142 02143 02144 GetElementPtrConstantExpr:: 02145 GetElementPtrConstantExpr(Constant *C, ArrayRef<Constant*> IdxList, 02146 Type *DestTy) 02147 : ConstantExpr(DestTy, Instruction::GetElementPtr, 02148 OperandTraits<GetElementPtrConstantExpr>::op_end(this) 02149 - (IdxList.size()+1), IdxList.size()+1) { 02150 OperandList[0] = C; 02151 for (unsigned i = 0, E = IdxList.size(); i != E; ++i) 02152 OperandList[i+1] = IdxList[i]; 02153 } 02154 02155 //===----------------------------------------------------------------------===// 02156 // ConstantData* implementations 02157 02158 void ConstantDataArray::anchor() {} 02159 void ConstantDataVector::anchor() {} 02160 02161 /// getElementType - Return the element type of the array/vector. 02162 Type *ConstantDataSequential::getElementType() const { 02163 return getType()->getElementType(); 02164 } 02165 02166 StringRef ConstantDataSequential::getRawDataValues() const { 02167 return StringRef(DataElements, getNumElements()*getElementByteSize()); 02168 } 02169 02170 /// isElementTypeCompatible - Return true if a ConstantDataSequential can be 02171 /// formed with a vector or array of the specified element type. 02172 /// ConstantDataArray only works with normal float and int types that are 02173 /// stored densely in memory, not with things like i42 or x86_f80. 02174 bool ConstantDataSequential::isElementTypeCompatible(const Type *Ty) { 02175 if (Ty->isFloatTy() || Ty->isDoubleTy()) return true; 02176 if (const IntegerType *IT = dyn_cast<IntegerType>(Ty)) { 02177 switch (IT->getBitWidth()) { 02178 case 8: 02179 case 16: 02180 case 32: 02181 case 64: 02182 return true; 02183 default: break; 02184 } 02185 } 02186 return false; 02187 } 02188 02189 /// getNumElements - Return the number of elements in the array or vector. 02190 unsigned ConstantDataSequential::getNumElements() const { 02191 if (ArrayType *AT = dyn_cast<ArrayType>(getType())) 02192 return AT->getNumElements(); 02193 return getType()->getVectorNumElements(); 02194 } 02195 02196 02197 /// getElementByteSize - Return the size in bytes of the elements in the data. 02198 uint64_t ConstantDataSequential::getElementByteSize() const { 02199 return getElementType()->getPrimitiveSizeInBits()/8; 02200 } 02201 02202 /// getElementPointer - Return the start of the specified element. 02203 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const { 02204 assert(Elt < getNumElements() && "Invalid Elt"); 02205 return DataElements+Elt*getElementByteSize(); 02206 } 02207 02208 02209 /// isAllZeros - return true if the array is empty or all zeros. 02210 static bool isAllZeros(StringRef Arr) { 02211 for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I) 02212 if (*I != 0) 02213 return false; 02214 return true; 02215 } 02216 02217 /// getImpl - This is the underlying implementation of all of the 02218 /// ConstantDataSequential::get methods. They all thunk down to here, providing 02219 /// the correct element type. We take the bytes in as a StringRef because 02220 /// we *want* an underlying "char*" to avoid TBAA type punning violations. 02221 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) { 02222 assert(isElementTypeCompatible(Ty->getSequentialElementType())); 02223 // If the elements are all zero or there are no elements, return a CAZ, which 02224 // is more dense and canonical. 02225 if (isAllZeros(Elements)) 02226 return ConstantAggregateZero::get(Ty); 02227 02228 // Do a lookup to see if we have already formed one of these. 02229 StringMap<ConstantDataSequential*>::MapEntryTy &Slot = 02230 Ty->getContext().pImpl->CDSConstants.GetOrCreateValue(Elements); 02231 02232 // The bucket can point to a linked list of different CDS's that have the same 02233 // body but different types. For example, 0,0,0,1 could be a 4 element array 02234 // of i8, or a 1-element array of i32. They'll both end up in the same 02235 /// StringMap bucket, linked up by their Next pointers. Walk the list. 02236 ConstantDataSequential **Entry = &Slot.getValue(); 02237 for (ConstantDataSequential *Node = *Entry; Node != 0; 02238 Entry = &Node->Next, Node = *Entry) 02239 if (Node->getType() == Ty) 02240 return Node; 02241 02242 // Okay, we didn't get a hit. Create a node of the right class, link it in, 02243 // and return it. 02244 if (isa<ArrayType>(Ty)) 02245 return *Entry = new ConstantDataArray(Ty, Slot.getKeyData()); 02246 02247 assert(isa<VectorType>(Ty)); 02248 return *Entry = new ConstantDataVector(Ty, Slot.getKeyData()); 02249 } 02250 02251 void ConstantDataSequential::destroyConstant() { 02252 // Remove the constant from the StringMap. 02253 StringMap<ConstantDataSequential*> &CDSConstants = 02254 getType()->getContext().pImpl->CDSConstants; 02255 02256 StringMap<ConstantDataSequential*>::iterator Slot = 02257 CDSConstants.find(getRawDataValues()); 02258 02259 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table"); 02260 02261 ConstantDataSequential **Entry = &Slot->getValue(); 02262 02263 // Remove the entry from the hash table. 02264 if ((*Entry)->Next == 0) { 02265 // If there is only one value in the bucket (common case) it must be this 02266 // entry, and removing the entry should remove the bucket completely. 02267 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential"); 02268 getContext().pImpl->CDSConstants.erase(Slot); 02269 } else { 02270 // Otherwise, there are multiple entries linked off the bucket, unlink the 02271 // node we care about but keep the bucket around. 02272 for (ConstantDataSequential *Node = *Entry; ; 02273 Entry = &Node->Next, Node = *Entry) { 02274 assert(Node && "Didn't find entry in its uniquing hash table!"); 02275 // If we found our entry, unlink it from the list and we're done. 02276 if (Node == this) { 02277 *Entry = Node->Next; 02278 break; 02279 } 02280 } 02281 } 02282 02283 // If we were part of a list, make sure that we don't delete the list that is 02284 // still owned by the uniquing map. 02285 Next = 0; 02286 02287 // Finally, actually delete it. 02288 destroyConstantImpl(); 02289 } 02290 02291 /// get() constructors - Return a constant with array type with an element 02292 /// count and element type matching the ArrayRef passed in. Note that this 02293 /// can return a ConstantAggregateZero object. 02294 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) { 02295 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size()); 02296 const char *Data = reinterpret_cast<const char *>(Elts.data()); 02297 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty); 02298 } 02299 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){ 02300 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size()); 02301 const char *Data = reinterpret_cast<const char *>(Elts.data()); 02302 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty); 02303 } 02304 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){ 02305 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size()); 02306 const char *Data = reinterpret_cast<const char *>(Elts.data()); 02307 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty); 02308 } 02309 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){ 02310 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size()); 02311 const char *Data = reinterpret_cast<const char *>(Elts.data()); 02312 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty); 02313 } 02314 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) { 02315 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size()); 02316 const char *Data = reinterpret_cast<const char *>(Elts.data()); 02317 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty); 02318 } 02319 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) { 02320 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size()); 02321 const char *Data = reinterpret_cast<const char *>(Elts.data()); 02322 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty); 02323 } 02324 02325 /// getString - This method constructs a CDS and initializes it with a text 02326 /// string. The default behavior (AddNull==true) causes a null terminator to 02327 /// be placed at the end of the array (increasing the length of the string by 02328 /// one more than the StringRef would normally indicate. Pass AddNull=false 02329 /// to disable this behavior. 02330 Constant *ConstantDataArray::getString(LLVMContext &Context, 02331 StringRef Str, bool AddNull) { 02332 if (!AddNull) { 02333 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data()); 02334 return get(Context, ArrayRef<uint8_t>(const_cast<uint8_t *>(Data), 02335 Str.size())); 02336 } 02337 02338 SmallVector<uint8_t, 64> ElementVals; 02339 ElementVals.append(Str.begin(), Str.end()); 02340 ElementVals.push_back(0); 02341 return get(Context, ElementVals); 02342 } 02343 02344 /// get() constructors - Return a constant with vector type with an element 02345 /// count and element type matching the ArrayRef passed in. Note that this 02346 /// can return a ConstantAggregateZero object. 02347 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){ 02348 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size()); 02349 const char *Data = reinterpret_cast<const char *>(Elts.data()); 02350 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty); 02351 } 02352 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){ 02353 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size()); 02354 const char *Data = reinterpret_cast<const char *>(Elts.data()); 02355 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty); 02356 } 02357 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){ 02358 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size()); 02359 const char *Data = reinterpret_cast<const char *>(Elts.data()); 02360 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty); 02361 } 02362 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){ 02363 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size()); 02364 const char *Data = reinterpret_cast<const char *>(Elts.data()); 02365 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty); 02366 } 02367 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) { 02368 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size()); 02369 const char *Data = reinterpret_cast<const char *>(Elts.data()); 02370 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty); 02371 } 02372 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) { 02373 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size()); 02374 const char *Data = reinterpret_cast<const char *>(Elts.data()); 02375 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty); 02376 } 02377 02378 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) { 02379 assert(isElementTypeCompatible(V->getType()) && 02380 "Element type not compatible with ConstantData"); 02381 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 02382 if (CI->getType()->isIntegerTy(8)) { 02383 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue()); 02384 return get(V->getContext(), Elts); 02385 } 02386 if (CI->getType()->isIntegerTy(16)) { 02387 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue()); 02388 return get(V->getContext(), Elts); 02389 } 02390 if (CI->getType()->isIntegerTy(32)) { 02391 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue()); 02392 return get(V->getContext(), Elts); 02393 } 02394 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type"); 02395 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue()); 02396 return get(V->getContext(), Elts); 02397 } 02398 02399 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) { 02400 if (CFP->getType()->isFloatTy()) { 02401 SmallVector<float, 16> Elts(NumElts, CFP->getValueAPF().convertToFloat()); 02402 return get(V->getContext(), Elts); 02403 } 02404 if (CFP->getType()->isDoubleTy()) { 02405 SmallVector<double, 16> Elts(NumElts, 02406 CFP->getValueAPF().convertToDouble()); 02407 return get(V->getContext(), Elts); 02408 } 02409 } 02410 return ConstantVector::getSplat(NumElts, V); 02411 } 02412 02413 02414 /// getElementAsInteger - If this is a sequential container of integers (of 02415 /// any size), return the specified element in the low bits of a uint64_t. 02416 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const { 02417 assert(isa<IntegerType>(getElementType()) && 02418 "Accessor can only be used when element is an integer"); 02419 const char *EltPtr = getElementPointer(Elt); 02420 02421 // The data is stored in host byte order, make sure to cast back to the right 02422 // type to load with the right endianness. 02423 switch (getElementType()->getIntegerBitWidth()) { 02424 default: llvm_unreachable("Invalid bitwidth for CDS"); 02425 case 8: 02426 return *const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(EltPtr)); 02427 case 16: 02428 return *const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(EltPtr)); 02429 case 32: 02430 return *const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(EltPtr)); 02431 case 64: 02432 return *const_cast<uint64_t *>(reinterpret_cast<const uint64_t *>(EltPtr)); 02433 } 02434 } 02435 02436 /// getElementAsAPFloat - If this is a sequential container of floating point 02437 /// type, return the specified element as an APFloat. 02438 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const { 02439 const char *EltPtr = getElementPointer(Elt); 02440 02441 switch (getElementType()->getTypeID()) { 02442 default: 02443 llvm_unreachable("Accessor can only be used when element is float/double!"); 02444 case Type::FloatTyID: { 02445 const float *FloatPrt = reinterpret_cast<const float *>(EltPtr); 02446 return APFloat(*const_cast<float *>(FloatPrt)); 02447 } 02448 case Type::DoubleTyID: { 02449 const double *DoublePtr = reinterpret_cast<const double *>(EltPtr); 02450 return APFloat(*const_cast<double *>(DoublePtr)); 02451 } 02452 } 02453 } 02454 02455 /// getElementAsFloat - If this is an sequential container of floats, return 02456 /// the specified element as a float. 02457 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const { 02458 assert(getElementType()->isFloatTy() && 02459 "Accessor can only be used when element is a 'float'"); 02460 const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt)); 02461 return *const_cast<float *>(EltPtr); 02462 } 02463 02464 /// getElementAsDouble - If this is an sequential container of doubles, return 02465 /// the specified element as a float. 02466 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const { 02467 assert(getElementType()->isDoubleTy() && 02468 "Accessor can only be used when element is a 'float'"); 02469 const double *EltPtr = 02470 reinterpret_cast<const double *>(getElementPointer(Elt)); 02471 return *const_cast<double *>(EltPtr); 02472 } 02473 02474 /// getElementAsConstant - Return a Constant for a specified index's element. 02475 /// Note that this has to compute a new constant to return, so it isn't as 02476 /// efficient as getElementAsInteger/Float/Double. 02477 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const { 02478 if (getElementType()->isFloatTy() || getElementType()->isDoubleTy()) 02479 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt)); 02480 02481 return ConstantInt::get(getElementType(), getElementAsInteger(Elt)); 02482 } 02483 02484 /// isString - This method returns true if this is an array of i8. 02485 bool ConstantDataSequential::isString() const { 02486 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8); 02487 } 02488 02489 /// isCString - This method returns true if the array "isString", ends with a 02490 /// nul byte, and does not contains any other nul bytes. 02491 bool ConstantDataSequential::isCString() const { 02492 if (!isString()) 02493 return false; 02494 02495 StringRef Str = getAsString(); 02496 02497 // The last value must be nul. 02498 if (Str.back() != 0) return false; 02499 02500 // Other elements must be non-nul. 02501 return Str.drop_back().find(0) == StringRef::npos; 02502 } 02503 02504 /// getSplatValue - If this is a splat constant, meaning that all of the 02505 /// elements have the same value, return that value. Otherwise return NULL. 02506 Constant *ConstantDataVector::getSplatValue() const { 02507 const char *Base = getRawDataValues().data(); 02508 02509 // Compare elements 1+ to the 0'th element. 02510 unsigned EltSize = getElementByteSize(); 02511 for (unsigned i = 1, e = getNumElements(); i != e; ++i) 02512 if (memcmp(Base, Base+i*EltSize, EltSize)) 02513 return 0; 02514 02515 // If they're all the same, return the 0th one as a representative. 02516 return getElementAsConstant(0); 02517 } 02518 02519 //===----------------------------------------------------------------------===// 02520 // replaceUsesOfWithOnConstant implementations 02521 02522 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of 02523 /// 'From' to be uses of 'To'. This must update the uniquing data structures 02524 /// etc. 02525 /// 02526 /// Note that we intentionally replace all uses of From with To here. Consider 02527 /// a large array that uses 'From' 1000 times. By handling this case all here, 02528 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that 02529 /// single invocation handles all 1000 uses. Handling them one at a time would 02530 /// work, but would be really slow because it would have to unique each updated 02531 /// array instance. 02532 /// 02533 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To, 02534 Use *U) { 02535 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!"); 02536 Constant *ToC = cast<Constant>(To); 02537 02538 LLVMContextImpl *pImpl = getType()->getContext().pImpl; 02539 02540 SmallVector<Constant*, 8> Values; 02541 LLVMContextImpl::ArrayConstantsTy::LookupKey Lookup; 02542 Lookup.first = cast<ArrayType>(getType()); 02543 Values.reserve(getNumOperands()); // Build replacement array. 02544 02545 // Fill values with the modified operands of the constant array. Also, 02546 // compute whether this turns into an all-zeros array. 02547 unsigned NumUpdated = 0; 02548 02549 // Keep track of whether all the values in the array are "ToC". 02550 bool AllSame = true; 02551 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) { 02552 Constant *Val = cast<Constant>(O->get()); 02553 if (Val == From) { 02554 Val = ToC; 02555 ++NumUpdated; 02556 } 02557 Values.push_back(Val); 02558 AllSame &= Val == ToC; 02559 } 02560 02561 Constant *Replacement = 0; 02562 if (AllSame && ToC->isNullValue()) { 02563 Replacement = ConstantAggregateZero::get(getType()); 02564 } else if (AllSame && isa<UndefValue>(ToC)) { 02565 Replacement = UndefValue::get(getType()); 02566 } else { 02567 // Check to see if we have this array type already. 02568 Lookup.second = makeArrayRef(Values); 02569 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I = 02570 pImpl->ArrayConstants.find(Lookup); 02571 02572 if (I != pImpl->ArrayConstants.map_end()) { 02573 Replacement = I->first; 02574 } else { 02575 // Okay, the new shape doesn't exist in the system yet. Instead of 02576 // creating a new constant array, inserting it, replaceallusesof'ing the 02577 // old with the new, then deleting the old... just update the current one 02578 // in place! 02579 pImpl->ArrayConstants.remove(this); 02580 02581 // Update to the new value. Optimize for the case when we have a single 02582 // operand that we're changing, but handle bulk updates efficiently. 02583 if (NumUpdated == 1) { 02584 unsigned OperandToUpdate = U - OperandList; 02585 assert(getOperand(OperandToUpdate) == From && 02586 "ReplaceAllUsesWith broken!"); 02587 setOperand(OperandToUpdate, ToC); 02588 } else { 02589 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 02590 if (getOperand(i) == From) 02591 setOperand(i, ToC); 02592 } 02593 pImpl->ArrayConstants.insert(this); 02594 return; 02595 } 02596 } 02597 02598 // Otherwise, I do need to replace this with an existing value. 02599 assert(Replacement != this && "I didn't contain From!"); 02600 02601 // Everyone using this now uses the replacement. 02602 replaceAllUsesWith(Replacement); 02603 02604 // Delete the old constant! 02605 destroyConstant(); 02606 } 02607 02608 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To, 02609 Use *U) { 02610 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!"); 02611 Constant *ToC = cast<Constant>(To); 02612 02613 unsigned OperandToUpdate = U-OperandList; 02614 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!"); 02615 02616 SmallVector<Constant*, 8> Values; 02617 LLVMContextImpl::StructConstantsTy::LookupKey Lookup; 02618 Lookup.first = cast<StructType>(getType()); 02619 Values.reserve(getNumOperands()); // Build replacement struct. 02620 02621 // Fill values with the modified operands of the constant struct. Also, 02622 // compute whether this turns into an all-zeros struct. 02623 bool isAllZeros = false; 02624 bool isAllUndef = false; 02625 if (ToC->isNullValue()) { 02626 isAllZeros = true; 02627 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) { 02628 Constant *Val = cast<Constant>(O->get()); 02629 Values.push_back(Val); 02630 if (isAllZeros) isAllZeros = Val->isNullValue(); 02631 } 02632 } else if (isa<UndefValue>(ToC)) { 02633 isAllUndef = true; 02634 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) { 02635 Constant *Val = cast<Constant>(O->get()); 02636 Values.push_back(Val); 02637 if (isAllUndef) isAllUndef = isa<UndefValue>(Val); 02638 } 02639 } else { 02640 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) 02641 Values.push_back(cast<Constant>(O->get())); 02642 } 02643 Values[OperandToUpdate] = ToC; 02644 02645 LLVMContextImpl *pImpl = getContext().pImpl; 02646 02647 Constant *Replacement = 0; 02648 if (isAllZeros) { 02649 Replacement = ConstantAggregateZero::get(getType()); 02650 } else if (isAllUndef) { 02651 Replacement = UndefValue::get(getType()); 02652 } else { 02653 // Check to see if we have this struct type already. 02654 Lookup.second = makeArrayRef(Values); 02655 LLVMContextImpl::StructConstantsTy::MapTy::iterator I = 02656 pImpl->StructConstants.find(Lookup); 02657 02658 if (I != pImpl->StructConstants.map_end()) { 02659 Replacement = I->first; 02660 } else { 02661 // Okay, the new shape doesn't exist in the system yet. Instead of 02662 // creating a new constant struct, inserting it, replaceallusesof'ing the 02663 // old with the new, then deleting the old... just update the current one 02664 // in place! 02665 pImpl->StructConstants.remove(this); 02666 02667 // Update to the new value. 02668 setOperand(OperandToUpdate, ToC); 02669 pImpl->StructConstants.insert(this); 02670 return; 02671 } 02672 } 02673 02674 assert(Replacement != this && "I didn't contain From!"); 02675 02676 // Everyone using this now uses the replacement. 02677 replaceAllUsesWith(Replacement); 02678 02679 // Delete the old constant! 02680 destroyConstant(); 02681 } 02682 02683 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To, 02684 Use *U) { 02685 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!"); 02686 02687 SmallVector<Constant*, 8> Values; 02688 Values.reserve(getNumOperands()); // Build replacement array... 02689 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 02690 Constant *Val = getOperand(i); 02691 if (Val == From) Val = cast<Constant>(To); 02692 Values.push_back(Val); 02693 } 02694 02695 Constant *Replacement = get(Values); 02696 assert(Replacement != this && "I didn't contain From!"); 02697 02698 // Everyone using this now uses the replacement. 02699 replaceAllUsesWith(Replacement); 02700 02701 // Delete the old constant! 02702 destroyConstant(); 02703 } 02704 02705 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV, 02706 Use *U) { 02707 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!"); 02708 Constant *To = cast<Constant>(ToV); 02709 02710 SmallVector<Constant*, 8> NewOps; 02711 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 02712 Constant *Op = getOperand(i); 02713 NewOps.push_back(Op == From ? To : Op); 02714 } 02715 02716 Constant *Replacement = getWithOperands(NewOps); 02717 assert(Replacement != this && "I didn't contain From!"); 02718 02719 // Everyone using this now uses the replacement. 02720 replaceAllUsesWith(Replacement); 02721 02722 // Delete the old constant! 02723 destroyConstant(); 02724 } 02725 02726 Instruction *ConstantExpr::getAsInstruction() { 02727 SmallVector<Value*,4> ValueOperands; 02728 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I) 02729 ValueOperands.push_back(cast<Value>(I)); 02730 02731 ArrayRef<Value*> Ops(ValueOperands); 02732 02733 switch (getOpcode()) { 02734 case Instruction::Trunc: 02735 case Instruction::ZExt: 02736 case Instruction::SExt: 02737 case Instruction::FPTrunc: 02738 case Instruction::FPExt: 02739 case Instruction::UIToFP: 02740 case Instruction::SIToFP: 02741 case Instruction::FPToUI: 02742 case Instruction::FPToSI: 02743 case Instruction::PtrToInt: 02744 case Instruction::IntToPtr: 02745 case Instruction::BitCast: 02746 return CastInst::Create((Instruction::CastOps)getOpcode(), 02747 Ops[0], getType()); 02748 case Instruction::Select: 02749 return SelectInst::Create(Ops[0], Ops[1], Ops[2]); 02750 case Instruction::InsertElement: 02751 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]); 02752 case Instruction::ExtractElement: 02753 return ExtractElementInst::Create(Ops[0], Ops[1]); 02754 case Instruction::InsertValue: 02755 return InsertValueInst::Create(Ops[0], Ops[1], getIndices()); 02756 case Instruction::ExtractValue: 02757 return ExtractValueInst::Create(Ops[0], getIndices()); 02758 case Instruction::ShuffleVector: 02759 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]); 02760 02761 case Instruction::GetElementPtr: 02762 if (cast<GEPOperator>(this)->isInBounds()) 02763 return GetElementPtrInst::CreateInBounds(Ops[0], Ops.slice(1)); 02764 else 02765 return GetElementPtrInst::Create(Ops[0], Ops.slice(1)); 02766 02767 case Instruction::ICmp: 02768 case Instruction::FCmp: 02769 return CmpInst::Create((Instruction::OtherOps)getOpcode(), 02770 getPredicate(), Ops[0], Ops[1]); 02771 02772 default: 02773 assert(getNumOperands() == 2 && "Must be binary operator?"); 02774 BinaryOperator *BO = 02775 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(), 02776 Ops[0], Ops[1]); 02777 if (isa<OverflowingBinaryOperator>(BO)) { 02778 BO->setHasNoUnsignedWrap(SubclassOptionalData & 02779 OverflowingBinaryOperator::NoUnsignedWrap); 02780 BO->setHasNoSignedWrap(SubclassOptionalData & 02781 OverflowingBinaryOperator::NoSignedWrap); 02782 } 02783 if (isa<PossiblyExactOperator>(BO)) 02784 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact); 02785 return BO; 02786 } 02787 }