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 // Static constructor to create a '0' constant of arbitrary type...
38 Constant *Constant::getNullValue(const Type *Ty) {
39 switch (Ty->getPrimitiveID()) {
40 case Type::BoolTyID: return ConstantBool::get(false);
44 case Type::LongTyID: return ConstantSInt::get(Ty, 0);
47 case Type::UShortTyID:
49 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
52 case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
54 case Type::PointerTyID:
55 return ConstantPointerNull::get(cast<PointerType>(Ty));
61 void Constant::destroyConstantImpl() {
62 // When a Constant is destroyed, there may be lingering
63 // references to the constant by other constants in the constant pool. These
64 // constants are implicitly dependant on the module that is being deleted,
65 // but they don't know that. Because we only find out when the CPV is
66 // deleted, we must now notify all of our users (that should only be
67 // Constants) that they are, in fact, invalid now and should be deleted.
69 while (!use_empty()) {
70 Value *V = use_back();
71 #ifndef NDEBUG // Only in -g mode...
72 if (!isa<Constant>(V))
73 std::cerr << "While deleting: " << *this
74 << "\n\nUse still stuck around after Def is destroyed: "
77 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
78 Constant *CPV = cast<Constant>(V);
79 CPV->destroyConstant();
81 // The constant should remove itself from our use list...
82 assert((use_empty() || use_back() != V) && "Constant not removed!");
85 // Value has no outstanding references it is safe to delete it now...
89 //===----------------------------------------------------------------------===//
90 // ConstantXXX Classes
91 //===----------------------------------------------------------------------===//
93 //===----------------------------------------------------------------------===//
94 // Normal Constructors
96 ConstantBool::ConstantBool(bool V) : Constant(Type::BoolTy) {
100 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : Constant(Ty) {
104 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
105 assert(isValueValidForType(Ty, V) && "Value too large for type!");
108 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
109 assert(isValueValidForType(Ty, V) && "Value too large for type!");
112 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
113 assert(isValueValidForType(Ty, V) && "Value too large for type!");
117 ConstantArray::ConstantArray(const ArrayType *T,
118 const std::vector<Constant*> &V) : Constant(T) {
119 for (unsigned i = 0; i < V.size(); i++) {
120 assert(V[i]->getType() == T->getElementType());
121 Operands.push_back(Use(V[i], this));
125 ConstantStruct::ConstantStruct(const StructType *T,
126 const std::vector<Constant*> &V) : Constant(T) {
127 const StructType::ElementTypes &ETypes = T->getElementTypes();
128 assert(V.size() == ETypes.size() &&
129 "Invalid initializer vector for constant structure");
130 for (unsigned i = 0; i < V.size(); i++) {
131 assert(V[i]->getType() == ETypes[i]);
132 Operands.push_back(Use(V[i], this));
136 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
137 : ConstantPointer(GV->getType()) {
138 Operands.push_back(Use(GV, this));
141 ConstantExpr::ConstantExpr(unsigned opCode, Constant *C, const Type *Ty)
142 : Constant(Ty), iType(opCode) {
143 Operands.push_back(Use(C, this));
146 ConstantExpr::ConstantExpr(unsigned opCode, Constant* C1,
147 Constant* C2, const Type *Ty)
148 : Constant(Ty), iType(opCode) {
149 Operands.push_back(Use(C1, this));
150 Operands.push_back(Use(C2, this));
153 ConstantExpr::ConstantExpr(unsigned opCode, Constant* C,
154 const std::vector<Constant*> &IdxList, const Type *Ty)
155 : Constant(Ty), iType(opCode) {
156 Operands.reserve(1+IdxList.size());
157 Operands.push_back(Use(C, this));
158 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
159 Operands.push_back(Use(IdxList[i], this));
164 //===----------------------------------------------------------------------===//
165 // classof implementations
167 bool ConstantInt::classof(const Constant *CPV) {
168 return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
170 bool ConstantSInt::classof(const Constant *CPV) {
171 return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
173 bool ConstantUInt::classof(const Constant *CPV) {
174 return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
176 bool ConstantFP::classof(const Constant *CPV) {
177 const Type *Ty = CPV->getType();
178 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
179 !isa<ConstantExpr>(CPV));
181 bool ConstantArray::classof(const Constant *CPV) {
182 return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
184 bool ConstantStruct::classof(const Constant *CPV) {
185 return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
187 bool ConstantPointer::classof(const Constant *CPV) {
188 return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
193 //===----------------------------------------------------------------------===//
194 // isValueValidForType implementations
196 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
197 switch (Ty->getPrimitiveID()) {
199 return false; // These can't be represented as integers!!!
202 case Type::SByteTyID:
203 return (Val <= INT8_MAX && Val >= INT8_MIN);
204 case Type::ShortTyID:
205 return (Val <= INT16_MAX && Val >= INT16_MIN);
207 return (Val <= INT32_MAX && Val >= INT32_MIN);
209 return true; // This is the largest type...
215 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
216 switch (Ty->getPrimitiveID()) {
218 return false; // These can't be represented as integers!!!
221 case Type::UByteTyID:
222 return (Val <= UINT8_MAX);
223 case Type::UShortTyID:
224 return (Val <= UINT16_MAX);
226 return (Val <= UINT32_MAX);
227 case Type::ULongTyID:
228 return true; // This is the largest type...
234 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
235 switch (Ty->getPrimitiveID()) {
237 return false; // These can't be represented as floating point!
239 // TODO: Figure out how to test if a double can be cast to a float!
240 case Type::FloatTyID:
242 return (Val <= UINT8_MAX);
244 case Type::DoubleTyID:
245 return true; // This is the largest type...
249 //===----------------------------------------------------------------------===//
250 // Factory Function Implementation
252 template<class ValType, class ConstantClass>
254 typedef pair<const Type*, ValType> ConstHashKey;
255 map<ConstHashKey, ConstantClass *> Map;
257 inline ConstantClass *get(const Type *Ty, ValType V) {
258 typename map<ConstHashKey,ConstantClass *>::iterator I =
259 Map.find(ConstHashKey(Ty, V));
260 return (I != Map.end()) ? I->second : 0;
263 inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
264 Map.insert(make_pair(ConstHashKey(Ty, V), CP));
267 inline void remove(ConstantClass *CP) {
268 for (typename map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
269 E = Map.end(); I != E;++I)
270 if (I->second == CP) {
277 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
279 static ValueMap<uint64_t, ConstantInt> IntConstants;
281 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
282 ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
283 if (!Result) // If no preexisting value, create one now...
284 IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
288 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
289 ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
290 if (!Result) // If no preexisting value, create one now...
291 IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
295 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
296 assert(V <= 127 && "Can only be used with very small positive constants!");
297 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
298 return ConstantUInt::get(Ty, V);
301 //---- ConstantFP::get() implementation...
303 static ValueMap<double, ConstantFP> FPConstants;
305 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
306 ConstantFP *Result = FPConstants.get(Ty, V);
307 if (!Result) // If no preexisting value, create one now...
308 FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
312 //---- ConstantArray::get() implementation...
314 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
316 ConstantArray *ConstantArray::get(const ArrayType *Ty,
317 const std::vector<Constant*> &V) {
318 ConstantArray *Result = ArrayConstants.get(Ty, V);
319 if (!Result) // If no preexisting value, create one now...
320 ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
324 // ConstantArray::get(const string&) - Return an array that is initialized to
325 // contain the specified string. A null terminator is added to the specified
326 // string so that it may be used in a natural way...
328 ConstantArray *ConstantArray::get(const std::string &Str) {
329 std::vector<Constant*> ElementVals;
331 for (unsigned i = 0; i < Str.length(); ++i)
332 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
334 // Add a null terminator to the string...
335 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
337 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
338 return ConstantArray::get(ATy, ElementVals);
342 // destroyConstant - Remove the constant from the constant table...
344 void ConstantArray::destroyConstant() {
345 ArrayConstants.remove(this);
346 destroyConstantImpl();
349 //---- ConstantStruct::get() implementation...
351 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
353 ConstantStruct *ConstantStruct::get(const StructType *Ty,
354 const std::vector<Constant*> &V) {
355 ConstantStruct *Result = StructConstants.get(Ty, V);
356 if (!Result) // If no preexisting value, create one now...
357 StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
361 // destroyConstant - Remove the constant from the constant table...
363 void ConstantStruct::destroyConstant() {
364 StructConstants.remove(this);
365 destroyConstantImpl();
368 //---- ConstantPointerNull::get() implementation...
370 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
372 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
373 ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
374 if (!Result) // If no preexisting value, create one now...
375 NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
379 //---- ConstantPointerRef::get() implementation...
381 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
382 assert(GV->getParent() && "Global Value must be attached to a module!");
384 // The Module handles the pointer reference sharing...
385 return GV->getParent()->getConstantPointerRef(GV);
388 //---- ConstantExpr::get() implementations...
389 // Return NULL on invalid expressions.
391 typedef pair<unsigned, vector<Constant*> > ExprMapKeyType;
392 static ValueMap<const ExprMapKeyType, ConstantExpr> ExprConstants;
394 ConstantExpr *ConstantExpr::get(unsigned Opcode, Constant *C, const Type *Ty) {
396 // Look up the constant in the table first to ensure uniqueness
397 vector<Constant*> argVec(1, C);
398 const ExprMapKeyType &Key = make_pair(Opcode, argVec);
399 ConstantExpr *Result = ExprConstants.get(Ty, Key);
400 if (Result) return Result;
402 // Its not in the table so create a new one and put it in the table.
403 // Check the operands for consistency first
404 assert(Opcode == Instruction::Cast ||
405 (Opcode >= Instruction::FirstUnaryOp &&
406 Opcode < Instruction::NumUnaryOps) &&
407 "Invalid opcode in unary ConstantExpr!");
409 // type of operand will not match result for Cast operation
410 assert((Opcode == Instruction::Cast || Ty == C->getType()) &&
411 "Type of operand in unary constant expression should match result");
413 Result = new ConstantExpr(Opcode, C, Ty);
414 ExprConstants.add(Ty, Key, Result);
418 ConstantExpr *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
421 // Look up the constant in the table first to ensure uniqueness
422 vector<Constant*> argVec(1, C1); argVec.push_back(C2);
423 const ExprMapKeyType &Key = make_pair(Opcode, argVec);
424 ConstantExpr *Result = ExprConstants.get(Ty, Key);
425 if (Result) return Result;
427 // Its not in the table so create a new one and put it in the table.
428 // Check the operands for consistency first
429 assert((Opcode >= Instruction::FirstBinaryOp &&
430 Opcode < Instruction::NumBinaryOps) &&
431 "Invalid opcode in binary constant expression");
433 assert(Ty == C1->getType() && Ty == C2->getType() &&
434 "Operand types in binary constant expression should match result");
436 Result = new ConstantExpr(Opcode, C1, C2, Ty);
437 ExprConstants.add(Ty, Key, Result);
441 ConstantExpr *ConstantExpr::get(unsigned Opcode, Constant *C,
442 const std::vector<Constant*> &IdxList,
445 // Look up the constant in the table first to ensure uniqueness
446 vector<Constant*> argVec(1, C);
447 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
449 const ExprMapKeyType &Key = make_pair(Opcode, argVec);
450 ConstantExpr *Result = ExprConstants.get(Ty, Key);
451 if (Result) return Result;
453 // Its not in the table so create a new one and put it in the table.
454 // Check the operands for consistency first
455 // Must be a getElementPtr. Check for valid getElementPtr expression.
457 assert(Opcode == Instruction::GetElementPtr &&
458 "Operator other than GetElementPtr used with an index list");
460 assert(isa<PointerType>(Ty) &&
461 "Non-pointer type for constant GelElementPtr expression");
463 std::vector<Value*> ValIdxList(IdxList.begin(), IdxList.end());
464 const Type *fldType = GetElementPtrInst::getIndexedType(C->getType(),
466 assert(fldType && "Invalid index list for constant GelElementPtr expression");
468 assert(cast<PointerType>(Ty)->getElementType() == fldType &&
469 "Type for constant GelElementPtr expression doesn't match field type");
471 Result = new ConstantExpr(Opcode, C, IdxList, Ty);
472 ExprConstants.add(Ty, Key, Result);
476 // destroyConstant - Remove the constant from the constant table...
478 void ConstantExpr::destroyConstant() {
479 ExprConstants.remove(this);
480 destroyConstantImpl();
483 const char *ConstantExpr::getOpcodeName(unsigned Opcode) {
484 return Instruction::getOpcodeName(Opcode);
488 //---- ConstantPointerRef::mutateReferences() implementation...
490 unsigned ConstantPointerRef::mutateReferences(Value *OldV, Value *NewV) {
491 assert(getValue() == OldV && "Cannot mutate old value if I'm not using it!");
492 GlobalValue *NewGV = cast<GlobalValue>(NewV);
493 getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);
499 //---- ConstantPointerExpr::mutateReferences() implementation...
501 unsigned ConstantExpr::mutateReferences(Value* OldV, Value *NewV) {
502 unsigned NumReplaced = 0;
503 Constant *NewC = cast<Constant>(NewV);
504 for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
505 if (Operands[i] == OldV) {