Add locking around the attributes list.
[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 "LLVMContextImpl.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Metadata.h"
20 #include "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/SCCIterator.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/System/Mutex.h"
31 #include "llvm/System/RWMutex.h"
32 #include "llvm/System/Threading.h"
33 #include <algorithm>
34 #include <cstdarg>
35 using namespace llvm;
36
37 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
38 // created and later destroyed, all in an effort to make sure that there is only
39 // a single canonical version of a type.
40 //
41 // #define DEBUG_MERGE_TYPES 1
42
43 AbstractTypeUser::~AbstractTypeUser() {}
44
45
46 //===----------------------------------------------------------------------===//
47 //                         Type Class Implementation
48 //===----------------------------------------------------------------------===//
49
50 // Lock used for guarding access to the type maps.
51 static ManagedStatic<sys::SmartMutex<true> > TypeMapLock;
52
53 // Recursive lock used for guarding access to AbstractTypeUsers.
54 // NOTE: The true template parameter means this will no-op when we're not in
55 // multithreaded mode.
56 static ManagedStatic<sys::SmartMutex<true> > AbstractTypeUsersLock;
57
58 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
59 // for types as they are needed.  Because resolution of types must invalidate
60 // all of the abstract type descriptions, we keep them in a seperate map to make
61 // this easy.
62 static ManagedStatic<TypePrinting> ConcreteTypeDescriptions;
63 static ManagedStatic<TypePrinting> AbstractTypeDescriptions;
64
65 /// Because of the way Type subclasses are allocated, this function is necessary
66 /// to use the correct kind of "delete" operator to deallocate the Type object.
67 /// Some type objects (FunctionTy, StructTy) allocate additional space after 
68 /// the space for their derived type to hold the contained types array of
69 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
70 /// allocated with the type object, decreasing allocations and eliminating the
71 /// need for a std::vector to be used in the Type class itself. 
72 /// @brief Type destruction function
73 void Type::destroy() const {
74
75   // Structures and Functions allocate their contained types past the end of
76   // the type object itself. These need to be destroyed differently than the
77   // other types.
78   if (isa<FunctionType>(this) || isa<StructType>(this)) {
79     // First, make sure we destruct any PATypeHandles allocated by these
80     // subclasses.  They must be manually destructed. 
81     for (unsigned i = 0; i < NumContainedTys; ++i)
82       ContainedTys[i].PATypeHandle::~PATypeHandle();
83
84     // Now call the destructor for the subclass directly because we're going
85     // to delete this as an array of char.
86     if (isa<FunctionType>(this))
87       static_cast<const FunctionType*>(this)->FunctionType::~FunctionType();
88     else
89       static_cast<const StructType*>(this)->StructType::~StructType();
90
91     // Finally, remove the memory as an array deallocation of the chars it was
92     // constructed from.
93     operator delete(const_cast<Type *>(this));
94
95     return;
96   }
97
98   // For all the other type subclasses, there is either no contained types or 
99   // just one (all Sequentials). For Sequentials, the PATypeHandle is not
100   // allocated past the type object, its included directly in the SequentialType
101   // class. This means we can safely just do "normal" delete of this object and
102   // all the destructors that need to run will be run.
103   delete this; 
104 }
105
106 const Type *Type::getPrimitiveType(LLVMContext &C, TypeID IDNumber) {
107   switch (IDNumber) {
108   case VoidTyID      : return getVoidTy(C);
109   case FloatTyID     : return getFloatTy(C);
110   case DoubleTyID    : return getDoubleTy(C);
111   case X86_FP80TyID  : return getX86_FP80Ty(C);
112   case FP128TyID     : return getFP128Ty(C);
113   case PPC_FP128TyID : return getPPC_FP128Ty(C);
114   case LabelTyID     : return getLabelTy(C);
115   case MetadataTyID  : return getMetadataTy(C);
116   default:
117     return 0;
118   }
119 }
120
121 const Type *Type::getVAArgsPromotedType(LLVMContext &C) const {
122   if (ID == IntegerTyID && getSubclassData() < 32)
123     return Type::getInt32Ty(C);
124   else if (ID == FloatTyID)
125     return Type::getDoubleTy(C);
126   else
127     return this;
128 }
129
130 /// getScalarType - If this is a vector type, return the element type,
131 /// otherwise return this.
132 const Type *Type::getScalarType() const {
133   if (const VectorType *VTy = dyn_cast<VectorType>(this))
134     return VTy->getElementType();
135   return this;
136 }
137
138 /// isIntOrIntVector - Return true if this is an integer type or a vector of
139 /// integer types.
140 ///
141 bool Type::isIntOrIntVector() const {
142   if (isInteger())
143     return true;
144   if (ID != Type::VectorTyID) return false;
145   
146   return cast<VectorType>(this)->getElementType()->isInteger();
147 }
148
149 /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
150 ///
151 bool Type::isFPOrFPVector() const {
152   if (ID == Type::FloatTyID || ID == Type::DoubleTyID || 
153       ID == Type::FP128TyID || ID == Type::X86_FP80TyID || 
154       ID == Type::PPC_FP128TyID)
155     return true;
156   if (ID != Type::VectorTyID) return false;
157   
158   return cast<VectorType>(this)->getElementType()->isFloatingPoint();
159 }
160
161 // canLosslesslyBitCastTo - Return true if this type can be converted to
162 // 'Ty' without any reinterpretation of bits.  For example, i8* to i32*.
163 //
164 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
165   // Identity cast means no change so return true
166   if (this == Ty) 
167     return true;
168   
169   // They are not convertible unless they are at least first class types
170   if (!this->isFirstClassType() || !Ty->isFirstClassType())
171     return false;
172
173   // Vector -> Vector conversions are always lossless if the two vector types
174   // have the same size, otherwise not.
175   if (const VectorType *thisPTy = dyn_cast<VectorType>(this))
176     if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
177       return thisPTy->getBitWidth() == thatPTy->getBitWidth();
178
179   // At this point we have only various mismatches of the first class types
180   // remaining and ptr->ptr. Just select the lossless conversions. Everything
181   // else is not lossless.
182   if (isa<PointerType>(this))
183     return isa<PointerType>(Ty);
184   return false;  // Other types have no identity values
185 }
186
187 unsigned Type::getPrimitiveSizeInBits() const {
188   switch (getTypeID()) {
189   case Type::FloatTyID: return 32;
190   case Type::DoubleTyID: return 64;
191   case Type::X86_FP80TyID: return 80;
192   case Type::FP128TyID: return 128;
193   case Type::PPC_FP128TyID: return 128;
194   case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
195   case Type::VectorTyID:  return cast<VectorType>(this)->getBitWidth();
196   default: return 0;
197   }
198 }
199
200 /// getScalarSizeInBits - If this is a vector type, return the
201 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
202 /// getPrimitiveSizeInBits value for this type.
203 unsigned Type::getScalarSizeInBits() const {
204   return getScalarType()->getPrimitiveSizeInBits();
205 }
206
207 /// getFPMantissaWidth - Return the width of the mantissa of this type.  This
208 /// is only valid on floating point types.  If the FP type does not
209 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
210 int Type::getFPMantissaWidth() const {
211   if (const VectorType *VTy = dyn_cast<VectorType>(this))
212     return VTy->getElementType()->getFPMantissaWidth();
213   assert(isFloatingPoint() && "Not a floating point type!");
214   if (ID == FloatTyID) return 24;
215   if (ID == DoubleTyID) return 53;
216   if (ID == X86_FP80TyID) return 64;
217   if (ID == FP128TyID) return 113;
218   assert(ID == PPC_FP128TyID && "unknown fp type");
219   return -1;
220 }
221
222 /// isSizedDerivedType - Derived types like structures and arrays are sized
223 /// iff all of the members of the type are sized as well.  Since asking for
224 /// their size is relatively uncommon, move this operation out of line.
225 bool Type::isSizedDerivedType() const {
226   if (isa<IntegerType>(this))
227     return true;
228
229   if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
230     return ATy->getElementType()->isSized();
231
232   if (const VectorType *PTy = dyn_cast<VectorType>(this))
233     return PTy->getElementType()->isSized();
234
235   if (!isa<StructType>(this)) 
236     return false;
237
238   // Okay, our struct is sized if all of the elements are...
239   for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
240     if (!(*I)->isSized()) 
241       return false;
242
243   return true;
244 }
245
246 /// getForwardedTypeInternal - This method is used to implement the union-find
247 /// algorithm for when a type is being forwarded to another type.
248 const Type *Type::getForwardedTypeInternal() const {
249   assert(ForwardType && "This type is not being forwarded to another type!");
250
251   // Check to see if the forwarded type has been forwarded on.  If so, collapse
252   // the forwarding links.
253   const Type *RealForwardedType = ForwardType->getForwardedType();
254   if (!RealForwardedType)
255     return ForwardType;  // No it's not forwarded again
256
257   // Yes, it is forwarded again.  First thing, add the reference to the new
258   // forward type.
259   if (RealForwardedType->isAbstract())
260     cast<DerivedType>(RealForwardedType)->addRef();
261
262   // Now drop the old reference.  This could cause ForwardType to get deleted.
263   cast<DerivedType>(ForwardType)->dropRef();
264
265   // Return the updated type.
266   ForwardType = RealForwardedType;
267   return ForwardType;
268 }
269
270 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
271   llvm_unreachable("Attempting to refine a derived type!");
272 }
273 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
274   llvm_unreachable("DerivedType is already a concrete type!");
275 }
276
277
278 std::string Type::getDescription() const {
279   TypePrinting &Map =
280     isAbstract() ? *AbstractTypeDescriptions : *ConcreteTypeDescriptions;
281   
282   std::string DescStr;
283   raw_string_ostream DescOS(DescStr);
284   Map.print(this, DescOS);
285   return DescOS.str();
286 }
287
288
289 bool StructType::indexValid(const Value *V) const {
290   // Structure indexes require 32-bit integer constants.
291   if (V->getType() == Type::getInt32Ty(V->getContext()))
292     if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
293       return indexValid(CU->getZExtValue());
294   return false;
295 }
296
297 bool StructType::indexValid(unsigned V) const {
298   return V < NumContainedTys;
299 }
300
301 // getTypeAtIndex - Given an index value into the type, return the type of the
302 // element.  For a structure type, this must be a constant value...
303 //
304 const Type *StructType::getTypeAtIndex(const Value *V) const {
305   unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
306   return getTypeAtIndex(Idx);
307 }
308
309 const Type *StructType::getTypeAtIndex(unsigned Idx) const {
310   assert(indexValid(Idx) && "Invalid structure index!");
311   return ContainedTys[Idx];
312 }
313
314 //===----------------------------------------------------------------------===//
315 //                          Primitive 'Type' data
316 //===----------------------------------------------------------------------===//
317
318 const Type *Type::getVoidTy(LLVMContext &C) {
319   return C.pImpl->VoidTy;
320 }
321
322 const Type *Type::getLabelTy(LLVMContext &C) {
323   return C.pImpl->LabelTy;
324 }
325
326 const Type *Type::getFloatTy(LLVMContext &C) {
327   return C.pImpl->FloatTy;
328 }
329
330 const Type *Type::getDoubleTy(LLVMContext &C) {
331   return C.pImpl->DoubleTy;
332 }
333
334 const Type *Type::getMetadataTy(LLVMContext &C) {
335   return C.pImpl->MetadataTy;
336 }
337
338 const Type *Type::getX86_FP80Ty(LLVMContext &C) {
339   return C.pImpl->X86_FP80Ty;
340 }
341
342 const Type *Type::getFP128Ty(LLVMContext &C) {
343   return C.pImpl->FP128Ty;
344 }
345
346 const Type *Type::getPPC_FP128Ty(LLVMContext &C) {
347   return C.pImpl->PPC_FP128Ty;
348 }
349
350 const IntegerType *Type::getInt1Ty(LLVMContext &C) {
351   return C.pImpl->Int1Ty;
352 }
353
354 const IntegerType *Type::getInt8Ty(LLVMContext &C) {
355   return C.pImpl->Int8Ty;
356 }
357
358 const IntegerType *Type::getInt16Ty(LLVMContext &C) {
359   return C.pImpl->Int16Ty;
360 }
361
362 const IntegerType *Type::getInt32Ty(LLVMContext &C) {
363   return C.pImpl->Int32Ty;
364 }
365
366 const IntegerType *Type::getInt64Ty(LLVMContext &C) {
367   return C.pImpl->Int64Ty;
368 }
369
370 //===----------------------------------------------------------------------===//
371 //                          Derived Type Constructors
372 //===----------------------------------------------------------------------===//
373
374 /// isValidReturnType - Return true if the specified type is valid as a return
375 /// type.
376 bool FunctionType::isValidReturnType(const Type *RetTy) {
377   if (RetTy->isFirstClassType()) {
378     if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
379       return PTy->getElementType() != Type::getMetadataTy(RetTy->getContext());
380     return true;
381   }
382   if (RetTy == Type::getVoidTy(RetTy->getContext()) ||
383       RetTy == Type::getMetadataTy(RetTy->getContext()) ||
384       isa<OpaqueType>(RetTy))
385     return true;
386   
387   // If this is a multiple return case, verify that each return is a first class
388   // value and that there is at least one value.
389   const StructType *SRetTy = dyn_cast<StructType>(RetTy);
390   if (SRetTy == 0 || SRetTy->getNumElements() == 0)
391     return false;
392   
393   for (unsigned i = 0, e = SRetTy->getNumElements(); i != e; ++i)
394     if (!SRetTy->getElementType(i)->isFirstClassType())
395       return false;
396   return true;
397 }
398
399 /// isValidArgumentType - Return true if the specified type is valid as an
400 /// argument type.
401 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
402   if ((!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy)) ||
403       (isa<PointerType>(ArgTy) &&
404        cast<PointerType>(ArgTy)->getElementType() == 
405             Type::getMetadataTy(ArgTy->getContext())))
406     return false;
407
408   return true;
409 }
410
411 FunctionType::FunctionType(const Type *Result,
412                            const std::vector<const Type*> &Params,
413                            bool IsVarArgs)
414   : DerivedType(Result->getContext(), FunctionTyID), isVarArgs(IsVarArgs) {
415   ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
416   NumContainedTys = Params.size() + 1; // + 1 for result type
417   assert(isValidReturnType(Result) && "invalid return type for function");
418
419
420   bool isAbstract = Result->isAbstract();
421   new (&ContainedTys[0]) PATypeHandle(Result, this);
422
423   for (unsigned i = 0; i != Params.size(); ++i) {
424     assert(isValidArgumentType(Params[i]) &&
425            "Not a valid type for function argument!");
426     new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
427     isAbstract |= Params[i]->isAbstract();
428   }
429
430   // Calculate whether or not this type is abstract
431   setAbstract(isAbstract);
432 }
433
434 StructType::StructType(LLVMContext &C, 
435                        const std::vector<const Type*> &Types, bool isPacked)
436   : CompositeType(C, StructTyID) {
437   ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
438   NumContainedTys = Types.size();
439   setSubclassData(isPacked);
440   bool isAbstract = false;
441   for (unsigned i = 0; i < Types.size(); ++i) {
442     assert(Types[i] && "<null> type for structure field!");
443     assert(isValidElementType(Types[i]) &&
444            "Invalid type for structure element!");
445     new (&ContainedTys[i]) PATypeHandle(Types[i], this);
446     isAbstract |= Types[i]->isAbstract();
447   }
448
449   // Calculate whether or not this type is abstract
450   setAbstract(isAbstract);
451 }
452
453 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
454   : SequentialType(ArrayTyID, ElType) {
455   NumElements = NumEl;
456
457   // Calculate whether or not this type is abstract
458   setAbstract(ElType->isAbstract());
459 }
460
461 VectorType::VectorType(const Type *ElType, unsigned NumEl)
462   : SequentialType(VectorTyID, ElType) {
463   NumElements = NumEl;
464   setAbstract(ElType->isAbstract());
465   assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
466   assert(isValidElementType(ElType) &&
467          "Elements of a VectorType must be a primitive type");
468
469 }
470
471
472 PointerType::PointerType(const Type *E, unsigned AddrSpace)
473   : SequentialType(PointerTyID, E) {
474   AddressSpace = AddrSpace;
475   // Calculate whether or not this type is abstract
476   setAbstract(E->isAbstract());
477 }
478
479 OpaqueType::OpaqueType(LLVMContext &C) : DerivedType(C, OpaqueTyID) {
480   setAbstract(true);
481 #ifdef DEBUG_MERGE_TYPES
482   DOUT << "Derived new type: " << *this << "\n";
483 #endif
484 }
485
486 void PATypeHolder::destroy() {
487   Ty = 0;
488 }
489
490 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
491 // another (more concrete) type, we must eliminate all references to other
492 // types, to avoid some circular reference problems.
493 void DerivedType::dropAllTypeUses() {
494   if (NumContainedTys != 0) {
495     // The type must stay abstract.  To do this, we insert a pointer to a type
496     // that will never get resolved, thus will always be abstract.
497     static Type *AlwaysOpaqueTy = 0;
498     static PATypeHolder* Holder = 0;
499     Type *tmp = AlwaysOpaqueTy;
500     if (llvm_is_multithreaded()) {
501       sys::MemoryFence();
502       if (!tmp) {
503         llvm_acquire_global_lock();
504         tmp = AlwaysOpaqueTy;
505         if (!tmp) {
506           tmp = OpaqueType::get(getContext());
507           PATypeHolder* tmp2 = new PATypeHolder(AlwaysOpaqueTy);
508           sys::MemoryFence();
509           AlwaysOpaqueTy = tmp;
510           Holder = tmp2;
511         }
512       
513         llvm_release_global_lock();
514       }
515     } else {
516       AlwaysOpaqueTy = OpaqueType::get(getContext());
517       Holder = new PATypeHolder(AlwaysOpaqueTy);
518     } 
519         
520     ContainedTys[0] = AlwaysOpaqueTy;
521
522     // Change the rest of the types to be Int32Ty's.  It doesn't matter what we
523     // pick so long as it doesn't point back to this type.  We choose something
524     // concrete to avoid overhead for adding to AbstracTypeUser lists and stuff.
525     for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
526       ContainedTys[i] = Type::getInt32Ty(getContext());
527   }
528 }
529
530
531 namespace {
532
533 /// TypePromotionGraph and graph traits - this is designed to allow us to do
534 /// efficient SCC processing of type graphs.  This is the exact same as
535 /// GraphTraits<Type*>, except that we pretend that concrete types have no
536 /// children to avoid processing them.
537 struct TypePromotionGraph {
538   Type *Ty;
539   TypePromotionGraph(Type *T) : Ty(T) {}
540 };
541
542 }
543
544 namespace llvm {
545   template <> struct GraphTraits<TypePromotionGraph> {
546     typedef Type NodeType;
547     typedef Type::subtype_iterator ChildIteratorType;
548
549     static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
550     static inline ChildIteratorType child_begin(NodeType *N) {
551       if (N->isAbstract())
552         return N->subtype_begin();
553       else           // No need to process children of concrete types.
554         return N->subtype_end();
555     }
556     static inline ChildIteratorType child_end(NodeType *N) {
557       return N->subtype_end();
558     }
559   };
560 }
561
562
563 // PromoteAbstractToConcrete - This is a recursive function that walks a type
564 // graph calculating whether or not a type is abstract.
565 //
566 void Type::PromoteAbstractToConcrete() {
567   if (!isAbstract()) return;
568
569   scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
570   scc_iterator<TypePromotionGraph> SE = scc_end  (TypePromotionGraph(this));
571
572   for (; SI != SE; ++SI) {
573     std::vector<Type*> &SCC = *SI;
574
575     // Concrete types are leaves in the tree.  Since an SCC will either be all
576     // abstract or all concrete, we only need to check one type.
577     if (SCC[0]->isAbstract()) {
578       if (isa<OpaqueType>(SCC[0]))
579         return;     // Not going to be concrete, sorry.
580
581       // If all of the children of all of the types in this SCC are concrete,
582       // then this SCC is now concrete as well.  If not, neither this SCC, nor
583       // any parent SCCs will be concrete, so we might as well just exit.
584       for (unsigned i = 0, e = SCC.size(); i != e; ++i)
585         for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
586                E = SCC[i]->subtype_end(); CI != E; ++CI)
587           if ((*CI)->isAbstract())
588             // If the child type is in our SCC, it doesn't make the entire SCC
589             // abstract unless there is a non-SCC abstract type.
590             if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
591               return;               // Not going to be concrete, sorry.
592
593       // Okay, we just discovered this whole SCC is now concrete, mark it as
594       // such!
595       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
596         assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
597
598         SCC[i]->setAbstract(false);
599       }
600
601       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
602         assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
603         // The type just became concrete, notify all users!
604         cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
605       }
606     }
607   }
608 }
609
610
611 //===----------------------------------------------------------------------===//
612 //                      Type Structural Equality Testing
613 //===----------------------------------------------------------------------===//
614
615 // TypesEqual - Two types are considered structurally equal if they have the
616 // same "shape": Every level and element of the types have identical primitive
617 // ID's, and the graphs have the same edges/nodes in them.  Nodes do not have to
618 // be pointer equals to be equivalent though.  This uses an optimistic algorithm
619 // that assumes that two graphs are the same until proven otherwise.
620 //
621 static bool TypesEqual(const Type *Ty, const Type *Ty2,
622                        std::map<const Type *, const Type *> &EqTypes) {
623   if (Ty == Ty2) return true;
624   if (Ty->getTypeID() != Ty2->getTypeID()) return false;
625   if (isa<OpaqueType>(Ty))
626     return false;  // Two unequal opaque types are never equal
627
628   std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
629   if (It != EqTypes.end())
630     return It->second == Ty2;    // Looping back on a type, check for equality
631
632   // Otherwise, add the mapping to the table to make sure we don't get
633   // recursion on the types...
634   EqTypes.insert(It, std::make_pair(Ty, Ty2));
635
636   // Two really annoying special cases that breaks an otherwise nice simple
637   // algorithm is the fact that arraytypes have sizes that differentiates types,
638   // and that function types can be varargs or not.  Consider this now.
639   //
640   if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
641     const IntegerType *ITy2 = cast<IntegerType>(Ty2);
642     return ITy->getBitWidth() == ITy2->getBitWidth();
643   } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
644     const PointerType *PTy2 = cast<PointerType>(Ty2);
645     return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
646            TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
647   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
648     const StructType *STy2 = cast<StructType>(Ty2);
649     if (STy->getNumElements() != STy2->getNumElements()) return false;
650     if (STy->isPacked() != STy2->isPacked()) return false;
651     for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
652       if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
653         return false;
654     return true;
655   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
656     const ArrayType *ATy2 = cast<ArrayType>(Ty2);
657     return ATy->getNumElements() == ATy2->getNumElements() &&
658            TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
659   } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
660     const VectorType *PTy2 = cast<VectorType>(Ty2);
661     return PTy->getNumElements() == PTy2->getNumElements() &&
662            TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
663   } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
664     const FunctionType *FTy2 = cast<FunctionType>(Ty2);
665     if (FTy->isVarArg() != FTy2->isVarArg() ||
666         FTy->getNumParams() != FTy2->getNumParams() ||
667         !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
668       return false;
669     for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
670       if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
671         return false;
672     }
673     return true;
674   } else {
675     llvm_unreachable("Unknown derived type!");
676     return false;
677   }
678 }
679
680 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
681   std::map<const Type *, const Type *> EqTypes;
682   return TypesEqual(Ty, Ty2, EqTypes);
683 }
684
685 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
686 // TargetTy in the type graph.  We know that Ty is an abstract type, so if we
687 // ever reach a non-abstract type, we know that we don't need to search the
688 // subgraph.
689 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
690                                 SmallPtrSet<const Type*, 128> &VisitedTypes) {
691   if (TargetTy == CurTy) return true;
692   if (!CurTy->isAbstract()) return false;
693
694   if (!VisitedTypes.insert(CurTy))
695     return false;  // Already been here.
696
697   for (Type::subtype_iterator I = CurTy->subtype_begin(),
698        E = CurTy->subtype_end(); I != E; ++I)
699     if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
700       return true;
701   return false;
702 }
703
704 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
705                                 SmallPtrSet<const Type*, 128> &VisitedTypes) {
706   if (TargetTy == CurTy) return true;
707
708   if (!VisitedTypes.insert(CurTy))
709     return false;  // Already been here.
710
711   for (Type::subtype_iterator I = CurTy->subtype_begin(),
712        E = CurTy->subtype_end(); I != E; ++I)
713     if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
714       return true;
715   return false;
716 }
717
718 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
719 /// back to itself.
720 static bool TypeHasCycleThroughItself(const Type *Ty) {
721   SmallPtrSet<const Type*, 128> VisitedTypes;
722
723   if (Ty->isAbstract()) {  // Optimized case for abstract types.
724     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
725          I != E; ++I)
726       if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
727         return true;
728   } else {
729     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
730          I != E; ++I)
731       if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
732         return true;
733   }
734   return false;
735 }
736
737 //===----------------------------------------------------------------------===//
738 // Function Type Factory and Value Class...
739 //
740 const IntegerType *IntegerType::get(LLVMContext &C, unsigned NumBits) {
741   assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
742   assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
743
744   // Check for the built-in integer types
745   switch (NumBits) {
746     case  1: return cast<IntegerType>(Type::getInt1Ty(C));
747     case  8: return cast<IntegerType>(Type::getInt8Ty(C));
748     case 16: return cast<IntegerType>(Type::getInt16Ty(C));
749     case 32: return cast<IntegerType>(Type::getInt32Ty(C));
750     case 64: return cast<IntegerType>(Type::getInt64Ty(C));
751     default: 
752       break;
753   }
754
755   LLVMContextImpl *pImpl = C.pImpl;
756   
757   IntegerValType IVT(NumBits);
758   IntegerType *ITy = 0;
759   
760   // First, see if the type is already in the table, for which
761   // a reader lock suffices.
762   sys::SmartScopedLock<true> L(*TypeMapLock);
763   ITy = pImpl->IntegerTypes.get(IVT);
764     
765   if (!ITy) {
766     // Value not found.  Derive a new type!
767     ITy = new IntegerType(C, NumBits);
768     pImpl->IntegerTypes.add(IVT, ITy);
769   }
770 #ifdef DEBUG_MERGE_TYPES
771   DOUT << "Derived new type: " << *ITy << "\n";
772 #endif
773   return ITy;
774 }
775
776 bool IntegerType::isPowerOf2ByteWidth() const {
777   unsigned BitWidth = getBitWidth();
778   return (BitWidth > 7) && isPowerOf2_32(BitWidth);
779 }
780
781 APInt IntegerType::getMask() const {
782   return APInt::getAllOnesValue(getBitWidth());
783 }
784
785 FunctionValType FunctionValType::get(const FunctionType *FT) {
786   // Build up a FunctionValType
787   std::vector<const Type *> ParamTypes;
788   ParamTypes.reserve(FT->getNumParams());
789   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
790     ParamTypes.push_back(FT->getParamType(i));
791   return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
792 }
793
794
795 // FunctionType::get - The factory function for the FunctionType class...
796 FunctionType *FunctionType::get(const Type *ReturnType,
797                                 const std::vector<const Type*> &Params,
798                                 bool isVarArg) {
799   FunctionValType VT(ReturnType, Params, isVarArg);
800   FunctionType *FT = 0;
801   
802   LLVMContextImpl *pImpl = ReturnType->getContext().pImpl;
803   
804   sys::SmartScopedLock<true> L(*TypeMapLock);
805   FT = pImpl->FunctionTypes.get(VT);
806   
807   if (!FT) {
808     FT = (FunctionType*) operator new(sizeof(FunctionType) +
809                                     sizeof(PATypeHandle)*(Params.size()+1));
810     new (FT) FunctionType(ReturnType, Params, isVarArg);
811     pImpl->FunctionTypes.add(VT, FT);
812   }
813
814 #ifdef DEBUG_MERGE_TYPES
815   DOUT << "Derived new type: " << FT << "\n";
816 #endif
817   return FT;
818 }
819
820 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
821   assert(ElementType && "Can't get array of <null> types!");
822   assert(isValidElementType(ElementType) && "Invalid type for array element!");
823
824   ArrayValType AVT(ElementType, NumElements);
825   ArrayType *AT = 0;
826
827   LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
828   
829   sys::SmartScopedLock<true> L(*TypeMapLock);
830   AT = pImpl->ArrayTypes.get(AVT);
831       
832   if (!AT) {
833     // Value not found.  Derive a new type!
834     pImpl->ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
835   }
836 #ifdef DEBUG_MERGE_TYPES
837   DOUT << "Derived new type: " << *AT << "\n";
838 #endif
839   return AT;
840 }
841
842 bool ArrayType::isValidElementType(const Type *ElemTy) {
843   if (ElemTy == Type::getVoidTy(ElemTy->getContext()) ||
844       ElemTy == Type::getLabelTy(ElemTy->getContext()) ||
845       ElemTy == Type::getMetadataTy(ElemTy->getContext()))
846     return false;
847
848   if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
849     if (PTy->getElementType() == Type::getMetadataTy(ElemTy->getContext()))
850       return false;
851
852   return true;
853 }
854
855 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
856   assert(ElementType && "Can't get vector of <null> types!");
857
858   VectorValType PVT(ElementType, NumElements);
859   VectorType *PT = 0;
860   
861   LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
862   
863   sys::SmartScopedLock<true> L(*TypeMapLock);
864   PT = pImpl->VectorTypes.get(PVT);
865     
866   if (!PT) {
867     pImpl->VectorTypes.add(PVT, PT = new VectorType(ElementType, NumElements));
868   }
869 #ifdef DEBUG_MERGE_TYPES
870   DOUT << "Derived new type: " << *PT << "\n";
871 #endif
872   return PT;
873 }
874
875 bool VectorType::isValidElementType(const Type *ElemTy) {
876   if (ElemTy->isInteger() || ElemTy->isFloatingPoint() ||
877       isa<OpaqueType>(ElemTy))
878     return true;
879
880   return false;
881 }
882
883 //===----------------------------------------------------------------------===//
884 // Struct Type Factory...
885 //
886
887 StructType *StructType::get(LLVMContext &Context,
888                             const std::vector<const Type*> &ETypes, 
889                             bool isPacked) {
890   StructValType STV(ETypes, isPacked);
891   StructType *ST = 0;
892   
893   LLVMContextImpl *pImpl = Context.pImpl;
894   
895   sys::SmartScopedLock<true> L(*TypeMapLock);
896   ST = pImpl->StructTypes.get(STV);
897     
898   if (!ST) {
899     // Value not found.  Derive a new type!
900     ST = (StructType*) operator new(sizeof(StructType) +
901                                     sizeof(PATypeHandle) * ETypes.size());
902     new (ST) StructType(Context, ETypes, isPacked);
903     pImpl->StructTypes.add(STV, ST);
904   }
905 #ifdef DEBUG_MERGE_TYPES
906   DOUT << "Derived new type: " << *ST << "\n";
907 #endif
908   return ST;
909 }
910
911 StructType *StructType::get(LLVMContext &Context, const Type *type, ...) {
912   va_list ap;
913   std::vector<const llvm::Type*> StructFields;
914   va_start(ap, type);
915   while (type) {
916     StructFields.push_back(type);
917     type = va_arg(ap, llvm::Type*);
918   }
919   return llvm::StructType::get(Context, StructFields);
920 }
921
922 bool StructType::isValidElementType(const Type *ElemTy) {
923   if (ElemTy == Type::getVoidTy(ElemTy->getContext()) ||
924       ElemTy == Type::getLabelTy(ElemTy->getContext()) ||
925       ElemTy == Type::getMetadataTy(ElemTy->getContext()))
926     return false;
927
928   if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
929     if (PTy->getElementType() == Type::getMetadataTy(ElemTy->getContext()))
930       return false;
931
932   return true;
933 }
934
935
936 //===----------------------------------------------------------------------===//
937 // Pointer Type Factory...
938 //
939
940 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
941   assert(ValueType && "Can't get a pointer to <null> type!");
942   assert(ValueType != Type::getVoidTy(ValueType->getContext()) &&
943          "Pointer to void is not valid, use i8* instead!");
944   assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
945   PointerValType PVT(ValueType, AddressSpace);
946
947   PointerType *PT = 0;
948   
949   LLVMContextImpl *pImpl = ValueType->getContext().pImpl;
950   
951   sys::SmartScopedLock<true> L(*TypeMapLock);
952   PT = pImpl->PointerTypes.get(PVT);
953   
954   if (!PT) {
955     // Value not found.  Derive a new type!
956     pImpl->PointerTypes.add(PVT, PT = new PointerType(ValueType, AddressSpace));
957   }
958 #ifdef DEBUG_MERGE_TYPES
959   DOUT << "Derived new type: " << *PT << "\n";
960 #endif
961   return PT;
962 }
963
964 PointerType *Type::getPointerTo(unsigned addrs) const {
965   return PointerType::get(this, addrs);
966 }
967
968 bool PointerType::isValidElementType(const Type *ElemTy) {
969   if (ElemTy == Type::getVoidTy(ElemTy->getContext()) ||
970       ElemTy == Type::getLabelTy(ElemTy->getContext()))
971     return false;
972
973   if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
974     if (PTy->getElementType() == Type::getMetadataTy(ElemTy->getContext()))
975       return false;
976
977   return true;
978 }
979
980
981 //===----------------------------------------------------------------------===//
982 //                     Derived Type Refinement Functions
983 //===----------------------------------------------------------------------===//
984
985 // addAbstractTypeUser - Notify an abstract type that there is a new user of
986 // it.  This function is called primarily by the PATypeHandle class.
987 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
988   assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
989   AbstractTypeUsersLock->acquire();
990   AbstractTypeUsers.push_back(U);
991   AbstractTypeUsersLock->release();
992 }
993
994
995 // removeAbstractTypeUser - Notify an abstract type that a user of the class
996 // no longer has a handle to the type.  This function is called primarily by
997 // the PATypeHandle class.  When there are no users of the abstract type, it
998 // is annihilated, because there is no way to get a reference to it ever again.
999 //
1000 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1001   AbstractTypeUsersLock->acquire();
1002   
1003   // Search from back to front because we will notify users from back to
1004   // front.  Also, it is likely that there will be a stack like behavior to
1005   // users that register and unregister users.
1006   //
1007   unsigned i;
1008   for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1009     assert(i != 0 && "AbstractTypeUser not in user list!");
1010
1011   --i;  // Convert to be in range 0 <= i < size()
1012   assert(i < AbstractTypeUsers.size() && "Index out of range!");  // Wraparound?
1013
1014   AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1015
1016 #ifdef DEBUG_MERGE_TYPES
1017   DOUT << "  remAbstractTypeUser[" << (void*)this << ", "
1018        << *this << "][" << i << "] User = " << U << "\n";
1019 #endif
1020
1021   if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1022 #ifdef DEBUG_MERGE_TYPES
1023     DOUT << "DELETEing unused abstract type: <" << *this
1024          << ">[" << (void*)this << "]" << "\n";
1025 #endif
1026   
1027   this->destroy();
1028   }
1029   
1030   AbstractTypeUsersLock->release();
1031 }
1032
1033 // unlockedRefineAbstractTypeTo - This function is used when it is discovered
1034 // that the 'this' abstract type is actually equivalent to the NewType
1035 // specified. This causes all users of 'this' to switch to reference the more 
1036 // concrete type NewType and for 'this' to be deleted.  Only used for internal
1037 // callers.
1038 //
1039 void DerivedType::unlockedRefineAbstractTypeTo(const Type *NewType) {
1040   assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1041   assert(this != NewType && "Can't refine to myself!");
1042   assert(ForwardType == 0 && "This type has already been refined!");
1043
1044   // The descriptions may be out of date.  Conservatively clear them all!
1045   if (AbstractTypeDescriptions.isConstructed())
1046     AbstractTypeDescriptions->clear();
1047
1048 #ifdef DEBUG_MERGE_TYPES
1049   DOUT << "REFINING abstract type [" << (void*)this << " "
1050        << *this << "] to [" << (void*)NewType << " "
1051        << *NewType << "]!\n";
1052 #endif
1053
1054   // Make sure to put the type to be refined to into a holder so that if IT gets
1055   // refined, that we will not continue using a dead reference...
1056   //
1057   PATypeHolder NewTy(NewType);
1058   // Any PATypeHolders referring to this type will now automatically forward o
1059   // the type we are resolved to.
1060   ForwardType = NewType;
1061   if (NewType->isAbstract())
1062     cast<DerivedType>(NewType)->addRef();
1063
1064   // Add a self use of the current type so that we don't delete ourself until
1065   // after the function exits.
1066   //
1067   PATypeHolder CurrentTy(this);
1068
1069   // To make the situation simpler, we ask the subclass to remove this type from
1070   // the type map, and to replace any type uses with uses of non-abstract types.
1071   // This dramatically limits the amount of recursive type trouble we can find
1072   // ourselves in.
1073   dropAllTypeUses();
1074
1075   // Iterate over all of the uses of this type, invoking callback.  Each user
1076   // should remove itself from our use list automatically.  We have to check to
1077   // make sure that NewTy doesn't _become_ 'this'.  If it does, resolving types
1078   // will not cause users to drop off of the use list.  If we resolve to ourself
1079   // we succeed!
1080   //
1081   AbstractTypeUsersLock->acquire();
1082   while (!AbstractTypeUsers.empty() && NewTy != this) {
1083     AbstractTypeUser *User = AbstractTypeUsers.back();
1084
1085     unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1086 #ifdef DEBUG_MERGE_TYPES
1087     DOUT << " REFINING user " << OldSize-1 << "[" << (void*)User
1088          << "] of abstract type [" << (void*)this << " "
1089          << *this << "] to [" << (void*)NewTy.get() << " "
1090          << *NewTy << "]!\n";
1091 #endif
1092     User->refineAbstractType(this, NewTy);
1093
1094     assert(AbstractTypeUsers.size() != OldSize &&
1095            "AbsTyUser did not remove self from user list!");
1096   }
1097   AbstractTypeUsersLock->release();
1098
1099   // If we were successful removing all users from the type, 'this' will be
1100   // deleted when the last PATypeHolder is destroyed or updated from this type.
1101   // This may occur on exit of this function, as the CurrentTy object is
1102   // destroyed.
1103 }
1104
1105 // refineAbstractTypeTo - This function is used by external callers to notify
1106 // us that this abstract type is equivalent to another type.
1107 //
1108 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1109   // All recursive calls will go through unlockedRefineAbstractTypeTo,
1110   // to avoid deadlock problems.
1111   sys::SmartScopedLock<true> L(*TypeMapLock);
1112   unlockedRefineAbstractTypeTo(NewType);
1113 }
1114
1115 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1116 // the current type has transitioned from being abstract to being concrete.
1117 //
1118 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1119 #ifdef DEBUG_MERGE_TYPES
1120   DOUT << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1121 #endif
1122
1123   AbstractTypeUsersLock->acquire();
1124   unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1125   while (!AbstractTypeUsers.empty()) {
1126     AbstractTypeUser *ATU = AbstractTypeUsers.back();
1127     ATU->typeBecameConcrete(this);
1128
1129     assert(AbstractTypeUsers.size() < OldSize-- &&
1130            "AbstractTypeUser did not remove itself from the use list!");
1131   }
1132   AbstractTypeUsersLock->release();
1133 }
1134
1135 // refineAbstractType - Called when a contained type is found to be more
1136 // concrete - this could potentially change us from an abstract type to a
1137 // concrete type.
1138 //
1139 void FunctionType::refineAbstractType(const DerivedType *OldType,
1140                                       const Type *NewType) {
1141   LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1142   pImpl->FunctionTypes.RefineAbstractType(this, OldType, NewType);
1143 }
1144
1145 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1146   LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1147   pImpl->FunctionTypes.TypeBecameConcrete(this, AbsTy);
1148 }
1149
1150
1151 // refineAbstractType - Called when a contained type is found to be more
1152 // concrete - this could potentially change us from an abstract type to a
1153 // concrete type.
1154 //
1155 void ArrayType::refineAbstractType(const DerivedType *OldType,
1156                                    const Type *NewType) {
1157   LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1158   pImpl->ArrayTypes.RefineAbstractType(this, OldType, NewType);
1159 }
1160
1161 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1162   LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1163   pImpl->ArrayTypes.TypeBecameConcrete(this, AbsTy);
1164 }
1165
1166 // refineAbstractType - Called when a contained type is found to be more
1167 // concrete - this could potentially change us from an abstract type to a
1168 // concrete type.
1169 //
1170 void VectorType::refineAbstractType(const DerivedType *OldType,
1171                                    const Type *NewType) {
1172   LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1173   pImpl->VectorTypes.RefineAbstractType(this, OldType, NewType);
1174 }
1175
1176 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1177   LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1178   pImpl->VectorTypes.TypeBecameConcrete(this, AbsTy);
1179 }
1180
1181 // refineAbstractType - Called when a contained type is found to be more
1182 // concrete - this could potentially change us from an abstract type to a
1183 // concrete type.
1184 //
1185 void StructType::refineAbstractType(const DerivedType *OldType,
1186                                     const Type *NewType) {
1187   LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1188   pImpl->StructTypes.RefineAbstractType(this, OldType, NewType);
1189 }
1190
1191 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1192   LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1193   pImpl->StructTypes.TypeBecameConcrete(this, AbsTy);
1194 }
1195
1196 // refineAbstractType - Called when a contained type is found to be more
1197 // concrete - this could potentially change us from an abstract type to a
1198 // concrete type.
1199 //
1200 void PointerType::refineAbstractType(const DerivedType *OldType,
1201                                      const Type *NewType) {
1202   LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1203   pImpl->PointerTypes.RefineAbstractType(this, OldType, NewType);
1204 }
1205
1206 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1207   LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1208   pImpl->PointerTypes.TypeBecameConcrete(this, AbsTy);
1209 }
1210
1211 bool SequentialType::indexValid(const Value *V) const {
1212   if (isa<IntegerType>(V->getType())) 
1213     return true;
1214   return false;
1215 }
1216
1217 namespace llvm {
1218 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1219   if (T == 0)
1220     OS << "<null> value!\n";
1221   else
1222     T->print(OS);
1223   return OS;
1224 }
1225
1226 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1227   T.print(OS);
1228   return OS;
1229 }
1230
1231 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {
1232   T.print(OS);
1233   return OS;
1234 }
1235 }