Type.cpp 125 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789
  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/Attr.h"
  15. #include "clang/AST/CharUnits.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/Type.h"
  22. #include "clang/AST/TypeVisitor.h"
  23. #include "clang/Basic/Specifiers.h"
  24. #include "clang/Basic/TargetInfo.h"
  25. #include "llvm/ADT/APSInt.h"
  26. #include "llvm/ADT/StringExtras.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include <algorithm>
  29. using namespace clang;
  30. bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const {
  31. return (*this != Other) &&
  32. // CVR qualifiers superset
  33. (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) &&
  34. // ObjC GC qualifiers superset
  35. ((getObjCGCAttr() == Other.getObjCGCAttr()) ||
  36. (hasObjCGCAttr() && !Other.hasObjCGCAttr())) &&
  37. // Address space superset.
  38. ((getAddressSpace() == Other.getAddressSpace()) ||
  39. (hasAddressSpace()&& !Other.hasAddressSpace())) &&
  40. // Lifetime qualifier superset.
  41. ((getObjCLifetime() == Other.getObjCLifetime()) ||
  42. (hasObjCLifetime() && !Other.hasObjCLifetime()));
  43. }
  44. const IdentifierInfo* QualType::getBaseTypeIdentifier() const {
  45. const Type* ty = getTypePtr();
  46. NamedDecl *ND = nullptr;
  47. if (ty->isPointerType() || ty->isReferenceType())
  48. return ty->getPointeeType().getBaseTypeIdentifier();
  49. else if (ty->isRecordType())
  50. ND = ty->getAs<RecordType>()->getDecl();
  51. else if (ty->isEnumeralType())
  52. ND = ty->getAs<EnumType>()->getDecl();
  53. else if (ty->getTypeClass() == Type::Typedef)
  54. ND = ty->getAs<TypedefType>()->getDecl();
  55. else if (ty->isArrayType())
  56. return ty->castAsArrayTypeUnsafe()->
  57. getElementType().getBaseTypeIdentifier();
  58. if (ND)
  59. return ND->getIdentifier();
  60. return nullptr;
  61. }
  62. bool QualType::isConstant(QualType T, ASTContext &Ctx) {
  63. if (T.isConstQualified())
  64. return true;
  65. if (const ArrayType *AT = Ctx.getAsArrayType(T))
  66. return AT->getElementType().isConstant(Ctx);
  67. return T.getAddressSpace() == LangAS::opencl_constant;
  68. }
  69. unsigned ConstantArrayType::getNumAddressingBits(ASTContext &Context,
  70. QualType ElementType,
  71. const llvm::APInt &NumElements) {
  72. uint64_t ElementSize = Context.getTypeSizeInChars(ElementType).getQuantity();
  73. // Fast path the common cases so we can avoid the conservative computation
  74. // below, which in common cases allocates "large" APSInt values, which are
  75. // slow.
  76. // If the element size is a power of 2, we can directly compute the additional
  77. // number of addressing bits beyond those required for the element count.
  78. if (llvm::isPowerOf2_64(ElementSize)) {
  79. return NumElements.getActiveBits() + llvm::Log2_64(ElementSize);
  80. }
  81. // If both the element count and element size fit in 32-bits, we can do the
  82. // computation directly in 64-bits.
  83. if ((ElementSize >> 32) == 0 && NumElements.getBitWidth() <= 64 &&
  84. (NumElements.getZExtValue() >> 32) == 0) {
  85. uint64_t TotalSize = NumElements.getZExtValue() * ElementSize;
  86. return 64 - llvm::countLeadingZeros(TotalSize);
  87. }
  88. // Otherwise, use APSInt to handle arbitrary sized values.
  89. llvm::APSInt SizeExtended(NumElements, true);
  90. unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
  91. SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
  92. SizeExtended.getBitWidth()) * 2);
  93. llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
  94. TotalSize *= SizeExtended;
  95. return TotalSize.getActiveBits();
  96. }
  97. unsigned ConstantArrayType::getMaxSizeBits(ASTContext &Context) {
  98. unsigned Bits = Context.getTypeSize(Context.getSizeType());
  99. // Limit the number of bits in size_t so that maximal bit size fits 64 bit
  100. // integer (see PR8256). We can do this as currently there is no hardware
  101. // that supports full 64-bit virtual space.
  102. if (Bits > 61)
  103. Bits = 61;
  104. return Bits;
  105. }
  106. DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context,
  107. QualType et, QualType can,
  108. Expr *e, ArraySizeModifier sm,
  109. unsigned tq,
  110. SourceRange brackets)
  111. : ArrayType(DependentSizedArray, et, can, sm, tq,
  112. (et->containsUnexpandedParameterPack() ||
  113. (e && e->containsUnexpandedParameterPack()))),
  114. Context(Context), SizeExpr((Stmt*) e), Brackets(brackets)
  115. {
  116. }
  117. void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
  118. const ASTContext &Context,
  119. QualType ET,
  120. ArraySizeModifier SizeMod,
  121. unsigned TypeQuals,
  122. Expr *E) {
  123. ID.AddPointer(ET.getAsOpaquePtr());
  124. ID.AddInteger(SizeMod);
  125. ID.AddInteger(TypeQuals);
  126. E->Profile(ID, Context, true);
  127. }
  128. DependentSizedExtVectorType::DependentSizedExtVectorType(const
  129. ASTContext &Context,
  130. QualType ElementType,
  131. QualType can,
  132. Expr *SizeExpr,
  133. SourceLocation loc)
  134. : Type(DependentSizedExtVector, can, /*Dependent=*/true,
  135. /*InstantiationDependent=*/true,
  136. ElementType->isVariablyModifiedType(),
  137. (ElementType->containsUnexpandedParameterPack() ||
  138. (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))),
  139. Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
  140. loc(loc)
  141. {
  142. }
  143. void
  144. DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
  145. const ASTContext &Context,
  146. QualType ElementType, Expr *SizeExpr) {
  147. ID.AddPointer(ElementType.getAsOpaquePtr());
  148. SizeExpr->Profile(ID, Context, true);
  149. }
  150. VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
  151. VectorKind vecKind)
  152. : VectorType(Vector, vecType, nElements, canonType, vecKind) {}
  153. VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
  154. QualType canonType, VectorKind vecKind)
  155. : Type(tc, canonType, vecType->isDependentType(),
  156. vecType->isInstantiationDependentType(),
  157. vecType->isVariablyModifiedType(),
  158. vecType->containsUnexpandedParameterPack()),
  159. ElementType(vecType)
  160. {
  161. VectorTypeBits.VecKind = vecKind;
  162. VectorTypeBits.NumElements = nElements;
  163. }
  164. /// getArrayElementTypeNoTypeQual - If this is an array type, return the
  165. /// element type of the array, potentially with type qualifiers missing.
  166. /// This method should never be used when type qualifiers are meaningful.
  167. const Type *Type::getArrayElementTypeNoTypeQual() const {
  168. // If this is directly an array type, return it.
  169. if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
  170. return ATy->getElementType().getTypePtr();
  171. // If the canonical form of this type isn't the right kind, reject it.
  172. if (!isa<ArrayType>(CanonicalType))
  173. return nullptr;
  174. // If this is a typedef for an array type, strip the typedef off without
  175. // losing all typedef information.
  176. return cast<ArrayType>(getUnqualifiedDesugaredType())
  177. ->getElementType().getTypePtr();
  178. }
  179. /// getDesugaredType - Return the specified type with any "sugar" removed from
  180. /// the type. This takes off typedefs, typeof's etc. If the outer level of
  181. /// the type is already concrete, it returns it unmodified. This is similar
  182. /// to getting the canonical type, but it doesn't remove *all* typedefs. For
  183. /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
  184. /// concrete.
  185. QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
  186. SplitQualType split = getSplitDesugaredType(T);
  187. return Context.getQualifiedType(split.Ty, split.Quals);
  188. }
  189. QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
  190. const ASTContext &Context) {
  191. SplitQualType split = type.split();
  192. QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
  193. return Context.getQualifiedType(desugar, split.Quals);
  194. }
  195. QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
  196. switch (getTypeClass()) {
  197. #define ABSTRACT_TYPE(Class, Parent)
  198. #define TYPE(Class, Parent) \
  199. case Type::Class: { \
  200. const Class##Type *ty = cast<Class##Type>(this); \
  201. if (!ty->isSugared()) return QualType(ty, 0); \
  202. return ty->desugar(); \
  203. }
  204. #include "clang/AST/TypeNodes.def"
  205. }
  206. llvm_unreachable("bad type kind!");
  207. }
  208. SplitQualType QualType::getSplitDesugaredType(QualType T) {
  209. QualifierCollector Qs;
  210. QualType Cur = T;
  211. while (true) {
  212. const Type *CurTy = Qs.strip(Cur);
  213. switch (CurTy->getTypeClass()) {
  214. #define ABSTRACT_TYPE(Class, Parent)
  215. #define TYPE(Class, Parent) \
  216. case Type::Class: { \
  217. const Class##Type *Ty = cast<Class##Type>(CurTy); \
  218. if (!Ty->isSugared()) \
  219. return SplitQualType(Ty, Qs); \
  220. Cur = Ty->desugar(); \
  221. break; \
  222. }
  223. #include "clang/AST/TypeNodes.def"
  224. }
  225. }
  226. }
  227. SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
  228. SplitQualType split = type.split();
  229. // All the qualifiers we've seen so far.
  230. Qualifiers quals = split.Quals;
  231. // The last type node we saw with any nodes inside it.
  232. const Type *lastTypeWithQuals = split.Ty;
  233. while (true) {
  234. QualType next;
  235. // Do a single-step desugar, aborting the loop if the type isn't
  236. // sugared.
  237. switch (split.Ty->getTypeClass()) {
  238. #define ABSTRACT_TYPE(Class, Parent)
  239. #define TYPE(Class, Parent) \
  240. case Type::Class: { \
  241. const Class##Type *ty = cast<Class##Type>(split.Ty); \
  242. if (!ty->isSugared()) goto done; \
  243. next = ty->desugar(); \
  244. break; \
  245. }
  246. #include "clang/AST/TypeNodes.def"
  247. }
  248. // Otherwise, split the underlying type. If that yields qualifiers,
  249. // update the information.
  250. split = next.split();
  251. if (!split.Quals.empty()) {
  252. lastTypeWithQuals = split.Ty;
  253. quals.addConsistentQualifiers(split.Quals);
  254. }
  255. }
  256. done:
  257. return SplitQualType(lastTypeWithQuals, quals);
  258. }
  259. QualType QualType::IgnoreParens(QualType T) {
  260. // FIXME: this seems inherently un-qualifiers-safe.
  261. while (const ParenType *PT = T->getAs<ParenType>())
  262. T = PT->getInnerType();
  263. return T;
  264. }
  265. /// \brief This will check for a T (which should be a Type which can act as
  266. /// sugar, such as a TypedefType) by removing any existing sugar until it
  267. /// reaches a T or a non-sugared type.
  268. template<typename T> static const T *getAsSugar(const Type *Cur) {
  269. while (true) {
  270. if (const T *Sugar = dyn_cast<T>(Cur))
  271. return Sugar;
  272. switch (Cur->getTypeClass()) {
  273. #define ABSTRACT_TYPE(Class, Parent)
  274. #define TYPE(Class, Parent) \
  275. case Type::Class: { \
  276. const Class##Type *Ty = cast<Class##Type>(Cur); \
  277. if (!Ty->isSugared()) return 0; \
  278. Cur = Ty->desugar().getTypePtr(); \
  279. break; \
  280. }
  281. #include "clang/AST/TypeNodes.def"
  282. }
  283. }
  284. }
  285. template <> const TypedefType *Type::getAs() const {
  286. return getAsSugar<TypedefType>(this);
  287. }
  288. template <> const TemplateSpecializationType *Type::getAs() const {
  289. return getAsSugar<TemplateSpecializationType>(this);
  290. }
  291. template <> const AttributedType *Type::getAs() const {
  292. return getAsSugar<AttributedType>(this);
  293. }
  294. /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
  295. /// sugar off the given type. This should produce an object of the
  296. /// same dynamic type as the canonical type.
  297. const Type *Type::getUnqualifiedDesugaredType() const {
  298. const Type *Cur = this;
  299. while (true) {
  300. switch (Cur->getTypeClass()) {
  301. #define ABSTRACT_TYPE(Class, Parent)
  302. #define TYPE(Class, Parent) \
  303. case Class: { \
  304. const Class##Type *Ty = cast<Class##Type>(Cur); \
  305. if (!Ty->isSugared()) return Cur; \
  306. Cur = Ty->desugar().getTypePtr(); \
  307. break; \
  308. }
  309. #include "clang/AST/TypeNodes.def"
  310. }
  311. }
  312. }
  313. bool Type::isClassType() const {
  314. if (const RecordType *RT = getAs<RecordType>())
  315. return RT->getDecl()->isClass();
  316. return false;
  317. }
  318. bool Type::isStructureType() const {
  319. if (const RecordType *RT = getAs<RecordType>())
  320. return RT->getDecl()->isStruct();
  321. return false;
  322. }
  323. bool Type::isObjCBoxableRecordType() const {
  324. if (const RecordType *RT = getAs<RecordType>())
  325. return RT->getDecl()->hasAttr<ObjCBoxableAttr>();
  326. return false;
  327. }
  328. bool Type::isInterfaceType() const {
  329. if (const RecordType *RT = getAs<RecordType>())
  330. return RT->getDecl()->isInterface();
  331. return false;
  332. }
  333. bool Type::isStructureOrClassType() const {
  334. if (const RecordType *RT = getAs<RecordType>()) {
  335. RecordDecl *RD = RT->getDecl();
  336. return RD->isStruct() || RD->isClass() || RD->isInterface();
  337. }
  338. return false;
  339. }
  340. bool Type::isVoidPointerType() const {
  341. if (const PointerType *PT = getAs<PointerType>())
  342. return PT->getPointeeType()->isVoidType();
  343. return false;
  344. }
  345. bool Type::isUnionType() const {
  346. if (const RecordType *RT = getAs<RecordType>())
  347. return RT->getDecl()->isUnion();
  348. return false;
  349. }
  350. bool Type::isComplexType() const {
  351. if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
  352. return CT->getElementType()->isFloatingType();
  353. return false;
  354. }
  355. bool Type::isComplexIntegerType() const {
  356. // Check for GCC complex integer extension.
  357. return getAsComplexIntegerType();
  358. }
  359. const ComplexType *Type::getAsComplexIntegerType() const {
  360. if (const ComplexType *Complex = getAs<ComplexType>())
  361. if (Complex->getElementType()->isIntegerType())
  362. return Complex;
  363. return nullptr;
  364. }
  365. QualType Type::getPointeeType() const {
  366. if (const PointerType *PT = getAs<PointerType>())
  367. return PT->getPointeeType();
  368. if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
  369. return OPT->getPointeeType();
  370. if (const BlockPointerType *BPT = getAs<BlockPointerType>())
  371. return BPT->getPointeeType();
  372. if (const ReferenceType *RT = getAs<ReferenceType>())
  373. return RT->getPointeeType();
  374. if (const MemberPointerType *MPT = getAs<MemberPointerType>())
  375. return MPT->getPointeeType();
  376. if (const DecayedType *DT = getAs<DecayedType>())
  377. return DT->getPointeeType();
  378. return QualType();
  379. }
  380. const RecordType *Type::getAsStructureType() const {
  381. // If this is directly a structure type, return it.
  382. if (const RecordType *RT = dyn_cast<RecordType>(this)) {
  383. if (RT->getDecl()->isStruct())
  384. return RT;
  385. }
  386. // If the canonical form of this type isn't the right kind, reject it.
  387. if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
  388. if (!RT->getDecl()->isStruct())
  389. return nullptr;
  390. // If this is a typedef for a structure type, strip the typedef off without
  391. // losing all typedef information.
  392. return cast<RecordType>(getUnqualifiedDesugaredType());
  393. }
  394. return nullptr;
  395. }
  396. const RecordType *Type::getAsUnionType() const {
  397. // If this is directly a union type, return it.
  398. if (const RecordType *RT = dyn_cast<RecordType>(this)) {
  399. if (RT->getDecl()->isUnion())
  400. return RT;
  401. }
  402. // If the canonical form of this type isn't the right kind, reject it.
  403. if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
  404. if (!RT->getDecl()->isUnion())
  405. return nullptr;
  406. // If this is a typedef for a union type, strip the typedef off without
  407. // losing all typedef information.
  408. return cast<RecordType>(getUnqualifiedDesugaredType());
  409. }
  410. return nullptr;
  411. }
  412. bool Type::isObjCIdOrObjectKindOfType(const ASTContext &ctx,
  413. const ObjCObjectType *&bound) const {
  414. bound = nullptr;
  415. const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>();
  416. if (!OPT)
  417. return false;
  418. // Easy case: id.
  419. if (OPT->isObjCIdType())
  420. return true;
  421. // If it's not a __kindof type, reject it now.
  422. if (!OPT->isKindOfType())
  423. return false;
  424. // If it's Class or qualified Class, it's not an object type.
  425. if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType())
  426. return false;
  427. // Figure out the type bound for the __kindof type.
  428. bound = OPT->getObjectType()->stripObjCKindOfTypeAndQuals(ctx)
  429. ->getAs<ObjCObjectType>();
  430. return true;
  431. }
  432. bool Type::isObjCClassOrClassKindOfType() const {
  433. const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>();
  434. if (!OPT)
  435. return false;
  436. // Easy case: Class.
  437. if (OPT->isObjCClassType())
  438. return true;
  439. // If it's not a __kindof type, reject it now.
  440. if (!OPT->isKindOfType())
  441. return false;
  442. // If it's Class or qualified Class, it's a class __kindof type.
  443. return OPT->isObjCClassType() || OPT->isObjCQualifiedClassType();
  444. }
  445. /// Was this type written with the special inert-in-MRC __unsafe_unretained
  446. /// qualifier?
  447. ///
  448. /// This approximates the answer to the following question: if this
  449. /// translation unit were compiled in ARC, would this type be qualified
  450. /// with __unsafe_unretained?
  451. bool Type::isObjCInertUnsafeUnretainedType() const {
  452. const Type *cur = this;
  453. while (true) {
  454. if (auto attributed = dyn_cast<AttributedType>(cur)) {
  455. if (attributed->getAttrKind() ==
  456. AttributedType::attr_objc_inert_unsafe_unretained)
  457. return true;
  458. }
  459. // Single-step desugar until we run out of sugar.
  460. QualType next = cur->getLocallyUnqualifiedSingleStepDesugaredType();
  461. if (next.getTypePtr() == cur) return false;
  462. cur = next.getTypePtr();
  463. }
  464. }
  465. ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
  466. ArrayRef<QualType> typeArgs,
  467. ArrayRef<ObjCProtocolDecl *> protocols,
  468. bool isKindOf)
  469. : Type(ObjCObject, Canonical, Base->isDependentType(),
  470. Base->isInstantiationDependentType(),
  471. Base->isVariablyModifiedType(),
  472. Base->containsUnexpandedParameterPack()),
  473. BaseType(Base)
  474. {
  475. ObjCObjectTypeBits.IsKindOf = isKindOf;
  476. ObjCObjectTypeBits.NumTypeArgs = typeArgs.size();
  477. assert(getTypeArgsAsWritten().size() == typeArgs.size() &&
  478. "bitfield overflow in type argument count");
  479. ObjCObjectTypeBits.NumProtocols = protocols.size();
  480. assert(getNumProtocols() == protocols.size() &&
  481. "bitfield overflow in protocol count");
  482. if (!typeArgs.empty())
  483. memcpy(getTypeArgStorage(), typeArgs.data(),
  484. typeArgs.size() * sizeof(QualType));
  485. if (!protocols.empty())
  486. memcpy(getProtocolStorage(), protocols.data(),
  487. protocols.size() * sizeof(ObjCProtocolDecl*));
  488. for (auto typeArg : typeArgs) {
  489. if (typeArg->isDependentType())
  490. setDependent();
  491. else if (typeArg->isInstantiationDependentType())
  492. setInstantiationDependent();
  493. if (typeArg->containsUnexpandedParameterPack())
  494. setContainsUnexpandedParameterPack();
  495. }
  496. }
  497. bool ObjCObjectType::isSpecialized() const {
  498. // If we have type arguments written here, the type is specialized.
  499. if (ObjCObjectTypeBits.NumTypeArgs > 0)
  500. return true;
  501. // Otherwise, check whether the base type is specialized.
  502. if (auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
  503. // Terminate when we reach an interface type.
  504. if (isa<ObjCInterfaceType>(objcObject))
  505. return false;
  506. return objcObject->isSpecialized();
  507. }
  508. // Not specialized.
  509. return false;
  510. }
  511. ArrayRef<QualType> ObjCObjectType::getTypeArgs() const {
  512. // We have type arguments written on this type.
  513. if (isSpecializedAsWritten())
  514. return getTypeArgsAsWritten();
  515. // Look at the base type, which might have type arguments.
  516. if (auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
  517. // Terminate when we reach an interface type.
  518. if (isa<ObjCInterfaceType>(objcObject))
  519. return { };
  520. return objcObject->getTypeArgs();
  521. }
  522. // No type arguments.
  523. return { };
  524. }
  525. bool ObjCObjectType::isKindOfType() const {
  526. if (isKindOfTypeAsWritten())
  527. return true;
  528. // Look at the base type, which might have type arguments.
  529. if (auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
  530. // Terminate when we reach an interface type.
  531. if (isa<ObjCInterfaceType>(objcObject))
  532. return false;
  533. return objcObject->isKindOfType();
  534. }
  535. // Not a "__kindof" type.
  536. return false;
  537. }
  538. QualType ObjCObjectType::stripObjCKindOfTypeAndQuals(
  539. const ASTContext &ctx) const {
  540. if (!isKindOfType() && qual_empty())
  541. return QualType(this, 0);
  542. // Recursively strip __kindof.
  543. SplitQualType splitBaseType = getBaseType().split();
  544. QualType baseType(splitBaseType.Ty, 0);
  545. if (const ObjCObjectType *baseObj
  546. = splitBaseType.Ty->getAs<ObjCObjectType>()) {
  547. baseType = baseObj->stripObjCKindOfTypeAndQuals(ctx);
  548. }
  549. return ctx.getObjCObjectType(ctx.getQualifiedType(baseType,
  550. splitBaseType.Quals),
  551. getTypeArgsAsWritten(),
  552. /*protocols=*/{ },
  553. /*isKindOf=*/false);
  554. }
  555. const ObjCObjectPointerType *ObjCObjectPointerType::stripObjCKindOfTypeAndQuals(
  556. const ASTContext &ctx) const {
  557. if (!isKindOfType() && qual_empty())
  558. return this;
  559. QualType obj = getObjectType()->stripObjCKindOfTypeAndQuals(ctx);
  560. return ctx.getObjCObjectPointerType(obj)->castAs<ObjCObjectPointerType>();
  561. }
  562. namespace {
  563. template<typename F>
  564. QualType simpleTransform(ASTContext &ctx, QualType type, F &&f);
  565. /// Visitor used by simpleTransform() to perform the transformation.
  566. template<typename F>
  567. struct SimpleTransformVisitor
  568. : public TypeVisitor<SimpleTransformVisitor<F>, QualType> {
  569. ASTContext &Ctx;
  570. F &&TheFunc;
  571. QualType recurse(QualType type) {
  572. return simpleTransform(Ctx, type, std::move(TheFunc));
  573. }
  574. public:
  575. SimpleTransformVisitor(ASTContext &ctx, F &&f) : Ctx(ctx), TheFunc(std::move(f)) { }
  576. // None of the clients of this transformation can occur where
  577. // there are dependent types, so skip dependent types.
  578. #define TYPE(Class, Base)
  579. #define DEPENDENT_TYPE(Class, Base) \
  580. QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
  581. #include "clang/AST/TypeNodes.def"
  582. #define TRIVIAL_TYPE_CLASS(Class) \
  583. QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
  584. TRIVIAL_TYPE_CLASS(Builtin)
  585. QualType VisitComplexType(const ComplexType *T) {
  586. QualType elementType = recurse(T->getElementType());
  587. if (elementType.isNull())
  588. return QualType();
  589. if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
  590. return QualType(T, 0);
  591. return Ctx.getComplexType(elementType);
  592. }
  593. QualType VisitPointerType(const PointerType *T) {
  594. QualType pointeeType = recurse(T->getPointeeType());
  595. if (pointeeType.isNull())
  596. return QualType();
  597. if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
  598. return QualType(T, 0);
  599. return Ctx.getPointerType(pointeeType);
  600. }
  601. QualType VisitBlockPointerType(const BlockPointerType *T) {
  602. QualType pointeeType = recurse(T->getPointeeType());
  603. if (pointeeType.isNull())
  604. return QualType();
  605. if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
  606. return QualType(T, 0);
  607. return Ctx.getBlockPointerType(pointeeType);
  608. }
  609. QualType VisitLValueReferenceType(const LValueReferenceType *T) {
  610. QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
  611. if (pointeeType.isNull())
  612. return QualType();
  613. if (pointeeType.getAsOpaquePtr()
  614. == T->getPointeeTypeAsWritten().getAsOpaquePtr())
  615. return QualType(T, 0);
  616. return Ctx.getLValueReferenceType(pointeeType, T->isSpelledAsLValue());
  617. }
  618. QualType VisitRValueReferenceType(const RValueReferenceType *T) {
  619. QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
  620. if (pointeeType.isNull())
  621. return QualType();
  622. if (pointeeType.getAsOpaquePtr()
  623. == T->getPointeeTypeAsWritten().getAsOpaquePtr())
  624. return QualType(T, 0);
  625. return Ctx.getRValueReferenceType(pointeeType);
  626. }
  627. QualType VisitMemberPointerType(const MemberPointerType *T) {
  628. QualType pointeeType = recurse(T->getPointeeType());
  629. if (pointeeType.isNull())
  630. return QualType();
  631. if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
  632. return QualType(T, 0);
  633. return Ctx.getMemberPointerType(pointeeType, T->getClass());
  634. }
  635. QualType VisitConstantArrayType(const ConstantArrayType *T) {
  636. QualType elementType = recurse(T->getElementType());
  637. if (elementType.isNull())
  638. return QualType();
  639. if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
  640. return QualType(T, 0);
  641. return Ctx.getConstantArrayType(elementType, T->getSize(),
  642. T->getSizeModifier(),
  643. T->getIndexTypeCVRQualifiers());
  644. }
  645. QualType VisitVariableArrayType(const VariableArrayType *T) {
  646. QualType elementType = recurse(T->getElementType());
  647. if (elementType.isNull())
  648. return QualType();
  649. if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
  650. return QualType(T, 0);
  651. return Ctx.getVariableArrayType(elementType, T->getSizeExpr(),
  652. T->getSizeModifier(),
  653. T->getIndexTypeCVRQualifiers(),
  654. T->getBracketsRange());
  655. }
  656. QualType VisitIncompleteArrayType(const IncompleteArrayType *T) {
  657. QualType elementType = recurse(T->getElementType());
  658. if (elementType.isNull())
  659. return QualType();
  660. if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
  661. return QualType(T, 0);
  662. return Ctx.getIncompleteArrayType(elementType, T->getSizeModifier(),
  663. T->getIndexTypeCVRQualifiers());
  664. }
  665. QualType VisitVectorType(const VectorType *T) {
  666. QualType elementType = recurse(T->getElementType());
  667. if (elementType.isNull())
  668. return QualType();
  669. if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
  670. return QualType(T, 0);
  671. return Ctx.getVectorType(elementType, T->getNumElements(),
  672. T->getVectorKind());
  673. }
  674. QualType VisitExtVectorType(const ExtVectorType *T) {
  675. QualType elementType = recurse(T->getElementType());
  676. if (elementType.isNull())
  677. return QualType();
  678. if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
  679. return QualType(T, 0);
  680. return Ctx.getExtVectorType(elementType, T->getNumElements());
  681. }
  682. QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
  683. QualType returnType = recurse(T->getReturnType());
  684. if (returnType.isNull())
  685. return QualType();
  686. if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr())
  687. return QualType(T, 0);
  688. return Ctx.getFunctionNoProtoType(returnType, T->getExtInfo());
  689. }
  690. QualType VisitFunctionProtoType(const FunctionProtoType *T) {
  691. QualType returnType = recurse(T->getReturnType());
  692. if (returnType.isNull())
  693. return QualType();
  694. // Transform parameter types.
  695. SmallVector<QualType, 4> paramTypes;
  696. bool paramChanged = false;
  697. for (auto paramType : T->getParamTypes()) {
  698. QualType newParamType = recurse(paramType);
  699. if (newParamType.isNull())
  700. return QualType();
  701. if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
  702. paramChanged = true;
  703. paramTypes.push_back(newParamType);
  704. }
  705. // Transform extended info.
  706. FunctionProtoType::ExtProtoInfo info = T->getExtProtoInfo();
  707. bool exceptionChanged = false;
  708. if (info.ExceptionSpec.Type == EST_Dynamic) {
  709. SmallVector<QualType, 4> exceptionTypes;
  710. for (auto exceptionType : info.ExceptionSpec.Exceptions) {
  711. QualType newExceptionType = recurse(exceptionType);
  712. if (newExceptionType.isNull())
  713. return QualType();
  714. if (newExceptionType.getAsOpaquePtr()
  715. != exceptionType.getAsOpaquePtr())
  716. exceptionChanged = true;
  717. exceptionTypes.push_back(newExceptionType);
  718. }
  719. if (exceptionChanged) {
  720. info.ExceptionSpec.Exceptions =
  721. llvm::makeArrayRef(exceptionTypes).copy(Ctx);
  722. }
  723. }
  724. if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr() &&
  725. !paramChanged && !exceptionChanged)
  726. return QualType(T, 0);
  727. return Ctx.getFunctionType(returnType, paramTypes, info);
  728. }
  729. QualType VisitParenType(const ParenType *T) {
  730. QualType innerType = recurse(T->getInnerType());
  731. if (innerType.isNull())
  732. return QualType();
  733. if (innerType.getAsOpaquePtr() == T->getInnerType().getAsOpaquePtr())
  734. return QualType(T, 0);
  735. return Ctx.getParenType(innerType);
  736. }
  737. TRIVIAL_TYPE_CLASS(Typedef)
  738. QualType VisitAdjustedType(const AdjustedType *T) {
  739. QualType originalType = recurse(T->getOriginalType());
  740. if (originalType.isNull())
  741. return QualType();
  742. QualType adjustedType = recurse(T->getAdjustedType());
  743. if (adjustedType.isNull())
  744. return QualType();
  745. if (originalType.getAsOpaquePtr()
  746. == T->getOriginalType().getAsOpaquePtr() &&
  747. adjustedType.getAsOpaquePtr() == T->getAdjustedType().getAsOpaquePtr())
  748. return QualType(T, 0);
  749. return Ctx.getAdjustedType(originalType, adjustedType);
  750. }
  751. QualType VisitDecayedType(const DecayedType *T) {
  752. QualType originalType = recurse(T->getOriginalType());
  753. if (originalType.isNull())
  754. return QualType();
  755. if (originalType.getAsOpaquePtr()
  756. == T->getOriginalType().getAsOpaquePtr())
  757. return QualType(T, 0);
  758. return Ctx.getDecayedType(originalType);
  759. }
  760. TRIVIAL_TYPE_CLASS(TypeOfExpr)
  761. TRIVIAL_TYPE_CLASS(TypeOf)
  762. TRIVIAL_TYPE_CLASS(Decltype)
  763. TRIVIAL_TYPE_CLASS(UnaryTransform)
  764. TRIVIAL_TYPE_CLASS(Record)
  765. TRIVIAL_TYPE_CLASS(Enum)
  766. // FIXME: Non-trivial to implement, but important for C++
  767. TRIVIAL_TYPE_CLASS(Elaborated)
  768. QualType VisitAttributedType(const AttributedType *T) {
  769. QualType modifiedType = recurse(T->getModifiedType());
  770. if (modifiedType.isNull())
  771. return QualType();
  772. QualType equivalentType = recurse(T->getEquivalentType());
  773. if (equivalentType.isNull())
  774. return QualType();
  775. if (modifiedType.getAsOpaquePtr()
  776. == T->getModifiedType().getAsOpaquePtr() &&
  777. equivalentType.getAsOpaquePtr()
  778. == T->getEquivalentType().getAsOpaquePtr())
  779. return QualType(T, 0);
  780. return Ctx.getAttributedType(T->getAttrKind(), modifiedType,
  781. equivalentType);
  782. }
  783. QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
  784. QualType replacementType = recurse(T->getReplacementType());
  785. if (replacementType.isNull())
  786. return QualType();
  787. if (replacementType.getAsOpaquePtr()
  788. == T->getReplacementType().getAsOpaquePtr())
  789. return QualType(T, 0);
  790. return Ctx.getSubstTemplateTypeParmType(T->getReplacedParameter(),
  791. replacementType);
  792. }
  793. // FIXME: Non-trivial to implement, but important for C++
  794. TRIVIAL_TYPE_CLASS(TemplateSpecialization)
  795. QualType VisitAutoType(const AutoType *T) {
  796. if (!T->isDeduced())
  797. return QualType(T, 0);
  798. QualType deducedType = recurse(T->getDeducedType());
  799. if (deducedType.isNull())
  800. return QualType();
  801. if (deducedType.getAsOpaquePtr()
  802. == T->getDeducedType().getAsOpaquePtr())
  803. return QualType(T, 0);
  804. return Ctx.getAutoType(deducedType, T->getKeyword(),
  805. T->isDependentType());
  806. }
  807. // FIXME: Non-trivial to implement, but important for C++
  808. TRIVIAL_TYPE_CLASS(PackExpansion)
  809. QualType VisitObjCObjectType(const ObjCObjectType *T) {
  810. QualType baseType = recurse(T->getBaseType());
  811. if (baseType.isNull())
  812. return QualType();
  813. // Transform type arguments.
  814. bool typeArgChanged = false;
  815. SmallVector<QualType, 4> typeArgs;
  816. for (auto typeArg : T->getTypeArgsAsWritten()) {
  817. QualType newTypeArg = recurse(typeArg);
  818. if (newTypeArg.isNull())
  819. return QualType();
  820. if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr())
  821. typeArgChanged = true;
  822. typeArgs.push_back(newTypeArg);
  823. }
  824. if (baseType.getAsOpaquePtr() == T->getBaseType().getAsOpaquePtr() &&
  825. !typeArgChanged)
  826. return QualType(T, 0);
  827. return Ctx.getObjCObjectType(baseType, typeArgs,
  828. llvm::makeArrayRef(T->qual_begin(),
  829. T->getNumProtocols()),
  830. T->isKindOfTypeAsWritten());
  831. }
  832. TRIVIAL_TYPE_CLASS(ObjCInterface)
  833. QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
  834. QualType pointeeType = recurse(T->getPointeeType());
  835. if (pointeeType.isNull())
  836. return QualType();
  837. if (pointeeType.getAsOpaquePtr()
  838. == T->getPointeeType().getAsOpaquePtr())
  839. return QualType(T, 0);
  840. return Ctx.getObjCObjectPointerType(pointeeType);
  841. }
  842. QualType VisitAtomicType(const AtomicType *T) {
  843. QualType valueType = recurse(T->getValueType());
  844. if (valueType.isNull())
  845. return QualType();
  846. if (valueType.getAsOpaquePtr()
  847. == T->getValueType().getAsOpaquePtr())
  848. return QualType(T, 0);
  849. return Ctx.getAtomicType(valueType);
  850. }
  851. #undef TRIVIAL_TYPE_CLASS
  852. };
  853. /// Perform a simple type transformation that does not change the
  854. /// semantics of the type.
  855. template<typename F>
  856. QualType simpleTransform(ASTContext &ctx, QualType type, F &&f) {
  857. // Transform the type. If it changed, return the transformed result.
  858. QualType transformed = f(type);
  859. if (transformed.getAsOpaquePtr() != type.getAsOpaquePtr())
  860. return transformed;
  861. // Split out the qualifiers from the type.
  862. SplitQualType splitType = type.split();
  863. // Visit the type itself.
  864. SimpleTransformVisitor<F> visitor(ctx, std::move(f));
  865. QualType result = visitor.Visit(splitType.Ty);
  866. if (result.isNull())
  867. return result;
  868. // Reconstruct the transformed type by applying the local qualifiers
  869. // from the split type.
  870. return ctx.getQualifiedType(result, splitType.Quals);
  871. }
  872. } // end anonymous namespace
  873. /// Substitute the given type arguments for Objective-C type
  874. /// parameters within the given type, recursively.
  875. QualType QualType::substObjCTypeArgs(
  876. ASTContext &ctx,
  877. ArrayRef<QualType> typeArgs,
  878. ObjCSubstitutionContext context) const {
  879. return simpleTransform(ctx, *this,
  880. [&](QualType type) -> QualType {
  881. SplitQualType splitType = type.split();
  882. // Replace an Objective-C type parameter reference with the corresponding
  883. // type argument.
  884. if (const auto *typedefTy = dyn_cast<TypedefType>(splitType.Ty)) {
  885. if (auto *typeParam = dyn_cast<ObjCTypeParamDecl>(typedefTy->getDecl())) {
  886. // If we have type arguments, use them.
  887. if (!typeArgs.empty()) {
  888. // FIXME: Introduce SubstObjCTypeParamType ?
  889. QualType argType = typeArgs[typeParam->getIndex()];
  890. return ctx.getQualifiedType(argType, splitType.Quals);
  891. }
  892. switch (context) {
  893. case ObjCSubstitutionContext::Ordinary:
  894. case ObjCSubstitutionContext::Parameter:
  895. case ObjCSubstitutionContext::Superclass:
  896. // Substitute the bound.
  897. return ctx.getQualifiedType(typeParam->getUnderlyingType(),
  898. splitType.Quals);
  899. case ObjCSubstitutionContext::Result:
  900. case ObjCSubstitutionContext::Property: {
  901. // Substitute the __kindof form of the underlying type.
  902. const auto *objPtr = typeParam->getUnderlyingType()
  903. ->castAs<ObjCObjectPointerType>();
  904. // __kindof types, id, and Class don't need an additional
  905. // __kindof.
  906. if (objPtr->isKindOfType() || objPtr->isObjCIdOrClassType())
  907. return ctx.getQualifiedType(typeParam->getUnderlyingType(),
  908. splitType.Quals);
  909. // Add __kindof.
  910. const auto *obj = objPtr->getObjectType();
  911. QualType resultTy = ctx.getObjCObjectType(obj->getBaseType(),
  912. obj->getTypeArgsAsWritten(),
  913. obj->getProtocols(),
  914. /*isKindOf=*/true);
  915. // Rebuild object pointer type.
  916. resultTy = ctx.getObjCObjectPointerType(resultTy);
  917. return ctx.getQualifiedType(resultTy, splitType.Quals);
  918. }
  919. }
  920. }
  921. }
  922. // If we have a function type, update the context appropriately.
  923. if (const auto *funcType = dyn_cast<FunctionType>(splitType.Ty)) {
  924. // Substitute result type.
  925. QualType returnType = funcType->getReturnType().substObjCTypeArgs(
  926. ctx,
  927. typeArgs,
  928. ObjCSubstitutionContext::Result);
  929. if (returnType.isNull())
  930. return QualType();
  931. // Handle non-prototyped functions, which only substitute into the result
  932. // type.
  933. if (isa<FunctionNoProtoType>(funcType)) {
  934. // If the return type was unchanged, do nothing.
  935. if (returnType.getAsOpaquePtr()
  936. == funcType->getReturnType().getAsOpaquePtr())
  937. return type;
  938. // Otherwise, build a new type.
  939. return ctx.getFunctionNoProtoType(returnType, funcType->getExtInfo());
  940. }
  941. const auto *funcProtoType = cast<FunctionProtoType>(funcType);
  942. // Transform parameter types.
  943. SmallVector<QualType, 4> paramTypes;
  944. bool paramChanged = false;
  945. for (auto paramType : funcProtoType->getParamTypes()) {
  946. QualType newParamType = paramType.substObjCTypeArgs(
  947. ctx,
  948. typeArgs,
  949. ObjCSubstitutionContext::Parameter);
  950. if (newParamType.isNull())
  951. return QualType();
  952. if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
  953. paramChanged = true;
  954. paramTypes.push_back(newParamType);
  955. }
  956. // Transform extended info.
  957. FunctionProtoType::ExtProtoInfo info = funcProtoType->getExtProtoInfo();
  958. bool exceptionChanged = false;
  959. if (info.ExceptionSpec.Type == EST_Dynamic) {
  960. SmallVector<QualType, 4> exceptionTypes;
  961. for (auto exceptionType : info.ExceptionSpec.Exceptions) {
  962. QualType newExceptionType = exceptionType.substObjCTypeArgs(
  963. ctx,
  964. typeArgs,
  965. ObjCSubstitutionContext::Ordinary);
  966. if (newExceptionType.isNull())
  967. return QualType();
  968. if (newExceptionType.getAsOpaquePtr()
  969. != exceptionType.getAsOpaquePtr())
  970. exceptionChanged = true;
  971. exceptionTypes.push_back(newExceptionType);
  972. }
  973. if (exceptionChanged) {
  974. info.ExceptionSpec.Exceptions =
  975. llvm::makeArrayRef(exceptionTypes).copy(ctx);
  976. }
  977. }
  978. if (returnType.getAsOpaquePtr()
  979. == funcProtoType->getReturnType().getAsOpaquePtr() &&
  980. !paramChanged && !exceptionChanged)
  981. return type;
  982. return ctx.getFunctionType(returnType, paramTypes, info);
  983. }
  984. // Substitute into the type arguments of a specialized Objective-C object
  985. // type.
  986. if (const auto *objcObjectType = dyn_cast<ObjCObjectType>(splitType.Ty)) {
  987. if (objcObjectType->isSpecializedAsWritten()) {
  988. SmallVector<QualType, 4> newTypeArgs;
  989. bool anyChanged = false;
  990. for (auto typeArg : objcObjectType->getTypeArgsAsWritten()) {
  991. QualType newTypeArg = typeArg.substObjCTypeArgs(
  992. ctx, typeArgs,
  993. ObjCSubstitutionContext::Ordinary);
  994. if (newTypeArg.isNull())
  995. return QualType();
  996. if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr()) {
  997. // If we're substituting based on an unspecialized context type,
  998. // produce an unspecialized type.
  999. ArrayRef<ObjCProtocolDecl *> protocols(
  1000. objcObjectType->qual_begin(),
  1001. objcObjectType->getNumProtocols());
  1002. if (typeArgs.empty() &&
  1003. context != ObjCSubstitutionContext::Superclass) {
  1004. return ctx.getObjCObjectType(
  1005. objcObjectType->getBaseType(), { },
  1006. protocols,
  1007. objcObjectType->isKindOfTypeAsWritten());
  1008. }
  1009. anyChanged = true;
  1010. }
  1011. newTypeArgs.push_back(newTypeArg);
  1012. }
  1013. if (anyChanged) {
  1014. ArrayRef<ObjCProtocolDecl *> protocols(
  1015. objcObjectType->qual_begin(),
  1016. objcObjectType->getNumProtocols());
  1017. return ctx.getObjCObjectType(objcObjectType->getBaseType(),
  1018. newTypeArgs, protocols,
  1019. objcObjectType->isKindOfTypeAsWritten());
  1020. }
  1021. }
  1022. return type;
  1023. }
  1024. return type;
  1025. });
  1026. }
  1027. QualType QualType::substObjCMemberType(QualType objectType,
  1028. const DeclContext *dc,
  1029. ObjCSubstitutionContext context) const {
  1030. if (auto subs = objectType->getObjCSubstitutions(dc))
  1031. return substObjCTypeArgs(dc->getParentASTContext(), *subs, context);
  1032. return *this;
  1033. }
  1034. QualType QualType::stripObjCKindOfType(const ASTContext &constCtx) const {
  1035. // FIXME: Because ASTContext::getAttributedType() is non-const.
  1036. auto &ctx = const_cast<ASTContext &>(constCtx);
  1037. return simpleTransform(ctx, *this,
  1038. [&](QualType type) -> QualType {
  1039. SplitQualType splitType = type.split();
  1040. if (auto *objType = splitType.Ty->getAs<ObjCObjectType>()) {
  1041. if (!objType->isKindOfType())
  1042. return type;
  1043. QualType baseType
  1044. = objType->getBaseType().stripObjCKindOfType(ctx);
  1045. return ctx.getQualifiedType(
  1046. ctx.getObjCObjectType(baseType,
  1047. objType->getTypeArgsAsWritten(),
  1048. objType->getProtocols(),
  1049. /*isKindOf=*/false),
  1050. splitType.Quals);
  1051. }
  1052. return type;
  1053. });
  1054. }
  1055. Optional<ArrayRef<QualType>> Type::getObjCSubstitutions(
  1056. const DeclContext *dc) const {
  1057. // Look through method scopes.
  1058. if (auto method = dyn_cast<ObjCMethodDecl>(dc))
  1059. dc = method->getDeclContext();
  1060. // Find the class or category in which the type we're substituting
  1061. // was declared.
  1062. const ObjCInterfaceDecl *dcClassDecl = dyn_cast<ObjCInterfaceDecl>(dc);
  1063. const ObjCCategoryDecl *dcCategoryDecl = nullptr;
  1064. ObjCTypeParamList *dcTypeParams = nullptr;
  1065. if (dcClassDecl) {
  1066. // If the class does not have any type parameters, there's no
  1067. // substitution to do.
  1068. dcTypeParams = dcClassDecl->getTypeParamList();
  1069. if (!dcTypeParams)
  1070. return None;
  1071. } else {
  1072. // If we are in neither a class nor a category, there's no
  1073. // substitution to perform.
  1074. dcCategoryDecl = dyn_cast<ObjCCategoryDecl>(dc);
  1075. if (!dcCategoryDecl)
  1076. return None;
  1077. // If the category does not have any type parameters, there's no
  1078. // substitution to do.
  1079. dcTypeParams = dcCategoryDecl->getTypeParamList();
  1080. if (!dcTypeParams)
  1081. return None;
  1082. dcClassDecl = dcCategoryDecl->getClassInterface();
  1083. if (!dcClassDecl)
  1084. return None;
  1085. }
  1086. assert(dcTypeParams && "No substitutions to perform");
  1087. assert(dcClassDecl && "No class context");
  1088. // Find the underlying object type.
  1089. const ObjCObjectType *objectType;
  1090. if (const auto *objectPointerType = getAs<ObjCObjectPointerType>()) {
  1091. objectType = objectPointerType->getObjectType();
  1092. } else if (getAs<BlockPointerType>()) {
  1093. ASTContext &ctx = dc->getParentASTContext();
  1094. objectType = ctx.getObjCObjectType(ctx.ObjCBuiltinIdTy, { }, { })
  1095. ->castAs<ObjCObjectType>();;
  1096. } else {
  1097. objectType = getAs<ObjCObjectType>();
  1098. }
  1099. /// Extract the class from the receiver object type.
  1100. ObjCInterfaceDecl *curClassDecl = objectType ? objectType->getInterface()
  1101. : nullptr;
  1102. if (!curClassDecl) {
  1103. // If we don't have a context type (e.g., this is "id" or some
  1104. // variant thereof), substitute the bounds.
  1105. return llvm::ArrayRef<QualType>();
  1106. }
  1107. // Follow the superclass chain until we've mapped the receiver type
  1108. // to the same class as the context.
  1109. while (curClassDecl != dcClassDecl) {
  1110. // Map to the superclass type.
  1111. QualType superType = objectType->getSuperClassType();
  1112. if (superType.isNull()) {
  1113. objectType = nullptr;
  1114. break;
  1115. }
  1116. objectType = superType->castAs<ObjCObjectType>();
  1117. curClassDecl = objectType->getInterface();
  1118. }
  1119. // If we don't have a receiver type, or the receiver type does not
  1120. // have type arguments, substitute in the defaults.
  1121. if (!objectType || objectType->isUnspecialized()) {
  1122. return llvm::ArrayRef<QualType>();
  1123. }
  1124. // The receiver type has the type arguments we want.
  1125. return objectType->getTypeArgs();
  1126. }
  1127. bool Type::acceptsObjCTypeParams() const {
  1128. if (auto *IfaceT = getAsObjCInterfaceType()) {
  1129. if (auto *ID = IfaceT->getInterface()) {
  1130. if (ID->getTypeParamList())
  1131. return true;
  1132. }
  1133. }
  1134. return false;
  1135. }
  1136. void ObjCObjectType::computeSuperClassTypeSlow() const {
  1137. // Retrieve the class declaration for this type. If there isn't one
  1138. // (e.g., this is some variant of "id" or "Class"), then there is no
  1139. // superclass type.
  1140. ObjCInterfaceDecl *classDecl = getInterface();
  1141. if (!classDecl) {
  1142. CachedSuperClassType.setInt(true);
  1143. return;
  1144. }
  1145. // Extract the superclass type.
  1146. const ObjCObjectType *superClassObjTy = classDecl->getSuperClassType();
  1147. if (!superClassObjTy) {
  1148. CachedSuperClassType.setInt(true);
  1149. return;
  1150. }
  1151. ObjCInterfaceDecl *superClassDecl = superClassObjTy->getInterface();
  1152. if (!superClassDecl) {
  1153. CachedSuperClassType.setInt(true);
  1154. return;
  1155. }
  1156. // If the superclass doesn't have type parameters, then there is no
  1157. // substitution to perform.
  1158. QualType superClassType(superClassObjTy, 0);
  1159. ObjCTypeParamList *superClassTypeParams = superClassDecl->getTypeParamList();
  1160. if (!superClassTypeParams) {
  1161. CachedSuperClassType.setPointerAndInt(
  1162. superClassType->castAs<ObjCObjectType>(), true);
  1163. return;
  1164. }
  1165. // If the superclass reference is unspecialized, return it.
  1166. if (superClassObjTy->isUnspecialized()) {
  1167. CachedSuperClassType.setPointerAndInt(superClassObjTy, true);
  1168. return;
  1169. }
  1170. // If the subclass is not parameterized, there aren't any type
  1171. // parameters in the superclass reference to substitute.
  1172. ObjCTypeParamList *typeParams = classDecl->getTypeParamList();
  1173. if (!typeParams) {
  1174. CachedSuperClassType.setPointerAndInt(
  1175. superClassType->castAs<ObjCObjectType>(), true);
  1176. return;
  1177. }
  1178. // If the subclass type isn't specialized, return the unspecialized
  1179. // superclass.
  1180. if (isUnspecialized()) {
  1181. QualType unspecializedSuper
  1182. = classDecl->getASTContext().getObjCInterfaceType(
  1183. superClassObjTy->getInterface());
  1184. CachedSuperClassType.setPointerAndInt(
  1185. unspecializedSuper->castAs<ObjCObjectType>(),
  1186. true);
  1187. return;
  1188. }
  1189. // Substitute the provided type arguments into the superclass type.
  1190. ArrayRef<QualType> typeArgs = getTypeArgs();
  1191. assert(typeArgs.size() == typeParams->size());
  1192. CachedSuperClassType.setPointerAndInt(
  1193. superClassType.substObjCTypeArgs(classDecl->getASTContext(), typeArgs,
  1194. ObjCSubstitutionContext::Superclass)
  1195. ->castAs<ObjCObjectType>(),
  1196. true);
  1197. }
  1198. const ObjCInterfaceType *ObjCObjectPointerType::getInterfaceType() const {
  1199. if (auto interfaceDecl = getObjectType()->getInterface()) {
  1200. return interfaceDecl->getASTContext().getObjCInterfaceType(interfaceDecl)
  1201. ->castAs<ObjCInterfaceType>();
  1202. }
  1203. return nullptr;
  1204. }
  1205. QualType ObjCObjectPointerType::getSuperClassType() const {
  1206. QualType superObjectType = getObjectType()->getSuperClassType();
  1207. if (superObjectType.isNull())
  1208. return superObjectType;
  1209. ASTContext &ctx = getInterfaceDecl()->getASTContext();
  1210. return ctx.getObjCObjectPointerType(superObjectType);
  1211. }
  1212. const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
  1213. // There is no sugar for ObjCObjectType's, just return the canonical
  1214. // type pointer if it is the right class. There is no typedef information to
  1215. // return and these cannot be Address-space qualified.
  1216. if (const ObjCObjectType *T = getAs<ObjCObjectType>())
  1217. if (T->getNumProtocols() && T->getInterface())
  1218. return T;
  1219. return nullptr;
  1220. }
  1221. bool Type::isObjCQualifiedInterfaceType() const {
  1222. return getAsObjCQualifiedInterfaceType() != nullptr;
  1223. }
  1224. const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
  1225. // There is no sugar for ObjCQualifiedIdType's, just return the canonical
  1226. // type pointer if it is the right class.
  1227. if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
  1228. if (OPT->isObjCQualifiedIdType())
  1229. return OPT;
  1230. }
  1231. return nullptr;
  1232. }
  1233. const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
  1234. // There is no sugar for ObjCQualifiedClassType's, just return the canonical
  1235. // type pointer if it is the right class.
  1236. if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
  1237. if (OPT->isObjCQualifiedClassType())
  1238. return OPT;
  1239. }
  1240. return nullptr;
  1241. }
  1242. const ObjCObjectType *Type::getAsObjCInterfaceType() const {
  1243. if (const ObjCObjectType *OT = getAs<ObjCObjectType>()) {
  1244. if (OT->getInterface())
  1245. return OT;
  1246. }
  1247. return nullptr;
  1248. }
  1249. const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
  1250. if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
  1251. if (OPT->getInterfaceType())
  1252. return OPT;
  1253. }
  1254. return nullptr;
  1255. }
  1256. const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
  1257. QualType PointeeType;
  1258. if (const PointerType *PT = getAs<PointerType>())
  1259. PointeeType = PT->getPointeeType();
  1260. else if (const ReferenceType *RT = getAs<ReferenceType>())
  1261. PointeeType = RT->getPointeeType();
  1262. else
  1263. return nullptr;
  1264. if (const RecordType *RT = PointeeType->getAs<RecordType>())
  1265. return dyn_cast<CXXRecordDecl>(RT->getDecl());
  1266. return nullptr;
  1267. }
  1268. CXXRecordDecl *Type::getAsCXXRecordDecl() const {
  1269. return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl());
  1270. }
  1271. TagDecl *Type::getAsTagDecl() const {
  1272. if (const auto *TT = getAs<TagType>())
  1273. return cast<TagDecl>(TT->getDecl());
  1274. if (const auto *Injected = getAs<InjectedClassNameType>())
  1275. return Injected->getDecl();
  1276. return nullptr;
  1277. }
  1278. namespace {
  1279. class GetContainedAutoVisitor :
  1280. public TypeVisitor<GetContainedAutoVisitor, AutoType*> {
  1281. public:
  1282. using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit;
  1283. AutoType *Visit(QualType T) {
  1284. if (T.isNull())
  1285. return nullptr;
  1286. return Visit(T.getTypePtr());
  1287. }
  1288. // The 'auto' type itself.
  1289. AutoType *VisitAutoType(const AutoType *AT) {
  1290. return const_cast<AutoType*>(AT);
  1291. }
  1292. // Only these types can contain the desired 'auto' type.
  1293. AutoType *VisitPointerType(const PointerType *T) {
  1294. return Visit(T->getPointeeType());
  1295. }
  1296. AutoType *VisitBlockPointerType(const BlockPointerType *T) {
  1297. return Visit(T->getPointeeType());
  1298. }
  1299. AutoType *VisitReferenceType(const ReferenceType *T) {
  1300. return Visit(T->getPointeeTypeAsWritten());
  1301. }
  1302. AutoType *VisitMemberPointerType(const MemberPointerType *T) {
  1303. return Visit(T->getPointeeType());
  1304. }
  1305. AutoType *VisitArrayType(const ArrayType *T) {
  1306. return Visit(T->getElementType());
  1307. }
  1308. AutoType *VisitDependentSizedExtVectorType(
  1309. const DependentSizedExtVectorType *T) {
  1310. return Visit(T->getElementType());
  1311. }
  1312. AutoType *VisitVectorType(const VectorType *T) {
  1313. return Visit(T->getElementType());
  1314. }
  1315. AutoType *VisitFunctionType(const FunctionType *T) {
  1316. return Visit(T->getReturnType());
  1317. }
  1318. AutoType *VisitParenType(const ParenType *T) {
  1319. return Visit(T->getInnerType());
  1320. }
  1321. AutoType *VisitAttributedType(const AttributedType *T) {
  1322. return Visit(T->getModifiedType());
  1323. }
  1324. AutoType *VisitAdjustedType(const AdjustedType *T) {
  1325. return Visit(T->getOriginalType());
  1326. }
  1327. };
  1328. }
  1329. AutoType *Type::getContainedAutoType() const {
  1330. return GetContainedAutoVisitor().Visit(this);
  1331. }
  1332. bool Type::hasIntegerRepresentation() const {
  1333. if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
  1334. return VT->getElementType()->isIntegerType();
  1335. else
  1336. return isIntegerType();
  1337. }
  1338. /// \brief Determine whether this type is an integral type.
  1339. ///
  1340. /// This routine determines whether the given type is an integral type per
  1341. /// C++ [basic.fundamental]p7. Although the C standard does not define the
  1342. /// term "integral type", it has a similar term "integer type", and in C++
  1343. /// the two terms are equivalent. However, C's "integer type" includes
  1344. /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
  1345. /// parameter is used to determine whether we should be following the C or
  1346. /// C++ rules when determining whether this type is an integral/integer type.
  1347. ///
  1348. /// For cases where C permits "an integer type" and C++ permits "an integral
  1349. /// type", use this routine.
  1350. ///
  1351. /// For cases where C permits "an integer type" and C++ permits "an integral
  1352. /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
  1353. ///
  1354. /// \param Ctx The context in which this type occurs.
  1355. ///
  1356. /// \returns true if the type is considered an integral type, false otherwise.
  1357. bool Type::isIntegralType(ASTContext &Ctx) const {
  1358. if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
  1359. return BT->getKind() >= BuiltinType::Bool &&
  1360. BT->getKind() <= BuiltinType::Int128;
  1361. // Complete enum types are integral in C.
  1362. if (!Ctx.getLangOpts().CPlusPlus)
  1363. if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
  1364. return ET->getDecl()->isComplete();
  1365. return false;
  1366. }
  1367. bool Type::isIntegralOrUnscopedEnumerationType() const {
  1368. if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
  1369. return BT->getKind() >= BuiltinType::Bool &&
  1370. BT->getKind() <= BuiltinType::Int128;
  1371. // Check for a complete enum type; incomplete enum types are not properly an
  1372. // enumeration type in the sense required here.
  1373. // C++0x: However, if the underlying type of the enum is fixed, it is
  1374. // considered complete.
  1375. if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
  1376. return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
  1377. return false;
  1378. }
  1379. bool Type::isCharType() const {
  1380. if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
  1381. return BT->getKind() == BuiltinType::Char_U ||
  1382. BT->getKind() == BuiltinType::UChar ||
  1383. BT->getKind() == BuiltinType::Char_S ||
  1384. BT->getKind() == BuiltinType::SChar;
  1385. return false;
  1386. }
  1387. bool Type::isWideCharType() const {
  1388. if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
  1389. return BT->getKind() == BuiltinType::WChar_S ||
  1390. BT->getKind() == BuiltinType::WChar_U;
  1391. return false;
  1392. }
  1393. bool Type::isChar16Type() const {
  1394. if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
  1395. return BT->getKind() == BuiltinType::Char16;
  1396. return false;
  1397. }
  1398. bool Type::isChar32Type() const {
  1399. if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
  1400. return BT->getKind() == BuiltinType::Char32;
  1401. return false;
  1402. }
  1403. /// \brief Determine whether this type is any of the built-in character
  1404. /// types.
  1405. bool Type::isAnyCharacterType() const {
  1406. const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
  1407. if (!BT) return false;
  1408. switch (BT->getKind()) {
  1409. default: return false;
  1410. case BuiltinType::Char_U:
  1411. case BuiltinType::UChar:
  1412. case BuiltinType::WChar_U:
  1413. case BuiltinType::Char16:
  1414. case BuiltinType::Char32:
  1415. case BuiltinType::Char_S:
  1416. case BuiltinType::SChar:
  1417. case BuiltinType::WChar_S:
  1418. return true;
  1419. }
  1420. }
  1421. /// isSignedIntegerType - Return true if this is an integer type that is
  1422. /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
  1423. /// an enum decl which has a signed representation
  1424. bool Type::isSignedIntegerType() const {
  1425. if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
  1426. return BT->getKind() >= BuiltinType::Char_S &&
  1427. BT->getKind() <= BuiltinType::Int128;
  1428. }
  1429. if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
  1430. // Incomplete enum types are not treated as integer types.
  1431. // FIXME: In C++, enum types are never integer types.
  1432. if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
  1433. return ET->getDecl()->getIntegerType()->isSignedIntegerType();
  1434. }
  1435. return false;
  1436. }
  1437. bool Type::isSignedIntegerOrEnumerationType() const {
  1438. if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
  1439. return BT->getKind() >= BuiltinType::Char_S &&
  1440. BT->getKind() <= BuiltinType::Int128;
  1441. }
  1442. if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
  1443. if (ET->getDecl()->isComplete())
  1444. return ET->getDecl()->getIntegerType()->isSignedIntegerType();
  1445. }
  1446. return false;
  1447. }
  1448. bool Type::hasSignedIntegerRepresentation() const {
  1449. if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
  1450. return VT->getElementType()->isSignedIntegerOrEnumerationType();
  1451. else
  1452. return isSignedIntegerOrEnumerationType();
  1453. }
  1454. /// isUnsignedIntegerType - Return true if this is an integer type that is
  1455. /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
  1456. /// decl which has an unsigned representation
  1457. bool Type::isUnsignedIntegerType() const {
  1458. if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
  1459. return BT->getKind() >= BuiltinType::Bool &&
  1460. BT->getKind() <= BuiltinType::UInt128;
  1461. }
  1462. if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
  1463. // Incomplete enum types are not treated as integer types.
  1464. // FIXME: In C++, enum types are never integer types.
  1465. if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
  1466. return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
  1467. }
  1468. return false;
  1469. }
  1470. bool Type::isUnsignedIntegerOrEnumerationType() const {
  1471. if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
  1472. return BT->getKind() >= BuiltinType::Bool &&
  1473. BT->getKind() <= BuiltinType::UInt128;
  1474. }
  1475. if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
  1476. if (ET->getDecl()->isComplete())
  1477. return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
  1478. }
  1479. return false;
  1480. }
  1481. bool Type::hasUnsignedIntegerRepresentation() const {
  1482. if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
  1483. return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
  1484. else
  1485. return isUnsignedIntegerOrEnumerationType();
  1486. }
  1487. bool Type::isFloatingType() const {
  1488. if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
  1489. return BT->getKind() >= BuiltinType::Half &&
  1490. BT->getKind() <= BuiltinType::LongDouble;
  1491. if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
  1492. return CT->getElementType()->isFloatingType();
  1493. return false;
  1494. }
  1495. bool Type::hasFloatingRepresentation() const {
  1496. if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
  1497. return VT->getElementType()->isFloatingType();
  1498. else
  1499. return isFloatingType();
  1500. }
  1501. bool Type::isRealFloatingType() const {
  1502. if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
  1503. return BT->isFloatingPoint();
  1504. return false;
  1505. }
  1506. bool Type::isRealType() const {
  1507. if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
  1508. return BT->getKind() >= BuiltinType::Bool &&
  1509. BT->getKind() <= BuiltinType::LongDouble;
  1510. if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
  1511. return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
  1512. return false;
  1513. }
  1514. bool Type::isArithmeticType() const {
  1515. if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
  1516. return BT->getKind() >= BuiltinType::Bool &&
  1517. BT->getKind() <= BuiltinType::LongDouble;
  1518. if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
  1519. // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
  1520. // If a body isn't seen by the time we get here, return false.
  1521. //
  1522. // C++0x: Enumerations are not arithmetic types. For now, just return
  1523. // false for scoped enumerations since that will disable any
  1524. // unwanted implicit conversions.
  1525. return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
  1526. return isa<ComplexType>(CanonicalType);
  1527. }
  1528. Type::ScalarTypeKind Type::getScalarTypeKind() const {
  1529. assert(isScalarType());
  1530. const Type *T = CanonicalType.getTypePtr();
  1531. if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
  1532. if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
  1533. if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
  1534. if (BT->isInteger()) return STK_Integral;
  1535. if (BT->isFloatingPoint()) return STK_Floating;
  1536. llvm_unreachable("unknown scalar builtin type");
  1537. } else if (isa<PointerType>(T)) {
  1538. return STK_CPointer;
  1539. } else if (isa<BlockPointerType>(T)) {
  1540. return STK_BlockPointer;
  1541. } else if (isa<ObjCObjectPointerType>(T)) {
  1542. return STK_ObjCObjectPointer;
  1543. } else if (isa<MemberPointerType>(T)) {
  1544. return STK_MemberPointer;
  1545. } else if (isa<EnumType>(T)) {
  1546. assert(cast<EnumType>(T)->getDecl()->isComplete());
  1547. return STK_Integral;
  1548. } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
  1549. if (CT->getElementType()->isRealFloatingType())
  1550. return STK_FloatingComplex;
  1551. return STK_IntegralComplex;
  1552. }
  1553. llvm_unreachable("unknown scalar type");
  1554. }
  1555. /// \brief Determines whether the type is a C++ aggregate type or C
  1556. /// aggregate or union type.
  1557. ///
  1558. /// An aggregate type is an array or a class type (struct, union, or
  1559. /// class) that has no user-declared constructors, no private or
  1560. /// protected non-static data members, no base classes, and no virtual
  1561. /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
  1562. /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
  1563. /// includes union types.
  1564. bool Type::isAggregateType() const {
  1565. if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
  1566. if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
  1567. return ClassDecl->isAggregate();
  1568. return true;
  1569. }
  1570. return isa<ArrayType>(CanonicalType);
  1571. }
  1572. /// isConstantSizeType - Return true if this is not a variable sized type,
  1573. /// according to the rules of C99 6.7.5p3. It is not legal to call this on
  1574. /// incomplete types or dependent types.
  1575. bool Type::isConstantSizeType() const {
  1576. assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
  1577. assert(!isDependentType() && "This doesn't make sense for dependent types");
  1578. // The VAT must have a size, as it is known to be complete.
  1579. return !isa<VariableArrayType>(CanonicalType);
  1580. }
  1581. /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
  1582. /// - a type that can describe objects, but which lacks information needed to
  1583. /// determine its size.
  1584. bool Type::isIncompleteType(NamedDecl **Def) const {
  1585. if (Def)
  1586. *Def = nullptr;
  1587. switch (CanonicalType->getTypeClass()) {
  1588. default: return false;
  1589. case Builtin:
  1590. // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
  1591. // be completed.
  1592. return isVoidType();
  1593. case Enum: {
  1594. EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
  1595. if (Def)
  1596. *Def = EnumD;
  1597. // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
  1598. if (EnumD->isFixed())
  1599. return false;
  1600. return !EnumD->isCompleteDefinition();
  1601. }
  1602. case Record: {
  1603. // A tagged type (struct/union/enum/class) is incomplete if the decl is a
  1604. // forward declaration, but not a full definition (C99 6.2.5p22).
  1605. RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
  1606. if (Def)
  1607. *Def = Rec;
  1608. return !Rec->isCompleteDefinition();
  1609. }
  1610. case ConstantArray:
  1611. // An array is incomplete if its element type is incomplete
  1612. // (C++ [dcl.array]p1).
  1613. // We don't handle variable arrays (they're not allowed in C++) or
  1614. // dependent-sized arrays (dependent types are never treated as incomplete).
  1615. return cast<ArrayType>(CanonicalType)->getElementType()
  1616. ->isIncompleteType(Def);
  1617. case IncompleteArray:
  1618. // An array of unknown size is an incomplete type (C99 6.2.5p22).
  1619. return true;
  1620. case MemberPointer: {
  1621. // Member pointers in the MS ABI have special behavior in
  1622. // RequireCompleteType: they attach a MSInheritanceAttr to the CXXRecordDecl
  1623. // to indicate which inheritance model to use.
  1624. auto *MPTy = cast<MemberPointerType>(CanonicalType);
  1625. const Type *ClassTy = MPTy->getClass();
  1626. // Member pointers with dependent class types don't get special treatment.
  1627. if (ClassTy->isDependentType())
  1628. return false;
  1629. const CXXRecordDecl *RD = ClassTy->getAsCXXRecordDecl();
  1630. ASTContext &Context = RD->getASTContext();
  1631. // Member pointers not in the MS ABI don't get special treatment.
  1632. if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
  1633. return false;
  1634. // The inheritance attribute might only be present on the most recent
  1635. // CXXRecordDecl, use that one.
  1636. RD = RD->getMostRecentDecl();
  1637. // Nothing interesting to do if the inheritance attribute is already set.
  1638. if (RD->hasAttr<MSInheritanceAttr>())
  1639. return false;
  1640. return true;
  1641. }
  1642. case ObjCObject:
  1643. return cast<ObjCObjectType>(CanonicalType)->getBaseType()
  1644. ->isIncompleteType(Def);
  1645. case ObjCInterface: {
  1646. // ObjC interfaces are incomplete if they are @class, not @interface.
  1647. ObjCInterfaceDecl *Interface
  1648. = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
  1649. if (Def)
  1650. *Def = Interface;
  1651. return !Interface->hasDefinition();
  1652. }
  1653. }
  1654. }
  1655. bool QualType::isPODType(ASTContext &Context) const {
  1656. // C++11 has a more relaxed definition of POD.
  1657. if (Context.getLangOpts().CPlusPlus11)
  1658. return isCXX11PODType(Context);
  1659. return isCXX98PODType(Context);
  1660. }
  1661. bool QualType::isCXX98PODType(ASTContext &Context) const {
  1662. // The compiler shouldn't query this for incomplete types, but the user might.
  1663. // We return false for that case. Except for incomplete arrays of PODs, which
  1664. // are PODs according to the standard.
  1665. if (isNull())
  1666. return 0;
  1667. if ((*this)->isIncompleteArrayType())
  1668. return Context.getBaseElementType(*this).isCXX98PODType(Context);
  1669. if ((*this)->isIncompleteType())
  1670. return false;
  1671. if (Context.getLangOpts().ObjCAutoRefCount) {
  1672. switch (getObjCLifetime()) {
  1673. case Qualifiers::OCL_ExplicitNone:
  1674. return true;
  1675. case Qualifiers::OCL_Strong:
  1676. case Qualifiers::OCL_Weak:
  1677. case Qualifiers::OCL_Autoreleasing:
  1678. return false;
  1679. case Qualifiers::OCL_None:
  1680. break;
  1681. }
  1682. }
  1683. QualType CanonicalType = getTypePtr()->CanonicalType;
  1684. switch (CanonicalType->getTypeClass()) {
  1685. // Everything not explicitly mentioned is not POD.
  1686. default: return false;
  1687. case Type::VariableArray:
  1688. case Type::ConstantArray:
  1689. // IncompleteArray is handled above.
  1690. return Context.getBaseElementType(*this).isCXX98PODType(Context);
  1691. case Type::ObjCObjectPointer:
  1692. case Type::BlockPointer:
  1693. case Type::Builtin:
  1694. case Type::Complex:
  1695. case Type::Pointer:
  1696. case Type::MemberPointer:
  1697. case Type::Vector:
  1698. case Type::ExtVector:
  1699. return true;
  1700. case Type::Enum:
  1701. return true;
  1702. case Type::Record:
  1703. if (CXXRecordDecl *ClassDecl
  1704. = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
  1705. return ClassDecl->isPOD();
  1706. // C struct/union is POD.
  1707. return true;
  1708. }
  1709. }
  1710. bool QualType::isTrivialType(ASTContext &Context) const {
  1711. // The compiler shouldn't query this for incomplete types, but the user might.
  1712. // We return false for that case. Except for incomplete arrays of PODs, which
  1713. // are PODs according to the standard.
  1714. if (isNull())
  1715. return 0;
  1716. if ((*this)->isArrayType())
  1717. return Context.getBaseElementType(*this).isTrivialType(Context);
  1718. // Return false for incomplete types after skipping any incomplete array
  1719. // types which are expressly allowed by the standard and thus our API.
  1720. if ((*this)->isIncompleteType())
  1721. return false;
  1722. if (Context.getLangOpts().ObjCAutoRefCount) {
  1723. switch (getObjCLifetime()) {
  1724. case Qualifiers::OCL_ExplicitNone:
  1725. return true;
  1726. case Qualifiers::OCL_Strong:
  1727. case Qualifiers::OCL_Weak:
  1728. case Qualifiers::OCL_Autoreleasing:
  1729. return false;
  1730. case Qualifiers::OCL_None:
  1731. if ((*this)->isObjCLifetimeType())
  1732. return false;
  1733. break;
  1734. }
  1735. }
  1736. QualType CanonicalType = getTypePtr()->CanonicalType;
  1737. if (CanonicalType->isDependentType())
  1738. return false;
  1739. // C++0x [basic.types]p9:
  1740. // Scalar types, trivial class types, arrays of such types, and
  1741. // cv-qualified versions of these types are collectively called trivial
  1742. // types.
  1743. // As an extension, Clang treats vector types as Scalar types.
  1744. if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
  1745. return true;
  1746. if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
  1747. if (const CXXRecordDecl *ClassDecl =
  1748. dyn_cast<CXXRecordDecl>(RT->getDecl())) {
  1749. // C++11 [class]p6:
  1750. // A trivial class is a class that has a default constructor,
  1751. // has no non-trivial default constructors, and is trivially
  1752. // copyable.
  1753. return ClassDecl->hasDefaultConstructor() &&
  1754. !ClassDecl->hasNonTrivialDefaultConstructor() &&
  1755. ClassDecl->isTriviallyCopyable();
  1756. }
  1757. return true;
  1758. }
  1759. // No other types can match.
  1760. return false;
  1761. }
  1762. bool QualType::isTriviallyCopyableType(ASTContext &Context) const {
  1763. if ((*this)->isArrayType())
  1764. return Context.getBaseElementType(*this).isTriviallyCopyableType(Context);
  1765. if (Context.getLangOpts().ObjCAutoRefCount) {
  1766. switch (getObjCLifetime()) {
  1767. case Qualifiers::OCL_ExplicitNone:
  1768. return true;
  1769. case Qualifiers::OCL_Strong:
  1770. case Qualifiers::OCL_Weak:
  1771. case Qualifiers::OCL_Autoreleasing:
  1772. return false;
  1773. case Qualifiers::OCL_None:
  1774. if ((*this)->isObjCLifetimeType())
  1775. return false;
  1776. break;
  1777. }
  1778. }
  1779. // C++11 [basic.types]p9
  1780. // Scalar types, trivially copyable class types, arrays of such types, and
  1781. // non-volatile const-qualified versions of these types are collectively
  1782. // called trivially copyable types.
  1783. QualType CanonicalType = getCanonicalType();
  1784. if (CanonicalType->isDependentType())
  1785. return false;
  1786. if (CanonicalType.isVolatileQualified())
  1787. return false;
  1788. // Return false for incomplete types after skipping any incomplete array types
  1789. // which are expressly allowed by the standard and thus our API.
  1790. if (CanonicalType->isIncompleteType())
  1791. return false;
  1792. // As an extension, Clang treats vector types as Scalar types.
  1793. if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
  1794. return true;
  1795. if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
  1796. if (const CXXRecordDecl *ClassDecl =
  1797. dyn_cast<CXXRecordDecl>(RT->getDecl())) {
  1798. if (!ClassDecl->isTriviallyCopyable()) return false;
  1799. }
  1800. return true;
  1801. }
  1802. // No other types can match.
  1803. return false;
  1804. }
  1805. bool Type::isLiteralType(const ASTContext &Ctx) const {
  1806. if (isDependentType())
  1807. return false;
  1808. // C++1y [basic.types]p10:
  1809. // A type is a literal type if it is:
  1810. // -- cv void; or
  1811. if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
  1812. return true;
  1813. // C++11 [basic.types]p10:
  1814. // A type is a literal type if it is:
  1815. // [...]
  1816. // -- an array of literal type other than an array of runtime bound; or
  1817. if (isVariableArrayType())
  1818. return false;
  1819. const Type *BaseTy = getBaseElementTypeUnsafe();
  1820. assert(BaseTy && "NULL element type");
  1821. // Return false for incomplete types after skipping any incomplete array
  1822. // types; those are expressly allowed by the standard and thus our API.
  1823. if (BaseTy->isIncompleteType())
  1824. return false;
  1825. // C++11 [basic.types]p10:
  1826. // A type is a literal type if it is:
  1827. // -- a scalar type; or
  1828. // As an extension, Clang treats vector types and complex types as
  1829. // literal types.
  1830. if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
  1831. BaseTy->isAnyComplexType())
  1832. return true;
  1833. // -- a reference type; or
  1834. if (BaseTy->isReferenceType())
  1835. return true;
  1836. // -- a class type that has all of the following properties:
  1837. if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
  1838. // -- a trivial destructor,
  1839. // -- every constructor call and full-expression in the
  1840. // brace-or-equal-initializers for non-static data members (if any)
  1841. // is a constant expression,
  1842. // -- it is an aggregate type or has at least one constexpr
  1843. // constructor or constructor template that is not a copy or move
  1844. // constructor, and
  1845. // -- all non-static data members and base classes of literal types
  1846. //
  1847. // We resolve DR1361 by ignoring the second bullet.
  1848. if (const CXXRecordDecl *ClassDecl =
  1849. dyn_cast<CXXRecordDecl>(RT->getDecl()))
  1850. return ClassDecl->isLiteral();
  1851. return true;
  1852. }
  1853. // We treat _Atomic T as a literal type if T is a literal type.
  1854. if (const AtomicType *AT = BaseTy->getAs<AtomicType>())
  1855. return AT->getValueType()->isLiteralType(Ctx);
  1856. // If this type hasn't been deduced yet, then conservatively assume that
  1857. // it'll work out to be a literal type.
  1858. if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
  1859. return true;
  1860. return false;
  1861. }
  1862. bool Type::isStandardLayoutType() const {
  1863. if (isDependentType())
  1864. return false;
  1865. // C++0x [basic.types]p9:
  1866. // Scalar types, standard-layout class types, arrays of such types, and
  1867. // cv-qualified versions of these types are collectively called
  1868. // standard-layout types.
  1869. const Type *BaseTy = getBaseElementTypeUnsafe();
  1870. assert(BaseTy && "NULL element type");
  1871. // Return false for incomplete types after skipping any incomplete array
  1872. // types which are expressly allowed by the standard and thus our API.
  1873. if (BaseTy->isIncompleteType())
  1874. return false;
  1875. // As an extension, Clang treats vector types as Scalar types.
  1876. if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
  1877. if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
  1878. if (const CXXRecordDecl *ClassDecl =
  1879. dyn_cast<CXXRecordDecl>(RT->getDecl()))
  1880. if (!ClassDecl->isStandardLayout())
  1881. return false;
  1882. // Default to 'true' for non-C++ class types.
  1883. // FIXME: This is a bit dubious, but plain C structs should trivially meet
  1884. // all the requirements of standard layout classes.
  1885. return true;
  1886. }
  1887. // No other types can match.
  1888. return false;
  1889. }
  1890. // This is effectively the intersection of isTrivialType and
  1891. // isStandardLayoutType. We implement it directly to avoid redundant
  1892. // conversions from a type to a CXXRecordDecl.
  1893. bool QualType::isCXX11PODType(ASTContext &Context) const {
  1894. const Type *ty = getTypePtr();
  1895. if (ty->isDependentType())
  1896. return false;
  1897. if (Context.getLangOpts().ObjCAutoRefCount) {
  1898. switch (getObjCLifetime()) {
  1899. case Qualifiers::OCL_ExplicitNone:
  1900. return true;
  1901. case Qualifiers::OCL_Strong:
  1902. case Qualifiers::OCL_Weak:
  1903. case Qualifiers::OCL_Autoreleasing:
  1904. return false;
  1905. case Qualifiers::OCL_None:
  1906. break;
  1907. }
  1908. }
  1909. // C++11 [basic.types]p9:
  1910. // Scalar types, POD classes, arrays of such types, and cv-qualified
  1911. // versions of these types are collectively called trivial types.
  1912. const Type *BaseTy = ty->getBaseElementTypeUnsafe();
  1913. assert(BaseTy && "NULL element type");
  1914. // Return false for incomplete types after skipping any incomplete array
  1915. // types which are expressly allowed by the standard and thus our API.
  1916. if (BaseTy->isIncompleteType())
  1917. return false;
  1918. // As an extension, Clang treats vector types as Scalar types.
  1919. if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
  1920. if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
  1921. if (const CXXRecordDecl *ClassDecl =
  1922. dyn_cast<CXXRecordDecl>(RT->getDecl())) {
  1923. // C++11 [class]p10:
  1924. // A POD struct is a non-union class that is both a trivial class [...]
  1925. if (!ClassDecl->isTrivial()) return false;
  1926. // C++11 [class]p10:
  1927. // A POD struct is a non-union class that is both a trivial class and
  1928. // a standard-layout class [...]
  1929. if (!ClassDecl->isStandardLayout()) return false;
  1930. // C++11 [class]p10:
  1931. // A POD struct is a non-union class that is both a trivial class and
  1932. // a standard-layout class, and has no non-static data members of type
  1933. // non-POD struct, non-POD union (or array of such types). [...]
  1934. //
  1935. // We don't directly query the recursive aspect as the requirements for
  1936. // both standard-layout classes and trivial classes apply recursively
  1937. // already.
  1938. }
  1939. return true;
  1940. }
  1941. // No other types can match.
  1942. return false;
  1943. }
  1944. bool Type::isPromotableIntegerType() const {
  1945. if (const BuiltinType *BT = getAs<BuiltinType>())
  1946. switch (BT->getKind()) {
  1947. case BuiltinType::Bool:
  1948. case BuiltinType::Char_S:
  1949. case BuiltinType::Char_U:
  1950. case BuiltinType::SChar:
  1951. case BuiltinType::UChar:
  1952. case BuiltinType::Short:
  1953. case BuiltinType::UShort:
  1954. case BuiltinType::WChar_S:
  1955. case BuiltinType::WChar_U:
  1956. case BuiltinType::Char16:
  1957. case BuiltinType::Char32:
  1958. return true;
  1959. default:
  1960. return false;
  1961. }
  1962. // Enumerated types are promotable to their compatible integer types
  1963. // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
  1964. if (const EnumType *ET = getAs<EnumType>()){
  1965. if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
  1966. || ET->getDecl()->isScoped())
  1967. return false;
  1968. return true;
  1969. }
  1970. return false;
  1971. }
  1972. bool Type::isSpecifierType() const {
  1973. // Note that this intentionally does not use the canonical type.
  1974. switch (getTypeClass()) {
  1975. case Builtin:
  1976. case Record:
  1977. case Enum:
  1978. case Typedef:
  1979. case Complex:
  1980. case TypeOfExpr:
  1981. case TypeOf:
  1982. case TemplateTypeParm:
  1983. case SubstTemplateTypeParm:
  1984. case TemplateSpecialization:
  1985. case Elaborated:
  1986. case DependentName:
  1987. case DependentTemplateSpecialization:
  1988. case ObjCInterface:
  1989. case ObjCObject:
  1990. case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
  1991. return true;
  1992. default:
  1993. return false;
  1994. }
  1995. }
  1996. ElaboratedTypeKeyword
  1997. TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
  1998. switch (TypeSpec) {
  1999. default: return ETK_None;
  2000. case TST_typename: return ETK_Typename;
  2001. case TST_class: return ETK_Class;
  2002. case TST_struct: return ETK_Struct;
  2003. case TST_interface: return ETK_Interface;
  2004. case TST_union: return ETK_Union;
  2005. case TST_enum: return ETK_Enum;
  2006. }
  2007. }
  2008. TagTypeKind
  2009. TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
  2010. switch(TypeSpec) {
  2011. case TST_class: return TTK_Class;
  2012. case TST_struct: return TTK_Struct;
  2013. case TST_interface: return TTK_Interface;
  2014. case TST_union: return TTK_Union;
  2015. case TST_enum: return TTK_Enum;
  2016. }
  2017. llvm_unreachable("Type specifier is not a tag type kind.");
  2018. }
  2019. ElaboratedTypeKeyword
  2020. TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
  2021. switch (Kind) {
  2022. case TTK_Class: return ETK_Class;
  2023. case TTK_Struct: return ETK_Struct;
  2024. case TTK_Interface: return ETK_Interface;
  2025. case TTK_Union: return ETK_Union;
  2026. case TTK_Enum: return ETK_Enum;
  2027. }
  2028. llvm_unreachable("Unknown tag type kind.");
  2029. }
  2030. TagTypeKind
  2031. TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
  2032. switch (Keyword) {
  2033. case ETK_Class: return TTK_Class;
  2034. case ETK_Struct: return TTK_Struct;
  2035. case ETK_Interface: return TTK_Interface;
  2036. case ETK_Union: return TTK_Union;
  2037. case ETK_Enum: return TTK_Enum;
  2038. case ETK_None: // Fall through.
  2039. case ETK_Typename:
  2040. llvm_unreachable("Elaborated type keyword is not a tag type kind.");
  2041. }
  2042. llvm_unreachable("Unknown elaborated type keyword.");
  2043. }
  2044. bool
  2045. TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
  2046. switch (Keyword) {
  2047. case ETK_None:
  2048. case ETK_Typename:
  2049. return false;
  2050. case ETK_Class:
  2051. case ETK_Struct:
  2052. case ETK_Interface:
  2053. case ETK_Union:
  2054. case ETK_Enum:
  2055. return true;
  2056. }
  2057. llvm_unreachable("Unknown elaborated type keyword.");
  2058. }
  2059. StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
  2060. switch (Keyword) {
  2061. case ETK_None: return "";
  2062. case ETK_Typename: return "typename";
  2063. case ETK_Class: return "class";
  2064. case ETK_Struct: return "struct";
  2065. case ETK_Interface: return "__interface";
  2066. case ETK_Union: return "union";
  2067. case ETK_Enum: return "enum";
  2068. }
  2069. llvm_unreachable("Unknown elaborated type keyword.");
  2070. }
  2071. DependentTemplateSpecializationType::DependentTemplateSpecializationType(
  2072. ElaboratedTypeKeyword Keyword,
  2073. NestedNameSpecifier *NNS, const IdentifierInfo *Name,
  2074. unsigned NumArgs, const TemplateArgument *Args,
  2075. QualType Canon)
  2076. : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
  2077. /*VariablyModified=*/false,
  2078. NNS && NNS->containsUnexpandedParameterPack()),
  2079. NNS(NNS), Name(Name), NumArgs(NumArgs) {
  2080. assert((!NNS || NNS->isDependent()) &&
  2081. "DependentTemplateSpecializatonType requires dependent qualifier");
  2082. for (unsigned I = 0; I != NumArgs; ++I) {
  2083. if (Args[I].containsUnexpandedParameterPack())
  2084. setContainsUnexpandedParameterPack();
  2085. new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
  2086. }
  2087. }
  2088. void
  2089. DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
  2090. const ASTContext &Context,
  2091. ElaboratedTypeKeyword Keyword,
  2092. NestedNameSpecifier *Qualifier,
  2093. const IdentifierInfo *Name,
  2094. unsigned NumArgs,
  2095. const TemplateArgument *Args) {
  2096. ID.AddInteger(Keyword);
  2097. ID.AddPointer(Qualifier);
  2098. ID.AddPointer(Name);
  2099. for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
  2100. Args[Idx].Profile(ID, Context);
  2101. }
  2102. bool Type::isElaboratedTypeSpecifier() const {
  2103. ElaboratedTypeKeyword Keyword;
  2104. if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
  2105. Keyword = Elab->getKeyword();
  2106. else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
  2107. Keyword = DepName->getKeyword();
  2108. else if (const DependentTemplateSpecializationType *DepTST =
  2109. dyn_cast<DependentTemplateSpecializationType>(this))
  2110. Keyword = DepTST->getKeyword();
  2111. else
  2112. return false;
  2113. return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
  2114. }
  2115. const char *Type::getTypeClassName() const {
  2116. switch (TypeBits.TC) {
  2117. #define ABSTRACT_TYPE(Derived, Base)
  2118. #define TYPE(Derived, Base) case Derived: return #Derived;
  2119. #include "clang/AST/TypeNodes.def"
  2120. }
  2121. llvm_unreachable("Invalid type class.");
  2122. }
  2123. StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
  2124. switch (getKind()) {
  2125. case Void:
  2126. return "void";
  2127. case Bool:
  2128. return Policy.Bool ? "bool" : "_Bool";
  2129. case Char_S:
  2130. return "char";
  2131. case Char_U:
  2132. return "char";
  2133. case SChar:
  2134. return "signed char";
  2135. case Short:
  2136. return "short";
  2137. case Int:
  2138. return "int";
  2139. case Long:
  2140. return "long";
  2141. case LongLong:
  2142. return "long long";
  2143. case Int128:
  2144. return "__int128";
  2145. case UChar:
  2146. return "unsigned char";
  2147. case UShort:
  2148. return "unsigned short";
  2149. case UInt:
  2150. return "unsigned int";
  2151. case ULong:
  2152. return "unsigned long";
  2153. case ULongLong:
  2154. return "unsigned long long";
  2155. case UInt128:
  2156. return "unsigned __int128";
  2157. case Half:
  2158. return Policy.Half ? "half" : "__fp16";
  2159. case Float:
  2160. return "float";
  2161. case Double:
  2162. return "double";
  2163. case LongDouble:
  2164. return "long double";
  2165. case WChar_S:
  2166. case WChar_U:
  2167. return Policy.MSWChar ? "__wchar_t" : "wchar_t";
  2168. case Char16:
  2169. return "char16_t";
  2170. case Char32:
  2171. return "char32_t";
  2172. case NullPtr:
  2173. return "nullptr_t";
  2174. case Overload:
  2175. return "<overloaded function type>";
  2176. case BoundMember:
  2177. return "<bound member function type>";
  2178. case PseudoObject:
  2179. return "<pseudo-object type>";
  2180. case Dependent:
  2181. return "<dependent type>";
  2182. case UnknownAny:
  2183. return "<unknown type>";
  2184. case ARCUnbridgedCast:
  2185. return "<ARC unbridged cast type>";
  2186. case BuiltinFn:
  2187. return "<builtin fn type>";
  2188. case ObjCId:
  2189. return "id";
  2190. case ObjCClass:
  2191. return "Class";
  2192. case ObjCSel:
  2193. return "SEL";
  2194. case OCLImage1d:
  2195. return "image1d_t";
  2196. case OCLImage1dArray:
  2197. return "image1d_array_t";
  2198. case OCLImage1dBuffer:
  2199. return "image1d_buffer_t";
  2200. case OCLImage2d:
  2201. return "image2d_t";
  2202. case OCLImage2dArray:
  2203. return "image2d_array_t";
  2204. case OCLImage2dDepth:
  2205. return "image2d_depth_t";
  2206. case OCLImage2dArrayDepth:
  2207. return "image2d_array_depth_t";
  2208. case OCLImage2dMSAA:
  2209. return "image2d_msaa_t";
  2210. case OCLImage2dArrayMSAA:
  2211. return "image2d_array_msaa_t";
  2212. case OCLImage2dMSAADepth:
  2213. return "image2d_msaa_depth_t";
  2214. case OCLImage2dArrayMSAADepth:
  2215. return "image2d_array_msaa_depth_t";
  2216. case OCLImage3d:
  2217. return "image3d_t";
  2218. case OCLSampler:
  2219. return "sampler_t";
  2220. case OCLEvent:
  2221. return "event_t";
  2222. case OCLClkEvent:
  2223. return "clk_event_t";
  2224. case OCLQueue:
  2225. return "queue_t";
  2226. case OCLNDRange:
  2227. return "ndrange_t";
  2228. case OCLReserveID:
  2229. return "reserve_id_t";
  2230. case OMPArraySection:
  2231. return "<OpenMP array section type>";
  2232. }
  2233. llvm_unreachable("Invalid builtin type.");
  2234. }
  2235. QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
  2236. if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
  2237. return RefType->getPointeeType();
  2238. // C++0x [basic.lval]:
  2239. // Class prvalues can have cv-qualified types; non-class prvalues always
  2240. // have cv-unqualified types.
  2241. //
  2242. // See also C99 6.3.2.1p2.
  2243. if (!Context.getLangOpts().CPlusPlus ||
  2244. (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
  2245. return getUnqualifiedType();
  2246. return *this;
  2247. }
  2248. StringRef FunctionType::getNameForCallConv(CallingConv CC) {
  2249. switch (CC) {
  2250. case CC_C: return "cdecl";
  2251. case CC_X86StdCall: return "stdcall";
  2252. case CC_X86FastCall: return "fastcall";
  2253. case CC_X86ThisCall: return "thiscall";
  2254. case CC_X86Pascal: return "pascal";
  2255. case CC_X86VectorCall: return "vectorcall";
  2256. case CC_X86_64Win64: return "ms_abi";
  2257. case CC_X86_64SysV: return "sysv_abi";
  2258. case CC_AAPCS: return "aapcs";
  2259. case CC_AAPCS_VFP: return "aapcs-vfp";
  2260. case CC_IntelOclBicc: return "intel_ocl_bicc";
  2261. case CC_SpirFunction: return "spir_function";
  2262. case CC_SpirKernel: return "spir_kernel";
  2263. }
  2264. llvm_unreachable("Invalid calling convention.");
  2265. }
  2266. FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
  2267. QualType canonical,
  2268. const ExtProtoInfo &epi)
  2269. : FunctionType(FunctionProto, result, canonical,
  2270. result->isDependentType(),
  2271. result->isInstantiationDependentType(),
  2272. result->isVariablyModifiedType(),
  2273. result->containsUnexpandedParameterPack(), epi.ExtInfo),
  2274. NumParams(params.size()),
  2275. NumExceptions(epi.ExceptionSpec.Exceptions.size()),
  2276. ExceptionSpecType(epi.ExceptionSpec.Type),
  2277. HasAnyConsumedParams(epi.ConsumedParameters != nullptr),
  2278. Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn) {
  2279. assert(NumParams == params.size() && "function has too many parameters");
  2280. FunctionTypeBits.TypeQuals = epi.TypeQuals;
  2281. FunctionTypeBits.RefQualifier = epi.RefQualifier;
  2282. // Fill in the trailing argument array.
  2283. QualType *argSlot = reinterpret_cast<QualType*>(this+1);
  2284. for (unsigned i = 0; i != NumParams; ++i) {
  2285. if (params[i]->isDependentType())
  2286. setDependent();
  2287. else if (params[i]->isInstantiationDependentType())
  2288. setInstantiationDependent();
  2289. if (params[i]->containsUnexpandedParameterPack())
  2290. setContainsUnexpandedParameterPack();
  2291. argSlot[i] = params[i];
  2292. }
  2293. if (getExceptionSpecType() == EST_Dynamic) {
  2294. // Fill in the exception array.
  2295. QualType *exnSlot = argSlot + NumParams;
  2296. unsigned I = 0;
  2297. for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
  2298. // Note that a dependent exception specification does *not* make
  2299. // a type dependent; it's not even part of the C++ type system.
  2300. if (ExceptionType->isInstantiationDependentType())
  2301. setInstantiationDependent();
  2302. if (ExceptionType->containsUnexpandedParameterPack())
  2303. setContainsUnexpandedParameterPack();
  2304. exnSlot[I++] = ExceptionType;
  2305. }
  2306. } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
  2307. // Store the noexcept expression and context.
  2308. Expr **noexSlot = reinterpret_cast<Expr **>(argSlot + NumParams);
  2309. *noexSlot = epi.ExceptionSpec.NoexceptExpr;
  2310. if (epi.ExceptionSpec.NoexceptExpr) {
  2311. if (epi.ExceptionSpec.NoexceptExpr->isValueDependent() ||
  2312. epi.ExceptionSpec.NoexceptExpr->isInstantiationDependent())
  2313. setInstantiationDependent();
  2314. if (epi.ExceptionSpec.NoexceptExpr->containsUnexpandedParameterPack())
  2315. setContainsUnexpandedParameterPack();
  2316. }
  2317. } else if (getExceptionSpecType() == EST_Uninstantiated) {
  2318. // Store the function decl from which we will resolve our
  2319. // exception specification.
  2320. FunctionDecl **slot =
  2321. reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
  2322. slot[0] = epi.ExceptionSpec.SourceDecl;
  2323. slot[1] = epi.ExceptionSpec.SourceTemplate;
  2324. // This exception specification doesn't make the type dependent, because
  2325. // it's not instantiated as part of instantiating the type.
  2326. } else if (getExceptionSpecType() == EST_Unevaluated) {
  2327. // Store the function decl from which we will resolve our
  2328. // exception specification.
  2329. FunctionDecl **slot =
  2330. reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
  2331. slot[0] = epi.ExceptionSpec.SourceDecl;
  2332. }
  2333. if (epi.ConsumedParameters) {
  2334. bool *consumedParams = const_cast<bool *>(getConsumedParamsBuffer());
  2335. for (unsigned i = 0; i != NumParams; ++i)
  2336. consumedParams[i] = epi.ConsumedParameters[i];
  2337. }
  2338. }
  2339. bool FunctionProtoType::hasDependentExceptionSpec() const {
  2340. if (Expr *NE = getNoexceptExpr())
  2341. return NE->isValueDependent();
  2342. for (QualType ET : exceptions())
  2343. // A pack expansion with a non-dependent pattern is still dependent,
  2344. // because we don't know whether the pattern is in the exception spec
  2345. // or not (that depends on whether the pack has 0 expansions).
  2346. if (ET->isDependentType() || ET->getAs<PackExpansionType>())
  2347. return true;
  2348. return false;
  2349. }
  2350. FunctionProtoType::NoexceptResult
  2351. FunctionProtoType::getNoexceptSpec(const ASTContext &ctx) const {
  2352. ExceptionSpecificationType est = getExceptionSpecType();
  2353. if (est == EST_BasicNoexcept)
  2354. return NR_Nothrow;
  2355. if (est != EST_ComputedNoexcept)
  2356. return NR_NoNoexcept;
  2357. Expr *noexceptExpr = getNoexceptExpr();
  2358. if (!noexceptExpr)
  2359. return NR_BadNoexcept;
  2360. if (noexceptExpr->isValueDependent())
  2361. return NR_Dependent;
  2362. llvm::APSInt value;
  2363. bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, nullptr,
  2364. /*evaluated*/false);
  2365. (void)isICE;
  2366. assert(isICE && "AST should not contain bad noexcept expressions.");
  2367. return value.getBoolValue() ? NR_Nothrow : NR_Throw;
  2368. }
  2369. bool FunctionProtoType::isNothrow(const ASTContext &Ctx,
  2370. bool ResultIfDependent) const {
  2371. ExceptionSpecificationType EST = getExceptionSpecType();
  2372. assert(EST != EST_Unevaluated && EST != EST_Uninstantiated);
  2373. if (EST == EST_DynamicNone || EST == EST_BasicNoexcept)
  2374. return true;
  2375. if (EST == EST_Dynamic && ResultIfDependent) {
  2376. // A dynamic exception specification is throwing unless every exception
  2377. // type is an (unexpanded) pack expansion type.
  2378. for (unsigned I = 0, N = NumExceptions; I != N; ++I)
  2379. if (!getExceptionType(I)->getAs<PackExpansionType>())
  2380. return false;
  2381. return ResultIfDependent;
  2382. }
  2383. if (EST != EST_ComputedNoexcept)
  2384. return false;
  2385. NoexceptResult NR = getNoexceptSpec(Ctx);
  2386. if (NR == NR_Dependent)
  2387. return ResultIfDependent;
  2388. return NR == NR_Nothrow;
  2389. }
  2390. bool FunctionProtoType::isTemplateVariadic() const {
  2391. for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
  2392. if (isa<PackExpansionType>(getParamType(ArgIdx - 1)))
  2393. return true;
  2394. return false;
  2395. }
  2396. void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
  2397. const QualType *ArgTys, unsigned NumParams,
  2398. const ExtProtoInfo &epi,
  2399. const ASTContext &Context) {
  2400. // We have to be careful not to get ambiguous profile encodings.
  2401. // Note that valid type pointers are never ambiguous with anything else.
  2402. //
  2403. // The encoding grammar begins:
  2404. // type type* bool int bool
  2405. // If that final bool is true, then there is a section for the EH spec:
  2406. // bool type*
  2407. // This is followed by an optional "consumed argument" section of the
  2408. // same length as the first type sequence:
  2409. // bool*
  2410. // Finally, we have the ext info and trailing return type flag:
  2411. // int bool
  2412. //
  2413. // There is no ambiguity between the consumed arguments and an empty EH
  2414. // spec because of the leading 'bool' which unambiguously indicates
  2415. // whether the following bool is the EH spec or part of the arguments.
  2416. ID.AddPointer(Result.getAsOpaquePtr());
  2417. for (unsigned i = 0; i != NumParams; ++i)
  2418. ID.AddPointer(ArgTys[i].getAsOpaquePtr());
  2419. // This method is relatively performance sensitive, so as a performance
  2420. // shortcut, use one AddInteger call instead of four for the next four
  2421. // fields.
  2422. assert(!(unsigned(epi.Variadic) & ~1) &&
  2423. !(unsigned(epi.TypeQuals) & ~255) &&
  2424. !(unsigned(epi.RefQualifier) & ~3) &&
  2425. !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
  2426. "Values larger than expected.");
  2427. ID.AddInteger(unsigned(epi.Variadic) +
  2428. (epi.TypeQuals << 1) +
  2429. (epi.RefQualifier << 9) +
  2430. (epi.ExceptionSpec.Type << 11));
  2431. if (epi.ExceptionSpec.Type == EST_Dynamic) {
  2432. for (QualType Ex : epi.ExceptionSpec.Exceptions)
  2433. ID.AddPointer(Ex.getAsOpaquePtr());
  2434. } else if (epi.ExceptionSpec.Type == EST_ComputedNoexcept &&
  2435. epi.ExceptionSpec.NoexceptExpr) {
  2436. epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, false);
  2437. } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
  2438. epi.ExceptionSpec.Type == EST_Unevaluated) {
  2439. ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
  2440. }
  2441. if (epi.ConsumedParameters) {
  2442. for (unsigned i = 0; i != NumParams; ++i)
  2443. ID.AddBoolean(epi.ConsumedParameters[i]);
  2444. }
  2445. epi.ExtInfo.Profile(ID);
  2446. ID.AddBoolean(epi.HasTrailingReturn);
  2447. }
  2448. void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
  2449. const ASTContext &Ctx) {
  2450. Profile(ID, getReturnType(), param_type_begin(), NumParams, getExtProtoInfo(),
  2451. Ctx);
  2452. }
  2453. QualType TypedefType::desugar() const {
  2454. return getDecl()->getUnderlyingType();
  2455. }
  2456. TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
  2457. : Type(TypeOfExpr, can, E->isTypeDependent(),
  2458. E->isInstantiationDependent(),
  2459. E->getType()->isVariablyModifiedType(),
  2460. E->containsUnexpandedParameterPack()),
  2461. TOExpr(E) {
  2462. }
  2463. bool TypeOfExprType::isSugared() const {
  2464. return !TOExpr->isTypeDependent();
  2465. }
  2466. QualType TypeOfExprType::desugar() const {
  2467. if (isSugared())
  2468. return getUnderlyingExpr()->getType();
  2469. return QualType(this, 0);
  2470. }
  2471. void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
  2472. const ASTContext &Context, Expr *E) {
  2473. E->Profile(ID, Context, true);
  2474. }
  2475. DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
  2476. // C++11 [temp.type]p2: "If an expression e involves a template parameter,
  2477. // decltype(e) denotes a unique dependent type." Hence a decltype type is
  2478. // type-dependent even if its expression is only instantiation-dependent.
  2479. : Type(Decltype, can, E->isInstantiationDependent(),
  2480. E->isInstantiationDependent(),
  2481. E->getType()->isVariablyModifiedType(),
  2482. E->containsUnexpandedParameterPack()),
  2483. E(E),
  2484. UnderlyingType(underlyingType) {
  2485. }
  2486. bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
  2487. QualType DecltypeType::desugar() const {
  2488. if (isSugared())
  2489. return getUnderlyingType();
  2490. return QualType(this, 0);
  2491. }
  2492. DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
  2493. : DecltypeType(E, Context.DependentTy), Context(Context) { }
  2494. void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
  2495. const ASTContext &Context, Expr *E) {
  2496. E->Profile(ID, Context, true);
  2497. }
  2498. TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
  2499. : Type(TC, can, D->isDependentType(),
  2500. /*InstantiationDependent=*/D->isDependentType(),
  2501. /*VariablyModified=*/false,
  2502. /*ContainsUnexpandedParameterPack=*/false),
  2503. decl(const_cast<TagDecl*>(D)) {}
  2504. static TagDecl *getInterestingTagDecl(TagDecl *decl) {
  2505. for (auto I : decl->redecls()) {
  2506. if (I->isCompleteDefinition() || I->isBeingDefined())
  2507. return I;
  2508. }
  2509. // If there's no definition (not even in progress), return what we have.
  2510. return decl;
  2511. }
  2512. UnaryTransformType::UnaryTransformType(QualType BaseType,
  2513. QualType UnderlyingType,
  2514. UTTKind UKind,
  2515. QualType CanonicalType)
  2516. : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(),
  2517. UnderlyingType->isInstantiationDependentType(),
  2518. UnderlyingType->isVariablyModifiedType(),
  2519. BaseType->containsUnexpandedParameterPack())
  2520. , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
  2521. {}
  2522. TagDecl *TagType::getDecl() const {
  2523. return getInterestingTagDecl(decl);
  2524. }
  2525. bool TagType::isBeingDefined() const {
  2526. return getDecl()->isBeingDefined();
  2527. }
  2528. bool AttributedType::isQualifier() const {
  2529. switch (getAttrKind()) {
  2530. // These are type qualifiers in the traditional C sense: they annotate
  2531. // something about a specific value/variable of a type. (They aren't
  2532. // always part of the canonical type, though.)
  2533. case AttributedType::attr_address_space:
  2534. case AttributedType::attr_objc_gc:
  2535. case AttributedType::attr_objc_ownership:
  2536. case AttributedType::attr_objc_inert_unsafe_unretained:
  2537. case AttributedType::attr_nonnull:
  2538. case AttributedType::attr_nullable:
  2539. case AttributedType::attr_null_unspecified:
  2540. return true;
  2541. // These aren't qualifiers; they rewrite the modified type to be a
  2542. // semantically different type.
  2543. case AttributedType::attr_regparm:
  2544. case AttributedType::attr_vector_size:
  2545. case AttributedType::attr_neon_vector_type:
  2546. case AttributedType::attr_neon_polyvector_type:
  2547. case AttributedType::attr_pcs:
  2548. case AttributedType::attr_pcs_vfp:
  2549. case AttributedType::attr_noreturn:
  2550. case AttributedType::attr_cdecl:
  2551. case AttributedType::attr_fastcall:
  2552. case AttributedType::attr_stdcall:
  2553. case AttributedType::attr_thiscall:
  2554. case AttributedType::attr_pascal:
  2555. case AttributedType::attr_vectorcall:
  2556. case AttributedType::attr_inteloclbicc:
  2557. case AttributedType::attr_ms_abi:
  2558. case AttributedType::attr_sysv_abi:
  2559. case AttributedType::attr_ptr32:
  2560. case AttributedType::attr_ptr64:
  2561. case AttributedType::attr_sptr:
  2562. case AttributedType::attr_uptr:
  2563. case AttributedType::attr_objc_kindof:
  2564. return false;
  2565. }
  2566. llvm_unreachable("bad attributed type kind");
  2567. }
  2568. bool AttributedType::isMSTypeSpec() const {
  2569. switch (getAttrKind()) {
  2570. default: return false;
  2571. case attr_ptr32:
  2572. case attr_ptr64:
  2573. case attr_sptr:
  2574. case attr_uptr:
  2575. return true;
  2576. }
  2577. llvm_unreachable("invalid attr kind");
  2578. }
  2579. bool AttributedType::isCallingConv() const {
  2580. switch (getAttrKind()) {
  2581. case attr_ptr32:
  2582. case attr_ptr64:
  2583. case attr_sptr:
  2584. case attr_uptr:
  2585. case attr_address_space:
  2586. case attr_regparm:
  2587. case attr_vector_size:
  2588. case attr_neon_vector_type:
  2589. case attr_neon_polyvector_type:
  2590. case attr_objc_gc:
  2591. case attr_objc_ownership:
  2592. case attr_objc_inert_unsafe_unretained:
  2593. case attr_noreturn:
  2594. case attr_nonnull:
  2595. case attr_nullable:
  2596. case attr_null_unspecified:
  2597. case attr_objc_kindof:
  2598. return false;
  2599. case attr_pcs:
  2600. case attr_pcs_vfp:
  2601. case attr_cdecl:
  2602. case attr_fastcall:
  2603. case attr_stdcall:
  2604. case attr_thiscall:
  2605. case attr_vectorcall:
  2606. case attr_pascal:
  2607. case attr_ms_abi:
  2608. case attr_sysv_abi:
  2609. case attr_inteloclbicc:
  2610. return true;
  2611. }
  2612. llvm_unreachable("invalid attr kind");
  2613. }
  2614. CXXRecordDecl *InjectedClassNameType::getDecl() const {
  2615. return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
  2616. }
  2617. IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
  2618. return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
  2619. }
  2620. SubstTemplateTypeParmPackType::
  2621. SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
  2622. QualType Canon,
  2623. const TemplateArgument &ArgPack)
  2624. : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true),
  2625. Replaced(Param),
  2626. Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size())
  2627. {
  2628. }
  2629. TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
  2630. return TemplateArgument(llvm::makeArrayRef(Arguments, NumArguments));
  2631. }
  2632. void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
  2633. Profile(ID, getReplacedParameter(), getArgumentPack());
  2634. }
  2635. void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
  2636. const TemplateTypeParmType *Replaced,
  2637. const TemplateArgument &ArgPack) {
  2638. ID.AddPointer(Replaced);
  2639. ID.AddInteger(ArgPack.pack_size());
  2640. for (const auto &P : ArgPack.pack_elements())
  2641. ID.AddPointer(P.getAsType().getAsOpaquePtr());
  2642. }
  2643. bool TemplateSpecializationType::
  2644. anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
  2645. bool &InstantiationDependent) {
  2646. return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size(),
  2647. InstantiationDependent);
  2648. }
  2649. bool TemplateSpecializationType::
  2650. anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N,
  2651. bool &InstantiationDependent) {
  2652. for (unsigned i = 0; i != N; ++i) {
  2653. if (Args[i].getArgument().isDependent()) {
  2654. InstantiationDependent = true;
  2655. return true;
  2656. }
  2657. if (Args[i].getArgument().isInstantiationDependent())
  2658. InstantiationDependent = true;
  2659. }
  2660. return false;
  2661. }
  2662. TemplateSpecializationType::
  2663. TemplateSpecializationType(TemplateName T,
  2664. const TemplateArgument *Args, unsigned NumArgs,
  2665. QualType Canon, QualType AliasedType)
  2666. : Type(TemplateSpecialization,
  2667. Canon.isNull()? QualType(this, 0) : Canon,
  2668. Canon.isNull()? true : Canon->isDependentType(),
  2669. Canon.isNull()? true : Canon->isInstantiationDependentType(),
  2670. false,
  2671. T.containsUnexpandedParameterPack()),
  2672. Template(T), NumArgs(NumArgs), TypeAlias(!AliasedType.isNull()) {
  2673. assert(!T.getAsDependentTemplateName() &&
  2674. "Use DependentTemplateSpecializationType for dependent template-name");
  2675. assert((T.getKind() == TemplateName::Template ||
  2676. T.getKind() == TemplateName::SubstTemplateTemplateParm ||
  2677. T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
  2678. "Unexpected template name for TemplateSpecializationType");
  2679. TemplateArgument *TemplateArgs
  2680. = reinterpret_cast<TemplateArgument *>(this + 1);
  2681. for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
  2682. // Update instantiation-dependent and variably-modified bits.
  2683. // If the canonical type exists and is non-dependent, the template
  2684. // specialization type can be non-dependent even if one of the type
  2685. // arguments is. Given:
  2686. // template<typename T> using U = int;
  2687. // U<T> is always non-dependent, irrespective of the type T.
  2688. // However, U<Ts> contains an unexpanded parameter pack, even though
  2689. // its expansion (and thus its desugared type) doesn't.
  2690. if (Args[Arg].isInstantiationDependent())
  2691. setInstantiationDependent();
  2692. if (Args[Arg].getKind() == TemplateArgument::Type &&
  2693. Args[Arg].getAsType()->isVariablyModifiedType())
  2694. setVariablyModified();
  2695. if (Args[Arg].containsUnexpandedParameterPack())
  2696. setContainsUnexpandedParameterPack();
  2697. new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
  2698. }
  2699. // Store the aliased type if this is a type alias template specialization.
  2700. if (TypeAlias) {
  2701. TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
  2702. *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
  2703. }
  2704. }
  2705. void
  2706. TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
  2707. TemplateName T,
  2708. const TemplateArgument *Args,
  2709. unsigned NumArgs,
  2710. const ASTContext &Context) {
  2711. T.Profile(ID);
  2712. for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
  2713. Args[Idx].Profile(ID, Context);
  2714. }
  2715. QualType
  2716. QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
  2717. if (!hasNonFastQualifiers())
  2718. return QT.withFastQualifiers(getFastQualifiers());
  2719. return Context.getQualifiedType(QT, *this);
  2720. }
  2721. QualType
  2722. QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
  2723. if (!hasNonFastQualifiers())
  2724. return QualType(T, getFastQualifiers());
  2725. return Context.getQualifiedType(T, *this);
  2726. }
  2727. void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
  2728. QualType BaseType,
  2729. ArrayRef<QualType> typeArgs,
  2730. ArrayRef<ObjCProtocolDecl *> protocols,
  2731. bool isKindOf) {
  2732. ID.AddPointer(BaseType.getAsOpaquePtr());
  2733. ID.AddInteger(typeArgs.size());
  2734. for (auto typeArg : typeArgs)
  2735. ID.AddPointer(typeArg.getAsOpaquePtr());
  2736. ID.AddInteger(protocols.size());
  2737. for (auto proto : protocols)
  2738. ID.AddPointer(proto);
  2739. ID.AddBoolean(isKindOf);
  2740. }
  2741. void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
  2742. Profile(ID, getBaseType(), getTypeArgsAsWritten(),
  2743. llvm::makeArrayRef(qual_begin(), getNumProtocols()),
  2744. isKindOfTypeAsWritten());
  2745. }
  2746. namespace {
  2747. /// \brief The cached properties of a type.
  2748. class CachedProperties {
  2749. Linkage L;
  2750. bool local;
  2751. public:
  2752. CachedProperties(Linkage L, bool local) : L(L), local(local) {}
  2753. Linkage getLinkage() const { return L; }
  2754. bool hasLocalOrUnnamedType() const { return local; }
  2755. friend CachedProperties merge(CachedProperties L, CachedProperties R) {
  2756. Linkage MergedLinkage = minLinkage(L.L, R.L);
  2757. return CachedProperties(MergedLinkage,
  2758. L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
  2759. }
  2760. };
  2761. }
  2762. static CachedProperties computeCachedProperties(const Type *T);
  2763. namespace clang {
  2764. /// The type-property cache. This is templated so as to be
  2765. /// instantiated at an internal type to prevent unnecessary symbol
  2766. /// leakage.
  2767. template <class Private> class TypePropertyCache {
  2768. public:
  2769. static CachedProperties get(QualType T) {
  2770. return get(T.getTypePtr());
  2771. }
  2772. static CachedProperties get(const Type *T) {
  2773. ensure(T);
  2774. return CachedProperties(T->TypeBits.getLinkage(),
  2775. T->TypeBits.hasLocalOrUnnamedType());
  2776. }
  2777. static void ensure(const Type *T) {
  2778. // If the cache is valid, we're okay.
  2779. if (T->TypeBits.isCacheValid()) return;
  2780. // If this type is non-canonical, ask its canonical type for the
  2781. // relevant information.
  2782. if (!T->isCanonicalUnqualified()) {
  2783. const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
  2784. ensure(CT);
  2785. T->TypeBits.CacheValid = true;
  2786. T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
  2787. T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
  2788. return;
  2789. }
  2790. // Compute the cached properties and then set the cache.
  2791. CachedProperties Result = computeCachedProperties(T);
  2792. T->TypeBits.CacheValid = true;
  2793. T->TypeBits.CachedLinkage = Result.getLinkage();
  2794. T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
  2795. }
  2796. };
  2797. }
  2798. // Instantiate the friend template at a private class. In a
  2799. // reasonable implementation, these symbols will be internal.
  2800. // It is terrible that this is the best way to accomplish this.
  2801. namespace { class Private {}; }
  2802. typedef TypePropertyCache<Private> Cache;
  2803. static CachedProperties computeCachedProperties(const Type *T) {
  2804. switch (T->getTypeClass()) {
  2805. #define TYPE(Class,Base)
  2806. #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
  2807. #include "clang/AST/TypeNodes.def"
  2808. llvm_unreachable("didn't expect a non-canonical type here");
  2809. #define TYPE(Class,Base)
  2810. #define DEPENDENT_TYPE(Class,Base) case Type::Class:
  2811. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
  2812. #include "clang/AST/TypeNodes.def"
  2813. // Treat instantiation-dependent types as external.
  2814. assert(T->isInstantiationDependentType());
  2815. return CachedProperties(ExternalLinkage, false);
  2816. case Type::Auto:
  2817. // Give non-deduced 'auto' types external linkage. We should only see them
  2818. // here in error recovery.
  2819. return CachedProperties(ExternalLinkage, false);
  2820. case Type::Builtin:
  2821. // C++ [basic.link]p8:
  2822. // A type is said to have linkage if and only if:
  2823. // - it is a fundamental type (3.9.1); or
  2824. return CachedProperties(ExternalLinkage, false);
  2825. case Type::Record:
  2826. case Type::Enum: {
  2827. const TagDecl *Tag = cast<TagType>(T)->getDecl();
  2828. // C++ [basic.link]p8:
  2829. // - it is a class or enumeration type that is named (or has a name
  2830. // for linkage purposes (7.1.3)) and the name has linkage; or
  2831. // - it is a specialization of a class template (14); or
  2832. Linkage L = Tag->getLinkageInternal();
  2833. bool IsLocalOrUnnamed =
  2834. Tag->getDeclContext()->isFunctionOrMethod() ||
  2835. !Tag->hasNameForLinkage();
  2836. return CachedProperties(L, IsLocalOrUnnamed);
  2837. }
  2838. // C++ [basic.link]p8:
  2839. // - it is a compound type (3.9.2) other than a class or enumeration,
  2840. // compounded exclusively from types that have linkage; or
  2841. case Type::Complex:
  2842. return Cache::get(cast<ComplexType>(T)->getElementType());
  2843. case Type::Pointer:
  2844. return Cache::get(cast<PointerType>(T)->getPointeeType());
  2845. case Type::BlockPointer:
  2846. return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
  2847. case Type::LValueReference:
  2848. case Type::RValueReference:
  2849. return Cache::get(cast<ReferenceType>(T)->getPointeeType());
  2850. case Type::MemberPointer: {
  2851. const MemberPointerType *MPT = cast<MemberPointerType>(T);
  2852. return merge(Cache::get(MPT->getClass()),
  2853. Cache::get(MPT->getPointeeType()));
  2854. }
  2855. case Type::ConstantArray:
  2856. case Type::IncompleteArray:
  2857. case Type::VariableArray:
  2858. return Cache::get(cast<ArrayType>(T)->getElementType());
  2859. case Type::Vector:
  2860. case Type::ExtVector:
  2861. return Cache::get(cast<VectorType>(T)->getElementType());
  2862. case Type::FunctionNoProto:
  2863. return Cache::get(cast<FunctionType>(T)->getReturnType());
  2864. case Type::FunctionProto: {
  2865. const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
  2866. CachedProperties result = Cache::get(FPT->getReturnType());
  2867. for (const auto &ai : FPT->param_types())
  2868. result = merge(result, Cache::get(ai));
  2869. return result;
  2870. }
  2871. case Type::ObjCInterface: {
  2872. Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
  2873. return CachedProperties(L, false);
  2874. }
  2875. case Type::ObjCObject:
  2876. return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
  2877. case Type::ObjCObjectPointer:
  2878. return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
  2879. case Type::Atomic:
  2880. return Cache::get(cast<AtomicType>(T)->getValueType());
  2881. case Type::Pipe:
  2882. return Cache::get(cast<PipeType>(T)->getElementType());
  2883. }
  2884. llvm_unreachable("unhandled type class");
  2885. }
  2886. /// \brief Determine the linkage of this type.
  2887. Linkage Type::getLinkage() const {
  2888. Cache::ensure(this);
  2889. return TypeBits.getLinkage();
  2890. }
  2891. bool Type::hasUnnamedOrLocalType() const {
  2892. Cache::ensure(this);
  2893. return TypeBits.hasLocalOrUnnamedType();
  2894. }
  2895. static LinkageInfo computeLinkageInfo(QualType T);
  2896. static LinkageInfo computeLinkageInfo(const Type *T) {
  2897. switch (T->getTypeClass()) {
  2898. #define TYPE(Class,Base)
  2899. #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
  2900. #include "clang/AST/TypeNodes.def"
  2901. llvm_unreachable("didn't expect a non-canonical type here");
  2902. #define TYPE(Class,Base)
  2903. #define DEPENDENT_TYPE(Class,Base) case Type::Class:
  2904. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
  2905. #include "clang/AST/TypeNodes.def"
  2906. // Treat instantiation-dependent types as external.
  2907. assert(T->isInstantiationDependentType());
  2908. return LinkageInfo::external();
  2909. case Type::Builtin:
  2910. return LinkageInfo::external();
  2911. case Type::Auto:
  2912. return LinkageInfo::external();
  2913. case Type::Record:
  2914. case Type::Enum:
  2915. return cast<TagType>(T)->getDecl()->getLinkageAndVisibility();
  2916. case Type::Complex:
  2917. return computeLinkageInfo(cast<ComplexType>(T)->getElementType());
  2918. case Type::Pointer:
  2919. return computeLinkageInfo(cast<PointerType>(T)->getPointeeType());
  2920. case Type::BlockPointer:
  2921. return computeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
  2922. case Type::LValueReference:
  2923. case Type::RValueReference:
  2924. return computeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
  2925. case Type::MemberPointer: {
  2926. const MemberPointerType *MPT = cast<MemberPointerType>(T);
  2927. LinkageInfo LV = computeLinkageInfo(MPT->getClass());
  2928. LV.merge(computeLinkageInfo(MPT->getPointeeType()));
  2929. return LV;
  2930. }
  2931. case Type::ConstantArray:
  2932. case Type::IncompleteArray:
  2933. case Type::VariableArray:
  2934. return computeLinkageInfo(cast<ArrayType>(T)->getElementType());
  2935. case Type::Vector:
  2936. case Type::ExtVector:
  2937. return computeLinkageInfo(cast<VectorType>(T)->getElementType());
  2938. case Type::FunctionNoProto:
  2939. return computeLinkageInfo(cast<FunctionType>(T)->getReturnType());
  2940. case Type::FunctionProto: {
  2941. const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
  2942. LinkageInfo LV = computeLinkageInfo(FPT->getReturnType());
  2943. for (const auto &ai : FPT->param_types())
  2944. LV.merge(computeLinkageInfo(ai));
  2945. return LV;
  2946. }
  2947. case Type::ObjCInterface:
  2948. return cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
  2949. case Type::ObjCObject:
  2950. return computeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
  2951. case Type::ObjCObjectPointer:
  2952. return computeLinkageInfo(cast<ObjCObjectPointerType>(T)->getPointeeType());
  2953. case Type::Atomic:
  2954. return computeLinkageInfo(cast<AtomicType>(T)->getValueType());
  2955. case Type::Pipe:
  2956. return computeLinkageInfo(cast<PipeType>(T)->getElementType());
  2957. }
  2958. llvm_unreachable("unhandled type class");
  2959. }
  2960. static LinkageInfo computeLinkageInfo(QualType T) {
  2961. return computeLinkageInfo(T.getTypePtr());
  2962. }
  2963. bool Type::isLinkageValid() const {
  2964. if (!TypeBits.isCacheValid())
  2965. return true;
  2966. return computeLinkageInfo(getCanonicalTypeInternal()).getLinkage() ==
  2967. TypeBits.getLinkage();
  2968. }
  2969. LinkageInfo Type::getLinkageAndVisibility() const {
  2970. if (!isCanonicalUnqualified())
  2971. return computeLinkageInfo(getCanonicalTypeInternal());
  2972. LinkageInfo LV = computeLinkageInfo(this);
  2973. assert(LV.getLinkage() == getLinkage());
  2974. return LV;
  2975. }
  2976. Optional<NullabilityKind> Type::getNullability(const ASTContext &context) const {
  2977. QualType type(this, 0);
  2978. do {
  2979. // Check whether this is an attributed type with nullability
  2980. // information.
  2981. if (auto attributed = dyn_cast<AttributedType>(type.getTypePtr())) {
  2982. if (auto nullability = attributed->getImmediateNullability())
  2983. return nullability;
  2984. }
  2985. // Desugar the type. If desugaring does nothing, we're done.
  2986. QualType desugared = type.getSingleStepDesugaredType(context);
  2987. if (desugared.getTypePtr() == type.getTypePtr())
  2988. return None;
  2989. type = desugared;
  2990. } while (true);
  2991. }
  2992. bool Type::canHaveNullability() const {
  2993. QualType type = getCanonicalTypeInternal();
  2994. switch (type->getTypeClass()) {
  2995. // We'll only see canonical types here.
  2996. #define NON_CANONICAL_TYPE(Class, Parent) \
  2997. case Type::Class: \
  2998. llvm_unreachable("non-canonical type");
  2999. #define TYPE(Class, Parent)
  3000. #include "clang/AST/TypeNodes.def"
  3001. // Pointer types.
  3002. case Type::Pointer:
  3003. case Type::BlockPointer:
  3004. case Type::MemberPointer:
  3005. case Type::ObjCObjectPointer:
  3006. return true;
  3007. // Dependent types that could instantiate to pointer types.
  3008. case Type::UnresolvedUsing:
  3009. case Type::TypeOfExpr:
  3010. case Type::TypeOf:
  3011. case Type::Decltype:
  3012. case Type::UnaryTransform:
  3013. case Type::TemplateTypeParm:
  3014. case Type::SubstTemplateTypeParmPack:
  3015. case Type::DependentName:
  3016. case Type::DependentTemplateSpecialization:
  3017. return true;
  3018. // Dependent template specializations can instantiate to pointer
  3019. // types unless they're known to be specializations of a class
  3020. // template.
  3021. case Type::TemplateSpecialization:
  3022. if (TemplateDecl *templateDecl
  3023. = cast<TemplateSpecializationType>(type.getTypePtr())
  3024. ->getTemplateName().getAsTemplateDecl()) {
  3025. if (isa<ClassTemplateDecl>(templateDecl))
  3026. return false;
  3027. }
  3028. return true;
  3029. // auto is considered dependent when it isn't deduced.
  3030. case Type::Auto:
  3031. return !cast<AutoType>(type.getTypePtr())->isDeduced();
  3032. case Type::Builtin:
  3033. switch (cast<BuiltinType>(type.getTypePtr())->getKind()) {
  3034. // Signed, unsigned, and floating-point types cannot have nullability.
  3035. #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
  3036. #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
  3037. #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
  3038. #define BUILTIN_TYPE(Id, SingletonId)
  3039. #include "clang/AST/BuiltinTypes.def"
  3040. return false;
  3041. // Dependent types that could instantiate to a pointer type.
  3042. case BuiltinType::Dependent:
  3043. case BuiltinType::Overload:
  3044. case BuiltinType::BoundMember:
  3045. case BuiltinType::PseudoObject:
  3046. case BuiltinType::UnknownAny:
  3047. case BuiltinType::ARCUnbridgedCast:
  3048. return true;
  3049. case BuiltinType::Void:
  3050. case BuiltinType::ObjCId:
  3051. case BuiltinType::ObjCClass:
  3052. case BuiltinType::ObjCSel:
  3053. case BuiltinType::OCLImage1d:
  3054. case BuiltinType::OCLImage1dArray:
  3055. case BuiltinType::OCLImage1dBuffer:
  3056. case BuiltinType::OCLImage2d:
  3057. case BuiltinType::OCLImage2dArray:
  3058. case BuiltinType::OCLImage2dDepth:
  3059. case BuiltinType::OCLImage2dArrayDepth:
  3060. case BuiltinType::OCLImage2dMSAA:
  3061. case BuiltinType::OCLImage2dArrayMSAA:
  3062. case BuiltinType::OCLImage2dMSAADepth:
  3063. case BuiltinType::OCLImage2dArrayMSAADepth:
  3064. case BuiltinType::OCLImage3d:
  3065. case BuiltinType::OCLSampler:
  3066. case BuiltinType::OCLEvent:
  3067. case BuiltinType::OCLClkEvent:
  3068. case BuiltinType::OCLQueue:
  3069. case BuiltinType::OCLNDRange:
  3070. case BuiltinType::OCLReserveID:
  3071. case BuiltinType::BuiltinFn:
  3072. case BuiltinType::NullPtr:
  3073. case BuiltinType::OMPArraySection:
  3074. return false;
  3075. }
  3076. // Non-pointer types.
  3077. case Type::Complex:
  3078. case Type::LValueReference:
  3079. case Type::RValueReference:
  3080. case Type::ConstantArray:
  3081. case Type::IncompleteArray:
  3082. case Type::VariableArray:
  3083. case Type::DependentSizedArray:
  3084. case Type::DependentSizedExtVector:
  3085. case Type::Vector:
  3086. case Type::ExtVector:
  3087. case Type::FunctionProto:
  3088. case Type::FunctionNoProto:
  3089. case Type::Record:
  3090. case Type::Enum:
  3091. case Type::InjectedClassName:
  3092. case Type::PackExpansion:
  3093. case Type::ObjCObject:
  3094. case Type::ObjCInterface:
  3095. case Type::Atomic:
  3096. case Type::Pipe:
  3097. return false;
  3098. }
  3099. llvm_unreachable("bad type kind!");
  3100. }
  3101. llvm::Optional<NullabilityKind> AttributedType::getImmediateNullability() const {
  3102. if (getAttrKind() == AttributedType::attr_nonnull)
  3103. return NullabilityKind::NonNull;
  3104. if (getAttrKind() == AttributedType::attr_nullable)
  3105. return NullabilityKind::Nullable;
  3106. if (getAttrKind() == AttributedType::attr_null_unspecified)
  3107. return NullabilityKind::Unspecified;
  3108. return None;
  3109. }
  3110. Optional<NullabilityKind> AttributedType::stripOuterNullability(QualType &T) {
  3111. if (auto attributed = dyn_cast<AttributedType>(T.getTypePtr())) {
  3112. if (auto nullability = attributed->getImmediateNullability()) {
  3113. T = attributed->getModifiedType();
  3114. return nullability;
  3115. }
  3116. }
  3117. return None;
  3118. }
  3119. bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const {
  3120. const ObjCObjectPointerType *objcPtr = getAs<ObjCObjectPointerType>();
  3121. if (!objcPtr)
  3122. return false;
  3123. if (objcPtr->isObjCIdType()) {
  3124. // id is always okay.
  3125. return true;
  3126. }
  3127. // Blocks are NSObjects.
  3128. if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) {
  3129. if (iface->getIdentifier() != ctx.getNSObjectName())
  3130. return false;
  3131. // Continue to check qualifiers, below.
  3132. } else if (objcPtr->isObjCQualifiedIdType()) {
  3133. // Continue to check qualifiers, below.
  3134. } else {
  3135. return false;
  3136. }
  3137. // Check protocol qualifiers.
  3138. for (ObjCProtocolDecl *proto : objcPtr->quals()) {
  3139. // Blocks conform to NSObject and NSCopying.
  3140. if (proto->getIdentifier() != ctx.getNSObjectName() &&
  3141. proto->getIdentifier() != ctx.getNSCopyingName())
  3142. return false;
  3143. }
  3144. return true;
  3145. }
  3146. Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
  3147. if (isObjCARCImplicitlyUnretainedType())
  3148. return Qualifiers::OCL_ExplicitNone;
  3149. return Qualifiers::OCL_Strong;
  3150. }
  3151. bool Type::isObjCARCImplicitlyUnretainedType() const {
  3152. assert(isObjCLifetimeType() &&
  3153. "cannot query implicit lifetime for non-inferrable type");
  3154. const Type *canon = getCanonicalTypeInternal().getTypePtr();
  3155. // Walk down to the base type. We don't care about qualifiers for this.
  3156. while (const ArrayType *array = dyn_cast<ArrayType>(canon))
  3157. canon = array->getElementType().getTypePtr();
  3158. if (const ObjCObjectPointerType *opt
  3159. = dyn_cast<ObjCObjectPointerType>(canon)) {
  3160. // Class and Class<Protocol> don't require retention.
  3161. if (opt->getObjectType()->isObjCClass())
  3162. return true;
  3163. }
  3164. return false;
  3165. }
  3166. bool Type::isObjCNSObjectType() const {
  3167. if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
  3168. return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
  3169. return false;
  3170. }
  3171. bool Type::isObjCIndependentClassType() const {
  3172. if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
  3173. return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>();
  3174. return false;
  3175. }
  3176. bool Type::isObjCRetainableType() const {
  3177. return isObjCObjectPointerType() ||
  3178. isBlockPointerType() ||
  3179. isObjCNSObjectType();
  3180. }
  3181. bool Type::isObjCIndirectLifetimeType() const {
  3182. if (isObjCLifetimeType())
  3183. return true;
  3184. if (const PointerType *OPT = getAs<PointerType>())
  3185. return OPT->getPointeeType()->isObjCIndirectLifetimeType();
  3186. if (const ReferenceType *Ref = getAs<ReferenceType>())
  3187. return Ref->getPointeeType()->isObjCIndirectLifetimeType();
  3188. if (const MemberPointerType *MemPtr = getAs<MemberPointerType>())
  3189. return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
  3190. return false;
  3191. }
  3192. /// Returns true if objects of this type have lifetime semantics under
  3193. /// ARC.
  3194. bool Type::isObjCLifetimeType() const {
  3195. const Type *type = this;
  3196. while (const ArrayType *array = type->getAsArrayTypeUnsafe())
  3197. type = array->getElementType().getTypePtr();
  3198. return type->isObjCRetainableType();
  3199. }
  3200. /// \brief Determine whether the given type T is a "bridgable" Objective-C type,
  3201. /// which is either an Objective-C object pointer type or an
  3202. bool Type::isObjCARCBridgableType() const {
  3203. return isObjCObjectPointerType() || isBlockPointerType();
  3204. }
  3205. /// \brief Determine whether the given type T is a "bridgeable" C type.
  3206. bool Type::isCARCBridgableType() const {
  3207. const PointerType *Pointer = getAs<PointerType>();
  3208. if (!Pointer)
  3209. return false;
  3210. QualType Pointee = Pointer->getPointeeType();
  3211. return Pointee->isVoidType() || Pointee->isRecordType();
  3212. }
  3213. bool Type::hasSizedVLAType() const {
  3214. if (!isVariablyModifiedType()) return false;
  3215. if (const PointerType *ptr = getAs<PointerType>())
  3216. return ptr->getPointeeType()->hasSizedVLAType();
  3217. if (const ReferenceType *ref = getAs<ReferenceType>())
  3218. return ref->getPointeeType()->hasSizedVLAType();
  3219. if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
  3220. if (isa<VariableArrayType>(arr) &&
  3221. cast<VariableArrayType>(arr)->getSizeExpr())
  3222. return true;
  3223. return arr->getElementType()->hasSizedVLAType();
  3224. }
  3225. return false;
  3226. }
  3227. QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
  3228. switch (type.getObjCLifetime()) {
  3229. case Qualifiers::OCL_None:
  3230. case Qualifiers::OCL_ExplicitNone:
  3231. case Qualifiers::OCL_Autoreleasing:
  3232. break;
  3233. case Qualifiers::OCL_Strong:
  3234. return DK_objc_strong_lifetime;
  3235. case Qualifiers::OCL_Weak:
  3236. return DK_objc_weak_lifetime;
  3237. }
  3238. /// Currently, the only destruction kind we recognize is C++ objects
  3239. /// with non-trivial destructors.
  3240. const CXXRecordDecl *record =
  3241. type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  3242. if (record && record->hasDefinition() && !record->hasTrivialDestructor())
  3243. return DK_cxx_destructor;
  3244. return DK_none;
  3245. }
  3246. CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
  3247. return getClass()->getAsCXXRecordDecl()->getMostRecentDecl();
  3248. }