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 "ConstantFolding.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"
24 ConstantBool *ConstantBool::True = new ConstantBool(true);
25 ConstantBool *ConstantBool::False = new ConstantBool(false);
28 //===----------------------------------------------------------------------===//
30 //===----------------------------------------------------------------------===//
32 // Specialize setName to take care of symbol table majik
33 void Constant::setName(const std::string &Name, SymbolTable *ST) {
34 assert(ST && "Type::setName - Must provide symbol table argument!");
36 if (Name.size()) ST->insert(Name, this);
39 void Constant::destroyConstantImpl() {
40 // When a Constant is destroyed, there may be lingering
41 // references to the constant by other constants in the constant pool. These
42 // constants are implicitly dependent on the module that is being deleted,
43 // but they don't know that. Because we only find out when the CPV is
44 // deleted, we must now notify all of our users (that should only be
45 // Constants) that they are, in fact, invalid now and should be deleted.
47 while (!use_empty()) {
48 Value *V = use_back();
49 #ifndef NDEBUG // Only in -g mode...
50 if (!isa<Constant>(V))
51 std::cerr << "While deleting: " << *this
52 << "\n\nUse still stuck around after Def is destroyed: "
55 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
56 Constant *CPV = cast<Constant>(V);
57 CPV->destroyConstant();
59 // The constant should remove itself from our use list...
60 assert((use_empty() || use_back() != V) && "Constant not removed!");
63 // Value has no outstanding references it is safe to delete it now...
67 // Static constructor to create a '0' constant of arbitrary type...
68 Constant *Constant::getNullValue(const Type *Ty) {
69 switch (Ty->getPrimitiveID()) {
70 case Type::BoolTyID: {
71 static Constant *NullBool = ConstantBool::get(false);
74 case Type::SByteTyID: {
75 static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
78 case Type::UByteTyID: {
79 static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
82 case Type::ShortTyID: {
83 static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
86 case Type::UShortTyID: {
87 static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
91 static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
94 case Type::UIntTyID: {
95 static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
98 case Type::LongTyID: {
99 static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
102 case Type::ULongTyID: {
103 static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
107 case Type::FloatTyID: {
108 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
111 case Type::DoubleTyID: {
112 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
116 case Type::PointerTyID:
117 return ConstantPointerNull::get(cast<PointerType>(Ty));
119 case Type::StructTyID:
120 case Type::ArrayTyID:
121 return ConstantAggregateZero::get(Ty);
123 // Function, Type, Label, or Opaque type?
124 assert(0 && "Cannot create a null constant of that type!");
129 // Static constructor to create the maximum constant of an integral type...
130 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
131 switch (Ty->getPrimitiveID()) {
132 case Type::BoolTyID: return ConstantBool::True;
133 case Type::SByteTyID:
134 case Type::ShortTyID:
136 case Type::LongTyID: {
137 // Calculate 011111111111111...
138 unsigned TypeBits = Ty->getPrimitiveSize()*8;
139 int64_t Val = INT64_MAX; // All ones
140 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
141 return ConstantSInt::get(Ty, Val);
144 case Type::UByteTyID:
145 case Type::UShortTyID:
147 case Type::ULongTyID: return getAllOnesValue(Ty);
153 // Static constructor to create the minimum constant for an integral type...
154 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
155 switch (Ty->getPrimitiveID()) {
156 case Type::BoolTyID: return ConstantBool::False;
157 case Type::SByteTyID:
158 case Type::ShortTyID:
160 case Type::LongTyID: {
161 // Calculate 1111111111000000000000
162 unsigned TypeBits = Ty->getPrimitiveSize()*8;
163 int64_t Val = -1; // All ones
164 Val <<= TypeBits-1; // Shift over to the right spot
165 return ConstantSInt::get(Ty, Val);
168 case Type::UByteTyID:
169 case Type::UShortTyID:
171 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
177 // Static constructor to create an integral constant with all bits set
178 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
179 switch (Ty->getPrimitiveID()) {
180 case Type::BoolTyID: return ConstantBool::True;
181 case Type::SByteTyID:
182 case Type::ShortTyID:
184 case Type::LongTyID: return ConstantSInt::get(Ty, -1);
186 case Type::UByteTyID:
187 case Type::UShortTyID:
189 case Type::ULongTyID: {
190 // Calculate ~0 of the right type...
191 unsigned TypeBits = Ty->getPrimitiveSize()*8;
192 uint64_t Val = ~0ULL; // All ones
193 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
194 return ConstantUInt::get(Ty, Val);
200 bool ConstantUInt::isAllOnesValue() const {
201 unsigned TypeBits = getType()->getPrimitiveSize()*8;
202 uint64_t Val = ~0ULL; // All ones
203 Val >>= 64-TypeBits; // Shift out inappropriate bits
204 return getValue() == Val;
208 //===----------------------------------------------------------------------===//
209 // ConstantXXX Classes
210 //===----------------------------------------------------------------------===//
212 //===----------------------------------------------------------------------===//
213 // Normal Constructors
215 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy) {
219 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty) {
223 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
224 assert(Ty->isInteger() && Ty->isSigned() &&
225 "Illegal type for unsigned integer constant!");
226 assert(isValueValidForType(Ty, V) && "Value too large for type!");
229 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
230 assert(Ty->isInteger() && Ty->isUnsigned() &&
231 "Illegal type for unsigned integer constant!");
232 assert(isValueValidForType(Ty, V) && "Value too large for type!");
235 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
236 assert(isValueValidForType(Ty, V) && "Value too large for type!");
240 ConstantArray::ConstantArray(const ArrayType *T,
241 const std::vector<Constant*> &V) : Constant(T) {
242 Operands.reserve(V.size());
243 for (unsigned i = 0, e = V.size(); i != e; ++i) {
244 assert(V[i]->getType() == T->getElementType() ||
246 V[i]->getType()->getPrimitiveID() ==
247 T->getElementType()->getPrimitiveID()));
248 Operands.push_back(Use(V[i], this));
252 ConstantStruct::ConstantStruct(const StructType *T,
253 const std::vector<Constant*> &V) : Constant(T) {
254 assert(V.size() == T->getNumElements() &&
255 "Invalid initializer vector for constant structure");
256 Operands.reserve(V.size());
257 for (unsigned i = 0, e = V.size(); i != e; ++i) {
258 assert((V[i]->getType() == T->getElementType(i) ||
259 ((T->getElementType(i)->isAbstract() ||
260 V[i]->getType()->isAbstract()) &&
261 T->getElementType(i)->getPrimitiveID() ==
262 V[i]->getType()->getPrimitiveID())) &&
263 "Initializer for struct element doesn't match struct element type!");
264 Operands.push_back(Use(V[i], this));
268 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
269 : Constant(GV->getType()) {
271 Operands.push_back(Use(GV, this));
274 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
275 : Constant(Ty), iType(Opcode) {
277 Operands.push_back(Use(C, this));
280 // Select instruction creation ctor
281 ConstantExpr::ConstantExpr(Constant *C, Constant *V1, Constant *V2)
282 : Constant(V1->getType()), iType(Instruction::Select) {
284 Operands.push_back(Use(C, this));
285 Operands.push_back(Use(V1, this));
286 Operands.push_back(Use(V2, this));
290 static bool isSetCC(unsigned Opcode) {
291 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
292 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
293 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
296 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
297 : Constant(isSetCC(Opcode) ? Type::BoolTy : C1->getType()), iType(Opcode) {
299 Operands.push_back(Use(C1, this));
300 Operands.push_back(Use(C2, this));
303 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
305 : Constant(DestTy), iType(Instruction::GetElementPtr) {
306 Operands.reserve(1+IdxList.size());
307 Operands.push_back(Use(C, this));
308 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
309 Operands.push_back(Use(IdxList[i], this));
314 //===----------------------------------------------------------------------===//
315 // classof implementations
317 bool ConstantIntegral::classof(const Constant *CPV) {
318 return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
321 bool ConstantInt::classof(const Constant *CPV) {
322 return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
324 bool ConstantSInt::classof(const Constant *CPV) {
325 return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
327 bool ConstantUInt::classof(const Constant *CPV) {
328 return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
330 bool ConstantFP::classof(const Constant *CPV) {
331 const Type *Ty = CPV->getType();
332 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
333 !isa<ConstantExpr>(CPV));
335 bool ConstantAggregateZero::classof(const Constant *CPV) {
336 return (isa<ArrayType>(CPV->getType()) || isa<StructType>(CPV->getType())) &&
339 bool ConstantArray::classof(const Constant *CPV) {
340 return isa<ArrayType>(CPV->getType()) && !CPV->isNullValue();
342 bool ConstantStruct::classof(const Constant *CPV) {
343 return isa<StructType>(CPV->getType()) && !CPV->isNullValue();
346 bool ConstantPointerNull::classof(const Constant *CPV) {
347 return isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV) &&
348 CPV->getNumOperands() == 0;
351 bool ConstantPointerRef::classof(const Constant *CPV) {
352 return isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV) &&
353 CPV->getNumOperands() == 1;
358 //===----------------------------------------------------------------------===//
359 // isValueValidForType implementations
361 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
362 switch (Ty->getPrimitiveID()) {
364 return false; // These can't be represented as integers!!!
367 case Type::SByteTyID:
368 return (Val <= INT8_MAX && Val >= INT8_MIN);
369 case Type::ShortTyID:
370 return (Val <= INT16_MAX && Val >= INT16_MIN);
372 return (Val <= INT32_MAX && Val >= INT32_MIN);
374 return true; // This is the largest type...
380 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
381 switch (Ty->getPrimitiveID()) {
383 return false; // These can't be represented as integers!!!
386 case Type::UByteTyID:
387 return (Val <= UINT8_MAX);
388 case Type::UShortTyID:
389 return (Val <= UINT16_MAX);
391 return (Val <= UINT32_MAX);
392 case Type::ULongTyID:
393 return true; // This is the largest type...
399 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
400 switch (Ty->getPrimitiveID()) {
402 return false; // These can't be represented as floating point!
404 // TODO: Figure out how to test if a double can be cast to a float!
405 case Type::FloatTyID:
406 case Type::DoubleTyID:
407 return true; // This is the largest type...
411 //===----------------------------------------------------------------------===//
412 // replaceUsesOfWithOnConstant implementations
414 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
415 bool DisableChecking) {
416 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
418 std::vector<Constant*> Values;
419 Values.reserve(getValues().size()); // Build replacement array...
420 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
421 Constant *Val = cast<Constant>(getValues()[i]);
422 if (Val == From) Val = cast<Constant>(To);
423 Values.push_back(Val);
426 Constant *Replacement = ConstantArray::get(getType(), Values);
427 assert(Replacement != this && "I didn't contain From!");
429 // Everyone using this now uses the replacement...
431 uncheckedReplaceAllUsesWith(Replacement);
433 replaceAllUsesWith(Replacement);
435 // Delete the old constant!
439 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
440 bool DisableChecking) {
441 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
443 std::vector<Constant*> Values;
444 Values.reserve(getValues().size());
445 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
446 Constant *Val = cast<Constant>(getValues()[i]);
447 if (Val == From) Val = cast<Constant>(To);
448 Values.push_back(Val);
451 Constant *Replacement = ConstantStruct::get(getType(), Values);
452 assert(Replacement != this && "I didn't contain From!");
454 // Everyone using this now uses the replacement...
456 uncheckedReplaceAllUsesWith(Replacement);
458 replaceAllUsesWith(Replacement);
460 // Delete the old constant!
464 void ConstantPointerRef::replaceUsesOfWithOnConstant(Value *From, Value *To,
465 bool DisableChecking) {
466 if (isa<GlobalValue>(To)) {
467 assert(From == getOperand(0) && "Doesn't contain from!");
468 ConstantPointerRef *Replacement =
469 ConstantPointerRef::get(cast<GlobalValue>(To));
471 // Everyone using this now uses the replacement...
473 uncheckedReplaceAllUsesWith(Replacement);
475 replaceAllUsesWith(Replacement);
478 // Just replace ourselves with the To value specified.
480 uncheckedReplaceAllUsesWith(To);
482 replaceAllUsesWith(To);
485 // Delete the old constant!
489 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
490 bool DisableChecking) {
491 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
492 Constant *To = cast<Constant>(ToV);
494 Constant *Replacement = 0;
495 if (getOpcode() == Instruction::GetElementPtr) {
496 std::vector<Constant*> Indices;
497 Constant *Pointer = getOperand(0);
498 Indices.reserve(getNumOperands()-1);
499 if (Pointer == From) Pointer = To;
501 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
502 Constant *Val = getOperand(i);
503 if (Val == From) Val = To;
504 Indices.push_back(Val);
506 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
507 } else if (getOpcode() == Instruction::Cast) {
508 assert(getOperand(0) == From && "Cast only has one use!");
509 Replacement = ConstantExpr::getCast(To, getType());
510 } else if (getNumOperands() == 2) {
511 Constant *C1 = getOperand(0);
512 Constant *C2 = getOperand(1);
513 if (C1 == From) C1 = To;
514 if (C2 == From) C2 = To;
515 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
517 assert(0 && "Unknown ConstantExpr type!");
521 assert(Replacement != this && "I didn't contain From!");
523 // Everyone using this now uses the replacement...
525 uncheckedReplaceAllUsesWith(Replacement);
527 replaceAllUsesWith(Replacement);
529 // Delete the old constant!
533 //===----------------------------------------------------------------------===//
534 // Factory Function Implementation
536 // ConstantCreator - A class that is used to create constants by
537 // ValueMap*. This class should be partially specialized if there is
538 // something strange that needs to be done to interface to the ctor for the
542 template<class ConstantClass, class TypeClass, class ValType>
543 struct ConstantCreator {
544 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
545 return new ConstantClass(Ty, V);
549 template<class ConstantClass, class TypeClass>
550 struct ConvertConstantType {
551 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
552 assert(0 && "This type cannot be converted!\n");
559 template<class ValType, class TypeClass, class ConstantClass>
560 class ValueMap : public AbstractTypeUser {
561 typedef std::pair<const TypeClass*, ValType> MapKey;
562 typedef std::map<MapKey, ConstantClass *> MapTy;
563 typedef typename MapTy::iterator MapIterator;
566 typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
567 AbstractTypeMapTy AbstractTypeMap;
569 // getOrCreate - Return the specified constant from the map, creating it if
571 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
572 MapKey Lookup(Ty, V);
573 MapIterator I = Map.lower_bound(Lookup);
574 if (I != Map.end() && I->first == Lookup)
575 return I->second; // Is it in the map?
577 // If no preexisting value, create one now...
578 ConstantClass *Result =
579 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
582 /// FIXME: why does this assert fail when loading 176.gcc?
583 //assert(Result->getType() == Ty && "Type specified is not correct!");
584 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
586 // If the type of the constant is abstract, make sure that an entry exists
587 // for it in the AbstractTypeMap.
588 if (Ty->isAbstract()) {
589 typename AbstractTypeMapTy::iterator TI =
590 AbstractTypeMap.lower_bound(Ty);
592 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
593 // Add ourselves to the ATU list of the type.
594 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
596 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
602 void remove(ConstantClass *CP) {
603 // FIXME: This should not use a linear scan. If this gets to be a
604 // performance problem, someone should look at this.
605 MapIterator I = Map.begin();
606 for (MapIterator E = Map.end(); I != E && I->second != CP; ++I)
609 assert(I != Map.end() && "Constant not found in constant table!");
611 // Now that we found the entry, make sure this isn't the entry that
612 // the AbstractTypeMap points to.
613 const TypeClass *Ty = I->first.first;
614 if (Ty->isAbstract()) {
615 assert(AbstractTypeMap.count(Ty) &&
616 "Abstract type not in AbstractTypeMap?");
617 MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
618 if (ATMEntryIt == I) {
619 // Yes, we are removing the representative entry for this type.
620 // See if there are any other entries of the same type.
621 MapIterator TmpIt = ATMEntryIt;
623 // First check the entry before this one...
624 if (TmpIt != Map.begin()) {
626 if (TmpIt->first.first != Ty) // Not the same type, move back...
630 // If we didn't find the same type, try to move forward...
631 if (TmpIt == ATMEntryIt) {
633 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
634 --TmpIt; // No entry afterwards with the same type
637 // If there is another entry in the map of the same abstract type,
638 // update the AbstractTypeMap entry now.
639 if (TmpIt != ATMEntryIt) {
642 // Otherwise, we are removing the last instance of this type
643 // from the table. Remove from the ATM, and from user list.
644 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
645 AbstractTypeMap.erase(Ty);
653 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
654 typename AbstractTypeMapTy::iterator I =
655 AbstractTypeMap.find(cast<TypeClass>(OldTy));
657 assert(I != AbstractTypeMap.end() &&
658 "Abstract type not in AbstractTypeMap?");
660 // Convert a constant at a time until the last one is gone. The last one
661 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
662 // eliminated eventually.
664 ConvertConstantType<ConstantClass,
665 TypeClass>::convert(I->second->second,
666 cast<TypeClass>(NewTy));
668 I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
669 } while (I != AbstractTypeMap.end());
672 // If the type became concrete without being refined to any other existing
673 // type, we just remove ourselves from the ATU list.
674 void typeBecameConcrete(const DerivedType *AbsTy) {
675 AbsTy->removeAbstractTypeUser(this);
679 std::cerr << "Constant.cpp: ValueMap\n";
686 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
688 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
689 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
691 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
692 return SIntConstants.getOrCreate(Ty, V);
695 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
696 return UIntConstants.getOrCreate(Ty, V);
699 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
700 assert(V <= 127 && "Can only be used with very small positive constants!");
701 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
702 return ConstantUInt::get(Ty, V);
705 //---- ConstantFP::get() implementation...
709 struct ConstantCreator<ConstantFP, Type, uint64_t> {
710 static ConstantFP *create(const Type *Ty, uint64_t V) {
711 assert(Ty == Type::DoubleTy);
717 return new ConstantFP(Ty, T.F);
721 struct ConstantCreator<ConstantFP, Type, uint32_t> {
722 static ConstantFP *create(const Type *Ty, uint32_t V) {
723 assert(Ty == Type::FloatTy);
729 return new ConstantFP(Ty, T.F);
734 static ValueMap<uint64_t, Type, ConstantFP> DoubleConstants;
735 static ValueMap<uint32_t, Type, ConstantFP> FloatConstants;
737 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
738 if (Ty == Type::FloatTy) {
739 // Force the value through memory to normalize it.
745 return FloatConstants.getOrCreate(Ty, T.I);
747 assert(Ty == Type::DoubleTy);
753 return DoubleConstants.getOrCreate(Ty, T.I);
757 //---- ConstantAggregateZero::get() implementation...
760 // ConstantAggregateZero does not take extra "value" argument...
761 template<class ValType>
762 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
763 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
764 return new ConstantAggregateZero(Ty);
769 struct ConvertConstantType<ConstantAggregateZero, Type> {
770 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
771 // Make everyone now use a constant of the new type...
772 Constant *New = ConstantAggregateZero::get(NewTy);
773 assert(New != OldC && "Didn't replace constant??");
774 OldC->uncheckedReplaceAllUsesWith(New);
775 OldC->destroyConstant(); // This constant is now dead, destroy it.
780 static ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
782 Constant *ConstantAggregateZero::get(const Type *Ty) {
783 return AggZeroConstants.getOrCreate(Ty, 0);
786 // destroyConstant - Remove the constant from the constant table...
788 void ConstantAggregateZero::destroyConstant() {
789 AggZeroConstants.remove(this);
790 destroyConstantImpl();
793 void ConstantAggregateZero::replaceUsesOfWithOnConstant(Value *From, Value *To,
794 bool DisableChecking) {
795 assert(0 && "No uses!");
801 //---- ConstantArray::get() implementation...
805 struct ConvertConstantType<ConstantArray, ArrayType> {
806 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
807 // Make everyone now use a constant of the new type...
808 std::vector<Constant*> C;
809 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
810 C.push_back(cast<Constant>(OldC->getOperand(i)));
811 Constant *New = ConstantArray::get(NewTy, C);
812 assert(New != OldC && "Didn't replace constant??");
813 OldC->uncheckedReplaceAllUsesWith(New);
814 OldC->destroyConstant(); // This constant is now dead, destroy it.
819 static ValueMap<std::vector<Constant*>, ArrayType,
820 ConstantArray> ArrayConstants;
822 Constant *ConstantArray::get(const ArrayType *Ty,
823 const std::vector<Constant*> &V) {
824 // If this is an all-zero array, return a ConstantAggregateZero object
827 if (!C->isNullValue())
828 return ArrayConstants.getOrCreate(Ty, V);
829 for (unsigned i = 1, e = V.size(); i != e; ++i)
831 return ArrayConstants.getOrCreate(Ty, V);
833 return ConstantAggregateZero::get(Ty);
836 // destroyConstant - Remove the constant from the constant table...
838 void ConstantArray::destroyConstant() {
839 ArrayConstants.remove(this);
840 destroyConstantImpl();
843 // ConstantArray::get(const string&) - Return an array that is initialized to
844 // contain the specified string. A null terminator is added to the specified
845 // string so that it may be used in a natural way...
847 Constant *ConstantArray::get(const std::string &Str) {
848 std::vector<Constant*> ElementVals;
850 for (unsigned i = 0; i < Str.length(); ++i)
851 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
853 // Add a null terminator to the string...
854 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
856 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
857 return ConstantArray::get(ATy, ElementVals);
860 /// isString - This method returns true if the array is an array of sbyte or
861 /// ubyte, and if the elements of the array are all ConstantInt's.
862 bool ConstantArray::isString() const {
863 // Check the element type for sbyte or ubyte...
864 if (getType()->getElementType() != Type::UByteTy &&
865 getType()->getElementType() != Type::SByteTy)
867 // Check the elements to make sure they are all integers, not constant
869 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
870 if (!isa<ConstantInt>(getOperand(i)))
875 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
876 // then this method converts the array to an std::string and returns it.
877 // Otherwise, it asserts out.
879 std::string ConstantArray::getAsString() const {
880 assert(isString() && "Not a string!");
882 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
883 Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
888 //---- ConstantStruct::get() implementation...
893 struct ConvertConstantType<ConstantStruct, StructType> {
894 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
895 // Make everyone now use a constant of the new type...
896 std::vector<Constant*> C;
897 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
898 C.push_back(cast<Constant>(OldC->getOperand(i)));
899 Constant *New = ConstantStruct::get(NewTy, C);
900 assert(New != OldC && "Didn't replace constant??");
902 OldC->uncheckedReplaceAllUsesWith(New);
903 OldC->destroyConstant(); // This constant is now dead, destroy it.
908 static ValueMap<std::vector<Constant*>, StructType,
909 ConstantStruct> StructConstants;
911 Constant *ConstantStruct::get(const StructType *Ty,
912 const std::vector<Constant*> &V) {
913 // Create a ConstantAggregateZero value if all elements are zeros...
914 for (unsigned i = 0, e = V.size(); i != e; ++i)
915 if (!V[i]->isNullValue())
916 return StructConstants.getOrCreate(Ty, V);
918 return ConstantAggregateZero::get(Ty);
921 // destroyConstant - Remove the constant from the constant table...
923 void ConstantStruct::destroyConstant() {
924 StructConstants.remove(this);
925 destroyConstantImpl();
928 //---- ConstantPointerNull::get() implementation...
932 // ConstantPointerNull does not take extra "value" argument...
933 template<class ValType>
934 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
935 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
936 return new ConstantPointerNull(Ty);
941 struct ConvertConstantType<ConstantPointerNull, PointerType> {
942 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
943 // Make everyone now use a constant of the new type...
944 Constant *New = ConstantPointerNull::get(NewTy);
945 assert(New != OldC && "Didn't replace constant??");
946 OldC->uncheckedReplaceAllUsesWith(New);
947 OldC->destroyConstant(); // This constant is now dead, destroy it.
952 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
954 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
955 return NullPtrConstants.getOrCreate(Ty, 0);
958 // destroyConstant - Remove the constant from the constant table...
960 void ConstantPointerNull::destroyConstant() {
961 NullPtrConstants.remove(this);
962 destroyConstantImpl();
966 //---- ConstantPointerRef::get() implementation...
968 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
969 assert(GV->getParent() && "Global Value must be attached to a module!");
971 // The Module handles the pointer reference sharing...
972 return GV->getParent()->getConstantPointerRef(GV);
975 // destroyConstant - Remove the constant from the constant table...
977 void ConstantPointerRef::destroyConstant() {
978 getValue()->getParent()->destroyConstantPointerRef(this);
979 destroyConstantImpl();
983 //---- ConstantExpr::get() implementations...
985 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
989 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
990 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
991 if (V.first == Instruction::Cast)
992 return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
993 if ((V.first >= Instruction::BinaryOpsBegin &&
994 V.first < Instruction::BinaryOpsEnd) ||
995 V.first == Instruction::Shl || V.first == Instruction::Shr)
996 return new ConstantExpr(V.first, V.second[0], V.second[1]);
998 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1000 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1001 return new ConstantExpr(V.second[0], IdxList, Ty);
1006 struct ConvertConstantType<ConstantExpr, Type> {
1007 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1009 switch (OldC->getOpcode()) {
1010 case Instruction::Cast:
1011 New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1013 case Instruction::Select:
1014 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1015 OldC->getOperand(1),
1016 OldC->getOperand(2));
1018 case Instruction::Shl:
1019 case Instruction::Shr:
1020 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1021 OldC->getOperand(0), OldC->getOperand(1));
1024 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1025 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1026 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1027 OldC->getOperand(1));
1029 case Instruction::GetElementPtr:
1030 // Make everyone now use a constant of the new type...
1031 std::vector<Constant*> C;
1032 for (unsigned i = 1, e = OldC->getNumOperands(); i != e; ++i)
1033 C.push_back(cast<Constant>(OldC->getOperand(i)));
1034 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), C);
1038 assert(New != OldC && "Didn't replace constant??");
1039 OldC->uncheckedReplaceAllUsesWith(New);
1040 OldC->destroyConstant(); // This constant is now dead, destroy it.
1043 } // end namespace llvm
1046 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
1048 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1049 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1051 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1052 return FC; // Fold a few common cases...
1054 // Look up the constant in the table first to ensure uniqueness
1055 std::vector<Constant*> argVec(1, C);
1056 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1057 return ExprConstants.getOrCreate(Ty, Key);
1060 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1061 Constant *C1, Constant *C2) {
1062 if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1063 return getShiftTy(ReqTy, Opcode, C1, C2);
1064 // Check the operands for consistency first
1065 assert((Opcode >= Instruction::BinaryOpsBegin &&
1066 Opcode < Instruction::BinaryOpsEnd) &&
1067 "Invalid opcode in binary constant expression");
1068 assert(C1->getType() == C2->getType() &&
1069 "Operand types in binary constant expression should match");
1071 if (ReqTy == C1->getType())
1072 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1073 return FC; // Fold a few common cases...
1075 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1076 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1077 return ExprConstants.getOrCreate(ReqTy, Key);
1080 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1081 Constant *V1, Constant *V2) {
1082 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1083 assert(V1->getType() == V2->getType() && "Select value types must match!");
1084 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1086 if (ReqTy == V1->getType())
1087 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1088 return SC; // Fold common cases
1090 std::vector<Constant*> argVec(3, C);
1093 ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1094 return ExprConstants.getOrCreate(ReqTy, Key);
1097 /// getShiftTy - Return a shift left or shift right constant expr
1098 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1099 Constant *C1, Constant *C2) {
1100 // Check the operands for consistency first
1101 assert((Opcode == Instruction::Shl ||
1102 Opcode == Instruction::Shr) &&
1103 "Invalid opcode in binary constant expression");
1104 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1105 "Invalid operand types for Shift constant expr!");
1107 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1108 return FC; // Fold a few common cases...
1110 // Look up the constant in the table first to ensure uniqueness
1111 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1112 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1113 return ExprConstants.getOrCreate(ReqTy, Key);
1117 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1118 const std::vector<Constant*> &IdxList) {
1119 assert(GetElementPtrInst::getIndexedType(C->getType(),
1120 std::vector<Value*>(IdxList.begin(), IdxList.end()), true) &&
1121 "GEP indices invalid!");
1123 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1124 return FC; // Fold a few common cases...
1126 assert(isa<PointerType>(C->getType()) &&
1127 "Non-pointer type for constant GetElementPtr expression");
1128 // Look up the constant in the table first to ensure uniqueness
1129 std::vector<Constant*> argVec(1, C);
1130 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
1131 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,argVec);
1132 return ExprConstants.getOrCreate(ReqTy, Key);
1135 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1136 const std::vector<Constant*> &IdxList){
1137 // Get the result type of the getelementptr!
1138 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1140 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1142 assert(Ty && "GEP indices invalid!");
1143 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1147 // destroyConstant - Remove the constant from the constant table...
1149 void ConstantExpr::destroyConstant() {
1150 ExprConstants.remove(this);
1151 destroyConstantImpl();
1154 const char *ConstantExpr::getOpcodeName() const {
1155 return Instruction::getOpcodeName(getOpcode());