Type safety for Constants.cpp! Some of this is temporary, as I'm planning to push...
[oota-llvm.git] / lib / VMCore / Type.cpp
1 //===-- Type.cpp - Implement the Type class -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Type class for the VMCore library.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/DerivedTypes.h"
15 #include "llvm/Constants.h"
16 #include "llvm/Assembly/Writer.h"
17 #include "llvm/ADT/DepthFirstIterator.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/SCCIterator.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Support/Threading.h"
27 #include "llvm/System/Mutex.h"
28 #include "llvm/System/RWMutex.h"
29 #include <algorithm>
30 #include <cstdarg>
31 using namespace llvm;
32
33 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
34 // created and later destroyed, all in an effort to make sure that there is only
35 // a single canonical version of a type.
36 //
37 // #define DEBUG_MERGE_TYPES 1
38
39 AbstractTypeUser::~AbstractTypeUser() {}
40
41
42 //===----------------------------------------------------------------------===//
43 //                         Type Class Implementation
44 //===----------------------------------------------------------------------===//
45
46 // Reader/writer lock used for guarding access to the type maps.
47 static ManagedStatic<sys::RWMutex> TypeMapLock;
48
49 // Recursive lock used for guarding access to AbstractTypeUsers.
50 static ManagedStatic<sys::Mutex> AbstractTypeUsersLock;
51
52 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
53 // for types as they are needed.  Because resolution of types must invalidate
54 // all of the abstract type descriptions, we keep them in a seperate map to make
55 // this easy.
56 static ManagedStatic<TypePrinting> ConcreteTypeDescriptions;
57 static ManagedStatic<TypePrinting> AbstractTypeDescriptions;
58
59 /// Because of the way Type subclasses are allocated, this function is necessary
60 /// to use the correct kind of "delete" operator to deallocate the Type object.
61 /// Some type objects (FunctionTy, StructTy) allocate additional space after 
62 /// the space for their derived type to hold the contained types array of
63 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
64 /// allocated with the type object, decreasing allocations and eliminating the
65 /// need for a std::vector to be used in the Type class itself. 
66 /// @brief Type destruction function
67 void Type::destroy() const {
68
69   // Structures and Functions allocate their contained types past the end of
70   // the type object itself. These need to be destroyed differently than the
71   // other types.
72   if (isa<FunctionType>(this) || isa<StructType>(this)) {
73     // First, make sure we destruct any PATypeHandles allocated by these
74     // subclasses.  They must be manually destructed. 
75     for (unsigned i = 0; i < NumContainedTys; ++i)
76       ContainedTys[i].PATypeHandle::~PATypeHandle();
77
78     // Now call the destructor for the subclass directly because we're going
79     // to delete this as an array of char.
80     if (isa<FunctionType>(this))
81       static_cast<const FunctionType*>(this)->FunctionType::~FunctionType();
82     else
83       static_cast<const StructType*>(this)->StructType::~StructType();
84
85     // Finally, remove the memory as an array deallocation of the chars it was
86     // constructed from.
87     operator delete(const_cast<Type *>(this));
88
89     return;
90   }
91
92   // For all the other type subclasses, there is either no contained types or 
93   // just one (all Sequentials). For Sequentials, the PATypeHandle is not
94   // allocated past the type object, its included directly in the SequentialType
95   // class. This means we can safely just do "normal" delete of this object and
96   // all the destructors that need to run will be run.
97   delete this; 
98 }
99
100 const Type *Type::getPrimitiveType(TypeID IDNumber) {
101   switch (IDNumber) {
102   case VoidTyID      : return VoidTy;
103   case FloatTyID     : return FloatTy;
104   case DoubleTyID    : return DoubleTy;
105   case X86_FP80TyID  : return X86_FP80Ty;
106   case FP128TyID     : return FP128Ty;
107   case PPC_FP128TyID : return PPC_FP128Ty;
108   case LabelTyID     : return LabelTy;
109   case MetadataTyID  : return MetadataTy;
110   default:
111     return 0;
112   }
113 }
114
115 const Type *Type::getVAArgsPromotedType() const {
116   if (ID == IntegerTyID && getSubclassData() < 32)
117     return Type::Int32Ty;
118   else if (ID == FloatTyID)
119     return Type::DoubleTy;
120   else
121     return this;
122 }
123
124 /// getScalarType - If this is a vector type, return the element type,
125 /// otherwise return this.
126 const Type *Type::getScalarType() const {
127   if (const VectorType *VTy = dyn_cast<VectorType>(this))
128     return VTy->getElementType();
129   return this;
130 }
131
132 /// isIntOrIntVector - Return true if this is an integer type or a vector of
133 /// integer types.
134 ///
135 bool Type::isIntOrIntVector() const {
136   if (isInteger())
137     return true;
138   if (ID != Type::VectorTyID) return false;
139   
140   return cast<VectorType>(this)->getElementType()->isInteger();
141 }
142
143 /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
144 ///
145 bool Type::isFPOrFPVector() const {
146   if (ID == Type::FloatTyID || ID == Type::DoubleTyID || 
147       ID == Type::FP128TyID || ID == Type::X86_FP80TyID || 
148       ID == Type::PPC_FP128TyID)
149     return true;
150   if (ID != Type::VectorTyID) return false;
151   
152   return cast<VectorType>(this)->getElementType()->isFloatingPoint();
153 }
154
155 // canLosslesslyBitCastTo - Return true if this type can be converted to
156 // 'Ty' without any reinterpretation of bits.  For example, i8* to i32*.
157 //
158 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
159   // Identity cast means no change so return true
160   if (this == Ty) 
161     return true;
162   
163   // They are not convertible unless they are at least first class types
164   if (!this->isFirstClassType() || !Ty->isFirstClassType())
165     return false;
166
167   // Vector -> Vector conversions are always lossless if the two vector types
168   // have the same size, otherwise not.
169   if (const VectorType *thisPTy = dyn_cast<VectorType>(this))
170     if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
171       return thisPTy->getBitWidth() == thatPTy->getBitWidth();
172
173   // At this point we have only various mismatches of the first class types
174   // remaining and ptr->ptr. Just select the lossless conversions. Everything
175   // else is not lossless.
176   if (isa<PointerType>(this))
177     return isa<PointerType>(Ty);
178   return false;  // Other types have no identity values
179 }
180
181 unsigned Type::getPrimitiveSizeInBits() const {
182   switch (getTypeID()) {
183   case Type::FloatTyID: return 32;
184   case Type::DoubleTyID: return 64;
185   case Type::X86_FP80TyID: return 80;
186   case Type::FP128TyID: return 128;
187   case Type::PPC_FP128TyID: return 128;
188   case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
189   case Type::VectorTyID:  return cast<VectorType>(this)->getBitWidth();
190   default: return 0;
191   }
192 }
193
194 /// getScalarSizeInBits - If this is a vector type, return the
195 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
196 /// getPrimitiveSizeInBits value for this type.
197 unsigned Type::getScalarSizeInBits() const {
198   return getScalarType()->getPrimitiveSizeInBits();
199 }
200
201 /// getFPMantissaWidth - Return the width of the mantissa of this type.  This
202 /// is only valid on floating point types.  If the FP type does not
203 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
204 int Type::getFPMantissaWidth() const {
205   if (const VectorType *VTy = dyn_cast<VectorType>(this))
206     return VTy->getElementType()->getFPMantissaWidth();
207   assert(isFloatingPoint() && "Not a floating point type!");
208   if (ID == FloatTyID) return 24;
209   if (ID == DoubleTyID) return 53;
210   if (ID == X86_FP80TyID) return 64;
211   if (ID == FP128TyID) return 113;
212   assert(ID == PPC_FP128TyID && "unknown fp type");
213   return -1;
214 }
215
216 /// isSizedDerivedType - Derived types like structures and arrays are sized
217 /// iff all of the members of the type are sized as well.  Since asking for
218 /// their size is relatively uncommon, move this operation out of line.
219 bool Type::isSizedDerivedType() const {
220   if (isa<IntegerType>(this))
221     return true;
222
223   if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
224     return ATy->getElementType()->isSized();
225
226   if (const VectorType *PTy = dyn_cast<VectorType>(this))
227     return PTy->getElementType()->isSized();
228
229   if (!isa<StructType>(this)) 
230     return false;
231
232   // Okay, our struct is sized if all of the elements are...
233   for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
234     if (!(*I)->isSized()) 
235       return false;
236
237   return true;
238 }
239
240 /// getForwardedTypeInternal - This method is used to implement the union-find
241 /// algorithm for when a type is being forwarded to another type.
242 const Type *Type::getForwardedTypeInternal() const {
243   assert(ForwardType && "This type is not being forwarded to another type!");
244
245   // Check to see if the forwarded type has been forwarded on.  If so, collapse
246   // the forwarding links.
247   const Type *RealForwardedType = ForwardType->getForwardedType();
248   if (!RealForwardedType)
249     return ForwardType;  // No it's not forwarded again
250
251   // Yes, it is forwarded again.  First thing, add the reference to the new
252   // forward type.
253   if (RealForwardedType->isAbstract())
254     cast<DerivedType>(RealForwardedType)->addRef();
255
256   // Now drop the old reference.  This could cause ForwardType to get deleted.
257   cast<DerivedType>(ForwardType)->dropRef();
258
259   // Return the updated type.
260   ForwardType = RealForwardedType;
261   return ForwardType;
262 }
263
264 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
265   abort();
266 }
267 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
268   abort();
269 }
270
271
272 std::string Type::getDescription() const {
273   TypePrinting &Map =
274     isAbstract() ? *AbstractTypeDescriptions : *ConcreteTypeDescriptions;
275   
276   std::string DescStr;
277   raw_string_ostream DescOS(DescStr);
278   Map.print(this, DescOS);
279   return DescOS.str();
280 }
281
282
283 bool StructType::indexValid(const Value *V) const {
284   // Structure indexes require 32-bit integer constants.
285   if (V->getType() == Type::Int32Ty)
286     if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
287       return indexValid(CU->getZExtValue());
288   return false;
289 }
290
291 bool StructType::indexValid(unsigned V) const {
292   return V < NumContainedTys;
293 }
294
295 // getTypeAtIndex - Given an index value into the type, return the type of the
296 // element.  For a structure type, this must be a constant value...
297 //
298 const Type *StructType::getTypeAtIndex(const Value *V) const {
299   unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
300   return getTypeAtIndex(Idx);
301 }
302
303 const Type *StructType::getTypeAtIndex(unsigned Idx) const {
304   assert(indexValid(Idx) && "Invalid structure index!");
305   return ContainedTys[Idx];
306 }
307
308 //===----------------------------------------------------------------------===//
309 //                          Primitive 'Type' data
310 //===----------------------------------------------------------------------===//
311
312 const Type *Type::VoidTy       = new Type(Type::VoidTyID);
313 const Type *Type::FloatTy      = new Type(Type::FloatTyID);
314 const Type *Type::DoubleTy     = new Type(Type::DoubleTyID);
315 const Type *Type::X86_FP80Ty   = new Type(Type::X86_FP80TyID);
316 const Type *Type::FP128Ty      = new Type(Type::FP128TyID);
317 const Type *Type::PPC_FP128Ty  = new Type(Type::PPC_FP128TyID);
318 const Type *Type::LabelTy      = new Type(Type::LabelTyID);
319 const Type *Type::MetadataTy   = new Type(Type::MetadataTyID);
320
321 namespace {
322   struct BuiltinIntegerType : public IntegerType {
323     explicit BuiltinIntegerType(unsigned W) : IntegerType(W) {}
324   };
325 }
326 const IntegerType *Type::Int1Ty  = new BuiltinIntegerType(1);
327 const IntegerType *Type::Int8Ty  = new BuiltinIntegerType(8);
328 const IntegerType *Type::Int16Ty = new BuiltinIntegerType(16);
329 const IntegerType *Type::Int32Ty = new BuiltinIntegerType(32);
330 const IntegerType *Type::Int64Ty = new BuiltinIntegerType(64);
331
332 //===----------------------------------------------------------------------===//
333 //                          Derived Type Constructors
334 //===----------------------------------------------------------------------===//
335
336 /// isValidReturnType - Return true if the specified type is valid as a return
337 /// type.
338 bool FunctionType::isValidReturnType(const Type *RetTy) {
339   if (RetTy->isFirstClassType()) {
340     if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
341       return PTy->getElementType() != Type::MetadataTy;
342     return true;
343   }
344   if (RetTy == Type::VoidTy || RetTy == Type::MetadataTy ||
345       isa<OpaqueType>(RetTy))
346     return true;
347   
348   // If this is a multiple return case, verify that each return is a first class
349   // value and that there is at least one value.
350   const StructType *SRetTy = dyn_cast<StructType>(RetTy);
351   if (SRetTy == 0 || SRetTy->getNumElements() == 0)
352     return false;
353   
354   for (unsigned i = 0, e = SRetTy->getNumElements(); i != e; ++i)
355     if (!SRetTy->getElementType(i)->isFirstClassType())
356       return false;
357   return true;
358 }
359
360 /// isValidArgumentType - Return true if the specified type is valid as an
361 /// argument type.
362 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
363   if ((!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy)) ||
364       (isa<PointerType>(ArgTy) &&
365        cast<PointerType>(ArgTy)->getElementType() == Type::MetadataTy))
366     return false;
367
368   return true;
369 }
370
371 FunctionType::FunctionType(const Type *Result,
372                            const std::vector<const Type*> &Params,
373                            bool IsVarArgs)
374   : DerivedType(FunctionTyID), isVarArgs(IsVarArgs) {
375   ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
376   NumContainedTys = Params.size() + 1; // + 1 for result type
377   assert(isValidReturnType(Result) && "invalid return type for function");
378
379
380   bool isAbstract = Result->isAbstract();
381   new (&ContainedTys[0]) PATypeHandle(Result, this);
382
383   for (unsigned i = 0; i != Params.size(); ++i) {
384     assert(isValidArgumentType(Params[i]) &&
385            "Not a valid type for function argument!");
386     new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
387     isAbstract |= Params[i]->isAbstract();
388   }
389
390   // Calculate whether or not this type is abstract
391   setAbstract(isAbstract);
392 }
393
394 StructType::StructType(const std::vector<const Type*> &Types, bool isPacked)
395   : CompositeType(StructTyID) {
396   ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
397   NumContainedTys = Types.size();
398   setSubclassData(isPacked);
399   bool isAbstract = false;
400   for (unsigned i = 0; i < Types.size(); ++i) {
401     assert(Types[i] && "<null> type for structure field!");
402     assert(isValidElementType(Types[i]) &&
403            "Invalid type for structure element!");
404     new (&ContainedTys[i]) PATypeHandle(Types[i], this);
405     isAbstract |= Types[i]->isAbstract();
406   }
407
408   // Calculate whether or not this type is abstract
409   setAbstract(isAbstract);
410 }
411
412 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
413   : SequentialType(ArrayTyID, ElType) {
414   NumElements = NumEl;
415
416   // Calculate whether or not this type is abstract
417   setAbstract(ElType->isAbstract());
418 }
419
420 VectorType::VectorType(const Type *ElType, unsigned NumEl)
421   : SequentialType(VectorTyID, ElType) {
422   NumElements = NumEl;
423   setAbstract(ElType->isAbstract());
424   assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
425   assert(isValidElementType(ElType) &&
426          "Elements of a VectorType must be a primitive type");
427
428 }
429
430
431 PointerType::PointerType(const Type *E, unsigned AddrSpace)
432   : SequentialType(PointerTyID, E) {
433   AddressSpace = AddrSpace;
434   // Calculate whether or not this type is abstract
435   setAbstract(E->isAbstract());
436 }
437
438 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
439   setAbstract(true);
440 #ifdef DEBUG_MERGE_TYPES
441   DOUT << "Derived new type: " << *this << "\n";
442 #endif
443 }
444
445 void PATypeHolder::destroy() {
446   Ty = 0;
447 }
448
449 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
450 // another (more concrete) type, we must eliminate all references to other
451 // types, to avoid some circular reference problems.
452 void DerivedType::dropAllTypeUses() {
453   if (NumContainedTys != 0) {
454     // The type must stay abstract.  To do this, we insert a pointer to a type
455     // that will never get resolved, thus will always be abstract.
456     static Type *AlwaysOpaqueTy = OpaqueType::get();
457     static PATypeHolder Holder(AlwaysOpaqueTy);
458     ContainedTys[0] = AlwaysOpaqueTy;
459
460     // Change the rest of the types to be Int32Ty's.  It doesn't matter what we
461     // pick so long as it doesn't point back to this type.  We choose something
462     // concrete to avoid overhead for adding to AbstracTypeUser lists and stuff.
463     for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
464       ContainedTys[i] = Type::Int32Ty;
465   }
466 }
467
468
469 namespace {
470
471 /// TypePromotionGraph and graph traits - this is designed to allow us to do
472 /// efficient SCC processing of type graphs.  This is the exact same as
473 /// GraphTraits<Type*>, except that we pretend that concrete types have no
474 /// children to avoid processing them.
475 struct TypePromotionGraph {
476   Type *Ty;
477   TypePromotionGraph(Type *T) : Ty(T) {}
478 };
479
480 }
481
482 namespace llvm {
483   template <> struct GraphTraits<TypePromotionGraph> {
484     typedef Type NodeType;
485     typedef Type::subtype_iterator ChildIteratorType;
486
487     static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
488     static inline ChildIteratorType child_begin(NodeType *N) {
489       if (N->isAbstract())
490         return N->subtype_begin();
491       else           // No need to process children of concrete types.
492         return N->subtype_end();
493     }
494     static inline ChildIteratorType child_end(NodeType *N) {
495       return N->subtype_end();
496     }
497   };
498 }
499
500
501 // PromoteAbstractToConcrete - This is a recursive function that walks a type
502 // graph calculating whether or not a type is abstract.
503 //
504 void Type::PromoteAbstractToConcrete() {
505   if (!isAbstract()) return;
506
507   scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
508   scc_iterator<TypePromotionGraph> SE = scc_end  (TypePromotionGraph(this));
509
510   for (; SI != SE; ++SI) {
511     std::vector<Type*> &SCC = *SI;
512
513     // Concrete types are leaves in the tree.  Since an SCC will either be all
514     // abstract or all concrete, we only need to check one type.
515     if (SCC[0]->isAbstract()) {
516       if (isa<OpaqueType>(SCC[0]))
517         return;     // Not going to be concrete, sorry.
518
519       // If all of the children of all of the types in this SCC are concrete,
520       // then this SCC is now concrete as well.  If not, neither this SCC, nor
521       // any parent SCCs will be concrete, so we might as well just exit.
522       for (unsigned i = 0, e = SCC.size(); i != e; ++i)
523         for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
524                E = SCC[i]->subtype_end(); CI != E; ++CI)
525           if ((*CI)->isAbstract())
526             // If the child type is in our SCC, it doesn't make the entire SCC
527             // abstract unless there is a non-SCC abstract type.
528             if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
529               return;               // Not going to be concrete, sorry.
530
531       // Okay, we just discovered this whole SCC is now concrete, mark it as
532       // such!
533       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
534         assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
535
536         SCC[i]->setAbstract(false);
537       }
538
539       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
540         assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
541         // The type just became concrete, notify all users!
542         cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
543       }
544     }
545   }
546 }
547
548
549 //===----------------------------------------------------------------------===//
550 //                      Type Structural Equality Testing
551 //===----------------------------------------------------------------------===//
552
553 // TypesEqual - Two types are considered structurally equal if they have the
554 // same "shape": Every level and element of the types have identical primitive
555 // ID's, and the graphs have the same edges/nodes in them.  Nodes do not have to
556 // be pointer equals to be equivalent though.  This uses an optimistic algorithm
557 // that assumes that two graphs are the same until proven otherwise.
558 //
559 static bool TypesEqual(const Type *Ty, const Type *Ty2,
560                        std::map<const Type *, const Type *> &EqTypes) {
561   if (Ty == Ty2) return true;
562   if (Ty->getTypeID() != Ty2->getTypeID()) return false;
563   if (isa<OpaqueType>(Ty))
564     return false;  // Two unequal opaque types are never equal
565
566   std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
567   if (It != EqTypes.end())
568     return It->second == Ty2;    // Looping back on a type, check for equality
569
570   // Otherwise, add the mapping to the table to make sure we don't get
571   // recursion on the types...
572   EqTypes.insert(It, std::make_pair(Ty, Ty2));
573
574   // Two really annoying special cases that breaks an otherwise nice simple
575   // algorithm is the fact that arraytypes have sizes that differentiates types,
576   // and that function types can be varargs or not.  Consider this now.
577   //
578   if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
579     const IntegerType *ITy2 = cast<IntegerType>(Ty2);
580     return ITy->getBitWidth() == ITy2->getBitWidth();
581   } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
582     const PointerType *PTy2 = cast<PointerType>(Ty2);
583     return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
584            TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
585   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
586     const StructType *STy2 = cast<StructType>(Ty2);
587     if (STy->getNumElements() != STy2->getNumElements()) return false;
588     if (STy->isPacked() != STy2->isPacked()) return false;
589     for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
590       if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
591         return false;
592     return true;
593   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
594     const ArrayType *ATy2 = cast<ArrayType>(Ty2);
595     return ATy->getNumElements() == ATy2->getNumElements() &&
596            TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
597   } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
598     const VectorType *PTy2 = cast<VectorType>(Ty2);
599     return PTy->getNumElements() == PTy2->getNumElements() &&
600            TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
601   } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
602     const FunctionType *FTy2 = cast<FunctionType>(Ty2);
603     if (FTy->isVarArg() != FTy2->isVarArg() ||
604         FTy->getNumParams() != FTy2->getNumParams() ||
605         !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
606       return false;
607     for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
608       if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
609         return false;
610     }
611     return true;
612   } else {
613     assert(0 && "Unknown derived type!");
614     return false;
615   }
616 }
617
618 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
619   std::map<const Type *, const Type *> EqTypes;
620   return TypesEqual(Ty, Ty2, EqTypes);
621 }
622
623 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
624 // TargetTy in the type graph.  We know that Ty is an abstract type, so if we
625 // ever reach a non-abstract type, we know that we don't need to search the
626 // subgraph.
627 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
628                                 SmallPtrSet<const Type*, 128> &VisitedTypes) {
629   if (TargetTy == CurTy) return true;
630   if (!CurTy->isAbstract()) return false;
631
632   if (!VisitedTypes.insert(CurTy))
633     return false;  // Already been here.
634
635   for (Type::subtype_iterator I = CurTy->subtype_begin(),
636        E = CurTy->subtype_end(); I != E; ++I)
637     if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
638       return true;
639   return false;
640 }
641
642 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
643                                 SmallPtrSet<const Type*, 128> &VisitedTypes) {
644   if (TargetTy == CurTy) return true;
645
646   if (!VisitedTypes.insert(CurTy))
647     return false;  // Already been here.
648
649   for (Type::subtype_iterator I = CurTy->subtype_begin(),
650        E = CurTy->subtype_end(); I != E; ++I)
651     if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
652       return true;
653   return false;
654 }
655
656 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
657 /// back to itself.
658 static bool TypeHasCycleThroughItself(const Type *Ty) {
659   SmallPtrSet<const Type*, 128> VisitedTypes;
660
661   if (Ty->isAbstract()) {  // Optimized case for abstract types.
662     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
663          I != E; ++I)
664       if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
665         return true;
666   } else {
667     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
668          I != E; ++I)
669       if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
670         return true;
671   }
672   return false;
673 }
674
675 /// getSubElementHash - Generate a hash value for all of the SubType's of this
676 /// type.  The hash value is guaranteed to be zero if any of the subtypes are 
677 /// an opaque type.  Otherwise we try to mix them in as well as possible, but do
678 /// not look at the subtype's subtype's.
679 static unsigned getSubElementHash(const Type *Ty) {
680   unsigned HashVal = 0;
681   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
682        I != E; ++I) {
683     HashVal *= 32;
684     const Type *SubTy = I->get();
685     HashVal += SubTy->getTypeID();
686     switch (SubTy->getTypeID()) {
687     default: break;
688     case Type::OpaqueTyID: return 0;    // Opaque -> hash = 0 no matter what.
689     case Type::IntegerTyID:
690       HashVal ^= (cast<IntegerType>(SubTy)->getBitWidth() << 3);
691       break;
692     case Type::FunctionTyID:
693       HashVal ^= cast<FunctionType>(SubTy)->getNumParams()*2 + 
694                  cast<FunctionType>(SubTy)->isVarArg();
695       break;
696     case Type::ArrayTyID:
697       HashVal ^= cast<ArrayType>(SubTy)->getNumElements();
698       break;
699     case Type::VectorTyID:
700       HashVal ^= cast<VectorType>(SubTy)->getNumElements();
701       break;
702     case Type::StructTyID:
703       HashVal ^= cast<StructType>(SubTy)->getNumElements();
704       break;
705     case Type::PointerTyID:
706       HashVal ^= cast<PointerType>(SubTy)->getAddressSpace();
707       break;
708     }
709   }
710   return HashVal ? HashVal : 1;  // Do not return zero unless opaque subty.
711 }
712
713 //===----------------------------------------------------------------------===//
714 //                       Derived Type Factory Functions
715 //===----------------------------------------------------------------------===//
716
717 namespace llvm {
718 class TypeMapBase {
719 protected:
720   /// TypesByHash - Keep track of types by their structure hash value.  Note
721   /// that we only keep track of types that have cycles through themselves in
722   /// this map.
723   ///
724   std::multimap<unsigned, PATypeHolder> TypesByHash;
725
726 public:
727   ~TypeMapBase() {
728     // PATypeHolder won't destroy non-abstract types.
729     // We can't destroy them by simply iterating, because
730     // they may contain references to each-other.
731 #if 0
732     for (std::multimap<unsigned, PATypeHolder>::iterator I
733          = TypesByHash.begin(), E = TypesByHash.end(); I != E; ++I) {
734       Type *Ty = const_cast<Type*>(I->second.Ty);
735       I->second.destroy();
736       // We can't invoke destroy or delete, because the type may
737       // contain references to already freed types.
738       // So we have to destruct the object the ugly way.
739       if (Ty) {
740         Ty->AbstractTypeUsers.clear();
741         static_cast<const Type*>(Ty)->Type::~Type();
742         operator delete(Ty);
743       }
744     }
745 #endif
746   }
747
748   void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
749     std::multimap<unsigned, PATypeHolder>::iterator I =
750       TypesByHash.lower_bound(Hash);
751     for (; I != TypesByHash.end() && I->first == Hash; ++I) {
752       if (I->second == Ty) {
753         TypesByHash.erase(I);
754         return;
755       }
756     }
757     
758     // This must be do to an opaque type that was resolved.  Switch down to hash
759     // code of zero.
760     assert(Hash && "Didn't find type entry!");
761     RemoveFromTypesByHash(0, Ty);
762   }
763   
764   /// TypeBecameConcrete - When Ty gets a notification that TheType just became
765   /// concrete, drop uses and make Ty non-abstract if we should.
766   void TypeBecameConcrete(DerivedType *Ty, const DerivedType *TheType) {
767     // If the element just became concrete, remove 'ty' from the abstract
768     // type user list for the type.  Do this for as many times as Ty uses
769     // OldType.
770     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
771          I != E; ++I)
772       if (I->get() == TheType)
773         TheType->removeAbstractTypeUser(Ty);
774     
775     // If the type is currently thought to be abstract, rescan all of our
776     // subtypes to see if the type has just become concrete!  Note that this
777     // may send out notifications to AbstractTypeUsers that types become
778     // concrete.
779     if (Ty->isAbstract())
780       Ty->PromoteAbstractToConcrete();
781   }
782 };
783 }
784
785
786 // TypeMap - Make sure that only one instance of a particular type may be
787 // created on any given run of the compiler... note that this involves updating
788 // our map if an abstract type gets refined somehow.
789 //
790 namespace llvm {
791 template<class ValType, class TypeClass>
792 class TypeMap : public TypeMapBase {
793   std::map<ValType, PATypeHolder> Map;
794 public:
795   typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
796   ~TypeMap() { print("ON EXIT"); }
797
798   inline TypeClass *get(const ValType &V) {
799     iterator I = Map.find(V);
800     return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
801   }
802
803   inline void add(const ValType &V, TypeClass *Ty) {
804     Map.insert(std::make_pair(V, Ty));
805
806     // If this type has a cycle, remember it.
807     TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
808     print("add");
809   }
810   
811   /// RefineAbstractType - This method is called after we have merged a type
812   /// with another one.  We must now either merge the type away with
813   /// some other type or reinstall it in the map with it's new configuration.
814   void RefineAbstractType(TypeClass *Ty, const DerivedType *OldType,
815                         const Type *NewType) {
816 #ifdef DEBUG_MERGE_TYPES
817     DOUT << "RefineAbstractType(" << (void*)OldType << "[" << *OldType
818          << "], " << (void*)NewType << " [" << *NewType << "])\n";
819 #endif
820     
821     // Otherwise, we are changing one subelement type into another.  Clearly the
822     // OldType must have been abstract, making us abstract.
823     assert(Ty->isAbstract() && "Refining a non-abstract type!");
824     assert(OldType != NewType);
825
826     // Make a temporary type holder for the type so that it doesn't disappear on
827     // us when we erase the entry from the map.
828     PATypeHolder TyHolder = Ty;
829
830     // The old record is now out-of-date, because one of the children has been
831     // updated.  Remove the obsolete entry from the map.
832     unsigned NumErased = Map.erase(ValType::get(Ty));
833     assert(NumErased && "Element not found!"); NumErased = NumErased;
834
835     // Remember the structural hash for the type before we start hacking on it,
836     // in case we need it later.
837     unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
838
839     // Find the type element we are refining... and change it now!
840     for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i)
841       if (Ty->ContainedTys[i] == OldType)
842         Ty->ContainedTys[i] = NewType;
843     unsigned NewTypeHash = ValType::hashTypeStructure(Ty);
844     
845     // If there are no cycles going through this node, we can do a simple,
846     // efficient lookup in the map, instead of an inefficient nasty linear
847     // lookup.
848     if (!TypeHasCycleThroughItself(Ty)) {
849       typename std::map<ValType, PATypeHolder>::iterator I;
850       bool Inserted;
851
852       tie(I, Inserted) = Map.insert(std::make_pair(ValType::get(Ty), Ty));
853       if (!Inserted) {
854         // Refined to a different type altogether?
855         RemoveFromTypesByHash(OldTypeHash, Ty);
856
857         // We already have this type in the table.  Get rid of the newly refined
858         // type.
859         TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
860         Ty->unlockedRefineAbstractTypeTo(NewTy);
861         return;
862       }
863     } else {
864       // Now we check to see if there is an existing entry in the table which is
865       // structurally identical to the newly refined type.  If so, this type
866       // gets refined to the pre-existing type.
867       //
868       std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry;
869       tie(I, E) = TypesByHash.equal_range(NewTypeHash);
870       Entry = E;
871       for (; I != E; ++I) {
872         if (I->second == Ty) {
873           // Remember the position of the old type if we see it in our scan.
874           Entry = I;
875         } else {
876           if (TypesEqual(Ty, I->second)) {
877             TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
878
879             // Remove the old entry form TypesByHash.  If the hash values differ
880             // now, remove it from the old place.  Otherwise, continue scanning
881             // withing this hashcode to reduce work.
882             if (NewTypeHash != OldTypeHash) {
883               RemoveFromTypesByHash(OldTypeHash, Ty);
884             } else {
885               if (Entry == E) {
886                 // Find the location of Ty in the TypesByHash structure if we
887                 // haven't seen it already.
888                 while (I->second != Ty) {
889                   ++I;
890                   assert(I != E && "Structure doesn't contain type??");
891                 }
892                 Entry = I;
893               }
894               TypesByHash.erase(Entry);
895             }
896             Ty->unlockedRefineAbstractTypeTo(NewTy);
897             return;
898           }
899         }
900       }
901
902       // If there is no existing type of the same structure, we reinsert an
903       // updated record into the map.
904       Map.insert(std::make_pair(ValType::get(Ty), Ty));
905     }
906
907     // If the hash codes differ, update TypesByHash
908     if (NewTypeHash != OldTypeHash) {
909       RemoveFromTypesByHash(OldTypeHash, Ty);
910       TypesByHash.insert(std::make_pair(NewTypeHash, Ty));
911     }
912     
913     // If the type is currently thought to be abstract, rescan all of our
914     // subtypes to see if the type has just become concrete!  Note that this
915     // may send out notifications to AbstractTypeUsers that types become
916     // concrete.
917     if (Ty->isAbstract())
918       Ty->PromoteAbstractToConcrete();
919   }
920
921   void print(const char *Arg) const {
922 #ifdef DEBUG_MERGE_TYPES
923     DOUT << "TypeMap<>::" << Arg << " table contents:\n";
924     unsigned i = 0;
925     for (typename std::map<ValType, PATypeHolder>::const_iterator I
926            = Map.begin(), E = Map.end(); I != E; ++I)
927       DOUT << " " << (++i) << ". " << (void*)I->second.get() << " "
928            << *I->second.get() << "\n";
929 #endif
930   }
931
932   void dump() const { print("dump output"); }
933 };
934 }
935
936
937 //===----------------------------------------------------------------------===//
938 // Function Type Factory and Value Class...
939 //
940
941 //===----------------------------------------------------------------------===//
942 // Integer Type Factory...
943 //
944 namespace llvm {
945 class IntegerValType {
946   uint32_t bits;
947 public:
948   IntegerValType(uint16_t numbits) : bits(numbits) {}
949
950   static IntegerValType get(const IntegerType *Ty) {
951     return IntegerValType(Ty->getBitWidth());
952   }
953
954   static unsigned hashTypeStructure(const IntegerType *Ty) {
955     return (unsigned)Ty->getBitWidth();
956   }
957
958   inline bool operator<(const IntegerValType &IVT) const {
959     return bits < IVT.bits;
960   }
961 };
962 }
963
964 static ManagedStatic<TypeMap<IntegerValType, IntegerType> > IntegerTypes;
965
966 const IntegerType *IntegerType::get(unsigned NumBits) {
967   assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
968   assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
969
970   // Check for the built-in integer types
971   switch (NumBits) {
972     case  1: return cast<IntegerType>(Type::Int1Ty);
973     case  8: return cast<IntegerType>(Type::Int8Ty);
974     case 16: return cast<IntegerType>(Type::Int16Ty);
975     case 32: return cast<IntegerType>(Type::Int32Ty);
976     case 64: return cast<IntegerType>(Type::Int64Ty);
977     default: 
978       break;
979   }
980   
981   IntegerValType IVT(NumBits);
982   IntegerType *ITy = 0;
983   if (llvm_is_multithreaded()) {
984     // First, see if the type is already in the table, for which
985     // a reader lock suffices.
986     TypeMapLock->reader_acquire();
987     ITy = IntegerTypes->get(IVT);
988     TypeMapLock->reader_release();
989     
990     if (!ITy) {
991       // OK, not in the table, get a writer lock.
992       TypeMapLock->writer_acquire();
993       ITy = IntegerTypes->get(IVT);
994       
995       // We need to _recheck_ the table in case someone
996       // put it in between when we released the reader lock
997       // and when we gained the writer lock!
998       if (!ITy) {
999         // Value not found.  Derive a new type!
1000         ITy = new IntegerType(NumBits);
1001         IntegerTypes->add(IVT, ITy);
1002       }
1003       
1004       TypeMapLock->writer_release();
1005     }
1006   } else {
1007     ITy = IntegerTypes->get(IVT);
1008     if (ITy) return ITy;           // Found a match, return it!
1009
1010     // Value not found.  Derive a new type!
1011     ITy = new IntegerType(NumBits);
1012     IntegerTypes->add(IVT, ITy);
1013   }
1014 #ifdef DEBUG_MERGE_TYPES
1015   DOUT << "Derived new type: " << *ITy << "\n";
1016 #endif
1017   return ITy;
1018 }
1019
1020 bool IntegerType::isPowerOf2ByteWidth() const {
1021   unsigned BitWidth = getBitWidth();
1022   return (BitWidth > 7) && isPowerOf2_32(BitWidth);
1023 }
1024
1025 APInt IntegerType::getMask() const {
1026   return APInt::getAllOnesValue(getBitWidth());
1027 }
1028
1029 // FunctionValType - Define a class to hold the key that goes into the TypeMap
1030 //
1031 namespace llvm {
1032 class FunctionValType {
1033   const Type *RetTy;
1034   std::vector<const Type*> ArgTypes;
1035   bool isVarArg;
1036 public:
1037   FunctionValType(const Type *ret, const std::vector<const Type*> &args,
1038                   bool isVA) : RetTy(ret), ArgTypes(args), isVarArg(isVA) {}
1039
1040   static FunctionValType get(const FunctionType *FT);
1041
1042   static unsigned hashTypeStructure(const FunctionType *FT) {
1043     unsigned Result = FT->getNumParams()*2 + FT->isVarArg();
1044     return Result;
1045   }
1046
1047   inline bool operator<(const FunctionValType &MTV) const {
1048     if (RetTy < MTV.RetTy) return true;
1049     if (RetTy > MTV.RetTy) return false;
1050     if (isVarArg < MTV.isVarArg) return true;
1051     if (isVarArg > MTV.isVarArg) return false;
1052     if (ArgTypes < MTV.ArgTypes) return true;
1053     if (ArgTypes > MTV.ArgTypes) return false;
1054     return false;
1055   }
1056 };
1057 }
1058
1059 // Define the actual map itself now...
1060 static ManagedStatic<TypeMap<FunctionValType, FunctionType> > FunctionTypes;
1061
1062 FunctionValType FunctionValType::get(const FunctionType *FT) {
1063   // Build up a FunctionValType
1064   std::vector<const Type *> ParamTypes;
1065   ParamTypes.reserve(FT->getNumParams());
1066   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1067     ParamTypes.push_back(FT->getParamType(i));
1068   return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
1069 }
1070
1071
1072 // FunctionType::get - The factory function for the FunctionType class...
1073 FunctionType *FunctionType::get(const Type *ReturnType,
1074                                 const std::vector<const Type*> &Params,
1075                                 bool isVarArg) {
1076   FunctionValType VT(ReturnType, Params, isVarArg);
1077   FunctionType *FT = 0;
1078   
1079   if (llvm_is_multithreaded()) {
1080     TypeMapLock->reader_acquire();
1081     FT = FunctionTypes->get(VT);
1082     TypeMapLock->reader_release();
1083     
1084     if (!FT) {
1085       TypeMapLock->writer_acquire();
1086       
1087       // Have to check again here, because it might have
1088       // been inserted between when we release the reader
1089       // lock and when we acquired the writer lock.
1090       FT = FunctionTypes->get(VT);
1091       if (!FT) {
1092         FT = (FunctionType*) operator new(sizeof(FunctionType) +
1093                                         sizeof(PATypeHandle)*(Params.size()+1));
1094         new (FT) FunctionType(ReturnType, Params, isVarArg);
1095         FunctionTypes->add(VT, FT);
1096       }
1097       TypeMapLock->writer_release();
1098     }
1099   } else {
1100     FT = FunctionTypes->get(VT);
1101     if (FT)
1102       return FT;
1103
1104     FT = (FunctionType*) operator new(sizeof(FunctionType) +
1105                                       sizeof(PATypeHandle)*(Params.size()+1));
1106     new (FT) FunctionType(ReturnType, Params, isVarArg);
1107     FunctionTypes->add(VT, FT);
1108   }
1109   
1110 #ifdef DEBUG_MERGE_TYPES
1111   DOUT << "Derived new type: " << FT << "\n";
1112 #endif
1113   return FT;
1114 }
1115
1116 //===----------------------------------------------------------------------===//
1117 // Array Type Factory...
1118 //
1119 namespace llvm {
1120 class ArrayValType {
1121   const Type *ValTy;
1122   uint64_t Size;
1123 public:
1124   ArrayValType(const Type *val, uint64_t sz) : ValTy(val), Size(sz) {}
1125
1126   static ArrayValType get(const ArrayType *AT) {
1127     return ArrayValType(AT->getElementType(), AT->getNumElements());
1128   }
1129
1130   static unsigned hashTypeStructure(const ArrayType *AT) {
1131     return (unsigned)AT->getNumElements();
1132   }
1133
1134   inline bool operator<(const ArrayValType &MTV) const {
1135     if (Size < MTV.Size) return true;
1136     return Size == MTV.Size && ValTy < MTV.ValTy;
1137   }
1138 };
1139 }
1140
1141 static ManagedStatic<TypeMap<ArrayValType, ArrayType> > ArrayTypes;
1142
1143 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
1144   assert(ElementType && "Can't get array of <null> types!");
1145   assert(isValidElementType(ElementType) && "Invalid type for array element!");
1146
1147   ArrayValType AVT(ElementType, NumElements);
1148   ArrayType *AT = 0;
1149   
1150   if (llvm_is_multithreaded()) {
1151     TypeMapLock->reader_acquire();
1152     AT = ArrayTypes->get(AVT);
1153     TypeMapLock->reader_release();
1154     
1155     if (!AT) {
1156       TypeMapLock->writer_acquire();
1157       
1158       // Recheck.  Might have changed between release and acquire.
1159       AT = ArrayTypes->get(AVT);
1160       if (!AT) {
1161         // Value not found.  Derive a new type!
1162         ArrayTypes->add(AVT, AT = new ArrayType(ElementType, NumElements));
1163       }
1164       TypeMapLock->writer_release();
1165     }
1166   } else {
1167     AT = ArrayTypes->get(AVT);
1168     if (AT) return AT;           // Found a match, return it!
1169     
1170     // Value not found.  Derive a new type!
1171     ArrayTypes->add(AVT, AT = new ArrayType(ElementType, NumElements));
1172   }
1173 #ifdef DEBUG_MERGE_TYPES
1174   DOUT << "Derived new type: " << *AT << "\n";
1175 #endif
1176   return AT;
1177 }
1178
1179 bool ArrayType::isValidElementType(const Type *ElemTy) {
1180   if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy ||
1181       ElemTy == Type::MetadataTy)
1182     return false;
1183
1184   if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1185     if (PTy->getElementType() == Type::MetadataTy)
1186       return false;
1187
1188   return true;
1189 }
1190
1191
1192 //===----------------------------------------------------------------------===//
1193 // Vector Type Factory...
1194 //
1195 namespace llvm {
1196 class VectorValType {
1197   const Type *ValTy;
1198   unsigned Size;
1199 public:
1200   VectorValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
1201
1202   static VectorValType get(const VectorType *PT) {
1203     return VectorValType(PT->getElementType(), PT->getNumElements());
1204   }
1205
1206   static unsigned hashTypeStructure(const VectorType *PT) {
1207     return PT->getNumElements();
1208   }
1209
1210   inline bool operator<(const VectorValType &MTV) const {
1211     if (Size < MTV.Size) return true;
1212     return Size == MTV.Size && ValTy < MTV.ValTy;
1213   }
1214 };
1215 }
1216
1217 static ManagedStatic<TypeMap<VectorValType, VectorType> > VectorTypes;
1218
1219 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
1220   assert(ElementType && "Can't get vector of <null> types!");
1221
1222   VectorValType PVT(ElementType, NumElements);
1223   VectorType *PT = 0;
1224   
1225   if (llvm_is_multithreaded()) {
1226     TypeMapLock->reader_acquire();
1227     PT = VectorTypes->get(PVT);
1228     TypeMapLock->reader_release();
1229     
1230     if (!PT) {
1231       TypeMapLock->writer_acquire();
1232       PT = VectorTypes->get(PVT);
1233       // Recheck.  Might have changed between release and acquire.
1234       if (!PT) {
1235         VectorTypes->add(PVT, PT = new VectorType(ElementType, NumElements));
1236       }
1237       TypeMapLock->writer_acquire();
1238     }
1239   } else {
1240     PT = VectorTypes->get(PVT);
1241     if (PT) return PT;           // Found a match, return it!
1242     
1243     // Value not found.  Derive a new type!
1244     VectorTypes->add(PVT, PT = new VectorType(ElementType, NumElements));
1245   }
1246 #ifdef DEBUG_MERGE_TYPES
1247   DOUT << "Derived new type: " << *PT << "\n";
1248 #endif
1249   return PT;
1250 }
1251
1252 bool VectorType::isValidElementType(const Type *ElemTy) {
1253   if (ElemTy->isInteger() || ElemTy->isFloatingPoint() ||
1254       isa<OpaqueType>(ElemTy))
1255     return true;
1256
1257   return false;
1258 }
1259
1260 //===----------------------------------------------------------------------===//
1261 // Struct Type Factory...
1262 //
1263
1264 namespace llvm {
1265 // StructValType - Define a class to hold the key that goes into the TypeMap
1266 //
1267 class StructValType {
1268   std::vector<const Type*> ElTypes;
1269   bool packed;
1270 public:
1271   StructValType(const std::vector<const Type*> &args, bool isPacked)
1272     : ElTypes(args), packed(isPacked) {}
1273
1274   static StructValType get(const StructType *ST) {
1275     std::vector<const Type *> ElTypes;
1276     ElTypes.reserve(ST->getNumElements());
1277     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
1278       ElTypes.push_back(ST->getElementType(i));
1279
1280     return StructValType(ElTypes, ST->isPacked());
1281   }
1282
1283   static unsigned hashTypeStructure(const StructType *ST) {
1284     return ST->getNumElements();
1285   }
1286
1287   inline bool operator<(const StructValType &STV) const {
1288     if (ElTypes < STV.ElTypes) return true;
1289     else if (ElTypes > STV.ElTypes) return false;
1290     else return (int)packed < (int)STV.packed;
1291   }
1292 };
1293 }
1294
1295 static ManagedStatic<TypeMap<StructValType, StructType> > StructTypes;
1296
1297 StructType *StructType::get(const std::vector<const Type*> &ETypes, 
1298                             bool isPacked) {
1299   StructValType STV(ETypes, isPacked);
1300   StructType *ST = 0;
1301   
1302   if (llvm_is_multithreaded()) {
1303     TypeMapLock->reader_acquire();
1304     ST = StructTypes->get(STV);
1305     TypeMapLock->reader_release();
1306     
1307     if (!ST) {
1308       TypeMapLock->writer_acquire();
1309       ST = StructTypes->get(STV);
1310       // Recheck.  Might have changed between release and acquire.
1311       if (!ST) {
1312         // Value not found.  Derive a new type!
1313         ST = (StructType*) operator new(sizeof(StructType) +
1314                                         sizeof(PATypeHandle) * ETypes.size());
1315         new (ST) StructType(ETypes, isPacked);
1316         StructTypes->add(STV, ST);
1317       }
1318       TypeMapLock->writer_release();
1319     }
1320   } else {
1321     ST = StructTypes->get(STV);
1322     if (ST) return ST;
1323     
1324     // Value not found.  Derive a new type!
1325     ST = (StructType*) operator new(sizeof(StructType) +
1326                                     sizeof(PATypeHandle) * ETypes.size());
1327     new (ST) StructType(ETypes, isPacked);
1328     StructTypes->add(STV, ST);
1329   }
1330 #ifdef DEBUG_MERGE_TYPES
1331   DOUT << "Derived new type: " << *ST << "\n";
1332 #endif
1333   return ST;
1334 }
1335
1336 StructType *StructType::get(const Type *type, ...) {
1337   va_list ap;
1338   std::vector<const llvm::Type*> StructFields;
1339   va_start(ap, type);
1340   while (type) {
1341     StructFields.push_back(type);
1342     type = va_arg(ap, llvm::Type*);
1343   }
1344   return llvm::StructType::get(StructFields);
1345 }
1346
1347 bool StructType::isValidElementType(const Type *ElemTy) {
1348   if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy ||
1349       ElemTy == Type::MetadataTy)
1350     return false;
1351
1352   if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1353     if (PTy->getElementType() == Type::MetadataTy)
1354       return false;
1355
1356   return true;
1357 }
1358
1359
1360 //===----------------------------------------------------------------------===//
1361 // Pointer Type Factory...
1362 //
1363
1364 // PointerValType - Define a class to hold the key that goes into the TypeMap
1365 //
1366 namespace llvm {
1367 class PointerValType {
1368   const Type *ValTy;
1369   unsigned AddressSpace;
1370 public:
1371   PointerValType(const Type *val, unsigned as) : ValTy(val), AddressSpace(as) {}
1372
1373   static PointerValType get(const PointerType *PT) {
1374     return PointerValType(PT->getElementType(), PT->getAddressSpace());
1375   }
1376
1377   static unsigned hashTypeStructure(const PointerType *PT) {
1378     return getSubElementHash(PT);
1379   }
1380
1381   bool operator<(const PointerValType &MTV) const {
1382     if (AddressSpace < MTV.AddressSpace) return true;
1383     return AddressSpace == MTV.AddressSpace && ValTy < MTV.ValTy;
1384   }
1385 };
1386 }
1387
1388 static ManagedStatic<TypeMap<PointerValType, PointerType> > PointerTypes;
1389
1390 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
1391   assert(ValueType && "Can't get a pointer to <null> type!");
1392   assert(ValueType != Type::VoidTy &&
1393          "Pointer to void is not valid, use i8* instead!");
1394   assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
1395   PointerValType PVT(ValueType, AddressSpace);
1396
1397   PointerType *PT = 0;
1398   
1399   if (llvm_is_multithreaded()) {
1400     TypeMapLock->reader_acquire();
1401     PT = PointerTypes->get(PVT);
1402     TypeMapLock->reader_release();
1403     
1404     if (!PT) {
1405       TypeMapLock->writer_acquire();
1406       PT = PointerTypes->get(PVT);
1407       // Recheck.  Might have changed between release and acquire.
1408       if (!PT) {
1409         // Value not found.  Derive a new type!
1410         PointerTypes->add(PVT, PT = new PointerType(ValueType, AddressSpace));
1411       }
1412       TypeMapLock->writer_release();
1413     }
1414   } else {
1415     PT = PointerTypes->get(PVT);
1416     if (PT) return PT;
1417     
1418     // Value not found.  Derive a new type!
1419     PointerTypes->add(PVT, PT = new PointerType(ValueType, AddressSpace));
1420   }
1421 #ifdef DEBUG_MERGE_TYPES
1422   DOUT << "Derived new type: " << *PT << "\n";
1423 #endif
1424   return PT;
1425 }
1426
1427 PointerType *Type::getPointerTo(unsigned addrs) const {
1428   return PointerType::get(this, addrs);
1429 }
1430
1431 bool PointerType::isValidElementType(const Type *ElemTy) {
1432   if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy)
1433     return false;
1434
1435   if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1436     if (PTy->getElementType() == Type::MetadataTy)
1437       return false;
1438
1439   return true;
1440 }
1441
1442
1443 //===----------------------------------------------------------------------===//
1444 //                     Derived Type Refinement Functions
1445 //===----------------------------------------------------------------------===//
1446
1447 // addAbstractTypeUser - Notify an abstract type that there is a new user of
1448 // it.  This function is called primarily by the PATypeHandle class.
1449 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
1450   assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
1451   if (llvm_is_multithreaded()) {
1452     AbstractTypeUsersLock->acquire();
1453     AbstractTypeUsers.push_back(U);
1454     AbstractTypeUsersLock->release();
1455   } else {
1456     AbstractTypeUsers.push_back(U);
1457   }
1458 }
1459
1460
1461 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1462 // no longer has a handle to the type.  This function is called primarily by
1463 // the PATypeHandle class.  When there are no users of the abstract type, it
1464 // is annihilated, because there is no way to get a reference to it ever again.
1465 //
1466 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1467   if (llvm_is_multithreaded()) AbstractTypeUsersLock->acquire();
1468   
1469   // Search from back to front because we will notify users from back to
1470   // front.  Also, it is likely that there will be a stack like behavior to
1471   // users that register and unregister users.
1472   //
1473   unsigned i;
1474   for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1475     assert(i != 0 && "AbstractTypeUser not in user list!");
1476
1477   --i;  // Convert to be in range 0 <= i < size()
1478   assert(i < AbstractTypeUsers.size() && "Index out of range!");  // Wraparound?
1479
1480   AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1481
1482 #ifdef DEBUG_MERGE_TYPES
1483   DOUT << "  remAbstractTypeUser[" << (void*)this << ", "
1484        << *this << "][" << i << "] User = " << U << "\n";
1485 #endif
1486
1487   if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1488 #ifdef DEBUG_MERGE_TYPES
1489     DOUT << "DELETEing unused abstract type: <" << *this
1490          << ">[" << (void*)this << "]" << "\n";
1491 #endif
1492   
1493   this->destroy();
1494   }
1495   
1496   if (llvm_is_multithreaded()) AbstractTypeUsersLock->release();
1497 }
1498
1499 // unlockedRefineAbstractTypeTo - This function is used when it is discovered
1500 // that the 'this' abstract type is actually equivalent to the NewType
1501 // specified. This causes all users of 'this' to switch to reference the more 
1502 // concrete type NewType and for 'this' to be deleted.  Only used for internal
1503 // callers.
1504 //
1505 void DerivedType::unlockedRefineAbstractTypeTo(const Type *NewType) {
1506   assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1507   assert(this != NewType && "Can't refine to myself!");
1508   assert(ForwardType == 0 && "This type has already been refined!");
1509
1510   // The descriptions may be out of date.  Conservatively clear them all!
1511   if (AbstractTypeDescriptions.isConstructed())
1512     AbstractTypeDescriptions->clear();
1513
1514 #ifdef DEBUG_MERGE_TYPES
1515   DOUT << "REFINING abstract type [" << (void*)this << " "
1516        << *this << "] to [" << (void*)NewType << " "
1517        << *NewType << "]!\n";
1518 #endif
1519
1520   // Make sure to put the type to be refined to into a holder so that if IT gets
1521   // refined, that we will not continue using a dead reference...
1522   //
1523   PATypeHolder NewTy(NewType);
1524   // Any PATypeHolders referring to this type will now automatically forward o
1525   // the type we are resolved to.
1526   ForwardType = NewType;
1527   if (NewType->isAbstract())
1528     cast<DerivedType>(NewType)->addRef();
1529
1530   // Add a self use of the current type so that we don't delete ourself until
1531   // after the function exits.
1532   //
1533   PATypeHolder CurrentTy(this);
1534
1535   // To make the situation simpler, we ask the subclass to remove this type from
1536   // the type map, and to replace any type uses with uses of non-abstract types.
1537   // This dramatically limits the amount of recursive type trouble we can find
1538   // ourselves in.
1539   dropAllTypeUses();
1540
1541   // Iterate over all of the uses of this type, invoking callback.  Each user
1542   // should remove itself from our use list automatically.  We have to check to
1543   // make sure that NewTy doesn't _become_ 'this'.  If it does, resolving types
1544   // will not cause users to drop off of the use list.  If we resolve to ourself
1545   // we succeed!
1546   //
1547   if (llvm_is_multithreaded()) AbstractTypeUsersLock->acquire();
1548   while (!AbstractTypeUsers.empty() && NewTy != this) {
1549     AbstractTypeUser *User = AbstractTypeUsers.back();
1550
1551     unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1552 #ifdef DEBUG_MERGE_TYPES
1553     DOUT << " REFINING user " << OldSize-1 << "[" << (void*)User
1554          << "] of abstract type [" << (void*)this << " "
1555          << *this << "] to [" << (void*)NewTy.get() << " "
1556          << *NewTy << "]!\n";
1557 #endif
1558     User->refineAbstractType(this, NewTy);
1559
1560     assert(AbstractTypeUsers.size() != OldSize &&
1561            "AbsTyUser did not remove self from user list!");
1562   }
1563   if (llvm_is_multithreaded()) AbstractTypeUsersLock->release();
1564
1565   // If we were successful removing all users from the type, 'this' will be
1566   // deleted when the last PATypeHolder is destroyed or updated from this type.
1567   // This may occur on exit of this function, as the CurrentTy object is
1568   // destroyed.
1569 }
1570
1571 // refineAbstractTypeTo - This function is used by external callers to notify
1572 // us that this abstract type is equivalent to another type.
1573 //
1574 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1575   if (llvm_is_multithreaded()) {
1576     // All recursive calls will go through unlockedRefineAbstractTypeTo,
1577     // to avoid deadlock problems.
1578     TypeMapLock->writer_acquire();
1579     unlockedRefineAbstractTypeTo(NewType);
1580     TypeMapLock->writer_release();
1581   } else {
1582     unlockedRefineAbstractTypeTo(NewType);
1583   }
1584 }
1585
1586 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1587 // the current type has transitioned from being abstract to being concrete.
1588 //
1589 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1590 #ifdef DEBUG_MERGE_TYPES
1591   DOUT << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1592 #endif
1593
1594   if (llvm_is_multithreaded()) AbstractTypeUsersLock->acquire();
1595   unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1596   while (!AbstractTypeUsers.empty()) {
1597     AbstractTypeUser *ATU = AbstractTypeUsers.back();
1598     ATU->typeBecameConcrete(this);
1599
1600     assert(AbstractTypeUsers.size() < OldSize-- &&
1601            "AbstractTypeUser did not remove itself from the use list!");
1602   }
1603   if (llvm_is_multithreaded()) AbstractTypeUsersLock->release();
1604 }
1605
1606 // refineAbstractType - Called when a contained type is found to be more
1607 // concrete - this could potentially change us from an abstract type to a
1608 // concrete type.
1609 //
1610 void FunctionType::refineAbstractType(const DerivedType *OldType,
1611                                       const Type *NewType) {
1612   FunctionTypes->RefineAbstractType(this, OldType, NewType);
1613 }
1614
1615 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1616   FunctionTypes->TypeBecameConcrete(this, AbsTy);
1617 }
1618
1619
1620 // refineAbstractType - Called when a contained type is found to be more
1621 // concrete - this could potentially change us from an abstract type to a
1622 // concrete type.
1623 //
1624 void ArrayType::refineAbstractType(const DerivedType *OldType,
1625                                    const Type *NewType) {
1626   ArrayTypes->RefineAbstractType(this, OldType, NewType);
1627 }
1628
1629 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1630   ArrayTypes->TypeBecameConcrete(this, AbsTy);
1631 }
1632
1633 // refineAbstractType - Called when a contained type is found to be more
1634 // concrete - this could potentially change us from an abstract type to a
1635 // concrete type.
1636 //
1637 void VectorType::refineAbstractType(const DerivedType *OldType,
1638                                    const Type *NewType) {
1639   VectorTypes->RefineAbstractType(this, OldType, NewType);
1640 }
1641
1642 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1643   VectorTypes->TypeBecameConcrete(this, AbsTy);
1644 }
1645
1646 // refineAbstractType - Called when a contained type is found to be more
1647 // concrete - this could potentially change us from an abstract type to a
1648 // concrete type.
1649 //
1650 void StructType::refineAbstractType(const DerivedType *OldType,
1651                                     const Type *NewType) {
1652   StructTypes->RefineAbstractType(this, OldType, NewType);
1653 }
1654
1655 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1656   StructTypes->TypeBecameConcrete(this, AbsTy);
1657 }
1658
1659 // refineAbstractType - Called when a contained type is found to be more
1660 // concrete - this could potentially change us from an abstract type to a
1661 // concrete type.
1662 //
1663 void PointerType::refineAbstractType(const DerivedType *OldType,
1664                                      const Type *NewType) {
1665   PointerTypes->RefineAbstractType(this, OldType, NewType);
1666 }
1667
1668 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1669   PointerTypes->TypeBecameConcrete(this, AbsTy);
1670 }
1671
1672 bool SequentialType::indexValid(const Value *V) const {
1673   if (isa<IntegerType>(V->getType())) 
1674     return true;
1675   return false;
1676 }
1677
1678 namespace llvm {
1679 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1680   if (T == 0)
1681     OS << "<null> value!\n";
1682   else
1683     T->print(OS);
1684   return OS;
1685 }
1686
1687 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1688   T.print(OS);
1689   return OS;
1690 }
1691
1692 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {
1693   T.print(OS);
1694   return OS;
1695 }
1696 }