As pointed out by Duncan, I accidentally dropped the first MemoryFence of the
[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 = 0;
457     static PATypeHolder* Holder = 0;
458     if (!AlwaysOpaqueTy) {
459       if (llvm_is_multithreaded()) {
460         llvm_acquire_global_lock();
461       
462         if (!AlwaysOpaqueTy) {
463           Type *tmp = OpaqueType::get();
464           PATypeHolder* tmp2 = new PATypeHolder(AlwaysOpaqueTy);
465           sys::MemoryFence();
466           AlwaysOpaqueTy = tmp;
467           Holder = tmp2;
468         }
469       
470         llvm_release_global_lock();
471       } else {
472         AlwaysOpaqueTy = OpaqueType::get();
473         Holder = new PATypeHolder(AlwaysOpaqueTy);
474       } 
475     }
476     
477     ContainedTys[0] = AlwaysOpaqueTy;
478
479     // Change the rest of the types to be Int32Ty's.  It doesn't matter what we
480     // pick so long as it doesn't point back to this type.  We choose something
481     // concrete to avoid overhead for adding to AbstracTypeUser lists and stuff.
482     for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
483       ContainedTys[i] = Type::Int32Ty;
484   }
485 }
486
487
488 namespace {
489
490 /// TypePromotionGraph and graph traits - this is designed to allow us to do
491 /// efficient SCC processing of type graphs.  This is the exact same as
492 /// GraphTraits<Type*>, except that we pretend that concrete types have no
493 /// children to avoid processing them.
494 struct TypePromotionGraph {
495   Type *Ty;
496   TypePromotionGraph(Type *T) : Ty(T) {}
497 };
498
499 }
500
501 namespace llvm {
502   template <> struct GraphTraits<TypePromotionGraph> {
503     typedef Type NodeType;
504     typedef Type::subtype_iterator ChildIteratorType;
505
506     static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
507     static inline ChildIteratorType child_begin(NodeType *N) {
508       if (N->isAbstract())
509         return N->subtype_begin();
510       else           // No need to process children of concrete types.
511         return N->subtype_end();
512     }
513     static inline ChildIteratorType child_end(NodeType *N) {
514       return N->subtype_end();
515     }
516   };
517 }
518
519
520 // PromoteAbstractToConcrete - This is a recursive function that walks a type
521 // graph calculating whether or not a type is abstract.
522 //
523 void Type::PromoteAbstractToConcrete() {
524   if (!isAbstract()) return;
525
526   scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
527   scc_iterator<TypePromotionGraph> SE = scc_end  (TypePromotionGraph(this));
528
529   for (; SI != SE; ++SI) {
530     std::vector<Type*> &SCC = *SI;
531
532     // Concrete types are leaves in the tree.  Since an SCC will either be all
533     // abstract or all concrete, we only need to check one type.
534     if (SCC[0]->isAbstract()) {
535       if (isa<OpaqueType>(SCC[0]))
536         return;     // Not going to be concrete, sorry.
537
538       // If all of the children of all of the types in this SCC are concrete,
539       // then this SCC is now concrete as well.  If not, neither this SCC, nor
540       // any parent SCCs will be concrete, so we might as well just exit.
541       for (unsigned i = 0, e = SCC.size(); i != e; ++i)
542         for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
543                E = SCC[i]->subtype_end(); CI != E; ++CI)
544           if ((*CI)->isAbstract())
545             // If the child type is in our SCC, it doesn't make the entire SCC
546             // abstract unless there is a non-SCC abstract type.
547             if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
548               return;               // Not going to be concrete, sorry.
549
550       // Okay, we just discovered this whole SCC is now concrete, mark it as
551       // such!
552       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
553         assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
554
555         SCC[i]->setAbstract(false);
556       }
557
558       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
559         assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
560         // The type just became concrete, notify all users!
561         cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
562       }
563     }
564   }
565 }
566
567
568 //===----------------------------------------------------------------------===//
569 //                      Type Structural Equality Testing
570 //===----------------------------------------------------------------------===//
571
572 // TypesEqual - Two types are considered structurally equal if they have the
573 // same "shape": Every level and element of the types have identical primitive
574 // ID's, and the graphs have the same edges/nodes in them.  Nodes do not have to
575 // be pointer equals to be equivalent though.  This uses an optimistic algorithm
576 // that assumes that two graphs are the same until proven otherwise.
577 //
578 static bool TypesEqual(const Type *Ty, const Type *Ty2,
579                        std::map<const Type *, const Type *> &EqTypes) {
580   if (Ty == Ty2) return true;
581   if (Ty->getTypeID() != Ty2->getTypeID()) return false;
582   if (isa<OpaqueType>(Ty))
583     return false;  // Two unequal opaque types are never equal
584
585   std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
586   if (It != EqTypes.end())
587     return It->second == Ty2;    // Looping back on a type, check for equality
588
589   // Otherwise, add the mapping to the table to make sure we don't get
590   // recursion on the types...
591   EqTypes.insert(It, std::make_pair(Ty, Ty2));
592
593   // Two really annoying special cases that breaks an otherwise nice simple
594   // algorithm is the fact that arraytypes have sizes that differentiates types,
595   // and that function types can be varargs or not.  Consider this now.
596   //
597   if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
598     const IntegerType *ITy2 = cast<IntegerType>(Ty2);
599     return ITy->getBitWidth() == ITy2->getBitWidth();
600   } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
601     const PointerType *PTy2 = cast<PointerType>(Ty2);
602     return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
603            TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
604   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
605     const StructType *STy2 = cast<StructType>(Ty2);
606     if (STy->getNumElements() != STy2->getNumElements()) return false;
607     if (STy->isPacked() != STy2->isPacked()) return false;
608     for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
609       if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
610         return false;
611     return true;
612   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
613     const ArrayType *ATy2 = cast<ArrayType>(Ty2);
614     return ATy->getNumElements() == ATy2->getNumElements() &&
615            TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
616   } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
617     const VectorType *PTy2 = cast<VectorType>(Ty2);
618     return PTy->getNumElements() == PTy2->getNumElements() &&
619            TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
620   } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
621     const FunctionType *FTy2 = cast<FunctionType>(Ty2);
622     if (FTy->isVarArg() != FTy2->isVarArg() ||
623         FTy->getNumParams() != FTy2->getNumParams() ||
624         !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
625       return false;
626     for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
627       if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
628         return false;
629     }
630     return true;
631   } else {
632     assert(0 && "Unknown derived type!");
633     return false;
634   }
635 }
636
637 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
638   std::map<const Type *, const Type *> EqTypes;
639   return TypesEqual(Ty, Ty2, EqTypes);
640 }
641
642 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
643 // TargetTy in the type graph.  We know that Ty is an abstract type, so if we
644 // ever reach a non-abstract type, we know that we don't need to search the
645 // subgraph.
646 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
647                                 SmallPtrSet<const Type*, 128> &VisitedTypes) {
648   if (TargetTy == CurTy) return true;
649   if (!CurTy->isAbstract()) return false;
650
651   if (!VisitedTypes.insert(CurTy))
652     return false;  // Already been here.
653
654   for (Type::subtype_iterator I = CurTy->subtype_begin(),
655        E = CurTy->subtype_end(); I != E; ++I)
656     if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
657       return true;
658   return false;
659 }
660
661 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
662                                 SmallPtrSet<const Type*, 128> &VisitedTypes) {
663   if (TargetTy == CurTy) return true;
664
665   if (!VisitedTypes.insert(CurTy))
666     return false;  // Already been here.
667
668   for (Type::subtype_iterator I = CurTy->subtype_begin(),
669        E = CurTy->subtype_end(); I != E; ++I)
670     if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
671       return true;
672   return false;
673 }
674
675 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
676 /// back to itself.
677 static bool TypeHasCycleThroughItself(const Type *Ty) {
678   SmallPtrSet<const Type*, 128> VisitedTypes;
679
680   if (Ty->isAbstract()) {  // Optimized case for abstract types.
681     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
682          I != E; ++I)
683       if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
684         return true;
685   } else {
686     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
687          I != E; ++I)
688       if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
689         return true;
690   }
691   return false;
692 }
693
694 /// getSubElementHash - Generate a hash value for all of the SubType's of this
695 /// type.  The hash value is guaranteed to be zero if any of the subtypes are 
696 /// an opaque type.  Otherwise we try to mix them in as well as possible, but do
697 /// not look at the subtype's subtype's.
698 static unsigned getSubElementHash(const Type *Ty) {
699   unsigned HashVal = 0;
700   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
701        I != E; ++I) {
702     HashVal *= 32;
703     const Type *SubTy = I->get();
704     HashVal += SubTy->getTypeID();
705     switch (SubTy->getTypeID()) {
706     default: break;
707     case Type::OpaqueTyID: return 0;    // Opaque -> hash = 0 no matter what.
708     case Type::IntegerTyID:
709       HashVal ^= (cast<IntegerType>(SubTy)->getBitWidth() << 3);
710       break;
711     case Type::FunctionTyID:
712       HashVal ^= cast<FunctionType>(SubTy)->getNumParams()*2 + 
713                  cast<FunctionType>(SubTy)->isVarArg();
714       break;
715     case Type::ArrayTyID:
716       HashVal ^= cast<ArrayType>(SubTy)->getNumElements();
717       break;
718     case Type::VectorTyID:
719       HashVal ^= cast<VectorType>(SubTy)->getNumElements();
720       break;
721     case Type::StructTyID:
722       HashVal ^= cast<StructType>(SubTy)->getNumElements();
723       break;
724     case Type::PointerTyID:
725       HashVal ^= cast<PointerType>(SubTy)->getAddressSpace();
726       break;
727     }
728   }
729   return HashVal ? HashVal : 1;  // Do not return zero unless opaque subty.
730 }
731
732 //===----------------------------------------------------------------------===//
733 //                       Derived Type Factory Functions
734 //===----------------------------------------------------------------------===//
735
736 namespace llvm {
737 class TypeMapBase {
738 protected:
739   /// TypesByHash - Keep track of types by their structure hash value.  Note
740   /// that we only keep track of types that have cycles through themselves in
741   /// this map.
742   ///
743   std::multimap<unsigned, PATypeHolder> TypesByHash;
744
745 public:
746   ~TypeMapBase() {
747     // PATypeHolder won't destroy non-abstract types.
748     // We can't destroy them by simply iterating, because
749     // they may contain references to each-other.
750 #if 0
751     for (std::multimap<unsigned, PATypeHolder>::iterator I
752          = TypesByHash.begin(), E = TypesByHash.end(); I != E; ++I) {
753       Type *Ty = const_cast<Type*>(I->second.Ty);
754       I->second.destroy();
755       // We can't invoke destroy or delete, because the type may
756       // contain references to already freed types.
757       // So we have to destruct the object the ugly way.
758       if (Ty) {
759         Ty->AbstractTypeUsers.clear();
760         static_cast<const Type*>(Ty)->Type::~Type();
761         operator delete(Ty);
762       }
763     }
764 #endif
765   }
766
767   void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
768     std::multimap<unsigned, PATypeHolder>::iterator I =
769       TypesByHash.lower_bound(Hash);
770     for (; I != TypesByHash.end() && I->first == Hash; ++I) {
771       if (I->second == Ty) {
772         TypesByHash.erase(I);
773         return;
774       }
775     }
776     
777     // This must be do to an opaque type that was resolved.  Switch down to hash
778     // code of zero.
779     assert(Hash && "Didn't find type entry!");
780     RemoveFromTypesByHash(0, Ty);
781   }
782   
783   /// TypeBecameConcrete - When Ty gets a notification that TheType just became
784   /// concrete, drop uses and make Ty non-abstract if we should.
785   void TypeBecameConcrete(DerivedType *Ty, const DerivedType *TheType) {
786     // If the element just became concrete, remove 'ty' from the abstract
787     // type user list for the type.  Do this for as many times as Ty uses
788     // OldType.
789     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
790          I != E; ++I)
791       if (I->get() == TheType)
792         TheType->removeAbstractTypeUser(Ty);
793     
794     // If the type is currently thought to be abstract, rescan all of our
795     // subtypes to see if the type has just become concrete!  Note that this
796     // may send out notifications to AbstractTypeUsers that types become
797     // concrete.
798     if (Ty->isAbstract())
799       Ty->PromoteAbstractToConcrete();
800   }
801 };
802 }
803
804
805 // TypeMap - Make sure that only one instance of a particular type may be
806 // created on any given run of the compiler... note that this involves updating
807 // our map if an abstract type gets refined somehow.
808 //
809 namespace llvm {
810 template<class ValType, class TypeClass>
811 class TypeMap : public TypeMapBase {
812   std::map<ValType, PATypeHolder> Map;
813 public:
814   typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
815   ~TypeMap() { print("ON EXIT"); }
816
817   inline TypeClass *get(const ValType &V) {
818     iterator I = Map.find(V);
819     return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
820   }
821
822   inline void add(const ValType &V, TypeClass *Ty) {
823     Map.insert(std::make_pair(V, Ty));
824
825     // If this type has a cycle, remember it.
826     TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
827     print("add");
828   }
829   
830   /// RefineAbstractType - This method is called after we have merged a type
831   /// with another one.  We must now either merge the type away with
832   /// some other type or reinstall it in the map with it's new configuration.
833   void RefineAbstractType(TypeClass *Ty, const DerivedType *OldType,
834                         const Type *NewType) {
835 #ifdef DEBUG_MERGE_TYPES
836     DOUT << "RefineAbstractType(" << (void*)OldType << "[" << *OldType
837          << "], " << (void*)NewType << " [" << *NewType << "])\n";
838 #endif
839     
840     // Otherwise, we are changing one subelement type into another.  Clearly the
841     // OldType must have been abstract, making us abstract.
842     assert(Ty->isAbstract() && "Refining a non-abstract type!");
843     assert(OldType != NewType);
844
845     // Make a temporary type holder for the type so that it doesn't disappear on
846     // us when we erase the entry from the map.
847     PATypeHolder TyHolder = Ty;
848
849     // The old record is now out-of-date, because one of the children has been
850     // updated.  Remove the obsolete entry from the map.
851     unsigned NumErased = Map.erase(ValType::get(Ty));
852     assert(NumErased && "Element not found!"); NumErased = NumErased;
853
854     // Remember the structural hash for the type before we start hacking on it,
855     // in case we need it later.
856     unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
857
858     // Find the type element we are refining... and change it now!
859     for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i)
860       if (Ty->ContainedTys[i] == OldType)
861         Ty->ContainedTys[i] = NewType;
862     unsigned NewTypeHash = ValType::hashTypeStructure(Ty);
863     
864     // If there are no cycles going through this node, we can do a simple,
865     // efficient lookup in the map, instead of an inefficient nasty linear
866     // lookup.
867     if (!TypeHasCycleThroughItself(Ty)) {
868       typename std::map<ValType, PATypeHolder>::iterator I;
869       bool Inserted;
870
871       tie(I, Inserted) = Map.insert(std::make_pair(ValType::get(Ty), Ty));
872       if (!Inserted) {
873         // Refined to a different type altogether?
874         RemoveFromTypesByHash(OldTypeHash, Ty);
875
876         // We already have this type in the table.  Get rid of the newly refined
877         // type.
878         TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
879         Ty->unlockedRefineAbstractTypeTo(NewTy);
880         return;
881       }
882     } else {
883       // Now we check to see if there is an existing entry in the table which is
884       // structurally identical to the newly refined type.  If so, this type
885       // gets refined to the pre-existing type.
886       //
887       std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry;
888       tie(I, E) = TypesByHash.equal_range(NewTypeHash);
889       Entry = E;
890       for (; I != E; ++I) {
891         if (I->second == Ty) {
892           // Remember the position of the old type if we see it in our scan.
893           Entry = I;
894         } else {
895           if (TypesEqual(Ty, I->second)) {
896             TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
897
898             // Remove the old entry form TypesByHash.  If the hash values differ
899             // now, remove it from the old place.  Otherwise, continue scanning
900             // withing this hashcode to reduce work.
901             if (NewTypeHash != OldTypeHash) {
902               RemoveFromTypesByHash(OldTypeHash, Ty);
903             } else {
904               if (Entry == E) {
905                 // Find the location of Ty in the TypesByHash structure if we
906                 // haven't seen it already.
907                 while (I->second != Ty) {
908                   ++I;
909                   assert(I != E && "Structure doesn't contain type??");
910                 }
911                 Entry = I;
912               }
913               TypesByHash.erase(Entry);
914             }
915             Ty->unlockedRefineAbstractTypeTo(NewTy);
916             return;
917           }
918         }
919       }
920
921       // If there is no existing type of the same structure, we reinsert an
922       // updated record into the map.
923       Map.insert(std::make_pair(ValType::get(Ty), Ty));
924     }
925
926     // If the hash codes differ, update TypesByHash
927     if (NewTypeHash != OldTypeHash) {
928       RemoveFromTypesByHash(OldTypeHash, Ty);
929       TypesByHash.insert(std::make_pair(NewTypeHash, Ty));
930     }
931     
932     // If the type is currently thought to be abstract, rescan all of our
933     // subtypes to see if the type has just become concrete!  Note that this
934     // may send out notifications to AbstractTypeUsers that types become
935     // concrete.
936     if (Ty->isAbstract())
937       Ty->PromoteAbstractToConcrete();
938   }
939
940   void print(const char *Arg) const {
941 #ifdef DEBUG_MERGE_TYPES
942     DOUT << "TypeMap<>::" << Arg << " table contents:\n";
943     unsigned i = 0;
944     for (typename std::map<ValType, PATypeHolder>::const_iterator I
945            = Map.begin(), E = Map.end(); I != E; ++I)
946       DOUT << " " << (++i) << ". " << (void*)I->second.get() << " "
947            << *I->second.get() << "\n";
948 #endif
949   }
950
951   void dump() const { print("dump output"); }
952 };
953 }
954
955
956 //===----------------------------------------------------------------------===//
957 // Function Type Factory and Value Class...
958 //
959
960 //===----------------------------------------------------------------------===//
961 // Integer Type Factory...
962 //
963 namespace llvm {
964 class IntegerValType {
965   uint32_t bits;
966 public:
967   IntegerValType(uint16_t numbits) : bits(numbits) {}
968
969   static IntegerValType get(const IntegerType *Ty) {
970     return IntegerValType(Ty->getBitWidth());
971   }
972
973   static unsigned hashTypeStructure(const IntegerType *Ty) {
974     return (unsigned)Ty->getBitWidth();
975   }
976
977   inline bool operator<(const IntegerValType &IVT) const {
978     return bits < IVT.bits;
979   }
980 };
981 }
982
983 static ManagedStatic<TypeMap<IntegerValType, IntegerType> > IntegerTypes;
984
985 const IntegerType *IntegerType::get(unsigned NumBits) {
986   assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
987   assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
988
989   // Check for the built-in integer types
990   switch (NumBits) {
991     case  1: return cast<IntegerType>(Type::Int1Ty);
992     case  8: return cast<IntegerType>(Type::Int8Ty);
993     case 16: return cast<IntegerType>(Type::Int16Ty);
994     case 32: return cast<IntegerType>(Type::Int32Ty);
995     case 64: return cast<IntegerType>(Type::Int64Ty);
996     default: 
997       break;
998   }
999   
1000   IntegerValType IVT(NumBits);
1001   IntegerType *ITy = 0;
1002   if (llvm_is_multithreaded()) {
1003     // First, see if the type is already in the table, for which
1004     // a reader lock suffices.
1005     TypeMapLock->reader_acquire();
1006     ITy = IntegerTypes->get(IVT);
1007     TypeMapLock->reader_release();
1008     
1009     if (!ITy) {
1010       // OK, not in the table, get a writer lock.
1011       TypeMapLock->writer_acquire();
1012       ITy = IntegerTypes->get(IVT);
1013       
1014       // We need to _recheck_ the table in case someone
1015       // put it in between when we released the reader lock
1016       // and when we gained the writer lock!
1017       if (!ITy) {
1018         // Value not found.  Derive a new type!
1019         ITy = new IntegerType(NumBits);
1020         IntegerTypes->add(IVT, ITy);
1021       }
1022       
1023       TypeMapLock->writer_release();
1024     }
1025   } else {
1026     ITy = IntegerTypes->get(IVT);
1027     if (ITy) return ITy;           // Found a match, return it!
1028
1029     // Value not found.  Derive a new type!
1030     ITy = new IntegerType(NumBits);
1031     IntegerTypes->add(IVT, ITy);
1032   }
1033 #ifdef DEBUG_MERGE_TYPES
1034   DOUT << "Derived new type: " << *ITy << "\n";
1035 #endif
1036   return ITy;
1037 }
1038
1039 bool IntegerType::isPowerOf2ByteWidth() const {
1040   unsigned BitWidth = getBitWidth();
1041   return (BitWidth > 7) && isPowerOf2_32(BitWidth);
1042 }
1043
1044 APInt IntegerType::getMask() const {
1045   return APInt::getAllOnesValue(getBitWidth());
1046 }
1047
1048 // FunctionValType - Define a class to hold the key that goes into the TypeMap
1049 //
1050 namespace llvm {
1051 class FunctionValType {
1052   const Type *RetTy;
1053   std::vector<const Type*> ArgTypes;
1054   bool isVarArg;
1055 public:
1056   FunctionValType(const Type *ret, const std::vector<const Type*> &args,
1057                   bool isVA) : RetTy(ret), ArgTypes(args), isVarArg(isVA) {}
1058
1059   static FunctionValType get(const FunctionType *FT);
1060
1061   static unsigned hashTypeStructure(const FunctionType *FT) {
1062     unsigned Result = FT->getNumParams()*2 + FT->isVarArg();
1063     return Result;
1064   }
1065
1066   inline bool operator<(const FunctionValType &MTV) const {
1067     if (RetTy < MTV.RetTy) return true;
1068     if (RetTy > MTV.RetTy) return false;
1069     if (isVarArg < MTV.isVarArg) return true;
1070     if (isVarArg > MTV.isVarArg) return false;
1071     if (ArgTypes < MTV.ArgTypes) return true;
1072     if (ArgTypes > MTV.ArgTypes) return false;
1073     return false;
1074   }
1075 };
1076 }
1077
1078 // Define the actual map itself now...
1079 static ManagedStatic<TypeMap<FunctionValType, FunctionType> > FunctionTypes;
1080
1081 FunctionValType FunctionValType::get(const FunctionType *FT) {
1082   // Build up a FunctionValType
1083   std::vector<const Type *> ParamTypes;
1084   ParamTypes.reserve(FT->getNumParams());
1085   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1086     ParamTypes.push_back(FT->getParamType(i));
1087   return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
1088 }
1089
1090
1091 // FunctionType::get - The factory function for the FunctionType class...
1092 FunctionType *FunctionType::get(const Type *ReturnType,
1093                                 const std::vector<const Type*> &Params,
1094                                 bool isVarArg) {
1095   FunctionValType VT(ReturnType, Params, isVarArg);
1096   FunctionType *FT = 0;
1097   
1098   if (llvm_is_multithreaded()) {
1099     TypeMapLock->reader_acquire();
1100     FT = FunctionTypes->get(VT);
1101     TypeMapLock->reader_release();
1102     
1103     if (!FT) {
1104       TypeMapLock->writer_acquire();
1105       
1106       // Have to check again here, because it might have
1107       // been inserted between when we release the reader
1108       // lock and when we acquired the writer lock.
1109       FT = FunctionTypes->get(VT);
1110       if (!FT) {
1111         FT = (FunctionType*) operator new(sizeof(FunctionType) +
1112                                         sizeof(PATypeHandle)*(Params.size()+1));
1113         new (FT) FunctionType(ReturnType, Params, isVarArg);
1114         FunctionTypes->add(VT, FT);
1115       }
1116       TypeMapLock->writer_release();
1117     }
1118   } else {
1119     FT = FunctionTypes->get(VT);
1120     if (FT)
1121       return FT;
1122
1123     FT = (FunctionType*) operator new(sizeof(FunctionType) +
1124                                       sizeof(PATypeHandle)*(Params.size()+1));
1125     new (FT) FunctionType(ReturnType, Params, isVarArg);
1126     FunctionTypes->add(VT, FT);
1127   }
1128   
1129 #ifdef DEBUG_MERGE_TYPES
1130   DOUT << "Derived new type: " << FT << "\n";
1131 #endif
1132   return FT;
1133 }
1134
1135 //===----------------------------------------------------------------------===//
1136 // Array Type Factory...
1137 //
1138 namespace llvm {
1139 class ArrayValType {
1140   const Type *ValTy;
1141   uint64_t Size;
1142 public:
1143   ArrayValType(const Type *val, uint64_t sz) : ValTy(val), Size(sz) {}
1144
1145   static ArrayValType get(const ArrayType *AT) {
1146     return ArrayValType(AT->getElementType(), AT->getNumElements());
1147   }
1148
1149   static unsigned hashTypeStructure(const ArrayType *AT) {
1150     return (unsigned)AT->getNumElements();
1151   }
1152
1153   inline bool operator<(const ArrayValType &MTV) const {
1154     if (Size < MTV.Size) return true;
1155     return Size == MTV.Size && ValTy < MTV.ValTy;
1156   }
1157 };
1158 }
1159
1160 static ManagedStatic<TypeMap<ArrayValType, ArrayType> > ArrayTypes;
1161
1162 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
1163   assert(ElementType && "Can't get array of <null> types!");
1164   assert(isValidElementType(ElementType) && "Invalid type for array element!");
1165
1166   ArrayValType AVT(ElementType, NumElements);
1167   ArrayType *AT = 0;
1168   
1169   if (llvm_is_multithreaded()) {
1170     TypeMapLock->reader_acquire();
1171     AT = ArrayTypes->get(AVT);
1172     TypeMapLock->reader_release();
1173     
1174     if (!AT) {
1175       TypeMapLock->writer_acquire();
1176       
1177       // Recheck.  Might have changed between release and acquire.
1178       AT = ArrayTypes->get(AVT);
1179       if (!AT) {
1180         // Value not found.  Derive a new type!
1181         ArrayTypes->add(AVT, AT = new ArrayType(ElementType, NumElements));
1182       }
1183       TypeMapLock->writer_release();
1184     }
1185   } else {
1186     AT = ArrayTypes->get(AVT);
1187     if (AT) return AT;           // Found a match, return it!
1188     
1189     // Value not found.  Derive a new type!
1190     ArrayTypes->add(AVT, AT = new ArrayType(ElementType, NumElements));
1191   }
1192 #ifdef DEBUG_MERGE_TYPES
1193   DOUT << "Derived new type: " << *AT << "\n";
1194 #endif
1195   return AT;
1196 }
1197
1198 bool ArrayType::isValidElementType(const Type *ElemTy) {
1199   if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy ||
1200       ElemTy == Type::MetadataTy)
1201     return false;
1202
1203   if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1204     if (PTy->getElementType() == Type::MetadataTy)
1205       return false;
1206
1207   return true;
1208 }
1209
1210
1211 //===----------------------------------------------------------------------===//
1212 // Vector Type Factory...
1213 //
1214 namespace llvm {
1215 class VectorValType {
1216   const Type *ValTy;
1217   unsigned Size;
1218 public:
1219   VectorValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
1220
1221   static VectorValType get(const VectorType *PT) {
1222     return VectorValType(PT->getElementType(), PT->getNumElements());
1223   }
1224
1225   static unsigned hashTypeStructure(const VectorType *PT) {
1226     return PT->getNumElements();
1227   }
1228
1229   inline bool operator<(const VectorValType &MTV) const {
1230     if (Size < MTV.Size) return true;
1231     return Size == MTV.Size && ValTy < MTV.ValTy;
1232   }
1233 };
1234 }
1235
1236 static ManagedStatic<TypeMap<VectorValType, VectorType> > VectorTypes;
1237
1238 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
1239   assert(ElementType && "Can't get vector of <null> types!");
1240
1241   VectorValType PVT(ElementType, NumElements);
1242   VectorType *PT = 0;
1243   
1244   if (llvm_is_multithreaded()) {
1245     TypeMapLock->reader_acquire();
1246     PT = VectorTypes->get(PVT);
1247     TypeMapLock->reader_release();
1248     
1249     if (!PT) {
1250       TypeMapLock->writer_acquire();
1251       PT = VectorTypes->get(PVT);
1252       // Recheck.  Might have changed between release and acquire.
1253       if (!PT) {
1254         VectorTypes->add(PVT, PT = new VectorType(ElementType, NumElements));
1255       }
1256       TypeMapLock->writer_acquire();
1257     }
1258   } else {
1259     PT = VectorTypes->get(PVT);
1260     if (PT) return PT;           // Found a match, return it!
1261     
1262     // Value not found.  Derive a new type!
1263     VectorTypes->add(PVT, PT = new VectorType(ElementType, NumElements));
1264   }
1265 #ifdef DEBUG_MERGE_TYPES
1266   DOUT << "Derived new type: " << *PT << "\n";
1267 #endif
1268   return PT;
1269 }
1270
1271 bool VectorType::isValidElementType(const Type *ElemTy) {
1272   if (ElemTy->isInteger() || ElemTy->isFloatingPoint() ||
1273       isa<OpaqueType>(ElemTy))
1274     return true;
1275
1276   return false;
1277 }
1278
1279 //===----------------------------------------------------------------------===//
1280 // Struct Type Factory...
1281 //
1282
1283 namespace llvm {
1284 // StructValType - Define a class to hold the key that goes into the TypeMap
1285 //
1286 class StructValType {
1287   std::vector<const Type*> ElTypes;
1288   bool packed;
1289 public:
1290   StructValType(const std::vector<const Type*> &args, bool isPacked)
1291     : ElTypes(args), packed(isPacked) {}
1292
1293   static StructValType get(const StructType *ST) {
1294     std::vector<const Type *> ElTypes;
1295     ElTypes.reserve(ST->getNumElements());
1296     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
1297       ElTypes.push_back(ST->getElementType(i));
1298
1299     return StructValType(ElTypes, ST->isPacked());
1300   }
1301
1302   static unsigned hashTypeStructure(const StructType *ST) {
1303     return ST->getNumElements();
1304   }
1305
1306   inline bool operator<(const StructValType &STV) const {
1307     if (ElTypes < STV.ElTypes) return true;
1308     else if (ElTypes > STV.ElTypes) return false;
1309     else return (int)packed < (int)STV.packed;
1310   }
1311 };
1312 }
1313
1314 static ManagedStatic<TypeMap<StructValType, StructType> > StructTypes;
1315
1316 StructType *StructType::get(const std::vector<const Type*> &ETypes, 
1317                             bool isPacked) {
1318   StructValType STV(ETypes, isPacked);
1319   StructType *ST = 0;
1320   
1321   if (llvm_is_multithreaded()) {
1322     TypeMapLock->reader_acquire();
1323     ST = StructTypes->get(STV);
1324     TypeMapLock->reader_release();
1325     
1326     if (!ST) {
1327       TypeMapLock->writer_acquire();
1328       ST = StructTypes->get(STV);
1329       // Recheck.  Might have changed between release and acquire.
1330       if (!ST) {
1331         // Value not found.  Derive a new type!
1332         ST = (StructType*) operator new(sizeof(StructType) +
1333                                         sizeof(PATypeHandle) * ETypes.size());
1334         new (ST) StructType(ETypes, isPacked);
1335         StructTypes->add(STV, ST);
1336       }
1337       TypeMapLock->writer_release();
1338     }
1339   } else {
1340     ST = StructTypes->get(STV);
1341     if (ST) return ST;
1342     
1343     // Value not found.  Derive a new type!
1344     ST = (StructType*) operator new(sizeof(StructType) +
1345                                     sizeof(PATypeHandle) * ETypes.size());
1346     new (ST) StructType(ETypes, isPacked);
1347     StructTypes->add(STV, ST);
1348   }
1349 #ifdef DEBUG_MERGE_TYPES
1350   DOUT << "Derived new type: " << *ST << "\n";
1351 #endif
1352   return ST;
1353 }
1354
1355 StructType *StructType::get(const Type *type, ...) {
1356   va_list ap;
1357   std::vector<const llvm::Type*> StructFields;
1358   va_start(ap, type);
1359   while (type) {
1360     StructFields.push_back(type);
1361     type = va_arg(ap, llvm::Type*);
1362   }
1363   return llvm::StructType::get(StructFields);
1364 }
1365
1366 bool StructType::isValidElementType(const Type *ElemTy) {
1367   if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy ||
1368       ElemTy == Type::MetadataTy)
1369     return false;
1370
1371   if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1372     if (PTy->getElementType() == Type::MetadataTy)
1373       return false;
1374
1375   return true;
1376 }
1377
1378
1379 //===----------------------------------------------------------------------===//
1380 // Pointer Type Factory...
1381 //
1382
1383 // PointerValType - Define a class to hold the key that goes into the TypeMap
1384 //
1385 namespace llvm {
1386 class PointerValType {
1387   const Type *ValTy;
1388   unsigned AddressSpace;
1389 public:
1390   PointerValType(const Type *val, unsigned as) : ValTy(val), AddressSpace(as) {}
1391
1392   static PointerValType get(const PointerType *PT) {
1393     return PointerValType(PT->getElementType(), PT->getAddressSpace());
1394   }
1395
1396   static unsigned hashTypeStructure(const PointerType *PT) {
1397     return getSubElementHash(PT);
1398   }
1399
1400   bool operator<(const PointerValType &MTV) const {
1401     if (AddressSpace < MTV.AddressSpace) return true;
1402     return AddressSpace == MTV.AddressSpace && ValTy < MTV.ValTy;
1403   }
1404 };
1405 }
1406
1407 static ManagedStatic<TypeMap<PointerValType, PointerType> > PointerTypes;
1408
1409 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
1410   assert(ValueType && "Can't get a pointer to <null> type!");
1411   assert(ValueType != Type::VoidTy &&
1412          "Pointer to void is not valid, use i8* instead!");
1413   assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
1414   PointerValType PVT(ValueType, AddressSpace);
1415
1416   PointerType *PT = 0;
1417   
1418   if (llvm_is_multithreaded()) {
1419     TypeMapLock->reader_acquire();
1420     PT = PointerTypes->get(PVT);
1421     TypeMapLock->reader_release();
1422     
1423     if (!PT) {
1424       TypeMapLock->writer_acquire();
1425       PT = PointerTypes->get(PVT);
1426       // Recheck.  Might have changed between release and acquire.
1427       if (!PT) {
1428         // Value not found.  Derive a new type!
1429         PointerTypes->add(PVT, PT = new PointerType(ValueType, AddressSpace));
1430       }
1431       TypeMapLock->writer_release();
1432     }
1433   } else {
1434     PT = PointerTypes->get(PVT);
1435     if (PT) return PT;
1436     
1437     // Value not found.  Derive a new type!
1438     PointerTypes->add(PVT, PT = new PointerType(ValueType, AddressSpace));
1439   }
1440 #ifdef DEBUG_MERGE_TYPES
1441   DOUT << "Derived new type: " << *PT << "\n";
1442 #endif
1443   return PT;
1444 }
1445
1446 PointerType *Type::getPointerTo(unsigned addrs) const {
1447   return PointerType::get(this, addrs);
1448 }
1449
1450 bool PointerType::isValidElementType(const Type *ElemTy) {
1451   if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy)
1452     return false;
1453
1454   if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1455     if (PTy->getElementType() == Type::MetadataTy)
1456       return false;
1457
1458   return true;
1459 }
1460
1461
1462 //===----------------------------------------------------------------------===//
1463 //                     Derived Type Refinement Functions
1464 //===----------------------------------------------------------------------===//
1465
1466 // addAbstractTypeUser - Notify an abstract type that there is a new user of
1467 // it.  This function is called primarily by the PATypeHandle class.
1468 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
1469   assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
1470   if (llvm_is_multithreaded()) {
1471     AbstractTypeUsersLock->acquire();
1472     AbstractTypeUsers.push_back(U);
1473     AbstractTypeUsersLock->release();
1474   } else {
1475     AbstractTypeUsers.push_back(U);
1476   }
1477 }
1478
1479
1480 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1481 // no longer has a handle to the type.  This function is called primarily by
1482 // the PATypeHandle class.  When there are no users of the abstract type, it
1483 // is annihilated, because there is no way to get a reference to it ever again.
1484 //
1485 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1486   if (llvm_is_multithreaded()) AbstractTypeUsersLock->acquire();
1487   
1488   // Search from back to front because we will notify users from back to
1489   // front.  Also, it is likely that there will be a stack like behavior to
1490   // users that register and unregister users.
1491   //
1492   unsigned i;
1493   for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1494     assert(i != 0 && "AbstractTypeUser not in user list!");
1495
1496   --i;  // Convert to be in range 0 <= i < size()
1497   assert(i < AbstractTypeUsers.size() && "Index out of range!");  // Wraparound?
1498
1499   AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1500
1501 #ifdef DEBUG_MERGE_TYPES
1502   DOUT << "  remAbstractTypeUser[" << (void*)this << ", "
1503        << *this << "][" << i << "] User = " << U << "\n";
1504 #endif
1505
1506   if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1507 #ifdef DEBUG_MERGE_TYPES
1508     DOUT << "DELETEing unused abstract type: <" << *this
1509          << ">[" << (void*)this << "]" << "\n";
1510 #endif
1511   
1512   this->destroy();
1513   }
1514   
1515   if (llvm_is_multithreaded()) AbstractTypeUsersLock->release();
1516 }
1517
1518 // unlockedRefineAbstractTypeTo - This function is used when it is discovered
1519 // that the 'this' abstract type is actually equivalent to the NewType
1520 // specified. This causes all users of 'this' to switch to reference the more 
1521 // concrete type NewType and for 'this' to be deleted.  Only used for internal
1522 // callers.
1523 //
1524 void DerivedType::unlockedRefineAbstractTypeTo(const Type *NewType) {
1525   assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1526   assert(this != NewType && "Can't refine to myself!");
1527   assert(ForwardType == 0 && "This type has already been refined!");
1528
1529   // The descriptions may be out of date.  Conservatively clear them all!
1530   if (AbstractTypeDescriptions.isConstructed())
1531     AbstractTypeDescriptions->clear();
1532
1533 #ifdef DEBUG_MERGE_TYPES
1534   DOUT << "REFINING abstract type [" << (void*)this << " "
1535        << *this << "] to [" << (void*)NewType << " "
1536        << *NewType << "]!\n";
1537 #endif
1538
1539   // Make sure to put the type to be refined to into a holder so that if IT gets
1540   // refined, that we will not continue using a dead reference...
1541   //
1542   PATypeHolder NewTy(NewType);
1543   // Any PATypeHolders referring to this type will now automatically forward o
1544   // the type we are resolved to.
1545   ForwardType = NewType;
1546   if (NewType->isAbstract())
1547     cast<DerivedType>(NewType)->addRef();
1548
1549   // Add a self use of the current type so that we don't delete ourself until
1550   // after the function exits.
1551   //
1552   PATypeHolder CurrentTy(this);
1553
1554   // To make the situation simpler, we ask the subclass to remove this type from
1555   // the type map, and to replace any type uses with uses of non-abstract types.
1556   // This dramatically limits the amount of recursive type trouble we can find
1557   // ourselves in.
1558   dropAllTypeUses();
1559
1560   // Iterate over all of the uses of this type, invoking callback.  Each user
1561   // should remove itself from our use list automatically.  We have to check to
1562   // make sure that NewTy doesn't _become_ 'this'.  If it does, resolving types
1563   // will not cause users to drop off of the use list.  If we resolve to ourself
1564   // we succeed!
1565   //
1566   if (llvm_is_multithreaded()) AbstractTypeUsersLock->acquire();
1567   while (!AbstractTypeUsers.empty() && NewTy != this) {
1568     AbstractTypeUser *User = AbstractTypeUsers.back();
1569
1570     unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1571 #ifdef DEBUG_MERGE_TYPES
1572     DOUT << " REFINING user " << OldSize-1 << "[" << (void*)User
1573          << "] of abstract type [" << (void*)this << " "
1574          << *this << "] to [" << (void*)NewTy.get() << " "
1575          << *NewTy << "]!\n";
1576 #endif
1577     User->refineAbstractType(this, NewTy);
1578
1579     assert(AbstractTypeUsers.size() != OldSize &&
1580            "AbsTyUser did not remove self from user list!");
1581   }
1582   if (llvm_is_multithreaded()) AbstractTypeUsersLock->release();
1583
1584   // If we were successful removing all users from the type, 'this' will be
1585   // deleted when the last PATypeHolder is destroyed or updated from this type.
1586   // This may occur on exit of this function, as the CurrentTy object is
1587   // destroyed.
1588 }
1589
1590 // refineAbstractTypeTo - This function is used by external callers to notify
1591 // us that this abstract type is equivalent to another type.
1592 //
1593 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1594   if (llvm_is_multithreaded()) {
1595     // All recursive calls will go through unlockedRefineAbstractTypeTo,
1596     // to avoid deadlock problems.
1597     TypeMapLock->writer_acquire();
1598     unlockedRefineAbstractTypeTo(NewType);
1599     TypeMapLock->writer_release();
1600   } else {
1601     unlockedRefineAbstractTypeTo(NewType);
1602   }
1603 }
1604
1605 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1606 // the current type has transitioned from being abstract to being concrete.
1607 //
1608 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1609 #ifdef DEBUG_MERGE_TYPES
1610   DOUT << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1611 #endif
1612
1613   if (llvm_is_multithreaded()) AbstractTypeUsersLock->acquire();
1614   unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1615   while (!AbstractTypeUsers.empty()) {
1616     AbstractTypeUser *ATU = AbstractTypeUsers.back();
1617     ATU->typeBecameConcrete(this);
1618
1619     assert(AbstractTypeUsers.size() < OldSize-- &&
1620            "AbstractTypeUser did not remove itself from the use list!");
1621   }
1622   if (llvm_is_multithreaded()) AbstractTypeUsersLock->release();
1623 }
1624
1625 // refineAbstractType - Called when a contained type is found to be more
1626 // concrete - this could potentially change us from an abstract type to a
1627 // concrete type.
1628 //
1629 void FunctionType::refineAbstractType(const DerivedType *OldType,
1630                                       const Type *NewType) {
1631   FunctionTypes->RefineAbstractType(this, OldType, NewType);
1632 }
1633
1634 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1635   FunctionTypes->TypeBecameConcrete(this, AbsTy);
1636 }
1637
1638
1639 // refineAbstractType - Called when a contained type is found to be more
1640 // concrete - this could potentially change us from an abstract type to a
1641 // concrete type.
1642 //
1643 void ArrayType::refineAbstractType(const DerivedType *OldType,
1644                                    const Type *NewType) {
1645   ArrayTypes->RefineAbstractType(this, OldType, NewType);
1646 }
1647
1648 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1649   ArrayTypes->TypeBecameConcrete(this, AbsTy);
1650 }
1651
1652 // refineAbstractType - Called when a contained type is found to be more
1653 // concrete - this could potentially change us from an abstract type to a
1654 // concrete type.
1655 //
1656 void VectorType::refineAbstractType(const DerivedType *OldType,
1657                                    const Type *NewType) {
1658   VectorTypes->RefineAbstractType(this, OldType, NewType);
1659 }
1660
1661 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1662   VectorTypes->TypeBecameConcrete(this, AbsTy);
1663 }
1664
1665 // refineAbstractType - Called when a contained type is found to be more
1666 // concrete - this could potentially change us from an abstract type to a
1667 // concrete type.
1668 //
1669 void StructType::refineAbstractType(const DerivedType *OldType,
1670                                     const Type *NewType) {
1671   StructTypes->RefineAbstractType(this, OldType, NewType);
1672 }
1673
1674 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1675   StructTypes->TypeBecameConcrete(this, AbsTy);
1676 }
1677
1678 // refineAbstractType - Called when a contained type is found to be more
1679 // concrete - this could potentially change us from an abstract type to a
1680 // concrete type.
1681 //
1682 void PointerType::refineAbstractType(const DerivedType *OldType,
1683                                      const Type *NewType) {
1684   PointerTypes->RefineAbstractType(this, OldType, NewType);
1685 }
1686
1687 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1688   PointerTypes->TypeBecameConcrete(this, AbsTy);
1689 }
1690
1691 bool SequentialType::indexValid(const Value *V) const {
1692   if (isa<IntegerType>(V->getType())) 
1693     return true;
1694   return false;
1695 }
1696
1697 namespace llvm {
1698 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1699   if (T == 0)
1700     OS << "<null> value!\n";
1701   else
1702     T->print(OS);
1703   return OS;
1704 }
1705
1706 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1707   T.print(OS);
1708   return OS;
1709 }
1710
1711 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {
1712   T.print(OS);
1713   return OS;
1714 }
1715 }