Type.cpp 136 KB

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