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