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()) {
270 Operands.push_back(Use(GV, this));
273 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
274 : Constant(Ty), iType(Opcode) {
275 Operands.push_back(Use(C, this));
278 static bool isSetCC(unsigned Opcode) {
279 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
280 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
281 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
284 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
285 : Constant(isSetCC(Opcode) ? Type::BoolTy : C1->getType()), iType(Opcode) {
286 Operands.push_back(Use(C1, this));
287 Operands.push_back(Use(C2, this));
290 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
292 : Constant(DestTy), iType(Instruction::GetElementPtr) {
293 Operands.reserve(1+IdxList.size());
294 Operands.push_back(Use(C, this));
295 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
296 Operands.push_back(Use(IdxList[i], this));
301 //===----------------------------------------------------------------------===//
302 // classof implementations
304 bool ConstantIntegral::classof(const Constant *CPV) {
305 return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
308 bool ConstantInt::classof(const Constant *CPV) {
309 return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
311 bool ConstantSInt::classof(const Constant *CPV) {
312 return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
314 bool ConstantUInt::classof(const Constant *CPV) {
315 return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
317 bool ConstantFP::classof(const Constant *CPV) {
318 const Type *Ty = CPV->getType();
319 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
320 !isa<ConstantExpr>(CPV));
322 bool ConstantAggregateZero::classof(const Constant *CPV) {
323 return (isa<ArrayType>(CPV->getType()) || isa<StructType>(CPV->getType())) &&
326 bool ConstantArray::classof(const Constant *CPV) {
327 return isa<ArrayType>(CPV->getType()) && !CPV->isNullValue();
329 bool ConstantStruct::classof(const Constant *CPV) {
330 return isa<StructType>(CPV->getType()) && !CPV->isNullValue();
333 bool ConstantPointerNull::classof(const Constant *CPV) {
334 return isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV) &&
335 CPV->getNumOperands() == 0;
338 bool ConstantPointerRef::classof(const Constant *CPV) {
339 return isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV) &&
340 CPV->getNumOperands() == 1;
345 //===----------------------------------------------------------------------===//
346 // isValueValidForType implementations
348 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
349 switch (Ty->getPrimitiveID()) {
351 return false; // These can't be represented as integers!!!
354 case Type::SByteTyID:
355 return (Val <= INT8_MAX && Val >= INT8_MIN);
356 case Type::ShortTyID:
357 return (Val <= INT16_MAX && Val >= INT16_MIN);
359 return (Val <= INT32_MAX && Val >= INT32_MIN);
361 return true; // This is the largest type...
367 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
368 switch (Ty->getPrimitiveID()) {
370 return false; // These can't be represented as integers!!!
373 case Type::UByteTyID:
374 return (Val <= UINT8_MAX);
375 case Type::UShortTyID:
376 return (Val <= UINT16_MAX);
378 return (Val <= UINT32_MAX);
379 case Type::ULongTyID:
380 return true; // This is the largest type...
386 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
387 switch (Ty->getPrimitiveID()) {
389 return false; // These can't be represented as floating point!
391 // TODO: Figure out how to test if a double can be cast to a float!
392 case Type::FloatTyID:
393 case Type::DoubleTyID:
394 return true; // This is the largest type...
398 //===----------------------------------------------------------------------===//
399 // replaceUsesOfWithOnConstant implementations
401 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
402 bool DisableChecking) {
403 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
405 std::vector<Constant*> Values;
406 Values.reserve(getValues().size()); // Build replacement array...
407 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
408 Constant *Val = cast<Constant>(getValues()[i]);
409 if (Val == From) Val = cast<Constant>(To);
410 Values.push_back(Val);
413 Constant *Replacement = ConstantArray::get(getType(), Values);
414 assert(Replacement != this && "I didn't contain From!");
416 // Everyone using this now uses the replacement...
418 uncheckedReplaceAllUsesWith(Replacement);
420 replaceAllUsesWith(Replacement);
422 // Delete the old constant!
426 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
427 bool DisableChecking) {
428 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
430 std::vector<Constant*> Values;
431 Values.reserve(getValues().size());
432 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
433 Constant *Val = cast<Constant>(getValues()[i]);
434 if (Val == From) Val = cast<Constant>(To);
435 Values.push_back(Val);
438 Constant *Replacement = ConstantStruct::get(getType(), Values);
439 assert(Replacement != this && "I didn't contain From!");
441 // Everyone using this now uses the replacement...
443 uncheckedReplaceAllUsesWith(Replacement);
445 replaceAllUsesWith(Replacement);
447 // Delete the old constant!
451 void ConstantPointerRef::replaceUsesOfWithOnConstant(Value *From, Value *To,
452 bool DisableChecking) {
453 if (isa<GlobalValue>(To)) {
454 assert(From == getOperand(0) && "Doesn't contain from!");
455 ConstantPointerRef *Replacement =
456 ConstantPointerRef::get(cast<GlobalValue>(To));
458 // Everyone using this now uses the replacement...
460 uncheckedReplaceAllUsesWith(Replacement);
462 replaceAllUsesWith(Replacement);
465 // Just replace ourselves with the To value specified.
467 uncheckedReplaceAllUsesWith(To);
469 replaceAllUsesWith(To);
472 // Delete the old constant!
476 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
477 bool DisableChecking) {
478 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
479 Constant *To = cast<Constant>(ToV);
481 Constant *Replacement = 0;
482 if (getOpcode() == Instruction::GetElementPtr) {
483 std::vector<Constant*> Indices;
484 Constant *Pointer = getOperand(0);
485 Indices.reserve(getNumOperands()-1);
486 if (Pointer == From) Pointer = To;
488 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
489 Constant *Val = getOperand(i);
490 if (Val == From) Val = To;
491 Indices.push_back(Val);
493 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
494 } else if (getOpcode() == Instruction::Cast) {
495 assert(getOperand(0) == From && "Cast only has one use!");
496 Replacement = ConstantExpr::getCast(To, getType());
497 } else if (getNumOperands() == 2) {
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::get(getOpcode(), C1, C2);
504 assert(0 && "Unknown ConstantExpr type!");
508 assert(Replacement != this && "I didn't contain From!");
510 // Everyone using this now uses the replacement...
512 uncheckedReplaceAllUsesWith(Replacement);
514 replaceAllUsesWith(Replacement);
516 // Delete the old constant!
520 //===----------------------------------------------------------------------===//
521 // Factory Function Implementation
523 // ConstantCreator - A class that is used to create constants by
524 // ValueMap*. This class should be partially specialized if there is
525 // something strange that needs to be done to interface to the ctor for the
529 template<class ConstantClass, class TypeClass, class ValType>
530 struct ConstantCreator {
531 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
532 return new ConstantClass(Ty, V);
536 template<class ConstantClass, class TypeClass>
537 struct ConvertConstantType {
538 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
539 assert(0 && "This type cannot be converted!\n");
546 template<class ValType, class TypeClass, class ConstantClass>
547 class ValueMap : public AbstractTypeUser {
548 typedef std::pair<const TypeClass*, ValType> MapKey;
549 typedef std::map<MapKey, ConstantClass *> MapTy;
550 typedef typename MapTy::iterator MapIterator;
553 typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
554 AbstractTypeMapTy AbstractTypeMap;
556 // getOrCreate - Return the specified constant from the map, creating it if
558 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
559 MapKey Lookup(Ty, V);
560 MapIterator I = Map.lower_bound(Lookup);
561 if (I != Map.end() && I->first == Lookup)
562 return I->second; // Is it in the map?
564 // If no preexisting value, create one now...
565 ConstantClass *Result =
566 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
569 /// FIXME: why does this assert fail when loading 176.gcc?
570 //assert(Result->getType() == Ty && "Type specified is not correct!");
571 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
573 // If the type of the constant is abstract, make sure that an entry exists
574 // for it in the AbstractTypeMap.
575 if (Ty->isAbstract()) {
576 typename AbstractTypeMapTy::iterator TI =
577 AbstractTypeMap.lower_bound(Ty);
579 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
580 // Add ourselves to the ATU list of the type.
581 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
583 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
589 void remove(ConstantClass *CP) {
590 // FIXME: This should not use a linear scan. If this gets to be a
591 // performance problem, someone should look at this.
592 MapIterator I = Map.begin();
593 for (MapIterator E = Map.end(); I != E && I->second != CP; ++I)
596 assert(I != Map.end() && "Constant not found in constant table!");
598 // Now that we found the entry, make sure this isn't the entry that
599 // the AbstractTypeMap points to.
600 const TypeClass *Ty = I->first.first;
601 if (Ty->isAbstract()) {
602 assert(AbstractTypeMap.count(Ty) &&
603 "Abstract type not in AbstractTypeMap?");
604 MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
605 if (ATMEntryIt == I) {
606 // Yes, we are removing the representative entry for this type.
607 // See if there are any other entries of the same type.
608 MapIterator TmpIt = ATMEntryIt;
610 // First check the entry before this one...
611 if (TmpIt != Map.begin()) {
613 if (TmpIt->first.first != Ty) // Not the same type, move back...
617 // If we didn't find the same type, try to move forward...
618 if (TmpIt == ATMEntryIt) {
620 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
621 --TmpIt; // No entry afterwards with the same type
624 // If there is another entry in the map of the same abstract type,
625 // update the AbstractTypeMap entry now.
626 if (TmpIt != ATMEntryIt) {
629 // Otherwise, we are removing the last instance of this type
630 // from the table. Remove from the ATM, and from user list.
631 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
632 AbstractTypeMap.erase(Ty);
640 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
641 typename AbstractTypeMapTy::iterator I =
642 AbstractTypeMap.find(cast<TypeClass>(OldTy));
644 assert(I != AbstractTypeMap.end() &&
645 "Abstract type not in AbstractTypeMap?");
647 // Convert a constant at a time until the last one is gone. The last one
648 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
649 // eliminated eventually.
651 ConvertConstantType<ConstantClass,
652 TypeClass>::convert(I->second->second,
653 cast<TypeClass>(NewTy));
655 I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
656 } while (I != AbstractTypeMap.end());
659 // If the type became concrete without being refined to any other existing
660 // type, we just remove ourselves from the ATU list.
661 void typeBecameConcrete(const DerivedType *AbsTy) {
662 AbsTy->removeAbstractTypeUser(this);
666 std::cerr << "Constant.cpp: ValueMap\n";
673 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
675 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
676 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
678 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
679 return SIntConstants.getOrCreate(Ty, V);
682 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
683 return UIntConstants.getOrCreate(Ty, V);
686 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
687 assert(V <= 127 && "Can only be used with very small positive constants!");
688 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
689 return ConstantUInt::get(Ty, V);
692 //---- ConstantFP::get() implementation...
696 struct ConstantCreator<ConstantFP, Type, uint64_t> {
697 static ConstantFP *create(const Type *Ty, uint64_t V) {
698 assert(Ty == Type::DoubleTy);
704 return new ConstantFP(Ty, T.F);
708 struct ConstantCreator<ConstantFP, Type, uint32_t> {
709 static ConstantFP *create(const Type *Ty, uint32_t V) {
710 assert(Ty == Type::FloatTy);
716 return new ConstantFP(Ty, T.F);
721 static ValueMap<uint64_t, Type, ConstantFP> DoubleConstants;
722 static ValueMap<uint32_t, Type, ConstantFP> FloatConstants;
724 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
725 if (Ty == Type::FloatTy) {
726 // Force the value through memory to normalize it.
732 return FloatConstants.getOrCreate(Ty, T.I);
734 assert(Ty == Type::DoubleTy);
740 return DoubleConstants.getOrCreate(Ty, T.I);
744 //---- ConstantAggregateZero::get() implementation...
747 // ConstantAggregateZero does not take extra "value" argument...
748 template<class ValType>
749 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
750 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
751 return new ConstantAggregateZero(Ty);
756 struct ConvertConstantType<ConstantAggregateZero, Type> {
757 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
758 // Make everyone now use a constant of the new type...
759 Constant *New = ConstantAggregateZero::get(NewTy);
760 assert(New != OldC && "Didn't replace constant??");
761 OldC->uncheckedReplaceAllUsesWith(New);
762 OldC->destroyConstant(); // This constant is now dead, destroy it.
767 static ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
769 Constant *ConstantAggregateZero::get(const Type *Ty) {
770 return AggZeroConstants.getOrCreate(Ty, 0);
773 // destroyConstant - Remove the constant from the constant table...
775 void ConstantAggregateZero::destroyConstant() {
776 AggZeroConstants.remove(this);
777 destroyConstantImpl();
780 void ConstantAggregateZero::replaceUsesOfWithOnConstant(Value *From, Value *To,
781 bool DisableChecking) {
782 assert(0 && "No uses!");
788 //---- ConstantArray::get() implementation...
792 struct ConvertConstantType<ConstantArray, ArrayType> {
793 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
794 // Make everyone now use a constant of the new type...
795 std::vector<Constant*> C;
796 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
797 C.push_back(cast<Constant>(OldC->getOperand(i)));
798 Constant *New = ConstantArray::get(NewTy, C);
799 assert(New != OldC && "Didn't replace constant??");
800 OldC->uncheckedReplaceAllUsesWith(New);
801 OldC->destroyConstant(); // This constant is now dead, destroy it.
806 static ValueMap<std::vector<Constant*>, ArrayType,
807 ConstantArray> ArrayConstants;
809 Constant *ConstantArray::get(const ArrayType *Ty,
810 const std::vector<Constant*> &V) {
811 // If this is an all-zero array, return a ConstantAggregateZero object
814 if (!C->isNullValue())
815 return ArrayConstants.getOrCreate(Ty, V);
816 for (unsigned i = 1, e = V.size(); i != e; ++i)
818 return ArrayConstants.getOrCreate(Ty, V);
820 return ConstantAggregateZero::get(Ty);
823 // destroyConstant - Remove the constant from the constant table...
825 void ConstantArray::destroyConstant() {
826 ArrayConstants.remove(this);
827 destroyConstantImpl();
830 // ConstantArray::get(const string&) - Return an array that is initialized to
831 // contain the specified string. A null terminator is added to the specified
832 // string so that it may be used in a natural way...
834 Constant *ConstantArray::get(const std::string &Str) {
835 std::vector<Constant*> ElementVals;
837 for (unsigned i = 0; i < Str.length(); ++i)
838 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
840 // Add a null terminator to the string...
841 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
843 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
844 return ConstantArray::get(ATy, ElementVals);
847 /// isString - This method returns true if the array is an array of sbyte or
848 /// ubyte, and if the elements of the array are all ConstantInt's.
849 bool ConstantArray::isString() const {
850 // Check the element type for sbyte or ubyte...
851 if (getType()->getElementType() != Type::UByteTy &&
852 getType()->getElementType() != Type::SByteTy)
854 // Check the elements to make sure they are all integers, not constant
856 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
857 if (!isa<ConstantInt>(getOperand(i)))
862 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
863 // then this method converts the array to an std::string and returns it.
864 // Otherwise, it asserts out.
866 std::string ConstantArray::getAsString() const {
867 assert(isString() && "Not a string!");
869 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
870 Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
875 //---- ConstantStruct::get() implementation...
880 struct ConvertConstantType<ConstantStruct, StructType> {
881 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
882 // Make everyone now use a constant of the new type...
883 std::vector<Constant*> C;
884 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
885 C.push_back(cast<Constant>(OldC->getOperand(i)));
886 Constant *New = ConstantStruct::get(NewTy, C);
887 assert(New != OldC && "Didn't replace constant??");
889 OldC->uncheckedReplaceAllUsesWith(New);
890 OldC->destroyConstant(); // This constant is now dead, destroy it.
895 static ValueMap<std::vector<Constant*>, StructType,
896 ConstantStruct> StructConstants;
898 Constant *ConstantStruct::get(const StructType *Ty,
899 const std::vector<Constant*> &V) {
900 // Create a ConstantAggregateZero value if all elements are zeros...
901 for (unsigned i = 0, e = V.size(); i != e; ++i)
902 if (!V[i]->isNullValue())
903 return StructConstants.getOrCreate(Ty, V);
905 return ConstantAggregateZero::get(Ty);
908 // destroyConstant - Remove the constant from the constant table...
910 void ConstantStruct::destroyConstant() {
911 StructConstants.remove(this);
912 destroyConstantImpl();
915 //---- ConstantPointerNull::get() implementation...
919 // ConstantPointerNull does not take extra "value" argument...
920 template<class ValType>
921 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
922 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
923 return new ConstantPointerNull(Ty);
928 struct ConvertConstantType<ConstantPointerNull, PointerType> {
929 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
930 // Make everyone now use a constant of the new type...
931 Constant *New = ConstantPointerNull::get(NewTy);
932 assert(New != OldC && "Didn't replace constant??");
933 OldC->uncheckedReplaceAllUsesWith(New);
934 OldC->destroyConstant(); // This constant is now dead, destroy it.
939 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
941 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
942 return NullPtrConstants.getOrCreate(Ty, 0);
945 // destroyConstant - Remove the constant from the constant table...
947 void ConstantPointerNull::destroyConstant() {
948 NullPtrConstants.remove(this);
949 destroyConstantImpl();
953 //---- ConstantPointerRef::get() implementation...
955 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
956 assert(GV->getParent() && "Global Value must be attached to a module!");
958 // The Module handles the pointer reference sharing...
959 return GV->getParent()->getConstantPointerRef(GV);
962 // destroyConstant - Remove the constant from the constant table...
964 void ConstantPointerRef::destroyConstant() {
965 getValue()->getParent()->destroyConstantPointerRef(this);
966 destroyConstantImpl();
970 //---- ConstantExpr::get() implementations...
972 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
976 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
977 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
978 if (V.first == Instruction::Cast)
979 return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
980 if ((V.first >= Instruction::BinaryOpsBegin &&
981 V.first < Instruction::BinaryOpsEnd) ||
982 V.first == Instruction::Shl || V.first == Instruction::Shr)
983 return new ConstantExpr(V.first, V.second[0], V.second[1]);
985 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
987 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
988 return new ConstantExpr(V.second[0], IdxList, Ty);
993 struct ConvertConstantType<ConstantExpr, Type> {
994 static void convert(ConstantExpr *OldC, const Type *NewTy) {
996 switch (OldC->getOpcode()) {
997 case Instruction::Cast:
998 New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1000 case Instruction::Shl:
1001 case Instruction::Shr:
1002 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1003 OldC->getOperand(0), OldC->getOperand(1));
1006 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1007 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1008 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1009 OldC->getOperand(1));
1011 case Instruction::GetElementPtr:
1012 // Make everyone now use a constant of the new type...
1013 std::vector<Constant*> C;
1014 for (unsigned i = 1, e = OldC->getNumOperands(); i != e; ++i)
1015 C.push_back(cast<Constant>(OldC->getOperand(i)));
1016 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), C);
1020 assert(New != OldC && "Didn't replace constant??");
1021 OldC->uncheckedReplaceAllUsesWith(New);
1022 OldC->destroyConstant(); // This constant is now dead, destroy it.
1025 } // end namespace llvm
1028 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
1030 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1031 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1033 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1034 return FC; // Fold a few common cases...
1036 // Look up the constant in the table first to ensure uniqueness
1037 std::vector<Constant*> argVec(1, C);
1038 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1039 return ExprConstants.getOrCreate(Ty, Key);
1042 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1043 Constant *C1, Constant *C2) {
1044 if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1045 return getShiftTy(ReqTy, Opcode, C1, C2);
1046 // Check the operands for consistency first
1047 assert((Opcode >= Instruction::BinaryOpsBegin &&
1048 Opcode < Instruction::BinaryOpsEnd) &&
1049 "Invalid opcode in binary constant expression");
1050 assert(C1->getType() == C2->getType() &&
1051 "Operand types in binary constant expression should match");
1053 if (ReqTy == C1->getType())
1054 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1055 return FC; // Fold a few common cases...
1057 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1058 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1059 return ExprConstants.getOrCreate(ReqTy, Key);
1062 /// getShiftTy - Return a shift left or shift right constant expr
1063 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1064 Constant *C1, Constant *C2) {
1065 // Check the operands for consistency first
1066 assert((Opcode == Instruction::Shl ||
1067 Opcode == Instruction::Shr) &&
1068 "Invalid opcode in binary constant expression");
1069 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1070 "Invalid operand types for Shift constant expr!");
1072 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1073 return FC; // Fold a few common cases...
1075 // Look up the constant in the table first to ensure uniqueness
1076 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1077 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1078 return ExprConstants.getOrCreate(ReqTy, Key);
1082 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1083 const std::vector<Constant*> &IdxList) {
1084 assert(GetElementPtrInst::getIndexedType(C->getType(),
1085 std::vector<Value*>(IdxList.begin(), IdxList.end()), true) &&
1086 "GEP indices invalid!");
1088 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1089 return FC; // Fold a few common cases...
1091 assert(isa<PointerType>(C->getType()) &&
1092 "Non-pointer type for constant GetElementPtr expression");
1093 // Look up the constant in the table first to ensure uniqueness
1094 std::vector<Constant*> argVec(1, C);
1095 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
1096 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,argVec);
1097 return ExprConstants.getOrCreate(ReqTy, Key);
1100 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1101 const std::vector<Constant*> &IdxList){
1102 // Get the result type of the getelementptr!
1103 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1105 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1107 assert(Ty && "GEP indices invalid!");
1108 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1112 // destroyConstant - Remove the constant from the constant table...
1114 void ConstantExpr::destroyConstant() {
1115 ExprConstants.remove(this);
1116 destroyConstantImpl();
1119 const char *ConstantExpr::getOpcodeName() const {
1120 return Instruction::getOpcodeName(getOpcode());
1123 unsigned Constant::mutateReferences(Value *OldV, Value *NewV) {
1124 // Uses of constant pointer refs are global values, not constants!
1125 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
1126 GlobalValue *NewGV = cast<GlobalValue>(NewV);
1127 GlobalValue *OldGV = CPR->getValue();
1129 assert(OldGV == OldV && "Cannot mutate old value if I'm not using it!");
1130 Operands[0] = NewGV;
1131 OldGV->getParent()->mutateConstantPointerRef(OldGV, NewGV);
1134 Constant *NewC = cast<Constant>(NewV);
1135 unsigned NumReplaced = 0;
1136 for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
1137 if (Operands[i] == OldV) {