Add a helper for telling whether a type is a pointer or vector of pointer type.
[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/Module.h"
16 #include <algorithm>
17 #include <cstdarg>
18 #include "llvm/ADT/SmallString.h"
19 using namespace llvm;
20
21 //===----------------------------------------------------------------------===//
22 //                         Type Class Implementation
23 //===----------------------------------------------------------------------===//
24
25 Type *Type::getPrimitiveType(LLVMContext &C, TypeID IDNumber) {
26   switch (IDNumber) {
27   case VoidTyID      : return getVoidTy(C);
28   case HalfTyID      : return getHalfTy(C);
29   case FloatTyID     : return getFloatTy(C);
30   case DoubleTyID    : return getDoubleTy(C);
31   case X86_FP80TyID  : return getX86_FP80Ty(C);
32   case FP128TyID     : return getFP128Ty(C);
33   case PPC_FP128TyID : return getPPC_FP128Ty(C);
34   case LabelTyID     : return getLabelTy(C);
35   case MetadataTyID  : return getMetadataTy(C);
36   case X86_MMXTyID   : return getX86_MMXTy(C);
37   default:
38     return 0;
39   }
40 }
41
42 /// getScalarType - If this is a vector type, return the element type,
43 /// otherwise return this.
44 Type *Type::getScalarType() {
45   if (VectorType *VTy = dyn_cast<VectorType>(this))
46     return VTy->getElementType();
47   return this;
48 }
49
50 const Type *Type::getScalarType() const {
51   if (const VectorType *VTy = dyn_cast<VectorType>(this))
52     return VTy->getElementType();
53   return this;
54 }
55
56 /// isIntegerTy - Return true if this is an IntegerType of the specified width.
57 bool Type::isIntegerTy(unsigned Bitwidth) const {
58   return isIntegerTy() && cast<IntegerType>(this)->getBitWidth() == Bitwidth;
59 }
60
61 // canLosslesslyBitCastTo - Return true if this type can be converted to
62 // 'Ty' without any reinterpretation of bits.  For example, i8* to i32*.
63 //
64 bool Type::canLosslesslyBitCastTo(Type *Ty) const {
65   // Identity cast means no change so return true
66   if (this == Ty) 
67     return true;
68   
69   // They are not convertible unless they are at least first class types
70   if (!this->isFirstClassType() || !Ty->isFirstClassType())
71     return false;
72
73   // Vector -> Vector conversions are always lossless if the two vector types
74   // have the same size, otherwise not.  Also, 64-bit vector types can be
75   // converted to x86mmx.
76   if (const VectorType *thisPTy = dyn_cast<VectorType>(this)) {
77     if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
78       return thisPTy->getBitWidth() == thatPTy->getBitWidth();
79     if (Ty->getTypeID() == Type::X86_MMXTyID &&
80         thisPTy->getBitWidth() == 64)
81       return true;
82   }
83
84   if (this->getTypeID() == Type::X86_MMXTyID)
85     if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
86       if (thatPTy->getBitWidth() == 64)
87         return true;
88
89   // At this point we have only various mismatches of the first class types
90   // remaining and ptr->ptr. Just select the lossless conversions. Everything
91   // else is not lossless.
92   if (this->isPointerTy())
93     return Ty->isPointerTy();
94   return false;  // Other types have no identity values
95 }
96
97 bool Type::isEmptyTy() const {
98   const ArrayType *ATy = dyn_cast<ArrayType>(this);
99   if (ATy) {
100     unsigned NumElements = ATy->getNumElements();
101     return NumElements == 0 || ATy->getElementType()->isEmptyTy();
102   }
103
104   const StructType *STy = dyn_cast<StructType>(this);
105   if (STy) {
106     unsigned NumElements = STy->getNumElements();
107     for (unsigned i = 0; i < NumElements; ++i)
108       if (!STy->getElementType(i)->isEmptyTy())
109         return false;
110     return true;
111   }
112
113   return false;
114 }
115
116 unsigned Type::getPrimitiveSizeInBits() const {
117   switch (getTypeID()) {
118   case Type::HalfTyID: return 16;
119   case Type::FloatTyID: return 32;
120   case Type::DoubleTyID: return 64;
121   case Type::X86_FP80TyID: return 80;
122   case Type::FP128TyID: return 128;
123   case Type::PPC_FP128TyID: return 128;
124   case Type::X86_MMXTyID: return 64;
125   case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
126   case Type::VectorTyID:  return cast<VectorType>(this)->getBitWidth();
127   default: return 0;
128   }
129 }
130
131 /// getScalarSizeInBits - If this is a vector type, return the
132 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
133 /// getPrimitiveSizeInBits value for this type.
134 unsigned Type::getScalarSizeInBits() {
135   return getScalarType()->getPrimitiveSizeInBits();
136 }
137
138 /// getFPMantissaWidth - Return the width of the mantissa of this type.  This
139 /// is only valid on floating point types.  If the FP type does not
140 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
141 int Type::getFPMantissaWidth() const {
142   if (const VectorType *VTy = dyn_cast<VectorType>(this))
143     return VTy->getElementType()->getFPMantissaWidth();
144   assert(isFloatingPointTy() && "Not a floating point type!");
145   if (getTypeID() == HalfTyID) return 11;
146   if (getTypeID() == FloatTyID) return 24;
147   if (getTypeID() == DoubleTyID) return 53;
148   if (getTypeID() == X86_FP80TyID) return 64;
149   if (getTypeID() == FP128TyID) return 113;
150   assert(getTypeID() == PPC_FP128TyID && "unknown fp type");
151   return -1;
152 }
153
154 /// isSizedDerivedType - Derived types like structures and arrays are sized
155 /// iff all of the members of the type are sized as well.  Since asking for
156 /// their size is relatively uncommon, move this operation out of line.
157 bool Type::isSizedDerivedType() const {
158   if (this->isIntegerTy())
159     return true;
160
161   if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
162     return ATy->getElementType()->isSized();
163
164   if (const VectorType *VTy = dyn_cast<VectorType>(this))
165     return VTy->getElementType()->isSized();
166
167   if (!this->isStructTy()) 
168     return false;
169
170   return cast<StructType>(this)->isSized();
171 }
172
173 //===----------------------------------------------------------------------===//
174 //                         Subclass Helper Methods
175 //===----------------------------------------------------------------------===//
176
177 unsigned Type::getIntegerBitWidth() const {
178   return cast<IntegerType>(this)->getBitWidth();
179 }
180
181 bool Type::isFunctionVarArg() const {
182   return cast<FunctionType>(this)->isVarArg();
183 }
184
185 Type *Type::getFunctionParamType(unsigned i) const {
186   return cast<FunctionType>(this)->getParamType(i);
187 }
188
189 unsigned Type::getFunctionNumParams() const {
190   return cast<FunctionType>(this)->getNumParams();
191 }
192
193 StringRef Type::getStructName() const {
194   return cast<StructType>(this)->getName();
195 }
196
197 unsigned Type::getStructNumElements() const {
198   return cast<StructType>(this)->getNumElements();
199 }
200
201 Type *Type::getStructElementType(unsigned N) const {
202   return cast<StructType>(this)->getElementType(N);
203 }
204
205 Type *Type::getSequentialElementType() const {
206   return cast<SequentialType>(this)->getElementType();
207 }
208
209 uint64_t Type::getArrayNumElements() const {
210   return cast<ArrayType>(this)->getNumElements();
211 }
212
213 unsigned Type::getVectorNumElements() const {
214   return cast<VectorType>(this)->getNumElements();
215 }
216
217 unsigned Type::getPointerAddressSpace() const {
218   if (isPointerTy())
219     return cast<PointerType>(this)->getAddressSpace();
220   if (isVectorTy())
221     return getSequentialElementType()->getPointerAddressSpace();
222   llvm_unreachable("Should never reach here!");
223   return 0;
224 }
225
226
227 //===----------------------------------------------------------------------===//
228 //                          Primitive 'Type' data
229 //===----------------------------------------------------------------------===//
230
231 Type *Type::getVoidTy(LLVMContext &C) { return &C.pImpl->VoidTy; }
232 Type *Type::getLabelTy(LLVMContext &C) { return &C.pImpl->LabelTy; }
233 Type *Type::getHalfTy(LLVMContext &C) { return &C.pImpl->HalfTy; }
234 Type *Type::getFloatTy(LLVMContext &C) { return &C.pImpl->FloatTy; }
235 Type *Type::getDoubleTy(LLVMContext &C) { return &C.pImpl->DoubleTy; }
236 Type *Type::getMetadataTy(LLVMContext &C) { return &C.pImpl->MetadataTy; }
237 Type *Type::getX86_FP80Ty(LLVMContext &C) { return &C.pImpl->X86_FP80Ty; }
238 Type *Type::getFP128Ty(LLVMContext &C) { return &C.pImpl->FP128Ty; }
239 Type *Type::getPPC_FP128Ty(LLVMContext &C) { return &C.pImpl->PPC_FP128Ty; }
240 Type *Type::getX86_MMXTy(LLVMContext &C) { return &C.pImpl->X86_MMXTy; }
241
242 IntegerType *Type::getInt1Ty(LLVMContext &C) { return &C.pImpl->Int1Ty; }
243 IntegerType *Type::getInt8Ty(LLVMContext &C) { return &C.pImpl->Int8Ty; }
244 IntegerType *Type::getInt16Ty(LLVMContext &C) { return &C.pImpl->Int16Ty; }
245 IntegerType *Type::getInt32Ty(LLVMContext &C) { return &C.pImpl->Int32Ty; }
246 IntegerType *Type::getInt64Ty(LLVMContext &C) { return &C.pImpl->Int64Ty; }
247
248 IntegerType *Type::getIntNTy(LLVMContext &C, unsigned N) {
249   return IntegerType::get(C, N);
250 }
251
252 PointerType *Type::getHalfPtrTy(LLVMContext &C, unsigned AS) {
253   return getHalfTy(C)->getPointerTo(AS);
254 }
255
256 PointerType *Type::getFloatPtrTy(LLVMContext &C, unsigned AS) {
257   return getFloatTy(C)->getPointerTo(AS);
258 }
259
260 PointerType *Type::getDoublePtrTy(LLVMContext &C, unsigned AS) {
261   return getDoubleTy(C)->getPointerTo(AS);
262 }
263
264 PointerType *Type::getX86_FP80PtrTy(LLVMContext &C, unsigned AS) {
265   return getX86_FP80Ty(C)->getPointerTo(AS);
266 }
267
268 PointerType *Type::getFP128PtrTy(LLVMContext &C, unsigned AS) {
269   return getFP128Ty(C)->getPointerTo(AS);
270 }
271
272 PointerType *Type::getPPC_FP128PtrTy(LLVMContext &C, unsigned AS) {
273   return getPPC_FP128Ty(C)->getPointerTo(AS);
274 }
275
276 PointerType *Type::getX86_MMXPtrTy(LLVMContext &C, unsigned AS) {
277   return getX86_MMXTy(C)->getPointerTo(AS);
278 }
279
280 PointerType *Type::getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS) {
281   return getIntNTy(C, N)->getPointerTo(AS);
282 }
283
284 PointerType *Type::getInt1PtrTy(LLVMContext &C, unsigned AS) {
285   return getInt1Ty(C)->getPointerTo(AS);
286 }
287
288 PointerType *Type::getInt8PtrTy(LLVMContext &C, unsigned AS) {
289   return getInt8Ty(C)->getPointerTo(AS);
290 }
291
292 PointerType *Type::getInt16PtrTy(LLVMContext &C, unsigned AS) {
293   return getInt16Ty(C)->getPointerTo(AS);
294 }
295
296 PointerType *Type::getInt32PtrTy(LLVMContext &C, unsigned AS) {
297   return getInt32Ty(C)->getPointerTo(AS);
298 }
299
300 PointerType *Type::getInt64PtrTy(LLVMContext &C, unsigned AS) {
301   return getInt64Ty(C)->getPointerTo(AS);
302 }
303
304
305 //===----------------------------------------------------------------------===//
306 //                       IntegerType Implementation
307 //===----------------------------------------------------------------------===//
308
309 IntegerType *IntegerType::get(LLVMContext &C, unsigned NumBits) {
310   assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
311   assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
312   
313   // Check for the built-in integer types
314   switch (NumBits) {
315   case  1: return cast<IntegerType>(Type::getInt1Ty(C));
316   case  8: return cast<IntegerType>(Type::getInt8Ty(C));
317   case 16: return cast<IntegerType>(Type::getInt16Ty(C));
318   case 32: return cast<IntegerType>(Type::getInt32Ty(C));
319   case 64: return cast<IntegerType>(Type::getInt64Ty(C));
320   default: 
321     break;
322   }
323   
324   IntegerType *&Entry = C.pImpl->IntegerTypes[NumBits];
325   
326   if (Entry == 0)
327     Entry = new (C.pImpl->TypeAllocator) IntegerType(C, NumBits);
328   
329   return Entry;
330 }
331
332 bool IntegerType::isPowerOf2ByteWidth() const {
333   unsigned BitWidth = getBitWidth();
334   return (BitWidth > 7) && isPowerOf2_32(BitWidth);
335 }
336
337 APInt IntegerType::getMask() const {
338   return APInt::getAllOnesValue(getBitWidth());
339 }
340
341 //===----------------------------------------------------------------------===//
342 //                       FunctionType Implementation
343 //===----------------------------------------------------------------------===//
344
345 FunctionType::FunctionType(Type *Result, ArrayRef<Type*> Params,
346                            bool IsVarArgs)
347   : Type(Result->getContext(), FunctionTyID) {
348   Type **SubTys = reinterpret_cast<Type**>(this+1);
349   assert(isValidReturnType(Result) && "invalid return type for function");
350   setSubclassData(IsVarArgs);
351
352   SubTys[0] = const_cast<Type*>(Result);
353
354   for (unsigned i = 0, e = Params.size(); i != e; ++i) {
355     assert(isValidArgumentType(Params[i]) &&
356            "Not a valid type for function argument!");
357     SubTys[i+1] = Params[i];
358   }
359
360   ContainedTys = SubTys;
361   NumContainedTys = Params.size() + 1; // + 1 for result type
362 }
363
364 // FunctionType::get - The factory function for the FunctionType class.
365 FunctionType *FunctionType::get(Type *ReturnType,
366                                 ArrayRef<Type*> Params, bool isVarArg) {
367   LLVMContextImpl *pImpl = ReturnType->getContext().pImpl;
368   FunctionTypeKeyInfo::KeyTy Key(ReturnType, Params, isVarArg);
369   LLVMContextImpl::FunctionTypeMap::iterator I =
370     pImpl->FunctionTypes.find_as(Key);
371   FunctionType *FT;
372
373   if (I == pImpl->FunctionTypes.end()) {
374     FT = (FunctionType*) pImpl->TypeAllocator.
375       Allocate(sizeof(FunctionType) + sizeof(Type*) * (Params.size() + 1),
376                AlignOf<FunctionType>::Alignment);
377     new (FT) FunctionType(ReturnType, Params, isVarArg);
378     pImpl->FunctionTypes[FT] = true;
379   } else {
380     FT = I->first;
381   }
382
383   return FT;
384 }
385
386 FunctionType *FunctionType::get(Type *Result, bool isVarArg) {
387   return get(Result, ArrayRef<Type *>(), isVarArg);
388 }
389
390 /// isValidReturnType - Return true if the specified type is valid as a return
391 /// type.
392 bool FunctionType::isValidReturnType(Type *RetTy) {
393   return !RetTy->isFunctionTy() && !RetTy->isLabelTy() &&
394   !RetTy->isMetadataTy();
395 }
396
397 /// isValidArgumentType - Return true if the specified type is valid as an
398 /// argument type.
399 bool FunctionType::isValidArgumentType(Type *ArgTy) {
400   return ArgTy->isFirstClassType();
401 }
402
403 //===----------------------------------------------------------------------===//
404 //                       StructType Implementation
405 //===----------------------------------------------------------------------===//
406
407 // Primitive Constructors.
408
409 StructType *StructType::get(LLVMContext &Context, ArrayRef<Type*> ETypes, 
410                             bool isPacked) {
411   LLVMContextImpl *pImpl = Context.pImpl;
412   AnonStructTypeKeyInfo::KeyTy Key(ETypes, isPacked);
413   LLVMContextImpl::StructTypeMap::iterator I =
414     pImpl->AnonStructTypes.find_as(Key);
415   StructType *ST;
416
417   if (I == pImpl->AnonStructTypes.end()) {
418     // Value not found.  Create a new type!
419     ST = new (Context.pImpl->TypeAllocator) StructType(Context);
420     ST->setSubclassData(SCDB_IsLiteral);  // Literal struct.
421     ST->setBody(ETypes, isPacked);
422     Context.pImpl->AnonStructTypes[ST] = true;
423   } else {
424     ST = I->first;
425   }
426
427   return ST;
428 }
429
430 void StructType::setBody(ArrayRef<Type*> Elements, bool isPacked) {
431   assert(isOpaque() && "Struct body already set!");
432   
433   setSubclassData(getSubclassData() | SCDB_HasBody);
434   if (isPacked)
435     setSubclassData(getSubclassData() | SCDB_Packed);
436
437   unsigned NumElements = Elements.size();
438   Type **Elts = getContext().pImpl->TypeAllocator.Allocate<Type*>(NumElements);
439   memcpy(Elts, Elements.data(), sizeof(Elements[0]) * NumElements);
440   
441   ContainedTys = Elts;
442   NumContainedTys = NumElements;
443 }
444
445 void StructType::setName(StringRef Name) {
446   if (Name == getName()) return;
447
448   StringMap<StructType *> &SymbolTable = getContext().pImpl->NamedStructTypes;
449   typedef StringMap<StructType *>::MapEntryTy EntryTy;
450
451   // If this struct already had a name, remove its symbol table entry. Don't
452   // delete the data yet because it may be part of the new name.
453   if (SymbolTableEntry)
454     SymbolTable.remove((EntryTy *)SymbolTableEntry);
455
456   // If this is just removing the name, we're done.
457   if (Name.empty()) {
458     if (SymbolTableEntry) {
459       // Delete the old string data.
460       ((EntryTy *)SymbolTableEntry)->Destroy(SymbolTable.getAllocator());
461       SymbolTableEntry = 0;
462     }
463     return;
464   }
465   
466   // Look up the entry for the name.
467   EntryTy *Entry = &getContext().pImpl->NamedStructTypes.GetOrCreateValue(Name);
468   
469   // While we have a name collision, try a random rename.
470   if (Entry->getValue()) {
471     SmallString<64> TempStr(Name);
472     TempStr.push_back('.');
473     raw_svector_ostream TmpStream(TempStr);
474     unsigned NameSize = Name.size();
475    
476     do {
477       TempStr.resize(NameSize + 1);
478       TmpStream.resync();
479       TmpStream << getContext().pImpl->NamedStructTypesUniqueID++;
480       
481       Entry = &getContext().pImpl->
482                  NamedStructTypes.GetOrCreateValue(TmpStream.str());
483     } while (Entry->getValue());
484   }
485
486   // Okay, we found an entry that isn't used.  It's us!
487   Entry->setValue(this);
488
489   // Delete the old string data.
490   if (SymbolTableEntry)
491     ((EntryTy *)SymbolTableEntry)->Destroy(SymbolTable.getAllocator());
492   SymbolTableEntry = Entry;
493 }
494
495 //===----------------------------------------------------------------------===//
496 // StructType Helper functions.
497
498 StructType *StructType::create(LLVMContext &Context, StringRef Name) {
499   StructType *ST = new (Context.pImpl->TypeAllocator) StructType(Context);
500   if (!Name.empty())
501     ST->setName(Name);
502   return ST;
503 }
504
505 StructType *StructType::get(LLVMContext &Context, bool isPacked) {
506   return get(Context, llvm::ArrayRef<Type*>(), isPacked);
507 }
508
509 StructType *StructType::get(Type *type, ...) {
510   assert(type != 0 && "Cannot create a struct type with no elements with this");
511   LLVMContext &Ctx = type->getContext();
512   va_list ap;
513   SmallVector<llvm::Type*, 8> StructFields;
514   va_start(ap, type);
515   while (type) {
516     StructFields.push_back(type);
517     type = va_arg(ap, llvm::Type*);
518   }
519   return llvm::StructType::get(Ctx, StructFields);
520 }
521
522 StructType *StructType::create(LLVMContext &Context, ArrayRef<Type*> Elements,
523                                StringRef Name, bool isPacked) {
524   StructType *ST = create(Context, Name);
525   ST->setBody(Elements, isPacked);
526   return ST;
527 }
528
529 StructType *StructType::create(LLVMContext &Context, ArrayRef<Type*> Elements) {
530   return create(Context, Elements, StringRef());
531 }
532
533 StructType *StructType::create(LLVMContext &Context) {
534   return create(Context, StringRef());
535 }
536
537 StructType *StructType::create(ArrayRef<Type*> Elements, StringRef Name,
538                                bool isPacked) {
539   assert(!Elements.empty() &&
540          "This method may not be invoked with an empty list");
541   return create(Elements[0]->getContext(), Elements, Name, isPacked);
542 }
543
544 StructType *StructType::create(ArrayRef<Type*> Elements) {
545   assert(!Elements.empty() &&
546          "This method may not be invoked with an empty list");
547   return create(Elements[0]->getContext(), Elements, StringRef());
548 }
549
550 StructType *StructType::create(StringRef Name, Type *type, ...) {
551   assert(type != 0 && "Cannot create a struct type with no elements with this");
552   LLVMContext &Ctx = type->getContext();
553   va_list ap;
554   SmallVector<llvm::Type*, 8> StructFields;
555   va_start(ap, type);
556   while (type) {
557     StructFields.push_back(type);
558     type = va_arg(ap, llvm::Type*);
559   }
560   return llvm::StructType::create(Ctx, StructFields, Name);
561 }
562
563 bool StructType::isSized() const {
564   if ((getSubclassData() & SCDB_IsSized) != 0)
565     return true;
566   if (isOpaque())
567     return false;
568
569   // Okay, our struct is sized if all of the elements are, but if one of the
570   // elements is opaque, the struct isn't sized *yet*, but may become sized in
571   // the future, so just bail out without caching.
572   for (element_iterator I = element_begin(), E = element_end(); I != E; ++I)
573     if (!(*I)->isSized())
574       return false;
575
576   // Here we cheat a bit and cast away const-ness. The goal is to memoize when
577   // we find a sized type, as types can only move from opaque to sized, not the
578   // other way.
579   const_cast<StructType*>(this)->setSubclassData(
580     getSubclassData() | SCDB_IsSized);
581   return true;
582 }
583
584 StringRef StructType::getName() const {
585   assert(!isLiteral() && "Literal structs never have names");
586   if (SymbolTableEntry == 0) return StringRef();
587   
588   return ((StringMapEntry<StructType*> *)SymbolTableEntry)->getKey();
589 }
590
591 void StructType::setBody(Type *type, ...) {
592   assert(type != 0 && "Cannot create a struct type with no elements with this");
593   va_list ap;
594   SmallVector<llvm::Type*, 8> StructFields;
595   va_start(ap, type);
596   while (type) {
597     StructFields.push_back(type);
598     type = va_arg(ap, llvm::Type*);
599   }
600   setBody(StructFields);
601 }
602
603 bool StructType::isValidElementType(Type *ElemTy) {
604   return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
605          !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
606 }
607
608 /// isLayoutIdentical - Return true if this is layout identical to the
609 /// specified struct.
610 bool StructType::isLayoutIdentical(StructType *Other) const {
611   if (this == Other) return true;
612   
613   if (isPacked() != Other->isPacked() ||
614       getNumElements() != Other->getNumElements())
615     return false;
616   
617   return std::equal(element_begin(), element_end(), Other->element_begin());
618 }
619
620 /// getTypeByName - Return the type with the specified name, or null if there
621 /// is none by that name.
622 StructType *Module::getTypeByName(StringRef Name) const {
623   StringMap<StructType*>::iterator I =
624     getContext().pImpl->NamedStructTypes.find(Name);
625   if (I != getContext().pImpl->NamedStructTypes.end())
626     return I->second;
627   return 0;
628 }
629
630
631 //===----------------------------------------------------------------------===//
632 //                       CompositeType Implementation
633 //===----------------------------------------------------------------------===//
634
635 Type *CompositeType::getTypeAtIndex(const Value *V) {
636   if (StructType *STy = dyn_cast<StructType>(this)) {
637     unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
638     assert(indexValid(Idx) && "Invalid structure index!");
639     return STy->getElementType(Idx);
640   }
641   
642   return cast<SequentialType>(this)->getElementType();
643 }
644 Type *CompositeType::getTypeAtIndex(unsigned Idx) {
645   if (StructType *STy = dyn_cast<StructType>(this)) {
646     assert(indexValid(Idx) && "Invalid structure index!");
647     return STy->getElementType(Idx);
648   }
649   
650   return cast<SequentialType>(this)->getElementType();
651 }
652 bool CompositeType::indexValid(const Value *V) const {
653   if (const StructType *STy = dyn_cast<StructType>(this)) {
654     // Structure indexes require 32-bit integer constants.
655     if (V->getType()->isIntegerTy(32))
656       if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
657         return CU->getZExtValue() < STy->getNumElements();
658     return false;
659   }
660   
661   // Sequential types can be indexed by any integer.
662   return V->getType()->isIntegerTy();
663 }
664
665 bool CompositeType::indexValid(unsigned Idx) const {
666   if (const StructType *STy = dyn_cast<StructType>(this))
667     return Idx < STy->getNumElements();
668   // Sequential types can be indexed by any integer.
669   return true;
670 }
671
672
673 //===----------------------------------------------------------------------===//
674 //                           ArrayType Implementation
675 //===----------------------------------------------------------------------===//
676
677 ArrayType::ArrayType(Type *ElType, uint64_t NumEl)
678   : SequentialType(ArrayTyID, ElType) {
679   NumElements = NumEl;
680 }
681
682 ArrayType *ArrayType::get(Type *elementType, uint64_t NumElements) {
683   Type *ElementType = const_cast<Type*>(elementType);
684   assert(isValidElementType(ElementType) && "Invalid type for array element!");
685     
686   LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
687   ArrayType *&Entry = 
688     pImpl->ArrayTypes[std::make_pair(ElementType, NumElements)];
689   
690   if (Entry == 0)
691     Entry = new (pImpl->TypeAllocator) ArrayType(ElementType, NumElements);
692   return Entry;
693 }
694
695 bool ArrayType::isValidElementType(Type *ElemTy) {
696   return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
697          !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
698 }
699
700 //===----------------------------------------------------------------------===//
701 //                          VectorType Implementation
702 //===----------------------------------------------------------------------===//
703
704 VectorType::VectorType(Type *ElType, unsigned NumEl)
705   : SequentialType(VectorTyID, ElType) {
706   NumElements = NumEl;
707 }
708
709 VectorType *VectorType::get(Type *elementType, unsigned NumElements) {
710   Type *ElementType = const_cast<Type*>(elementType);
711   assert(NumElements > 0 && "#Elements of a VectorType must be greater than 0");
712   assert(isValidElementType(ElementType) &&
713          "Elements of a VectorType must be a primitive type");
714   
715   LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
716   VectorType *&Entry = ElementType->getContext().pImpl
717     ->VectorTypes[std::make_pair(ElementType, NumElements)];
718   
719   if (Entry == 0)
720     Entry = new (pImpl->TypeAllocator) VectorType(ElementType, NumElements);
721   return Entry;
722 }
723
724 bool VectorType::isValidElementType(Type *ElemTy) {
725   if (PointerType *PTy = dyn_cast<PointerType>(ElemTy))
726     ElemTy = PTy->getElementType();
727   return ElemTy->isIntegerTy() || ElemTy->isFloatingPointTy();
728 }
729
730 //===----------------------------------------------------------------------===//
731 //                         PointerType Implementation
732 //===----------------------------------------------------------------------===//
733
734 PointerType *PointerType::get(Type *EltTy, unsigned AddressSpace) {
735   assert(EltTy && "Can't get a pointer to <null> type!");
736   assert(isValidElementType(EltTy) && "Invalid type for pointer element!");
737   
738   LLVMContextImpl *CImpl = EltTy->getContext().pImpl;
739   
740   // Since AddressSpace #0 is the common case, we special case it.
741   PointerType *&Entry = AddressSpace == 0 ? CImpl->PointerTypes[EltTy]
742      : CImpl->ASPointerTypes[std::make_pair(EltTy, AddressSpace)];
743
744   if (Entry == 0)
745     Entry = new (CImpl->TypeAllocator) PointerType(EltTy, AddressSpace);
746   return Entry;
747 }
748
749
750 PointerType::PointerType(Type *E, unsigned AddrSpace)
751   : SequentialType(PointerTyID, E) {
752 #ifndef NDEBUG
753   const unsigned oldNCT = NumContainedTys;
754 #endif
755   setSubclassData(AddrSpace);
756   // Check for miscompile. PR11652.
757   assert(oldNCT == NumContainedTys && "bitfield written out of bounds?");
758 }
759
760 PointerType *Type::getPointerTo(unsigned addrs) {
761   return PointerType::get(this, addrs);
762 }
763
764 bool PointerType::isValidElementType(Type *ElemTy) {
765   return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
766          !ElemTy->isMetadataTy();
767 }