1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes...
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "llvm/ConstantHandling.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/iMemory.h"
18 #include "llvm/SymbolTable.h"
19 #include "llvm/Module.h"
20 #include "Support/StringExtras.h"
23 ConstantBool *ConstantBool::True = new ConstantBool(true);
24 ConstantBool *ConstantBool::False = new ConstantBool(false);
27 //===----------------------------------------------------------------------===//
29 //===----------------------------------------------------------------------===//
31 // Specialize setName to take care of symbol table majik
32 void Constant::setName(const std::string &Name, SymbolTable *ST) {
33 assert(ST && "Type::setName - Must provide symbol table argument!");
35 if (Name.size()) ST->insert(Name, this);
38 void Constant::destroyConstantImpl() {
39 // When a Constant is destroyed, there may be lingering
40 // references to the constant by other constants in the constant pool. These
41 // constants are implicitly dependent on the module that is being deleted,
42 // but they don't know that. Because we only find out when the CPV is
43 // deleted, we must now notify all of our users (that should only be
44 // Constants) that they are, in fact, invalid now and should be deleted.
46 while (!use_empty()) {
47 Value *V = use_back();
48 #ifndef NDEBUG // Only in -g mode...
49 if (!isa<Constant>(V))
50 std::cerr << "While deleting: " << *this
51 << "\n\nUse still stuck around after Def is destroyed: "
54 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
55 Constant *CPV = cast<Constant>(V);
56 CPV->destroyConstant();
58 // The constant should remove itself from our use list...
59 assert((use_empty() || use_back() != V) && "Constant not removed!");
62 // Value has no outstanding references it is safe to delete it now...
66 // Static constructor to create a '0' constant of arbitrary type...
67 Constant *Constant::getNullValue(const Type *Ty) {
68 switch (Ty->getPrimitiveID()) {
69 case Type::BoolTyID: {
70 static Constant *NullBool = ConstantBool::get(false);
73 case Type::SByteTyID: {
74 static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
77 case Type::UByteTyID: {
78 static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
81 case Type::ShortTyID: {
82 static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
85 case Type::UShortTyID: {
86 static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
90 static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
93 case Type::UIntTyID: {
94 static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
97 case Type::LongTyID: {
98 static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
101 case Type::ULongTyID: {
102 static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
106 case Type::FloatTyID: {
107 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
110 case Type::DoubleTyID: {
111 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
115 case Type::PointerTyID:
116 return ConstantPointerNull::get(cast<PointerType>(Ty));
118 case Type::StructTyID: {
119 const StructType *ST = cast<StructType>(Ty);
120 const StructType::ElementTypes &ETs = ST->getElementTypes();
121 std::vector<Constant*> Elements;
122 Elements.resize(ETs.size());
123 for (unsigned i = 0, e = ETs.size(); i != e; ++i)
124 Elements[i] = Constant::getNullValue(ETs[i]);
125 return ConstantStruct::get(ST, Elements);
127 case Type::ArrayTyID: {
128 const ArrayType *AT = cast<ArrayType>(Ty);
129 Constant *El = Constant::getNullValue(AT->getElementType());
130 unsigned NumElements = AT->getNumElements();
131 return ConstantArray::get(AT, std::vector<Constant*>(NumElements, El));
134 // Function, Type, Label, or Opaque type?
135 assert(0 && "Cannot create a null constant of that type!");
140 // Static constructor to create the maximum constant of an integral type...
141 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
142 switch (Ty->getPrimitiveID()) {
143 case Type::BoolTyID: return ConstantBool::True;
144 case Type::SByteTyID:
145 case Type::ShortTyID:
147 case Type::LongTyID: {
148 // Calculate 011111111111111...
149 unsigned TypeBits = Ty->getPrimitiveSize()*8;
150 int64_t Val = INT64_MAX; // All ones
151 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
152 return ConstantSInt::get(Ty, Val);
155 case Type::UByteTyID:
156 case Type::UShortTyID:
158 case Type::ULongTyID: return getAllOnesValue(Ty);
164 // Static constructor to create the minimum constant for an integral type...
165 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
166 switch (Ty->getPrimitiveID()) {
167 case Type::BoolTyID: return ConstantBool::False;
168 case Type::SByteTyID:
169 case Type::ShortTyID:
171 case Type::LongTyID: {
172 // Calculate 1111111111000000000000
173 unsigned TypeBits = Ty->getPrimitiveSize()*8;
174 int64_t Val = -1; // All ones
175 Val <<= TypeBits-1; // Shift over to the right spot
176 return ConstantSInt::get(Ty, Val);
179 case Type::UByteTyID:
180 case Type::UShortTyID:
182 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
188 // Static constructor to create an integral constant with all bits set
189 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
190 switch (Ty->getPrimitiveID()) {
191 case Type::BoolTyID: return ConstantBool::True;
192 case Type::SByteTyID:
193 case Type::ShortTyID:
195 case Type::LongTyID: return ConstantSInt::get(Ty, -1);
197 case Type::UByteTyID:
198 case Type::UShortTyID:
200 case Type::ULongTyID: {
201 // Calculate ~0 of the right type...
202 unsigned TypeBits = Ty->getPrimitiveSize()*8;
203 uint64_t Val = ~0ULL; // All ones
204 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
205 return ConstantUInt::get(Ty, Val);
211 bool ConstantUInt::isAllOnesValue() const {
212 unsigned TypeBits = getType()->getPrimitiveSize()*8;
213 uint64_t Val = ~0ULL; // All ones
214 Val >>= 64-TypeBits; // Shift out inappropriate bits
215 return getValue() == Val;
219 //===----------------------------------------------------------------------===//
220 // ConstantXXX Classes
221 //===----------------------------------------------------------------------===//
223 //===----------------------------------------------------------------------===//
224 // Normal Constructors
226 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy) {
230 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty) {
234 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
235 assert(Ty->isInteger() && Ty->isSigned() &&
236 "Illegal type for unsigned integer constant!");
237 assert(isValueValidForType(Ty, V) && "Value too large for type!");
240 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
241 assert(Ty->isInteger() && Ty->isUnsigned() &&
242 "Illegal type for unsigned integer constant!");
243 assert(isValueValidForType(Ty, V) && "Value too large for type!");
246 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
247 assert(isValueValidForType(Ty, V) && "Value too large for type!");
251 ConstantArray::ConstantArray(const ArrayType *T,
252 const std::vector<Constant*> &V) : Constant(T) {
253 Operands.reserve(V.size());
254 for (unsigned i = 0, e = V.size(); i != e; ++i) {
255 assert(V[i]->getType() == T->getElementType() ||
257 V[i]->getType()->getPrimitiveID() ==
258 T->getElementType()->getPrimitiveID()));
259 Operands.push_back(Use(V[i], this));
263 ConstantStruct::ConstantStruct(const StructType *T,
264 const std::vector<Constant*> &V) : Constant(T) {
265 const StructType::ElementTypes &ETypes = T->getElementTypes();
266 assert(V.size() == ETypes.size() &&
267 "Invalid initializer vector for constant structure");
268 Operands.reserve(V.size());
269 for (unsigned i = 0, e = V.size(); i != e; ++i) {
270 assert((V[i]->getType() == ETypes[i] ||
271 ((ETypes[i]->isAbstract() || V[i]->getType()->isAbstract()) &&
272 ETypes[i]->getPrimitiveID()==V[i]->getType()->getPrimitiveID())) &&
273 "Initializer for struct element doesn't match struct element type!");
274 Operands.push_back(Use(V[i], this));
278 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
279 : ConstantPointer(GV->getType()) {
280 Operands.push_back(Use(GV, this));
283 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
284 : Constant(Ty), iType(Opcode) {
285 Operands.push_back(Use(C, this));
288 static bool isSetCC(unsigned Opcode) {
289 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
290 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
291 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
294 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
295 : Constant(isSetCC(Opcode) ? Type::BoolTy : C1->getType()), iType(Opcode) {
296 Operands.push_back(Use(C1, this));
297 Operands.push_back(Use(C2, this));
300 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
302 : Constant(DestTy), iType(Instruction::GetElementPtr) {
303 Operands.reserve(1+IdxList.size());
304 Operands.push_back(Use(C, this));
305 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
306 Operands.push_back(Use(IdxList[i], this));
311 //===----------------------------------------------------------------------===//
312 // classof implementations
314 bool ConstantIntegral::classof(const Constant *CPV) {
315 return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
318 bool ConstantInt::classof(const Constant *CPV) {
319 return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
321 bool ConstantSInt::classof(const Constant *CPV) {
322 return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
324 bool ConstantUInt::classof(const Constant *CPV) {
325 return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
327 bool ConstantFP::classof(const Constant *CPV) {
328 const Type *Ty = CPV->getType();
329 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
330 !isa<ConstantExpr>(CPV));
332 bool ConstantArray::classof(const Constant *CPV) {
333 return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
335 bool ConstantStruct::classof(const Constant *CPV) {
336 return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
338 bool ConstantPointer::classof(const Constant *CPV) {
339 return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
344 //===----------------------------------------------------------------------===//
345 // isValueValidForType implementations
347 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
348 switch (Ty->getPrimitiveID()) {
350 return false; // These can't be represented as integers!!!
353 case Type::SByteTyID:
354 return (Val <= INT8_MAX && Val >= INT8_MIN);
355 case Type::ShortTyID:
356 return (Val <= INT16_MAX && Val >= INT16_MIN);
358 return (Val <= INT32_MAX && Val >= INT32_MIN);
360 return true; // This is the largest type...
366 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
367 switch (Ty->getPrimitiveID()) {
369 return false; // These can't be represented as integers!!!
372 case Type::UByteTyID:
373 return (Val <= UINT8_MAX);
374 case Type::UShortTyID:
375 return (Val <= UINT16_MAX);
377 return (Val <= UINT32_MAX);
378 case Type::ULongTyID:
379 return true; // This is the largest type...
385 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
386 switch (Ty->getPrimitiveID()) {
388 return false; // These can't be represented as floating point!
390 // TODO: Figure out how to test if a double can be cast to a float!
391 case Type::FloatTyID:
392 case Type::DoubleTyID:
393 return true; // This is the largest type...
397 //===----------------------------------------------------------------------===//
398 // replaceUsesOfWithOnConstant implementations
400 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
401 bool DisableChecking) {
402 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
404 std::vector<Constant*> Values;
405 Values.reserve(getValues().size()); // Build replacement array...
406 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
407 Constant *Val = cast<Constant>(getValues()[i]);
408 if (Val == From) Val = cast<Constant>(To);
409 Values.push_back(Val);
412 ConstantArray *Replacement = ConstantArray::get(getType(), Values);
413 assert(Replacement != this && "I didn't contain From!");
415 // Everyone using this now uses the replacement...
417 uncheckedReplaceAllUsesWith(Replacement);
419 replaceAllUsesWith(Replacement);
421 // Delete the old constant!
425 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
426 bool DisableChecking) {
427 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
429 std::vector<Constant*> Values;
430 Values.reserve(getValues().size());
431 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
432 Constant *Val = cast<Constant>(getValues()[i]);
433 if (Val == From) Val = cast<Constant>(To);
434 Values.push_back(Val);
437 ConstantStruct *Replacement = ConstantStruct::get(getType(), Values);
438 assert(Replacement != this && "I didn't contain From!");
440 // Everyone using this now uses the replacement...
442 uncheckedReplaceAllUsesWith(Replacement);
444 replaceAllUsesWith(Replacement);
446 // Delete the old constant!
450 void ConstantPointerRef::replaceUsesOfWithOnConstant(Value *From, Value *To,
451 bool DisableChecking) {
452 if (isa<GlobalValue>(To)) {
453 assert(From == getOperand(0) && "Doesn't contain from!");
454 ConstantPointerRef *Replacement =
455 ConstantPointerRef::get(cast<GlobalValue>(To));
457 // Everyone using this now uses the replacement...
459 uncheckedReplaceAllUsesWith(Replacement);
461 replaceAllUsesWith(Replacement);
464 // Just replace ourselves with the To value specified.
466 uncheckedReplaceAllUsesWith(To);
468 replaceAllUsesWith(To);
471 // Delete the old constant!
475 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
476 bool DisableChecking) {
477 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
478 Constant *To = cast<Constant>(ToV);
480 Constant *Replacement = 0;
481 if (getOpcode() == Instruction::GetElementPtr) {
482 std::vector<Constant*> Indices;
483 Constant *Pointer = getOperand(0);
484 Indices.reserve(getNumOperands()-1);
485 if (Pointer == From) Pointer = To;
487 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
488 Constant *Val = getOperand(i);
489 if (Val == From) Val = To;
490 Indices.push_back(Val);
492 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
493 } else if (getOpcode() == Instruction::Cast) {
494 assert(getOperand(0) == From && "Cast only has one use!");
495 Replacement = ConstantExpr::getCast(To, getType());
496 } else if (getOpcode() == Instruction::Shl ||
497 getOpcode() == Instruction::Shr) {
498 Constant *C1 = getOperand(0);
499 Constant *C2 = getOperand(1);
500 if (C1 == From) C1 = To;
501 if (C2 == From) C2 = To;
502 Replacement = ConstantExpr::getShift(getOpcode(), C1, C2);
503 } else if (getNumOperands() == 2) {
504 Constant *C1 = getOperand(0);
505 Constant *C2 = getOperand(1);
506 if (C1 == From) C1 = To;
507 if (C2 == From) C2 = To;
508 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
510 assert(0 && "Unknown ConstantExpr type!");
514 assert(Replacement != this && "I didn't contain From!");
516 // Everyone using this now uses the replacement...
518 uncheckedReplaceAllUsesWith(Replacement);
520 replaceAllUsesWith(Replacement);
522 // Delete the old constant!
526 //===----------------------------------------------------------------------===//
527 // Factory Function Implementation
529 // ConstantCreator - A class that is used to create constants by
530 // ValueMap*. This class should be partially specialized if there is
531 // something strange that needs to be done to interface to the ctor for the
534 template<class ConstantClass, class TypeClass, class ValType>
535 struct ConstantCreator {
536 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
537 return new ConstantClass(Ty, V);
541 template<class ConstantClass, class TypeClass>
542 struct ConvertConstantType {
543 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
544 assert(0 && "This type cannot be converted!\n");
550 template<class ValType, class TypeClass, class ConstantClass>
551 class ValueMap : public AbstractTypeUser {
552 typedef std::pair<const TypeClass*, ValType> MapKey;
553 typedef std::map<MapKey, ConstantClass *> MapTy;
554 typedef typename MapTy::iterator MapIterator;
557 typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
558 AbstractTypeMapTy AbstractTypeMap;
560 // getOrCreate - Return the specified constant from the map, creating it if
562 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
563 MapKey Lookup(Ty, V);
564 MapIterator I = Map.lower_bound(Lookup);
565 if (I != Map.end() && I->first == Lookup)
566 return I->second; // Is it in the map?
568 // If no preexisting value, create one now...
569 ConstantClass *Result =
570 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
573 /// FIXME: why does this assert fail when loading 176.gcc?
574 //assert(Result->getType() == Ty && "Type specified is not correct!");
575 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
577 // If the type of the constant is abstract, make sure that an entry exists
578 // for it in the AbstractTypeMap.
579 if (Ty->isAbstract()) {
580 typename AbstractTypeMapTy::iterator TI =
581 AbstractTypeMap.lower_bound(Ty);
583 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
584 // Add ourselves to the ATU list of the type.
585 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
587 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
593 void remove(ConstantClass *CP) {
594 // FIXME: This should not use a linear scan. If this gets to be a
595 // performance problem, someone should look at this.
596 MapIterator I = Map.begin();
597 for (MapIterator E = Map.end(); I != E && I->second != CP; ++I)
600 assert(I != Map.end() && "Constant not found in constant table!");
602 // Now that we found the entry, make sure this isn't the entry that
603 // the AbstractTypeMap points to.
604 const TypeClass *Ty = I->first.first;
605 if (Ty->isAbstract()) {
606 assert(AbstractTypeMap.count(Ty) &&
607 "Abstract type not in AbstractTypeMap?");
608 MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
609 if (ATMEntryIt == I) {
610 // Yes, we are removing the representative entry for this type.
611 // See if there are any other entries of the same type.
612 MapIterator TmpIt = ATMEntryIt;
614 // First check the entry before this one...
615 if (TmpIt != Map.begin()) {
617 if (TmpIt->first.first != Ty) // Not the same type, move back...
621 // If we didn't find the same type, try to move forward...
622 if (TmpIt == ATMEntryIt) {
624 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
625 --TmpIt; // No entry afterwards with the same type
628 // If there is another entry in the map of the same abstract type,
629 // update the AbstractTypeMap entry now.
630 if (TmpIt != ATMEntryIt) {
633 // Otherwise, we are removing the last instance of this type
634 // from the table. Remove from the ATM, and from user list.
635 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
636 AbstractTypeMap.erase(Ty);
644 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
645 typename AbstractTypeMapTy::iterator I =
646 AbstractTypeMap.find(cast<TypeClass>(OldTy));
648 assert(I != AbstractTypeMap.end() &&
649 "Abstract type not in AbstractTypeMap?");
651 // Convert a constant at a time until the last one is gone. The last one
652 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
653 // eliminated eventually.
655 ConvertConstantType<ConstantClass,
656 TypeClass>::convert(I->second->second,
657 cast<TypeClass>(NewTy));
659 I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
660 } while (I != AbstractTypeMap.end());
663 // If the type became concrete without being refined to any other existing
664 // type, we just remove ourselves from the ATU list.
665 void typeBecameConcrete(const DerivedType *AbsTy) {
666 AbsTy->removeAbstractTypeUser(this);
670 std::cerr << "Constant.cpp: ValueMap\n";
677 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
679 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
680 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
682 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
683 return SIntConstants.getOrCreate(Ty, V);
686 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
687 return UIntConstants.getOrCreate(Ty, V);
690 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
691 assert(V <= 127 && "Can only be used with very small positive constants!");
692 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
693 return ConstantUInt::get(Ty, V);
696 //---- ConstantFP::get() implementation...
698 static ValueMap<double, Type, ConstantFP> FPConstants;
700 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
701 return FPConstants.getOrCreate(Ty, V);
704 //---- ConstantArray::get() implementation...
708 struct ConvertConstantType<ConstantArray, ArrayType> {
709 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
710 // Make everyone now use a constant of the new type...
711 std::vector<Constant*> C;
712 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
713 C.push_back(cast<Constant>(OldC->getOperand(i)));
714 Constant *New = ConstantArray::get(NewTy, C);
715 assert(New != OldC && "Didn't replace constant??");
716 OldC->uncheckedReplaceAllUsesWith(New);
717 OldC->destroyConstant(); // This constant is now dead, destroy it.
722 static ValueMap<std::vector<Constant*>, ArrayType,
723 ConstantArray> ArrayConstants;
725 ConstantArray *ConstantArray::get(const ArrayType *Ty,
726 const std::vector<Constant*> &V) {
727 return ArrayConstants.getOrCreate(Ty, V);
730 // destroyConstant - Remove the constant from the constant table...
732 void ConstantArray::destroyConstant() {
733 ArrayConstants.remove(this);
734 destroyConstantImpl();
737 // ConstantArray::get(const string&) - Return an array that is initialized to
738 // contain the specified string. A null terminator is added to the specified
739 // string so that it may be used in a natural way...
741 ConstantArray *ConstantArray::get(const std::string &Str) {
742 std::vector<Constant*> ElementVals;
744 for (unsigned i = 0; i < Str.length(); ++i)
745 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
747 // Add a null terminator to the string...
748 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
750 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
751 return ConstantArray::get(ATy, ElementVals);
754 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
755 // then this method converts the array to an std::string and returns it.
756 // Otherwise, it asserts out.
758 std::string ConstantArray::getAsString() const {
759 assert((getType()->getElementType() == Type::UByteTy ||
760 getType()->getElementType() == Type::SByteTy) && "Not a string!");
763 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
764 Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
769 //---- ConstantStruct::get() implementation...
773 struct ConvertConstantType<ConstantStruct, StructType> {
774 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
775 // Make everyone now use a constant of the new type...
776 std::vector<Constant*> C;
777 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
778 C.push_back(cast<Constant>(OldC->getOperand(i)));
779 Constant *New = ConstantStruct::get(NewTy, C);
780 assert(New != OldC && "Didn't replace constant??");
782 OldC->uncheckedReplaceAllUsesWith(New);
783 OldC->destroyConstant(); // This constant is now dead, destroy it.
787 static ValueMap<std::vector<Constant*>, StructType,
788 ConstantStruct> StructConstants;
790 ConstantStruct *ConstantStruct::get(const StructType *Ty,
791 const std::vector<Constant*> &V) {
792 return StructConstants.getOrCreate(Ty, V);
795 // destroyConstant - Remove the constant from the constant table...
797 void ConstantStruct::destroyConstant() {
798 StructConstants.remove(this);
799 destroyConstantImpl();
802 //---- ConstantPointerNull::get() implementation...
805 // ConstantPointerNull does not take extra "value" argument...
806 template<class ValType>
807 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
808 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
809 return new ConstantPointerNull(Ty);
814 struct ConvertConstantType<ConstantPointerNull, PointerType> {
815 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
816 // Make everyone now use a constant of the new type...
817 Constant *New = ConstantPointerNull::get(NewTy);
818 assert(New != OldC && "Didn't replace constant??");
819 OldC->uncheckedReplaceAllUsesWith(New);
820 OldC->destroyConstant(); // This constant is now dead, destroy it.
824 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
826 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
827 return NullPtrConstants.getOrCreate(Ty, 0);
830 // destroyConstant - Remove the constant from the constant table...
832 void ConstantPointerNull::destroyConstant() {
833 NullPtrConstants.remove(this);
834 destroyConstantImpl();
838 //---- ConstantPointerRef::get() implementation...
840 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
841 assert(GV->getParent() && "Global Value must be attached to a module!");
843 // The Module handles the pointer reference sharing...
844 return GV->getParent()->getConstantPointerRef(GV);
847 // destroyConstant - Remove the constant from the constant table...
849 void ConstantPointerRef::destroyConstant() {
850 getValue()->getParent()->destroyConstantPointerRef(this);
851 destroyConstantImpl();
855 //---- ConstantExpr::get() implementations...
857 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
860 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
861 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
862 if (V.first == Instruction::Cast)
863 return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
864 if ((V.first >= Instruction::BinaryOpsBegin &&
865 V.first < Instruction::BinaryOpsEnd) ||
866 V.first == Instruction::Shl || V.first == Instruction::Shr)
867 return new ConstantExpr(V.first, V.second[0], V.second[1]);
869 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
871 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
872 return new ConstantExpr(V.second[0], IdxList, Ty);
877 struct ConvertConstantType<ConstantExpr, Type> {
878 static void convert(ConstantExpr *OldC, const Type *NewTy) {
880 switch (OldC->getOpcode()) {
881 case Instruction::Cast:
882 New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
884 case Instruction::Shl:
885 case Instruction::Shr:
886 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
887 OldC->getOperand(0), OldC->getOperand(1));
890 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
891 OldC->getOpcode() < Instruction::BinaryOpsEnd);
892 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
893 OldC->getOperand(1));
895 case Instruction::GetElementPtr:
896 // Make everyone now use a constant of the new type...
897 std::vector<Constant*> C;
898 for (unsigned i = 1, e = OldC->getNumOperands(); i != e; ++i)
899 C.push_back(cast<Constant>(OldC->getOperand(i)));
900 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), C);
904 assert(New != OldC && "Didn't replace constant??");
905 OldC->uncheckedReplaceAllUsesWith(New);
906 OldC->destroyConstant(); // This constant is now dead, destroy it.
911 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
913 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
914 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
916 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
917 return FC; // Fold a few common cases...
919 // Look up the constant in the table first to ensure uniqueness
920 std::vector<Constant*> argVec(1, C);
921 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
922 return ExprConstants.getOrCreate(Ty, Key);
925 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
926 Constant *C1, Constant *C2) {
927 // Check the operands for consistency first
928 assert((Opcode >= Instruction::BinaryOpsBegin &&
929 Opcode < Instruction::BinaryOpsEnd) &&
930 "Invalid opcode in binary constant expression");
931 assert(C1->getType() == C2->getType() &&
932 "Operand types in binary constant expression should match");
934 if (ReqTy == C1->getType())
935 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
936 return FC; // Fold a few common cases...
938 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
939 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
940 return ExprConstants.getOrCreate(ReqTy, Key);
943 /// getShift - Return a shift left or shift right constant expr
944 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
945 Constant *C1, Constant *C2) {
946 // Check the operands for consistency first
947 assert((Opcode == Instruction::Shl ||
948 Opcode == Instruction::Shr) &&
949 "Invalid opcode in binary constant expression");
950 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
951 "Invalid operand types for Shift constant expr!");
953 if (Constant *FC = ConstantFoldShiftInstruction(Opcode, C1, C2))
954 return FC; // Fold a few common cases...
956 // Look up the constant in the table first to ensure uniqueness
957 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
958 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
959 return ExprConstants.getOrCreate(ReqTy, Key);
963 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
964 const std::vector<Constant*> &IdxList) {
965 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
966 return FC; // Fold a few common cases...
967 assert(isa<PointerType>(C->getType()) &&
968 "Non-pointer type for constant GetElementPtr expression");
970 // Look up the constant in the table first to ensure uniqueness
971 std::vector<Constant*> argVec(1, C);
972 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
973 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,argVec);
974 return ExprConstants.getOrCreate(ReqTy, Key);
977 Constant *ConstantExpr::getGetElementPtr(Constant *C,
978 const std::vector<Constant*> &IdxList){
979 // Get the result type of the getelementptr!
980 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
982 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
984 assert(Ty && "GEP indices invalid!");
986 if (C->isNullValue()) {
988 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
989 if (!IdxList[i]->isNullValue()) {
993 if (isNull) return ConstantPointerNull::get(PointerType::get(Ty));
996 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1000 // destroyConstant - Remove the constant from the constant table...
1002 void ConstantExpr::destroyConstant() {
1003 ExprConstants.remove(this);
1004 destroyConstantImpl();
1007 const char *ConstantExpr::getOpcodeName() const {
1008 return Instruction::getOpcodeName(getOpcode());
1011 unsigned Constant::mutateReferences(Value *OldV, Value *NewV) {
1012 // Uses of constant pointer refs are global values, not constants!
1013 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
1014 GlobalValue *NewGV = cast<GlobalValue>(NewV);
1015 GlobalValue *OldGV = CPR->getValue();
1017 assert(OldGV == OldV && "Cannot mutate old value if I'm not using it!");
1018 Operands[0] = NewGV;
1019 OldGV->getParent()->mutateConstantPointerRef(OldGV, NewGV);
1022 Constant *NewC = cast<Constant>(NewV);
1023 unsigned NumReplaced = 0;
1024 for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
1025 if (Operands[i] == OldV) {