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"
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 // Static constructor to create a '0' constant of arbitrary type...
37 Constant *Constant::getNullValue(const Type *Ty) {
38 switch (Ty->getPrimitiveID()) {
39 case Type::BoolTyID: return ConstantBool::get(false);
43 case Type::LongTyID: return ConstantSInt::get(Ty, 0);
46 case Type::UShortTyID:
48 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
51 case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
53 case Type::PointerTyID:
54 return ConstantPointerNull::get(cast<PointerType>(Ty));
60 void Constant::destroyConstantImpl() {
61 // When a Constant is destroyed, there may be lingering
62 // references to the constant by other constants in the constant pool. These
63 // constants are implicitly dependant on the module that is being deleted,
64 // but they don't know that. Because we only find out when the CPV is
65 // deleted, we must now notify all of our users (that should only be
66 // Constants) that they are, in fact, invalid now and should be deleted.
68 while (!use_empty()) {
69 Value *V = use_back();
70 #ifndef NDEBUG // Only in -g mode...
71 if (!isa<Constant>(V)) {
72 std::cerr << "While deleting: ";
74 std::cerr << "\nUse still stuck around after Def is destroyed: ";
79 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
80 Constant *CPV = cast<Constant>(V);
81 CPV->destroyConstant();
83 // The constant should remove itself from our use list...
84 assert((use_empty() || use_back() != V) && "Constant not removed!");
87 // Value has no outstanding references it is safe to delete it now...
91 //===----------------------------------------------------------------------===//
92 // ConstantXXX Classes
93 //===----------------------------------------------------------------------===//
95 //===----------------------------------------------------------------------===//
96 // Normal Constructors
98 ConstantBool::ConstantBool(bool V) : Constant(Type::BoolTy) {
102 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : Constant(Ty) {
106 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
107 assert(isValueValidForType(Ty, V) && "Value too large for type!");
110 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
111 assert(isValueValidForType(Ty, V) && "Value too large for type!");
114 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
115 assert(isValueValidForType(Ty, V) && "Value too large for type!");
119 ConstantArray::ConstantArray(const ArrayType *T,
120 const std::vector<Constant*> &V) : Constant(T) {
121 for (unsigned i = 0; i < V.size(); i++) {
122 assert(V[i]->getType() == T->getElementType());
123 Operands.push_back(Use(V[i], this));
127 ConstantStruct::ConstantStruct(const StructType *T,
128 const std::vector<Constant*> &V) : Constant(T) {
129 const StructType::ElementTypes &ETypes = T->getElementTypes();
130 assert(V.size() == ETypes.size() &&
131 "Invalid initializer vector for constant structure");
132 for (unsigned i = 0; i < V.size(); i++) {
133 assert(V[i]->getType() == ETypes[i]);
134 Operands.push_back(Use(V[i], this));
138 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
139 : ConstantPointer(GV->getType()) {
140 Operands.push_back(Use(GV, this));
143 ConstantExpr::ConstantExpr(unsigned opCode, Constant *C, const Type *Ty)
144 : Constant(Ty), iType(opCode) {
145 Operands.push_back(Use(C, this));
148 ConstantExpr::ConstantExpr(unsigned opCode, Constant* C1,
149 Constant* C2, const Type *Ty)
150 : Constant(Ty), iType(opCode) {
151 Operands.push_back(Use(C1, this));
152 Operands.push_back(Use(C2, this));
155 ConstantExpr::ConstantExpr(unsigned opCode, Constant* C,
156 const std::vector<Value*>& IdxList, const Type *Ty)
157 : Constant(Ty), iType(opCode) {
158 Operands.reserve(1+IdxList.size());
159 Operands.push_back(Use(C, this));
160 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
161 Operands.push_back(Use(IdxList[i], this));
166 //===----------------------------------------------------------------------===//
167 // classof implementations
169 bool ConstantInt::classof(const Constant *CPV) {
170 return CPV->getType()->isIntegral() && ! isa<ConstantExpr>(CPV);
172 bool ConstantSInt::classof(const Constant *CPV) {
173 return CPV->getType()->isSigned() && ! isa<ConstantExpr>(CPV);
175 bool ConstantUInt::classof(const Constant *CPV) {
176 return CPV->getType()->isUnsigned() && ! isa<ConstantExpr>(CPV);
178 bool ConstantFP::classof(const Constant *CPV) {
179 const Type *Ty = CPV->getType();
180 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
181 ! isa<ConstantExpr>(CPV));
183 bool ConstantArray::classof(const Constant *CPV) {
184 return isa<ArrayType>(CPV->getType()) && ! isa<ConstantExpr>(CPV);
186 bool ConstantStruct::classof(const Constant *CPV) {
187 return isa<StructType>(CPV->getType()) && ! isa<ConstantExpr>(CPV);
189 bool ConstantPointer::classof(const Constant *CPV) {
190 return (isa<PointerType>(CPV->getType()) && ! isa<ConstantExpr>(CPV));
195 //===----------------------------------------------------------------------===//
196 // isValueValidForType implementations
198 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
199 switch (Ty->getPrimitiveID()) {
201 return false; // These can't be represented as integers!!!
204 case Type::SByteTyID:
205 return (Val <= INT8_MAX && Val >= INT8_MIN);
206 case Type::ShortTyID:
207 return (Val <= INT16_MAX && Val >= INT16_MIN);
209 return (Val <= INT32_MAX && Val >= INT32_MIN);
211 return true; // This is the largest type...
217 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
218 switch (Ty->getPrimitiveID()) {
220 return false; // These can't be represented as integers!!!
223 case Type::UByteTyID:
224 return (Val <= UINT8_MAX);
225 case Type::UShortTyID:
226 return (Val <= UINT16_MAX);
228 return (Val <= UINT32_MAX);
229 case Type::ULongTyID:
230 return true; // This is the largest type...
236 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
237 switch (Ty->getPrimitiveID()) {
239 return false; // These can't be represented as floating point!
241 // TODO: Figure out how to test if a double can be cast to a float!
242 case Type::FloatTyID:
244 return (Val <= UINT8_MAX);
246 case Type::DoubleTyID:
247 return true; // This is the largest type...
251 //===----------------------------------------------------------------------===//
252 // Factory Function Implementation
254 template<class ValType, class ConstantClass>
256 typedef pair<const Type*, ValType> ConstHashKey;
257 map<ConstHashKey, ConstantClass *> Map;
259 inline ConstantClass *get(const Type *Ty, ValType V) {
260 map<ConstHashKey,ConstantClass *>::iterator I =
261 Map.find(ConstHashKey(Ty, V));
262 return (I != Map.end()) ? I->second : 0;
265 inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
266 Map.insert(make_pair(ConstHashKey(Ty, V), CP));
269 inline void remove(ConstantClass *CP) {
270 for (map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
271 E = Map.end(); I != E;++I)
272 if (I->second == CP) {
279 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
281 static ValueMap<uint64_t, ConstantInt> IntConstants;
283 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
284 ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
285 if (!Result) // If no preexisting value, create one now...
286 IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
290 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
291 ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
292 if (!Result) // If no preexisting value, create one now...
293 IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
297 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
298 assert(V <= 127 && "Can only be used with very small positive constants!");
299 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
300 return ConstantUInt::get(Ty, V);
303 //---- ConstantFP::get() implementation...
305 static ValueMap<double, ConstantFP> FPConstants;
307 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
308 ConstantFP *Result = FPConstants.get(Ty, V);
309 if (!Result) // If no preexisting value, create one now...
310 FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
314 //---- ConstantArray::get() implementation...
316 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
318 ConstantArray *ConstantArray::get(const ArrayType *Ty,
319 const std::vector<Constant*> &V) {
320 ConstantArray *Result = ArrayConstants.get(Ty, V);
321 if (!Result) // If no preexisting value, create one now...
322 ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
326 // ConstantArray::get(const string&) - Return an array that is initialized to
327 // contain the specified string. A null terminator is added to the specified
328 // string so that it may be used in a natural way...
330 ConstantArray *ConstantArray::get(const std::string &Str) {
331 std::vector<Constant*> ElementVals;
333 for (unsigned i = 0; i < Str.length(); ++i)
334 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
336 // Add a null terminator to the string...
337 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
339 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
340 return ConstantArray::get(ATy, ElementVals);
344 // destroyConstant - Remove the constant from the constant table...
346 void ConstantArray::destroyConstant() {
347 ArrayConstants.remove(this);
348 destroyConstantImpl();
351 //---- ConstantStruct::get() implementation...
353 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
355 ConstantStruct *ConstantStruct::get(const StructType *Ty,
356 const std::vector<Constant*> &V) {
357 ConstantStruct *Result = StructConstants.get(Ty, V);
358 if (!Result) // If no preexisting value, create one now...
359 StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
363 // destroyConstant - Remove the constant from the constant table...
365 void ConstantStruct::destroyConstant() {
366 StructConstants.remove(this);
367 destroyConstantImpl();
370 //---- ConstantPointerNull::get() implementation...
372 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
374 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
375 ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
376 if (!Result) // If no preexisting value, create one now...
377 NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
381 //---- ConstantPointerRef::get() implementation...
383 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
384 assert(GV->getParent() && "Global Value must be attached to a module!");
386 // The Module handles the pointer reference sharing...
387 return GV->getParent()->getConstantPointerRef(GV);
390 //---- ConstantExpr::get() implementations...
391 // Return NULL on invalid expressions.
393 typedef pair<unsigned, vector<Constant*> > ExprMapKeyType;
394 static ValueMap<const ExprMapKeyType, ConstantExpr> ExprConstants;
397 ConstantExpr::get(unsigned opCode, Constant *C, const Type *Ty) {
399 // Look up the constant in the table first to ensure uniqueness
400 vector<Constant*> argVec(1, C);
401 const ExprMapKeyType& key = make_pair(opCode, argVec);
402 ConstantExpr* result = ExprConstants.get(Ty, key);
406 // Its not in the table so create a new one and put it in the table.
407 // Check the operands for consistency first
408 if (opCode != Instruction::Cast &&
409 (opCode < Instruction::FirstUnaryOp ||
410 opCode >= Instruction::NumUnaryOps)) {
411 cerr << "Invalid opcode " << ConstantExpr::getOpcodeName(opCode)
412 << " in unary constant expression" << endl;
413 return NULL; // Not Cast or other unary opcode
415 // type of operand will not match result for Cast operation
416 if (opCode != Instruction::Cast && Ty != C->getType()) {
417 cerr << "Type of operand in unary constant expression should match result" << endl;
421 result = new ConstantExpr(opCode, C, Ty);
422 ExprConstants.add(Ty, key, result);
427 ConstantExpr::get(unsigned opCode, Constant *C1, Constant *C2,const Type *Ty) {
429 // Look up the constant in the table first to ensure uniqueness
430 vector<Constant*> argVec(1, C1); argVec.push_back(C2);
431 const ExprMapKeyType& key = make_pair(opCode, argVec);
432 ConstantExpr* result = ExprConstants.get(Ty, key);
436 // Its not in the table so create a new one and put it in the table.
437 // Check the operands for consistency first
438 if (opCode < Instruction::FirstBinaryOp ||
439 opCode >= Instruction::NumBinaryOps) {
440 cerr << "Invalid opcode " << ConstantExpr::getOpcodeName(opCode)
441 << " in binary constant expression" << endl;
444 if (Ty != C1->getType() || Ty != C2->getType()) {
445 cerr << "Types of both operands in binary constant expression should match result" << endl;
449 result = new ConstantExpr(opCode, C1, C2, Ty);
450 ExprConstants.add(Ty, key, result);
455 ConstantExpr::get(unsigned opCode, Constant*C,
456 const std::vector<Value*>& idxList, const Type *Ty) {
458 // Look up the constant in the table first to ensure uniqueness
459 vector<Constant*> argVec(1, C);
460 for(vector<Value*>::const_iterator VI=idxList.begin(), VE=idxList.end();
462 if (Constant *C = dyn_cast<Constant>(*VI))
465 cerr << "Non-constant index in constant GetElementPtr expr";
469 const ExprMapKeyType& key = make_pair(opCode, argVec);
470 ConstantExpr* result = ExprConstants.get(Ty, key);
474 // Its not in the table so create a new one and put it in the table.
475 // Check the operands for consistency first
476 // Must be a getElementPtr. Check for valid getElementPtr expression.
478 if (opCode != Instruction::GetElementPtr) {
479 cerr << "operator other than GetElementPtr used with an index list" << endl;
482 if (!isa<ConstantPointer>(C)) {
483 cerr << "Constant GelElementPtr expression using something other than a constant pointer" << endl;
486 if (!isa<PointerType>(Ty)) {
487 cerr << "Non-pointer type for constant GelElementPtr expression" << endl;
490 const Type* fldType = GetElementPtrInst::getIndexedType(C->getType(),
493 cerr << "Invalid index list for constant GelElementPtr expression" << endl;
496 if (cast<PointerType>(Ty)->getElementType() != fldType) {
497 cerr << "Type for constant GelElementPtr expression does not match field type" << endl;
501 result = new ConstantExpr(opCode, C, idxList, Ty);
502 ExprConstants.add(Ty, key, result);
506 // destroyConstant - Remove the constant from the constant table...
508 void ConstantExpr::destroyConstant() {
509 ExprConstants.remove(this);
510 destroyConstantImpl();
514 ConstantExpr::getOpcodeName(unsigned opCode) {
515 return Instruction::getOpcodeName(opCode);
519 //---- ConstantPointerRef::mutateReferences() implementation...
522 ConstantPointerRef::mutateReferences(Value* OldV, Value *NewV) {
523 assert(getValue() == OldV && "Cannot mutate old value if I'm not using it!");
524 GlobalValue* NewGV = cast<GlobalValue>(NewV);
525 getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);
531 //---- ConstantPointerExpr::mutateReferences() implementation...
534 ConstantExpr::mutateReferences(Value* OldV, Value *NewV) {
535 unsigned numReplaced = 0;
536 Constant* NewC = cast<Constant>(NewV);
537 for (unsigned i=0, N = getNumOperands(); i < N; ++i)
538 if (Operands[i] == OldV) {