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 std::map<const Type *, Constant*> NullValues;
69 // Static constructor to create a '0' constant of arbitrary type...
70 Constant *Constant::getNullValue(const Type *Ty) {
71 switch (Ty->getPrimitiveID()) {
72 case Type::BoolTyID: {
73 static Constant *NullBool = ConstantBool::get(false);
76 case Type::SByteTyID: {
77 static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
80 case Type::UByteTyID: {
81 static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
84 case Type::ShortTyID: {
85 static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
88 case Type::UShortTyID: {
89 static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
93 static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
96 case Type::UIntTyID: {
97 static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
100 case Type::LongTyID: {
101 static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
104 case Type::ULongTyID: {
105 static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
109 case Type::FloatTyID: {
110 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
113 case Type::DoubleTyID: {
114 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
118 case Type::PointerTyID:
119 return ConstantPointerNull::get(cast<PointerType>(Ty));
121 case Type::StructTyID: {
122 if (!Ty->isAbstract())
123 if (Constant *V = NullValues[Ty])
126 const StructType *ST = cast<StructType>(Ty);
127 std::vector<Constant*> Elements;
128 Elements.resize(ST->getNumElements());
129 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
130 Elements[i] = Constant::getNullValue(ST->getElementType(i));
131 Constant *Ret = ConstantStruct::get(ST, Elements);
132 if (!Ty->isAbstract())
133 NullValues[Ty] = Ret;
136 case Type::ArrayTyID: {
137 if (!Ty->isAbstract())
138 if (Constant *V = NullValues[Ty])
141 const ArrayType *AT = cast<ArrayType>(Ty);
142 Constant *El = Constant::getNullValue(AT->getElementType());
143 unsigned NumElements = AT->getNumElements();
144 Constant *Ret = ConstantArray::get(AT,
145 std::vector<Constant*>(NumElements, El));
146 if (!Ty->isAbstract())
147 NullValues[Ty] = Ret;
151 // Function, Type, Label, or Opaque type?
152 assert(0 && "Cannot create a null constant of that type!");
157 // Static constructor to create the maximum constant of an integral type...
158 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
159 switch (Ty->getPrimitiveID()) {
160 case Type::BoolTyID: return ConstantBool::True;
161 case Type::SByteTyID:
162 case Type::ShortTyID:
164 case Type::LongTyID: {
165 // Calculate 011111111111111...
166 unsigned TypeBits = Ty->getPrimitiveSize()*8;
167 int64_t Val = INT64_MAX; // All ones
168 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
169 return ConstantSInt::get(Ty, Val);
172 case Type::UByteTyID:
173 case Type::UShortTyID:
175 case Type::ULongTyID: return getAllOnesValue(Ty);
181 // Static constructor to create the minimum constant for an integral type...
182 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
183 switch (Ty->getPrimitiveID()) {
184 case Type::BoolTyID: return ConstantBool::False;
185 case Type::SByteTyID:
186 case Type::ShortTyID:
188 case Type::LongTyID: {
189 // Calculate 1111111111000000000000
190 unsigned TypeBits = Ty->getPrimitiveSize()*8;
191 int64_t Val = -1; // All ones
192 Val <<= TypeBits-1; // Shift over to the right spot
193 return ConstantSInt::get(Ty, Val);
196 case Type::UByteTyID:
197 case Type::UShortTyID:
199 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
205 // Static constructor to create an integral constant with all bits set
206 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
207 switch (Ty->getPrimitiveID()) {
208 case Type::BoolTyID: return ConstantBool::True;
209 case Type::SByteTyID:
210 case Type::ShortTyID:
212 case Type::LongTyID: return ConstantSInt::get(Ty, -1);
214 case Type::UByteTyID:
215 case Type::UShortTyID:
217 case Type::ULongTyID: {
218 // Calculate ~0 of the right type...
219 unsigned TypeBits = Ty->getPrimitiveSize()*8;
220 uint64_t Val = ~0ULL; // All ones
221 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
222 return ConstantUInt::get(Ty, Val);
228 bool ConstantUInt::isAllOnesValue() const {
229 unsigned TypeBits = getType()->getPrimitiveSize()*8;
230 uint64_t Val = ~0ULL; // All ones
231 Val >>= 64-TypeBits; // Shift out inappropriate bits
232 return getValue() == Val;
236 //===----------------------------------------------------------------------===//
237 // ConstantXXX Classes
238 //===----------------------------------------------------------------------===//
240 //===----------------------------------------------------------------------===//
241 // Normal Constructors
243 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy) {
247 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty) {
251 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
252 assert(Ty->isInteger() && Ty->isSigned() &&
253 "Illegal type for unsigned integer constant!");
254 assert(isValueValidForType(Ty, V) && "Value too large for type!");
257 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
258 assert(Ty->isInteger() && Ty->isUnsigned() &&
259 "Illegal type for unsigned integer constant!");
260 assert(isValueValidForType(Ty, V) && "Value too large for type!");
263 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
264 assert(isValueValidForType(Ty, V) && "Value too large for type!");
268 ConstantArray::ConstantArray(const ArrayType *T,
269 const std::vector<Constant*> &V) : Constant(T) {
270 Operands.reserve(V.size());
271 for (unsigned i = 0, e = V.size(); i != e; ++i) {
272 assert(V[i]->getType() == T->getElementType() ||
274 V[i]->getType()->getPrimitiveID() ==
275 T->getElementType()->getPrimitiveID()));
276 Operands.push_back(Use(V[i], this));
280 ConstantStruct::ConstantStruct(const StructType *T,
281 const std::vector<Constant*> &V) : Constant(T) {
282 assert(V.size() == T->getNumElements() &&
283 "Invalid initializer vector for constant structure");
284 Operands.reserve(V.size());
285 for (unsigned i = 0, e = V.size(); i != e; ++i) {
286 assert((V[i]->getType() == T->getElementType(i) ||
287 ((T->getElementType(i)->isAbstract() ||
288 V[i]->getType()->isAbstract()) &&
289 T->getElementType(i)->getPrimitiveID() ==
290 V[i]->getType()->getPrimitiveID())) &&
291 "Initializer for struct element doesn't match struct element type!");
292 Operands.push_back(Use(V[i], this));
296 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
297 : Constant(GV->getType()) {
298 Operands.push_back(Use(GV, this));
301 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
302 : Constant(Ty), iType(Opcode) {
303 Operands.push_back(Use(C, this));
306 static bool isSetCC(unsigned Opcode) {
307 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
308 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
309 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
312 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
313 : Constant(isSetCC(Opcode) ? Type::BoolTy : C1->getType()), iType(Opcode) {
314 Operands.push_back(Use(C1, this));
315 Operands.push_back(Use(C2, this));
318 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
320 : Constant(DestTy), iType(Instruction::GetElementPtr) {
321 Operands.reserve(1+IdxList.size());
322 Operands.push_back(Use(C, this));
323 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
324 Operands.push_back(Use(IdxList[i], this));
329 //===----------------------------------------------------------------------===//
330 // classof implementations
332 bool ConstantIntegral::classof(const Constant *CPV) {
333 return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
336 bool ConstantInt::classof(const Constant *CPV) {
337 return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
339 bool ConstantSInt::classof(const Constant *CPV) {
340 return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
342 bool ConstantUInt::classof(const Constant *CPV) {
343 return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
345 bool ConstantFP::classof(const Constant *CPV) {
346 const Type *Ty = CPV->getType();
347 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
348 !isa<ConstantExpr>(CPV));
350 bool ConstantArray::classof(const Constant *CPV) {
351 return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
353 bool ConstantStruct::classof(const Constant *CPV) {
354 return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
357 bool ConstantPointerNull::classof(const Constant *CPV) {
358 return isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV) &&
359 CPV->getNumOperands() == 0;
362 bool ConstantPointerRef::classof(const Constant *CPV) {
363 return isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV) &&
364 CPV->getNumOperands() == 1;
369 //===----------------------------------------------------------------------===//
370 // isValueValidForType implementations
372 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
373 switch (Ty->getPrimitiveID()) {
375 return false; // These can't be represented as integers!!!
378 case Type::SByteTyID:
379 return (Val <= INT8_MAX && Val >= INT8_MIN);
380 case Type::ShortTyID:
381 return (Val <= INT16_MAX && Val >= INT16_MIN);
383 return (Val <= INT32_MAX && Val >= INT32_MIN);
385 return true; // This is the largest type...
391 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
392 switch (Ty->getPrimitiveID()) {
394 return false; // These can't be represented as integers!!!
397 case Type::UByteTyID:
398 return (Val <= UINT8_MAX);
399 case Type::UShortTyID:
400 return (Val <= UINT16_MAX);
402 return (Val <= UINT32_MAX);
403 case Type::ULongTyID:
404 return true; // This is the largest type...
410 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
411 switch (Ty->getPrimitiveID()) {
413 return false; // These can't be represented as floating point!
415 // TODO: Figure out how to test if a double can be cast to a float!
416 case Type::FloatTyID:
417 case Type::DoubleTyID:
418 return true; // This is the largest type...
422 //===----------------------------------------------------------------------===//
423 // replaceUsesOfWithOnConstant implementations
425 void ConstantArray::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()); // Build replacement array...
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 Constant *Replacement = ConstantArray::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 ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
451 bool DisableChecking) {
452 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
454 std::vector<Constant*> Values;
455 Values.reserve(getValues().size());
456 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
457 Constant *Val = cast<Constant>(getValues()[i]);
458 if (Val == From) Val = cast<Constant>(To);
459 Values.push_back(Val);
462 Constant *Replacement = ConstantStruct::get(getType(), Values);
463 assert(Replacement != this && "I didn't contain From!");
465 // Everyone using this now uses the replacement...
467 uncheckedReplaceAllUsesWith(Replacement);
469 replaceAllUsesWith(Replacement);
471 // Delete the old constant!
475 void ConstantPointerRef::replaceUsesOfWithOnConstant(Value *From, Value *To,
476 bool DisableChecking) {
477 if (isa<GlobalValue>(To)) {
478 assert(From == getOperand(0) && "Doesn't contain from!");
479 ConstantPointerRef *Replacement =
480 ConstantPointerRef::get(cast<GlobalValue>(To));
482 // Everyone using this now uses the replacement...
484 uncheckedReplaceAllUsesWith(Replacement);
486 replaceAllUsesWith(Replacement);
489 // Just replace ourselves with the To value specified.
491 uncheckedReplaceAllUsesWith(To);
493 replaceAllUsesWith(To);
496 // Delete the old constant!
500 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
501 bool DisableChecking) {
502 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
503 Constant *To = cast<Constant>(ToV);
505 Constant *Replacement = 0;
506 if (getOpcode() == Instruction::GetElementPtr) {
507 std::vector<Constant*> Indices;
508 Constant *Pointer = getOperand(0);
509 Indices.reserve(getNumOperands()-1);
510 if (Pointer == From) Pointer = To;
512 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
513 Constant *Val = getOperand(i);
514 if (Val == From) Val = To;
515 Indices.push_back(Val);
517 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
518 } else if (getOpcode() == Instruction::Cast) {
519 assert(getOperand(0) == From && "Cast only has one use!");
520 Replacement = ConstantExpr::getCast(To, getType());
521 } else if (getNumOperands() == 2) {
522 Constant *C1 = getOperand(0);
523 Constant *C2 = getOperand(1);
524 if (C1 == From) C1 = To;
525 if (C2 == From) C2 = To;
526 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
528 assert(0 && "Unknown ConstantExpr type!");
532 assert(Replacement != this && "I didn't contain From!");
534 // Everyone using this now uses the replacement...
536 uncheckedReplaceAllUsesWith(Replacement);
538 replaceAllUsesWith(Replacement);
540 // Delete the old constant!
544 //===----------------------------------------------------------------------===//
545 // Factory Function Implementation
547 // ConstantCreator - A class that is used to create constants by
548 // ValueMap*. This class should be partially specialized if there is
549 // something strange that needs to be done to interface to the ctor for the
553 template<class ConstantClass, class TypeClass, class ValType>
554 struct ConstantCreator {
555 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
556 return new ConstantClass(Ty, V);
560 template<class ConstantClass, class TypeClass>
561 struct ConvertConstantType {
562 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
563 assert(0 && "This type cannot be converted!\n");
570 template<class ValType, class TypeClass, class ConstantClass>
571 class ValueMap : public AbstractTypeUser {
572 typedef std::pair<const TypeClass*, ValType> MapKey;
573 typedef std::map<MapKey, ConstantClass *> MapTy;
574 typedef typename MapTy::iterator MapIterator;
577 typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
578 AbstractTypeMapTy AbstractTypeMap;
580 // getOrCreate - Return the specified constant from the map, creating it if
582 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
583 MapKey Lookup(Ty, V);
584 MapIterator I = Map.lower_bound(Lookup);
585 if (I != Map.end() && I->first == Lookup)
586 return I->second; // Is it in the map?
588 // If no preexisting value, create one now...
589 ConstantClass *Result =
590 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
593 /// FIXME: why does this assert fail when loading 176.gcc?
594 //assert(Result->getType() == Ty && "Type specified is not correct!");
595 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
597 // If the type of the constant is abstract, make sure that an entry exists
598 // for it in the AbstractTypeMap.
599 if (Ty->isAbstract()) {
600 typename AbstractTypeMapTy::iterator TI =
601 AbstractTypeMap.lower_bound(Ty);
603 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
604 // Add ourselves to the ATU list of the type.
605 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
607 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
613 void remove(ConstantClass *CP) {
614 // FIXME: This should not use a linear scan. If this gets to be a
615 // performance problem, someone should look at this.
616 MapIterator I = Map.begin();
617 for (MapIterator E = Map.end(); I != E && I->second != CP; ++I)
620 assert(I != Map.end() && "Constant not found in constant table!");
622 // Now that we found the entry, make sure this isn't the entry that
623 // the AbstractTypeMap points to.
624 const TypeClass *Ty = I->first.first;
625 if (Ty->isAbstract()) {
626 assert(AbstractTypeMap.count(Ty) &&
627 "Abstract type not in AbstractTypeMap?");
628 MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
629 if (ATMEntryIt == I) {
630 // Yes, we are removing the representative entry for this type.
631 // See if there are any other entries of the same type.
632 MapIterator TmpIt = ATMEntryIt;
634 // First check the entry before this one...
635 if (TmpIt != Map.begin()) {
637 if (TmpIt->first.first != Ty) // Not the same type, move back...
641 // If we didn't find the same type, try to move forward...
642 if (TmpIt == ATMEntryIt) {
644 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
645 --TmpIt; // No entry afterwards with the same type
648 // If there is another entry in the map of the same abstract type,
649 // update the AbstractTypeMap entry now.
650 if (TmpIt != ATMEntryIt) {
653 // Otherwise, we are removing the last instance of this type
654 // from the table. Remove from the ATM, and from user list.
655 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
656 AbstractTypeMap.erase(Ty);
664 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
665 typename AbstractTypeMapTy::iterator I =
666 AbstractTypeMap.find(cast<TypeClass>(OldTy));
668 assert(I != AbstractTypeMap.end() &&
669 "Abstract type not in AbstractTypeMap?");
671 // Convert a constant at a time until the last one is gone. The last one
672 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
673 // eliminated eventually.
675 ConvertConstantType<ConstantClass,
676 TypeClass>::convert(I->second->second,
677 cast<TypeClass>(NewTy));
679 I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
680 } while (I != AbstractTypeMap.end());
683 // If the type became concrete without being refined to any other existing
684 // type, we just remove ourselves from the ATU list.
685 void typeBecameConcrete(const DerivedType *AbsTy) {
686 AbsTy->removeAbstractTypeUser(this);
690 std::cerr << "Constant.cpp: ValueMap\n";
697 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
699 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
700 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
702 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
703 return SIntConstants.getOrCreate(Ty, V);
706 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
707 return UIntConstants.getOrCreate(Ty, V);
710 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
711 assert(V <= 127 && "Can only be used with very small positive constants!");
712 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
713 return ConstantUInt::get(Ty, V);
716 //---- ConstantFP::get() implementation...
720 struct ConstantCreator<ConstantFP, Type, uint64_t> {
721 static ConstantFP *create(const Type *Ty, uint64_t V) {
722 assert(Ty == Type::DoubleTy);
728 return new ConstantFP(Ty, T.F);
732 struct ConstantCreator<ConstantFP, Type, uint32_t> {
733 static ConstantFP *create(const Type *Ty, uint32_t V) {
734 assert(Ty == Type::FloatTy);
740 return new ConstantFP(Ty, T.F);
745 static ValueMap<uint64_t, Type, ConstantFP> DoubleConstants;
746 static ValueMap<uint32_t, Type, ConstantFP> FloatConstants;
748 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
749 if (Ty == Type::FloatTy) {
750 // Force the value through memory to normalize it.
756 return FloatConstants.getOrCreate(Ty, T.I);
758 assert(Ty == Type::DoubleTy);
764 return DoubleConstants.getOrCreate(Ty, T.I);
768 //---- ConstantArray::get() implementation...
772 struct ConvertConstantType<ConstantArray, ArrayType> {
773 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
774 // Make everyone now use a constant of the new type...
775 std::vector<Constant*> C;
776 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
777 C.push_back(cast<Constant>(OldC->getOperand(i)));
778 Constant *New = ConstantArray::get(NewTy, C);
779 assert(New != OldC && "Didn't replace constant??");
780 OldC->uncheckedReplaceAllUsesWith(New);
781 OldC->destroyConstant(); // This constant is now dead, destroy it.
786 static ValueMap<std::vector<Constant*>, ArrayType,
787 ConstantArray> ArrayConstants;
789 ConstantArray *ConstantArray::get(const ArrayType *Ty,
790 const std::vector<Constant*> &V) {
791 return ArrayConstants.getOrCreate(Ty, V);
794 // destroyConstant - Remove the constant from the constant table...
796 void ConstantArray::destroyConstant() {
797 ArrayConstants.remove(this);
798 destroyConstantImpl();
801 // ConstantArray::get(const string&) - Return an array that is initialized to
802 // contain the specified string. A null terminator is added to the specified
803 // string so that it may be used in a natural way...
805 ConstantArray *ConstantArray::get(const std::string &Str) {
806 std::vector<Constant*> ElementVals;
808 for (unsigned i = 0; i < Str.length(); ++i)
809 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
811 // Add a null terminator to the string...
812 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
814 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
815 return ConstantArray::get(ATy, ElementVals);
818 /// isString - This method returns true if the array is an array of sbyte or
819 /// ubyte, and if the elements of the array are all ConstantInt's.
820 bool ConstantArray::isString() const {
821 // Check the element type for sbyte or ubyte...
822 if (getType()->getElementType() != Type::UByteTy &&
823 getType()->getElementType() != Type::SByteTy)
825 // Check the elements to make sure they are all integers, not constant
827 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
828 if (!isa<ConstantInt>(getOperand(i)))
833 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
834 // then this method converts the array to an std::string and returns it.
835 // Otherwise, it asserts out.
837 std::string ConstantArray::getAsString() const {
838 assert(isString() && "Not a string!");
840 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
841 Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
846 //---- ConstantStruct::get() implementation...
851 struct ConvertConstantType<ConstantStruct, StructType> {
852 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
853 // Make everyone now use a constant of the new type...
854 std::vector<Constant*> C;
855 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
856 C.push_back(cast<Constant>(OldC->getOperand(i)));
857 Constant *New = ConstantStruct::get(NewTy, C);
858 assert(New != OldC && "Didn't replace constant??");
860 OldC->uncheckedReplaceAllUsesWith(New);
861 OldC->destroyConstant(); // This constant is now dead, destroy it.
866 static ValueMap<std::vector<Constant*>, StructType,
867 ConstantStruct> StructConstants;
869 ConstantStruct *ConstantStruct::get(const StructType *Ty,
870 const std::vector<Constant*> &V) {
871 return StructConstants.getOrCreate(Ty, V);
874 // destroyConstant - Remove the constant from the constant table...
876 void ConstantStruct::destroyConstant() {
877 StructConstants.remove(this);
878 destroyConstantImpl();
881 //---- ConstantPointerNull::get() implementation...
885 // ConstantPointerNull does not take extra "value" argument...
886 template<class ValType>
887 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
888 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
889 return new ConstantPointerNull(Ty);
894 struct ConvertConstantType<ConstantPointerNull, PointerType> {
895 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
896 // Make everyone now use a constant of the new type...
897 Constant *New = ConstantPointerNull::get(NewTy);
898 assert(New != OldC && "Didn't replace constant??");
899 OldC->uncheckedReplaceAllUsesWith(New);
900 OldC->destroyConstant(); // This constant is now dead, destroy it.
905 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
907 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
908 return NullPtrConstants.getOrCreate(Ty, 0);
911 // destroyConstant - Remove the constant from the constant table...
913 void ConstantPointerNull::destroyConstant() {
914 NullPtrConstants.remove(this);
915 destroyConstantImpl();
919 //---- ConstantPointerRef::get() implementation...
921 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
922 assert(GV->getParent() && "Global Value must be attached to a module!");
924 // The Module handles the pointer reference sharing...
925 return GV->getParent()->getConstantPointerRef(GV);
928 // destroyConstant - Remove the constant from the constant table...
930 void ConstantPointerRef::destroyConstant() {
931 getValue()->getParent()->destroyConstantPointerRef(this);
932 destroyConstantImpl();
936 //---- ConstantExpr::get() implementations...
938 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
942 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
943 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
944 if (V.first == Instruction::Cast)
945 return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
946 if ((V.first >= Instruction::BinaryOpsBegin &&
947 V.first < Instruction::BinaryOpsEnd) ||
948 V.first == Instruction::Shl || V.first == Instruction::Shr)
949 return new ConstantExpr(V.first, V.second[0], V.second[1]);
951 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
953 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
954 return new ConstantExpr(V.second[0], IdxList, Ty);
959 struct ConvertConstantType<ConstantExpr, Type> {
960 static void convert(ConstantExpr *OldC, const Type *NewTy) {
962 switch (OldC->getOpcode()) {
963 case Instruction::Cast:
964 New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
966 case Instruction::Shl:
967 case Instruction::Shr:
968 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
969 OldC->getOperand(0), OldC->getOperand(1));
972 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
973 OldC->getOpcode() < Instruction::BinaryOpsEnd);
974 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
975 OldC->getOperand(1));
977 case Instruction::GetElementPtr:
978 // Make everyone now use a constant of the new type...
979 std::vector<Constant*> C;
980 for (unsigned i = 1, e = OldC->getNumOperands(); i != e; ++i)
981 C.push_back(cast<Constant>(OldC->getOperand(i)));
982 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), C);
986 assert(New != OldC && "Didn't replace constant??");
987 OldC->uncheckedReplaceAllUsesWith(New);
988 OldC->destroyConstant(); // This constant is now dead, destroy it.
991 } // end namespace llvm
994 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
996 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
997 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
999 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1000 return FC; // Fold a few common cases...
1002 // Look up the constant in the table first to ensure uniqueness
1003 std::vector<Constant*> argVec(1, C);
1004 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1005 return ExprConstants.getOrCreate(Ty, Key);
1008 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1009 Constant *C1, Constant *C2) {
1010 if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1011 return getShiftTy(ReqTy, Opcode, C1, C2);
1012 // Check the operands for consistency first
1013 assert((Opcode >= Instruction::BinaryOpsBegin &&
1014 Opcode < Instruction::BinaryOpsEnd) &&
1015 "Invalid opcode in binary constant expression");
1016 assert(C1->getType() == C2->getType() &&
1017 "Operand types in binary constant expression should match");
1019 if (ReqTy == C1->getType())
1020 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1021 return FC; // Fold a few common cases...
1023 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1024 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1025 return ExprConstants.getOrCreate(ReqTy, Key);
1028 /// getShiftTy - Return a shift left or shift right constant expr
1029 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1030 Constant *C1, Constant *C2) {
1031 // Check the operands for consistency first
1032 assert((Opcode == Instruction::Shl ||
1033 Opcode == Instruction::Shr) &&
1034 "Invalid opcode in binary constant expression");
1035 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1036 "Invalid operand types for Shift constant expr!");
1038 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1039 return FC; // Fold a few common cases...
1041 // Look up the constant in the table first to ensure uniqueness
1042 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1043 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1044 return ExprConstants.getOrCreate(ReqTy, Key);
1048 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1049 const std::vector<Constant*> &IdxList) {
1050 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1051 return FC; // Fold a few common cases...
1052 assert(isa<PointerType>(C->getType()) &&
1053 "Non-pointer type for constant GetElementPtr expression");
1055 // Look up the constant in the table first to ensure uniqueness
1056 std::vector<Constant*> argVec(1, C);
1057 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
1058 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,argVec);
1059 return ExprConstants.getOrCreate(ReqTy, Key);
1062 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1063 const std::vector<Constant*> &IdxList){
1064 // Get the result type of the getelementptr!
1065 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1067 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1069 assert(Ty && "GEP indices invalid!");
1071 if (C->isNullValue()) {
1073 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1074 if (!IdxList[i]->isNullValue()) {
1078 if (isNull) return ConstantPointerNull::get(PointerType::get(Ty));
1081 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1085 // destroyConstant - Remove the constant from the constant table...
1087 void ConstantExpr::destroyConstant() {
1088 ExprConstants.remove(this);
1089 destroyConstantImpl();
1092 const char *ConstantExpr::getOpcodeName() const {
1093 return Instruction::getOpcodeName(getOpcode());
1096 unsigned Constant::mutateReferences(Value *OldV, Value *NewV) {
1097 // Uses of constant pointer refs are global values, not constants!
1098 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
1099 GlobalValue *NewGV = cast<GlobalValue>(NewV);
1100 GlobalValue *OldGV = CPR->getValue();
1102 assert(OldGV == OldV && "Cannot mutate old value if I'm not using it!");
1103 Operands[0] = NewGV;
1104 OldGV->getParent()->mutateConstantPointerRef(OldGV, NewGV);
1107 Constant *NewC = cast<Constant>(NewV);
1108 unsigned NumReplaced = 0;
1109 for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
1110 if (Operands[i] == OldV) {