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