xref: /llvm-project-15.0.7/clang/lib/AST/Type.cpp (revision 0ab5e2cd)
1 //===--- Type.cpp - Type representation and manipulation ------------------===//
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 type-related functionality.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/CharUnits.h"
16 #include "clang/AST/Type.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/PrettyPrinter.h"
22 #include "clang/AST/TypeVisitor.h"
23 #include "clang/Basic/Specifiers.h"
24 #include "llvm/ADT/APSInt.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <algorithm>
28 using namespace clang;
29 
30 bool QualType::isConstant(QualType T, ASTContext &Ctx) {
31   if (T.isConstQualified())
32     return true;
33 
34   if (const ArrayType *AT = Ctx.getAsArrayType(T))
35     return AT->getElementType().isConstant(Ctx);
36 
37   return false;
38 }
39 
40 unsigned ConstantArrayType::getNumAddressingBits(ASTContext &Context,
41                                                  QualType ElementType,
42                                                const llvm::APInt &NumElements) {
43   llvm::APSInt SizeExtended(NumElements, true);
44   unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
45   SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
46                                               SizeExtended.getBitWidth()) * 2);
47 
48   uint64_t ElementSize
49     = Context.getTypeSizeInChars(ElementType).getQuantity();
50   llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
51   TotalSize *= SizeExtended;
52 
53   return TotalSize.getActiveBits();
54 }
55 
56 unsigned ConstantArrayType::getMaxSizeBits(ASTContext &Context) {
57   unsigned Bits = Context.getTypeSize(Context.getSizeType());
58 
59   // GCC appears to only allow 63 bits worth of address space when compiling
60   // for 64-bit, so we do the same.
61   if (Bits == 64)
62     --Bits;
63 
64   return Bits;
65 }
66 
67 DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context,
68                                                  QualType et, QualType can,
69                                                  Expr *e, ArraySizeModifier sm,
70                                                  unsigned tq,
71                                                  SourceRange brackets)
72     : ArrayType(DependentSizedArray, et, can, sm, tq,
73                 (et->containsUnexpandedParameterPack() ||
74                  (e && e->containsUnexpandedParameterPack()))),
75       Context(Context), SizeExpr((Stmt*) e), Brackets(brackets)
76 {
77 }
78 
79 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
80                                       const ASTContext &Context,
81                                       QualType ET,
82                                       ArraySizeModifier SizeMod,
83                                       unsigned TypeQuals,
84                                       Expr *E) {
85   ID.AddPointer(ET.getAsOpaquePtr());
86   ID.AddInteger(SizeMod);
87   ID.AddInteger(TypeQuals);
88   E->Profile(ID, Context, true);
89 }
90 
91 DependentSizedExtVectorType::DependentSizedExtVectorType(const
92                                                          ASTContext &Context,
93                                                          QualType ElementType,
94                                                          QualType can,
95                                                          Expr *SizeExpr,
96                                                          SourceLocation loc)
97     : Type(DependentSizedExtVector, can, /*Dependent=*/true,
98            ElementType->isVariablyModifiedType(),
99            (ElementType->containsUnexpandedParameterPack() ||
100             (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))),
101       Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
102       loc(loc)
103 {
104 }
105 
106 void
107 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
108                                      const ASTContext &Context,
109                                      QualType ElementType, Expr *SizeExpr) {
110   ID.AddPointer(ElementType.getAsOpaquePtr());
111   SizeExpr->Profile(ID, Context, true);
112 }
113 
114 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
115                        VectorKind vecKind)
116   : Type(Vector, canonType, vecType->isDependentType(),
117          vecType->isVariablyModifiedType(),
118          vecType->containsUnexpandedParameterPack()),
119     ElementType(vecType)
120 {
121   VectorTypeBits.VecKind = vecKind;
122   VectorTypeBits.NumElements = nElements;
123 }
124 
125 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
126                        QualType canonType, VectorKind vecKind)
127   : Type(tc, canonType, vecType->isDependentType(),
128          vecType->isVariablyModifiedType(),
129          vecType->containsUnexpandedParameterPack()),
130     ElementType(vecType)
131 {
132   VectorTypeBits.VecKind = vecKind;
133   VectorTypeBits.NumElements = nElements;
134 }
135 
136 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
137 /// element type of the array, potentially with type qualifiers missing.
138 /// This method should never be used when type qualifiers are meaningful.
139 const Type *Type::getArrayElementTypeNoTypeQual() const {
140   // If this is directly an array type, return it.
141   if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
142     return ATy->getElementType().getTypePtr();
143 
144   // If the canonical form of this type isn't the right kind, reject it.
145   if (!isa<ArrayType>(CanonicalType))
146     return 0;
147 
148   // If this is a typedef for an array type, strip the typedef off without
149   // losing all typedef information.
150   return cast<ArrayType>(getUnqualifiedDesugaredType())
151     ->getElementType().getTypePtr();
152 }
153 
154 /// getDesugaredType - Return the specified type with any "sugar" removed from
155 /// the type.  This takes off typedefs, typeof's etc.  If the outer level of
156 /// the type is already concrete, it returns it unmodified.  This is similar
157 /// to getting the canonical type, but it doesn't remove *all* typedefs.  For
158 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
159 /// concrete.
160 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
161   SplitQualType split = getSplitDesugaredType(T);
162   return Context.getQualifiedType(split.first, split.second);
163 }
164 
165 SplitQualType QualType::getSplitDesugaredType(QualType T) {
166   QualifierCollector Qs;
167 
168   QualType Cur = T;
169   while (true) {
170     const Type *CurTy = Qs.strip(Cur);
171     switch (CurTy->getTypeClass()) {
172 #define ABSTRACT_TYPE(Class, Parent)
173 #define TYPE(Class, Parent) \
174     case Type::Class: { \
175       const Class##Type *Ty = cast<Class##Type>(CurTy); \
176       if (!Ty->isSugared()) \
177         return SplitQualType(Ty, Qs); \
178       Cur = Ty->desugar(); \
179       break; \
180     }
181 #include "clang/AST/TypeNodes.def"
182     }
183   }
184 }
185 
186 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
187   SplitQualType split = type.split();
188 
189   // All the qualifiers we've seen so far.
190   Qualifiers quals = split.second;
191 
192   // The last type node we saw with any nodes inside it.
193   const Type *lastTypeWithQuals = split.first;
194 
195   while (true) {
196     QualType next;
197 
198     // Do a single-step desugar, aborting the loop if the type isn't
199     // sugared.
200     switch (split.first->getTypeClass()) {
201 #define ABSTRACT_TYPE(Class, Parent)
202 #define TYPE(Class, Parent) \
203     case Type::Class: { \
204       const Class##Type *ty = cast<Class##Type>(split.first); \
205       if (!ty->isSugared()) goto done; \
206       next = ty->desugar(); \
207       break; \
208     }
209 #include "clang/AST/TypeNodes.def"
210     }
211 
212     // Otherwise, split the underlying type.  If that yields qualifiers,
213     // update the information.
214     split = next.split();
215     if (!split.second.empty()) {
216       lastTypeWithQuals = split.first;
217       quals.addConsistentQualifiers(split.second);
218     }
219   }
220 
221  done:
222   return SplitQualType(lastTypeWithQuals, quals);
223 }
224 
225 QualType QualType::IgnoreParens(QualType T) {
226   // FIXME: this seems inherently un-qualifiers-safe.
227   while (const ParenType *PT = T->getAs<ParenType>())
228     T = PT->getInnerType();
229   return T;
230 }
231 
232 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
233 /// sugar off the given type.  This should produce an object of the
234 /// same dynamic type as the canonical type.
235 const Type *Type::getUnqualifiedDesugaredType() const {
236   const Type *Cur = this;
237 
238   while (true) {
239     switch (Cur->getTypeClass()) {
240 #define ABSTRACT_TYPE(Class, Parent)
241 #define TYPE(Class, Parent) \
242     case Class: { \
243       const Class##Type *Ty = cast<Class##Type>(Cur); \
244       if (!Ty->isSugared()) return Cur; \
245       Cur = Ty->desugar().getTypePtr(); \
246       break; \
247     }
248 #include "clang/AST/TypeNodes.def"
249     }
250   }
251 }
252 
253 /// isVoidType - Helper method to determine if this is the 'void' type.
254 bool Type::isVoidType() const {
255   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
256     return BT->getKind() == BuiltinType::Void;
257   return false;
258 }
259 
260 bool Type::isDerivedType() const {
261   switch (CanonicalType->getTypeClass()) {
262   case Pointer:
263   case VariableArray:
264   case ConstantArray:
265   case IncompleteArray:
266   case FunctionProto:
267   case FunctionNoProto:
268   case LValueReference:
269   case RValueReference:
270   case Record:
271     return true;
272   default:
273     return false;
274   }
275 }
276 
277 bool Type::isClassType() const {
278   if (const RecordType *RT = getAs<RecordType>())
279     return RT->getDecl()->isClass();
280   return false;
281 }
282 bool Type::isStructureType() const {
283   if (const RecordType *RT = getAs<RecordType>())
284     return RT->getDecl()->isStruct();
285   return false;
286 }
287 bool Type::isStructureOrClassType() const {
288   if (const RecordType *RT = getAs<RecordType>())
289     return RT->getDecl()->isStruct() || RT->getDecl()->isClass();
290   return false;
291 }
292 bool Type::isVoidPointerType() const {
293   if (const PointerType *PT = getAs<PointerType>())
294     return PT->getPointeeType()->isVoidType();
295   return false;
296 }
297 
298 bool Type::isUnionType() const {
299   if (const RecordType *RT = getAs<RecordType>())
300     return RT->getDecl()->isUnion();
301   return false;
302 }
303 
304 bool Type::isComplexType() const {
305   if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
306     return CT->getElementType()->isFloatingType();
307   return false;
308 }
309 
310 bool Type::isComplexIntegerType() const {
311   // Check for GCC complex integer extension.
312   return getAsComplexIntegerType();
313 }
314 
315 const ComplexType *Type::getAsComplexIntegerType() const {
316   if (const ComplexType *Complex = getAs<ComplexType>())
317     if (Complex->getElementType()->isIntegerType())
318       return Complex;
319   return 0;
320 }
321 
322 QualType Type::getPointeeType() const {
323   if (const PointerType *PT = getAs<PointerType>())
324     return PT->getPointeeType();
325   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
326     return OPT->getPointeeType();
327   if (const BlockPointerType *BPT = getAs<BlockPointerType>())
328     return BPT->getPointeeType();
329   if (const ReferenceType *RT = getAs<ReferenceType>())
330     return RT->getPointeeType();
331   return QualType();
332 }
333 
334 const RecordType *Type::getAsStructureType() const {
335   // If this is directly a structure type, return it.
336   if (const RecordType *RT = dyn_cast<RecordType>(this)) {
337     if (RT->getDecl()->isStruct())
338       return RT;
339   }
340 
341   // If the canonical form of this type isn't the right kind, reject it.
342   if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
343     if (!RT->getDecl()->isStruct())
344       return 0;
345 
346     // If this is a typedef for a structure type, strip the typedef off without
347     // losing all typedef information.
348     return cast<RecordType>(getUnqualifiedDesugaredType());
349   }
350   return 0;
351 }
352 
353 const RecordType *Type::getAsUnionType() const {
354   // If this is directly a union type, return it.
355   if (const RecordType *RT = dyn_cast<RecordType>(this)) {
356     if (RT->getDecl()->isUnion())
357       return RT;
358   }
359 
360   // If the canonical form of this type isn't the right kind, reject it.
361   if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
362     if (!RT->getDecl()->isUnion())
363       return 0;
364 
365     // If this is a typedef for a union type, strip the typedef off without
366     // losing all typedef information.
367     return cast<RecordType>(getUnqualifiedDesugaredType());
368   }
369 
370   return 0;
371 }
372 
373 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
374                                ObjCProtocolDecl * const *Protocols,
375                                unsigned NumProtocols)
376   : Type(ObjCObject, Canonical, false, false, false),
377     BaseType(Base)
378 {
379   ObjCObjectTypeBits.NumProtocols = NumProtocols;
380   assert(getNumProtocols() == NumProtocols &&
381          "bitfield overflow in protocol count");
382   if (NumProtocols)
383     memcpy(getProtocolStorage(), Protocols,
384            NumProtocols * sizeof(ObjCProtocolDecl*));
385 }
386 
387 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
388   // There is no sugar for ObjCObjectType's, just return the canonical
389   // type pointer if it is the right class.  There is no typedef information to
390   // return and these cannot be Address-space qualified.
391   if (const ObjCObjectType *T = getAs<ObjCObjectType>())
392     if (T->getNumProtocols() && T->getInterface())
393       return T;
394   return 0;
395 }
396 
397 bool Type::isObjCQualifiedInterfaceType() const {
398   return getAsObjCQualifiedInterfaceType() != 0;
399 }
400 
401 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
402   // There is no sugar for ObjCQualifiedIdType's, just return the canonical
403   // type pointer if it is the right class.
404   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
405     if (OPT->isObjCQualifiedIdType())
406       return OPT;
407   }
408   return 0;
409 }
410 
411 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
412   // There is no sugar for ObjCQualifiedClassType's, just return the canonical
413   // type pointer if it is the right class.
414   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
415     if (OPT->isObjCQualifiedClassType())
416       return OPT;
417   }
418   return 0;
419 }
420 
421 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
422   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
423     if (OPT->getInterfaceType())
424       return OPT;
425   }
426   return 0;
427 }
428 
429 const CXXRecordDecl *Type::getCXXRecordDeclForPointerType() const {
430   if (const PointerType *PT = getAs<PointerType>())
431     if (const RecordType *RT = PT->getPointeeType()->getAs<RecordType>())
432       return dyn_cast<CXXRecordDecl>(RT->getDecl());
433   return 0;
434 }
435 
436 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
437   if (const RecordType *RT = getAs<RecordType>())
438     return dyn_cast<CXXRecordDecl>(RT->getDecl());
439   else if (const InjectedClassNameType *Injected
440                                   = getAs<InjectedClassNameType>())
441     return Injected->getDecl();
442 
443   return 0;
444 }
445 
446 namespace {
447   class GetContainedAutoVisitor :
448     public TypeVisitor<GetContainedAutoVisitor, AutoType*> {
449   public:
450     using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit;
451     AutoType *Visit(QualType T) {
452       if (T.isNull())
453         return 0;
454       return Visit(T.getTypePtr());
455     }
456 
457     // The 'auto' type itself.
458     AutoType *VisitAutoType(const AutoType *AT) {
459       return const_cast<AutoType*>(AT);
460     }
461 
462     // Only these types can contain the desired 'auto' type.
463     AutoType *VisitPointerType(const PointerType *T) {
464       return Visit(T->getPointeeType());
465     }
466     AutoType *VisitBlockPointerType(const BlockPointerType *T) {
467       return Visit(T->getPointeeType());
468     }
469     AutoType *VisitReferenceType(const ReferenceType *T) {
470       return Visit(T->getPointeeTypeAsWritten());
471     }
472     AutoType *VisitMemberPointerType(const MemberPointerType *T) {
473       return Visit(T->getPointeeType());
474     }
475     AutoType *VisitArrayType(const ArrayType *T) {
476       return Visit(T->getElementType());
477     }
478     AutoType *VisitDependentSizedExtVectorType(
479       const DependentSizedExtVectorType *T) {
480       return Visit(T->getElementType());
481     }
482     AutoType *VisitVectorType(const VectorType *T) {
483       return Visit(T->getElementType());
484     }
485     AutoType *VisitFunctionType(const FunctionType *T) {
486       return Visit(T->getResultType());
487     }
488     AutoType *VisitParenType(const ParenType *T) {
489       return Visit(T->getInnerType());
490     }
491     AutoType *VisitAttributedType(const AttributedType *T) {
492       return Visit(T->getModifiedType());
493     }
494   };
495 }
496 
497 AutoType *Type::getContainedAutoType() const {
498   return GetContainedAutoVisitor().Visit(this);
499 }
500 
501 bool Type::isIntegerType() const {
502   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
503     return BT->getKind() >= BuiltinType::Bool &&
504            BT->getKind() <= BuiltinType::Int128;
505   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
506     // Incomplete enum types are not treated as integer types.
507     // FIXME: In C++, enum types are never integer types.
508     return ET->getDecl()->isComplete();
509   return false;
510 }
511 
512 bool Type::hasIntegerRepresentation() const {
513   if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
514     return VT->getElementType()->isIntegerType();
515   else
516     return isIntegerType();
517 }
518 
519 /// \brief Determine whether this type is an integral type.
520 ///
521 /// This routine determines whether the given type is an integral type per
522 /// C++ [basic.fundamental]p7. Although the C standard does not define the
523 /// term "integral type", it has a similar term "integer type", and in C++
524 /// the two terms are equivalent. However, C's "integer type" includes
525 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
526 /// parameter is used to determine whether we should be following the C or
527 /// C++ rules when determining whether this type is an integral/integer type.
528 ///
529 /// For cases where C permits "an integer type" and C++ permits "an integral
530 /// type", use this routine.
531 ///
532 /// For cases where C permits "an integer type" and C++ permits "an integral
533 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
534 ///
535 /// \param Ctx The context in which this type occurs.
536 ///
537 /// \returns true if the type is considered an integral type, false otherwise.
538 bool Type::isIntegralType(ASTContext &Ctx) const {
539   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
540     return BT->getKind() >= BuiltinType::Bool &&
541     BT->getKind() <= BuiltinType::Int128;
542 
543   if (!Ctx.getLangOptions().CPlusPlus)
544     if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
545       return ET->getDecl()->isComplete(); // Complete enum types are integral in C.
546 
547   return false;
548 }
549 
550 bool Type::isIntegralOrEnumerationType() const {
551   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
552     return BT->getKind() >= BuiltinType::Bool &&
553            BT->getKind() <= BuiltinType::Int128;
554 
555   // Check for a complete enum type; incomplete enum types are not properly an
556   // enumeration type in the sense required here.
557   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
558     return ET->getDecl()->isComplete();
559 
560   return false;
561 }
562 
563 bool Type::isIntegralOrUnscopedEnumerationType() const {
564   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
565     return BT->getKind() >= BuiltinType::Bool &&
566            BT->getKind() <= BuiltinType::Int128;
567 
568   // Check for a complete enum type; incomplete enum types are not properly an
569   // enumeration type in the sense required here.
570   // C++0x: However, if the underlying type of the enum is fixed, it is
571   // considered complete.
572   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
573     return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
574 
575   return false;
576 }
577 
578 
579 bool Type::isBooleanType() const {
580   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
581     return BT->getKind() == BuiltinType::Bool;
582   return false;
583 }
584 
585 bool Type::isCharType() const {
586   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
587     return BT->getKind() == BuiltinType::Char_U ||
588            BT->getKind() == BuiltinType::UChar ||
589            BT->getKind() == BuiltinType::Char_S ||
590            BT->getKind() == BuiltinType::SChar;
591   return false;
592 }
593 
594 bool Type::isWideCharType() const {
595   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
596     return BT->getKind() == BuiltinType::WChar_S ||
597            BT->getKind() == BuiltinType::WChar_U;
598   return false;
599 }
600 
601 /// \brief Determine whether this type is any of the built-in character
602 /// types.
603 bool Type::isAnyCharacterType() const {
604   const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
605   if (BT == 0) return false;
606   switch (BT->getKind()) {
607   default: return false;
608   case BuiltinType::Char_U:
609   case BuiltinType::UChar:
610   case BuiltinType::WChar_U:
611   case BuiltinType::Char16:
612   case BuiltinType::Char32:
613   case BuiltinType::Char_S:
614   case BuiltinType::SChar:
615   case BuiltinType::WChar_S:
616     return true;
617   }
618 }
619 
620 /// isSignedIntegerType - Return true if this is an integer type that is
621 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
622 /// an enum decl which has a signed representation
623 bool Type::isSignedIntegerType() const {
624   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
625     return BT->getKind() >= BuiltinType::Char_S &&
626            BT->getKind() <= BuiltinType::Int128;
627   }
628 
629   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
630     // Incomplete enum types are not treated as integer types.
631     // FIXME: In C++, enum types are never integer types.
632     if (ET->getDecl()->isComplete())
633       return ET->getDecl()->getIntegerType()->isSignedIntegerType();
634   }
635 
636   return false;
637 }
638 
639 bool Type::hasSignedIntegerRepresentation() const {
640   if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
641     return VT->getElementType()->isSignedIntegerType();
642   else
643     return isSignedIntegerType();
644 }
645 
646 /// isUnsignedIntegerType - Return true if this is an integer type that is
647 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
648 /// decl which has an unsigned representation
649 bool Type::isUnsignedIntegerType() const {
650   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
651     return BT->getKind() >= BuiltinType::Bool &&
652            BT->getKind() <= BuiltinType::UInt128;
653   }
654 
655   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
656     // Incomplete enum types are not treated as integer types.
657     // FIXME: In C++, enum types are never integer types.
658     if (ET->getDecl()->isComplete())
659       return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
660   }
661 
662   return false;
663 }
664 
665 bool Type::hasUnsignedIntegerRepresentation() const {
666   if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
667     return VT->getElementType()->isUnsignedIntegerType();
668   else
669     return isUnsignedIntegerType();
670 }
671 
672 bool Type::isFloatingType() const {
673   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
674     return BT->getKind() >= BuiltinType::Float &&
675            BT->getKind() <= BuiltinType::LongDouble;
676   if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
677     return CT->getElementType()->isFloatingType();
678   return false;
679 }
680 
681 bool Type::hasFloatingRepresentation() const {
682   if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
683     return VT->getElementType()->isFloatingType();
684   else
685     return isFloatingType();
686 }
687 
688 bool Type::isRealFloatingType() const {
689   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
690     return BT->isFloatingPoint();
691   return false;
692 }
693 
694 bool Type::isRealType() const {
695   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
696     return BT->getKind() >= BuiltinType::Bool &&
697            BT->getKind() <= BuiltinType::LongDouble;
698   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
699       return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
700   return false;
701 }
702 
703 bool Type::isArithmeticType() const {
704   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
705     return BT->getKind() >= BuiltinType::Bool &&
706            BT->getKind() <= BuiltinType::LongDouble;
707   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
708     // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
709     // If a body isn't seen by the time we get here, return false.
710     //
711     // C++0x: Enumerations are not arithmetic types. For now, just return
712     // false for scoped enumerations since that will disable any
713     // unwanted implicit conversions.
714     return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
715   return isa<ComplexType>(CanonicalType);
716 }
717 
718 bool Type::isScalarType() const {
719   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
720     return BT->getKind() > BuiltinType::Void &&
721            BT->getKind() <= BuiltinType::NullPtr;
722   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
723     // Enums are scalar types, but only if they are defined.  Incomplete enums
724     // are not treated as scalar types.
725     return ET->getDecl()->isComplete();
726   return isa<PointerType>(CanonicalType) ||
727          isa<BlockPointerType>(CanonicalType) ||
728          isa<MemberPointerType>(CanonicalType) ||
729          isa<ComplexType>(CanonicalType) ||
730          isa<ObjCObjectPointerType>(CanonicalType);
731 }
732 
733 Type::ScalarTypeKind Type::getScalarTypeKind() const {
734   assert(isScalarType());
735 
736   const Type *T = CanonicalType.getTypePtr();
737   if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
738     if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
739     if (BT->getKind() == BuiltinType::NullPtr) return STK_Pointer;
740     if (BT->isInteger()) return STK_Integral;
741     if (BT->isFloatingPoint()) return STK_Floating;
742     llvm_unreachable("unknown scalar builtin type");
743   } else if (isa<PointerType>(T) ||
744              isa<BlockPointerType>(T) ||
745              isa<ObjCObjectPointerType>(T)) {
746     return STK_Pointer;
747   } else if (isa<MemberPointerType>(T)) {
748     return STK_MemberPointer;
749   } else if (isa<EnumType>(T)) {
750     assert(cast<EnumType>(T)->getDecl()->isComplete());
751     return STK_Integral;
752   } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
753     if (CT->getElementType()->isRealFloatingType())
754       return STK_FloatingComplex;
755     return STK_IntegralComplex;
756   }
757 
758   llvm_unreachable("unknown scalar type");
759   return STK_Pointer;
760 }
761 
762 /// \brief Determines whether the type is a C++ aggregate type or C
763 /// aggregate or union type.
764 ///
765 /// An aggregate type is an array or a class type (struct, union, or
766 /// class) that has no user-declared constructors, no private or
767 /// protected non-static data members, no base classes, and no virtual
768 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
769 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
770 /// includes union types.
771 bool Type::isAggregateType() const {
772   if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
773     if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
774       return ClassDecl->isAggregate();
775 
776     return true;
777   }
778 
779   return isa<ArrayType>(CanonicalType);
780 }
781 
782 /// isConstantSizeType - Return true if this is not a variable sized type,
783 /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
784 /// incomplete types or dependent types.
785 bool Type::isConstantSizeType() const {
786   assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
787   assert(!isDependentType() && "This doesn't make sense for dependent types");
788   // The VAT must have a size, as it is known to be complete.
789   return !isa<VariableArrayType>(CanonicalType);
790 }
791 
792 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
793 /// - a type that can describe objects, but which lacks information needed to
794 /// determine its size.
795 bool Type::isIncompleteType() const {
796   switch (CanonicalType->getTypeClass()) {
797   default: return false;
798   case Builtin:
799     // Void is the only incomplete builtin type.  Per C99 6.2.5p19, it can never
800     // be completed.
801     return isVoidType();
802   case Enum:
803     // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
804     if (cast<EnumType>(CanonicalType)->getDecl()->isFixed())
805         return false;
806     // Fall through.
807   case Record:
808     // A tagged type (struct/union/enum/class) is incomplete if the decl is a
809     // forward declaration, but not a full definition (C99 6.2.5p22).
810     return !cast<TagType>(CanonicalType)->getDecl()->isDefinition();
811   case ConstantArray:
812     // An array is incomplete if its element type is incomplete
813     // (C++ [dcl.array]p1).
814     // We don't handle variable arrays (they're not allowed in C++) or
815     // dependent-sized arrays (dependent types are never treated as incomplete).
816     return cast<ArrayType>(CanonicalType)->getElementType()->isIncompleteType();
817   case IncompleteArray:
818     // An array of unknown size is an incomplete type (C99 6.2.5p22).
819     return true;
820   case ObjCObject:
821     return cast<ObjCObjectType>(CanonicalType)->getBaseType()
822                                                          ->isIncompleteType();
823   case ObjCInterface:
824     // ObjC interfaces are incomplete if they are @class, not @interface.
825     return cast<ObjCInterfaceType>(CanonicalType)->getDecl()->isForwardDecl();
826   }
827 }
828 
829 /// isPODType - Return true if this is a plain-old-data type (C++ 3.9p10)
830 bool Type::isPODType() const {
831   // The compiler shouldn't query this for incomplete types, but the user might.
832   // We return false for that case. Except for incomplete arrays of PODs, which
833   // are PODs according to the standard.
834   if (isIncompleteArrayType() &&
835       cast<ArrayType>(CanonicalType)->getElementType()->isPODType())
836     return true;
837   if (isIncompleteType())
838     return false;
839 
840   switch (CanonicalType->getTypeClass()) {
841     // Everything not explicitly mentioned is not POD.
842   default: return false;
843   case VariableArray:
844   case ConstantArray:
845     // IncompleteArray is handled above.
846     return cast<ArrayType>(CanonicalType)->getElementType()->isPODType();
847 
848   case Builtin:
849   case Complex:
850   case Pointer:
851   case MemberPointer:
852   case Vector:
853   case ExtVector:
854   case ObjCObjectPointer:
855   case BlockPointer:
856     return true;
857 
858   case Enum:
859     return true;
860 
861   case Record:
862     if (CXXRecordDecl *ClassDecl
863           = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
864       return ClassDecl->isPOD();
865 
866     // C struct/union is POD.
867     return true;
868   }
869 }
870 
871 bool Type::isLiteralType() const {
872   if (isIncompleteType())
873     return false;
874 
875   // C++0x [basic.types]p10:
876   //   A type is a literal type if it is:
877   switch (CanonicalType->getTypeClass()) {
878     // We're whitelisting
879   default: return false;
880 
881     //   -- a scalar type
882   case Builtin:
883   case Complex:
884   case Pointer:
885   case MemberPointer:
886   case Vector:
887   case ExtVector:
888   case ObjCObjectPointer:
889   case Enum:
890     return true;
891 
892     //   -- a class type with ...
893   case Record:
894     // FIXME: Do the tests
895     return false;
896 
897     //   -- an array of literal type
898     // Extension: variable arrays cannot be literal types, since they're
899     // runtime-sized.
900   case ConstantArray:
901     return cast<ArrayType>(CanonicalType)->getElementType()->isLiteralType();
902   }
903 }
904 
905 bool Type::isPromotableIntegerType() const {
906   if (const BuiltinType *BT = getAs<BuiltinType>())
907     switch (BT->getKind()) {
908     case BuiltinType::Bool:
909     case BuiltinType::Char_S:
910     case BuiltinType::Char_U:
911     case BuiltinType::SChar:
912     case BuiltinType::UChar:
913     case BuiltinType::Short:
914     case BuiltinType::UShort:
915       return true;
916     default:
917       return false;
918     }
919 
920   // Enumerated types are promotable to their compatible integer types
921   // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
922   if (const EnumType *ET = getAs<EnumType>()){
923     if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
924         || ET->getDecl()->isScoped())
925       return false;
926 
927     const BuiltinType *BT
928       = ET->getDecl()->getPromotionType()->getAs<BuiltinType>();
929     return BT->getKind() == BuiltinType::Int
930            || BT->getKind() == BuiltinType::UInt;
931   }
932 
933   return false;
934 }
935 
936 bool Type::isNullPtrType() const {
937   if (const BuiltinType *BT = getAs<BuiltinType>())
938     return BT->getKind() == BuiltinType::NullPtr;
939   return false;
940 }
941 
942 bool Type::isSpecifierType() const {
943   // Note that this intentionally does not use the canonical type.
944   switch (getTypeClass()) {
945   case Builtin:
946   case Record:
947   case Enum:
948   case Typedef:
949   case Complex:
950   case TypeOfExpr:
951   case TypeOf:
952   case TemplateTypeParm:
953   case SubstTemplateTypeParm:
954   case TemplateSpecialization:
955   case Elaborated:
956   case DependentName:
957   case DependentTemplateSpecialization:
958   case ObjCInterface:
959   case ObjCObject:
960   case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
961     return true;
962   default:
963     return false;
964   }
965 }
966 
967 ElaboratedTypeKeyword
968 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
969   switch (TypeSpec) {
970   default: return ETK_None;
971   case TST_typename: return ETK_Typename;
972   case TST_class: return ETK_Class;
973   case TST_struct: return ETK_Struct;
974   case TST_union: return ETK_Union;
975   case TST_enum: return ETK_Enum;
976   }
977 }
978 
979 TagTypeKind
980 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
981   switch(TypeSpec) {
982   case TST_class: return TTK_Class;
983   case TST_struct: return TTK_Struct;
984   case TST_union: return TTK_Union;
985   case TST_enum: return TTK_Enum;
986   }
987 
988   llvm_unreachable("Type specifier is not a tag type kind.");
989   return TTK_Union;
990 }
991 
992 ElaboratedTypeKeyword
993 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
994   switch (Kind) {
995   case TTK_Class: return ETK_Class;
996   case TTK_Struct: return ETK_Struct;
997   case TTK_Union: return ETK_Union;
998   case TTK_Enum: return ETK_Enum;
999   }
1000   llvm_unreachable("Unknown tag type kind.");
1001 }
1002 
1003 TagTypeKind
1004 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
1005   switch (Keyword) {
1006   case ETK_Class: return TTK_Class;
1007   case ETK_Struct: return TTK_Struct;
1008   case ETK_Union: return TTK_Union;
1009   case ETK_Enum: return TTK_Enum;
1010   case ETK_None: // Fall through.
1011   case ETK_Typename:
1012     llvm_unreachable("Elaborated type keyword is not a tag type kind.");
1013   }
1014   llvm_unreachable("Unknown elaborated type keyword.");
1015 }
1016 
1017 bool
1018 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
1019   switch (Keyword) {
1020   case ETK_None:
1021   case ETK_Typename:
1022     return false;
1023   case ETK_Class:
1024   case ETK_Struct:
1025   case ETK_Union:
1026   case ETK_Enum:
1027     return true;
1028   }
1029   llvm_unreachable("Unknown elaborated type keyword.");
1030 }
1031 
1032 const char*
1033 TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
1034   switch (Keyword) {
1035   case ETK_None: return "";
1036   case ETK_Typename: return "typename";
1037   case ETK_Class:  return "class";
1038   case ETK_Struct: return "struct";
1039   case ETK_Union:  return "union";
1040   case ETK_Enum:   return "enum";
1041   }
1042 
1043   llvm_unreachable("Unknown elaborated type keyword.");
1044   return "";
1045 }
1046 
1047 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
1048                          ElaboratedTypeKeyword Keyword,
1049                          NestedNameSpecifier *NNS, const IdentifierInfo *Name,
1050                          unsigned NumArgs, const TemplateArgument *Args,
1051                          QualType Canon)
1052   : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true,
1053                     /*VariablyModified=*/false,
1054                     NNS && NNS->containsUnexpandedParameterPack()),
1055     NNS(NNS), Name(Name), NumArgs(NumArgs) {
1056   assert((!NNS || NNS->isDependent()) &&
1057          "DependentTemplateSpecializatonType requires dependent qualifier");
1058   for (unsigned I = 0; I != NumArgs; ++I) {
1059     if (Args[I].containsUnexpandedParameterPack())
1060       setContainsUnexpandedParameterPack();
1061 
1062     new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
1063   }
1064 }
1065 
1066 void
1067 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1068                                              const ASTContext &Context,
1069                                              ElaboratedTypeKeyword Keyword,
1070                                              NestedNameSpecifier *Qualifier,
1071                                              const IdentifierInfo *Name,
1072                                              unsigned NumArgs,
1073                                              const TemplateArgument *Args) {
1074   ID.AddInteger(Keyword);
1075   ID.AddPointer(Qualifier);
1076   ID.AddPointer(Name);
1077   for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1078     Args[Idx].Profile(ID, Context);
1079 }
1080 
1081 bool Type::isElaboratedTypeSpecifier() const {
1082   ElaboratedTypeKeyword Keyword;
1083   if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
1084     Keyword = Elab->getKeyword();
1085   else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
1086     Keyword = DepName->getKeyword();
1087   else if (const DependentTemplateSpecializationType *DepTST =
1088              dyn_cast<DependentTemplateSpecializationType>(this))
1089     Keyword = DepTST->getKeyword();
1090   else
1091     return false;
1092 
1093   return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
1094 }
1095 
1096 const char *Type::getTypeClassName() const {
1097   switch (TypeBits.TC) {
1098 #define ABSTRACT_TYPE(Derived, Base)
1099 #define TYPE(Derived, Base) case Derived: return #Derived;
1100 #include "clang/AST/TypeNodes.def"
1101   }
1102 
1103   llvm_unreachable("Invalid type class.");
1104   return 0;
1105 }
1106 
1107 const char *BuiltinType::getName(const LangOptions &LO) const {
1108   switch (getKind()) {
1109   case Void:              return "void";
1110   case Bool:              return LO.Bool ? "bool" : "_Bool";
1111   case Char_S:            return "char";
1112   case Char_U:            return "char";
1113   case SChar:             return "signed char";
1114   case Short:             return "short";
1115   case Int:               return "int";
1116   case Long:              return "long";
1117   case LongLong:          return "long long";
1118   case Int128:            return "__int128_t";
1119   case UChar:             return "unsigned char";
1120   case UShort:            return "unsigned short";
1121   case UInt:              return "unsigned int";
1122   case ULong:             return "unsigned long";
1123   case ULongLong:         return "unsigned long long";
1124   case UInt128:           return "__uint128_t";
1125   case Float:             return "float";
1126   case Double:            return "double";
1127   case LongDouble:        return "long double";
1128   case WChar_S:
1129   case WChar_U:           return "wchar_t";
1130   case Char16:            return "char16_t";
1131   case Char32:            return "char32_t";
1132   case NullPtr:           return "nullptr_t";
1133   case Overload:          return "<overloaded function type>";
1134   case Dependent:         return "<dependent type>";
1135   case UnknownAny:        return "<unknown type>";
1136   case ObjCId:            return "id";
1137   case ObjCClass:         return "Class";
1138   case ObjCSel:           return "SEL";
1139   }
1140 
1141   llvm_unreachable("Invalid builtin type.");
1142   return 0;
1143 }
1144 
1145 QualType QualType::getNonLValueExprType(ASTContext &Context) const {
1146   if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
1147     return RefType->getPointeeType();
1148 
1149   // C++0x [basic.lval]:
1150   //   Class prvalues can have cv-qualified types; non-class prvalues always
1151   //   have cv-unqualified types.
1152   //
1153   // See also C99 6.3.2.1p2.
1154   if (!Context.getLangOptions().CPlusPlus ||
1155       (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
1156     return getUnqualifiedType();
1157 
1158   return *this;
1159 }
1160 
1161 llvm::StringRef FunctionType::getNameForCallConv(CallingConv CC) {
1162   switch (CC) {
1163   case CC_Default:
1164     llvm_unreachable("no name for default cc");
1165     return "";
1166 
1167   case CC_C: return "cdecl";
1168   case CC_X86StdCall: return "stdcall";
1169   case CC_X86FastCall: return "fastcall";
1170   case CC_X86ThisCall: return "thiscall";
1171   case CC_X86Pascal: return "pascal";
1172   case CC_AAPCS: return "aapcs";
1173   case CC_AAPCS_VFP: return "aapcs-vfp";
1174   }
1175 
1176   llvm_unreachable("Invalid calling convention.");
1177   return "";
1178 }
1179 
1180 FunctionProtoType::FunctionProtoType(QualType result, const QualType *args,
1181                                      unsigned numArgs, QualType canonical,
1182                                      const ExtProtoInfo &epi)
1183   : FunctionType(FunctionProto, result, epi.Variadic, epi.TypeQuals,
1184                  epi.RefQualifier, canonical,
1185                  result->isDependentType(),
1186                  result->isVariablyModifiedType(),
1187                  result->containsUnexpandedParameterPack(),
1188                  epi.ExtInfo),
1189     NumArgs(numArgs), NumExceptions(epi.NumExceptions),
1190     ExceptionSpecType(epi.ExceptionSpecType)
1191 {
1192   // Fill in the trailing argument array.
1193   QualType *argSlot = reinterpret_cast<QualType*>(this+1);
1194   for (unsigned i = 0; i != numArgs; ++i) {
1195     if (args[i]->isDependentType())
1196       setDependent();
1197 
1198     if (args[i]->containsUnexpandedParameterPack())
1199       setContainsUnexpandedParameterPack();
1200 
1201     argSlot[i] = args[i];
1202   }
1203 
1204   if (getExceptionSpecType() == EST_Dynamic) {
1205     // Fill in the exception array.
1206     QualType *exnSlot = argSlot + numArgs;
1207     for (unsigned i = 0, e = epi.NumExceptions; i != e; ++i) {
1208       if (epi.Exceptions[i]->isDependentType())
1209         setDependent();
1210 
1211       if (epi.Exceptions[i]->containsUnexpandedParameterPack())
1212         setContainsUnexpandedParameterPack();
1213 
1214       exnSlot[i] = epi.Exceptions[i];
1215     }
1216   } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
1217     // Store the noexcept expression and context.
1218     Expr **noexSlot = reinterpret_cast<Expr**>(argSlot + numArgs);
1219     *noexSlot = epi.NoexceptExpr;
1220   }
1221 }
1222 
1223 FunctionProtoType::NoexceptResult
1224 FunctionProtoType::getNoexceptSpec(ASTContext &ctx) const {
1225   ExceptionSpecificationType est = getExceptionSpecType();
1226   if (est == EST_BasicNoexcept)
1227     return NR_Nothrow;
1228 
1229   if (est != EST_ComputedNoexcept)
1230     return NR_NoNoexcept;
1231 
1232   Expr *noexceptExpr = getNoexceptExpr();
1233   if (!noexceptExpr)
1234     return NR_BadNoexcept;
1235   if (noexceptExpr->isValueDependent())
1236     return NR_Dependent;
1237 
1238   llvm::APSInt value;
1239   bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, 0,
1240                                                    /*evaluated*/false);
1241   (void)isICE;
1242   assert(isICE && "AST should not contain bad noexcept expressions.");
1243 
1244   return value.getBoolValue() ? NR_Nothrow : NR_Throw;
1245 }
1246 
1247 bool FunctionProtoType::isTemplateVariadic() const {
1248   for (unsigned ArgIdx = getNumArgs(); ArgIdx; --ArgIdx)
1249     if (isa<PackExpansionType>(getArgType(ArgIdx - 1)))
1250       return true;
1251 
1252   return false;
1253 }
1254 
1255 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1256                                 const QualType *ArgTys, unsigned NumArgs,
1257                                 const ExtProtoInfo &epi,
1258                                 const ASTContext &Context) {
1259   ID.AddPointer(Result.getAsOpaquePtr());
1260   for (unsigned i = 0; i != NumArgs; ++i)
1261     ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1262   ID.AddBoolean(epi.Variadic);
1263   ID.AddInteger(epi.TypeQuals);
1264   ID.AddInteger(epi.RefQualifier);
1265   ID.AddInteger(epi.ExceptionSpecType);
1266   if (epi.ExceptionSpecType == EST_Dynamic) {
1267     for (unsigned i = 0; i != epi.NumExceptions; ++i)
1268       ID.AddPointer(epi.Exceptions[i].getAsOpaquePtr());
1269   } else if (epi.ExceptionSpecType == EST_ComputedNoexcept && epi.NoexceptExpr){
1270     epi.NoexceptExpr->Profile(ID, Context, true);
1271   }
1272   epi.ExtInfo.Profile(ID);
1273 }
1274 
1275 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
1276                                 const ASTContext &Ctx) {
1277   Profile(ID, getResultType(), arg_type_begin(), NumArgs, getExtProtoInfo(),
1278           Ctx);
1279 }
1280 
1281 QualType TypedefType::desugar() const {
1282   return getDecl()->getUnderlyingType();
1283 }
1284 
1285 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1286   : Type(TypeOfExpr, can, E->isTypeDependent(),
1287          E->getType()->isVariablyModifiedType(),
1288          E->containsUnexpandedParameterPack()),
1289     TOExpr(E) {
1290 }
1291 
1292 QualType TypeOfExprType::desugar() const {
1293   return getUnderlyingExpr()->getType();
1294 }
1295 
1296 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1297                                       const ASTContext &Context, Expr *E) {
1298   E->Profile(ID, Context, true);
1299 }
1300 
1301 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1302   : Type(Decltype, can, E->isTypeDependent(),
1303          E->getType()->isVariablyModifiedType(),
1304          E->containsUnexpandedParameterPack()),
1305     E(E),
1306   UnderlyingType(underlyingType) {
1307 }
1308 
1309 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
1310   : DecltypeType(E, Context.DependentTy), Context(Context) { }
1311 
1312 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1313                                     const ASTContext &Context, Expr *E) {
1314   E->Profile(ID, Context, true);
1315 }
1316 
1317 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1318   : Type(TC, can, D->isDependentType(), /*VariablyModified=*/false,
1319          /*ContainsUnexpandedParameterPack=*/false),
1320     decl(const_cast<TagDecl*>(D)) {}
1321 
1322 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1323   for (TagDecl::redecl_iterator I = decl->redecls_begin(),
1324                                 E = decl->redecls_end();
1325        I != E; ++I) {
1326     if (I->isDefinition() || I->isBeingDefined())
1327       return *I;
1328   }
1329   // If there's no definition (not even in progress), return what we have.
1330   return decl;
1331 }
1332 
1333 TagDecl *TagType::getDecl() const {
1334   return getInterestingTagDecl(decl);
1335 }
1336 
1337 bool TagType::isBeingDefined() const {
1338   return getDecl()->isBeingDefined();
1339 }
1340 
1341 CXXRecordDecl *InjectedClassNameType::getDecl() const {
1342   return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1343 }
1344 
1345 bool RecordType::classof(const TagType *TT) {
1346   return isa<RecordDecl>(TT->getDecl());
1347 }
1348 
1349 bool EnumType::classof(const TagType *TT) {
1350   return isa<EnumDecl>(TT->getDecl());
1351 }
1352 
1353 SubstTemplateTypeParmPackType::
1354 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
1355                               QualType Canon,
1356                               const TemplateArgument &ArgPack)
1357   : Type(SubstTemplateTypeParmPack, Canon, true, false, true), Replaced(Param),
1358     Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size())
1359 {
1360 }
1361 
1362 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
1363   return TemplateArgument(Arguments, NumArguments);
1364 }
1365 
1366 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
1367   Profile(ID, getReplacedParameter(), getArgumentPack());
1368 }
1369 
1370 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
1371                                            const TemplateTypeParmType *Replaced,
1372                                             const TemplateArgument &ArgPack) {
1373   ID.AddPointer(Replaced);
1374   ID.AddInteger(ArgPack.pack_size());
1375   for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
1376                                     PEnd = ArgPack.pack_end();
1377        P != PEnd; ++P)
1378     ID.AddPointer(P->getAsType().getAsOpaquePtr());
1379 }
1380 
1381 bool TemplateSpecializationType::
1382 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args) {
1383   return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size());
1384 }
1385 
1386 bool TemplateSpecializationType::
1387 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N) {
1388   for (unsigned i = 0; i != N; ++i)
1389     if (Args[i].getArgument().isDependent())
1390       return true;
1391   return false;
1392 }
1393 
1394 bool TemplateSpecializationType::
1395 anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N) {
1396   for (unsigned i = 0; i != N; ++i)
1397     if (Args[i].isDependent())
1398       return true;
1399   return false;
1400 }
1401 
1402 TemplateSpecializationType::
1403 TemplateSpecializationType(TemplateName T,
1404                            const TemplateArgument *Args,
1405                            unsigned NumArgs, QualType Canon)
1406   : Type(TemplateSpecialization,
1407          Canon.isNull()? QualType(this, 0) : Canon,
1408          T.isDependent(), false, T.containsUnexpandedParameterPack()),
1409     Template(T), NumArgs(NumArgs)
1410 {
1411   assert(!T.getAsDependentTemplateName() &&
1412          "Use DependentTemplateSpecializationType for dependent template-name");
1413   assert((!Canon.isNull() ||
1414           T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)) &&
1415          "No canonical type for non-dependent class template specialization");
1416 
1417   TemplateArgument *TemplateArgs
1418     = reinterpret_cast<TemplateArgument *>(this + 1);
1419   for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1420     // Update dependent and variably-modified bits.
1421     if (Args[Arg].isDependent())
1422       setDependent();
1423     if (Args[Arg].getKind() == TemplateArgument::Type &&
1424         Args[Arg].getAsType()->isVariablyModifiedType())
1425       setVariablyModified();
1426     if (Args[Arg].containsUnexpandedParameterPack())
1427       setContainsUnexpandedParameterPack();
1428 
1429     new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
1430   }
1431 }
1432 
1433 void
1434 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1435                                     TemplateName T,
1436                                     const TemplateArgument *Args,
1437                                     unsigned NumArgs,
1438                                     const ASTContext &Context) {
1439   T.Profile(ID);
1440   for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1441     Args[Idx].Profile(ID, Context);
1442 }
1443 
1444 QualType
1445 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
1446   if (!hasNonFastQualifiers())
1447     return QT.withFastQualifiers(getFastQualifiers());
1448 
1449   return Context.getQualifiedType(QT, *this);
1450 }
1451 
1452 QualType
1453 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
1454   if (!hasNonFastQualifiers())
1455     return QualType(T, getFastQualifiers());
1456 
1457   return Context.getQualifiedType(T, *this);
1458 }
1459 
1460 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
1461                                  QualType BaseType,
1462                                  ObjCProtocolDecl * const *Protocols,
1463                                  unsigned NumProtocols) {
1464   ID.AddPointer(BaseType.getAsOpaquePtr());
1465   for (unsigned i = 0; i != NumProtocols; i++)
1466     ID.AddPointer(Protocols[i]);
1467 }
1468 
1469 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
1470   Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
1471 }
1472 
1473 namespace {
1474 
1475 /// \brief The cached properties of a type.
1476 class CachedProperties {
1477   char linkage;
1478   char visibility;
1479   bool local;
1480 
1481 public:
1482   CachedProperties(Linkage linkage, Visibility visibility, bool local)
1483     : linkage(linkage), visibility(visibility), local(local) {}
1484 
1485   Linkage getLinkage() const { return (Linkage) linkage; }
1486   Visibility getVisibility() const { return (Visibility) visibility; }
1487   bool hasLocalOrUnnamedType() const { return local; }
1488 
1489   friend CachedProperties merge(CachedProperties L, CachedProperties R) {
1490     return CachedProperties(minLinkage(L.getLinkage(), R.getLinkage()),
1491                             minVisibility(L.getVisibility(), R.getVisibility()),
1492                          L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
1493   }
1494 };
1495 }
1496 
1497 static CachedProperties computeCachedProperties(const Type *T);
1498 
1499 namespace clang {
1500 /// The type-property cache.  This is templated so as to be
1501 /// instantiated at an internal type to prevent unnecessary symbol
1502 /// leakage.
1503 template <class Private> class TypePropertyCache {
1504 public:
1505   static CachedProperties get(QualType T) {
1506     return get(T.getTypePtr());
1507   }
1508 
1509   static CachedProperties get(const Type *T) {
1510     ensure(T);
1511     return CachedProperties(T->TypeBits.getLinkage(),
1512                             T->TypeBits.getVisibility(),
1513                             T->TypeBits.hasLocalOrUnnamedType());
1514   }
1515 
1516   static void ensure(const Type *T) {
1517     // If the cache is valid, we're okay.
1518     if (T->TypeBits.isCacheValid()) return;
1519 
1520     // If this type is non-canonical, ask its canonical type for the
1521     // relevant information.
1522     if (!T->isCanonicalUnqualified()) {
1523       const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
1524       ensure(CT);
1525       T->TypeBits.CacheValidAndVisibility =
1526         CT->TypeBits.CacheValidAndVisibility;
1527       T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
1528       T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
1529       return;
1530     }
1531 
1532     // Compute the cached properties and then set the cache.
1533     CachedProperties Result = computeCachedProperties(T);
1534     T->TypeBits.CacheValidAndVisibility = Result.getVisibility() + 1U;
1535     assert(T->TypeBits.isCacheValid() &&
1536            T->TypeBits.getVisibility() == Result.getVisibility());
1537     T->TypeBits.CachedLinkage = Result.getLinkage();
1538     T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
1539   }
1540 };
1541 }
1542 
1543 // Instantiate the friend template at a private class.  In a
1544 // reasonable implementation, these symbols will be internal.
1545 // It is terrible that this is the best way to accomplish this.
1546 namespace { class Private {}; }
1547 typedef TypePropertyCache<Private> Cache;
1548 
1549 static CachedProperties computeCachedProperties(const Type *T) {
1550   switch (T->getTypeClass()) {
1551 #define TYPE(Class,Base)
1552 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
1553 #include "clang/AST/TypeNodes.def"
1554     llvm_unreachable("didn't expect a non-canonical type here");
1555 
1556 #define TYPE(Class,Base)
1557 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
1558 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
1559 #include "clang/AST/TypeNodes.def"
1560     // Treat dependent types as external.
1561     assert(T->isDependentType());
1562     return CachedProperties(ExternalLinkage, DefaultVisibility, false);
1563 
1564   case Type::Builtin:
1565     // C++ [basic.link]p8:
1566     //   A type is said to have linkage if and only if:
1567     //     - it is a fundamental type (3.9.1); or
1568     return CachedProperties(ExternalLinkage, DefaultVisibility, false);
1569 
1570   case Type::Record:
1571   case Type::Enum: {
1572     const TagDecl *Tag = cast<TagType>(T)->getDecl();
1573 
1574     // C++ [basic.link]p8:
1575     //     - it is a class or enumeration type that is named (or has a name
1576     //       for linkage purposes (7.1.3)) and the name has linkage; or
1577     //     -  it is a specialization of a class template (14); or
1578     NamedDecl::LinkageInfo LV = Tag->getLinkageAndVisibility();
1579     bool IsLocalOrUnnamed =
1580       Tag->getDeclContext()->isFunctionOrMethod() ||
1581       (!Tag->getIdentifier() && !Tag->getTypedefForAnonDecl());
1582     return CachedProperties(LV.linkage(), LV.visibility(), IsLocalOrUnnamed);
1583   }
1584 
1585     // C++ [basic.link]p8:
1586     //   - it is a compound type (3.9.2) other than a class or enumeration,
1587     //     compounded exclusively from types that have linkage; or
1588   case Type::Complex:
1589     return Cache::get(cast<ComplexType>(T)->getElementType());
1590   case Type::Pointer:
1591     return Cache::get(cast<PointerType>(T)->getPointeeType());
1592   case Type::BlockPointer:
1593     return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
1594   case Type::LValueReference:
1595   case Type::RValueReference:
1596     return Cache::get(cast<ReferenceType>(T)->getPointeeType());
1597   case Type::MemberPointer: {
1598     const MemberPointerType *MPT = cast<MemberPointerType>(T);
1599     return merge(Cache::get(MPT->getClass()),
1600                  Cache::get(MPT->getPointeeType()));
1601   }
1602   case Type::ConstantArray:
1603   case Type::IncompleteArray:
1604   case Type::VariableArray:
1605     return Cache::get(cast<ArrayType>(T)->getElementType());
1606   case Type::Vector:
1607   case Type::ExtVector:
1608     return Cache::get(cast<VectorType>(T)->getElementType());
1609   case Type::FunctionNoProto:
1610     return Cache::get(cast<FunctionType>(T)->getResultType());
1611   case Type::FunctionProto: {
1612     const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1613     CachedProperties result = Cache::get(FPT->getResultType());
1614     for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(),
1615            ae = FPT->arg_type_end(); ai != ae; ++ai)
1616       result = merge(result, Cache::get(*ai));
1617     return result;
1618   }
1619   case Type::ObjCInterface: {
1620     NamedDecl::LinkageInfo LV =
1621       cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
1622     return CachedProperties(LV.linkage(), LV.visibility(), false);
1623   }
1624   case Type::ObjCObject:
1625     return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
1626   case Type::ObjCObjectPointer:
1627     return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
1628   }
1629 
1630   llvm_unreachable("unhandled type class");
1631 
1632   // C++ [basic.link]p8:
1633   //   Names not covered by these rules have no linkage.
1634   return CachedProperties(NoLinkage, DefaultVisibility, false);
1635 }
1636 
1637 /// \brief Determine the linkage of this type.
1638 Linkage Type::getLinkage() const {
1639   Cache::ensure(this);
1640   return TypeBits.getLinkage();
1641 }
1642 
1643 /// \brief Determine the linkage of this type.
1644 Visibility Type::getVisibility() const {
1645   Cache::ensure(this);
1646   return TypeBits.getVisibility();
1647 }
1648 
1649 bool Type::hasUnnamedOrLocalType() const {
1650   Cache::ensure(this);
1651   return TypeBits.hasLocalOrUnnamedType();
1652 }
1653 
1654 std::pair<Linkage,Visibility> Type::getLinkageAndVisibility() const {
1655   Cache::ensure(this);
1656   return std::make_pair(TypeBits.getLinkage(), TypeBits.getVisibility());
1657 }
1658 
1659 void Type::ClearLinkageCache() {
1660   TypeBits.CacheValidAndVisibility = 0;
1661   if (QualType(this, 0) != CanonicalType)
1662     CanonicalType->TypeBits.CacheValidAndVisibility = 0;
1663 }
1664 
1665 bool Type::hasSizedVLAType() const {
1666   if (!isVariablyModifiedType()) return false;
1667 
1668   if (const PointerType *ptr = getAs<PointerType>())
1669     return ptr->getPointeeType()->hasSizedVLAType();
1670   if (const ReferenceType *ref = getAs<ReferenceType>())
1671     return ref->getPointeeType()->hasSizedVLAType();
1672   if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
1673     if (isa<VariableArrayType>(arr) &&
1674         cast<VariableArrayType>(arr)->getSizeExpr())
1675       return true;
1676 
1677     return arr->getElementType()->hasSizedVLAType();
1678   }
1679 
1680   return false;
1681 }
1682 
1683 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
1684   /// Currently, the only destruction kind we recognize is C++ objects
1685   /// with non-trivial destructors.
1686   const CXXRecordDecl *record =
1687     type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1688   if (record && !record->hasTrivialDestructor())
1689     return DK_cxx_destructor;
1690 
1691   return DK_none;
1692 }
1693