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