Ok, break down and add some cast<>'ing helper methods to the Type class
[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   // Opaque structs have no size.
189   if (cast<StructType>(this)->isOpaque())
190     return false;
191   
192   // Okay, our struct is sized if all of the elements are.
193   for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
194     if (!(*I)->isSized()) 
195       return false;
196
197   return true;
198 }
199
200 //===----------------------------------------------------------------------===//
201 //                         Subclass Helper Methods
202 //===----------------------------------------------------------------------===//
203
204 unsigned Type::getIntegerBitWidth() const {
205   return cast<IntegerType>(this)->getBitWidth();
206 }
207
208 bool Type::isFunctionVarArg() const {
209   return cast<FunctionType>(this)->isVarArg();
210 }
211
212 Type *Type::getFunctionParamType(unsigned i) const {
213   return cast<FunctionType>(this)->getParamType(i);
214 }
215
216 unsigned Type::getFunctionNumParams() const {
217   return cast<FunctionType>(this)->getNumParams();
218 }
219
220 Type *Type::getSequentialElementType() const {
221   return cast<SequentialType>(this)->getElementType();
222 }
223
224 uint64_t Type::getArrayNumElements() const {
225   return cast<ArrayType>(this)->getNumElements();
226 }
227
228 unsigned Type::getVectorNumElements() const {
229   return cast<VectorType>(this)->getNumElements();
230 }
231
232 unsigned Type::getPointerAddressSpace() const {
233   return cast<PointerType>(this)->getAddressSpace();
234 }
235
236
237
238
239 //===----------------------------------------------------------------------===//
240 //                          Primitive 'Type' data
241 //===----------------------------------------------------------------------===//
242
243 Type *Type::getVoidTy(LLVMContext &C) { return &C.pImpl->VoidTy; }
244 Type *Type::getLabelTy(LLVMContext &C) { return &C.pImpl->LabelTy; }
245 Type *Type::getHalfTy(LLVMContext &C) { return &C.pImpl->HalfTy; }
246 Type *Type::getFloatTy(LLVMContext &C) { return &C.pImpl->FloatTy; }
247 Type *Type::getDoubleTy(LLVMContext &C) { return &C.pImpl->DoubleTy; }
248 Type *Type::getMetadataTy(LLVMContext &C) { return &C.pImpl->MetadataTy; }
249 Type *Type::getX86_FP80Ty(LLVMContext &C) { return &C.pImpl->X86_FP80Ty; }
250 Type *Type::getFP128Ty(LLVMContext &C) { return &C.pImpl->FP128Ty; }
251 Type *Type::getPPC_FP128Ty(LLVMContext &C) { return &C.pImpl->PPC_FP128Ty; }
252 Type *Type::getX86_MMXTy(LLVMContext &C) { return &C.pImpl->X86_MMXTy; }
253
254 IntegerType *Type::getInt1Ty(LLVMContext &C) { return &C.pImpl->Int1Ty; }
255 IntegerType *Type::getInt8Ty(LLVMContext &C) { return &C.pImpl->Int8Ty; }
256 IntegerType *Type::getInt16Ty(LLVMContext &C) { return &C.pImpl->Int16Ty; }
257 IntegerType *Type::getInt32Ty(LLVMContext &C) { return &C.pImpl->Int32Ty; }
258 IntegerType *Type::getInt64Ty(LLVMContext &C) { return &C.pImpl->Int64Ty; }
259
260 IntegerType *Type::getIntNTy(LLVMContext &C, unsigned N) {
261   return IntegerType::get(C, N);
262 }
263
264 PointerType *Type::getHalfPtrTy(LLVMContext &C, unsigned AS) {
265   return getHalfTy(C)->getPointerTo(AS);
266 }
267
268 PointerType *Type::getFloatPtrTy(LLVMContext &C, unsigned AS) {
269   return getFloatTy(C)->getPointerTo(AS);
270 }
271
272 PointerType *Type::getDoublePtrTy(LLVMContext &C, unsigned AS) {
273   return getDoubleTy(C)->getPointerTo(AS);
274 }
275
276 PointerType *Type::getX86_FP80PtrTy(LLVMContext &C, unsigned AS) {
277   return getX86_FP80Ty(C)->getPointerTo(AS);
278 }
279
280 PointerType *Type::getFP128PtrTy(LLVMContext &C, unsigned AS) {
281   return getFP128Ty(C)->getPointerTo(AS);
282 }
283
284 PointerType *Type::getPPC_FP128PtrTy(LLVMContext &C, unsigned AS) {
285   return getPPC_FP128Ty(C)->getPointerTo(AS);
286 }
287
288 PointerType *Type::getX86_MMXPtrTy(LLVMContext &C, unsigned AS) {
289   return getX86_MMXTy(C)->getPointerTo(AS);
290 }
291
292 PointerType *Type::getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS) {
293   return getIntNTy(C, N)->getPointerTo(AS);
294 }
295
296 PointerType *Type::getInt1PtrTy(LLVMContext &C, unsigned AS) {
297   return getInt1Ty(C)->getPointerTo(AS);
298 }
299
300 PointerType *Type::getInt8PtrTy(LLVMContext &C, unsigned AS) {
301   return getInt8Ty(C)->getPointerTo(AS);
302 }
303
304 PointerType *Type::getInt16PtrTy(LLVMContext &C, unsigned AS) {
305   return getInt16Ty(C)->getPointerTo(AS);
306 }
307
308 PointerType *Type::getInt32PtrTy(LLVMContext &C, unsigned AS) {
309   return getInt32Ty(C)->getPointerTo(AS);
310 }
311
312 PointerType *Type::getInt64PtrTy(LLVMContext &C, unsigned AS) {
313   return getInt64Ty(C)->getPointerTo(AS);
314 }
315
316
317 //===----------------------------------------------------------------------===//
318 //                       IntegerType Implementation
319 //===----------------------------------------------------------------------===//
320
321 IntegerType *IntegerType::get(LLVMContext &C, unsigned NumBits) {
322   assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
323   assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
324   
325   // Check for the built-in integer types
326   switch (NumBits) {
327   case  1: return cast<IntegerType>(Type::getInt1Ty(C));
328   case  8: return cast<IntegerType>(Type::getInt8Ty(C));
329   case 16: return cast<IntegerType>(Type::getInt16Ty(C));
330   case 32: return cast<IntegerType>(Type::getInt32Ty(C));
331   case 64: return cast<IntegerType>(Type::getInt64Ty(C));
332   default: 
333     break;
334   }
335   
336   IntegerType *&Entry = C.pImpl->IntegerTypes[NumBits];
337   
338   if (Entry == 0)
339     Entry = new (C.pImpl->TypeAllocator) IntegerType(C, NumBits);
340   
341   return Entry;
342 }
343
344 bool IntegerType::isPowerOf2ByteWidth() const {
345   unsigned BitWidth = getBitWidth();
346   return (BitWidth > 7) && isPowerOf2_32(BitWidth);
347 }
348
349 APInt IntegerType::getMask() const {
350   return APInt::getAllOnesValue(getBitWidth());
351 }
352
353 //===----------------------------------------------------------------------===//
354 //                       FunctionType Implementation
355 //===----------------------------------------------------------------------===//
356
357 FunctionType::FunctionType(Type *Result, ArrayRef<Type*> Params,
358                            bool IsVarArgs)
359   : Type(Result->getContext(), FunctionTyID) {
360   Type **SubTys = reinterpret_cast<Type**>(this+1);
361   assert(isValidReturnType(Result) && "invalid return type for function");
362   setSubclassData(IsVarArgs);
363
364   SubTys[0] = const_cast<Type*>(Result);
365
366   for (unsigned i = 0, e = Params.size(); i != e; ++i) {
367     assert(isValidArgumentType(Params[i]) &&
368            "Not a valid type for function argument!");
369     SubTys[i+1] = Params[i];
370   }
371
372   ContainedTys = SubTys;
373   NumContainedTys = Params.size() + 1; // + 1 for result type
374 }
375
376 // FunctionType::get - The factory function for the FunctionType class.
377 FunctionType *FunctionType::get(Type *ReturnType,
378                                 ArrayRef<Type*> Params, bool isVarArg) {
379   // TODO: This is brutally slow.
380   std::vector<Type*> Key;
381   Key.reserve(Params.size()+2);
382   Key.push_back(const_cast<Type*>(ReturnType));
383   for (unsigned i = 0, e = Params.size(); i != e; ++i)
384     Key.push_back(const_cast<Type*>(Params[i]));
385   if (isVarArg)
386     Key.push_back(0);
387   
388   LLVMContextImpl *pImpl = ReturnType->getContext().pImpl;
389   FunctionType *&FT = pImpl->FunctionTypes[Key];
390   
391   if (FT == 0) {
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   }
397
398   return FT;
399 }
400
401
402 FunctionType *FunctionType::get(Type *Result, bool isVarArg) {
403   return get(Result, ArrayRef<Type *>(), isVarArg);
404 }
405
406
407 /// isValidReturnType - Return true if the specified type is valid as a return
408 /// type.
409 bool FunctionType::isValidReturnType(Type *RetTy) {
410   return !RetTy->isFunctionTy() && !RetTy->isLabelTy() &&
411   !RetTy->isMetadataTy();
412 }
413
414 /// isValidArgumentType - Return true if the specified type is valid as an
415 /// argument type.
416 bool FunctionType::isValidArgumentType(Type *ArgTy) {
417   return ArgTy->isFirstClassType();
418 }
419
420 //===----------------------------------------------------------------------===//
421 //                       StructType Implementation
422 //===----------------------------------------------------------------------===//
423
424 // Primitive Constructors.
425
426 StructType *StructType::get(LLVMContext &Context, ArrayRef<Type*> ETypes, 
427                             bool isPacked) {
428   // FIXME: std::vector is horribly inefficient for this probe.
429   std::vector<Type*> Key;
430   for (unsigned i = 0, e = ETypes.size(); i != e; ++i) {
431     assert(isValidElementType(ETypes[i]) &&
432            "Invalid type for structure element!");
433     Key.push_back(ETypes[i]);
434   }
435   if (isPacked)
436     Key.push_back(0);
437   
438   StructType *&ST = Context.pImpl->AnonStructTypes[Key];
439   if (ST) return ST;
440   
441   // Value not found.  Create a new type!
442   ST = new (Context.pImpl->TypeAllocator) StructType(Context);
443   ST->setSubclassData(SCDB_IsLiteral);  // Literal struct.
444   ST->setBody(ETypes, isPacked);
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   Type **Elts = getContext().pImpl->
456     TypeAllocator.Allocate<Type*>(Elements.size());
457   memcpy(Elts, Elements.data(), sizeof(Elements[0])*Elements.size());
458   
459   ContainedTys = Elts;
460   NumContainedTys = Elements.size();
461 }
462
463 void StructType::setName(StringRef Name) {
464   if (Name == getName()) return;
465
466   // If this struct already had a name, remove its symbol table entry.
467   if (SymbolTableEntry) {
468     getContext().pImpl->NamedStructTypes.erase(getName());
469     SymbolTableEntry = 0;
470   }
471   
472   // If this is just removing the name, we're done.
473   if (Name.empty())
474     return;
475   
476   // Look up the entry for the name.
477   StringMapEntry<StructType*> *Entry =
478     &getContext().pImpl->NamedStructTypes.GetOrCreateValue(Name);
479   
480   // While we have a name collision, try a random rename.
481   if (Entry->getValue()) {
482     SmallString<64> TempStr(Name);
483     TempStr.push_back('.');
484     raw_svector_ostream TmpStream(TempStr);
485    
486     do {
487       TempStr.resize(Name.size()+1);
488       TmpStream.resync();
489       TmpStream << getContext().pImpl->NamedStructTypesUniqueID++;
490       
491       Entry = &getContext().pImpl->
492                  NamedStructTypes.GetOrCreateValue(TmpStream.str());
493     } while (Entry->getValue());
494   }
495
496   // Okay, we found an entry that isn't used.  It's us!
497   Entry->setValue(this);
498     
499   SymbolTableEntry = Entry;
500 }
501
502 //===----------------------------------------------------------------------===//
503 // StructType Helper functions.
504
505 StructType *StructType::create(LLVMContext &Context, StringRef Name) {
506   StructType *ST = new (Context.pImpl->TypeAllocator) StructType(Context);
507   if (!Name.empty())
508     ST->setName(Name);
509   return ST;
510 }
511
512 StructType *StructType::get(LLVMContext &Context, bool isPacked) {
513   return get(Context, llvm::ArrayRef<Type*>(), isPacked);
514 }
515
516 StructType *StructType::get(Type *type, ...) {
517   assert(type != 0 && "Cannot create a struct type with no elements with this");
518   LLVMContext &Ctx = type->getContext();
519   va_list ap;
520   SmallVector<llvm::Type*, 8> StructFields;
521   va_start(ap, type);
522   while (type) {
523     StructFields.push_back(type);
524     type = va_arg(ap, llvm::Type*);
525   }
526   return llvm::StructType::get(Ctx, StructFields);
527 }
528
529 StructType *StructType::create(LLVMContext &Context, ArrayRef<Type*> Elements,
530                                StringRef Name, bool isPacked) {
531   StructType *ST = create(Context, Name);
532   ST->setBody(Elements, isPacked);
533   return ST;
534 }
535
536 StructType *StructType::create(LLVMContext &Context, ArrayRef<Type*> Elements) {
537   return create(Context, Elements, StringRef());
538 }
539
540 StructType *StructType::create(LLVMContext &Context) {
541   return create(Context, StringRef());
542 }
543
544
545 StructType *StructType::create(ArrayRef<Type*> Elements, StringRef Name,
546                                bool isPacked) {
547   assert(!Elements.empty() &&
548          "This method may not be invoked with an empty list");
549   return create(Elements[0]->getContext(), Elements, Name, isPacked);
550 }
551
552 StructType *StructType::create(ArrayRef<Type*> Elements) {
553   assert(!Elements.empty() &&
554          "This method may not be invoked with an empty list");
555   return create(Elements[0]->getContext(), Elements, StringRef());
556 }
557
558 StructType *StructType::create(StringRef Name, Type *type, ...) {
559   assert(type != 0 && "Cannot create a struct type with no elements with this");
560   LLVMContext &Ctx = type->getContext();
561   va_list ap;
562   SmallVector<llvm::Type*, 8> StructFields;
563   va_start(ap, type);
564   while (type) {
565     StructFields.push_back(type);
566     type = va_arg(ap, llvm::Type*);
567   }
568   return llvm::StructType::create(Ctx, StructFields, Name);
569 }
570
571
572 StringRef StructType::getName() const {
573   assert(!isLiteral() && "Literal structs never have names");
574   if (SymbolTableEntry == 0) return StringRef();
575   
576   return ((StringMapEntry<StructType*> *)SymbolTableEntry)->getKey();
577 }
578
579 void StructType::setBody(Type *type, ...) {
580   assert(type != 0 && "Cannot create a struct type with no elements with this");
581   va_list ap;
582   SmallVector<llvm::Type*, 8> StructFields;
583   va_start(ap, type);
584   while (type) {
585     StructFields.push_back(type);
586     type = va_arg(ap, llvm::Type*);
587   }
588   setBody(StructFields);
589 }
590
591 bool StructType::isValidElementType(Type *ElemTy) {
592   return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
593          !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
594 }
595
596 /// isLayoutIdentical - Return true if this is layout identical to the
597 /// specified struct.
598 bool StructType::isLayoutIdentical(StructType *Other) const {
599   if (this == Other) return true;
600   
601   if (isPacked() != Other->isPacked() ||
602       getNumElements() != Other->getNumElements())
603     return false;
604   
605   return std::equal(element_begin(), element_end(), Other->element_begin());
606 }
607
608
609 /// getTypeByName - Return the type with the specified name, or null if there
610 /// is none by that name.
611 StructType *Module::getTypeByName(StringRef Name) const {
612   StringMap<StructType*>::iterator I =
613     getContext().pImpl->NamedStructTypes.find(Name);
614   if (I != getContext().pImpl->NamedStructTypes.end())
615     return I->second;
616   return 0;
617 }
618
619
620 //===----------------------------------------------------------------------===//
621 //                       CompositeType Implementation
622 //===----------------------------------------------------------------------===//
623
624 Type *CompositeType::getTypeAtIndex(const Value *V) {
625   if (StructType *STy = dyn_cast<StructType>(this)) {
626     unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
627     assert(indexValid(Idx) && "Invalid structure index!");
628     return STy->getElementType(Idx);
629   }
630   
631   return cast<SequentialType>(this)->getElementType();
632 }
633 Type *CompositeType::getTypeAtIndex(unsigned Idx) {
634   if (StructType *STy = dyn_cast<StructType>(this)) {
635     assert(indexValid(Idx) && "Invalid structure index!");
636     return STy->getElementType(Idx);
637   }
638   
639   return cast<SequentialType>(this)->getElementType();
640 }
641 bool CompositeType::indexValid(const Value *V) const {
642   if (const StructType *STy = dyn_cast<StructType>(this)) {
643     // Structure indexes require 32-bit integer constants.
644     if (V->getType()->isIntegerTy(32))
645       if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
646         return CU->getZExtValue() < STy->getNumElements();
647     return false;
648   }
649   
650   // Sequential types can be indexed by any integer.
651   return V->getType()->isIntegerTy();
652 }
653
654 bool CompositeType::indexValid(unsigned Idx) const {
655   if (const StructType *STy = dyn_cast<StructType>(this))
656     return Idx < STy->getNumElements();
657   // Sequential types can be indexed by any integer.
658   return true;
659 }
660
661
662 //===----------------------------------------------------------------------===//
663 //                           ArrayType Implementation
664 //===----------------------------------------------------------------------===//
665
666 ArrayType::ArrayType(Type *ElType, uint64_t NumEl)
667   : SequentialType(ArrayTyID, ElType) {
668   NumElements = NumEl;
669 }
670
671
672 ArrayType *ArrayType::get(Type *elementType, uint64_t NumElements) {
673   Type *ElementType = const_cast<Type*>(elementType);
674   assert(isValidElementType(ElementType) && "Invalid type for array element!");
675     
676   LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
677   ArrayType *&Entry = 
678     pImpl->ArrayTypes[std::make_pair(ElementType, NumElements)];
679   
680   if (Entry == 0)
681     Entry = new (pImpl->TypeAllocator) ArrayType(ElementType, NumElements);
682   return Entry;
683 }
684
685 bool ArrayType::isValidElementType(Type *ElemTy) {
686   return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
687          !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
688 }
689
690 //===----------------------------------------------------------------------===//
691 //                          VectorType Implementation
692 //===----------------------------------------------------------------------===//
693
694 VectorType::VectorType(Type *ElType, unsigned NumEl)
695   : SequentialType(VectorTyID, ElType) {
696   NumElements = NumEl;
697 }
698
699 VectorType *VectorType::get(Type *elementType, unsigned NumElements) {
700   Type *ElementType = const_cast<Type*>(elementType);
701   assert(NumElements > 0 && "#Elements of a VectorType must be greater than 0");
702   assert(isValidElementType(ElementType) &&
703          "Elements of a VectorType must be a primitive type");
704   
705   LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
706   VectorType *&Entry = ElementType->getContext().pImpl
707     ->VectorTypes[std::make_pair(ElementType, NumElements)];
708   
709   if (Entry == 0)
710     Entry = new (pImpl->TypeAllocator) VectorType(ElementType, NumElements);
711   return Entry;
712 }
713
714 bool VectorType::isValidElementType(Type *ElemTy) {
715   if (PointerType *PTy = dyn_cast<PointerType>(ElemTy))
716     ElemTy = PTy->getElementType();
717   return ElemTy->isIntegerTy() || ElemTy->isFloatingPointTy();
718 }
719
720 //===----------------------------------------------------------------------===//
721 //                         PointerType Implementation
722 //===----------------------------------------------------------------------===//
723
724 PointerType *PointerType::get(Type *EltTy, unsigned AddressSpace) {
725   assert(EltTy && "Can't get a pointer to <null> type!");
726   assert(isValidElementType(EltTy) && "Invalid type for pointer element!");
727   
728   LLVMContextImpl *CImpl = EltTy->getContext().pImpl;
729   
730   // Since AddressSpace #0 is the common case, we special case it.
731   PointerType *&Entry = AddressSpace == 0 ? CImpl->PointerTypes[EltTy]
732      : CImpl->ASPointerTypes[std::make_pair(EltTy, AddressSpace)];
733
734   if (Entry == 0)
735     Entry = new (CImpl->TypeAllocator) PointerType(EltTy, AddressSpace);
736   return Entry;
737 }
738
739
740 PointerType::PointerType(Type *E, unsigned AddrSpace)
741   : SequentialType(PointerTyID, E) {
742 #ifndef NDEBUG
743   const unsigned oldNCT = NumContainedTys;
744 #endif
745   setSubclassData(AddrSpace);
746   // Check for miscompile. PR11652.
747   assert(oldNCT == NumContainedTys && "bitfield written out of bounds?");
748 }
749
750 PointerType *Type::getPointerTo(unsigned addrs) {
751   return PointerType::get(this, addrs);
752 }
753
754 bool PointerType::isValidElementType(Type *ElemTy) {
755   return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
756          !ElemTy->isMetadataTy();
757 }