Decl.h 172 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- Decl.h - Classes for representing declarations -----------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the Decl subclasses.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_CLANG_AST_DECL_H
  18. #define LLVM_CLANG_AST_DECL_H
  19. #include "clang/AST/APValue.h"
  20. #include "clang/AST/ASTContextAllocate.h"
  21. #include "clang/AST/DeclAccessPair.h"
  22. #include "clang/AST/DeclBase.h"
  23. #include "clang/AST/DeclarationName.h"
  24. #include "clang/AST/ExternalASTSource.h"
  25. #include "clang/AST/NestedNameSpecifier.h"
  26. #include "clang/AST/Redeclarable.h"
  27. #include "clang/AST/Type.h"
  28. #include "clang/Basic/AddressSpaces.h"
  29. #include "clang/Basic/Diagnostic.h"
  30. #include "clang/Basic/IdentifierTable.h"
  31. #include "clang/Basic/LLVM.h"
  32. #include "clang/Basic/Linkage.h"
  33. #include "clang/Basic/OperatorKinds.h"
  34. #include "clang/Basic/PartialDiagnostic.h"
  35. #include "clang/Basic/PragmaKinds.h"
  36. #include "clang/Basic/SourceLocation.h"
  37. #include "clang/Basic/Specifiers.h"
  38. #include "clang/Basic/Visibility.h"
  39. #include "llvm/ADT/APSInt.h"
  40. #include "llvm/ADT/ArrayRef.h"
  41. #include "llvm/ADT/Optional.h"
  42. #include "llvm/ADT/PointerIntPair.h"
  43. #include "llvm/ADT/PointerUnion.h"
  44. #include "llvm/ADT/StringRef.h"
  45. #include "llvm/ADT/iterator_range.h"
  46. #include "llvm/Support/Casting.h"
  47. #include "llvm/Support/Compiler.h"
  48. #include "llvm/Support/TrailingObjects.h"
  49. #include <cassert>
  50. #include <cstddef>
  51. #include <cstdint>
  52. #include <string>
  53. #include <utility>
  54. namespace clang {
  55. class ASTContext;
  56. struct ASTTemplateArgumentListInfo;
  57. class CompoundStmt;
  58. class DependentFunctionTemplateSpecializationInfo;
  59. class EnumDecl;
  60. class Expr;
  61. class FunctionTemplateDecl;
  62. class FunctionTemplateSpecializationInfo;
  63. class FunctionTypeLoc;
  64. class LabelStmt;
  65. class MemberSpecializationInfo;
  66. class Module;
  67. class NamespaceDecl;
  68. class ParmVarDecl;
  69. class RecordDecl;
  70. class Stmt;
  71. class StringLiteral;
  72. class TagDecl;
  73. class TemplateArgumentList;
  74. class TemplateArgumentListInfo;
  75. class TemplateParameterList;
  76. class TypeAliasTemplateDecl;
  77. class UnresolvedSetImpl;
  78. class VarTemplateDecl;
  79. /// The top declaration context.
  80. class TranslationUnitDecl : public Decl,
  81. public DeclContext,
  82. public Redeclarable<TranslationUnitDecl> {
  83. using redeclarable_base = Redeclarable<TranslationUnitDecl>;
  84. TranslationUnitDecl *getNextRedeclarationImpl() override {
  85. return getNextRedeclaration();
  86. }
  87. TranslationUnitDecl *getPreviousDeclImpl() override {
  88. return getPreviousDecl();
  89. }
  90. TranslationUnitDecl *getMostRecentDeclImpl() override {
  91. return getMostRecentDecl();
  92. }
  93. ASTContext &Ctx;
  94. /// The (most recently entered) anonymous namespace for this
  95. /// translation unit, if one has been created.
  96. NamespaceDecl *AnonymousNamespace = nullptr;
  97. explicit TranslationUnitDecl(ASTContext &ctx);
  98. virtual void anchor();
  99. public:
  100. using redecl_range = redeclarable_base::redecl_range;
  101. using redecl_iterator = redeclarable_base::redecl_iterator;
  102. using redeclarable_base::getMostRecentDecl;
  103. using redeclarable_base::getPreviousDecl;
  104. using redeclarable_base::isFirstDecl;
  105. using redeclarable_base::redecls;
  106. using redeclarable_base::redecls_begin;
  107. using redeclarable_base::redecls_end;
  108. ASTContext &getASTContext() const { return Ctx; }
  109. NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
  110. void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
  111. static TranslationUnitDecl *Create(ASTContext &C);
  112. // Implement isa/cast/dyncast/etc.
  113. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  114. static bool classofKind(Kind K) { return K == TranslationUnit; }
  115. static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
  116. return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
  117. }
  118. static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
  119. return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
  120. }
  121. };
  122. /// Represents a `#pragma comment` line. Always a child of
  123. /// TranslationUnitDecl.
  124. class PragmaCommentDecl final
  125. : public Decl,
  126. private llvm::TrailingObjects<PragmaCommentDecl, char> {
  127. friend class ASTDeclReader;
  128. friend class ASTDeclWriter;
  129. friend TrailingObjects;
  130. PragmaMSCommentKind CommentKind;
  131. PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc,
  132. PragmaMSCommentKind CommentKind)
  133. : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {}
  134. virtual void anchor();
  135. public:
  136. static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC,
  137. SourceLocation CommentLoc,
  138. PragmaMSCommentKind CommentKind,
  139. StringRef Arg);
  140. static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID,
  141. unsigned ArgSize);
  142. PragmaMSCommentKind getCommentKind() const { return CommentKind; }
  143. StringRef getArg() const { return getTrailingObjects<char>(); }
  144. // Implement isa/cast/dyncast/etc.
  145. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  146. static bool classofKind(Kind K) { return K == PragmaComment; }
  147. };
  148. /// Represents a `#pragma detect_mismatch` line. Always a child of
  149. /// TranslationUnitDecl.
  150. class PragmaDetectMismatchDecl final
  151. : public Decl,
  152. private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> {
  153. friend class ASTDeclReader;
  154. friend class ASTDeclWriter;
  155. friend TrailingObjects;
  156. size_t ValueStart;
  157. PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc,
  158. size_t ValueStart)
  159. : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {}
  160. virtual void anchor();
  161. public:
  162. static PragmaDetectMismatchDecl *Create(const ASTContext &C,
  163. TranslationUnitDecl *DC,
  164. SourceLocation Loc, StringRef Name,
  165. StringRef Value);
  166. static PragmaDetectMismatchDecl *
  167. CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize);
  168. StringRef getName() const { return getTrailingObjects<char>(); }
  169. StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; }
  170. // Implement isa/cast/dyncast/etc.
  171. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  172. static bool classofKind(Kind K) { return K == PragmaDetectMismatch; }
  173. };
  174. /// Declaration context for names declared as extern "C" in C++. This
  175. /// is neither the semantic nor lexical context for such declarations, but is
  176. /// used to check for conflicts with other extern "C" declarations. Example:
  177. ///
  178. /// \code
  179. /// namespace N { extern "C" void f(); } // #1
  180. /// void N::f() {} // #2
  181. /// namespace M { extern "C" void f(); } // #3
  182. /// \endcode
  183. ///
  184. /// The semantic context of #1 is namespace N and its lexical context is the
  185. /// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
  186. /// context is the TU. However, both declarations are also visible in the
  187. /// extern "C" context.
  188. ///
  189. /// The declaration at #3 finds it is a redeclaration of \c N::f through
  190. /// lookup in the extern "C" context.
  191. class ExternCContextDecl : public Decl, public DeclContext {
  192. explicit ExternCContextDecl(TranslationUnitDecl *TU)
  193. : Decl(ExternCContext, TU, SourceLocation()),
  194. DeclContext(ExternCContext) {}
  195. virtual void anchor();
  196. public:
  197. static ExternCContextDecl *Create(const ASTContext &C,
  198. TranslationUnitDecl *TU);
  199. // Implement isa/cast/dyncast/etc.
  200. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  201. static bool classofKind(Kind K) { return K == ExternCContext; }
  202. static DeclContext *castToDeclContext(const ExternCContextDecl *D) {
  203. return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
  204. }
  205. static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) {
  206. return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
  207. }
  208. };
  209. /// This represents a decl that may have a name. Many decls have names such
  210. /// as ObjCMethodDecl, but not \@class, etc.
  211. ///
  212. /// Note that not every NamedDecl is actually named (e.g., a struct might
  213. /// be anonymous), and not every name is an identifier.
  214. class NamedDecl : public Decl {
  215. /// The name of this declaration, which is typically a normal
  216. /// identifier but may also be a special kind of name (C++
  217. /// constructor, Objective-C selector, etc.)
  218. DeclarationName Name;
  219. virtual void anchor();
  220. private:
  221. NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY;
  222. protected:
  223. NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
  224. : Decl(DK, DC, L), Name(N) {}
  225. public:
  226. /// Get the identifier that names this declaration, if there is one.
  227. ///
  228. /// This will return NULL if this declaration has no name (e.g., for
  229. /// an unnamed class) or if the name is a special name (C++ constructor,
  230. /// Objective-C selector, etc.).
  231. IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
  232. /// Get the name of identifier for this declaration as a StringRef.
  233. ///
  234. /// This requires that the declaration have a name and that it be a simple
  235. /// identifier.
  236. StringRef getName() const {
  237. assert(Name.isIdentifier() && "Name is not a simple identifier");
  238. return getIdentifier() ? getIdentifier()->getName() : "";
  239. }
  240. /// Get a human-readable name for the declaration, even if it is one of the
  241. /// special kinds of names (C++ constructor, Objective-C selector, etc).
  242. ///
  243. /// Creating this name requires expensive string manipulation, so it should
  244. /// be called only when performance doesn't matter. For simple declarations,
  245. /// getNameAsCString() should suffice.
  246. //
  247. // FIXME: This function should be renamed to indicate that it is not just an
  248. // alternate form of getName(), and clients should move as appropriate.
  249. //
  250. // FIXME: Deprecated, move clients to getName().
  251. std::string getNameAsString() const { return Name.getAsString(); }
  252. /// Pretty-print the unqualified name of this declaration. Can be overloaded
  253. /// by derived classes to provide a more user-friendly name when appropriate.
  254. virtual void printName(raw_ostream &os) const;
  255. /// Get the actual, stored name of the declaration, which may be a special
  256. /// name.
  257. ///
  258. /// Note that generally in diagnostics, the non-null \p NamedDecl* itself
  259. /// should be sent into the diagnostic instead of using the result of
  260. /// \p getDeclName().
  261. ///
  262. /// A \p DeclarationName in a diagnostic will just be streamed to the output,
  263. /// which will directly result in a call to \p DeclarationName::print.
  264. ///
  265. /// A \p NamedDecl* in a diagnostic will also ultimately result in a call to
  266. /// \p DeclarationName::print, but with two customisation points along the
  267. /// way (\p getNameForDiagnostic and \p printName). These are used to print
  268. /// the template arguments if any, and to provide a user-friendly name for
  269. /// some entities (such as unnamed variables and anonymous records).
  270. DeclarationName getDeclName() const { return Name; }
  271. /// Set the name of this declaration.
  272. void setDeclName(DeclarationName N) { Name = N; }
  273. /// Returns a human-readable qualified name for this declaration, like
  274. /// A::B::i, for i being member of namespace A::B.
  275. ///
  276. /// If the declaration is not a member of context which can be named (record,
  277. /// namespace), it will return the same result as printName().
  278. ///
  279. /// Creating this name is expensive, so it should be called only when
  280. /// performance doesn't matter.
  281. void printQualifiedName(raw_ostream &OS) const;
  282. void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
  283. /// Print only the nested name specifier part of a fully-qualified name,
  284. /// including the '::' at the end. E.g.
  285. /// when `printQualifiedName(D)` prints "A::B::i",
  286. /// this function prints "A::B::".
  287. void printNestedNameSpecifier(raw_ostream &OS) const;
  288. void printNestedNameSpecifier(raw_ostream &OS,
  289. const PrintingPolicy &Policy) const;
  290. // FIXME: Remove string version.
  291. std::string getQualifiedNameAsString() const;
  292. /// Appends a human-readable name for this declaration into the given stream.
  293. ///
  294. /// This is the method invoked by Sema when displaying a NamedDecl
  295. /// in a diagnostic. It does not necessarily produce the same
  296. /// result as printName(); for example, class template
  297. /// specializations are printed with their template arguments.
  298. virtual void getNameForDiagnostic(raw_ostream &OS,
  299. const PrintingPolicy &Policy,
  300. bool Qualified) const;
  301. /// Determine whether this declaration, if known to be well-formed within
  302. /// its context, will replace the declaration OldD if introduced into scope.
  303. ///
  304. /// A declaration will replace another declaration if, for example, it is
  305. /// a redeclaration of the same variable or function, but not if it is a
  306. /// declaration of a different kind (function vs. class) or an overloaded
  307. /// function.
  308. ///
  309. /// \param IsKnownNewer \c true if this declaration is known to be newer
  310. /// than \p OldD (for instance, if this declaration is newly-created).
  311. bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
  312. /// Determine whether this declaration has linkage.
  313. bool hasLinkage() const;
  314. using Decl::isModulePrivate;
  315. using Decl::setModulePrivate;
  316. /// Determine whether this declaration is a C++ class member.
  317. bool isCXXClassMember() const {
  318. const DeclContext *DC = getDeclContext();
  319. // C++0x [class.mem]p1:
  320. // The enumerators of an unscoped enumeration defined in
  321. // the class are members of the class.
  322. if (isa<EnumDecl>(DC))
  323. DC = DC->getRedeclContext();
  324. return DC->isRecord();
  325. }
  326. /// Determine whether the given declaration is an instance member of
  327. /// a C++ class.
  328. bool isCXXInstanceMember() const;
  329. /// Determine if the declaration obeys the reserved identifier rules of the
  330. /// given language.
  331. ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const;
  332. /// Determine what kind of linkage this entity has.
  333. ///
  334. /// This is not the linkage as defined by the standard or the codegen notion
  335. /// of linkage. It is just an implementation detail that is used to compute
  336. /// those.
  337. Linkage getLinkageInternal() const;
  338. /// Get the linkage from a semantic point of view. Entities in
  339. /// anonymous namespaces are external (in c++98).
  340. Linkage getFormalLinkage() const {
  341. return clang::getFormalLinkage(getLinkageInternal());
  342. }
  343. /// True if this decl has external linkage.
  344. bool hasExternalFormalLinkage() const {
  345. return isExternalFormalLinkage(getLinkageInternal());
  346. }
  347. bool isExternallyVisible() const {
  348. return clang::isExternallyVisible(getLinkageInternal());
  349. }
  350. /// Determine whether this declaration can be redeclared in a
  351. /// different translation unit.
  352. bool isExternallyDeclarable() const {
  353. return isExternallyVisible() && !getOwningModuleForLinkage();
  354. }
  355. /// Determines the visibility of this entity.
  356. Visibility getVisibility() const {
  357. return getLinkageAndVisibility().getVisibility();
  358. }
  359. /// Determines the linkage and visibility of this entity.
  360. LinkageInfo getLinkageAndVisibility() const;
  361. /// Kinds of explicit visibility.
  362. enum ExplicitVisibilityKind {
  363. /// Do an LV computation for, ultimately, a type.
  364. /// Visibility may be restricted by type visibility settings and
  365. /// the visibility of template arguments.
  366. VisibilityForType,
  367. /// Do an LV computation for, ultimately, a non-type declaration.
  368. /// Visibility may be restricted by value visibility settings and
  369. /// the visibility of template arguments.
  370. VisibilityForValue
  371. };
  372. /// If visibility was explicitly specified for this
  373. /// declaration, return that visibility.
  374. Optional<Visibility>
  375. getExplicitVisibility(ExplicitVisibilityKind kind) const;
  376. /// True if the computed linkage is valid. Used for consistency
  377. /// checking. Should always return true.
  378. bool isLinkageValid() const;
  379. /// True if something has required us to compute the linkage
  380. /// of this declaration.
  381. ///
  382. /// Language features which can retroactively change linkage (like a
  383. /// typedef name for linkage purposes) may need to consider this,
  384. /// but hopefully only in transitory ways during parsing.
  385. bool hasLinkageBeenComputed() const {
  386. return hasCachedLinkage();
  387. }
  388. /// Looks through UsingDecls and ObjCCompatibleAliasDecls for
  389. /// the underlying named decl.
  390. NamedDecl *getUnderlyingDecl() {
  391. // Fast-path the common case.
  392. if (this->getKind() != UsingShadow &&
  393. this->getKind() != ConstructorUsingShadow &&
  394. this->getKind() != ObjCCompatibleAlias &&
  395. this->getKind() != NamespaceAlias)
  396. return this;
  397. return getUnderlyingDeclImpl();
  398. }
  399. const NamedDecl *getUnderlyingDecl() const {
  400. return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
  401. }
  402. NamedDecl *getMostRecentDecl() {
  403. return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
  404. }
  405. const NamedDecl *getMostRecentDecl() const {
  406. return const_cast<NamedDecl*>(this)->getMostRecentDecl();
  407. }
  408. ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
  409. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  410. static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
  411. };
  412. inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
  413. ND.printName(OS);
  414. return OS;
  415. }
  416. /// Represents the declaration of a label. Labels also have a
  417. /// corresponding LabelStmt, which indicates the position that the label was
  418. /// defined at. For normal labels, the location of the decl is the same as the
  419. /// location of the statement. For GNU local labels (__label__), the decl
  420. /// location is where the __label__ is.
  421. class LabelDecl : public NamedDecl {
  422. LabelStmt *TheStmt;
  423. StringRef MSAsmName;
  424. bool MSAsmNameResolved = false;
  425. /// For normal labels, this is the same as the main declaration
  426. /// label, i.e., the location of the identifier; for GNU local labels,
  427. /// this is the location of the __label__ keyword.
  428. SourceLocation LocStart;
  429. LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
  430. LabelStmt *S, SourceLocation StartL)
  431. : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
  432. void anchor() override;
  433. public:
  434. static LabelDecl *Create(ASTContext &C, DeclContext *DC,
  435. SourceLocation IdentL, IdentifierInfo *II);
  436. static LabelDecl *Create(ASTContext &C, DeclContext *DC,
  437. SourceLocation IdentL, IdentifierInfo *II,
  438. SourceLocation GnuLabelL);
  439. static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  440. LabelStmt *getStmt() const { return TheStmt; }
  441. void setStmt(LabelStmt *T) { TheStmt = T; }
  442. bool isGnuLocal() const { return LocStart != getLocation(); }
  443. void setLocStart(SourceLocation L) { LocStart = L; }
  444. SourceRange getSourceRange() const override LLVM_READONLY {
  445. return SourceRange(LocStart, getLocation());
  446. }
  447. bool isMSAsmLabel() const { return !MSAsmName.empty(); }
  448. bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
  449. void setMSAsmLabel(StringRef Name);
  450. StringRef getMSAsmLabel() const { return MSAsmName; }
  451. void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
  452. // Implement isa/cast/dyncast/etc.
  453. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  454. static bool classofKind(Kind K) { return K == Label; }
  455. };
  456. /// Represent a C++ namespace.
  457. class NamespaceDecl : public NamedDecl, public DeclContext,
  458. public Redeclarable<NamespaceDecl>
  459. {
  460. /// The starting location of the source range, pointing
  461. /// to either the namespace or the inline keyword.
  462. SourceLocation LocStart;
  463. /// The ending location of the source range.
  464. SourceLocation RBraceLoc;
  465. /// A pointer to either the anonymous namespace that lives just inside
  466. /// this namespace or to the first namespace in the chain (the latter case
  467. /// only when this is not the first in the chain), along with a
  468. /// boolean value indicating whether this is an inline namespace.
  469. llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
  470. NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
  471. SourceLocation StartLoc, SourceLocation IdLoc,
  472. IdentifierInfo *Id, NamespaceDecl *PrevDecl);
  473. using redeclarable_base = Redeclarable<NamespaceDecl>;
  474. NamespaceDecl *getNextRedeclarationImpl() override;
  475. NamespaceDecl *getPreviousDeclImpl() override;
  476. NamespaceDecl *getMostRecentDeclImpl() override;
  477. public:
  478. friend class ASTDeclReader;
  479. friend class ASTDeclWriter;
  480. static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
  481. bool Inline, SourceLocation StartLoc,
  482. SourceLocation IdLoc, IdentifierInfo *Id,
  483. NamespaceDecl *PrevDecl);
  484. static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  485. using redecl_range = redeclarable_base::redecl_range;
  486. using redecl_iterator = redeclarable_base::redecl_iterator;
  487. using redeclarable_base::redecls_begin;
  488. using redeclarable_base::redecls_end;
  489. using redeclarable_base::redecls;
  490. using redeclarable_base::getPreviousDecl;
  491. using redeclarable_base::getMostRecentDecl;
  492. using redeclarable_base::isFirstDecl;
  493. /// Returns true if this is an anonymous namespace declaration.
  494. ///
  495. /// For example:
  496. /// \code
  497. /// namespace {
  498. /// ...
  499. /// };
  500. /// \endcode
  501. /// q.v. C++ [namespace.unnamed]
  502. bool isAnonymousNamespace() const {
  503. return !getIdentifier();
  504. }
  505. /// Returns true if this is an inline namespace declaration.
  506. bool isInline() const {
  507. return AnonOrFirstNamespaceAndInline.getInt();
  508. }
  509. /// Set whether this is an inline namespace declaration.
  510. void setInline(bool Inline) {
  511. AnonOrFirstNamespaceAndInline.setInt(Inline);
  512. }
  513. /// Returns true if the inline qualifier for \c Name is redundant.
  514. bool isRedundantInlineQualifierFor(DeclarationName Name) const {
  515. if (!isInline())
  516. return false;
  517. auto X = lookup(Name);
  518. // We should not perform a lookup within a transparent context, so find a
  519. // non-transparent parent context.
  520. auto Y = getParent()->getNonTransparentContext()->lookup(Name);
  521. return std::distance(X.begin(), X.end()) ==
  522. std::distance(Y.begin(), Y.end());
  523. }
  524. /// Get the original (first) namespace declaration.
  525. NamespaceDecl *getOriginalNamespace();
  526. /// Get the original (first) namespace declaration.
  527. const NamespaceDecl *getOriginalNamespace() const;
  528. /// Return true if this declaration is an original (first) declaration
  529. /// of the namespace. This is false for non-original (subsequent) namespace
  530. /// declarations and anonymous namespaces.
  531. bool isOriginalNamespace() const;
  532. /// Retrieve the anonymous namespace nested inside this namespace,
  533. /// if any.
  534. NamespaceDecl *getAnonymousNamespace() const {
  535. return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
  536. }
  537. void setAnonymousNamespace(NamespaceDecl *D) {
  538. getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
  539. }
  540. /// Retrieves the canonical declaration of this namespace.
  541. NamespaceDecl *getCanonicalDecl() override {
  542. return getOriginalNamespace();
  543. }
  544. const NamespaceDecl *getCanonicalDecl() const {
  545. return getOriginalNamespace();
  546. }
  547. SourceRange getSourceRange() const override LLVM_READONLY {
  548. return SourceRange(LocStart, RBraceLoc);
  549. }
  550. SourceLocation getBeginLoc() const LLVM_READONLY { return LocStart; }
  551. SourceLocation getRBraceLoc() const { return RBraceLoc; }
  552. void setLocStart(SourceLocation L) { LocStart = L; }
  553. void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
  554. // Implement isa/cast/dyncast/etc.
  555. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  556. static bool classofKind(Kind K) { return K == Namespace; }
  557. static DeclContext *castToDeclContext(const NamespaceDecl *D) {
  558. return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
  559. }
  560. static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
  561. return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
  562. }
  563. };
  564. /// Represent the declaration of a variable (in which case it is
  565. /// an lvalue) a function (in which case it is a function designator) or
  566. /// an enum constant.
  567. class ValueDecl : public NamedDecl {
  568. QualType DeclType;
  569. void anchor() override;
  570. protected:
  571. ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
  572. DeclarationName N, QualType T)
  573. : NamedDecl(DK, DC, L, N), DeclType(T) {}
  574. public:
  575. QualType getType() const { return DeclType; }
  576. void setType(QualType newType) { DeclType = newType; }
  577. /// Determine whether this symbol is weakly-imported,
  578. /// or declared with the weak or weak-ref attr.
  579. bool isWeak() const;
  580. // Implement isa/cast/dyncast/etc.
  581. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  582. static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
  583. };
  584. /// A struct with extended info about a syntactic
  585. /// name qualifier, to be used for the case of out-of-line declarations.
  586. struct QualifierInfo {
  587. NestedNameSpecifierLoc QualifierLoc;
  588. /// The number of "outer" template parameter lists.
  589. /// The count includes all of the template parameter lists that were matched
  590. /// against the template-ids occurring into the NNS and possibly (in the
  591. /// case of an explicit specialization) a final "template <>".
  592. unsigned NumTemplParamLists = 0;
  593. /// A new-allocated array of size NumTemplParamLists,
  594. /// containing pointers to the "outer" template parameter lists.
  595. /// It includes all of the template parameter lists that were matched
  596. /// against the template-ids occurring into the NNS and possibly (in the
  597. /// case of an explicit specialization) a final "template <>".
  598. TemplateParameterList** TemplParamLists = nullptr;
  599. QualifierInfo() = default;
  600. QualifierInfo(const QualifierInfo &) = delete;
  601. QualifierInfo& operator=(const QualifierInfo &) = delete;
  602. /// Sets info about "outer" template parameter lists.
  603. void setTemplateParameterListsInfo(ASTContext &Context,
  604. ArrayRef<TemplateParameterList *> TPLists);
  605. };
  606. /// Represents a ValueDecl that came out of a declarator.
  607. /// Contains type source information through TypeSourceInfo.
  608. class DeclaratorDecl : public ValueDecl {
  609. // A struct representing a TInfo, a trailing requires-clause and a syntactic
  610. // qualifier, to be used for the (uncommon) case of out-of-line declarations
  611. // and constrained function decls.
  612. struct ExtInfo : public QualifierInfo {
  613. TypeSourceInfo *TInfo;
  614. Expr *TrailingRequiresClause = nullptr;
  615. };
  616. llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
  617. /// The start of the source range for this declaration,
  618. /// ignoring outer template declarations.
  619. SourceLocation InnerLocStart;
  620. bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
  621. ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
  622. const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
  623. protected:
  624. DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
  625. DeclarationName N, QualType T, TypeSourceInfo *TInfo,
  626. SourceLocation StartL)
  627. : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
  628. public:
  629. friend class ASTDeclReader;
  630. friend class ASTDeclWriter;
  631. TypeSourceInfo *getTypeSourceInfo() const {
  632. return hasExtInfo()
  633. ? getExtInfo()->TInfo
  634. : DeclInfo.get<TypeSourceInfo*>();
  635. }
  636. void setTypeSourceInfo(TypeSourceInfo *TI) {
  637. if (hasExtInfo())
  638. getExtInfo()->TInfo = TI;
  639. else
  640. DeclInfo = TI;
  641. }
  642. /// Return start of source range ignoring outer template declarations.
  643. SourceLocation getInnerLocStart() const { return InnerLocStart; }
  644. void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
  645. /// Return start of source range taking into account any outer template
  646. /// declarations.
  647. SourceLocation getOuterLocStart() const;
  648. SourceRange getSourceRange() const override LLVM_READONLY;
  649. SourceLocation getBeginLoc() const LLVM_READONLY {
  650. return getOuterLocStart();
  651. }
  652. /// Retrieve the nested-name-specifier that qualifies the name of this
  653. /// declaration, if it was present in the source.
  654. NestedNameSpecifier *getQualifier() const {
  655. return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
  656. : nullptr;
  657. }
  658. /// Retrieve the nested-name-specifier (with source-location
  659. /// information) that qualifies the name of this declaration, if it was
  660. /// present in the source.
  661. NestedNameSpecifierLoc getQualifierLoc() const {
  662. return hasExtInfo() ? getExtInfo()->QualifierLoc
  663. : NestedNameSpecifierLoc();
  664. }
  665. void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
  666. /// \brief Get the constraint-expression introduced by the trailing
  667. /// requires-clause in the function/member declaration, or null if no
  668. /// requires-clause was provided.
  669. Expr *getTrailingRequiresClause() {
  670. return hasExtInfo() ? getExtInfo()->TrailingRequiresClause
  671. : nullptr;
  672. }
  673. const Expr *getTrailingRequiresClause() const {
  674. return hasExtInfo() ? getExtInfo()->TrailingRequiresClause
  675. : nullptr;
  676. }
  677. void setTrailingRequiresClause(Expr *TrailingRequiresClause);
  678. unsigned getNumTemplateParameterLists() const {
  679. return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
  680. }
  681. TemplateParameterList *getTemplateParameterList(unsigned index) const {
  682. assert(index < getNumTemplateParameterLists());
  683. return getExtInfo()->TemplParamLists[index];
  684. }
  685. void setTemplateParameterListsInfo(ASTContext &Context,
  686. ArrayRef<TemplateParameterList *> TPLists);
  687. SourceLocation getTypeSpecStartLoc() const;
  688. SourceLocation getTypeSpecEndLoc() const;
  689. // Implement isa/cast/dyncast/etc.
  690. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  691. static bool classofKind(Kind K) {
  692. return K >= firstDeclarator && K <= lastDeclarator;
  693. }
  694. };
  695. /// Structure used to store a statement, the constant value to
  696. /// which it was evaluated (if any), and whether or not the statement
  697. /// is an integral constant expression (if known).
  698. struct EvaluatedStmt {
  699. /// Whether this statement was already evaluated.
  700. bool WasEvaluated : 1;
  701. /// Whether this statement is being evaluated.
  702. bool IsEvaluating : 1;
  703. /// Whether this variable is known to have constant initialization. This is
  704. /// currently only computed in C++, for static / thread storage duration
  705. /// variables that might have constant initialization and for variables that
  706. /// are usable in constant expressions.
  707. bool HasConstantInitialization : 1;
  708. /// Whether this variable is known to have constant destruction. That is,
  709. /// whether running the destructor on the initial value is a side-effect
  710. /// (and doesn't inspect any state that might have changed during program
  711. /// execution). This is currently only computed if the destructor is
  712. /// non-trivial.
  713. bool HasConstantDestruction : 1;
  714. /// In C++98, whether the initializer is an ICE. This affects whether the
  715. /// variable is usable in constant expressions.
  716. bool HasICEInit : 1;
  717. bool CheckedForICEInit : 1;
  718. Stmt *Value;
  719. APValue Evaluated;
  720. EvaluatedStmt()
  721. : WasEvaluated(false), IsEvaluating(false),
  722. HasConstantInitialization(false), HasConstantDestruction(false),
  723. HasICEInit(false), CheckedForICEInit(false) {}
  724. };
  725. /// Represents a variable declaration or definition.
  726. class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
  727. public:
  728. /// Initialization styles.
  729. enum InitializationStyle {
  730. /// C-style initialization with assignment
  731. CInit,
  732. /// Call-style initialization (C++98)
  733. CallInit,
  734. /// Direct list-initialization (C++11)
  735. ListInit
  736. };
  737. /// Kinds of thread-local storage.
  738. enum TLSKind {
  739. /// Not a TLS variable.
  740. TLS_None,
  741. /// TLS with a known-constant initializer.
  742. TLS_Static,
  743. /// TLS with a dynamic initializer.
  744. TLS_Dynamic
  745. };
  746. /// Return the string used to specify the storage class \p SC.
  747. ///
  748. /// It is illegal to call this function with SC == None.
  749. static const char *getStorageClassSpecifierString(StorageClass SC);
  750. protected:
  751. // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
  752. // have allocated the auxiliary struct of information there.
  753. //
  754. // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
  755. // this as *many* VarDecls are ParmVarDecls that don't have default
  756. // arguments. We could save some space by moving this pointer union to be
  757. // allocated in trailing space when necessary.
  758. using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
  759. /// The initializer for this variable or, for a ParmVarDecl, the
  760. /// C++ default argument.
  761. mutable InitType Init;
  762. private:
  763. friend class ASTDeclReader;
  764. friend class ASTNodeImporter;
  765. friend class StmtIteratorBase;
  766. class VarDeclBitfields {
  767. friend class ASTDeclReader;
  768. friend class VarDecl;
  769. unsigned SClass : 3;
  770. unsigned TSCSpec : 2;
  771. unsigned InitStyle : 2;
  772. /// Whether this variable is an ARC pseudo-__strong variable; see
  773. /// isARCPseudoStrong() for details.
  774. unsigned ARCPseudoStrong : 1;
  775. };
  776. enum { NumVarDeclBits = 8 };
  777. protected:
  778. enum { NumParameterIndexBits = 8 };
  779. enum DefaultArgKind {
  780. DAK_None,
  781. DAK_Unparsed,
  782. DAK_Uninstantiated,
  783. DAK_Normal
  784. };
  785. enum { NumScopeDepthOrObjCQualsBits = 7 };
  786. class ParmVarDeclBitfields {
  787. friend class ASTDeclReader;
  788. friend class ParmVarDecl;
  789. unsigned : NumVarDeclBits;
  790. /// Whether this parameter inherits a default argument from a
  791. /// prior declaration.
  792. unsigned HasInheritedDefaultArg : 1;
  793. /// Describes the kind of default argument for this parameter. By default
  794. /// this is none. If this is normal, then the default argument is stored in
  795. /// the \c VarDecl initializer expression unless we were unable to parse
  796. /// (even an invalid) expression for the default argument.
  797. unsigned DefaultArgKind : 2;
  798. /// Whether this parameter undergoes K&R argument promotion.
  799. unsigned IsKNRPromoted : 1;
  800. /// Whether this parameter is an ObjC method parameter or not.
  801. unsigned IsObjCMethodParam : 1;
  802. /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
  803. /// Otherwise, the number of function parameter scopes enclosing
  804. /// the function parameter scope in which this parameter was
  805. /// declared.
  806. unsigned ScopeDepthOrObjCQuals : NumScopeDepthOrObjCQualsBits;
  807. /// The number of parameters preceding this parameter in the
  808. /// function parameter scope in which it was declared.
  809. unsigned ParameterIndex : NumParameterIndexBits;
  810. };
  811. class NonParmVarDeclBitfields {
  812. friend class ASTDeclReader;
  813. friend class ImplicitParamDecl;
  814. friend class VarDecl;
  815. unsigned : NumVarDeclBits;
  816. // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
  817. /// Whether this variable is a definition which was demoted due to
  818. /// module merge.
  819. unsigned IsThisDeclarationADemotedDefinition : 1;
  820. /// Whether this variable is the exception variable in a C++ catch
  821. /// or an Objective-C @catch statement.
  822. unsigned ExceptionVar : 1;
  823. /// Whether this local variable could be allocated in the return
  824. /// slot of its function, enabling the named return value optimization
  825. /// (NRVO).
  826. unsigned NRVOVariable : 1;
  827. /// Whether this variable is the for-range-declaration in a C++0x
  828. /// for-range statement.
  829. unsigned CXXForRangeDecl : 1;
  830. /// Whether this variable is the for-in loop declaration in Objective-C.
  831. unsigned ObjCForDecl : 1;
  832. /// Whether this variable is (C++1z) inline.
  833. unsigned IsInline : 1;
  834. /// Whether this variable has (C++1z) inline explicitly specified.
  835. unsigned IsInlineSpecified : 1;
  836. /// Whether this variable is (C++0x) constexpr.
  837. unsigned IsConstexpr : 1;
  838. /// Whether this variable is the implicit variable for a lambda
  839. /// init-capture.
  840. unsigned IsInitCapture : 1;
  841. /// Whether this local extern variable's previous declaration was
  842. /// declared in the same block scope. This controls whether we should merge
  843. /// the type of this declaration with its previous declaration.
  844. unsigned PreviousDeclInSameBlockScope : 1;
  845. /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
  846. /// something else.
  847. unsigned ImplicitParamKind : 3;
  848. unsigned EscapingByref : 1;
  849. };
  850. union {
  851. unsigned AllBits;
  852. VarDeclBitfields VarDeclBits;
  853. ParmVarDeclBitfields ParmVarDeclBits;
  854. NonParmVarDeclBitfields NonParmVarDeclBits;
  855. };
  856. VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
  857. SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
  858. TypeSourceInfo *TInfo, StorageClass SC);
  859. using redeclarable_base = Redeclarable<VarDecl>;
  860. VarDecl *getNextRedeclarationImpl() override {
  861. return getNextRedeclaration();
  862. }
  863. VarDecl *getPreviousDeclImpl() override {
  864. return getPreviousDecl();
  865. }
  866. VarDecl *getMostRecentDeclImpl() override {
  867. return getMostRecentDecl();
  868. }
  869. public:
  870. using redecl_range = redeclarable_base::redecl_range;
  871. using redecl_iterator = redeclarable_base::redecl_iterator;
  872. using redeclarable_base::redecls_begin;
  873. using redeclarable_base::redecls_end;
  874. using redeclarable_base::redecls;
  875. using redeclarable_base::getPreviousDecl;
  876. using redeclarable_base::getMostRecentDecl;
  877. using redeclarable_base::isFirstDecl;
  878. static VarDecl *Create(ASTContext &C, DeclContext *DC,
  879. SourceLocation StartLoc, SourceLocation IdLoc,
  880. IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
  881. StorageClass S);
  882. static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  883. SourceRange getSourceRange() const override LLVM_READONLY;
  884. /// Returns the storage class as written in the source. For the
  885. /// computed linkage of symbol, see getLinkage.
  886. StorageClass getStorageClass() const {
  887. return (StorageClass) VarDeclBits.SClass;
  888. }
  889. void setStorageClass(StorageClass SC);
  890. void setTSCSpec(ThreadStorageClassSpecifier TSC) {
  891. VarDeclBits.TSCSpec = TSC;
  892. assert(VarDeclBits.TSCSpec == TSC && "truncation");
  893. }
  894. ThreadStorageClassSpecifier getTSCSpec() const {
  895. return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
  896. }
  897. TLSKind getTLSKind() const;
  898. /// Returns true if a variable with function scope is a non-static local
  899. /// variable.
  900. bool hasLocalStorage() const {
  901. if (getStorageClass() == SC_None) {
  902. // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
  903. // used to describe variables allocated in global memory and which are
  904. // accessed inside a kernel(s) as read-only variables. As such, variables
  905. // in constant address space cannot have local storage.
  906. if (getType().getAddressSpace() == LangAS::opencl_constant)
  907. return false;
  908. // Second check is for C++11 [dcl.stc]p4.
  909. return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
  910. }
  911. // Global Named Register (GNU extension)
  912. if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
  913. return false;
  914. // Return true for: Auto, Register.
  915. // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
  916. return getStorageClass() >= SC_Auto;
  917. }
  918. /// Returns true if a variable with function scope is a static local
  919. /// variable.
  920. bool isStaticLocal() const {
  921. return (getStorageClass() == SC_Static ||
  922. // C++11 [dcl.stc]p4
  923. (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
  924. && !isFileVarDecl();
  925. }
  926. /// Returns true if a variable has extern or __private_extern__
  927. /// storage.
  928. bool hasExternalStorage() const {
  929. return getStorageClass() == SC_Extern ||
  930. getStorageClass() == SC_PrivateExtern;
  931. }
  932. /// Returns true for all variables that do not have local storage.
  933. ///
  934. /// This includes all global variables as well as static variables declared
  935. /// within a function.
  936. bool hasGlobalStorage() const { return !hasLocalStorage(); }
  937. /// Get the storage duration of this variable, per C++ [basic.stc].
  938. StorageDuration getStorageDuration() const {
  939. return hasLocalStorage() ? SD_Automatic :
  940. getTSCSpec() ? SD_Thread : SD_Static;
  941. }
  942. /// Compute the language linkage.
  943. LanguageLinkage getLanguageLinkage() const;
  944. /// Determines whether this variable is a variable with external, C linkage.
  945. bool isExternC() const;
  946. /// Determines whether this variable's context is, or is nested within,
  947. /// a C++ extern "C" linkage spec.
  948. bool isInExternCContext() const;
  949. /// Determines whether this variable's context is, or is nested within,
  950. /// a C++ extern "C++" linkage spec.
  951. bool isInExternCXXContext() const;
  952. /// Returns true for local variable declarations other than parameters.
  953. /// Note that this includes static variables inside of functions. It also
  954. /// includes variables inside blocks.
  955. ///
  956. /// void foo() { int x; static int y; extern int z; }
  957. bool isLocalVarDecl() const {
  958. if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
  959. return false;
  960. if (const DeclContext *DC = getLexicalDeclContext())
  961. return DC->getRedeclContext()->isFunctionOrMethod();
  962. return false;
  963. }
  964. /// Similar to isLocalVarDecl but also includes parameters.
  965. bool isLocalVarDeclOrParm() const {
  966. return isLocalVarDecl() || getKind() == Decl::ParmVar;
  967. }
  968. /// Similar to isLocalVarDecl, but excludes variables declared in blocks.
  969. bool isFunctionOrMethodVarDecl() const {
  970. if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
  971. return false;
  972. const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
  973. return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
  974. }
  975. /// Determines whether this is a static data member.
  976. ///
  977. /// This will only be true in C++, and applies to, e.g., the
  978. /// variable 'x' in:
  979. /// \code
  980. /// struct S {
  981. /// static int x;
  982. /// };
  983. /// \endcode
  984. bool isStaticDataMember() const {
  985. // If it wasn't static, it would be a FieldDecl.
  986. return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
  987. }
  988. VarDecl *getCanonicalDecl() override;
  989. const VarDecl *getCanonicalDecl() const {
  990. return const_cast<VarDecl*>(this)->getCanonicalDecl();
  991. }
  992. enum DefinitionKind {
  993. /// This declaration is only a declaration.
  994. DeclarationOnly,
  995. /// This declaration is a tentative definition.
  996. TentativeDefinition,
  997. /// This declaration is definitely a definition.
  998. Definition
  999. };
  1000. /// Check whether this declaration is a definition. If this could be
  1001. /// a tentative definition (in C), don't check whether there's an overriding
  1002. /// definition.
  1003. DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
  1004. DefinitionKind isThisDeclarationADefinition() const {
  1005. return isThisDeclarationADefinition(getASTContext());
  1006. }
  1007. /// Check whether this variable is defined in this translation unit.
  1008. DefinitionKind hasDefinition(ASTContext &) const;
  1009. DefinitionKind hasDefinition() const {
  1010. return hasDefinition(getASTContext());
  1011. }
  1012. /// Get the tentative definition that acts as the real definition in a TU.
  1013. /// Returns null if there is a proper definition available.
  1014. VarDecl *getActingDefinition();
  1015. const VarDecl *getActingDefinition() const {
  1016. return const_cast<VarDecl*>(this)->getActingDefinition();
  1017. }
  1018. /// Get the real (not just tentative) definition for this declaration.
  1019. VarDecl *getDefinition(ASTContext &);
  1020. const VarDecl *getDefinition(ASTContext &C) const {
  1021. return const_cast<VarDecl*>(this)->getDefinition(C);
  1022. }
  1023. VarDecl *getDefinition() {
  1024. return getDefinition(getASTContext());
  1025. }
  1026. const VarDecl *getDefinition() const {
  1027. return const_cast<VarDecl*>(this)->getDefinition();
  1028. }
  1029. /// Determine whether this is or was instantiated from an out-of-line
  1030. /// definition of a static data member.
  1031. bool isOutOfLine() const override;
  1032. /// Returns true for file scoped variable declaration.
  1033. bool isFileVarDecl() const {
  1034. Kind K = getKind();
  1035. if (K == ParmVar || K == ImplicitParam)
  1036. return false;
  1037. if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
  1038. return true;
  1039. if (isStaticDataMember())
  1040. return true;
  1041. return false;
  1042. }
  1043. /// Get the initializer for this variable, no matter which
  1044. /// declaration it is attached to.
  1045. const Expr *getAnyInitializer() const {
  1046. const VarDecl *D;
  1047. return getAnyInitializer(D);
  1048. }
  1049. /// Get the initializer for this variable, no matter which
  1050. /// declaration it is attached to. Also get that declaration.
  1051. const Expr *getAnyInitializer(const VarDecl *&D) const;
  1052. bool hasInit() const;
  1053. const Expr *getInit() const {
  1054. return const_cast<VarDecl *>(this)->getInit();
  1055. }
  1056. Expr *getInit();
  1057. /// Retrieve the address of the initializer expression.
  1058. Stmt **getInitAddress();
  1059. void setInit(Expr *I);
  1060. /// Get the initializing declaration of this variable, if any. This is
  1061. /// usually the definition, except that for a static data member it can be
  1062. /// the in-class declaration.
  1063. VarDecl *getInitializingDeclaration();
  1064. const VarDecl *getInitializingDeclaration() const {
  1065. return const_cast<VarDecl *>(this)->getInitializingDeclaration();
  1066. }
  1067. /// Determine whether this variable's value might be usable in a
  1068. /// constant expression, according to the relevant language standard.
  1069. /// This only checks properties of the declaration, and does not check
  1070. /// whether the initializer is in fact a constant expression.
  1071. ///
  1072. /// This corresponds to C++20 [expr.const]p3's notion of a
  1073. /// "potentially-constant" variable.
  1074. bool mightBeUsableInConstantExpressions(const ASTContext &C) const;
  1075. /// Determine whether this variable's value can be used in a
  1076. /// constant expression, according to the relevant language standard,
  1077. /// including checking whether it was initialized by a constant expression.
  1078. bool isUsableInConstantExpressions(const ASTContext &C) const;
  1079. EvaluatedStmt *ensureEvaluatedStmt() const;
  1080. EvaluatedStmt *getEvaluatedStmt() const;
  1081. /// Attempt to evaluate the value of the initializer attached to this
  1082. /// declaration, and produce notes explaining why it cannot be evaluated.
  1083. /// Returns a pointer to the value if evaluation succeeded, 0 otherwise.
  1084. APValue *evaluateValue() const;
  1085. private:
  1086. APValue *evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,
  1087. bool IsConstantInitialization) const;
  1088. public:
  1089. /// Return the already-evaluated value of this variable's
  1090. /// initializer, or NULL if the value is not yet known. Returns pointer
  1091. /// to untyped APValue if the value could not be evaluated.
  1092. APValue *getEvaluatedValue() const;
  1093. /// Evaluate the destruction of this variable to determine if it constitutes
  1094. /// constant destruction.
  1095. ///
  1096. /// \pre hasConstantInitialization()
  1097. /// \return \c true if this variable has constant destruction, \c false if
  1098. /// not.
  1099. bool evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
  1100. /// Determine whether this variable has constant initialization.
  1101. ///
  1102. /// This is only set in two cases: when the language semantics require
  1103. /// constant initialization (globals in C and some globals in C++), and when
  1104. /// the variable is usable in constant expressions (constexpr, const int, and
  1105. /// reference variables in C++).
  1106. bool hasConstantInitialization() const;
  1107. /// Determine whether the initializer of this variable is an integer constant
  1108. /// expression. For use in C++98, where this affects whether the variable is
  1109. /// usable in constant expressions.
  1110. bool hasICEInitializer(const ASTContext &Context) const;
  1111. /// Evaluate the initializer of this variable to determine whether it's a
  1112. /// constant initializer. Should only be called once, after completing the
  1113. /// definition of the variable.
  1114. bool checkForConstantInitialization(
  1115. SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
  1116. void setInitStyle(InitializationStyle Style) {
  1117. VarDeclBits.InitStyle = Style;
  1118. }
  1119. /// The style of initialization for this declaration.
  1120. ///
  1121. /// C-style initialization is "int x = 1;". Call-style initialization is
  1122. /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
  1123. /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
  1124. /// expression for class types. List-style initialization is C++11 syntax,
  1125. /// e.g. "int x{1};". Clients can distinguish between different forms of
  1126. /// initialization by checking this value. In particular, "int x = {1};" is
  1127. /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
  1128. /// Init expression in all three cases is an InitListExpr.
  1129. InitializationStyle getInitStyle() const {
  1130. return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
  1131. }
  1132. /// Whether the initializer is a direct-initializer (list or call).
  1133. bool isDirectInit() const {
  1134. return getInitStyle() != CInit;
  1135. }
  1136. /// If this definition should pretend to be a declaration.
  1137. bool isThisDeclarationADemotedDefinition() const {
  1138. return isa<ParmVarDecl>(this) ? false :
  1139. NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
  1140. }
  1141. /// This is a definition which should be demoted to a declaration.
  1142. ///
  1143. /// In some cases (mostly module merging) we can end up with two visible
  1144. /// definitions one of which needs to be demoted to a declaration to keep
  1145. /// the AST invariants.
  1146. void demoteThisDefinitionToDeclaration() {
  1147. assert(isThisDeclarationADefinition() && "Not a definition!");
  1148. assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!");
  1149. NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
  1150. }
  1151. /// Determine whether this variable is the exception variable in a
  1152. /// C++ catch statememt or an Objective-C \@catch statement.
  1153. bool isExceptionVariable() const {
  1154. return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
  1155. }
  1156. void setExceptionVariable(bool EV) {
  1157. assert(!isa<ParmVarDecl>(this));
  1158. NonParmVarDeclBits.ExceptionVar = EV;
  1159. }
  1160. /// Determine whether this local variable can be used with the named
  1161. /// return value optimization (NRVO).
  1162. ///
  1163. /// The named return value optimization (NRVO) works by marking certain
  1164. /// non-volatile local variables of class type as NRVO objects. These
  1165. /// locals can be allocated within the return slot of their containing
  1166. /// function, in which case there is no need to copy the object to the
  1167. /// return slot when returning from the function. Within the function body,
  1168. /// each return that returns the NRVO object will have this variable as its
  1169. /// NRVO candidate.
  1170. bool isNRVOVariable() const {
  1171. return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
  1172. }
  1173. void setNRVOVariable(bool NRVO) {
  1174. assert(!isa<ParmVarDecl>(this));
  1175. NonParmVarDeclBits.NRVOVariable = NRVO;
  1176. }
  1177. /// Determine whether this variable is the for-range-declaration in
  1178. /// a C++0x for-range statement.
  1179. bool isCXXForRangeDecl() const {
  1180. return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
  1181. }
  1182. void setCXXForRangeDecl(bool FRD) {
  1183. assert(!isa<ParmVarDecl>(this));
  1184. NonParmVarDeclBits.CXXForRangeDecl = FRD;
  1185. }
  1186. /// Determine whether this variable is a for-loop declaration for a
  1187. /// for-in statement in Objective-C.
  1188. bool isObjCForDecl() const {
  1189. return NonParmVarDeclBits.ObjCForDecl;
  1190. }
  1191. void setObjCForDecl(bool FRD) {
  1192. NonParmVarDeclBits.ObjCForDecl = FRD;
  1193. }
  1194. /// Determine whether this variable is an ARC pseudo-__strong variable. A
  1195. /// pseudo-__strong variable has a __strong-qualified type but does not
  1196. /// actually retain the object written into it. Generally such variables are
  1197. /// also 'const' for safety. There are 3 cases where this will be set, 1) if
  1198. /// the variable is annotated with the objc_externally_retained attribute, 2)
  1199. /// if its 'self' in a non-init method, or 3) if its the variable in an for-in
  1200. /// loop.
  1201. bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
  1202. void setARCPseudoStrong(bool PS) { VarDeclBits.ARCPseudoStrong = PS; }
  1203. /// Whether this variable is (C++1z) inline.
  1204. bool isInline() const {
  1205. return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
  1206. }
  1207. bool isInlineSpecified() const {
  1208. return isa<ParmVarDecl>(this) ? false
  1209. : NonParmVarDeclBits.IsInlineSpecified;
  1210. }
  1211. void setInlineSpecified() {
  1212. assert(!isa<ParmVarDecl>(this));
  1213. NonParmVarDeclBits.IsInline = true;
  1214. NonParmVarDeclBits.IsInlineSpecified = true;
  1215. }
  1216. void setImplicitlyInline() {
  1217. assert(!isa<ParmVarDecl>(this));
  1218. NonParmVarDeclBits.IsInline = true;
  1219. }
  1220. /// Whether this variable is (C++11) constexpr.
  1221. bool isConstexpr() const {
  1222. return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
  1223. }
  1224. void setConstexpr(bool IC) {
  1225. assert(!isa<ParmVarDecl>(this));
  1226. NonParmVarDeclBits.IsConstexpr = IC;
  1227. }
  1228. /// Whether this variable is the implicit variable for a lambda init-capture.
  1229. bool isInitCapture() const {
  1230. return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
  1231. }
  1232. void setInitCapture(bool IC) {
  1233. assert(!isa<ParmVarDecl>(this));
  1234. NonParmVarDeclBits.IsInitCapture = IC;
  1235. }
  1236. /// Determine whether this variable is actually a function parameter pack or
  1237. /// init-capture pack.
  1238. bool isParameterPack() const;
  1239. /// Whether this local extern variable declaration's previous declaration
  1240. /// was declared in the same block scope. Only correct in C++.
  1241. bool isPreviousDeclInSameBlockScope() const {
  1242. return isa<ParmVarDecl>(this)
  1243. ? false
  1244. : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
  1245. }
  1246. void setPreviousDeclInSameBlockScope(bool Same) {
  1247. assert(!isa<ParmVarDecl>(this));
  1248. NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
  1249. }
  1250. /// Indicates the capture is a __block variable that is captured by a block
  1251. /// that can potentially escape (a block for which BlockDecl::doesNotEscape
  1252. /// returns false).
  1253. bool isEscapingByref() const;
  1254. /// Indicates the capture is a __block variable that is never captured by an
  1255. /// escaping block.
  1256. bool isNonEscapingByref() const;
  1257. void setEscapingByref() {
  1258. NonParmVarDeclBits.EscapingByref = true;
  1259. }
  1260. /// Determines if this variable's alignment is dependent.
  1261. bool hasDependentAlignment() const;
  1262. /// Retrieve the variable declaration from which this variable could
  1263. /// be instantiated, if it is an instantiation (rather than a non-template).
  1264. VarDecl *getTemplateInstantiationPattern() const;
  1265. /// If this variable is an instantiated static data member of a
  1266. /// class template specialization, returns the templated static data member
  1267. /// from which it was instantiated.
  1268. VarDecl *getInstantiatedFromStaticDataMember() const;
  1269. /// If this variable is an instantiation of a variable template or a
  1270. /// static data member of a class template, determine what kind of
  1271. /// template specialization or instantiation this is.
  1272. TemplateSpecializationKind getTemplateSpecializationKind() const;
  1273. /// Get the template specialization kind of this variable for the purposes of
  1274. /// template instantiation. This differs from getTemplateSpecializationKind()
  1275. /// for an instantiation of a class-scope explicit specialization.
  1276. TemplateSpecializationKind
  1277. getTemplateSpecializationKindForInstantiation() const;
  1278. /// If this variable is an instantiation of a variable template or a
  1279. /// static data member of a class template, determine its point of
  1280. /// instantiation.
  1281. SourceLocation getPointOfInstantiation() const;
  1282. /// If this variable is an instantiation of a static data member of a
  1283. /// class template specialization, retrieves the member specialization
  1284. /// information.
  1285. MemberSpecializationInfo *getMemberSpecializationInfo() const;
  1286. /// For a static data member that was instantiated from a static
  1287. /// data member of a class template, set the template specialiation kind.
  1288. void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
  1289. SourceLocation PointOfInstantiation = SourceLocation());
  1290. /// Specify that this variable is an instantiation of the
  1291. /// static data member VD.
  1292. void setInstantiationOfStaticDataMember(VarDecl *VD,
  1293. TemplateSpecializationKind TSK);
  1294. /// Retrieves the variable template that is described by this
  1295. /// variable declaration.
  1296. ///
  1297. /// Every variable template is represented as a VarTemplateDecl and a
  1298. /// VarDecl. The former contains template properties (such as
  1299. /// the template parameter lists) while the latter contains the
  1300. /// actual description of the template's
  1301. /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
  1302. /// VarDecl that from a VarTemplateDecl, while
  1303. /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
  1304. /// a VarDecl.
  1305. VarTemplateDecl *getDescribedVarTemplate() const;
  1306. void setDescribedVarTemplate(VarTemplateDecl *Template);
  1307. // Is this variable known to have a definition somewhere in the complete
  1308. // program? This may be true even if the declaration has internal linkage and
  1309. // has no definition within this source file.
  1310. bool isKnownToBeDefined() const;
  1311. /// Is destruction of this variable entirely suppressed? If so, the variable
  1312. /// need not have a usable destructor at all.
  1313. bool isNoDestroy(const ASTContext &) const;
  1314. /// Would the destruction of this variable have any effect, and if so, what
  1315. /// kind?
  1316. QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const;
  1317. // Implement isa/cast/dyncast/etc.
  1318. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  1319. static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
  1320. };
  1321. class ImplicitParamDecl : public VarDecl {
  1322. void anchor() override;
  1323. public:
  1324. /// Defines the kind of the implicit parameter: is this an implicit parameter
  1325. /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
  1326. /// context or something else.
  1327. enum ImplicitParamKind : unsigned {
  1328. /// Parameter for Objective-C 'self' argument
  1329. ObjCSelf,
  1330. /// Parameter for Objective-C '_cmd' argument
  1331. ObjCCmd,
  1332. /// Parameter for C++ 'this' argument
  1333. CXXThis,
  1334. /// Parameter for C++ virtual table pointers
  1335. CXXVTT,
  1336. /// Parameter for captured context
  1337. CapturedContext,
  1338. /// Other implicit parameter
  1339. Other,
  1340. };
  1341. /// Create implicit parameter.
  1342. static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
  1343. SourceLocation IdLoc, IdentifierInfo *Id,
  1344. QualType T, ImplicitParamKind ParamKind);
  1345. static ImplicitParamDecl *Create(ASTContext &C, QualType T,
  1346. ImplicitParamKind ParamKind);
  1347. static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  1348. ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
  1349. IdentifierInfo *Id, QualType Type,
  1350. ImplicitParamKind ParamKind)
  1351. : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
  1352. /*TInfo=*/nullptr, SC_None) {
  1353. NonParmVarDeclBits.ImplicitParamKind = ParamKind;
  1354. setImplicit();
  1355. }
  1356. ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
  1357. : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
  1358. SourceLocation(), /*Id=*/nullptr, Type,
  1359. /*TInfo=*/nullptr, SC_None) {
  1360. NonParmVarDeclBits.ImplicitParamKind = ParamKind;
  1361. setImplicit();
  1362. }
  1363. /// Returns the implicit parameter kind.
  1364. ImplicitParamKind getParameterKind() const {
  1365. return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
  1366. }
  1367. // Implement isa/cast/dyncast/etc.
  1368. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  1369. static bool classofKind(Kind K) { return K == ImplicitParam; }
  1370. };
  1371. /// Represents a parameter to a function.
  1372. class ParmVarDecl : public VarDecl {
  1373. public:
  1374. enum { MaxFunctionScopeDepth = 255 };
  1375. enum { MaxFunctionScopeIndex = 255 };
  1376. protected:
  1377. ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
  1378. SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
  1379. TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
  1380. : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
  1381. assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
  1382. assert(ParmVarDeclBits.DefaultArgKind == DAK_None);
  1383. assert(ParmVarDeclBits.IsKNRPromoted == false);
  1384. assert(ParmVarDeclBits.IsObjCMethodParam == false);
  1385. setDefaultArg(DefArg);
  1386. }
  1387. public:
  1388. static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
  1389. SourceLocation StartLoc,
  1390. SourceLocation IdLoc, IdentifierInfo *Id,
  1391. QualType T, TypeSourceInfo *TInfo,
  1392. StorageClass S, Expr *DefArg);
  1393. static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  1394. SourceRange getSourceRange() const override LLVM_READONLY;
  1395. void setObjCMethodScopeInfo(unsigned parameterIndex) {
  1396. ParmVarDeclBits.IsObjCMethodParam = true;
  1397. setParameterIndex(parameterIndex);
  1398. }
  1399. void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
  1400. assert(!ParmVarDeclBits.IsObjCMethodParam);
  1401. ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
  1402. assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth
  1403. && "truncation!");
  1404. setParameterIndex(parameterIndex);
  1405. }
  1406. bool isObjCMethodParameter() const {
  1407. return ParmVarDeclBits.IsObjCMethodParam;
  1408. }
  1409. /// Determines whether this parameter is destroyed in the callee function.
  1410. bool isDestroyedInCallee() const;
  1411. unsigned getFunctionScopeDepth() const {
  1412. if (ParmVarDeclBits.IsObjCMethodParam) return 0;
  1413. return ParmVarDeclBits.ScopeDepthOrObjCQuals;
  1414. }
  1415. static constexpr unsigned getMaxFunctionScopeDepth() {
  1416. return (1u << NumScopeDepthOrObjCQualsBits) - 1;
  1417. }
  1418. /// Returns the index of this parameter in its prototype or method scope.
  1419. unsigned getFunctionScopeIndex() const {
  1420. return getParameterIndex();
  1421. }
  1422. ObjCDeclQualifier getObjCDeclQualifier() const {
  1423. if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
  1424. return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
  1425. }
  1426. void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
  1427. assert(ParmVarDeclBits.IsObjCMethodParam);
  1428. ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
  1429. }
  1430. /// True if the value passed to this parameter must undergo
  1431. /// K&R-style default argument promotion:
  1432. ///
  1433. /// C99 6.5.2.2.
  1434. /// If the expression that denotes the called function has a type
  1435. /// that does not include a prototype, the integer promotions are
  1436. /// performed on each argument, and arguments that have type float
  1437. /// are promoted to double.
  1438. bool isKNRPromoted() const {
  1439. return ParmVarDeclBits.IsKNRPromoted;
  1440. }
  1441. void setKNRPromoted(bool promoted) {
  1442. ParmVarDeclBits.IsKNRPromoted = promoted;
  1443. }
  1444. Expr *getDefaultArg();
  1445. const Expr *getDefaultArg() const {
  1446. return const_cast<ParmVarDecl *>(this)->getDefaultArg();
  1447. }
  1448. void setDefaultArg(Expr *defarg);
  1449. /// Retrieve the source range that covers the entire default
  1450. /// argument.
  1451. SourceRange getDefaultArgRange() const;
  1452. void setUninstantiatedDefaultArg(Expr *arg);
  1453. Expr *getUninstantiatedDefaultArg();
  1454. const Expr *getUninstantiatedDefaultArg() const {
  1455. return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
  1456. }
  1457. /// Determines whether this parameter has a default argument,
  1458. /// either parsed or not.
  1459. bool hasDefaultArg() const;
  1460. /// Determines whether this parameter has a default argument that has not
  1461. /// yet been parsed. This will occur during the processing of a C++ class
  1462. /// whose member functions have default arguments, e.g.,
  1463. /// @code
  1464. /// class X {
  1465. /// public:
  1466. /// void f(int x = 17); // x has an unparsed default argument now
  1467. /// }; // x has a regular default argument now
  1468. /// @endcode
  1469. bool hasUnparsedDefaultArg() const {
  1470. return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
  1471. }
  1472. bool hasUninstantiatedDefaultArg() const {
  1473. return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
  1474. }
  1475. /// Specify that this parameter has an unparsed default argument.
  1476. /// The argument will be replaced with a real default argument via
  1477. /// setDefaultArg when the class definition enclosing the function
  1478. /// declaration that owns this default argument is completed.
  1479. void setUnparsedDefaultArg() {
  1480. ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
  1481. }
  1482. bool hasInheritedDefaultArg() const {
  1483. return ParmVarDeclBits.HasInheritedDefaultArg;
  1484. }
  1485. void setHasInheritedDefaultArg(bool I = true) {
  1486. ParmVarDeclBits.HasInheritedDefaultArg = I;
  1487. }
  1488. QualType getOriginalType() const;
  1489. /// Sets the function declaration that owns this
  1490. /// ParmVarDecl. Since ParmVarDecls are often created before the
  1491. /// FunctionDecls that own them, this routine is required to update
  1492. /// the DeclContext appropriately.
  1493. void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
  1494. // Implement isa/cast/dyncast/etc.
  1495. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  1496. static bool classofKind(Kind K) { return K == ParmVar; }
  1497. private:
  1498. enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
  1499. void setParameterIndex(unsigned parameterIndex) {
  1500. if (parameterIndex >= ParameterIndexSentinel) {
  1501. setParameterIndexLarge(parameterIndex);
  1502. return;
  1503. }
  1504. ParmVarDeclBits.ParameterIndex = parameterIndex;
  1505. assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
  1506. }
  1507. unsigned getParameterIndex() const {
  1508. unsigned d = ParmVarDeclBits.ParameterIndex;
  1509. return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
  1510. }
  1511. void setParameterIndexLarge(unsigned parameterIndex);
  1512. unsigned getParameterIndexLarge() const;
  1513. };
  1514. enum class MultiVersionKind {
  1515. None,
  1516. Target,
  1517. CPUSpecific,
  1518. CPUDispatch,
  1519. TargetClones
  1520. };
  1521. /// Represents a function declaration or definition.
  1522. ///
  1523. /// Since a given function can be declared several times in a program,
  1524. /// there may be several FunctionDecls that correspond to that
  1525. /// function. Only one of those FunctionDecls will be found when
  1526. /// traversing the list of declarations in the context of the
  1527. /// FunctionDecl (e.g., the translation unit); this FunctionDecl
  1528. /// contains all of the information known about the function. Other,
  1529. /// previous declarations of the function are available via the
  1530. /// getPreviousDecl() chain.
  1531. class FunctionDecl : public DeclaratorDecl,
  1532. public DeclContext,
  1533. public Redeclarable<FunctionDecl> {
  1534. // This class stores some data in DeclContext::FunctionDeclBits
  1535. // to save some space. Use the provided accessors to access it.
  1536. public:
  1537. /// The kind of templated function a FunctionDecl can be.
  1538. enum TemplatedKind {
  1539. // Not templated.
  1540. TK_NonTemplate,
  1541. // The pattern in a function template declaration.
  1542. TK_FunctionTemplate,
  1543. // A non-template function that is an instantiation or explicit
  1544. // specialization of a member of a templated class.
  1545. TK_MemberSpecialization,
  1546. // An instantiation or explicit specialization of a function template.
  1547. // Note: this might have been instantiated from a templated class if it
  1548. // is a class-scope explicit specialization.
  1549. TK_FunctionTemplateSpecialization,
  1550. // A function template specialization that hasn't yet been resolved to a
  1551. // particular specialized function template.
  1552. TK_DependentFunctionTemplateSpecialization
  1553. };
  1554. /// Stashed information about a defaulted function definition whose body has
  1555. /// not yet been lazily generated.
  1556. class DefaultedFunctionInfo final
  1557. : llvm::TrailingObjects<DefaultedFunctionInfo, DeclAccessPair> {
  1558. friend TrailingObjects;
  1559. unsigned NumLookups;
  1560. public:
  1561. static DefaultedFunctionInfo *Create(ASTContext &Context,
  1562. ArrayRef<DeclAccessPair> Lookups);
  1563. /// Get the unqualified lookup results that should be used in this
  1564. /// defaulted function definition.
  1565. ArrayRef<DeclAccessPair> getUnqualifiedLookups() const {
  1566. return {getTrailingObjects<DeclAccessPair>(), NumLookups};
  1567. }
  1568. };
  1569. private:
  1570. /// A new[]'d array of pointers to VarDecls for the formal
  1571. /// parameters of this function. This is null if a prototype or if there are
  1572. /// no formals.
  1573. ParmVarDecl **ParamInfo = nullptr;
  1574. /// The active member of this union is determined by
  1575. /// FunctionDeclBits.HasDefaultedFunctionInfo.
  1576. union {
  1577. /// The body of the function.
  1578. LazyDeclStmtPtr Body;
  1579. /// Information about a future defaulted function definition.
  1580. DefaultedFunctionInfo *DefaultedInfo;
  1581. };
  1582. unsigned ODRHash;
  1583. /// End part of this FunctionDecl's source range.
  1584. ///
  1585. /// We could compute the full range in getSourceRange(). However, when we're
  1586. /// dealing with a function definition deserialized from a PCH/AST file,
  1587. /// we can only compute the full range once the function body has been
  1588. /// de-serialized, so it's far better to have the (sometimes-redundant)
  1589. /// EndRangeLoc.
  1590. SourceLocation EndRangeLoc;
  1591. /// The template or declaration that this declaration
  1592. /// describes or was instantiated from, respectively.
  1593. ///
  1594. /// For non-templates, this value will be NULL. For function
  1595. /// declarations that describe a function template, this will be a
  1596. /// pointer to a FunctionTemplateDecl. For member functions
  1597. /// of class template specializations, this will be a MemberSpecializationInfo
  1598. /// pointer containing information about the specialization.
  1599. /// For function template specializations, this will be a
  1600. /// FunctionTemplateSpecializationInfo, which contains information about
  1601. /// the template being specialized and the template arguments involved in
  1602. /// that specialization.
  1603. llvm::PointerUnion<FunctionTemplateDecl *,
  1604. MemberSpecializationInfo *,
  1605. FunctionTemplateSpecializationInfo *,
  1606. DependentFunctionTemplateSpecializationInfo *>
  1607. TemplateOrSpecialization;
  1608. /// Provides source/type location info for the declaration name embedded in
  1609. /// the DeclaratorDecl base class.
  1610. DeclarationNameLoc DNLoc;
  1611. /// Specify that this function declaration is actually a function
  1612. /// template specialization.
  1613. ///
  1614. /// \param C the ASTContext.
  1615. ///
  1616. /// \param Template the function template that this function template
  1617. /// specialization specializes.
  1618. ///
  1619. /// \param TemplateArgs the template arguments that produced this
  1620. /// function template specialization from the template.
  1621. ///
  1622. /// \param InsertPos If non-NULL, the position in the function template
  1623. /// specialization set where the function template specialization data will
  1624. /// be inserted.
  1625. ///
  1626. /// \param TSK the kind of template specialization this is.
  1627. ///
  1628. /// \param TemplateArgsAsWritten location info of template arguments.
  1629. ///
  1630. /// \param PointOfInstantiation point at which the function template
  1631. /// specialization was first instantiated.
  1632. void setFunctionTemplateSpecialization(ASTContext &C,
  1633. FunctionTemplateDecl *Template,
  1634. const TemplateArgumentList *TemplateArgs,
  1635. void *InsertPos,
  1636. TemplateSpecializationKind TSK,
  1637. const TemplateArgumentListInfo *TemplateArgsAsWritten,
  1638. SourceLocation PointOfInstantiation);
  1639. /// Specify that this record is an instantiation of the
  1640. /// member function FD.
  1641. void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
  1642. TemplateSpecializationKind TSK);
  1643. void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
  1644. // This is unfortunately needed because ASTDeclWriter::VisitFunctionDecl
  1645. // need to access this bit but we want to avoid making ASTDeclWriter
  1646. // a friend of FunctionDeclBitfields just for this.
  1647. bool isDeletedBit() const { return FunctionDeclBits.IsDeleted; }
  1648. /// Whether an ODRHash has been stored.
  1649. bool hasODRHash() const { return FunctionDeclBits.HasODRHash; }
  1650. /// State that an ODRHash has been stored.
  1651. void setHasODRHash(bool B = true) { FunctionDeclBits.HasODRHash = B; }
  1652. protected:
  1653. FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
  1654. const DeclarationNameInfo &NameInfo, QualType T,
  1655. TypeSourceInfo *TInfo, StorageClass S, bool UsesFPIntrin,
  1656. bool isInlineSpecified, ConstexprSpecKind ConstexprKind,
  1657. Expr *TrailingRequiresClause = nullptr);
  1658. using redeclarable_base = Redeclarable<FunctionDecl>;
  1659. FunctionDecl *getNextRedeclarationImpl() override {
  1660. return getNextRedeclaration();
  1661. }
  1662. FunctionDecl *getPreviousDeclImpl() override {
  1663. return getPreviousDecl();
  1664. }
  1665. FunctionDecl *getMostRecentDeclImpl() override {
  1666. return getMostRecentDecl();
  1667. }
  1668. public:
  1669. friend class ASTDeclReader;
  1670. friend class ASTDeclWriter;
  1671. using redecl_range = redeclarable_base::redecl_range;
  1672. using redecl_iterator = redeclarable_base::redecl_iterator;
  1673. using redeclarable_base::redecls_begin;
  1674. using redeclarable_base::redecls_end;
  1675. using redeclarable_base::redecls;
  1676. using redeclarable_base::getPreviousDecl;
  1677. using redeclarable_base::getMostRecentDecl;
  1678. using redeclarable_base::isFirstDecl;
  1679. static FunctionDecl *
  1680. Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
  1681. SourceLocation NLoc, DeclarationName N, QualType T,
  1682. TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin = false,
  1683. bool isInlineSpecified = false, bool hasWrittenPrototype = true,
  1684. ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified,
  1685. Expr *TrailingRequiresClause = nullptr) {
  1686. DeclarationNameInfo NameInfo(N, NLoc);
  1687. return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo, SC,
  1688. UsesFPIntrin, isInlineSpecified,
  1689. hasWrittenPrototype, ConstexprKind,
  1690. TrailingRequiresClause);
  1691. }
  1692. static FunctionDecl *
  1693. Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
  1694. const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
  1695. StorageClass SC, bool UsesFPIntrin, bool isInlineSpecified,
  1696. bool hasWrittenPrototype, ConstexprSpecKind ConstexprKind,
  1697. Expr *TrailingRequiresClause);
  1698. static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  1699. DeclarationNameInfo getNameInfo() const {
  1700. return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
  1701. }
  1702. void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
  1703. bool Qualified) const override;
  1704. void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
  1705. /// Returns the location of the ellipsis of a variadic function.
  1706. SourceLocation getEllipsisLoc() const {
  1707. const auto *FPT = getType()->getAs<FunctionProtoType>();
  1708. if (FPT && FPT->isVariadic())
  1709. return FPT->getEllipsisLoc();
  1710. return SourceLocation();
  1711. }
  1712. SourceRange getSourceRange() const override LLVM_READONLY;
  1713. // Function definitions.
  1714. //
  1715. // A function declaration may be:
  1716. // - a non defining declaration,
  1717. // - a definition. A function may be defined because:
  1718. // - it has a body, or will have it in the case of late parsing.
  1719. // - it has an uninstantiated body. The body does not exist because the
  1720. // function is not used yet, but the declaration is considered a
  1721. // definition and does not allow other definition of this function.
  1722. // - it does not have a user specified body, but it does not allow
  1723. // redefinition, because it is deleted/defaulted or is defined through
  1724. // some other mechanism (alias, ifunc).
  1725. /// Returns true if the function has a body.
  1726. ///
  1727. /// The function body might be in any of the (re-)declarations of this
  1728. /// function. The variant that accepts a FunctionDecl pointer will set that
  1729. /// function declaration to the actual declaration containing the body (if
  1730. /// there is one).
  1731. bool hasBody(const FunctionDecl *&Definition) const;
  1732. bool hasBody() const override {
  1733. const FunctionDecl* Definition;
  1734. return hasBody(Definition);
  1735. }
  1736. /// Returns whether the function has a trivial body that does not require any
  1737. /// specific codegen.
  1738. bool hasTrivialBody() const;
  1739. /// Returns true if the function has a definition that does not need to be
  1740. /// instantiated.
  1741. ///
  1742. /// The variant that accepts a FunctionDecl pointer will set that function
  1743. /// declaration to the declaration that is a definition (if there is one).
  1744. ///
  1745. /// \param CheckForPendingFriendDefinition If \c true, also check for friend
  1746. /// declarations that were instantiataed from function definitions.
  1747. /// Such a declaration behaves as if it is a definition for the
  1748. /// purpose of redefinition checking, but isn't actually a "real"
  1749. /// definition until its body is instantiated.
  1750. bool isDefined(const FunctionDecl *&Definition,
  1751. bool CheckForPendingFriendDefinition = false) const;
  1752. bool isDefined() const {
  1753. const FunctionDecl* Definition;
  1754. return isDefined(Definition);
  1755. }
  1756. /// Get the definition for this declaration.
  1757. FunctionDecl *getDefinition() {
  1758. const FunctionDecl *Definition;
  1759. if (isDefined(Definition))
  1760. return const_cast<FunctionDecl *>(Definition);
  1761. return nullptr;
  1762. }
  1763. const FunctionDecl *getDefinition() const {
  1764. return const_cast<FunctionDecl *>(this)->getDefinition();
  1765. }
  1766. /// Retrieve the body (definition) of the function. The function body might be
  1767. /// in any of the (re-)declarations of this function. The variant that accepts
  1768. /// a FunctionDecl pointer will set that function declaration to the actual
  1769. /// declaration containing the body (if there is one).
  1770. /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
  1771. /// unnecessary AST de-serialization of the body.
  1772. Stmt *getBody(const FunctionDecl *&Definition) const;
  1773. Stmt *getBody() const override {
  1774. const FunctionDecl* Definition;
  1775. return getBody(Definition);
  1776. }
  1777. /// Returns whether this specific declaration of the function is also a
  1778. /// definition that does not contain uninstantiated body.
  1779. ///
  1780. /// This does not determine whether the function has been defined (e.g., in a
  1781. /// previous definition); for that information, use isDefined.
  1782. ///
  1783. /// Note: the function declaration does not become a definition until the
  1784. /// parser reaches the definition, if called before, this function will return
  1785. /// `false`.
  1786. bool isThisDeclarationADefinition() const {
  1787. return isDeletedAsWritten() || isDefaulted() ||
  1788. doesThisDeclarationHaveABody() || hasSkippedBody() ||
  1789. willHaveBody() || hasDefiningAttr();
  1790. }
  1791. /// Determine whether this specific declaration of the function is a friend
  1792. /// declaration that was instantiated from a function definition. Such
  1793. /// declarations behave like definitions in some contexts.
  1794. bool isThisDeclarationInstantiatedFromAFriendDefinition() const;
  1795. /// Returns whether this specific declaration of the function has a body.
  1796. bool doesThisDeclarationHaveABody() const {
  1797. return (!FunctionDeclBits.HasDefaultedFunctionInfo && Body) ||
  1798. isLateTemplateParsed();
  1799. }
  1800. void setBody(Stmt *B);
  1801. void setLazyBody(uint64_t Offset) {
  1802. FunctionDeclBits.HasDefaultedFunctionInfo = false;
  1803. Body = LazyDeclStmtPtr(Offset);
  1804. }
  1805. void setDefaultedFunctionInfo(DefaultedFunctionInfo *Info);
  1806. DefaultedFunctionInfo *getDefaultedFunctionInfo() const;
  1807. /// Whether this function is variadic.
  1808. bool isVariadic() const;
  1809. /// Whether this function is marked as virtual explicitly.
  1810. bool isVirtualAsWritten() const {
  1811. return FunctionDeclBits.IsVirtualAsWritten;
  1812. }
  1813. /// State that this function is marked as virtual explicitly.
  1814. void setVirtualAsWritten(bool V) { FunctionDeclBits.IsVirtualAsWritten = V; }
  1815. /// Whether this virtual function is pure, i.e. makes the containing class
  1816. /// abstract.
  1817. bool isPure() const { return FunctionDeclBits.IsPure; }
  1818. void setPure(bool P = true);
  1819. /// Whether this templated function will be late parsed.
  1820. bool isLateTemplateParsed() const {
  1821. return FunctionDeclBits.IsLateTemplateParsed;
  1822. }
  1823. /// State that this templated function will be late parsed.
  1824. void setLateTemplateParsed(bool ILT = true) {
  1825. FunctionDeclBits.IsLateTemplateParsed = ILT;
  1826. }
  1827. /// Whether this function is "trivial" in some specialized C++ senses.
  1828. /// Can only be true for default constructors, copy constructors,
  1829. /// copy assignment operators, and destructors. Not meaningful until
  1830. /// the class has been fully built by Sema.
  1831. bool isTrivial() const { return FunctionDeclBits.IsTrivial; }
  1832. void setTrivial(bool IT) { FunctionDeclBits.IsTrivial = IT; }
  1833. bool isTrivialForCall() const { return FunctionDeclBits.IsTrivialForCall; }
  1834. void setTrivialForCall(bool IT) { FunctionDeclBits.IsTrivialForCall = IT; }
  1835. /// Whether this function is defaulted. Valid for e.g.
  1836. /// special member functions, defaulted comparisions (not methods!).
  1837. bool isDefaulted() const { return FunctionDeclBits.IsDefaulted; }
  1838. void setDefaulted(bool D = true) { FunctionDeclBits.IsDefaulted = D; }
  1839. /// Whether this function is explicitly defaulted.
  1840. bool isExplicitlyDefaulted() const {
  1841. return FunctionDeclBits.IsExplicitlyDefaulted;
  1842. }
  1843. /// State that this function is explicitly defaulted.
  1844. void setExplicitlyDefaulted(bool ED = true) {
  1845. FunctionDeclBits.IsExplicitlyDefaulted = ED;
  1846. }
  1847. /// True if this method is user-declared and was not
  1848. /// deleted or defaulted on its first declaration.
  1849. bool isUserProvided() const {
  1850. auto *DeclAsWritten = this;
  1851. if (FunctionDecl *Pattern = getTemplateInstantiationPattern())
  1852. DeclAsWritten = Pattern;
  1853. return !(DeclAsWritten->isDeleted() ||
  1854. DeclAsWritten->getCanonicalDecl()->isDefaulted());
  1855. }
  1856. /// Whether falling off this function implicitly returns null/zero.
  1857. /// If a more specific implicit return value is required, front-ends
  1858. /// should synthesize the appropriate return statements.
  1859. bool hasImplicitReturnZero() const {
  1860. return FunctionDeclBits.HasImplicitReturnZero;
  1861. }
  1862. /// State that falling off this function implicitly returns null/zero.
  1863. /// If a more specific implicit return value is required, front-ends
  1864. /// should synthesize the appropriate return statements.
  1865. void setHasImplicitReturnZero(bool IRZ) {
  1866. FunctionDeclBits.HasImplicitReturnZero = IRZ;
  1867. }
  1868. /// Whether this function has a prototype, either because one
  1869. /// was explicitly written or because it was "inherited" by merging
  1870. /// a declaration without a prototype with a declaration that has a
  1871. /// prototype.
  1872. bool hasPrototype() const {
  1873. return hasWrittenPrototype() || hasInheritedPrototype();
  1874. }
  1875. /// Whether this function has a written prototype.
  1876. bool hasWrittenPrototype() const {
  1877. return FunctionDeclBits.HasWrittenPrototype;
  1878. }
  1879. /// State that this function has a written prototype.
  1880. void setHasWrittenPrototype(bool P = true) {
  1881. FunctionDeclBits.HasWrittenPrototype = P;
  1882. }
  1883. /// Whether this function inherited its prototype from a
  1884. /// previous declaration.
  1885. bool hasInheritedPrototype() const {
  1886. return FunctionDeclBits.HasInheritedPrototype;
  1887. }
  1888. /// State that this function inherited its prototype from a
  1889. /// previous declaration.
  1890. void setHasInheritedPrototype(bool P = true) {
  1891. FunctionDeclBits.HasInheritedPrototype = P;
  1892. }
  1893. /// Whether this is a (C++11) constexpr function or constexpr constructor.
  1894. bool isConstexpr() const {
  1895. return getConstexprKind() != ConstexprSpecKind::Unspecified;
  1896. }
  1897. void setConstexprKind(ConstexprSpecKind CSK) {
  1898. FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(CSK);
  1899. }
  1900. ConstexprSpecKind getConstexprKind() const {
  1901. return static_cast<ConstexprSpecKind>(FunctionDeclBits.ConstexprKind);
  1902. }
  1903. bool isConstexprSpecified() const {
  1904. return getConstexprKind() == ConstexprSpecKind::Constexpr;
  1905. }
  1906. bool isConsteval() const {
  1907. return getConstexprKind() == ConstexprSpecKind::Consteval;
  1908. }
  1909. /// Whether the instantiation of this function is pending.
  1910. /// This bit is set when the decision to instantiate this function is made
  1911. /// and unset if and when the function body is created. That leaves out
  1912. /// cases where instantiation did not happen because the template definition
  1913. /// was not seen in this TU. This bit remains set in those cases, under the
  1914. /// assumption that the instantiation will happen in some other TU.
  1915. bool instantiationIsPending() const {
  1916. return FunctionDeclBits.InstantiationIsPending;
  1917. }
  1918. /// State that the instantiation of this function is pending.
  1919. /// (see instantiationIsPending)
  1920. void setInstantiationIsPending(bool IC) {
  1921. FunctionDeclBits.InstantiationIsPending = IC;
  1922. }
  1923. /// Indicates the function uses __try.
  1924. bool usesSEHTry() const { return FunctionDeclBits.UsesSEHTry; }
  1925. void setUsesSEHTry(bool UST) { FunctionDeclBits.UsesSEHTry = UST; }
  1926. /// Whether this function has been deleted.
  1927. ///
  1928. /// A function that is "deleted" (via the C++0x "= delete" syntax)
  1929. /// acts like a normal function, except that it cannot actually be
  1930. /// called or have its address taken. Deleted functions are
  1931. /// typically used in C++ overload resolution to attract arguments
  1932. /// whose type or lvalue/rvalue-ness would permit the use of a
  1933. /// different overload that would behave incorrectly. For example,
  1934. /// one might use deleted functions to ban implicit conversion from
  1935. /// a floating-point number to an Integer type:
  1936. ///
  1937. /// @code
  1938. /// struct Integer {
  1939. /// Integer(long); // construct from a long
  1940. /// Integer(double) = delete; // no construction from float or double
  1941. /// Integer(long double) = delete; // no construction from long double
  1942. /// };
  1943. /// @endcode
  1944. // If a function is deleted, its first declaration must be.
  1945. bool isDeleted() const {
  1946. return getCanonicalDecl()->FunctionDeclBits.IsDeleted;
  1947. }
  1948. bool isDeletedAsWritten() const {
  1949. return FunctionDeclBits.IsDeleted && !isDefaulted();
  1950. }
  1951. void setDeletedAsWritten(bool D = true) { FunctionDeclBits.IsDeleted = D; }
  1952. /// Determines whether this function is "main", which is the
  1953. /// entry point into an executable program.
  1954. bool isMain() const;
  1955. /// Determines whether this function is a MSVCRT user defined entry
  1956. /// point.
  1957. bool isMSVCRTEntryPoint() const;
  1958. /// Determines whether this operator new or delete is one
  1959. /// of the reserved global placement operators:
  1960. /// void *operator new(size_t, void *);
  1961. /// void *operator new[](size_t, void *);
  1962. /// void operator delete(void *, void *);
  1963. /// void operator delete[](void *, void *);
  1964. /// These functions have special behavior under [new.delete.placement]:
  1965. /// These functions are reserved, a C++ program may not define
  1966. /// functions that displace the versions in the Standard C++ library.
  1967. /// The provisions of [basic.stc.dynamic] do not apply to these
  1968. /// reserved placement forms of operator new and operator delete.
  1969. ///
  1970. /// This function must be an allocation or deallocation function.
  1971. bool isReservedGlobalPlacementOperator() const;
  1972. /// Determines whether this function is one of the replaceable
  1973. /// global allocation functions:
  1974. /// void *operator new(size_t);
  1975. /// void *operator new(size_t, const std::nothrow_t &) noexcept;
  1976. /// void *operator new[](size_t);
  1977. /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
  1978. /// void operator delete(void *) noexcept;
  1979. /// void operator delete(void *, std::size_t) noexcept; [C++1y]
  1980. /// void operator delete(void *, const std::nothrow_t &) noexcept;
  1981. /// void operator delete[](void *) noexcept;
  1982. /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
  1983. /// void operator delete[](void *, const std::nothrow_t &) noexcept;
  1984. /// These functions have special behavior under C++1y [expr.new]:
  1985. /// An implementation is allowed to omit a call to a replaceable global
  1986. /// allocation function. [...]
  1987. ///
  1988. /// If this function is an aligned allocation/deallocation function, return
  1989. /// the parameter number of the requested alignment through AlignmentParam.
  1990. ///
  1991. /// If this function is an allocation/deallocation function that takes
  1992. /// the `std::nothrow_t` tag, return true through IsNothrow,
  1993. bool isReplaceableGlobalAllocationFunction(
  1994. Optional<unsigned> *AlignmentParam = nullptr,
  1995. bool *IsNothrow = nullptr) const;
  1996. /// Determine if this function provides an inline implementation of a builtin.
  1997. bool isInlineBuiltinDeclaration() const;
  1998. /// Determine whether this is a destroying operator delete.
  1999. bool isDestroyingOperatorDelete() const;
  2000. /// Compute the language linkage.
  2001. LanguageLinkage getLanguageLinkage() const;
  2002. /// Determines whether this function is a function with
  2003. /// external, C linkage.
  2004. bool isExternC() const;
  2005. /// Determines whether this function's context is, or is nested within,
  2006. /// a C++ extern "C" linkage spec.
  2007. bool isInExternCContext() const;
  2008. /// Determines whether this function's context is, or is nested within,
  2009. /// a C++ extern "C++" linkage spec.
  2010. bool isInExternCXXContext() const;
  2011. /// Determines whether this is a global function.
  2012. bool isGlobal() const;
  2013. /// Determines whether this function is known to be 'noreturn', through
  2014. /// an attribute on its declaration or its type.
  2015. bool isNoReturn() const;
  2016. /// True if the function was a definition but its body was skipped.
  2017. bool hasSkippedBody() const { return FunctionDeclBits.HasSkippedBody; }
  2018. void setHasSkippedBody(bool Skipped = true) {
  2019. FunctionDeclBits.HasSkippedBody = Skipped;
  2020. }
  2021. /// True if this function will eventually have a body, once it's fully parsed.
  2022. bool willHaveBody() const { return FunctionDeclBits.WillHaveBody; }
  2023. void setWillHaveBody(bool V = true) { FunctionDeclBits.WillHaveBody = V; }
  2024. /// True if this function is considered a multiversioned function.
  2025. bool isMultiVersion() const {
  2026. return getCanonicalDecl()->FunctionDeclBits.IsMultiVersion;
  2027. }
  2028. /// Sets the multiversion state for this declaration and all of its
  2029. /// redeclarations.
  2030. void setIsMultiVersion(bool V = true) {
  2031. getCanonicalDecl()->FunctionDeclBits.IsMultiVersion = V;
  2032. }
  2033. /// Gets the kind of multiversioning attribute this declaration has. Note that
  2034. /// this can return a value even if the function is not multiversion, such as
  2035. /// the case of 'target'.
  2036. MultiVersionKind getMultiVersionKind() const;
  2037. /// True if this function is a multiversioned dispatch function as a part of
  2038. /// the cpu_specific/cpu_dispatch functionality.
  2039. bool isCPUDispatchMultiVersion() const;
  2040. /// True if this function is a multiversioned processor specific function as a
  2041. /// part of the cpu_specific/cpu_dispatch functionality.
  2042. bool isCPUSpecificMultiVersion() const;
  2043. /// True if this function is a multiversioned dispatch function as a part of
  2044. /// the target functionality.
  2045. bool isTargetMultiVersion() const;
  2046. /// True if this function is a multiversioned dispatch function as a part of
  2047. /// the target-clones functionality.
  2048. bool isTargetClonesMultiVersion() const;
  2049. /// \brief Get the associated-constraints of this function declaration.
  2050. /// Currently, this will either be a vector of size 1 containing the
  2051. /// trailing-requires-clause or an empty vector.
  2052. ///
  2053. /// Use this instead of getTrailingRequiresClause for concepts APIs that
  2054. /// accept an ArrayRef of constraint expressions.
  2055. void getAssociatedConstraints(SmallVectorImpl<const Expr *> &AC) const {
  2056. if (auto *TRC = getTrailingRequiresClause())
  2057. AC.push_back(TRC);
  2058. }
  2059. void setPreviousDeclaration(FunctionDecl * PrevDecl);
  2060. FunctionDecl *getCanonicalDecl() override;
  2061. const FunctionDecl *getCanonicalDecl() const {
  2062. return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
  2063. }
  2064. unsigned getBuiltinID(bool ConsiderWrapperFunctions = false) const;
  2065. // ArrayRef interface to parameters.
  2066. ArrayRef<ParmVarDecl *> parameters() const {
  2067. return {ParamInfo, getNumParams()};
  2068. }
  2069. MutableArrayRef<ParmVarDecl *> parameters() {
  2070. return {ParamInfo, getNumParams()};
  2071. }
  2072. // Iterator access to formal parameters.
  2073. using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
  2074. using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
  2075. bool param_empty() const { return parameters().empty(); }
  2076. param_iterator param_begin() { return parameters().begin(); }
  2077. param_iterator param_end() { return parameters().end(); }
  2078. param_const_iterator param_begin() const { return parameters().begin(); }
  2079. param_const_iterator param_end() const { return parameters().end(); }
  2080. size_t param_size() const { return parameters().size(); }
  2081. /// Return the number of parameters this function must have based on its
  2082. /// FunctionType. This is the length of the ParamInfo array after it has been
  2083. /// created.
  2084. unsigned getNumParams() const;
  2085. const ParmVarDecl *getParamDecl(unsigned i) const {
  2086. assert(i < getNumParams() && "Illegal param #");
  2087. return ParamInfo[i];
  2088. }
  2089. ParmVarDecl *getParamDecl(unsigned i) {
  2090. assert(i < getNumParams() && "Illegal param #");
  2091. return ParamInfo[i];
  2092. }
  2093. void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
  2094. setParams(getASTContext(), NewParamInfo);
  2095. }
  2096. /// Returns the minimum number of arguments needed to call this function. This
  2097. /// may be fewer than the number of function parameters, if some of the
  2098. /// parameters have default arguments (in C++).
  2099. unsigned getMinRequiredArguments() const;
  2100. /// Determine whether this function has a single parameter, or multiple
  2101. /// parameters where all but the first have default arguments.
  2102. ///
  2103. /// This notion is used in the definition of copy/move constructors and
  2104. /// initializer list constructors. Note that, unlike getMinRequiredArguments,
  2105. /// parameter packs are not treated specially here.
  2106. bool hasOneParamOrDefaultArgs() const;
  2107. /// Find the source location information for how the type of this function
  2108. /// was written. May be absent (for example if the function was declared via
  2109. /// a typedef) and may contain a different type from that of the function
  2110. /// (for example if the function type was adjusted by an attribute).
  2111. FunctionTypeLoc getFunctionTypeLoc() const;
  2112. QualType getReturnType() const {
  2113. return getType()->castAs<FunctionType>()->getReturnType();
  2114. }
  2115. /// Attempt to compute an informative source range covering the
  2116. /// function return type. This may omit qualifiers and other information with
  2117. /// limited representation in the AST.
  2118. SourceRange getReturnTypeSourceRange() const;
  2119. /// Attempt to compute an informative source range covering the
  2120. /// function parameters, including the ellipsis of a variadic function.
  2121. /// The source range excludes the parentheses, and is invalid if there are
  2122. /// no parameters and no ellipsis.
  2123. SourceRange getParametersSourceRange() const;
  2124. /// Get the declared return type, which may differ from the actual return
  2125. /// type if the return type is deduced.
  2126. QualType getDeclaredReturnType() const {
  2127. auto *TSI = getTypeSourceInfo();
  2128. QualType T = TSI ? TSI->getType() : getType();
  2129. return T->castAs<FunctionType>()->getReturnType();
  2130. }
  2131. /// Gets the ExceptionSpecificationType as declared.
  2132. ExceptionSpecificationType getExceptionSpecType() const {
  2133. auto *TSI = getTypeSourceInfo();
  2134. QualType T = TSI ? TSI->getType() : getType();
  2135. const auto *FPT = T->getAs<FunctionProtoType>();
  2136. return FPT ? FPT->getExceptionSpecType() : EST_None;
  2137. }
  2138. /// Attempt to compute an informative source range covering the
  2139. /// function exception specification, if any.
  2140. SourceRange getExceptionSpecSourceRange() const;
  2141. /// Determine the type of an expression that calls this function.
  2142. QualType getCallResultType() const {
  2143. return getType()->castAs<FunctionType>()->getCallResultType(
  2144. getASTContext());
  2145. }
  2146. /// Returns the storage class as written in the source. For the
  2147. /// computed linkage of symbol, see getLinkage.
  2148. StorageClass getStorageClass() const {
  2149. return static_cast<StorageClass>(FunctionDeclBits.SClass);
  2150. }
  2151. /// Sets the storage class as written in the source.
  2152. void setStorageClass(StorageClass SClass) {
  2153. FunctionDeclBits.SClass = SClass;
  2154. }
  2155. /// Determine whether the "inline" keyword was specified for this
  2156. /// function.
  2157. bool isInlineSpecified() const { return FunctionDeclBits.IsInlineSpecified; }
  2158. /// Set whether the "inline" keyword was specified for this function.
  2159. void setInlineSpecified(bool I) {
  2160. FunctionDeclBits.IsInlineSpecified = I;
  2161. FunctionDeclBits.IsInline = I;
  2162. }
  2163. /// Determine whether the function was declared in source context
  2164. /// that requires constrained FP intrinsics
  2165. bool UsesFPIntrin() const { return FunctionDeclBits.UsesFPIntrin; }
  2166. /// Set whether the function was declared in source context
  2167. /// that requires constrained FP intrinsics
  2168. void setUsesFPIntrin(bool I) { FunctionDeclBits.UsesFPIntrin = I; }
  2169. /// Flag that this function is implicitly inline.
  2170. void setImplicitlyInline(bool I = true) { FunctionDeclBits.IsInline = I; }
  2171. /// Determine whether this function should be inlined, because it is
  2172. /// either marked "inline" or "constexpr" or is a member function of a class
  2173. /// that was defined in the class body.
  2174. bool isInlined() const { return FunctionDeclBits.IsInline; }
  2175. bool isInlineDefinitionExternallyVisible() const;
  2176. bool isMSExternInline() const;
  2177. bool doesDeclarationForceExternallyVisibleDefinition() const;
  2178. bool isStatic() const { return getStorageClass() == SC_Static; }
  2179. /// Whether this function declaration represents an C++ overloaded
  2180. /// operator, e.g., "operator+".
  2181. bool isOverloadedOperator() const {
  2182. return getOverloadedOperator() != OO_None;
  2183. }
  2184. OverloadedOperatorKind getOverloadedOperator() const;
  2185. const IdentifierInfo *getLiteralIdentifier() const;
  2186. /// If this function is an instantiation of a member function
  2187. /// of a class template specialization, retrieves the function from
  2188. /// which it was instantiated.
  2189. ///
  2190. /// This routine will return non-NULL for (non-templated) member
  2191. /// functions of class templates and for instantiations of function
  2192. /// templates. For example, given:
  2193. ///
  2194. /// \code
  2195. /// template<typename T>
  2196. /// struct X {
  2197. /// void f(T);
  2198. /// };
  2199. /// \endcode
  2200. ///
  2201. /// The declaration for X<int>::f is a (non-templated) FunctionDecl
  2202. /// whose parent is the class template specialization X<int>. For
  2203. /// this declaration, getInstantiatedFromFunction() will return
  2204. /// the FunctionDecl X<T>::A. When a complete definition of
  2205. /// X<int>::A is required, it will be instantiated from the
  2206. /// declaration returned by getInstantiatedFromMemberFunction().
  2207. FunctionDecl *getInstantiatedFromMemberFunction() const;
  2208. /// What kind of templated function this is.
  2209. TemplatedKind getTemplatedKind() const;
  2210. /// If this function is an instantiation of a member function of a
  2211. /// class template specialization, retrieves the member specialization
  2212. /// information.
  2213. MemberSpecializationInfo *getMemberSpecializationInfo() const;
  2214. /// Specify that this record is an instantiation of the
  2215. /// member function FD.
  2216. void setInstantiationOfMemberFunction(FunctionDecl *FD,
  2217. TemplateSpecializationKind TSK) {
  2218. setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
  2219. }
  2220. /// Retrieves the function template that is described by this
  2221. /// function declaration.
  2222. ///
  2223. /// Every function template is represented as a FunctionTemplateDecl
  2224. /// and a FunctionDecl (or something derived from FunctionDecl). The
  2225. /// former contains template properties (such as the template
  2226. /// parameter lists) while the latter contains the actual
  2227. /// description of the template's
  2228. /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
  2229. /// FunctionDecl that describes the function template,
  2230. /// getDescribedFunctionTemplate() retrieves the
  2231. /// FunctionTemplateDecl from a FunctionDecl.
  2232. FunctionTemplateDecl *getDescribedFunctionTemplate() const;
  2233. void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
  2234. /// Determine whether this function is a function template
  2235. /// specialization.
  2236. bool isFunctionTemplateSpecialization() const {
  2237. return getPrimaryTemplate() != nullptr;
  2238. }
  2239. /// If this function is actually a function template specialization,
  2240. /// retrieve information about this function template specialization.
  2241. /// Otherwise, returns NULL.
  2242. FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
  2243. /// Determines whether this function is a function template
  2244. /// specialization or a member of a class template specialization that can
  2245. /// be implicitly instantiated.
  2246. bool isImplicitlyInstantiable() const;
  2247. /// Determines if the given function was instantiated from a
  2248. /// function template.
  2249. bool isTemplateInstantiation() const;
  2250. /// Retrieve the function declaration from which this function could
  2251. /// be instantiated, if it is an instantiation (rather than a non-template
  2252. /// or a specialization, for example).
  2253. ///
  2254. /// If \p ForDefinition is \c false, explicit specializations will be treated
  2255. /// as if they were implicit instantiations. This will then find the pattern
  2256. /// corresponding to non-definition portions of the declaration, such as
  2257. /// default arguments and the exception specification.
  2258. FunctionDecl *
  2259. getTemplateInstantiationPattern(bool ForDefinition = true) const;
  2260. /// Retrieve the primary template that this function template
  2261. /// specialization either specializes or was instantiated from.
  2262. ///
  2263. /// If this function declaration is not a function template specialization,
  2264. /// returns NULL.
  2265. FunctionTemplateDecl *getPrimaryTemplate() const;
  2266. /// Retrieve the template arguments used to produce this function
  2267. /// template specialization from the primary template.
  2268. ///
  2269. /// If this function declaration is not a function template specialization,
  2270. /// returns NULL.
  2271. const TemplateArgumentList *getTemplateSpecializationArgs() const;
  2272. /// Retrieve the template argument list as written in the sources,
  2273. /// if any.
  2274. ///
  2275. /// If this function declaration is not a function template specialization
  2276. /// or if it had no explicit template argument list, returns NULL.
  2277. /// Note that it an explicit template argument list may be written empty,
  2278. /// e.g., template<> void foo<>(char* s);
  2279. const ASTTemplateArgumentListInfo*
  2280. getTemplateSpecializationArgsAsWritten() const;
  2281. /// Specify that this function declaration is actually a function
  2282. /// template specialization.
  2283. ///
  2284. /// \param Template the function template that this function template
  2285. /// specialization specializes.
  2286. ///
  2287. /// \param TemplateArgs the template arguments that produced this
  2288. /// function template specialization from the template.
  2289. ///
  2290. /// \param InsertPos If non-NULL, the position in the function template
  2291. /// specialization set where the function template specialization data will
  2292. /// be inserted.
  2293. ///
  2294. /// \param TSK the kind of template specialization this is.
  2295. ///
  2296. /// \param TemplateArgsAsWritten location info of template arguments.
  2297. ///
  2298. /// \param PointOfInstantiation point at which the function template
  2299. /// specialization was first instantiated.
  2300. void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
  2301. const TemplateArgumentList *TemplateArgs,
  2302. void *InsertPos,
  2303. TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
  2304. const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
  2305. SourceLocation PointOfInstantiation = SourceLocation()) {
  2306. setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
  2307. InsertPos, TSK, TemplateArgsAsWritten,
  2308. PointOfInstantiation);
  2309. }
  2310. /// Specifies that this function declaration is actually a
  2311. /// dependent function template specialization.
  2312. void setDependentTemplateSpecialization(ASTContext &Context,
  2313. const UnresolvedSetImpl &Templates,
  2314. const TemplateArgumentListInfo &TemplateArgs);
  2315. DependentFunctionTemplateSpecializationInfo *
  2316. getDependentSpecializationInfo() const;
  2317. /// Determine what kind of template instantiation this function
  2318. /// represents.
  2319. TemplateSpecializationKind getTemplateSpecializationKind() const;
  2320. /// Determine the kind of template specialization this function represents
  2321. /// for the purpose of template instantiation.
  2322. TemplateSpecializationKind
  2323. getTemplateSpecializationKindForInstantiation() const;
  2324. /// Determine what kind of template instantiation this function
  2325. /// represents.
  2326. void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
  2327. SourceLocation PointOfInstantiation = SourceLocation());
  2328. /// Retrieve the (first) point of instantiation of a function template
  2329. /// specialization or a member of a class template specialization.
  2330. ///
  2331. /// \returns the first point of instantiation, if this function was
  2332. /// instantiated from a template; otherwise, returns an invalid source
  2333. /// location.
  2334. SourceLocation getPointOfInstantiation() const;
  2335. /// Determine whether this is or was instantiated from an out-of-line
  2336. /// definition of a member function.
  2337. bool isOutOfLine() const override;
  2338. /// Identify a memory copying or setting function.
  2339. /// If the given function is a memory copy or setting function, returns
  2340. /// the corresponding Builtin ID. If the function is not a memory function,
  2341. /// returns 0.
  2342. unsigned getMemoryFunctionKind() const;
  2343. /// Returns ODRHash of the function. This value is calculated and
  2344. /// stored on first call, then the stored value returned on the other calls.
  2345. unsigned getODRHash();
  2346. /// Returns cached ODRHash of the function. This must have been previously
  2347. /// computed and stored.
  2348. unsigned getODRHash() const;
  2349. // Implement isa/cast/dyncast/etc.
  2350. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2351. static bool classofKind(Kind K) {
  2352. return K >= firstFunction && K <= lastFunction;
  2353. }
  2354. static DeclContext *castToDeclContext(const FunctionDecl *D) {
  2355. return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
  2356. }
  2357. static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
  2358. return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
  2359. }
  2360. };
  2361. /// Represents a member of a struct/union/class.
  2362. class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
  2363. unsigned BitField : 1;
  2364. unsigned Mutable : 1;
  2365. mutable unsigned CachedFieldIndex : 30;
  2366. /// The kinds of value we can store in InitializerOrBitWidth.
  2367. ///
  2368. /// Note that this is compatible with InClassInitStyle except for
  2369. /// ISK_CapturedVLAType.
  2370. enum InitStorageKind {
  2371. /// If the pointer is null, there's nothing special. Otherwise,
  2372. /// this is a bitfield and the pointer is the Expr* storing the
  2373. /// bit-width.
  2374. ISK_NoInit = (unsigned) ICIS_NoInit,
  2375. /// The pointer is an (optional due to delayed parsing) Expr*
  2376. /// holding the copy-initializer.
  2377. ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
  2378. /// The pointer is an (optional due to delayed parsing) Expr*
  2379. /// holding the list-initializer.
  2380. ISK_InClassListInit = (unsigned) ICIS_ListInit,
  2381. /// The pointer is a VariableArrayType* that's been captured;
  2382. /// the enclosing context is a lambda or captured statement.
  2383. ISK_CapturedVLAType,
  2384. };
  2385. /// If this is a bitfield with a default member initializer, this
  2386. /// structure is used to represent the two expressions.
  2387. struct InitAndBitWidth {
  2388. Expr *Init;
  2389. Expr *BitWidth;
  2390. };
  2391. /// Storage for either the bit-width, the in-class initializer, or
  2392. /// both (via InitAndBitWidth), or the captured variable length array bound.
  2393. ///
  2394. /// If the storage kind is ISK_InClassCopyInit or
  2395. /// ISK_InClassListInit, but the initializer is null, then this
  2396. /// field has an in-class initializer that has not yet been parsed
  2397. /// and attached.
  2398. // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
  2399. // overwhelmingly common case that we have none of these things.
  2400. llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
  2401. protected:
  2402. FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
  2403. SourceLocation IdLoc, IdentifierInfo *Id,
  2404. QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
  2405. InClassInitStyle InitStyle)
  2406. : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
  2407. BitField(false), Mutable(Mutable), CachedFieldIndex(0),
  2408. InitStorage(nullptr, (InitStorageKind) InitStyle) {
  2409. if (BW)
  2410. setBitWidth(BW);
  2411. }
  2412. public:
  2413. friend class ASTDeclReader;
  2414. friend class ASTDeclWriter;
  2415. static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
  2416. SourceLocation StartLoc, SourceLocation IdLoc,
  2417. IdentifierInfo *Id, QualType T,
  2418. TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
  2419. InClassInitStyle InitStyle);
  2420. static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  2421. /// Returns the index of this field within its record,
  2422. /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
  2423. unsigned getFieldIndex() const;
  2424. /// Determines whether this field is mutable (C++ only).
  2425. bool isMutable() const { return Mutable; }
  2426. /// Determines whether this field is a bitfield.
  2427. bool isBitField() const { return BitField; }
  2428. /// Determines whether this is an unnamed bitfield.
  2429. bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
  2430. /// Determines whether this field is a
  2431. /// representative for an anonymous struct or union. Such fields are
  2432. /// unnamed and are implicitly generated by the implementation to
  2433. /// store the data for the anonymous union or struct.
  2434. bool isAnonymousStructOrUnion() const;
  2435. Expr *getBitWidth() const {
  2436. if (!BitField)
  2437. return nullptr;
  2438. void *Ptr = InitStorage.getPointer();
  2439. if (getInClassInitStyle())
  2440. return static_cast<InitAndBitWidth*>(Ptr)->BitWidth;
  2441. return static_cast<Expr*>(Ptr);
  2442. }
  2443. unsigned getBitWidthValue(const ASTContext &Ctx) const;
  2444. /// Set the bit-field width for this member.
  2445. // Note: used by some clients (i.e., do not remove it).
  2446. void setBitWidth(Expr *Width) {
  2447. assert(!hasCapturedVLAType() && !BitField &&
  2448. "bit width or captured type already set");
  2449. assert(Width && "no bit width specified");
  2450. InitStorage.setPointer(
  2451. InitStorage.getInt()
  2452. ? new (getASTContext())
  2453. InitAndBitWidth{getInClassInitializer(), Width}
  2454. : static_cast<void*>(Width));
  2455. BitField = true;
  2456. }
  2457. /// Remove the bit-field width from this member.
  2458. // Note: used by some clients (i.e., do not remove it).
  2459. void removeBitWidth() {
  2460. assert(isBitField() && "no bitfield width to remove");
  2461. InitStorage.setPointer(getInClassInitializer());
  2462. BitField = false;
  2463. }
  2464. /// Is this a zero-length bit-field? Such bit-fields aren't really bit-fields
  2465. /// at all and instead act as a separator between contiguous runs of other
  2466. /// bit-fields.
  2467. bool isZeroLengthBitField(const ASTContext &Ctx) const;
  2468. /// Determine if this field is a subobject of zero size, that is, either a
  2469. /// zero-length bit-field or a field of empty class type with the
  2470. /// [[no_unique_address]] attribute.
  2471. bool isZeroSize(const ASTContext &Ctx) const;
  2472. /// Get the kind of (C++11) default member initializer that this field has.
  2473. InClassInitStyle getInClassInitStyle() const {
  2474. InitStorageKind storageKind = InitStorage.getInt();
  2475. return (storageKind == ISK_CapturedVLAType
  2476. ? ICIS_NoInit : (InClassInitStyle) storageKind);
  2477. }
  2478. /// Determine whether this member has a C++11 default member initializer.
  2479. bool hasInClassInitializer() const {
  2480. return getInClassInitStyle() != ICIS_NoInit;
  2481. }
  2482. /// Get the C++11 default member initializer for this member, or null if one
  2483. /// has not been set. If a valid declaration has a default member initializer,
  2484. /// but this returns null, then we have not parsed and attached it yet.
  2485. Expr *getInClassInitializer() const {
  2486. if (!hasInClassInitializer())
  2487. return nullptr;
  2488. void *Ptr = InitStorage.getPointer();
  2489. if (BitField)
  2490. return static_cast<InitAndBitWidth*>(Ptr)->Init;
  2491. return static_cast<Expr*>(Ptr);
  2492. }
  2493. /// Set the C++11 in-class initializer for this member.
  2494. void setInClassInitializer(Expr *Init) {
  2495. assert(hasInClassInitializer() && !getInClassInitializer());
  2496. if (BitField)
  2497. static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init;
  2498. else
  2499. InitStorage.setPointer(Init);
  2500. }
  2501. /// Remove the C++11 in-class initializer from this member.
  2502. void removeInClassInitializer() {
  2503. assert(hasInClassInitializer() && "no initializer to remove");
  2504. InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit);
  2505. }
  2506. /// Determine whether this member captures the variable length array
  2507. /// type.
  2508. bool hasCapturedVLAType() const {
  2509. return InitStorage.getInt() == ISK_CapturedVLAType;
  2510. }
  2511. /// Get the captured variable length array type.
  2512. const VariableArrayType *getCapturedVLAType() const {
  2513. return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
  2514. InitStorage.getPointer())
  2515. : nullptr;
  2516. }
  2517. /// Set the captured variable length array type for this field.
  2518. void setCapturedVLAType(const VariableArrayType *VLAType);
  2519. /// Returns the parent of this field declaration, which
  2520. /// is the struct in which this field is defined.
  2521. ///
  2522. /// Returns null if this is not a normal class/struct field declaration, e.g.
  2523. /// ObjCAtDefsFieldDecl, ObjCIvarDecl.
  2524. const RecordDecl *getParent() const {
  2525. return dyn_cast<RecordDecl>(getDeclContext());
  2526. }
  2527. RecordDecl *getParent() {
  2528. return dyn_cast<RecordDecl>(getDeclContext());
  2529. }
  2530. SourceRange getSourceRange() const override LLVM_READONLY;
  2531. /// Retrieves the canonical declaration of this field.
  2532. FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
  2533. const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
  2534. // Implement isa/cast/dyncast/etc.
  2535. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2536. static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
  2537. };
  2538. /// An instance of this object exists for each enum constant
  2539. /// that is defined. For example, in "enum X {a,b}", each of a/b are
  2540. /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
  2541. /// TagType for the X EnumDecl.
  2542. class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
  2543. Stmt *Init; // an integer constant expression
  2544. llvm::APSInt Val; // The value.
  2545. protected:
  2546. EnumConstantDecl(DeclContext *DC, SourceLocation L,
  2547. IdentifierInfo *Id, QualType T, Expr *E,
  2548. const llvm::APSInt &V)
  2549. : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
  2550. public:
  2551. friend class StmtIteratorBase;
  2552. static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
  2553. SourceLocation L, IdentifierInfo *Id,
  2554. QualType T, Expr *E,
  2555. const llvm::APSInt &V);
  2556. static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  2557. const Expr *getInitExpr() const { return (const Expr*) Init; }
  2558. Expr *getInitExpr() { return (Expr*) Init; }
  2559. const llvm::APSInt &getInitVal() const { return Val; }
  2560. void setInitExpr(Expr *E) { Init = (Stmt*) E; }
  2561. void setInitVal(const llvm::APSInt &V) { Val = V; }
  2562. SourceRange getSourceRange() const override LLVM_READONLY;
  2563. /// Retrieves the canonical declaration of this enumerator.
  2564. EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
  2565. const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
  2566. // Implement isa/cast/dyncast/etc.
  2567. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2568. static bool classofKind(Kind K) { return K == EnumConstant; }
  2569. };
  2570. /// Represents a field injected from an anonymous union/struct into the parent
  2571. /// scope. These are always implicit.
  2572. class IndirectFieldDecl : public ValueDecl,
  2573. public Mergeable<IndirectFieldDecl> {
  2574. NamedDecl **Chaining;
  2575. unsigned ChainingSize;
  2576. IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
  2577. DeclarationName N, QualType T,
  2578. MutableArrayRef<NamedDecl *> CH);
  2579. void anchor() override;
  2580. public:
  2581. friend class ASTDeclReader;
  2582. static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
  2583. SourceLocation L, IdentifierInfo *Id,
  2584. QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
  2585. static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  2586. using chain_iterator = ArrayRef<NamedDecl *>::const_iterator;
  2587. ArrayRef<NamedDecl *> chain() const {
  2588. return llvm::makeArrayRef(Chaining, ChainingSize);
  2589. }
  2590. chain_iterator chain_begin() const { return chain().begin(); }
  2591. chain_iterator chain_end() const { return chain().end(); }
  2592. unsigned getChainingSize() const { return ChainingSize; }
  2593. FieldDecl *getAnonField() const {
  2594. assert(chain().size() >= 2);
  2595. return cast<FieldDecl>(chain().back());
  2596. }
  2597. VarDecl *getVarDecl() const {
  2598. assert(chain().size() >= 2);
  2599. return dyn_cast<VarDecl>(chain().front());
  2600. }
  2601. IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
  2602. const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
  2603. // Implement isa/cast/dyncast/etc.
  2604. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2605. static bool classofKind(Kind K) { return K == IndirectField; }
  2606. };
  2607. /// Represents a declaration of a type.
  2608. class TypeDecl : public NamedDecl {
  2609. friend class ASTContext;
  2610. /// This indicates the Type object that represents
  2611. /// this TypeDecl. It is a cache maintained by
  2612. /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
  2613. /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
  2614. mutable const Type *TypeForDecl = nullptr;
  2615. /// The start of the source range for this declaration.
  2616. SourceLocation LocStart;
  2617. void anchor() override;
  2618. protected:
  2619. TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
  2620. SourceLocation StartL = SourceLocation())
  2621. : NamedDecl(DK, DC, L, Id), LocStart(StartL) {}
  2622. public:
  2623. // Low-level accessor. If you just want the type defined by this node,
  2624. // check out ASTContext::getTypeDeclType or one of
  2625. // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
  2626. // already know the specific kind of node this is.
  2627. const Type *getTypeForDecl() const { return TypeForDecl; }
  2628. void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
  2629. SourceLocation getBeginLoc() const LLVM_READONLY { return LocStart; }
  2630. void setLocStart(SourceLocation L) { LocStart = L; }
  2631. SourceRange getSourceRange() const override LLVM_READONLY {
  2632. if (LocStart.isValid())
  2633. return SourceRange(LocStart, getLocation());
  2634. else
  2635. return SourceRange(getLocation());
  2636. }
  2637. // Implement isa/cast/dyncast/etc.
  2638. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2639. static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
  2640. };
  2641. /// Base class for declarations which introduce a typedef-name.
  2642. class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
  2643. struct alignas(8) ModedTInfo {
  2644. TypeSourceInfo *first;
  2645. QualType second;
  2646. };
  2647. /// If int part is 0, we have not computed IsTransparentTag.
  2648. /// Otherwise, IsTransparentTag is (getInt() >> 1).
  2649. mutable llvm::PointerIntPair<
  2650. llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2>
  2651. MaybeModedTInfo;
  2652. void anchor() override;
  2653. protected:
  2654. TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
  2655. SourceLocation StartLoc, SourceLocation IdLoc,
  2656. IdentifierInfo *Id, TypeSourceInfo *TInfo)
  2657. : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
  2658. MaybeModedTInfo(TInfo, 0) {}
  2659. using redeclarable_base = Redeclarable<TypedefNameDecl>;
  2660. TypedefNameDecl *getNextRedeclarationImpl() override {
  2661. return getNextRedeclaration();
  2662. }
  2663. TypedefNameDecl *getPreviousDeclImpl() override {
  2664. return getPreviousDecl();
  2665. }
  2666. TypedefNameDecl *getMostRecentDeclImpl() override {
  2667. return getMostRecentDecl();
  2668. }
  2669. public:
  2670. using redecl_range = redeclarable_base::redecl_range;
  2671. using redecl_iterator = redeclarable_base::redecl_iterator;
  2672. using redeclarable_base::redecls_begin;
  2673. using redeclarable_base::redecls_end;
  2674. using redeclarable_base::redecls;
  2675. using redeclarable_base::getPreviousDecl;
  2676. using redeclarable_base::getMostRecentDecl;
  2677. using redeclarable_base::isFirstDecl;
  2678. bool isModed() const {
  2679. return MaybeModedTInfo.getPointer().is<ModedTInfo *>();
  2680. }
  2681. TypeSourceInfo *getTypeSourceInfo() const {
  2682. return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first
  2683. : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>();
  2684. }
  2685. QualType getUnderlyingType() const {
  2686. return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second
  2687. : MaybeModedTInfo.getPointer()
  2688. .get<TypeSourceInfo *>()
  2689. ->getType();
  2690. }
  2691. void setTypeSourceInfo(TypeSourceInfo *newType) {
  2692. MaybeModedTInfo.setPointer(newType);
  2693. }
  2694. void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
  2695. MaybeModedTInfo.setPointer(new (getASTContext(), 8)
  2696. ModedTInfo({unmodedTSI, modedTy}));
  2697. }
  2698. /// Retrieves the canonical declaration of this typedef-name.
  2699. TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
  2700. const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
  2701. /// Retrieves the tag declaration for which this is the typedef name for
  2702. /// linkage purposes, if any.
  2703. ///
  2704. /// \param AnyRedecl Look for the tag declaration in any redeclaration of
  2705. /// this typedef declaration.
  2706. TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
  2707. /// Determines if this typedef shares a name and spelling location with its
  2708. /// underlying tag type, as is the case with the NS_ENUM macro.
  2709. bool isTransparentTag() const {
  2710. if (MaybeModedTInfo.getInt())
  2711. return MaybeModedTInfo.getInt() & 0x2;
  2712. return isTransparentTagSlow();
  2713. }
  2714. // Implement isa/cast/dyncast/etc.
  2715. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2716. static bool classofKind(Kind K) {
  2717. return K >= firstTypedefName && K <= lastTypedefName;
  2718. }
  2719. private:
  2720. bool isTransparentTagSlow() const;
  2721. };
  2722. /// Represents the declaration of a typedef-name via the 'typedef'
  2723. /// type specifier.
  2724. class TypedefDecl : public TypedefNameDecl {
  2725. TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
  2726. SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
  2727. : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
  2728. public:
  2729. static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
  2730. SourceLocation StartLoc, SourceLocation IdLoc,
  2731. IdentifierInfo *Id, TypeSourceInfo *TInfo);
  2732. static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  2733. SourceRange getSourceRange() const override LLVM_READONLY;
  2734. // Implement isa/cast/dyncast/etc.
  2735. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2736. static bool classofKind(Kind K) { return K == Typedef; }
  2737. };
  2738. /// Represents the declaration of a typedef-name via a C++11
  2739. /// alias-declaration.
  2740. class TypeAliasDecl : public TypedefNameDecl {
  2741. /// The template for which this is the pattern, if any.
  2742. TypeAliasTemplateDecl *Template;
  2743. TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
  2744. SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
  2745. : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
  2746. Template(nullptr) {}
  2747. public:
  2748. static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
  2749. SourceLocation StartLoc, SourceLocation IdLoc,
  2750. IdentifierInfo *Id, TypeSourceInfo *TInfo);
  2751. static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  2752. SourceRange getSourceRange() const override LLVM_READONLY;
  2753. TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
  2754. void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
  2755. // Implement isa/cast/dyncast/etc.
  2756. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2757. static bool classofKind(Kind K) { return K == TypeAlias; }
  2758. };
  2759. /// Represents the declaration of a struct/union/class/enum.
  2760. class TagDecl : public TypeDecl,
  2761. public DeclContext,
  2762. public Redeclarable<TagDecl> {
  2763. // This class stores some data in DeclContext::TagDeclBits
  2764. // to save some space. Use the provided accessors to access it.
  2765. public:
  2766. // This is really ugly.
  2767. using TagKind = TagTypeKind;
  2768. private:
  2769. SourceRange BraceRange;
  2770. // A struct representing syntactic qualifier info,
  2771. // to be used for the (uncommon) case of out-of-line declarations.
  2772. using ExtInfo = QualifierInfo;
  2773. /// If the (out-of-line) tag declaration name
  2774. /// is qualified, it points to the qualifier info (nns and range);
  2775. /// otherwise, if the tag declaration is anonymous and it is part of
  2776. /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
  2777. /// otherwise, if the tag declaration is anonymous and it is used as a
  2778. /// declaration specifier for variables, it points to the first VarDecl (used
  2779. /// for mangling);
  2780. /// otherwise, it is a null (TypedefNameDecl) pointer.
  2781. llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
  2782. bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
  2783. ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
  2784. const ExtInfo *getExtInfo() const {
  2785. return TypedefNameDeclOrQualifier.get<ExtInfo *>();
  2786. }
  2787. protected:
  2788. TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
  2789. SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
  2790. SourceLocation StartL);
  2791. using redeclarable_base = Redeclarable<TagDecl>;
  2792. TagDecl *getNextRedeclarationImpl() override {
  2793. return getNextRedeclaration();
  2794. }
  2795. TagDecl *getPreviousDeclImpl() override {
  2796. return getPreviousDecl();
  2797. }
  2798. TagDecl *getMostRecentDeclImpl() override {
  2799. return getMostRecentDecl();
  2800. }
  2801. /// Completes the definition of this tag declaration.
  2802. ///
  2803. /// This is a helper function for derived classes.
  2804. void completeDefinition();
  2805. /// True if this decl is currently being defined.
  2806. void setBeingDefined(bool V = true) { TagDeclBits.IsBeingDefined = V; }
  2807. /// Indicates whether it is possible for declarations of this kind
  2808. /// to have an out-of-date definition.
  2809. ///
  2810. /// This option is only enabled when modules are enabled.
  2811. void setMayHaveOutOfDateDef(bool V = true) {
  2812. TagDeclBits.MayHaveOutOfDateDef = V;
  2813. }
  2814. public:
  2815. friend class ASTDeclReader;
  2816. friend class ASTDeclWriter;
  2817. using redecl_range = redeclarable_base::redecl_range;
  2818. using redecl_iterator = redeclarable_base::redecl_iterator;
  2819. using redeclarable_base::redecls_begin;
  2820. using redeclarable_base::redecls_end;
  2821. using redeclarable_base::redecls;
  2822. using redeclarable_base::getPreviousDecl;
  2823. using redeclarable_base::getMostRecentDecl;
  2824. using redeclarable_base::isFirstDecl;
  2825. SourceRange getBraceRange() const { return BraceRange; }
  2826. void setBraceRange(SourceRange R) { BraceRange = R; }
  2827. /// Return SourceLocation representing start of source
  2828. /// range ignoring outer template declarations.
  2829. SourceLocation getInnerLocStart() const { return getBeginLoc(); }
  2830. /// Return SourceLocation representing start of source
  2831. /// range taking into account any outer template declarations.
  2832. SourceLocation getOuterLocStart() const;
  2833. SourceRange getSourceRange() const override LLVM_READONLY;
  2834. TagDecl *getCanonicalDecl() override;
  2835. const TagDecl *getCanonicalDecl() const {
  2836. return const_cast<TagDecl*>(this)->getCanonicalDecl();
  2837. }
  2838. /// Return true if this declaration is a completion definition of the type.
  2839. /// Provided for consistency.
  2840. bool isThisDeclarationADefinition() const {
  2841. return isCompleteDefinition();
  2842. }
  2843. /// Return true if this decl has its body fully specified.
  2844. bool isCompleteDefinition() const { return TagDeclBits.IsCompleteDefinition; }
  2845. /// True if this decl has its body fully specified.
  2846. void setCompleteDefinition(bool V = true) {
  2847. TagDeclBits.IsCompleteDefinition = V;
  2848. }
  2849. /// Return true if this complete decl is
  2850. /// required to be complete for some existing use.
  2851. bool isCompleteDefinitionRequired() const {
  2852. return TagDeclBits.IsCompleteDefinitionRequired;
  2853. }
  2854. /// True if this complete decl is
  2855. /// required to be complete for some existing use.
  2856. void setCompleteDefinitionRequired(bool V = true) {
  2857. TagDeclBits.IsCompleteDefinitionRequired = V;
  2858. }
  2859. /// Return true if this decl is currently being defined.
  2860. bool isBeingDefined() const { return TagDeclBits.IsBeingDefined; }
  2861. /// True if this tag declaration is "embedded" (i.e., defined or declared
  2862. /// for the very first time) in the syntax of a declarator.
  2863. bool isEmbeddedInDeclarator() const {
  2864. return TagDeclBits.IsEmbeddedInDeclarator;
  2865. }
  2866. /// True if this tag declaration is "embedded" (i.e., defined or declared
  2867. /// for the very first time) in the syntax of a declarator.
  2868. void setEmbeddedInDeclarator(bool isInDeclarator) {
  2869. TagDeclBits.IsEmbeddedInDeclarator = isInDeclarator;
  2870. }
  2871. /// True if this tag is free standing, e.g. "struct foo;".
  2872. bool isFreeStanding() const { return TagDeclBits.IsFreeStanding; }
  2873. /// True if this tag is free standing, e.g. "struct foo;".
  2874. void setFreeStanding(bool isFreeStanding = true) {
  2875. TagDeclBits.IsFreeStanding = isFreeStanding;
  2876. }
  2877. /// Indicates whether it is possible for declarations of this kind
  2878. /// to have an out-of-date definition.
  2879. ///
  2880. /// This option is only enabled when modules are enabled.
  2881. bool mayHaveOutOfDateDef() const { return TagDeclBits.MayHaveOutOfDateDef; }
  2882. /// Whether this declaration declares a type that is
  2883. /// dependent, i.e., a type that somehow depends on template
  2884. /// parameters.
  2885. bool isDependentType() const { return isDependentContext(); }
  2886. /// Starts the definition of this tag declaration.
  2887. ///
  2888. /// This method should be invoked at the beginning of the definition
  2889. /// of this tag declaration. It will set the tag type into a state
  2890. /// where it is in the process of being defined.
  2891. void startDefinition();
  2892. /// Returns the TagDecl that actually defines this
  2893. /// struct/union/class/enum. When determining whether or not a
  2894. /// struct/union/class/enum has a definition, one should use this
  2895. /// method as opposed to 'isDefinition'. 'isDefinition' indicates
  2896. /// whether or not a specific TagDecl is defining declaration, not
  2897. /// whether or not the struct/union/class/enum type is defined.
  2898. /// This method returns NULL if there is no TagDecl that defines
  2899. /// the struct/union/class/enum.
  2900. TagDecl *getDefinition() const;
  2901. StringRef getKindName() const {
  2902. return TypeWithKeyword::getTagTypeKindName(getTagKind());
  2903. }
  2904. TagKind getTagKind() const {
  2905. return static_cast<TagKind>(TagDeclBits.TagDeclKind);
  2906. }
  2907. void setTagKind(TagKind TK) { TagDeclBits.TagDeclKind = TK; }
  2908. bool isStruct() const { return getTagKind() == TTK_Struct; }
  2909. bool isInterface() const { return getTagKind() == TTK_Interface; }
  2910. bool isClass() const { return getTagKind() == TTK_Class; }
  2911. bool isUnion() const { return getTagKind() == TTK_Union; }
  2912. bool isEnum() const { return getTagKind() == TTK_Enum; }
  2913. /// Is this tag type named, either directly or via being defined in
  2914. /// a typedef of this type?
  2915. ///
  2916. /// C++11 [basic.link]p8:
  2917. /// A type is said to have linkage if and only if:
  2918. /// - it is a class or enumeration type that is named (or has a
  2919. /// name for linkage purposes) and the name has linkage; ...
  2920. /// C++11 [dcl.typedef]p9:
  2921. /// If the typedef declaration defines an unnamed class (or enum),
  2922. /// the first typedef-name declared by the declaration to be that
  2923. /// class type (or enum type) is used to denote the class type (or
  2924. /// enum type) for linkage purposes only.
  2925. ///
  2926. /// C does not have an analogous rule, but the same concept is
  2927. /// nonetheless useful in some places.
  2928. bool hasNameForLinkage() const {
  2929. return (getDeclName() || getTypedefNameForAnonDecl());
  2930. }
  2931. TypedefNameDecl *getTypedefNameForAnonDecl() const {
  2932. return hasExtInfo() ? nullptr
  2933. : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
  2934. }
  2935. void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
  2936. /// Retrieve the nested-name-specifier that qualifies the name of this
  2937. /// declaration, if it was present in the source.
  2938. NestedNameSpecifier *getQualifier() const {
  2939. return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
  2940. : nullptr;
  2941. }
  2942. /// Retrieve the nested-name-specifier (with source-location
  2943. /// information) that qualifies the name of this declaration, if it was
  2944. /// present in the source.
  2945. NestedNameSpecifierLoc getQualifierLoc() const {
  2946. return hasExtInfo() ? getExtInfo()->QualifierLoc
  2947. : NestedNameSpecifierLoc();
  2948. }
  2949. void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
  2950. unsigned getNumTemplateParameterLists() const {
  2951. return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
  2952. }
  2953. TemplateParameterList *getTemplateParameterList(unsigned i) const {
  2954. assert(i < getNumTemplateParameterLists());
  2955. return getExtInfo()->TemplParamLists[i];
  2956. }
  2957. void setTemplateParameterListsInfo(ASTContext &Context,
  2958. ArrayRef<TemplateParameterList *> TPLists);
  2959. // Implement isa/cast/dyncast/etc.
  2960. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  2961. static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
  2962. static DeclContext *castToDeclContext(const TagDecl *D) {
  2963. return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
  2964. }
  2965. static TagDecl *castFromDeclContext(const DeclContext *DC) {
  2966. return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
  2967. }
  2968. };
  2969. /// Represents an enum. In C++11, enums can be forward-declared
  2970. /// with a fixed underlying type, and in C we allow them to be forward-declared
  2971. /// with no underlying type as an extension.
  2972. class EnumDecl : public TagDecl {
  2973. // This class stores some data in DeclContext::EnumDeclBits
  2974. // to save some space. Use the provided accessors to access it.
  2975. /// This represent the integer type that the enum corresponds
  2976. /// to for code generation purposes. Note that the enumerator constants may
  2977. /// have a different type than this does.
  2978. ///
  2979. /// If the underlying integer type was explicitly stated in the source
  2980. /// code, this is a TypeSourceInfo* for that type. Otherwise this type
  2981. /// was automatically deduced somehow, and this is a Type*.
  2982. ///
  2983. /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
  2984. /// some cases it won't.
  2985. ///
  2986. /// The underlying type of an enumeration never has any qualifiers, so
  2987. /// we can get away with just storing a raw Type*, and thus save an
  2988. /// extra pointer when TypeSourceInfo is needed.
  2989. llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType;
  2990. /// The integer type that values of this type should
  2991. /// promote to. In C, enumerators are generally of an integer type
  2992. /// directly, but gcc-style large enumerators (and all enumerators
  2993. /// in C++) are of the enum type instead.
  2994. QualType PromotionType;
  2995. /// If this enumeration is an instantiation of a member enumeration
  2996. /// of a class template specialization, this is the member specialization
  2997. /// information.
  2998. MemberSpecializationInfo *SpecializationInfo = nullptr;
  2999. /// Store the ODRHash after first calculation.
  3000. /// The corresponding flag HasODRHash is in EnumDeclBits
  3001. /// and can be accessed with the provided accessors.
  3002. unsigned ODRHash;
  3003. EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
  3004. SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
  3005. bool Scoped, bool ScopedUsingClassTag, bool Fixed);
  3006. void anchor() override;
  3007. void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
  3008. TemplateSpecializationKind TSK);
  3009. /// Sets the width in bits required to store all the
  3010. /// non-negative enumerators of this enum.
  3011. void setNumPositiveBits(unsigned Num) {
  3012. EnumDeclBits.NumPositiveBits = Num;
  3013. assert(EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount");
  3014. }
  3015. /// Returns the width in bits required to store all the
  3016. /// negative enumerators of this enum. (see getNumNegativeBits)
  3017. void setNumNegativeBits(unsigned Num) { EnumDeclBits.NumNegativeBits = Num; }
  3018. public:
  3019. /// True if this tag declaration is a scoped enumeration. Only
  3020. /// possible in C++11 mode.
  3021. void setScoped(bool Scoped = true) { EnumDeclBits.IsScoped = Scoped; }
  3022. /// If this tag declaration is a scoped enum,
  3023. /// then this is true if the scoped enum was declared using the class
  3024. /// tag, false if it was declared with the struct tag. No meaning is
  3025. /// associated if this tag declaration is not a scoped enum.
  3026. void setScopedUsingClassTag(bool ScopedUCT = true) {
  3027. EnumDeclBits.IsScopedUsingClassTag = ScopedUCT;
  3028. }
  3029. /// True if this is an Objective-C, C++11, or
  3030. /// Microsoft-style enumeration with a fixed underlying type.
  3031. void setFixed(bool Fixed = true) { EnumDeclBits.IsFixed = Fixed; }
  3032. private:
  3033. /// True if a valid hash is stored in ODRHash.
  3034. bool hasODRHash() const { return EnumDeclBits.HasODRHash; }
  3035. void setHasODRHash(bool Hash = true) { EnumDeclBits.HasODRHash = Hash; }
  3036. public:
  3037. friend class ASTDeclReader;
  3038. EnumDecl *getCanonicalDecl() override {
  3039. return cast<EnumDecl>(TagDecl::getCanonicalDecl());
  3040. }
  3041. const EnumDecl *getCanonicalDecl() const {
  3042. return const_cast<EnumDecl*>(this)->getCanonicalDecl();
  3043. }
  3044. EnumDecl *getPreviousDecl() {
  3045. return cast_or_null<EnumDecl>(
  3046. static_cast<TagDecl *>(this)->getPreviousDecl());
  3047. }
  3048. const EnumDecl *getPreviousDecl() const {
  3049. return const_cast<EnumDecl*>(this)->getPreviousDecl();
  3050. }
  3051. EnumDecl *getMostRecentDecl() {
  3052. return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
  3053. }
  3054. const EnumDecl *getMostRecentDecl() const {
  3055. return const_cast<EnumDecl*>(this)->getMostRecentDecl();
  3056. }
  3057. EnumDecl *getDefinition() const {
  3058. return cast_or_null<EnumDecl>(TagDecl::getDefinition());
  3059. }
  3060. static EnumDecl *Create(ASTContext &C, DeclContext *DC,
  3061. SourceLocation StartLoc, SourceLocation IdLoc,
  3062. IdentifierInfo *Id, EnumDecl *PrevDecl,
  3063. bool IsScoped, bool IsScopedUsingClassTag,
  3064. bool IsFixed);
  3065. static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  3066. /// Overrides to provide correct range when there's an enum-base specifier
  3067. /// with forward declarations.
  3068. SourceRange getSourceRange() const override LLVM_READONLY;
  3069. /// When created, the EnumDecl corresponds to a
  3070. /// forward-declared enum. This method is used to mark the
  3071. /// declaration as being defined; its enumerators have already been
  3072. /// added (via DeclContext::addDecl). NewType is the new underlying
  3073. /// type of the enumeration type.
  3074. void completeDefinition(QualType NewType,
  3075. QualType PromotionType,
  3076. unsigned NumPositiveBits,
  3077. unsigned NumNegativeBits);
  3078. // Iterates through the enumerators of this enumeration.
  3079. using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>;
  3080. using enumerator_range =
  3081. llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>;
  3082. enumerator_range enumerators() const {
  3083. return enumerator_range(enumerator_begin(), enumerator_end());
  3084. }
  3085. enumerator_iterator enumerator_begin() const {
  3086. const EnumDecl *E = getDefinition();
  3087. if (!E)
  3088. E = this;
  3089. return enumerator_iterator(E->decls_begin());
  3090. }
  3091. enumerator_iterator enumerator_end() const {
  3092. const EnumDecl *E = getDefinition();
  3093. if (!E)
  3094. E = this;
  3095. return enumerator_iterator(E->decls_end());
  3096. }
  3097. /// Return the integer type that enumerators should promote to.
  3098. QualType getPromotionType() const { return PromotionType; }
  3099. /// Set the promotion type.
  3100. void setPromotionType(QualType T) { PromotionType = T; }
  3101. /// Return the integer type this enum decl corresponds to.
  3102. /// This returns a null QualType for an enum forward definition with no fixed
  3103. /// underlying type.
  3104. QualType getIntegerType() const {
  3105. if (!IntegerType)
  3106. return QualType();
  3107. if (const Type *T = IntegerType.dyn_cast<const Type*>())
  3108. return QualType(T, 0);
  3109. return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
  3110. }
  3111. /// Set the underlying integer type.
  3112. void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
  3113. /// Set the underlying integer type source info.
  3114. void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
  3115. /// Return the type source info for the underlying integer type,
  3116. /// if no type source info exists, return 0.
  3117. TypeSourceInfo *getIntegerTypeSourceInfo() const {
  3118. return IntegerType.dyn_cast<TypeSourceInfo*>();
  3119. }
  3120. /// Retrieve the source range that covers the underlying type if
  3121. /// specified.
  3122. SourceRange getIntegerTypeRange() const LLVM_READONLY;
  3123. /// Returns the width in bits required to store all the
  3124. /// non-negative enumerators of this enum.
  3125. unsigned getNumPositiveBits() const { return EnumDeclBits.NumPositiveBits; }
  3126. /// Returns the width in bits required to store all the
  3127. /// negative enumerators of this enum. These widths include
  3128. /// the rightmost leading 1; that is:
  3129. ///
  3130. /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
  3131. /// ------------------------ ------- -----------------
  3132. /// -1 1111111 1
  3133. /// -10 1110110 5
  3134. /// -101 1001011 8
  3135. unsigned getNumNegativeBits() const { return EnumDeclBits.NumNegativeBits; }
  3136. /// Returns true if this is a C++11 scoped enumeration.
  3137. bool isScoped() const { return EnumDeclBits.IsScoped; }
  3138. /// Returns true if this is a C++11 scoped enumeration.
  3139. bool isScopedUsingClassTag() const {
  3140. return EnumDeclBits.IsScopedUsingClassTag;
  3141. }
  3142. /// Returns true if this is an Objective-C, C++11, or
  3143. /// Microsoft-style enumeration with a fixed underlying type.
  3144. bool isFixed() const { return EnumDeclBits.IsFixed; }
  3145. unsigned getODRHash();
  3146. /// Returns true if this can be considered a complete type.
  3147. bool isComplete() const {
  3148. // IntegerType is set for fixed type enums and non-fixed but implicitly
  3149. // int-sized Microsoft enums.
  3150. return isCompleteDefinition() || IntegerType;
  3151. }
  3152. /// Returns true if this enum is either annotated with
  3153. /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
  3154. bool isClosed() const;
  3155. /// Returns true if this enum is annotated with flag_enum and isn't annotated
  3156. /// with enum_extensibility(open).
  3157. bool isClosedFlag() const;
  3158. /// Returns true if this enum is annotated with neither flag_enum nor
  3159. /// enum_extensibility(open).
  3160. bool isClosedNonFlag() const;
  3161. /// Retrieve the enum definition from which this enumeration could
  3162. /// be instantiated, if it is an instantiation (rather than a non-template).
  3163. EnumDecl *getTemplateInstantiationPattern() const;
  3164. /// Returns the enumeration (declared within the template)
  3165. /// from which this enumeration type was instantiated, or NULL if
  3166. /// this enumeration was not instantiated from any template.
  3167. EnumDecl *getInstantiatedFromMemberEnum() const;
  3168. /// If this enumeration is a member of a specialization of a
  3169. /// templated class, determine what kind of template specialization
  3170. /// or instantiation this is.
  3171. TemplateSpecializationKind getTemplateSpecializationKind() const;
  3172. /// For an enumeration member that was instantiated from a member
  3173. /// enumeration of a templated class, set the template specialiation kind.
  3174. void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
  3175. SourceLocation PointOfInstantiation = SourceLocation());
  3176. /// If this enumeration is an instantiation of a member enumeration of
  3177. /// a class template specialization, retrieves the member specialization
  3178. /// information.
  3179. MemberSpecializationInfo *getMemberSpecializationInfo() const {
  3180. return SpecializationInfo;
  3181. }
  3182. /// Specify that this enumeration is an instantiation of the
  3183. /// member enumeration ED.
  3184. void setInstantiationOfMemberEnum(EnumDecl *ED,
  3185. TemplateSpecializationKind TSK) {
  3186. setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
  3187. }
  3188. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  3189. static bool classofKind(Kind K) { return K == Enum; }
  3190. };
  3191. /// Represents a struct/union/class. For example:
  3192. /// struct X; // Forward declaration, no "body".
  3193. /// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
  3194. /// This decl will be marked invalid if *any* members are invalid.
  3195. class RecordDecl : public TagDecl {
  3196. // This class stores some data in DeclContext::RecordDeclBits
  3197. // to save some space. Use the provided accessors to access it.
  3198. public:
  3199. friend class DeclContext;
  3200. /// Enum that represents the different ways arguments are passed to and
  3201. /// returned from function calls. This takes into account the target-specific
  3202. /// and version-specific rules along with the rules determined by the
  3203. /// language.
  3204. enum ArgPassingKind : unsigned {
  3205. /// The argument of this type can be passed directly in registers.
  3206. APK_CanPassInRegs,
  3207. /// The argument of this type cannot be passed directly in registers.
  3208. /// Records containing this type as a subobject are not forced to be passed
  3209. /// indirectly. This value is used only in C++. This value is required by
  3210. /// C++ because, in uncommon situations, it is possible for a class to have
  3211. /// only trivial copy/move constructors even when one of its subobjects has
  3212. /// a non-trivial copy/move constructor (if e.g. the corresponding copy/move
  3213. /// constructor in the derived class is deleted).
  3214. APK_CannotPassInRegs,
  3215. /// The argument of this type cannot be passed directly in registers.
  3216. /// Records containing this type as a subobject are forced to be passed
  3217. /// indirectly.
  3218. APK_CanNeverPassInRegs
  3219. };
  3220. protected:
  3221. RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
  3222. SourceLocation StartLoc, SourceLocation IdLoc,
  3223. IdentifierInfo *Id, RecordDecl *PrevDecl);
  3224. public:
  3225. static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
  3226. SourceLocation StartLoc, SourceLocation IdLoc,
  3227. IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
  3228. static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
  3229. RecordDecl *getPreviousDecl() {
  3230. return cast_or_null<RecordDecl>(
  3231. static_cast<TagDecl *>(this)->getPreviousDecl());
  3232. }
  3233. const RecordDecl *getPreviousDecl() const {
  3234. return const_cast<RecordDecl*>(this)->getPreviousDecl();
  3235. }
  3236. RecordDecl *getMostRecentDecl() {
  3237. return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
  3238. }
  3239. const RecordDecl *getMostRecentDecl() const {
  3240. return const_cast<RecordDecl*>(this)->getMostRecentDecl();
  3241. }
  3242. bool hasFlexibleArrayMember() const {
  3243. return RecordDeclBits.HasFlexibleArrayMember;
  3244. }
  3245. void setHasFlexibleArrayMember(bool V) {
  3246. RecordDeclBits.HasFlexibleArrayMember = V;
  3247. }
  3248. /// Whether this is an anonymous struct or union. To be an anonymous
  3249. /// struct or union, it must have been declared without a name and
  3250. /// there must be no objects of this type declared, e.g.,
  3251. /// @code
  3252. /// union { int i; float f; };
  3253. /// @endcode
  3254. /// is an anonymous union but neither of the following are:
  3255. /// @code
  3256. /// union X { int i; float f; };
  3257. /// union { int i; float f; } obj;
  3258. /// @endcode
  3259. bool isAnonymousStructOrUnion() const {
  3260. return RecordDeclBits.AnonymousStructOrUnion;
  3261. }
  3262. void setAnonymousStructOrUnion(bool Anon) {
  3263. RecordDeclBits.AnonymousStructOrUnion = Anon;
  3264. }
  3265. bool hasObjectMember() const { return RecordDeclBits.HasObjectMember; }
  3266. void setHasObjectMember(bool val) { RecordDeclBits.HasObjectMember = val; }
  3267. bool hasVolatileMember() const { return RecordDeclBits.HasVolatileMember; }
  3268. void setHasVolatileMember(bool val) {
  3269. RecordDeclBits.HasVolatileMember = val;
  3270. }
  3271. bool hasLoadedFieldsFromExternalStorage() const {
  3272. return RecordDeclBits.LoadedFieldsFromExternalStorage;
  3273. }
  3274. void setHasLoadedFieldsFromExternalStorage(bool val) const {
  3275. RecordDeclBits.LoadedFieldsFromExternalStorage = val;
  3276. }
  3277. /// Functions to query basic properties of non-trivial C structs.
  3278. bool isNonTrivialToPrimitiveDefaultInitialize() const {
  3279. return RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize;
  3280. }
  3281. void setNonTrivialToPrimitiveDefaultInitialize(bool V) {
  3282. RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize = V;
  3283. }
  3284. bool isNonTrivialToPrimitiveCopy() const {
  3285. return RecordDeclBits.NonTrivialToPrimitiveCopy;
  3286. }
  3287. void setNonTrivialToPrimitiveCopy(bool V) {
  3288. RecordDeclBits.NonTrivialToPrimitiveCopy = V;
  3289. }
  3290. bool isNonTrivialToPrimitiveDestroy() const {
  3291. return RecordDeclBits.NonTrivialToPrimitiveDestroy;
  3292. }
  3293. void setNonTrivialToPrimitiveDestroy(bool V) {
  3294. RecordDeclBits.NonTrivialToPrimitiveDestroy = V;
  3295. }
  3296. bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
  3297. return RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion;
  3298. }
  3299. void setHasNonTrivialToPrimitiveDefaultInitializeCUnion(bool V) {
  3300. RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion = V;
  3301. }
  3302. bool hasNonTrivialToPrimitiveDestructCUnion() const {
  3303. return RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion;
  3304. }
  3305. void setHasNonTrivialToPrimitiveDestructCUnion(bool V) {
  3306. RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion = V;
  3307. }
  3308. bool hasNonTrivialToPrimitiveCopyCUnion() const {
  3309. return RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion;
  3310. }
  3311. void setHasNonTrivialToPrimitiveCopyCUnion(bool V) {
  3312. RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion = V;
  3313. }
  3314. /// Determine whether this class can be passed in registers. In C++ mode,
  3315. /// it must have at least one trivial, non-deleted copy or move constructor.
  3316. /// FIXME: This should be set as part of completeDefinition.
  3317. bool canPassInRegisters() const {
  3318. return getArgPassingRestrictions() == APK_CanPassInRegs;
  3319. }
  3320. ArgPassingKind getArgPassingRestrictions() const {
  3321. return static_cast<ArgPassingKind>(RecordDeclBits.ArgPassingRestrictions);
  3322. }
  3323. void setArgPassingRestrictions(ArgPassingKind Kind) {
  3324. RecordDeclBits.ArgPassingRestrictions = Kind;
  3325. }
  3326. bool isParamDestroyedInCallee() const {
  3327. return RecordDeclBits.ParamDestroyedInCallee;
  3328. }
  3329. void setParamDestroyedInCallee(bool V) {
  3330. RecordDeclBits.ParamDestroyedInCallee = V;
  3331. }
  3332. /// Determines whether this declaration represents the
  3333. /// injected class name.
  3334. ///
  3335. /// The injected class name in C++ is the name of the class that
  3336. /// appears inside the class itself. For example:
  3337. ///
  3338. /// \code
  3339. /// struct C {
  3340. /// // C is implicitly declared here as a synonym for the class name.
  3341. /// };
  3342. ///
  3343. /// C::C c; // same as "C c;"
  3344. /// \endcode
  3345. bool isInjectedClassName() const;
  3346. /// Determine whether this record is a class describing a lambda
  3347. /// function object.
  3348. bool isLambda() const;
  3349. /// Determine whether this record is a record for captured variables in
  3350. /// CapturedStmt construct.
  3351. bool isCapturedRecord() const;
  3352. /// Mark the record as a record for captured variables in CapturedStmt
  3353. /// construct.
  3354. void setCapturedRecord();
  3355. /// Returns the RecordDecl that actually defines
  3356. /// this struct/union/class. When determining whether or not a
  3357. /// struct/union/class is completely defined, one should use this
  3358. /// method as opposed to 'isCompleteDefinition'.
  3359. /// 'isCompleteDefinition' indicates whether or not a specific
  3360. /// RecordDecl is a completed definition, not whether or not the
  3361. /// record type is defined. This method returns NULL if there is
  3362. /// no RecordDecl that defines the struct/union/tag.
  3363. RecordDecl *getDefinition() const {
  3364. return cast_or_null<RecordDecl>(TagDecl::getDefinition());
  3365. }
  3366. /// Returns whether this record is a union, or contains (at any nesting level)
  3367. /// a union member. This is used by CMSE to warn about possible information
  3368. /// leaks.
  3369. bool isOrContainsUnion() const;
  3370. // Iterator access to field members. The field iterator only visits
  3371. // the non-static data members of this class, ignoring any static
  3372. // data members, functions, constructors, destructors, etc.
  3373. using field_iterator = specific_decl_iterator<FieldDecl>;
  3374. using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>;
  3375. field_range fields() const { return field_range(field_begin(), field_end()); }
  3376. field_iterator field_begin() const;
  3377. field_iterator field_end() const {
  3378. return field_iterator(decl_iterator());
  3379. }
  3380. // Whether there are any fields (non-static data members) in this record.
  3381. bool field_empty() const {
  3382. return field_begin() == field_end();
  3383. }
  3384. /// Note that the definition of this type is now complete.
  3385. virtual void completeDefinition();
  3386. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  3387. static bool classofKind(Kind K) {
  3388. return K >= firstRecord && K <= lastRecord;
  3389. }
  3390. /// Get whether or not this is an ms_struct which can
  3391. /// be turned on with an attribute, pragma, or -mms-bitfields
  3392. /// commandline option.
  3393. bool isMsStruct(const ASTContext &C) const;
  3394. /// Whether we are allowed to insert extra padding between fields.
  3395. /// These padding are added to help AddressSanitizer detect
  3396. /// intra-object-overflow bugs.
  3397. bool mayInsertExtraPadding(bool EmitRemark = false) const;
  3398. /// Finds the first data member which has a name.
  3399. /// nullptr is returned if no named data member exists.
  3400. const FieldDecl *findFirstNamedDataMember() const;
  3401. private:
  3402. /// Deserialize just the fields.
  3403. void LoadFieldsFromExternalStorage() const;
  3404. };
  3405. class FileScopeAsmDecl : public Decl {
  3406. StringLiteral *AsmString;
  3407. SourceLocation RParenLoc;
  3408. FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
  3409. SourceLocation StartL, SourceLocation EndL)
  3410. : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
  3411. virtual void anchor();
  3412. public:
  3413. static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
  3414. StringLiteral *Str, SourceLocation AsmLoc,
  3415. SourceLocation RParenLoc);
  3416. static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  3417. SourceLocation getAsmLoc() const { return getLocation(); }
  3418. SourceLocation getRParenLoc() const { return RParenLoc; }
  3419. void setRParenLoc(SourceLocation L) { RParenLoc = L; }
  3420. SourceRange getSourceRange() const override LLVM_READONLY {
  3421. return SourceRange(getAsmLoc(), getRParenLoc());
  3422. }
  3423. const StringLiteral *getAsmString() const { return AsmString; }
  3424. StringLiteral *getAsmString() { return AsmString; }
  3425. void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
  3426. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  3427. static bool classofKind(Kind K) { return K == FileScopeAsm; }
  3428. };
  3429. /// Represents a block literal declaration, which is like an
  3430. /// unnamed FunctionDecl. For example:
  3431. /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
  3432. class BlockDecl : public Decl, public DeclContext {
  3433. // This class stores some data in DeclContext::BlockDeclBits
  3434. // to save some space. Use the provided accessors to access it.
  3435. public:
  3436. /// A class which contains all the information about a particular
  3437. /// captured value.
  3438. class Capture {
  3439. enum {
  3440. flag_isByRef = 0x1,
  3441. flag_isNested = 0x2
  3442. };
  3443. /// The variable being captured.
  3444. llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
  3445. /// The copy expression, expressed in terms of a DeclRef (or
  3446. /// BlockDeclRef) to the captured variable. Only required if the
  3447. /// variable has a C++ class type.
  3448. Expr *CopyExpr;
  3449. public:
  3450. Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
  3451. : VariableAndFlags(variable,
  3452. (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
  3453. CopyExpr(copy) {}
  3454. /// The variable being captured.
  3455. VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
  3456. /// Whether this is a "by ref" capture, i.e. a capture of a __block
  3457. /// variable.
  3458. bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
  3459. bool isEscapingByref() const {
  3460. return getVariable()->isEscapingByref();
  3461. }
  3462. bool isNonEscapingByref() const {
  3463. return getVariable()->isNonEscapingByref();
  3464. }
  3465. /// Whether this is a nested capture, i.e. the variable captured
  3466. /// is not from outside the immediately enclosing function/block.
  3467. bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
  3468. bool hasCopyExpr() const { return CopyExpr != nullptr; }
  3469. Expr *getCopyExpr() const { return CopyExpr; }
  3470. void setCopyExpr(Expr *e) { CopyExpr = e; }
  3471. };
  3472. private:
  3473. /// A new[]'d array of pointers to ParmVarDecls for the formal
  3474. /// parameters of this function. This is null if a prototype or if there are
  3475. /// no formals.
  3476. ParmVarDecl **ParamInfo = nullptr;
  3477. unsigned NumParams = 0;
  3478. Stmt *Body = nullptr;
  3479. TypeSourceInfo *SignatureAsWritten = nullptr;
  3480. const Capture *Captures = nullptr;
  3481. unsigned NumCaptures = 0;
  3482. unsigned ManglingNumber = 0;
  3483. Decl *ManglingContextDecl = nullptr;
  3484. protected:
  3485. BlockDecl(DeclContext *DC, SourceLocation CaretLoc);
  3486. public:
  3487. static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
  3488. static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  3489. SourceLocation getCaretLocation() const { return getLocation(); }
  3490. bool isVariadic() const { return BlockDeclBits.IsVariadic; }
  3491. void setIsVariadic(bool value) { BlockDeclBits.IsVariadic = value; }
  3492. CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
  3493. Stmt *getBody() const override { return (Stmt*) Body; }
  3494. void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
  3495. void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
  3496. TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
  3497. // ArrayRef access to formal parameters.
  3498. ArrayRef<ParmVarDecl *> parameters() const {
  3499. return {ParamInfo, getNumParams()};
  3500. }
  3501. MutableArrayRef<ParmVarDecl *> parameters() {
  3502. return {ParamInfo, getNumParams()};
  3503. }
  3504. // Iterator access to formal parameters.
  3505. using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
  3506. using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
  3507. bool param_empty() const { return parameters().empty(); }
  3508. param_iterator param_begin() { return parameters().begin(); }
  3509. param_iterator param_end() { return parameters().end(); }
  3510. param_const_iterator param_begin() const { return parameters().begin(); }
  3511. param_const_iterator param_end() const { return parameters().end(); }
  3512. size_t param_size() const { return parameters().size(); }
  3513. unsigned getNumParams() const { return NumParams; }
  3514. const ParmVarDecl *getParamDecl(unsigned i) const {
  3515. assert(i < getNumParams() && "Illegal param #");
  3516. return ParamInfo[i];
  3517. }
  3518. ParmVarDecl *getParamDecl(unsigned i) {
  3519. assert(i < getNumParams() && "Illegal param #");
  3520. return ParamInfo[i];
  3521. }
  3522. void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
  3523. /// True if this block (or its nested blocks) captures
  3524. /// anything of local storage from its enclosing scopes.
  3525. bool hasCaptures() const { return NumCaptures || capturesCXXThis(); }
  3526. /// Returns the number of captured variables.
  3527. /// Does not include an entry for 'this'.
  3528. unsigned getNumCaptures() const { return NumCaptures; }
  3529. using capture_const_iterator = ArrayRef<Capture>::const_iterator;
  3530. ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
  3531. capture_const_iterator capture_begin() const { return captures().begin(); }
  3532. capture_const_iterator capture_end() const { return captures().end(); }
  3533. bool capturesCXXThis() const { return BlockDeclBits.CapturesCXXThis; }
  3534. void setCapturesCXXThis(bool B = true) { BlockDeclBits.CapturesCXXThis = B; }
  3535. bool blockMissingReturnType() const {
  3536. return BlockDeclBits.BlockMissingReturnType;
  3537. }
  3538. void setBlockMissingReturnType(bool val = true) {
  3539. BlockDeclBits.BlockMissingReturnType = val;
  3540. }
  3541. bool isConversionFromLambda() const {
  3542. return BlockDeclBits.IsConversionFromLambda;
  3543. }
  3544. void setIsConversionFromLambda(bool val = true) {
  3545. BlockDeclBits.IsConversionFromLambda = val;
  3546. }
  3547. bool doesNotEscape() const { return BlockDeclBits.DoesNotEscape; }
  3548. void setDoesNotEscape(bool B = true) { BlockDeclBits.DoesNotEscape = B; }
  3549. bool canAvoidCopyToHeap() const {
  3550. return BlockDeclBits.CanAvoidCopyToHeap;
  3551. }
  3552. void setCanAvoidCopyToHeap(bool B = true) {
  3553. BlockDeclBits.CanAvoidCopyToHeap = B;
  3554. }
  3555. bool capturesVariable(const VarDecl *var) const;
  3556. void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
  3557. bool CapturesCXXThis);
  3558. unsigned getBlockManglingNumber() const { return ManglingNumber; }
  3559. Decl *getBlockManglingContextDecl() const { return ManglingContextDecl; }
  3560. void setBlockMangling(unsigned Number, Decl *Ctx) {
  3561. ManglingNumber = Number;
  3562. ManglingContextDecl = Ctx;
  3563. }
  3564. SourceRange getSourceRange() const override LLVM_READONLY;
  3565. // Implement isa/cast/dyncast/etc.
  3566. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  3567. static bool classofKind(Kind K) { return K == Block; }
  3568. static DeclContext *castToDeclContext(const BlockDecl *D) {
  3569. return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
  3570. }
  3571. static BlockDecl *castFromDeclContext(const DeclContext *DC) {
  3572. return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
  3573. }
  3574. };
  3575. /// Represents the body of a CapturedStmt, and serves as its DeclContext.
  3576. class CapturedDecl final
  3577. : public Decl,
  3578. public DeclContext,
  3579. private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
  3580. protected:
  3581. size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
  3582. return NumParams;
  3583. }
  3584. private:
  3585. /// The number of parameters to the outlined function.
  3586. unsigned NumParams;
  3587. /// The position of context parameter in list of parameters.
  3588. unsigned ContextParam;
  3589. /// The body of the outlined function.
  3590. llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
  3591. explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
  3592. ImplicitParamDecl *const *getParams() const {
  3593. return getTrailingObjects<ImplicitParamDecl *>();
  3594. }
  3595. ImplicitParamDecl **getParams() {
  3596. return getTrailingObjects<ImplicitParamDecl *>();
  3597. }
  3598. public:
  3599. friend class ASTDeclReader;
  3600. friend class ASTDeclWriter;
  3601. friend TrailingObjects;
  3602. static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
  3603. unsigned NumParams);
  3604. static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
  3605. unsigned NumParams);
  3606. Stmt *getBody() const override;
  3607. void setBody(Stmt *B);
  3608. bool isNothrow() const;
  3609. void setNothrow(bool Nothrow = true);
  3610. unsigned getNumParams() const { return NumParams; }
  3611. ImplicitParamDecl *getParam(unsigned i) const {
  3612. assert(i < NumParams);
  3613. return getParams()[i];
  3614. }
  3615. void setParam(unsigned i, ImplicitParamDecl *P) {
  3616. assert(i < NumParams);
  3617. getParams()[i] = P;
  3618. }
  3619. // ArrayRef interface to parameters.
  3620. ArrayRef<ImplicitParamDecl *> parameters() const {
  3621. return {getParams(), getNumParams()};
  3622. }
  3623. MutableArrayRef<ImplicitParamDecl *> parameters() {
  3624. return {getParams(), getNumParams()};
  3625. }
  3626. /// Retrieve the parameter containing captured variables.
  3627. ImplicitParamDecl *getContextParam() const {
  3628. assert(ContextParam < NumParams);
  3629. return getParam(ContextParam);
  3630. }
  3631. void setContextParam(unsigned i, ImplicitParamDecl *P) {
  3632. assert(i < NumParams);
  3633. ContextParam = i;
  3634. setParam(i, P);
  3635. }
  3636. unsigned getContextParamPosition() const { return ContextParam; }
  3637. using param_iterator = ImplicitParamDecl *const *;
  3638. using param_range = llvm::iterator_range<param_iterator>;
  3639. /// Retrieve an iterator pointing to the first parameter decl.
  3640. param_iterator param_begin() const { return getParams(); }
  3641. /// Retrieve an iterator one past the last parameter decl.
  3642. param_iterator param_end() const { return getParams() + NumParams; }
  3643. // Implement isa/cast/dyncast/etc.
  3644. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  3645. static bool classofKind(Kind K) { return K == Captured; }
  3646. static DeclContext *castToDeclContext(const CapturedDecl *D) {
  3647. return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
  3648. }
  3649. static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
  3650. return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
  3651. }
  3652. };
  3653. /// Describes a module import declaration, which makes the contents
  3654. /// of the named module visible in the current translation unit.
  3655. ///
  3656. /// An import declaration imports the named module (or submodule). For example:
  3657. /// \code
  3658. /// @import std.vector;
  3659. /// \endcode
  3660. ///
  3661. /// Import declarations can also be implicitly generated from
  3662. /// \#include/\#import directives.
  3663. class ImportDecl final : public Decl,
  3664. llvm::TrailingObjects<ImportDecl, SourceLocation> {
  3665. friend class ASTContext;
  3666. friend class ASTDeclReader;
  3667. friend class ASTReader;
  3668. friend TrailingObjects;
  3669. /// The imported module.
  3670. Module *ImportedModule = nullptr;
  3671. /// The next import in the list of imports local to the translation
  3672. /// unit being parsed (not loaded from an AST file).
  3673. ///
  3674. /// Includes a bit that indicates whether we have source-location information
  3675. /// for each identifier in the module name.
  3676. ///
  3677. /// When the bit is false, we only have a single source location for the
  3678. /// end of the import declaration.
  3679. llvm::PointerIntPair<ImportDecl *, 1, bool> NextLocalImportAndComplete;
  3680. ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
  3681. ArrayRef<SourceLocation> IdentifierLocs);
  3682. ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
  3683. SourceLocation EndLoc);
  3684. ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {}
  3685. bool isImportComplete() const { return NextLocalImportAndComplete.getInt(); }
  3686. void setImportComplete(bool C) { NextLocalImportAndComplete.setInt(C); }
  3687. /// The next import in the list of imports local to the translation
  3688. /// unit being parsed (not loaded from an AST file).
  3689. ImportDecl *getNextLocalImport() const {
  3690. return NextLocalImportAndComplete.getPointer();
  3691. }
  3692. void setNextLocalImport(ImportDecl *Import) {
  3693. NextLocalImportAndComplete.setPointer(Import);
  3694. }
  3695. public:
  3696. /// Create a new module import declaration.
  3697. static ImportDecl *Create(ASTContext &C, DeclContext *DC,
  3698. SourceLocation StartLoc, Module *Imported,
  3699. ArrayRef<SourceLocation> IdentifierLocs);
  3700. /// Create a new module import declaration for an implicitly-generated
  3701. /// import.
  3702. static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
  3703. SourceLocation StartLoc, Module *Imported,
  3704. SourceLocation EndLoc);
  3705. /// Create a new, deserialized module import declaration.
  3706. static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
  3707. unsigned NumLocations);
  3708. /// Retrieve the module that was imported by the import declaration.
  3709. Module *getImportedModule() const { return ImportedModule; }
  3710. /// Retrieves the locations of each of the identifiers that make up
  3711. /// the complete module name in the import declaration.
  3712. ///
  3713. /// This will return an empty array if the locations of the individual
  3714. /// identifiers aren't available.
  3715. ArrayRef<SourceLocation> getIdentifierLocs() const;
  3716. SourceRange getSourceRange() const override LLVM_READONLY;
  3717. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  3718. static bool classofKind(Kind K) { return K == Import; }
  3719. };
  3720. /// Represents a C++ Modules TS module export declaration.
  3721. ///
  3722. /// For example:
  3723. /// \code
  3724. /// export void foo();
  3725. /// \endcode
  3726. class ExportDecl final : public Decl, public DeclContext {
  3727. virtual void anchor();
  3728. private:
  3729. friend class ASTDeclReader;
  3730. /// The source location for the right brace (if valid).
  3731. SourceLocation RBraceLoc;
  3732. ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
  3733. : Decl(Export, DC, ExportLoc), DeclContext(Export),
  3734. RBraceLoc(SourceLocation()) {}
  3735. public:
  3736. static ExportDecl *Create(ASTContext &C, DeclContext *DC,
  3737. SourceLocation ExportLoc);
  3738. static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  3739. SourceLocation getExportLoc() const { return getLocation(); }
  3740. SourceLocation getRBraceLoc() const { return RBraceLoc; }
  3741. void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
  3742. bool hasBraces() const { return RBraceLoc.isValid(); }
  3743. SourceLocation getEndLoc() const LLVM_READONLY {
  3744. if (hasBraces())
  3745. return RBraceLoc;
  3746. // No braces: get the end location of the (only) declaration in context
  3747. // (if present).
  3748. return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
  3749. }
  3750. SourceRange getSourceRange() const override LLVM_READONLY {
  3751. return SourceRange(getLocation(), getEndLoc());
  3752. }
  3753. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  3754. static bool classofKind(Kind K) { return K == Export; }
  3755. static DeclContext *castToDeclContext(const ExportDecl *D) {
  3756. return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
  3757. }
  3758. static ExportDecl *castFromDeclContext(const DeclContext *DC) {
  3759. return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
  3760. }
  3761. };
  3762. /// Represents an empty-declaration.
  3763. class EmptyDecl : public Decl {
  3764. EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {}
  3765. virtual void anchor();
  3766. public:
  3767. static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
  3768. SourceLocation L);
  3769. static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
  3770. static bool classof(const Decl *D) { return classofKind(D->getKind()); }
  3771. static bool classofKind(Kind K) { return K == Empty; }
  3772. };
  3773. /// Insertion operator for diagnostics. This allows sending NamedDecl's
  3774. /// into a diagnostic with <<.
  3775. inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
  3776. const NamedDecl *ND) {
  3777. PD.AddTaggedVal(reinterpret_cast<uint64_t>(ND),
  3778. DiagnosticsEngine::ak_nameddecl);
  3779. return PD;
  3780. }
  3781. template<typename decl_type>
  3782. void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
  3783. // Note: This routine is implemented here because we need both NamedDecl
  3784. // and Redeclarable to be defined.
  3785. assert(RedeclLink.isFirst() &&
  3786. "setPreviousDecl on a decl already in a redeclaration chain");
  3787. if (PrevDecl) {
  3788. // Point to previous. Make sure that this is actually the most recent
  3789. // redeclaration, or we can build invalid chains. If the most recent
  3790. // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
  3791. First = PrevDecl->getFirstDecl();
  3792. assert(First->RedeclLink.isFirst() && "Expected first");
  3793. decl_type *MostRecent = First->getNextRedeclaration();
  3794. RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
  3795. // If the declaration was previously visible, a redeclaration of it remains
  3796. // visible even if it wouldn't be visible by itself.
  3797. static_cast<decl_type*>(this)->IdentifierNamespace |=
  3798. MostRecent->getIdentifierNamespace() &
  3799. (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
  3800. } else {
  3801. // Make this first.
  3802. First = static_cast<decl_type*>(this);
  3803. }
  3804. // First one will point to this one as latest.
  3805. First->RedeclLink.setLatest(static_cast<decl_type*>(this));
  3806. assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
  3807. cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid());
  3808. }
  3809. // Inline function definitions.
  3810. /// Check if the given decl is complete.
  3811. ///
  3812. /// We use this function to break a cycle between the inline definitions in
  3813. /// Type.h and Decl.h.
  3814. inline bool IsEnumDeclComplete(EnumDecl *ED) {
  3815. return ED->isComplete();
  3816. }
  3817. /// Check if the given decl is scoped.
  3818. ///
  3819. /// We use this function to break a cycle between the inline definitions in
  3820. /// Type.h and Decl.h.
  3821. inline bool IsEnumDeclScoped(EnumDecl *ED) {
  3822. return ED->isScoped();
  3823. }
  3824. /// OpenMP variants are mangled early based on their OpenMP context selector.
  3825. /// The new name looks likes this:
  3826. /// <name> + OpenMPVariantManglingSeparatorStr + <mangled OpenMP context>
  3827. static constexpr StringRef getOpenMPVariantManglingSeparatorStr() {
  3828. return "$ompvariant";
  3829. }
  3830. } // namespace clang
  3831. #endif // LLVM_CLANG_AST_DECL_H
  3832. #ifdef __GNUC__
  3833. #pragma GCC diagnostic pop
  3834. #endif