1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // This file implements the Constant* classes...
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Constants.h"
8 #include "llvm/ConstantHandling.h"
9 #include "llvm/DerivedTypes.h"
10 #include "llvm/iMemory.h"
11 #include "llvm/SymbolTable.h"
12 #include "llvm/Module.h"
13 #include "Support/StringExtras.h"
16 ConstantBool *ConstantBool::True = new ConstantBool(true);
17 ConstantBool *ConstantBool::False = new ConstantBool(false);
20 //===----------------------------------------------------------------------===//
22 //===----------------------------------------------------------------------===//
24 // Specialize setName to take care of symbol table majik
25 void Constant::setName(const std::string &Name, SymbolTable *ST) {
26 assert(ST && "Type::setName - Must provide symbol table argument!");
28 if (Name.size()) ST->insert(Name, this);
31 void Constant::destroyConstantImpl() {
32 // When a Constant is destroyed, there may be lingering
33 // references to the constant by other constants in the constant pool. These
34 // constants are implicitly dependant on the module that is being deleted,
35 // but they don't know that. Because we only find out when the CPV is
36 // deleted, we must now notify all of our users (that should only be
37 // Constants) that they are, in fact, invalid now and should be deleted.
39 while (!use_empty()) {
40 Value *V = use_back();
41 #ifndef NDEBUG // Only in -g mode...
42 if (!isa<Constant>(V))
43 std::cerr << "While deleting: " << *this
44 << "\n\nUse still stuck around after Def is destroyed: "
47 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
48 Constant *CPV = cast<Constant>(V);
49 CPV->destroyConstant();
51 // The constant should remove itself from our use list...
52 assert((use_empty() || use_back() != V) && "Constant not removed!");
55 // Value has no outstanding references it is safe to delete it now...
59 // Static constructor to create a '0' constant of arbitrary type...
60 Constant *Constant::getNullValue(const Type *Ty) {
61 switch (Ty->getPrimitiveID()) {
62 case Type::BoolTyID: return ConstantBool::get(false);
66 case Type::LongTyID: return ConstantSInt::get(Ty, 0);
69 case Type::UShortTyID:
71 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
74 case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
76 case Type::PointerTyID:
77 return ConstantPointerNull::get(cast<PointerType>(Ty));
78 case Type::StructTyID: {
79 const StructType *ST = cast<StructType>(Ty);
81 const StructType::ElementTypes &ETs = ST->getElementTypes();
82 std::vector<Constant*> Elements;
83 Elements.resize(ETs.size());
84 for (unsigned i = 0, e = ETs.size(); i != e; ++i)
85 Elements[i] = Constant::getNullValue(ETs[i]);
86 return ConstantStruct::get(ST, Elements);
88 case Type::ArrayTyID: {
89 const ArrayType *AT = cast<ArrayType>(Ty);
90 Constant *El = Constant::getNullValue(AT->getElementType());
91 unsigned NumElements = AT->getNumElements();
92 return ConstantArray::get(AT, std::vector<Constant*>(NumElements, El));
95 // Function, Type, Label, or Opaque type?
96 assert(0 && "Cannot create a null constant of that type!");
101 // Static constructor to create the maximum constant of an integral type...
102 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
103 switch (Ty->getPrimitiveID()) {
104 case Type::BoolTyID: return ConstantBool::True;
105 case Type::SByteTyID:
106 case Type::ShortTyID:
108 case Type::LongTyID: {
109 // Calculate 011111111111111...
110 unsigned TypeBits = Ty->getPrimitiveSize()*8;
111 int64_t Val = INT64_MAX; // All ones
112 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
113 return ConstantSInt::get(Ty, Val);
116 case Type::UByteTyID:
117 case Type::UShortTyID:
119 case Type::ULongTyID: return getAllOnesValue(Ty);
125 // Static constructor to create the minimum constant for an integral type...
126 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
127 switch (Ty->getPrimitiveID()) {
128 case Type::BoolTyID: return ConstantBool::False;
129 case Type::SByteTyID:
130 case Type::ShortTyID:
132 case Type::LongTyID: {
133 // Calculate 1111111111000000000000
134 unsigned TypeBits = Ty->getPrimitiveSize()*8;
135 int64_t Val = -1; // All ones
136 Val <<= TypeBits-1; // Shift over to the right spot
137 return ConstantSInt::get(Ty, Val);
140 case Type::UByteTyID:
141 case Type::UShortTyID:
143 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
149 // Static constructor to create an integral constant with all bits set
150 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
151 switch (Ty->getPrimitiveID()) {
152 case Type::BoolTyID: return ConstantBool::True;
153 case Type::SByteTyID:
154 case Type::ShortTyID:
156 case Type::LongTyID: return ConstantSInt::get(Ty, -1);
158 case Type::UByteTyID:
159 case Type::UShortTyID:
161 case Type::ULongTyID: {
162 // Calculate ~0 of the right type...
163 unsigned TypeBits = Ty->getPrimitiveSize()*8;
164 uint64_t Val = ~0ULL; // All ones
165 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
166 return ConstantUInt::get(Ty, Val);
172 bool ConstantUInt::isAllOnesValue() const {
173 unsigned TypeBits = getType()->getPrimitiveSize()*8;
174 uint64_t Val = ~0ULL; // All ones
175 Val >>= 64-TypeBits; // Shift out inappropriate bits
176 return getValue() == Val;
180 //===----------------------------------------------------------------------===//
181 // ConstantXXX Classes
182 //===----------------------------------------------------------------------===//
184 //===----------------------------------------------------------------------===//
185 // Normal Constructors
187 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy) {
191 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty) {
195 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
196 assert(Ty->isInteger() && Ty->isSigned() &&
197 "Illegal type for unsigned integer constant!");
198 assert(isValueValidForType(Ty, V) && "Value too large for type!");
201 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
202 assert(Ty->isInteger() && Ty->isUnsigned() &&
203 "Illegal type for unsigned integer constant!");
204 assert(isValueValidForType(Ty, V) && "Value too large for type!");
207 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
208 assert(isValueValidForType(Ty, V) && "Value too large for type!");
212 ConstantArray::ConstantArray(const ArrayType *T,
213 const std::vector<Constant*> &V) : Constant(T) {
214 Operands.reserve(V.size());
215 for (unsigned i = 0, e = V.size(); i != e; ++i) {
216 assert(V[i]->getType() == T->getElementType() ||
218 V[i]->getType()->getPrimitiveID() ==
219 T->getElementType()->getPrimitiveID()));
220 Operands.push_back(Use(V[i], this));
224 ConstantStruct::ConstantStruct(const StructType *T,
225 const std::vector<Constant*> &V) : Constant(T) {
226 const StructType::ElementTypes &ETypes = T->getElementTypes();
227 assert(V.size() == ETypes.size() &&
228 "Invalid initializer vector for constant structure");
229 Operands.reserve(V.size());
230 for (unsigned i = 0, e = V.size(); i != e; ++i) {
231 assert((V[i]->getType() == ETypes[i] ||
232 (ETypes[i]->isAbstract() &&
233 ETypes[i]->getPrimitiveID()==V[i]->getType()->getPrimitiveID())) &&
234 "Initializer for struct element doesn't match struct element type!");
235 Operands.push_back(Use(V[i], this));
239 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
240 : ConstantPointer(GV->getType()) {
241 Operands.push_back(Use(GV, this));
244 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
245 : Constant(Ty), iType(Opcode) {
246 Operands.push_back(Use(C, this));
249 static bool isSetCC(unsigned Opcode) {
250 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
251 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
252 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
255 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
256 : Constant(isSetCC(Opcode) ? Type::BoolTy : C1->getType()), iType(Opcode) {
257 Operands.push_back(Use(C1, this));
258 Operands.push_back(Use(C2, this));
261 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
263 : Constant(DestTy), iType(Instruction::GetElementPtr) {
264 Operands.reserve(1+IdxList.size());
265 Operands.push_back(Use(C, this));
266 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
267 Operands.push_back(Use(IdxList[i], this));
272 //===----------------------------------------------------------------------===//
273 // classof implementations
275 bool ConstantIntegral::classof(const Constant *CPV) {
276 return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
279 bool ConstantInt::classof(const Constant *CPV) {
280 return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
282 bool ConstantSInt::classof(const Constant *CPV) {
283 return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
285 bool ConstantUInt::classof(const Constant *CPV) {
286 return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
288 bool ConstantFP::classof(const Constant *CPV) {
289 const Type *Ty = CPV->getType();
290 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
291 !isa<ConstantExpr>(CPV));
293 bool ConstantArray::classof(const Constant *CPV) {
294 return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
296 bool ConstantStruct::classof(const Constant *CPV) {
297 return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
299 bool ConstantPointer::classof(const Constant *CPV) {
300 return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
305 //===----------------------------------------------------------------------===//
306 // isValueValidForType implementations
308 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
309 switch (Ty->getPrimitiveID()) {
311 return false; // These can't be represented as integers!!!
314 case Type::SByteTyID:
315 return (Val <= INT8_MAX && Val >= INT8_MIN);
316 case Type::ShortTyID:
317 return (Val <= INT16_MAX && Val >= INT16_MIN);
319 return (Val <= INT32_MAX && Val >= INT32_MIN);
321 return true; // This is the largest type...
327 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
328 switch (Ty->getPrimitiveID()) {
330 return false; // These can't be represented as integers!!!
333 case Type::UByteTyID:
334 return (Val <= UINT8_MAX);
335 case Type::UShortTyID:
336 return (Val <= UINT16_MAX);
338 return (Val <= UINT32_MAX);
339 case Type::ULongTyID:
340 return true; // This is the largest type...
346 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
347 switch (Ty->getPrimitiveID()) {
349 return false; // These can't be represented as floating point!
351 // TODO: Figure out how to test if a double can be cast to a float!
352 case Type::FloatTyID:
354 return (Val <= UINT8_MAX);
356 case Type::DoubleTyID:
357 return true; // This is the largest type...
361 //===----------------------------------------------------------------------===//
362 // replaceUsesOfWithOnConstant implementations
364 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To) {
365 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
367 std::vector<Constant*> Values;
368 Values.reserve(getValues().size()); // Build replacement array...
369 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
370 Constant *Val = cast<Constant>(getValues()[i]);
371 if (Val == From) Val = cast<Constant>(To);
372 Values.push_back(Val);
375 ConstantArray *Replacement = ConstantArray::get(getType(), Values);
376 assert(Replacement != this && "I didn't contain From!");
378 // Everyone using this now uses the replacement...
379 replaceAllUsesWith(Replacement);
381 // Delete the old constant!
385 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To) {
386 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
388 std::vector<Constant*> Values;
389 Values.reserve(getValues().size());
390 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
391 Constant *Val = cast<Constant>(getValues()[i]);
392 if (Val == From) Val = cast<Constant>(To);
393 Values.push_back(Val);
396 ConstantStruct *Replacement = ConstantStruct::get(getType(), Values);
397 assert(Replacement != this && "I didn't contain From!");
399 // Everyone using this now uses the replacement...
400 replaceAllUsesWith(Replacement);
402 // Delete the old constant!
406 void ConstantPointerRef::replaceUsesOfWithOnConstant(Value *From, Value *To) {
407 if (isa<GlobalValue>(To)) {
408 assert(From == getOperand(0) && "Doesn't contain from!");
409 ConstantPointerRef *Replacement =
410 ConstantPointerRef::get(cast<GlobalValue>(To));
412 // Everyone using this now uses the replacement...
413 replaceAllUsesWith(Replacement);
415 // Delete the old constant!
418 // Just replace ourselves with the To value specified.
419 replaceAllUsesWith(To);
421 // Delete the old constant!
426 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV) {
427 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
428 Constant *To = cast<Constant>(ToV);
430 Constant *Replacement = 0;
431 if (getOpcode() == Instruction::GetElementPtr) {
432 std::vector<Constant*> Indices;
433 Constant *Pointer = getOperand(0);
434 Indices.reserve(getNumOperands()-1);
435 if (Pointer == From) Pointer = To;
437 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
438 Constant *Val = getOperand(i);
439 if (Val == From) Val = To;
440 Indices.push_back(Val);
442 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
443 } else if (getOpcode() == Instruction::Cast) {
444 assert(getOperand(0) == From && "Cast only has one use!");
445 Replacement = ConstantExpr::getCast(To, getType());
446 } else if (getNumOperands() == 2) {
447 Constant *C1 = getOperand(0);
448 Constant *C2 = getOperand(1);
449 if (C1 == From) C1 = To;
450 if (C2 == From) C2 = To;
451 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
453 assert(0 && "Unknown ConstantExpr type!");
457 assert(Replacement != this && "I didn't contain From!");
459 // Everyone using this now uses the replacement...
460 replaceAllUsesWith(Replacement);
462 // Delete the old constant!
466 //===----------------------------------------------------------------------===//
467 // Factory Function Implementation
469 // ReplaceUsesOfWith - This is exactly the same as Value::replaceAllUsesWith,
470 // except that it doesn't have all of the asserts. The asserts fail because we
471 // are half-way done resolving types, which causes some types to exist as two
472 // different Type*'s at the same time. This is a sledgehammer to work around
475 static void ReplaceUsesOfWith(Value *Old, Value *New) {
476 while (!Old->use_empty()) {
477 User *Use = Old->use_back();
478 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
480 if (Constant *C = dyn_cast<Constant>(Use)) {
481 C->replaceUsesOfWithOnConstant(Old, New);
483 Use->replaceUsesOfWith(Old, New);
489 // ConstantCreator - A class that is used to create constants by
490 // ValueMap*. This class should be partially specialized if there is
491 // something strange that needs to be done to interface to the ctor for the
494 template<class ConstantClass, class TypeClass, class ValType>
495 struct ConstantCreator {
496 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
497 return new ConstantClass(Ty, V);
502 template<class ValType, class TypeClass, class ConstantClass>
505 typedef std::pair<const TypeClass*, ValType> ConstHashKey;
506 std::map<ConstHashKey, ConstantClass *> Map;
508 // getOrCreate - Return the specified constant from the map, creating it if
510 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
511 ConstHashKey Lookup(Ty, V);
512 typename std::map<ConstHashKey,ConstantClass *>::iterator I =
513 Map.lower_bound(Lookup);
514 if (I != Map.end() && I->first == Lookup)
515 return I->second; // Is it in the map?
517 // If no preexisting value, create one now...
518 ConstantClass *Result =
519 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
521 Map.insert(I, std::make_pair(ConstHashKey(Ty, V), Result));
525 void remove(ConstantClass *CP) {
526 // FIXME: This could be sped up a LOT. If this gets to be a performance
527 // problem, someone should look at this.
528 for (typename std::map<ConstHashKey, ConstantClass*>::iterator
529 I = Map.begin(), E = Map.end(); I != E; ++I)
530 if (I->second == CP) {
534 assert(0 && "Constant not found in constant table!");
541 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
543 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
544 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
546 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
547 return SIntConstants.getOrCreate(Ty, V);
550 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
551 return UIntConstants.getOrCreate(Ty, V);
554 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
555 assert(V <= 127 && "Can only be used with very small positive constants!");
556 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
557 return ConstantUInt::get(Ty, V);
560 //---- ConstantFP::get() implementation...
562 static ValueMap<double, Type, ConstantFP> FPConstants;
564 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
565 return FPConstants.getOrCreate(Ty, V);
568 //---- ConstantArray::get() implementation...
570 static ValueMap<std::vector<Constant*>, ArrayType,
571 ConstantArray> ArrayConstants;
573 ConstantArray *ConstantArray::get(const ArrayType *Ty,
574 const std::vector<Constant*> &V) {
575 return ArrayConstants.getOrCreate(Ty, V);
578 // destroyConstant - Remove the constant from the constant table...
580 void ConstantArray::destroyConstant() {
581 ArrayConstants.remove(this);
582 destroyConstantImpl();
585 /// refineAbstractType - If this callback is invoked, then this constant is of a
586 /// derived type, change all users to use a concrete constant of the new type.
588 void ConstantArray::refineAbstractType(const DerivedType *OldTy,
590 Value::refineAbstractType(OldTy, NewTy);
591 if (OldTy == NewTy) return;
593 // Make everyone now use a constant of the new type...
594 std::vector<Constant*> C;
595 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
596 C.push_back(cast<Constant>(getOperand(i)));
597 Constant *New = ConstantArray::get(cast<ArrayType>(NewTy), C);
599 ReplaceUsesOfWith(this, New);
600 destroyConstant(); // This constant is now dead, destroy it.
605 // ConstantArray::get(const string&) - Return an array that is initialized to
606 // contain the specified string. A null terminator is added to the specified
607 // string so that it may be used in a natural way...
609 ConstantArray *ConstantArray::get(const std::string &Str) {
610 std::vector<Constant*> ElementVals;
612 for (unsigned i = 0; i < Str.length(); ++i)
613 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
615 // Add a null terminator to the string...
616 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
618 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
619 return ConstantArray::get(ATy, ElementVals);
622 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
623 // then this method converts the array to an std::string and returns it.
624 // Otherwise, it asserts out.
626 std::string ConstantArray::getAsString() const {
627 assert((getType()->getElementType() == Type::UByteTy ||
628 getType()->getElementType() == Type::SByteTy) && "Not a string!");
631 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
632 Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
637 //---- ConstantStruct::get() implementation...
639 static ValueMap<std::vector<Constant*>, StructType,
640 ConstantStruct> StructConstants;
642 ConstantStruct *ConstantStruct::get(const StructType *Ty,
643 const std::vector<Constant*> &V) {
644 return StructConstants.getOrCreate(Ty, V);
647 // destroyConstant - Remove the constant from the constant table...
649 void ConstantStruct::destroyConstant() {
650 StructConstants.remove(this);
651 destroyConstantImpl();
654 /// refineAbstractType - If this callback is invoked, then this constant is of a
655 /// derived type, change all users to use a concrete constant of the new type.
657 void ConstantStruct::refineAbstractType(const DerivedType *OldTy,
659 Value::refineAbstractType(OldTy, NewTy);
660 if (OldTy == NewTy) return;
662 // Make everyone now use a constant of the new type...
663 std::vector<Constant*> C;
664 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
665 C.push_back(cast<Constant>(getOperand(i)));
666 Constant *New = ConstantStruct::get(cast<StructType>(NewTy), C);
668 ReplaceUsesOfWith(this, New);
669 destroyConstant(); // This constant is now dead, destroy it.
674 //---- ConstantPointerNull::get() implementation...
677 // ConstantPointerNull does not take extra "value" argument...
678 template<class ValType>
679 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
680 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
681 return new ConstantPointerNull(Ty);
685 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
687 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
688 return NullPtrConstants.getOrCreate(Ty, 0);
691 // destroyConstant - Remove the constant from the constant table...
693 void ConstantPointerNull::destroyConstant() {
694 NullPtrConstants.remove(this);
695 destroyConstantImpl();
698 /// refineAbstractType - If this callback is invoked, then this constant is of a
699 /// derived type, change all users to use a concrete constant of the new type.
701 void ConstantPointerNull::refineAbstractType(const DerivedType *OldTy,
703 Value::refineAbstractType(OldTy, NewTy);
704 if (OldTy == NewTy) return;
706 // Make everyone now use a constant of the new type...
707 Constant *New = ConstantPointerNull::get(cast<PointerType>(NewTy));
709 ReplaceUsesOfWith(this, New);
711 // This constant is now dead, destroy it.
718 //---- ConstantPointerRef::get() implementation...
720 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
721 assert(GV->getParent() && "Global Value must be attached to a module!");
723 // The Module handles the pointer reference sharing...
724 return GV->getParent()->getConstantPointerRef(GV);
727 // destroyConstant - Remove the constant from the constant table...
729 void ConstantPointerRef::destroyConstant() {
730 getValue()->getParent()->destroyConstantPointerRef(this);
731 destroyConstantImpl();
735 //---- ConstantExpr::get() implementations...
737 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
740 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
741 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
742 if (V.first == Instruction::Cast)
743 return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
744 if ((V.first >= Instruction::BinaryOpsBegin &&
745 V.first < Instruction::BinaryOpsEnd) ||
746 V.first == Instruction::Shl || V.first == Instruction::Shr)
747 return new ConstantExpr(V.first, V.second[0], V.second[1]);
749 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
751 // Check that the indices list is valid...
752 std::vector<Value*> ValIdxList(V.second.begin()+1, V.second.end());
753 const Type *DestTy = GetElementPtrInst::getIndexedType(Ty, ValIdxList,
755 assert(DestTy && "Invalid index list for GetElementPtr expression");
757 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
758 return new ConstantExpr(V.second[0], IdxList, PointerType::get(DestTy));
762 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
764 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
765 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
766 return FC; // Fold a few common cases...
768 // Look up the constant in the table first to ensure uniqueness
769 std::vector<Constant*> argVec(1, C);
770 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
771 return ExprConstants.getOrCreate(Ty, Key);
774 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
775 // Check the operands for consistency first
776 assert((Opcode >= Instruction::BinaryOpsBegin &&
777 Opcode < Instruction::BinaryOpsEnd) &&
778 "Invalid opcode in binary constant expression");
779 assert(C1->getType() == C2->getType() &&
780 "Operand types in binary constant expression should match");
782 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
783 return FC; // Fold a few common cases...
785 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
786 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
787 return ExprConstants.getOrCreate(C1->getType(), Key);
790 /// getShift - Return a shift left or shift right constant expr
791 Constant *ConstantExpr::getShift(unsigned Opcode, Constant *C1, Constant *C2) {
792 // Check the operands for consistency first
793 assert((Opcode == Instruction::Shl ||
794 Opcode == Instruction::Shr) &&
795 "Invalid opcode in binary constant expression");
796 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
797 "Invalid operand types for Shift constant expr!");
799 if (Constant *FC = ConstantFoldShiftInstruction(Opcode, C1, C2))
800 return FC; // Fold a few common cases...
802 // Look up the constant in the table first to ensure uniqueness
803 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
804 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
805 return ExprConstants.getOrCreate(C1->getType(), Key);
809 Constant *ConstantExpr::getGetElementPtr(Constant *C,
810 const std::vector<Constant*> &IdxList){
811 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
812 return FC; // Fold a few common cases...
813 const Type *Ty = C->getType();
814 assert(isa<PointerType>(Ty) &&
815 "Non-pointer type for constant GetElementPtr expression");
817 // Look up the constant in the table first to ensure uniqueness
818 std::vector<Constant*> argVec(1, C);
819 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
821 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,argVec);
822 return ExprConstants.getOrCreate(Ty, Key);
825 // destroyConstant - Remove the constant from the constant table...
827 void ConstantExpr::destroyConstant() {
828 ExprConstants.remove(this);
829 destroyConstantImpl();
832 /// refineAbstractType - If this callback is invoked, then this constant is of a
833 /// derived type, change all users to use a concrete constant of the new type.
835 void ConstantExpr::refineAbstractType(const DerivedType *OldTy,
837 Value::refineAbstractType(OldTy, NewTy);
838 if (OldTy == NewTy) return;
840 // FIXME: These need to use a lower-level implementation method, because the
841 // ::get methods intuit the type of the result based on the types of the
842 // operands. The operand types may not have had their types resolved yet.
845 if (getOpcode() == Instruction::Cast) {
846 New = getCast(getOperand(0), NewTy);
847 } else if (getOpcode() >= Instruction::BinaryOpsBegin &&
848 getOpcode() < Instruction::BinaryOpsEnd) {
849 New = get(getOpcode(), getOperand(0), getOperand(0));
850 } else if (getOpcode() == Instruction::Shl || getOpcode() ==Instruction::Shr){
851 New = getShift(getOpcode(), getOperand(0), getOperand(0));
853 assert(getOpcode() == Instruction::GetElementPtr);
855 // Make everyone now use a constant of the new type...
856 std::vector<Constant*> C;
857 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
858 C.push_back(cast<Constant>(getOperand(i)));
859 New = ConstantExpr::getGetElementPtr(getOperand(0), C);
862 ReplaceUsesOfWith(this, New);
863 destroyConstant(); // This constant is now dead, destroy it.
870 const char *ConstantExpr::getOpcodeName() const {
871 return Instruction::getOpcodeName(getOpcode());
874 unsigned Constant::mutateReferences(Value *OldV, Value *NewV) {
875 // Uses of constant pointer refs are global values, not constants!
876 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
877 GlobalValue *NewGV = cast<GlobalValue>(NewV);
878 GlobalValue *OldGV = CPR->getValue();
880 assert(OldGV == OldV && "Cannot mutate old value if I'm not using it!");
882 OldGV->getParent()->mutateConstantPointerRef(OldGV, NewGV);
885 Constant *NewC = cast<Constant>(NewV);
886 unsigned NumReplaced = 0;
887 for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
888 if (Operands[i] == OldV) {