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