blob: fb4063a5ca54446f010dcfa1e3e10a7ead2cfce5 [file] [log] [blame]
Chris Lattner00950542001-06-06 20:29:01 +00001//===-- Type.cpp - Implement the Type class ----------------------*- C++ -*--=//
2//
3// This file implements the Type class for the VMCore library.
4//
5//===----------------------------------------------------------------------===//
6
7#include "llvm/DerivedTypes.h"
Chris Lattner57dbb3a2001-07-23 17:46:59 +00008#include "llvm/Support/StringExtras.h"
Chris Lattnerc038a2f2001-09-07 16:56:42 +00009#include "llvm/SymbolTable.h"
10#include "llvm/Support/STLExtras.h"
11
12// DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
13// created and later destroyed, all in an effort to make sure that there is only
14// a single cannonical version of a type.
15//
16//#define DEBUG_MERGE_TYPES 1
17
18
Chris Lattner00950542001-06-06 20:29:01 +000019
20//===----------------------------------------------------------------------===//
21// Type Class Implementation
22//===----------------------------------------------------------------------===//
23
24static unsigned CurUID = 0;
25static vector<const Type *> UIDMappings;
26
Chris Lattnerc038a2f2001-09-07 16:56:42 +000027Type::Type(const string &name, PrimitiveID id)
28 : Value(Type::TypeTy, Value::TypeVal) {
29 setDescription(name);
Chris Lattner00950542001-06-06 20:29:01 +000030 ID = id;
Chris Lattnerc038a2f2001-09-07 16:56:42 +000031 Abstract = false;
Chris Lattner00950542001-06-06 20:29:01 +000032 UID = CurUID++; // Assign types UID's as they are created
33 UIDMappings.push_back(this);
34}
35
Chris Lattnerc038a2f2001-09-07 16:56:42 +000036void Type::setName(const string &Name, SymbolTable *ST) {
37 assert(ST && "Type::setName - Must provide symbol table argument!");
38
39 if (Name.size()) ST->insert(Name, this);
40}
41
42
Chris Lattner00950542001-06-06 20:29:01 +000043const Type *Type::getUniqueIDType(unsigned UID) {
44 assert(UID < UIDMappings.size() &&
45 "Type::getPrimitiveType: UID out of range!");
46 return UIDMappings[UID];
47}
48
49const Type *Type::getPrimitiveType(PrimitiveID IDNumber) {
50 switch (IDNumber) {
51 case VoidTyID : return VoidTy;
52 case BoolTyID : return BoolTy;
53 case UByteTyID : return UByteTy;
54 case SByteTyID : return SByteTy;
55 case UShortTyID: return UShortTy;
56 case ShortTyID : return ShortTy;
57 case UIntTyID : return UIntTy;
58 case IntTyID : return IntTy;
59 case ULongTyID : return ULongTy;
60 case LongTyID : return LongTy;
61 case FloatTyID : return FloatTy;
62 case DoubleTyID: return DoubleTy;
63 case TypeTyID : return TypeTy;
64 case LabelTyID : return LabelTy;
Chris Lattner00950542001-06-06 20:29:01 +000065 default:
66 return 0;
67 }
68}
69
Chris Lattner00950542001-06-06 20:29:01 +000070//===----------------------------------------------------------------------===//
71// Auxilliary classes
72//===----------------------------------------------------------------------===//
73//
74// These classes are used to implement specialized behavior for each different
75// type.
76//
77class SignedIntType : public Type {
78 int Size;
79public:
80 SignedIntType(const string &Name, PrimitiveID id, int size) : Type(Name, id) {
81 Size = size;
82 }
83
84 // isSigned - Return whether a numeric type is signed.
85 virtual bool isSigned() const { return 1; }
Chris Lattner1a2cefc2001-07-21 19:15:26 +000086
87 // isIntegral - Equivalent to isSigned() || isUnsigned, but with only a single
88 // virtual function invocation.
89 //
Vikram S. Advea4e6f882001-07-21 12:32:48 +000090 virtual bool isIntegral() const { return 1; }
Chris Lattner00950542001-06-06 20:29:01 +000091};
92
93class UnsignedIntType : public Type {
94 uint64_t Size;
95public:
96 UnsignedIntType(const string &N, PrimitiveID id, int size) : Type(N, id) {
97 Size = size;
98 }
99
100 // isUnsigned - Return whether a numeric type is signed.
101 virtual bool isUnsigned() const { return 1; }
Chris Lattner1a2cefc2001-07-21 19:15:26 +0000102
103 // isIntegral - Equivalent to isSigned() || isUnsigned, but with only a single
104 // virtual function invocation.
105 //
Vikram S. Advea4e6f882001-07-21 12:32:48 +0000106 virtual bool isIntegral() const { return 1; }
Chris Lattner00950542001-06-06 20:29:01 +0000107};
108
109static struct TypeType : public Type {
110 TypeType() : Type("type", TypeTyID) {}
111} TheTypeType; // Implement the type that is global.
112
113
114//===----------------------------------------------------------------------===//
115// Static 'Type' data
116//===----------------------------------------------------------------------===//
117
Chris Lattnerca24d382001-09-10 20:11:44 +0000118Type *Type::VoidTy = new Type("void" , VoidTyID),
119 *Type::BoolTy = new Type("bool" , BoolTyID),
120 *Type::SByteTy = new SignedIntType("sbyte" , SByteTyID, 1),
121 *Type::UByteTy = new UnsignedIntType("ubyte" , UByteTyID, 1),
122 *Type::ShortTy = new SignedIntType("short" , ShortTyID, 2),
123 *Type::UShortTy = new UnsignedIntType("ushort", UShortTyID, 2),
124 *Type::IntTy = new SignedIntType("int" , IntTyID, 4),
125 *Type::UIntTy = new UnsignedIntType("uint" , UIntTyID, 4),
126 *Type::LongTy = new SignedIntType("long" , LongTyID, 8),
127 *Type::ULongTy = new UnsignedIntType("ulong" , ULongTyID, 8),
128 *Type::FloatTy = new Type("float" , FloatTyID),
129 *Type::DoubleTy = new Type("double", DoubleTyID),
130 *Type::TypeTy = &TheTypeType,
131 *Type::LabelTy = new Type("label" , LabelTyID);
Chris Lattner00950542001-06-06 20:29:01 +0000132
133
134//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +0000135// Derived Type Constructors
136//===----------------------------------------------------------------------===//
137
138MethodType::MethodType(const Type *Result, const vector<const Type*> &Params,
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000139 bool IsVarArgs) : DerivedType("", MethodTyID),
140 ResultType(PATypeHandle<Type>(Result, this)),
Chris Lattnere5a57ee2001-07-25 22:47:55 +0000141 isVarArgs(IsVarArgs) {
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000142 ParamTys.reserve(Params.size());
Chris Lattner56c5acb2001-10-13 07:01:33 +0000143 for (unsigned i = 0; i < Params.size(); ++i)
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000144 ParamTys.push_back(PATypeHandle<Type>(Params[i], this));
145
146 setDerivedTypeProperties();
Chris Lattner00950542001-06-06 20:29:01 +0000147}
148
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000149ArrayType::ArrayType(const Type *ElType, int NumEl)
150 : DerivedType("", ArrayTyID), ElementType(PATypeHandle<Type>(ElType, this)) {
Chris Lattner00950542001-06-06 20:29:01 +0000151 NumElements = NumEl;
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000152 setDerivedTypeProperties();
Chris Lattner00950542001-06-06 20:29:01 +0000153}
154
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000155StructType::StructType(const vector<const Type*> &Types)
156 : DerivedType("", StructTyID) {
157 ETypes.reserve(Types.size());
Chris Lattner56c5acb2001-10-13 07:01:33 +0000158 for (unsigned i = 0; i < Types.size(); ++i) {
159 assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000160 ETypes.push_back(PATypeHandle<Type>(Types[i], this));
Chris Lattner56c5acb2001-10-13 07:01:33 +0000161 }
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000162 setDerivedTypeProperties();
Chris Lattner00950542001-06-06 20:29:01 +0000163}
164
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000165PointerType::PointerType(const Type *E) : DerivedType("", PointerTyID),
166 ValueType(PATypeHandle<Type>(E, this)) {
167 setDerivedTypeProperties();
Chris Lattner00950542001-06-06 20:29:01 +0000168}
169
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000170OpaqueType::OpaqueType() : DerivedType("", OpaqueTyID) {
171 setAbstract(true);
172 setDescription("opaque"+utostr(getUniqueID()));
173#ifdef DEBUG_MERGE_TYPES
174 cerr << "Derived new type: " << getDescription() << endl;
175#endif
176}
177
178
179
180
Chris Lattner00950542001-06-06 20:29:01 +0000181//===----------------------------------------------------------------------===//
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000182// Derived Type setDerivedTypeProperties Function
Chris Lattner00950542001-06-06 20:29:01 +0000183//===----------------------------------------------------------------------===//
184
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000185// getTypeProps - This is a recursive function that walks a type hierarchy
186// calculating the description for a type and whether or not it is abstract or
187// recursive. Worst case it will have to do a lot of traversing if you have
188// some whacko opaque types, but in most cases, it will do some simple stuff
189// when it hits non-abstract types that aren't recursive.
190//
191static string getTypeProps(const Type *Ty, vector<const Type *> &TypeStack,
192 bool &isAbstract, bool &isRecursive) {
193 string Result;
194 if (!Ty->isAbstract() && !Ty->isRecursive() && // Base case for the recursion
195 Ty->getDescription().size()) {
196 Result = Ty->getDescription(); // Primitive = leaf type
Chris Lattnerb00c5822001-10-02 03:41:24 +0000197 } else if (isa<OpaqueType>(Ty)) { // Base case for the recursion
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000198 Result = Ty->getDescription(); // Opaque = leaf type
199 isAbstract = true; // This whole type is abstract!
200 } else {
201 // Check to see if the Type is already on the stack...
202 unsigned Slot = 0, CurSize = TypeStack.size();
203 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
204
205 // This is another base case for the recursion. In this case, we know
206 // that we have looped back to a type that we have previously visited.
207 // Generate the appropriate upreference to handle this.
208 //
209 if (Slot < CurSize) {
210 Result = "\\" + utostr(CurSize-Slot); // Here's the upreference
211 isRecursive = true; // We know we are recursive
212 } else { // Recursive case: abstract derived type...
213 TypeStack.push_back(Ty); // Add us to the stack..
214
215 switch (Ty->getPrimitiveID()) {
216 case Type::MethodTyID: {
Chris Lattnerb00c5822001-10-02 03:41:24 +0000217 const MethodType *MTy = cast<const MethodType>(Ty);
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000218 Result = getTypeProps(MTy->getReturnType(), TypeStack,
219 isAbstract, isRecursive)+" (";
220 for (MethodType::ParamTypes::const_iterator
221 I = MTy->getParamTypes().begin(),
222 E = MTy->getParamTypes().end(); I != E; ++I) {
223 if (I != MTy->getParamTypes().begin())
224 Result += ", ";
225 Result += getTypeProps(*I, TypeStack, isAbstract, isRecursive);
226 }
227 if (MTy->isVarArg()) {
228 if (!MTy->getParamTypes().empty()) Result += ", ";
229 Result += "...";
230 }
231 Result += ")";
232 break;
233 }
234 case Type::StructTyID: {
Chris Lattnerb00c5822001-10-02 03:41:24 +0000235 const StructType *STy = cast<const StructType>(Ty);
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000236 Result = "{ ";
237 for (StructType::ElementTypes::const_iterator
238 I = STy->getElementTypes().begin(),
239 E = STy->getElementTypes().end(); I != E; ++I) {
240 if (I != STy->getElementTypes().begin())
241 Result += ", ";
242 Result += getTypeProps(*I, TypeStack, isAbstract, isRecursive);
243 }
244 Result += " }";
245 break;
246 }
247 case Type::PointerTyID: {
Chris Lattnerb00c5822001-10-02 03:41:24 +0000248 const PointerType *PTy = cast<const PointerType>(Ty);
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000249 Result = getTypeProps(PTy->getValueType(), TypeStack,
250 isAbstract, isRecursive) + " *";
251 break;
252 }
253 case Type::ArrayTyID: {
Chris Lattnerb00c5822001-10-02 03:41:24 +0000254 const ArrayType *ATy = cast<const ArrayType>(Ty);
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000255 int NumElements = ATy->getNumElements();
256 Result = "[";
257 if (NumElements != -1) Result += itostr(NumElements) + " x ";
258 Result += getTypeProps(ATy->getElementType(), TypeStack,
259 isAbstract, isRecursive) + "]";
260 break;
261 }
262 default:
263 assert(0 && "Unhandled case in getTypeProps!");
264 Result = "<error>";
265 }
266
267 TypeStack.pop_back(); // Remove self from stack...
268 }
269 }
270 return Result;
271}
272
273
274// setDerivedTypeProperties - This function is used to calculate the
275// isAbstract, isRecursive, and the Description settings for a type. The
276// getTypeProps function does all the dirty work.
277//
278void DerivedType::setDerivedTypeProperties() {
279 vector<const Type *> TypeStack;
280 bool isAbstract = false, isRecursive = false;
281
282 setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
283 setAbstract(isAbstract);
284 setRecursive(isRecursive);
285}
286
287
288//===----------------------------------------------------------------------===//
289// Type Structural Equality Testing
290//===----------------------------------------------------------------------===//
291
292// TypesEqual - Two types are considered structurally equal if they have the
293// same "shape": Every level and element of the types have identical primitive
294// ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
295// be pointer equals to be equivalent though. This uses an optimistic algorithm
296// that assumes that two graphs are the same until proven otherwise.
297//
298static bool TypesEqual(const Type *Ty, const Type *Ty2,
299 map<const Type *, const Type *> &EqTypes) {
300 if (Ty == Ty2) return true;
301 if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
302 if (Ty->isPrimitiveType()) return true;
303
304 if (Ty != Ty2) {
305 map<const Type*, const Type*>::iterator I = EqTypes.find(Ty);
306 if (I != EqTypes.end())
307 return I->second == Ty2; // Looping back on a type, check for equality
308
309 // Otherwise, add the mapping to the table to make sure we don't get
310 // recursion on the types...
311 EqTypes.insert(make_pair(Ty, Ty2));
312 }
313
314 // Iterate over the types and make sure the the contents are equivalent...
Chris Lattner74c2b762001-09-09 22:26:58 +0000315 Type::subtype_iterator I = Ty ->subtype_begin(), IE = Ty ->subtype_end();
316 Type::subtype_iterator I2 = Ty2->subtype_begin(), IE2 = Ty2->subtype_end();
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000317 for (; I != IE && I2 != IE2; ++I, ++I2)
318 if (!TypesEqual(*I, *I2, EqTypes)) return false;
319
Chris Lattner56c5acb2001-10-13 07:01:33 +0000320 // Two really annoying special cases that breaks an otherwise nice simple
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000321 // algorithm is the fact that arraytypes have sizes that differentiates types,
Chris Lattner56c5acb2001-10-13 07:01:33 +0000322 // and that method types can be varargs or not. Consider this now.
323 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
324 if (ATy->getNumElements() != cast<const ArrayType>(Ty2)->getNumElements())
325 return false;
326 } else if (const MethodType *MTy = dyn_cast<MethodType>(Ty)) {
327 if (MTy->isVarArg() != cast<const MethodType>(Ty2)->isVarArg())
328 return false;
329 }
330
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000331
332 return I == IE && I2 == IE2; // Types equal if both iterators are done
333}
334
335static bool TypesEqual(const Type *Ty, const Type *Ty2) {
336 map<const Type *, const Type *> EqTypes;
337 return TypesEqual(Ty, Ty2, EqTypes);
338}
339
340
341
342//===----------------------------------------------------------------------===//
343// Derived Type Factory Functions
344//===----------------------------------------------------------------------===//
345
346// TypeMap - Make sure that only one instance of a particular type may be
347// created on any given run of the compiler... note that this involves updating
348// our map if an abstract type gets refined somehow...
349//
350template<class ValType, class TypeClass>
351class TypeMap : public AbstractTypeUser {
352 typedef map<ValType, PATypeHandle<TypeClass> > MapTy;
353 MapTy Map;
354public:
355
356 ~TypeMap() { print("ON EXIT"); }
357
358 inline TypeClass *get(const ValType &V) {
359 map<ValType, PATypeHandle<TypeClass> >::iterator I = Map.find(V);
360 // TODO: FIXME: When Types are not CONST.
361 return (I != Map.end()) ? (TypeClass*)I->second.get() : 0;
362 }
363
364 inline void add(const ValType &V, TypeClass *T) {
365 Map.insert(make_pair(V, PATypeHandle<TypeClass>(T, this)));
366 print("add");
367 }
368
369 // containsEquivalent - Return true if the typemap contains a type that is
370 // structurally equivalent to the specified type.
371 //
372 inline const TypeClass *containsEquivalent(const TypeClass *Ty) {
373 for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
374 if (I->second.get() != Ty && TypesEqual(Ty, I->second.get()))
375 return (TypeClass*)I->second.get(); // FIXME TODO when types not const
376 return 0;
377 }
378
379 // refineAbstractType - This is called when one of the contained abstract
380 // types gets refined... this simply removes the abstract type from our table.
381 // We expect that whoever refined the type will add it back to the table,
382 // corrected.
383 //
384 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
385 if (OldTy == NewTy) return;
386#ifdef DEBUG_MERGE_TYPES
387 cerr << "Removing Old type from Tab: " << (void*)OldTy << ", "
388 << OldTy->getDescription() << " replacement == " << (void*)NewTy
389 << ", " << NewTy->getDescription() << endl;
390#endif
391 for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
392 if (I->second == OldTy) {
393 Map.erase(I);
394 print("refineAbstractType after");
395 return;
396 }
397 assert(0 && "Abstract type not found in table!");
398 }
399
400 void remove(const ValType &OldVal) {
401 MapTy::iterator I = Map.find(OldVal);
402 assert(I != Map.end() && "TypeMap::remove, element not found!");
403 Map.erase(I);
404 }
405
406 void print(const char *Arg) {
407#ifdef DEBUG_MERGE_TYPES
408 cerr << "TypeMap<>::" << Arg << " table contents:\n";
409 unsigned i = 0;
410 for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
411 cerr << " " << (++i) << ". " << I->second << " "
412 << I->second->getDescription() << endl;
413#endif
414 }
415};
416
417
418// ValTypeBase - This is the base class that is used by the various
419// instantiations of TypeMap. This class is an AbstractType user that notifies
420// the underlying TypeMap when it gets modified.
421//
422template<class ValType, class TypeClass>
423class ValTypeBase : public AbstractTypeUser {
424 TypeMap<ValType, TypeClass> &MyTable;
425protected:
426 inline ValTypeBase(TypeMap<ValType, TypeClass> &tab) : MyTable(tab) {}
427
428 // Subclass should override this... to update self as usual
429 virtual void doRefinement(const DerivedType *OldTy, const Type *NewTy) = 0;
430
431 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
432 if (OldTy == NewTy) return;
433 TypeMap<ValType, TypeClass> &Table = MyTable; // Copy MyTable reference
434 ValType Tmp(*(ValType*)this); // Copy this.
435 PATypeHandle<TypeClass> OldType(Table.get(*(ValType*)this), this);
436 Table.remove(*(ValType*)this); // Destroy's this!
437
438 // Refine temporary to new state...
439 Tmp.doRefinement(OldTy, NewTy);
440
441 Table.add((ValType&)Tmp, (TypeClass*)OldType.get());
442 }
443};
444
445
446
447//===----------------------------------------------------------------------===//
448// Method Type Factory and Value Class...
449//
450
451// MethodValType - Define a class to hold the key that goes into the TypeMap
452//
453class MethodValType : public ValTypeBase<MethodValType, MethodType> {
454 PATypeHandle<Type> RetTy;
455 vector<PATypeHandle<Type> > ArgTypes;
Chris Lattner56c5acb2001-10-13 07:01:33 +0000456 bool isVarArg;
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000457public:
458 MethodValType(const Type *ret, const vector<const Type*> &args,
Chris Lattner56c5acb2001-10-13 07:01:33 +0000459 bool IVA, TypeMap<MethodValType, MethodType> &Tab)
460 : ValTypeBase<MethodValType, MethodType>(Tab), RetTy(ret, this),
461 isVarArg(IVA) {
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000462 for (unsigned i = 0; i < args.size(); ++i)
463 ArgTypes.push_back(PATypeHandle<Type>(args[i], this));
464 }
465
466 // We *MUST* have an explicit copy ctor so that the TypeHandles think that
467 // this MethodValType owns them, not the old one!
468 //
469 MethodValType(const MethodValType &MVT)
Chris Lattner56c5acb2001-10-13 07:01:33 +0000470 : ValTypeBase<MethodValType, MethodType>(MVT), RetTy(MVT.RetTy, this),
471 isVarArg(MVT.isVarArg) {
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000472 ArgTypes.reserve(MVT.ArgTypes.size());
473 for (unsigned i = 0; i < MVT.ArgTypes.size(); ++i)
474 ArgTypes.push_back(PATypeHandle<Type>(MVT.ArgTypes[i], this));
475 }
476
477 // Subclass should override this... to update self as usual
478 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
479 if (RetTy == OldType) RetTy = NewType;
480 for (unsigned i = 0; i < ArgTypes.size(); ++i)
481 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
482 }
483
484 inline bool operator<(const MethodValType &MTV) const {
Chris Lattner56c5acb2001-10-13 07:01:33 +0000485 if (RetTy.get() < MTV.RetTy.get()) return true;
486 if (RetTy.get() > MTV.RetTy.get()) return false;
487
488 if (ArgTypes < MTV.ArgTypes) return true;
489 return (ArgTypes == MTV.ArgTypes) && isVarArg < MTV.isVarArg;
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000490 }
491};
492
493// Define the actual map itself now...
494static TypeMap<MethodValType, MethodType> MethodTypes;
495
496// MethodType::get - The factory function for the MethodType class...
497MethodType *MethodType::get(const Type *ReturnType,
Chris Lattner56c5acb2001-10-13 07:01:33 +0000498 const vector<const Type*> &Params,
499 bool isVarArg) {
500 MethodValType VT(ReturnType, Params, isVarArg, MethodTypes);
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000501 MethodType *MT = MethodTypes.get(VT);
502 if (MT) return MT;
Chris Lattnere5a57ee2001-07-25 22:47:55 +0000503
Chris Lattner56c5acb2001-10-13 07:01:33 +0000504 MethodTypes.add(VT, MT = new MethodType(ReturnType, Params, isVarArg));
Chris Lattnere5a57ee2001-07-25 22:47:55 +0000505
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000506#ifdef DEBUG_MERGE_TYPES
507 cerr << "Derived new type: " << MT << endl;
Chris Lattner00950542001-06-06 20:29:01 +0000508#endif
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000509 return MT;
Chris Lattner00950542001-06-06 20:29:01 +0000510}
511
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000512//===----------------------------------------------------------------------===//
513// Array Type Factory...
514//
515class ArrayValType : public ValTypeBase<ArrayValType, ArrayType> {
516 PATypeHandle<Type> ValTy;
517 int Size;
518public:
519 ArrayValType(const Type *val, int sz, TypeMap<ArrayValType, ArrayType> &Tab)
520 : ValTypeBase<ArrayValType, ArrayType>(Tab), ValTy(val, this), Size(sz) {}
Chris Lattner00950542001-06-06 20:29:01 +0000521
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000522 // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
523 // ArrayValType owns it, not the old one!
524 //
525 ArrayValType(const ArrayValType &AVT)
526 : ValTypeBase<ArrayValType, ArrayType>(AVT), ValTy(AVT.ValTy, this),
527 Size(AVT.Size) {}
Chris Lattner00950542001-06-06 20:29:01 +0000528
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000529 // Subclass should override this... to update self as usual
530 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
531 if (ValTy == OldType) ValTy = NewType;
Chris Lattner00950542001-06-06 20:29:01 +0000532 }
533
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000534 inline bool operator<(const ArrayValType &MTV) const {
535 if (Size < MTV.Size) return true;
536 return Size == MTV.Size && ValTy.get() < MTV.ValTy.get();
537 }
538};
539
540static TypeMap<ArrayValType, ArrayType> ArrayTypes;
541
542ArrayType *ArrayType::get(const Type *ElementType, int NumElements = -1) {
543 assert(ElementType && "Can't get array of null types!");
544
545 ArrayValType AVT(ElementType, NumElements, ArrayTypes);
546 ArrayType *AT = ArrayTypes.get(AVT);
547 if (AT) return AT; // Found a match, return it!
548
Chris Lattner00950542001-06-06 20:29:01 +0000549 // Value not found. Derive a new type!
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000550 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
Chris Lattner00950542001-06-06 20:29:01 +0000551
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000552#ifdef DEBUG_MERGE_TYPES
553 cerr << "Derived new type: " << AT->getDescription() << endl;
Chris Lattner00950542001-06-06 20:29:01 +0000554#endif
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000555 return AT;
Chris Lattner00950542001-06-06 20:29:01 +0000556}
557
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000558//===----------------------------------------------------------------------===//
559// Struct Type Factory...
560//
Chris Lattner00950542001-06-06 20:29:01 +0000561
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000562// StructValType - Define a class to hold the key that goes into the TypeMap
563//
564class StructValType : public ValTypeBase<StructValType, StructType> {
565 vector<PATypeHandle<Type> > ElTypes;
566public:
567 StructValType(const vector<const Type*> &args,
568 TypeMap<StructValType, StructType> &Tab)
569 : ValTypeBase<StructValType, StructType>(Tab) {
570 for (unsigned i = 0; i < args.size(); ++i)
571 ElTypes.push_back(PATypeHandle<Type>(args[i], this));
572 }
Chris Lattner00950542001-06-06 20:29:01 +0000573
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000574 // We *MUST* have an explicit copy ctor so that the TypeHandles think that
575 // this StructValType owns them, not the old one!
576 //
577 StructValType(const StructValType &SVT)
578 : ValTypeBase<StructValType, StructType>(SVT){
579 ElTypes.reserve(SVT.ElTypes.size());
580 for (unsigned i = 0; i < SVT.ElTypes.size(); ++i)
581 ElTypes.push_back(PATypeHandle<Type>(SVT.ElTypes[i], this));
582 }
583
584 // Subclass should override this... to update self as usual
585 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
586 for (unsigned i = 0; i < ElTypes.size(); ++i)
587 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
588 }
589
590 inline bool operator<(const StructValType &STV) const {
591 return ElTypes < STV.ElTypes;
592 }
593};
594
595static TypeMap<StructValType, StructType> StructTypes;
596
597StructType *StructType::get(const vector<const Type*> &ETypes) {
598 StructValType STV(ETypes, StructTypes);
599 StructType *ST = StructTypes.get(STV);
600 if (ST) return ST;
601
602 // Value not found. Derive a new type!
603 StructTypes.add(STV, ST = new StructType(ETypes));
604
605#ifdef DEBUG_MERGE_TYPES
606 cerr << "Derived new type: " << ST->getDescription() << endl;
Chris Lattner00950542001-06-06 20:29:01 +0000607#endif
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000608 return ST;
609}
610
611//===----------------------------------------------------------------------===//
612// Pointer Type Factory...
613//
614
615// PointerValType - Define a class to hold the key that goes into the TypeMap
616//
617class PointerValType : public ValTypeBase<PointerValType, PointerType> {
618 PATypeHandle<Type> ValTy;
619public:
620 PointerValType(const Type *val, TypeMap<PointerValType, PointerType> &Tab)
621 : ValTypeBase<PointerValType, PointerType>(Tab), ValTy(val, this) {}
622
623 // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
624 // PointerValType owns it, not the old one!
625 //
626 PointerValType(const PointerValType &PVT)
627 : ValTypeBase<PointerValType, PointerType>(PVT), ValTy(PVT.ValTy, this) {}
628
629 // Subclass should override this... to update self as usual
630 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
631 if (ValTy == OldType) ValTy = NewType;
632 }
633
634 inline bool operator<(const PointerValType &MTV) const {
635 return ValTy.get() < MTV.ValTy.get();
636 }
637};
638
639static TypeMap<PointerValType, PointerType> PointerTypes;
640
641PointerType *PointerType::get(const Type *ValueType) {
642 assert(ValueType && "Can't get a pointer to <null> type!");
643 PointerValType PVT(ValueType, PointerTypes);
644
645 PointerType *PT = PointerTypes.get(PVT);
646 if (PT) return PT;
647
648 // Value not found. Derive a new type!
649 PointerTypes.add(PVT, PT = new PointerType(ValueType));
650
651#ifdef DEBUG_MERGE_TYPES
652 cerr << "Derived new type: " << PT->getDescription() << endl;
653#endif
654 return PT;
655}
656
657
658
659//===----------------------------------------------------------------------===//
660// Derived Type Refinement Functions
661//===----------------------------------------------------------------------===//
662
663// removeAbstractTypeUser - Notify an abstract type that a user of the class
664// no longer has a handle to the type. This function is called primarily by
665// the PATypeHandle class. When there are no users of the abstract type, it
666// is anihilated, because there is no way to get a reference to it ever again.
667//
668void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
669 // Search from back to front because we will notify users from back to
670 // front. Also, it is likely that there will be a stack like behavior to
671 // users that register and unregister users.
672 //
673 for (unsigned i = AbstractTypeUsers.size(); i > 0; --i) {
674 if (AbstractTypeUsers[i-1] == U) {
675 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i-1);
676
677#ifdef DEBUG_MERGE_TYPES
678 cerr << " removeAbstractTypeUser[" << (void*)this << ", "
679 << getDescription() << "][" << AbstractTypeUsers.size()
680 << "] User = " << U << endl;
681#endif
682
683 if (AbstractTypeUsers.empty()) {
684#ifdef DEBUG_MERGE_TYPES
685 cerr << "DELETEing unused abstract type: " << getDescription()
686 << " " << (void*)this << endl;
687#endif
688 delete this; // No users of this abstract type!
689 }
690 return;
691 }
692 }
693 assert(isAbstract() && "removeAbstractTypeUser: Type not abstract!");
694 assert(0 && "AbstractTypeUser not in user list!");
695}
696
697
698// refineAbstractTypeTo - This function is used to when it is discovered that
699// the 'this' abstract type is actually equivalent to the NewType specified.
700// This causes all users of 'this' to switch to reference the more concrete
701// type NewType and for 'this' to be deleted.
702//
703void DerivedType::refineAbstractTypeTo(const Type *NewType) {
704 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
705 assert(this != NewType && "Can't refine to myself!");
706
707#ifdef DEBUG_MERGE_TYPES
708 cerr << "REFINING abstract type [" << (void*)this << " " << getDescription()
709 << "] to [" << (void*)NewType << " " << NewType->getDescription()
710 << "]!\n";
711#endif
712
713
714 // Make sure to put the type to be refined to into a holder so that if IT gets
715 // refined, that we will not continue using a dead reference...
716 //
717 PATypeHolder<Type> NewTy(NewType);
718
719 // Add a self use of the current type so that we don't delete ourself until
720 // after this while loop. We are careful to never invoke refine on ourself,
721 // so this extra reference shouldn't be a problem. Note that we must only
722 // remove a single reference at the end, but we must tolerate multiple self
723 // references because we could be refineAbstractTypeTo'ing recursively on the
724 // same type.
725 //
726 addAbstractTypeUser(this);
727
728 // Count the number of self uses. Stop looping when sizeof(list) == NSU.
729 unsigned NumSelfUses = 0;
730
731 // Iterate over all of the uses of this type, invoking callback. Each user
732 // should remove itself from our use list automatically.
733 //
734 while (AbstractTypeUsers.size() > NumSelfUses) {
735 AbstractTypeUser *User = AbstractTypeUsers.back();
736
737 if (User == this) {
738 // Move self use to the start of the list. Increment NSU.
739 swap(AbstractTypeUsers.back(), AbstractTypeUsers[NumSelfUses++]);
740 } else {
741 unsigned OldSize = AbstractTypeUsers.size();
742#ifdef DEBUG_MERGE_TYPES
743 cerr << " REFINING user " << OldSize-1 << " of abstract type ["
744 << (void*)this << " " << getDescription() << "] to ["
745 << (void*)NewTy.get() << " " << NewTy->getDescription() << "]!\n";
746#endif
747 AbstractTypeUsers.back()->refineAbstractType(this, NewTy);
748
749 assert(AbstractTypeUsers.size() != OldSize &&
750 "AbsTyUser did not remove self from user list!");
Chris Lattner00950542001-06-06 20:29:01 +0000751 }
752 }
753
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000754 // Remove a single self use, even though there may be several here. This will
755 // probably 'delete this', so no instance variables may be used after this
756 // occurs...
757 assert(AbstractTypeUsers.back() == this && "Only self uses should be left!");
758 removeAbstractTypeUser(this);
Chris Lattner00950542001-06-06 20:29:01 +0000759}
760
761
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000762// typeIsRefined - Notify AbstractTypeUsers of this type that the current type
763// has been refined a bit. The pointer is still valid and still should be
764// used, but the subtypes have changed.
765//
766void DerivedType::typeIsRefined() {
767 assert(isRefining >= 0 && isRefining <= 2 && "isRefining out of bounds!");
768 if (isRefining == 2) return; // Kill recursion here...
769 ++isRefining;
Chris Lattner00950542001-06-06 20:29:01 +0000770
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000771#ifdef DEBUG_MERGE_TYPES
772 cerr << "typeIsREFINED type: " << (void*)this <<" "<<getDescription() << endl;
773#endif
774 for (unsigned i = 0; i < AbstractTypeUsers.size(); ) {
775 AbstractTypeUser *ATU = AbstractTypeUsers[i];
776#ifdef DEBUG_MERGE_TYPES
777 cerr << " typeIsREFINED user " << i << " of abstract type ["
778 << (void*)this << " " << getDescription() << "]\n";
779#endif
780 ATU->refineAbstractType(this, this);
781
782 // If the user didn't remove itself from the list, continue...
783 if (AbstractTypeUsers.size() > i && AbstractTypeUsers[i] == ATU)
784 ++i;
Chris Lattner00950542001-06-06 20:29:01 +0000785 }
786
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000787 --isRefining;
788}
789
Chris Lattner00950542001-06-06 20:29:01 +0000790
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000791
792
793// refineAbstractType - Called when a contained type is found to be more
794// concrete - this could potentially change us from an abstract type to a
795// concrete type.
796//
797void MethodType::refineAbstractType(const DerivedType *OldType,
798 const Type *NewType) {
799#ifdef DEBUG_MERGE_TYPES
800 cerr << "MethodTy::refineAbstractTy(" << (void*)OldType << "["
801 << OldType->getDescription() << "], " << (void*)NewType << " ["
802 << NewType->getDescription() << "])\n";
Chris Lattner00950542001-06-06 20:29:01 +0000803#endif
Chris Lattnerc038a2f2001-09-07 16:56:42 +0000804
805 if (OldType == ResultType) {
806 ResultType = NewType;
807 } else {
808 unsigned i;
809 for (i = 0; i < ParamTys.size(); ++i)
810 if (OldType == ParamTys[i]) {
811 ParamTys[i] = NewType;
812 break;
813 }
814 assert(i != ParamTys.size() && "Did not contain oldtype!");
815 }
816
817
818 // Notify everyone that I have changed!
819 if (const MethodType *MTy = MethodTypes.containsEquivalent(this)) {
820#ifndef _NDEBUG
821 // Calculate accurate name for debugging purposes
822 vector<const Type *> TypeStack;
823 bool isAbstract = false, isRecursive = false;
824 setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
825#endif
826
827#ifdef DEBUG_MERGE_TYPES
828 cerr << "Type " << (void*)this << " equilivant to existing " << (void*)MTy
829 << " - destroying!\n";
830#endif
831 refineAbstractTypeTo(MTy); // Different type altogether...
832 return;
833 }
834 setDerivedTypeProperties(); // Update the name and isAbstract
835 typeIsRefined();
836}
837
838
839// refineAbstractType - Called when a contained type is found to be more
840// concrete - this could potentially change us from an abstract type to a
841// concrete type.
842//
843void ArrayType::refineAbstractType(const DerivedType *OldType,
844 const Type *NewType) {
845#ifdef DEBUG_MERGE_TYPES
846 cerr << "ArrayTy::refineAbstractTy(" << (void*)OldType << "["
847 << OldType->getDescription() << "], " << (void*)NewType << " ["
848 << NewType->getDescription() << "])\n";
849#endif
850 assert(OldType == ElementType && "Cannot refine from OldType!");
851 ElementType = NewType;
852
853 // Notify everyone that I have changed!
854 if (const ArrayType *ATy = ArrayTypes.containsEquivalent(this)) {
855#ifndef _NDEBUG
856 // Calculate accurate name for debugging purposes
857 vector<const Type *> TypeStack;
858 bool isAbstract = false, isRecursive = false;
859 setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
860#endif
861
862#ifdef DEBUG_MERGE_TYPES
863 cerr << "Type " << (void*)this << " equilivant to existing " << (void*)ATy
864 << " - destroying!\n";
865#endif
866 refineAbstractTypeTo(ATy); // Different type altogether...
867 return;
868 }
869 setDerivedTypeProperties(); // Update the name and isAbstract
870 typeIsRefined(); // Same type, different contents...
871}
872
873
874// refineAbstractType - Called when a contained type is found to be more
875// concrete - this could potentially change us from an abstract type to a
876// concrete type.
877//
878void StructType::refineAbstractType(const DerivedType *OldType,
879 const Type *NewType) {
880#ifdef DEBUG_MERGE_TYPES
881 cerr << "StructTy::refineAbstractTy(" << (void*)OldType << "["
882 << OldType->getDescription() << "], " << (void*)NewType << " ["
883 << NewType->getDescription() << "])\n";
884#endif
885
886 if (OldType != NewType) {
887 unsigned i;
888 for (i = 0; i < ETypes.size(); ++i)
889 if (OldType == ETypes[i]) {
890 ETypes[i] = NewType;
891 break;
892 }
893 assert(i != ETypes.size() && "Did not contain oldtype!");
894 }
895
896 vector<const Type *> ElTypes(
897 map_iterator(ETypes.begin(), mem_fun_ref(&PATypeHandle<Type>::get)),
898 map_iterator(ETypes.end() , mem_fun_ref(&PATypeHandle<Type>::get)));
899
900
901 // Notify everyone that I have changed!
902 if (const StructType *STy = StructTypes.containsEquivalent(this)) {
903#ifndef _NDEBUG
904 // Calculate accurate name for debugging purposes
905 vector<const Type *> TypeStack;
906 bool isAbstract = false, isRecursive = false;
907 setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
908#endif
909
910#ifdef DEBUG_MERGE_TYPES
911 cerr << "Type " << (void*)this << " equilivant to existing " << (void*)STy
912 << " - destroying!\n";
913#endif
914 refineAbstractTypeTo(STy); // Different type altogether...
915 return;
916 }
917 setDerivedTypeProperties(); // Update the name and isAbstract
918 typeIsRefined(); // Same type, different contents...
919}
920
921// refineAbstractType - Called when a contained type is found to be more
922// concrete - this could potentially change us from an abstract type to a
923// concrete type.
924//
925void PointerType::refineAbstractType(const DerivedType *OldType,
926 const Type *NewType) {
927#ifdef DEBUG_MERGE_TYPES
928 cerr << "PointerTy::refineAbstractTy(" << (void*)OldType << "["
929 << OldType->getDescription() << "], " << (void*)NewType << " ["
930 << NewType->getDescription() << "])\n";
931#endif
932 assert(OldType == ValueType && "Cannot refine from OldType!");
933 ValueType = NewType;
934
935 // Notify everyone that I have changed!
936 if (const PointerType *PTy = PointerTypes.containsEquivalent(this)) {
937#ifndef _NDEBUG
938 // Calculate accurate name for debugging purposes
939 vector<const Type *> TypeStack;
940 bool isAbstract = false, isRecursive = false;
941 setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
942#endif
943
944#ifdef DEBUG_MERGE_TYPES
945 cerr << "Type " << (void*)this << " equilivant to existing " << (void*)PTy
946 << " - destroying!\n";
947#endif
948 refineAbstractTypeTo(PTy); // Different type altogether...
949 return;
950 }
951 setDerivedTypeProperties(); // Update the name and isAbstract
952 typeIsRefined(); // Same type, different contents...
Chris Lattner00950542001-06-06 20:29:01 +0000953}
954