Type.cpp 132 KB

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