1 //===-- Constants.cpp - Implement Constant nodes -----------------*- C++ -*--=//
3 // This file implements the Constant* classes...
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Constants.h"
8 #include "llvm/DerivedTypes.h"
9 #include "llvm/iMemory.h"
10 #include "llvm/SymbolTable.h"
11 #include "llvm/Module.h"
12 #include "llvm/SlotCalculator.h"
13 #include "Support/StringExtras.h"
21 ConstantBool *ConstantBool::True = new ConstantBool(true);
22 ConstantBool *ConstantBool::False = new ConstantBool(false);
25 //===----------------------------------------------------------------------===//
27 //===----------------------------------------------------------------------===//
29 // Specialize setName to take care of symbol table majik
30 void Constant::setName(const std::string &Name, SymbolTable *ST) {
31 assert(ST && "Type::setName - Must provide symbol table argument!");
33 if (Name.size()) ST->insert(Name, this);
36 void Constant::destroyConstantImpl() {
37 // When a Constant is destroyed, there may be lingering
38 // references to the constant by other constants in the constant pool. These
39 // constants are implicitly dependant on the module that is being deleted,
40 // but they don't know that. Because we only find out when the CPV is
41 // deleted, we must now notify all of our users (that should only be
42 // Constants) that they are, in fact, invalid now and should be deleted.
44 while (!use_empty()) {
45 Value *V = use_back();
46 #ifndef NDEBUG // Only in -g mode...
47 if (!isa<Constant>(V))
48 std::cerr << "While deleting: " << *this
49 << "\n\nUse still stuck around after Def is destroyed: "
52 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
53 Constant *CPV = cast<Constant>(V);
54 CPV->destroyConstant();
56 // The constant should remove itself from our use list...
57 assert((use_empty() || use_back() != V) && "Constant not removed!");
60 // Value has no outstanding references it is safe to delete it now...
64 // Static constructor to create a '0' constant of arbitrary type...
65 Constant *Constant::getNullValue(const Type *Ty) {
66 switch (Ty->getPrimitiveID()) {
67 case Type::BoolTyID: return ConstantBool::get(false);
71 case Type::LongTyID: return ConstantSInt::get(Ty, 0);
74 case Type::UShortTyID:
76 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
79 case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
81 case Type::PointerTyID:
82 return ConstantPointerNull::get(cast<PointerType>(Ty));
88 // Static constructor to create the maximum constant of an integral type...
89 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
90 switch (Ty->getPrimitiveID()) {
91 case Type::BoolTyID: return ConstantBool::True;
95 case Type::LongTyID: {
96 // Calculate 011111111111111...
97 unsigned TypeBits = Ty->getPrimitiveSize()*8;
98 int64_t Val = INT64_MAX; // All ones
99 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
100 return ConstantSInt::get(Ty, Val);
103 case Type::UByteTyID:
104 case Type::UShortTyID:
106 case Type::ULongTyID: return getAllOnesValue(Ty);
112 // Static constructor to create the minimum constant for an integral type...
113 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
114 switch (Ty->getPrimitiveID()) {
115 case Type::BoolTyID: return ConstantBool::False;
116 case Type::SByteTyID:
117 case Type::ShortTyID:
119 case Type::LongTyID: {
120 // Calculate 1111111111000000000000
121 unsigned TypeBits = Ty->getPrimitiveSize()*8;
122 int64_t Val = -1; // All ones
123 Val <<= TypeBits-1; // Shift over to the right spot
124 return ConstantSInt::get(Ty, Val);
127 case Type::UByteTyID:
128 case Type::UShortTyID:
130 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
136 // Static constructor to create an integral constant with all bits set
137 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
138 switch (Ty->getPrimitiveID()) {
139 case Type::BoolTyID: return ConstantBool::True;
140 case Type::SByteTyID:
141 case Type::ShortTyID:
143 case Type::LongTyID: return ConstantSInt::get(Ty, -1);
145 case Type::UByteTyID:
146 case Type::UShortTyID:
148 case Type::ULongTyID: {
149 // Calculate ~0 of the right type...
150 unsigned TypeBits = Ty->getPrimitiveSize()*8;
151 uint64_t Val = ~0ULL; // All ones
152 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
153 return ConstantUInt::get(Ty, Val);
160 //===----------------------------------------------------------------------===//
161 // ConstantXXX Classes
162 //===----------------------------------------------------------------------===//
164 //===----------------------------------------------------------------------===//
165 // Normal Constructors
167 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy) {
171 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty) {
175 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
176 assert(Ty->isInteger() && Ty->isSigned() &&
177 "Illegal type for unsigned integer constant!");
178 assert(isValueValidForType(Ty, V) && "Value too large for type!");
181 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
182 assert(Ty->isInteger() && Ty->isUnsigned() &&
183 "Illegal type for unsigned integer constant!");
184 assert(isValueValidForType(Ty, V) && "Value too large for type!");
187 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
188 assert(isValueValidForType(Ty, V) && "Value too large for type!");
192 ConstantArray::ConstantArray(const ArrayType *T,
193 const std::vector<Constant*> &V) : Constant(T) {
194 for (unsigned i = 0; i < V.size(); i++) {
195 assert(V[i]->getType() == T->getElementType());
196 Operands.push_back(Use(V[i], this));
200 ConstantStruct::ConstantStruct(const StructType *T,
201 const std::vector<Constant*> &V) : Constant(T) {
202 const StructType::ElementTypes &ETypes = T->getElementTypes();
203 assert(V.size() == ETypes.size() &&
204 "Invalid initializer vector for constant structure");
205 for (unsigned i = 0; i < V.size(); i++) {
206 assert(V[i]->getType() == ETypes[i]);
207 Operands.push_back(Use(V[i], this));
211 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
212 : ConstantPointer(GV->getType()) {
213 Operands.push_back(Use(GV, this));
216 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
217 : Constant(Ty), iType(Opcode) {
218 Operands.push_back(Use(C, this));
221 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
222 : Constant(C1->getType()), iType(Opcode) {
223 Operands.push_back(Use(C1, this));
224 Operands.push_back(Use(C2, this));
227 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
229 : Constant(DestTy), iType(Instruction::GetElementPtr) {
230 Operands.reserve(1+IdxList.size());
231 Operands.push_back(Use(C, this));
232 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
233 Operands.push_back(Use(IdxList[i], this));
238 //===----------------------------------------------------------------------===//
239 // classof implementations
241 bool ConstantIntegral::classof(const Constant *CPV) {
242 return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
245 bool ConstantInt::classof(const Constant *CPV) {
246 return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
248 bool ConstantSInt::classof(const Constant *CPV) {
249 return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
251 bool ConstantUInt::classof(const Constant *CPV) {
252 return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
254 bool ConstantFP::classof(const Constant *CPV) {
255 const Type *Ty = CPV->getType();
256 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
257 !isa<ConstantExpr>(CPV));
259 bool ConstantArray::classof(const Constant *CPV) {
260 return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
262 bool ConstantStruct::classof(const Constant *CPV) {
263 return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
265 bool ConstantPointer::classof(const Constant *CPV) {
266 return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
271 //===----------------------------------------------------------------------===//
272 // isValueValidForType implementations
274 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
275 switch (Ty->getPrimitiveID()) {
277 return false; // These can't be represented as integers!!!
280 case Type::SByteTyID:
281 return (Val <= INT8_MAX && Val >= INT8_MIN);
282 case Type::ShortTyID:
283 return (Val <= INT16_MAX && Val >= INT16_MIN);
285 return (Val <= INT32_MAX && Val >= INT32_MIN);
287 return true; // This is the largest type...
293 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
294 switch (Ty->getPrimitiveID()) {
296 return false; // These can't be represented as integers!!!
299 case Type::UByteTyID:
300 return (Val <= UINT8_MAX);
301 case Type::UShortTyID:
302 return (Val <= UINT16_MAX);
304 return (Val <= UINT32_MAX);
305 case Type::ULongTyID:
306 return true; // This is the largest type...
312 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
313 switch (Ty->getPrimitiveID()) {
315 return false; // These can't be represented as floating point!
317 // TODO: Figure out how to test if a double can be cast to a float!
318 case Type::FloatTyID:
320 return (Val <= UINT8_MAX);
322 case Type::DoubleTyID:
323 return true; // This is the largest type...
327 //===----------------------------------------------------------------------===//
328 // Factory Function Implementation
330 template<class ValType, class ConstantClass>
332 typedef pair<const Type*, ValType> ConstHashKey;
333 map<ConstHashKey, ConstantClass *> Map;
335 inline ConstantClass *get(const Type *Ty, ValType V) {
336 typename map<ConstHashKey,ConstantClass *>::iterator I =
337 Map.find(ConstHashKey(Ty, V));
338 return (I != Map.end()) ? I->second : 0;
341 inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
342 Map.insert(make_pair(ConstHashKey(Ty, V), CP));
345 inline void remove(ConstantClass *CP) {
346 for (typename map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
347 E = Map.end(); I != E;++I)
348 if (I->second == CP) {
355 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
357 static ValueMap<uint64_t, ConstantInt> IntConstants;
359 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
360 ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
361 if (!Result) // If no preexisting value, create one now...
362 IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
366 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
367 ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
368 if (!Result) // If no preexisting value, create one now...
369 IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
373 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
374 assert(V <= 127 && "Can only be used with very small positive constants!");
375 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
376 return ConstantUInt::get(Ty, V);
379 //---- ConstantFP::get() implementation...
381 static ValueMap<double, ConstantFP> FPConstants;
383 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
384 ConstantFP *Result = FPConstants.get(Ty, V);
385 if (!Result) // If no preexisting value, create one now...
386 FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
390 //---- ConstantArray::get() implementation...
392 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
394 ConstantArray *ConstantArray::get(const ArrayType *Ty,
395 const std::vector<Constant*> &V) {
396 ConstantArray *Result = ArrayConstants.get(Ty, V);
397 if (!Result) // If no preexisting value, create one now...
398 ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
402 // ConstantArray::get(const string&) - Return an array that is initialized to
403 // contain the specified string. A null terminator is added to the specified
404 // string so that it may be used in a natural way...
406 ConstantArray *ConstantArray::get(const std::string &Str) {
407 std::vector<Constant*> ElementVals;
409 for (unsigned i = 0; i < Str.length(); ++i)
410 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
412 // Add a null terminator to the string...
413 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
415 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
416 return ConstantArray::get(ATy, ElementVals);
420 // destroyConstant - Remove the constant from the constant table...
422 void ConstantArray::destroyConstant() {
423 ArrayConstants.remove(this);
424 destroyConstantImpl();
427 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
428 // then this method converts the array to an std::string and returns it.
429 // Otherwise, it asserts out.
431 std::string ConstantArray::getAsString() const {
433 if (getType()->getElementType() == Type::SByteTy)
434 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
435 Result += (char)cast<ConstantSInt>(getOperand(i))->getValue();
437 assert(getType()->getElementType() == Type::UByteTy && "Not a string!");
438 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
439 Result += (char)cast<ConstantUInt>(getOperand(i))->getValue();
445 //---- ConstantStruct::get() implementation...
447 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
449 ConstantStruct *ConstantStruct::get(const StructType *Ty,
450 const std::vector<Constant*> &V) {
451 ConstantStruct *Result = StructConstants.get(Ty, V);
452 if (!Result) // If no preexisting value, create one now...
453 StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
457 // destroyConstant - Remove the constant from the constant table...
459 void ConstantStruct::destroyConstant() {
460 StructConstants.remove(this);
461 destroyConstantImpl();
465 //---- ConstantPointerNull::get() implementation...
467 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
469 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
470 ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
471 if (!Result) // If no preexisting value, create one now...
472 NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
476 // destroyConstant - Remove the constant from the constant table...
478 void ConstantPointerNull::destroyConstant() {
479 NullPtrConstants.remove(this);
480 destroyConstantImpl();
484 //---- ConstantPointerRef::get() implementation...
486 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
487 assert(GV->getParent() && "Global Value must be attached to a module!");
489 // The Module handles the pointer reference sharing...
490 return GV->getParent()->getConstantPointerRef(GV);
493 // destroyConstant - Remove the constant from the constant table...
495 void ConstantPointerRef::destroyConstant() {
496 getValue()->getParent()->destroyConstantPointerRef(this);
497 destroyConstantImpl();
501 //---- ConstantExpr::get() implementations...
503 typedef pair<unsigned, vector<Constant*> > ExprMapKeyType;
504 static ValueMap<const ExprMapKeyType, ConstantExpr> ExprConstants;
506 ConstantExpr *ConstantExpr::getCast(Constant *C, const Type *Ty) {
508 // Look up the constant in the table first to ensure uniqueness
509 vector<Constant*> argVec(1, C);
510 const ExprMapKeyType &Key = make_pair(Instruction::Cast, argVec);
511 ConstantExpr *Result = ExprConstants.get(Ty, Key);
512 if (Result) return Result;
514 // Its not in the table so create a new one and put it in the table.
515 Result = new ConstantExpr(Instruction::Cast, C, Ty);
516 ExprConstants.add(Ty, Key, Result);
520 ConstantExpr *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
521 // Look up the constant in the table first to ensure uniqueness
522 vector<Constant*> argVec(1, C1); argVec.push_back(C2);
523 const ExprMapKeyType &Key = make_pair(Opcode, argVec);
524 ConstantExpr *Result = ExprConstants.get(C1->getType(), Key);
525 if (Result) return Result;
527 // Its not in the table so create a new one and put it in the table.
528 // Check the operands for consistency first
529 assert((Opcode >= Instruction::FirstBinaryOp &&
530 Opcode < Instruction::NumBinaryOps) &&
531 "Invalid opcode in binary constant expression");
533 assert(C1->getType() == C2->getType() &&
534 "Operand types in binary constant expression should match");
536 Result = new ConstantExpr(Opcode, C1, C2);
537 ExprConstants.add(C1->getType(), Key, Result);
541 ConstantExpr *ConstantExpr::getGetElementPtr(Constant *C,
542 const std::vector<Constant*> &IdxList) {
543 const Type *Ty = C->getType();
545 // Look up the constant in the table first to ensure uniqueness
546 vector<Constant*> argVec(1, C);
547 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
549 const ExprMapKeyType &Key = make_pair(Instruction::GetElementPtr, argVec);
550 ConstantExpr *Result = ExprConstants.get(Ty, Key);
551 if (Result) return Result;
553 // Its not in the table so create a new one and put it in the table.
554 // Check the operands for consistency first
556 assert(isa<PointerType>(Ty) &&
557 "Non-pointer type for constant GelElementPtr expression");
559 // Check that the indices list is valid...
560 std::vector<Value*> ValIdxList(IdxList.begin(), IdxList.end());
561 const Type *DestTy = GetElementPtrInst::getIndexedType(Ty, ValIdxList, true);
562 assert(DestTy && "Invalid index list for constant GelElementPtr expression");
564 Result = new ConstantExpr(C, IdxList, PointerType::get(DestTy));
565 ExprConstants.add(Ty, Key, Result);
569 // destroyConstant - Remove the constant from the constant table...
571 void ConstantExpr::destroyConstant() {
572 ExprConstants.remove(this);
573 destroyConstantImpl();
576 const char *ConstantExpr::getOpcodeName() const {
577 return Instruction::getOpcodeName(getOpcode());
581 //---- ConstantPointerRef::mutateReferences() implementation...
583 unsigned ConstantPointerRef::mutateReferences(Value *OldV, Value *NewV) {
584 assert(getValue() == OldV && "Cannot mutate old value if I'm not using it!");
585 GlobalValue *NewGV = cast<GlobalValue>(NewV);
586 getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);
592 //---- ConstantPointerExpr::mutateReferences() implementation...
594 unsigned ConstantExpr::mutateReferences(Value* OldV, Value *NewV) {
595 unsigned NumReplaced = 0;
596 Constant *NewC = cast<Constant>(NewV);
597 for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
598 if (Operands[i] == OldV) {