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