1 //===-- Constants.cpp - Implement Constant nodes -----------------*- C++ -*--=//
3 // This file implements the Constant* classes...
5 //===----------------------------------------------------------------------===//
7 #define __STDC_LIMIT_MACROS // Get defs for INT64_MAX and friends...
8 #include "llvm/Constants.h"
9 #include "llvm/DerivedTypes.h"
10 #include "llvm/iMemory.h"
11 #include "llvm/SymbolTable.h"
12 #include "llvm/Module.h"
13 #include "llvm/SlotCalculator.h"
14 #include "Support/StringExtras.h"
22 ConstantBool *ConstantBool::True = new ConstantBool(true);
23 ConstantBool *ConstantBool::False = new ConstantBool(false);
26 //===----------------------------------------------------------------------===//
28 //===----------------------------------------------------------------------===//
30 // Specialize setName to take care of symbol table majik
31 void Constant::setName(const std::string &Name, SymbolTable *ST) {
32 assert(ST && "Type::setName - Must provide symbol table argument!");
34 if (Name.size()) ST->insert(Name, this);
37 void Constant::destroyConstantImpl() {
38 // When a Constant is destroyed, there may be lingering
39 // references to the constant by other constants in the constant pool. These
40 // constants are implicitly dependant on the module that is being deleted,
41 // but they don't know that. Because we only find out when the CPV is
42 // deleted, we must now notify all of our users (that should only be
43 // Constants) that they are, in fact, invalid now and should be deleted.
45 while (!use_empty()) {
46 Value *V = use_back();
47 #ifndef NDEBUG // Only in -g mode...
48 if (!isa<Constant>(V))
49 std::cerr << "While deleting: " << *this
50 << "\n\nUse still stuck around after Def is destroyed: "
53 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
54 Constant *CPV = cast<Constant>(V);
55 CPV->destroyConstant();
57 // The constant should remove itself from our use list...
58 assert((use_empty() || use_back() != V) && "Constant not removed!");
61 // Value has no outstanding references it is safe to delete it now...
65 // Static constructor to create a '0' constant of arbitrary type...
66 Constant *Constant::getNullValue(const Type *Ty) {
67 switch (Ty->getPrimitiveID()) {
68 case Type::BoolTyID: return ConstantBool::get(false);
72 case Type::LongTyID: return ConstantSInt::get(Ty, 0);
75 case Type::UShortTyID:
77 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
80 case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
82 case Type::PointerTyID:
83 return ConstantPointerNull::get(cast<PointerType>(Ty));
89 // Static constructor to create the maximum constant of an integral type...
90 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
91 switch (Ty->getPrimitiveID()) {
92 case Type::BoolTyID: return ConstantBool::True;
96 case Type::LongTyID: {
97 // Calculate 011111111111111...
98 unsigned TypeBits = Ty->getPrimitiveSize()*8;
99 int64_t Val = INT64_MAX; // All ones
100 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
101 return ConstantSInt::get(Ty, Val);
104 case Type::UByteTyID:
105 case Type::UShortTyID:
107 case Type::ULongTyID: return getAllOnesValue(Ty);
113 // Static constructor to create the minimum constant for an integral type...
114 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
115 switch (Ty->getPrimitiveID()) {
116 case Type::BoolTyID: return ConstantBool::False;
117 case Type::SByteTyID:
118 case Type::ShortTyID:
120 case Type::LongTyID: {
121 // Calculate 1111111111000000000000
122 unsigned TypeBits = Ty->getPrimitiveSize()*8;
123 int64_t Val = -1; // All ones
124 Val <<= TypeBits-1; // Shift over to the right spot
125 return ConstantSInt::get(Ty, Val);
128 case Type::UByteTyID:
129 case Type::UShortTyID:
131 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
137 // Static constructor to create an integral constant with all bits set
138 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
139 switch (Ty->getPrimitiveID()) {
140 case Type::BoolTyID: return ConstantBool::True;
141 case Type::SByteTyID:
142 case Type::ShortTyID:
144 case Type::LongTyID: return ConstantSInt::get(Ty, -1);
146 case Type::UByteTyID:
147 case Type::UShortTyID:
149 case Type::ULongTyID: {
150 // Calculate ~0 of the right type...
151 unsigned TypeBits = Ty->getPrimitiveSize()*8;
152 uint64_t Val = ~0ULL; // All ones
153 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
154 return ConstantUInt::get(Ty, Val);
161 //===----------------------------------------------------------------------===//
162 // ConstantXXX Classes
163 //===----------------------------------------------------------------------===//
165 //===----------------------------------------------------------------------===//
166 // Normal Constructors
168 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy) {
172 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty) {
176 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
177 assert(isValueValidForType(Ty, V) && "Value too large for type!");
180 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
181 assert(isValueValidForType(Ty, V) && "Value too large for type!");
184 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
185 assert(isValueValidForType(Ty, V) && "Value too large for type!");
189 ConstantArray::ConstantArray(const ArrayType *T,
190 const std::vector<Constant*> &V) : Constant(T) {
191 for (unsigned i = 0; i < V.size(); i++) {
192 assert(V[i]->getType() == T->getElementType());
193 Operands.push_back(Use(V[i], this));
197 ConstantStruct::ConstantStruct(const StructType *T,
198 const std::vector<Constant*> &V) : Constant(T) {
199 const StructType::ElementTypes &ETypes = T->getElementTypes();
200 assert(V.size() == ETypes.size() &&
201 "Invalid initializer vector for constant structure");
202 for (unsigned i = 0; i < V.size(); i++) {
203 assert(V[i]->getType() == ETypes[i]);
204 Operands.push_back(Use(V[i], this));
208 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
209 : ConstantPointer(GV->getType()) {
210 Operands.push_back(Use(GV, this));
213 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
214 : Constant(Ty), iType(Opcode) {
215 Operands.push_back(Use(C, this));
218 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
219 : Constant(C1->getType()), iType(Opcode) {
220 Operands.push_back(Use(C1, this));
221 Operands.push_back(Use(C2, this));
224 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
226 : Constant(DestTy), iType(Instruction::GetElementPtr) {
227 Operands.reserve(1+IdxList.size());
228 Operands.push_back(Use(C, this));
229 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
230 Operands.push_back(Use(IdxList[i], this));
235 //===----------------------------------------------------------------------===//
236 // classof implementations
238 bool ConstantIntegral::classof(const Constant *CPV) {
239 return (CPV->getType()->isIntegral() || CPV->getType() == Type::BoolTy) &&
240 !isa<ConstantExpr>(CPV);
243 bool ConstantInt::classof(const Constant *CPV) {
244 return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
246 bool ConstantSInt::classof(const Constant *CPV) {
247 return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
249 bool ConstantUInt::classof(const Constant *CPV) {
250 return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
252 bool ConstantFP::classof(const Constant *CPV) {
253 const Type *Ty = CPV->getType();
254 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
255 !isa<ConstantExpr>(CPV));
257 bool ConstantArray::classof(const Constant *CPV) {
258 return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
260 bool ConstantStruct::classof(const Constant *CPV) {
261 return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
263 bool ConstantPointer::classof(const Constant *CPV) {
264 return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
269 //===----------------------------------------------------------------------===//
270 // isValueValidForType implementations
272 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
273 switch (Ty->getPrimitiveID()) {
275 return false; // These can't be represented as integers!!!
278 case Type::SByteTyID:
279 return (Val <= INT8_MAX && Val >= INT8_MIN);
280 case Type::ShortTyID:
281 return (Val <= INT16_MAX && Val >= INT16_MIN);
283 return (Val <= INT32_MAX && Val >= INT32_MIN);
285 return true; // This is the largest type...
291 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
292 switch (Ty->getPrimitiveID()) {
294 return false; // These can't be represented as integers!!!
297 case Type::UByteTyID:
298 return (Val <= UINT8_MAX);
299 case Type::UShortTyID:
300 return (Val <= UINT16_MAX);
302 return (Val <= UINT32_MAX);
303 case Type::ULongTyID:
304 return true; // This is the largest type...
310 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
311 switch (Ty->getPrimitiveID()) {
313 return false; // These can't be represented as floating point!
315 // TODO: Figure out how to test if a double can be cast to a float!
316 case Type::FloatTyID:
318 return (Val <= UINT8_MAX);
320 case Type::DoubleTyID:
321 return true; // This is the largest type...
325 //===----------------------------------------------------------------------===//
326 // Factory Function Implementation
328 template<class ValType, class ConstantClass>
330 typedef pair<const Type*, ValType> ConstHashKey;
331 map<ConstHashKey, ConstantClass *> Map;
333 inline ConstantClass *get(const Type *Ty, ValType V) {
334 typename map<ConstHashKey,ConstantClass *>::iterator I =
335 Map.find(ConstHashKey(Ty, V));
336 return (I != Map.end()) ? I->second : 0;
339 inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
340 Map.insert(make_pair(ConstHashKey(Ty, V), CP));
343 inline void remove(ConstantClass *CP) {
344 for (typename map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
345 E = Map.end(); I != E;++I)
346 if (I->second == CP) {
353 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
355 static ValueMap<uint64_t, ConstantInt> IntConstants;
357 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
358 ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
359 if (!Result) // If no preexisting value, create one now...
360 IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
364 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
365 ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
366 if (!Result) // If no preexisting value, create one now...
367 IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
371 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
372 assert(V <= 127 && "Can only be used with very small positive constants!");
373 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
374 return ConstantUInt::get(Ty, V);
377 //---- ConstantFP::get() implementation...
379 static ValueMap<double, ConstantFP> FPConstants;
381 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
382 ConstantFP *Result = FPConstants.get(Ty, V);
383 if (!Result) // If no preexisting value, create one now...
384 FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
388 //---- ConstantArray::get() implementation...
390 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
392 ConstantArray *ConstantArray::get(const ArrayType *Ty,
393 const std::vector<Constant*> &V) {
394 ConstantArray *Result = ArrayConstants.get(Ty, V);
395 if (!Result) // If no preexisting value, create one now...
396 ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
400 // ConstantArray::get(const string&) - Return an array that is initialized to
401 // contain the specified string. A null terminator is added to the specified
402 // string so that it may be used in a natural way...
404 ConstantArray *ConstantArray::get(const std::string &Str) {
405 std::vector<Constant*> ElementVals;
407 for (unsigned i = 0; i < Str.length(); ++i)
408 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
410 // Add a null terminator to the string...
411 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
413 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
414 return ConstantArray::get(ATy, ElementVals);
418 // destroyConstant - Remove the constant from the constant table...
420 void ConstantArray::destroyConstant() {
421 ArrayConstants.remove(this);
422 destroyConstantImpl();
425 //---- ConstantStruct::get() implementation...
427 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
429 ConstantStruct *ConstantStruct::get(const StructType *Ty,
430 const std::vector<Constant*> &V) {
431 ConstantStruct *Result = StructConstants.get(Ty, V);
432 if (!Result) // If no preexisting value, create one now...
433 StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
437 // destroyConstant - Remove the constant from the constant table...
439 void ConstantStruct::destroyConstant() {
440 StructConstants.remove(this);
441 destroyConstantImpl();
444 //---- ConstantPointerNull::get() implementation...
446 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
448 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
449 ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
450 if (!Result) // If no preexisting value, create one now...
451 NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
455 //---- ConstantPointerRef::get() implementation...
457 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
458 assert(GV->getParent() && "Global Value must be attached to a module!");
460 // The Module handles the pointer reference sharing...
461 return GV->getParent()->getConstantPointerRef(GV);
464 //---- ConstantExpr::get() implementations...
466 typedef pair<unsigned, vector<Constant*> > ExprMapKeyType;
467 static ValueMap<const ExprMapKeyType, ConstantExpr> ExprConstants;
469 ConstantExpr *ConstantExpr::get(unsigned Opcode, Constant *C, const Type *Ty) {
471 // Look up the constant in the table first to ensure uniqueness
472 vector<Constant*> argVec(1, C);
473 const ExprMapKeyType &Key = make_pair(Opcode, argVec);
474 ConstantExpr *Result = ExprConstants.get(Ty, Key);
475 if (Result) return Result;
477 // Its not in the table so create a new one and put it in the table.
478 // Check the operands for consistency first
479 assert(Opcode == Instruction::Cast ||
480 (Opcode >= Instruction::FirstUnaryOp &&
481 Opcode < Instruction::NumUnaryOps) &&
482 "Invalid opcode in unary ConstantExpr!");
484 // type of operand will not match result for Cast operation
485 assert((Opcode == Instruction::Cast || Ty == C->getType()) &&
486 "Type of operand in unary constant expression should match result");
488 Result = new ConstantExpr(Opcode, C, Ty);
489 ExprConstants.add(Ty, Key, Result);
493 ConstantExpr *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
494 // Look up the constant in the table first to ensure uniqueness
495 vector<Constant*> argVec(1, C1); argVec.push_back(C2);
496 const ExprMapKeyType &Key = make_pair(Opcode, argVec);
497 ConstantExpr *Result = ExprConstants.get(C1->getType(), Key);
498 if (Result) return Result;
500 // Its not in the table so create a new one and put it in the table.
501 // Check the operands for consistency first
502 assert((Opcode >= Instruction::FirstBinaryOp &&
503 Opcode < Instruction::NumBinaryOps) &&
504 "Invalid opcode in binary constant expression");
506 assert(C1->getType() == C2->getType() &&
507 "Operand types in binary constant expression should match");
509 Result = new ConstantExpr(Opcode, C1, C2);
510 ExprConstants.add(C1->getType(), Key, Result);
514 ConstantExpr *ConstantExpr::getGetElementPtr(Constant *C,
515 const std::vector<Constant*> &IdxList) {
516 const Type *Ty = C->getType();
518 // Look up the constant in the table first to ensure uniqueness
519 vector<Constant*> argVec(1, C);
520 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
522 const ExprMapKeyType &Key = make_pair(Instruction::GetElementPtr, argVec);
523 ConstantExpr *Result = ExprConstants.get(Ty, Key);
524 if (Result) return Result;
526 // Its not in the table so create a new one and put it in the table.
527 // Check the operands for consistency first
529 assert(isa<PointerType>(Ty) &&
530 "Non-pointer type for constant GelElementPtr expression");
532 // Check that the indices list is valid...
533 std::vector<Value*> ValIdxList(IdxList.begin(), IdxList.end());
534 const Type *DestTy = GetElementPtrInst::getIndexedType(Ty, ValIdxList, true);
535 assert(DestTy && "Invalid index list for constant GelElementPtr expression");
537 Result = new ConstantExpr(C, IdxList, PointerType::get(DestTy));
538 ExprConstants.add(Ty, Key, Result);
542 // destroyConstant - Remove the constant from the constant table...
544 void ConstantExpr::destroyConstant() {
545 ExprConstants.remove(this);
546 destroyConstantImpl();
549 const char *ConstantExpr::getOpcodeName() const {
550 return Instruction::getOpcodeName(getOpcode());
554 //---- ConstantPointerRef::mutateReferences() implementation...
556 unsigned ConstantPointerRef::mutateReferences(Value *OldV, Value *NewV) {
557 assert(getValue() == OldV && "Cannot mutate old value if I'm not using it!");
558 GlobalValue *NewGV = cast<GlobalValue>(NewV);
559 getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);
565 //---- ConstantPointerExpr::mutateReferences() implementation...
567 unsigned ConstantExpr::mutateReferences(Value* OldV, Value *NewV) {
568 unsigned NumReplaced = 0;
569 Constant *NewC = cast<Constant>(NewV);
570 for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
571 if (Operands[i] == OldV) {