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"
24 ConstantBool *ConstantBool::True = new ConstantBool(true);
25 ConstantBool *ConstantBool::False = new ConstantBool(false);
28 //===----------------------------------------------------------------------===//
30 //===----------------------------------------------------------------------===//
32 // Specialize setName to take care of symbol table majik
33 void Constant::setName(const std::string &Name, SymbolTable *ST) {
34 assert(ST && "Type::setName - Must provide symbol table argument!");
36 if (Name.size()) ST->insert(Name, this);
39 // Static constructor to create a '0' constant of arbitrary type...
40 Constant *Constant::getNullValue(const Type *Ty) {
41 switch (Ty->getPrimitiveID()) {
42 case Type::BoolTyID: return ConstantBool::get(false);
46 case Type::LongTyID: return ConstantSInt::get(Ty, 0);
49 case Type::UShortTyID:
51 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
54 case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
56 case Type::PointerTyID:
57 return ConstantPointerNull::get(cast<PointerType>(Ty));
63 void Constant::destroyConstantImpl() {
64 // When a Constant is destroyed, there may be lingering
65 // references to the constant by other constants in the constant pool. These
66 // constants are implicitly dependant on the module that is being deleted,
67 // but they don't know that. Because we only find out when the CPV is
68 // deleted, we must now notify all of our users (that should only be
69 // Constants) that they are, in fact, invalid now and should be deleted.
71 while (!use_empty()) {
72 Value *V = use_back();
73 #ifndef NDEBUG // Only in -g mode...
74 if (!isa<Constant>(V)) {
75 std::cerr << "While deleting: ";
77 std::cerr << "\nUse still stuck around after Def is destroyed: ";
82 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
83 Constant *CPV = cast<Constant>(V);
84 CPV->destroyConstant();
86 // The constant should remove itself from our use list...
87 assert((use_empty() || use_back() != V) && "Constant not removed!");
90 // Value has no outstanding references it is safe to delete it now...
94 //===----------------------------------------------------------------------===//
95 // ConstantXXX Classes
96 //===----------------------------------------------------------------------===//
98 //===----------------------------------------------------------------------===//
99 // Normal Constructors
101 ConstantBool::ConstantBool(bool V) : Constant(Type::BoolTy) {
105 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : Constant(Ty) {
109 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
110 assert(isValueValidForType(Ty, V) && "Value too large for type!");
113 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
114 assert(isValueValidForType(Ty, V) && "Value too large for type!");
117 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
118 assert(isValueValidForType(Ty, V) && "Value too large for type!");
122 ConstantArray::ConstantArray(const ArrayType *T,
123 const std::vector<Constant*> &V) : Constant(T) {
124 for (unsigned i = 0; i < V.size(); i++) {
125 assert(V[i]->getType() == T->getElementType());
126 Operands.push_back(Use(V[i], this));
130 ConstantStruct::ConstantStruct(const StructType *T,
131 const std::vector<Constant*> &V) : Constant(T) {
132 const StructType::ElementTypes &ETypes = T->getElementTypes();
133 assert(V.size() == ETypes.size() &&
134 "Invalid initializer vector for constant structure");
135 for (unsigned i = 0; i < V.size(); i++) {
136 assert(V[i]->getType() == ETypes[i]);
137 Operands.push_back(Use(V[i], this));
141 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
142 : ConstantPointer(GV->getType()) {
143 Operands.push_back(Use(GV, this));
146 ConstantExpr::ConstantExpr(unsigned opCode, Constant *C, const Type *Ty)
147 : Constant(Ty), iType(opCode) {
148 Operands.push_back(Use(C, this));
151 ConstantExpr::ConstantExpr(unsigned opCode, Constant* C1,
152 Constant* C2, const Type *Ty)
153 : Constant(Ty), iType(opCode) {
154 Operands.push_back(Use(C1, this));
155 Operands.push_back(Use(C2, this));
158 ConstantExpr::ConstantExpr(unsigned opCode, Constant* C,
159 const std::vector<Value*>& IdxList, const Type *Ty)
160 : Constant(Ty), iType(opCode) {
161 Operands.reserve(1+IdxList.size());
162 Operands.push_back(Use(C, this));
163 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
164 Operands.push_back(Use(IdxList[i], this));
169 //===----------------------------------------------------------------------===//
170 // classof implementations
172 bool ConstantInt::classof(const Constant *CPV) {
173 return CPV->getType()->isIntegral() && ! isa<ConstantExpr>(CPV);
175 bool ConstantSInt::classof(const Constant *CPV) {
176 return CPV->getType()->isSigned() && ! isa<ConstantExpr>(CPV);
178 bool ConstantUInt::classof(const Constant *CPV) {
179 return CPV->getType()->isUnsigned() && ! isa<ConstantExpr>(CPV);
181 bool ConstantFP::classof(const Constant *CPV) {
182 const Type *Ty = CPV->getType();
183 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
184 ! isa<ConstantExpr>(CPV));
186 bool ConstantArray::classof(const Constant *CPV) {
187 return isa<ArrayType>(CPV->getType()) && ! isa<ConstantExpr>(CPV);
189 bool ConstantStruct::classof(const Constant *CPV) {
190 return isa<StructType>(CPV->getType()) && ! isa<ConstantExpr>(CPV);
192 bool ConstantPointer::classof(const Constant *CPV) {
193 return (isa<PointerType>(CPV->getType()) && ! isa<ConstantExpr>(CPV));
198 //===----------------------------------------------------------------------===//
199 // isValueValidForType implementations
201 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
202 switch (Ty->getPrimitiveID()) {
204 return false; // These can't be represented as integers!!!
207 case Type::SByteTyID:
208 return (Val <= INT8_MAX && Val >= INT8_MIN);
209 case Type::ShortTyID:
210 return (Val <= INT16_MAX && Val >= INT16_MIN);
212 return (Val <= INT32_MAX && Val >= INT32_MIN);
214 return true; // This is the largest type...
220 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
221 switch (Ty->getPrimitiveID()) {
223 return false; // These can't be represented as integers!!!
226 case Type::UByteTyID:
227 return (Val <= UINT8_MAX);
228 case Type::UShortTyID:
229 return (Val <= UINT16_MAX);
231 return (Val <= UINT32_MAX);
232 case Type::ULongTyID:
233 return true; // This is the largest type...
239 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
240 switch (Ty->getPrimitiveID()) {
242 return false; // These can't be represented as floating point!
244 // TODO: Figure out how to test if a double can be cast to a float!
245 case Type::FloatTyID:
247 return (Val <= UINT8_MAX);
249 case Type::DoubleTyID:
250 return true; // This is the largest type...
254 //===----------------------------------------------------------------------===//
255 // Factory Function Implementation
257 template<class ValType, class ConstantClass>
259 typedef pair<const Type*, ValType> ConstHashKey;
260 map<ConstHashKey, ConstantClass *> Map;
262 inline ConstantClass *get(const Type *Ty, ValType V) {
263 map<ConstHashKey,ConstantClass *>::iterator I =
264 Map.find(ConstHashKey(Ty, V));
265 return (I != Map.end()) ? I->second : 0;
268 inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
269 Map.insert(make_pair(ConstHashKey(Ty, V), CP));
272 inline void remove(ConstantClass *CP) {
273 for (map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
274 E = Map.end(); I != E;++I)
275 if (I->second == CP) {
282 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
284 static ValueMap<uint64_t, ConstantInt> IntConstants;
286 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
287 ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
288 if (!Result) // If no preexisting value, create one now...
289 IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
293 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
294 ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
295 if (!Result) // If no preexisting value, create one now...
296 IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
300 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
301 assert(V <= 127 && "Can only be used with very small positive constants!");
302 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
303 return ConstantUInt::get(Ty, V);
306 //---- ConstantFP::get() implementation...
308 static ValueMap<double, ConstantFP> FPConstants;
310 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
311 ConstantFP *Result = FPConstants.get(Ty, V);
312 if (!Result) // If no preexisting value, create one now...
313 FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
317 //---- ConstantArray::get() implementation...
319 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
321 ConstantArray *ConstantArray::get(const ArrayType *Ty,
322 const std::vector<Constant*> &V) {
323 ConstantArray *Result = ArrayConstants.get(Ty, V);
324 if (!Result) // If no preexisting value, create one now...
325 ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
329 // ConstantArray::get(const string&) - Return an array that is initialized to
330 // contain the specified string. A null terminator is added to the specified
331 // string so that it may be used in a natural way...
333 ConstantArray *ConstantArray::get(const std::string &Str) {
334 std::vector<Constant*> ElementVals;
336 for (unsigned i = 0; i < Str.length(); ++i)
337 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
339 // Add a null terminator to the string...
340 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
342 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
343 return ConstantArray::get(ATy, ElementVals);
347 // destroyConstant - Remove the constant from the constant table...
349 void ConstantArray::destroyConstant() {
350 ArrayConstants.remove(this);
351 destroyConstantImpl();
354 //---- ConstantStruct::get() implementation...
356 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
358 ConstantStruct *ConstantStruct::get(const StructType *Ty,
359 const std::vector<Constant*> &V) {
360 ConstantStruct *Result = StructConstants.get(Ty, V);
361 if (!Result) // If no preexisting value, create one now...
362 StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
366 // destroyConstant - Remove the constant from the constant table...
368 void ConstantStruct::destroyConstant() {
369 StructConstants.remove(this);
370 destroyConstantImpl();
373 //---- ConstantPointerNull::get() implementation...
375 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
377 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
378 ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
379 if (!Result) // If no preexisting value, create one now...
380 NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
384 //---- ConstantPointerRef::get() implementation...
386 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
387 assert(GV->getParent() && "Global Value must be attached to a module!");
389 // The Module handles the pointer reference sharing...
390 return GV->getParent()->getConstantPointerRef(GV);
393 //---- ConstantExpr::get() implementations...
394 // Return NULL on invalid expressions.
396 typedef pair<unsigned, vector<Constant*> > ExprMapKeyType;
397 static ValueMap<const ExprMapKeyType, ConstantExpr> ExprConstants;
400 ConstantExpr::get(unsigned opCode, Constant *C, const Type *Ty) {
402 // Look up the constant in the table first to ensure uniqueness
403 vector<Constant*> argVec(1, C);
404 const ExprMapKeyType& key = make_pair(opCode, argVec);
405 ConstantExpr* result = ExprConstants.get(Ty, key);
409 // Its not in the table so create a new one and put it in the table.
410 // Check the operands for consistency first
411 if (opCode != Instruction::Cast &&
412 (opCode < Instruction::FirstUnaryOp ||
413 opCode >= Instruction::NumUnaryOps)) {
414 std::cerr << "Invalid opcode " << ConstantExpr::getOpcodeName(opCode)
415 << " in unary constant expression" << std::endl;
416 return NULL; // Not Cast or other unary opcode
418 // type of operand will not match result for Cast operation
419 if (opCode != Instruction::Cast && Ty != C->getType()) {
420 cerr << "Type of operand in unary constant expression should match result" << endl;
424 result = new ConstantExpr(opCode, C, Ty);
425 ExprConstants.add(Ty, key, result);
430 ConstantExpr::get(unsigned opCode, Constant *C1, Constant *C2,const Type *Ty) {
432 // Look up the constant in the table first to ensure uniqueness
433 vector<Constant*> argVec(1, C1); argVec.push_back(C2);
434 const ExprMapKeyType& key = make_pair(opCode, argVec);
435 ConstantExpr* result = ExprConstants.get(Ty, key);
439 // Its not in the table so create a new one and put it in the table.
440 // Check the operands for consistency first
441 if (opCode < Instruction::FirstBinaryOp ||
442 opCode >= Instruction::NumBinaryOps) {
443 cerr << "Invalid opcode " << ConstantExpr::getOpcodeName(opCode)
444 << " in binary constant expression" << endl;
447 if (Ty != C1->getType() || Ty != C2->getType()) {
448 cerr << "Types of both operands in binary constant expression should match result" << endl;
452 result = new ConstantExpr(opCode, C1, C2, Ty);
453 ExprConstants.add(Ty, key, result);
458 ConstantExpr::get(unsigned opCode, Constant*C,
459 const std::vector<Value*>& idxList, const Type *Ty) {
461 // Look up the constant in the table first to ensure uniqueness
462 vector<Constant*> argVec(1, C);
463 for(vector<Value*>::const_iterator VI=idxList.begin(), VE=idxList.end();
465 if (Constant *C = dyn_cast<Constant>(*VI))
468 cerr << "Non-constant index in constant GetElementPtr expr";
472 const ExprMapKeyType& key = make_pair(opCode, argVec);
473 ConstantExpr* result = ExprConstants.get(Ty, key);
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 // Must be a getElementPtr. Check for valid getElementPtr expression.
481 if (opCode != Instruction::GetElementPtr) {
482 cerr << "operator other than GetElementPtr used with an index list" << endl;
485 if (!isa<ConstantPointer>(C)) {
486 cerr << "Constant GelElementPtr expression using something other than a constant pointer" << endl;
489 if (!isa<PointerType>(Ty)) {
490 cerr << "Non-pointer type for constant GelElementPtr expression" << endl;
493 const Type* fldType = GetElementPtrInst::getIndexedType(C->getType(),
496 cerr << "Invalid index list for constant GelElementPtr expression" << endl;
499 if (cast<PointerType>(Ty)->getElementType() != fldType) {
500 cerr << "Type for constant GelElementPtr expression does not match field type" << endl;
504 result = new ConstantExpr(opCode, C, idxList, Ty);
505 ExprConstants.add(Ty, key, result);
509 // destroyConstant - Remove the constant from the constant table...
511 void ConstantExpr::destroyConstant() {
512 ExprConstants.remove(this);
513 destroyConstantImpl();
517 ConstantExpr::getOpcodeName(unsigned opCode) {
518 return Instruction::getOpcodeName(opCode);
522 //---- ConstantPointerRef::mutateReferences() implementation...
525 ConstantPointerRef::mutateReferences(Value* OldV, Value *NewV) {
526 assert(getValue() == OldV && "Cannot mutate old value if I'm not using it!");
527 GlobalValue* NewGV = cast<GlobalValue>(NewV);
528 getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);
534 //---- ConstantPointerExpr::mutateReferences() implementation...
537 ConstantExpr::mutateReferences(Value* OldV, Value *NewV) {
538 unsigned numReplaced = 0;
539 Constant* NewC = cast<Constant>(NewV);
540 for (unsigned i=0, N = getNumOperands(); i < N; ++i)
541 if (Operands[i] == OldV) {