Type.cpp 75 KB

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