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