Type.cpp 132 KB

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