Type.cpp 134 KB

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