Decl.cpp 148 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125
  1. //===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Decl subclasses.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/Decl.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTLambda.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/Attr.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "clang/AST/DeclTemplate.h"
  21. #include "clang/AST/Expr.h"
  22. #include "clang/AST/ExprCXX.h"
  23. #include "clang/AST/PrettyPrinter.h"
  24. #include "clang/AST/Stmt.h"
  25. #include "clang/AST/TypeLoc.h"
  26. #include "clang/Basic/Builtins.h"
  27. #include "clang/Basic/IdentifierTable.h"
  28. #include "clang/Basic/Module.h"
  29. #include "clang/Basic/Specifiers.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/Frontend/FrontendDiagnostic.h"
  32. #include "llvm/Support/ErrorHandling.h"
  33. #include <algorithm>
  34. using namespace clang;
  35. Decl *clang::getPrimaryMergedDecl(Decl *D) {
  36. return D->getASTContext().getPrimaryMergedDecl(D);
  37. }
  38. // Defined here so that it can be inlined into its direct callers.
  39. bool Decl::isOutOfLine() const {
  40. return !getLexicalDeclContext()->Equals(getDeclContext());
  41. }
  42. TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
  43. : Decl(TranslationUnit, nullptr, SourceLocation()),
  44. DeclContext(TranslationUnit), Ctx(ctx), AnonymousNamespace(nullptr) {
  45. Hidden = Ctx.getLangOpts().ModulesLocalVisibility;
  46. }
  47. //===----------------------------------------------------------------------===//
  48. // NamedDecl Implementation
  49. //===----------------------------------------------------------------------===//
  50. // Visibility rules aren't rigorously externally specified, but here
  51. // are the basic principles behind what we implement:
  52. //
  53. // 1. An explicit visibility attribute is generally a direct expression
  54. // of the user's intent and should be honored. Only the innermost
  55. // visibility attribute applies. If no visibility attribute applies,
  56. // global visibility settings are considered.
  57. //
  58. // 2. There is one caveat to the above: on or in a template pattern,
  59. // an explicit visibility attribute is just a default rule, and
  60. // visibility can be decreased by the visibility of template
  61. // arguments. But this, too, has an exception: an attribute on an
  62. // explicit specialization or instantiation causes all the visibility
  63. // restrictions of the template arguments to be ignored.
  64. //
  65. // 3. A variable that does not otherwise have explicit visibility can
  66. // be restricted by the visibility of its type.
  67. //
  68. // 4. A visibility restriction is explicit if it comes from an
  69. // attribute (or something like it), not a global visibility setting.
  70. // When emitting a reference to an external symbol, visibility
  71. // restrictions are ignored unless they are explicit.
  72. //
  73. // 5. When computing the visibility of a non-type, including a
  74. // non-type member of a class, only non-type visibility restrictions
  75. // are considered: the 'visibility' attribute, global value-visibility
  76. // settings, and a few special cases like __private_extern.
  77. //
  78. // 6. When computing the visibility of a type, including a type member
  79. // of a class, only type visibility restrictions are considered:
  80. // the 'type_visibility' attribute and global type-visibility settings.
  81. // However, a 'visibility' attribute counts as a 'type_visibility'
  82. // attribute on any declaration that only has the former.
  83. //
  84. // The visibility of a "secondary" entity, like a template argument,
  85. // is computed using the kind of that entity, not the kind of the
  86. // primary entity for which we are computing visibility. For example,
  87. // the visibility of a specialization of either of these templates:
  88. // template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
  89. // template <class T, bool (&compare)(T, X)> class matcher;
  90. // is restricted according to the type visibility of the argument 'T',
  91. // the type visibility of 'bool(&)(T,X)', and the value visibility of
  92. // the argument function 'compare'. That 'has_match' is a value
  93. // and 'matcher' is a type only matters when looking for attributes
  94. // and settings from the immediate context.
  95. const unsigned IgnoreExplicitVisibilityBit = 2;
  96. const unsigned IgnoreAllVisibilityBit = 4;
  97. /// Kinds of LV computation. The linkage side of the computation is
  98. /// always the same, but different things can change how visibility is
  99. /// computed.
  100. enum LVComputationKind {
  101. /// Do an LV computation for, ultimately, a type.
  102. /// Visibility may be restricted by type visibility settings and
  103. /// the visibility of template arguments.
  104. LVForType = NamedDecl::VisibilityForType,
  105. /// Do an LV computation for, ultimately, a non-type declaration.
  106. /// Visibility may be restricted by value visibility settings and
  107. /// the visibility of template arguments.
  108. LVForValue = NamedDecl::VisibilityForValue,
  109. /// Do an LV computation for, ultimately, a type that already has
  110. /// some sort of explicit visibility. Visibility may only be
  111. /// restricted by the visibility of template arguments.
  112. LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
  113. /// Do an LV computation for, ultimately, a non-type declaration
  114. /// that already has some sort of explicit visibility. Visibility
  115. /// may only be restricted by the visibility of template arguments.
  116. LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
  117. /// Do an LV computation when we only care about the linkage.
  118. LVForLinkageOnly =
  119. LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
  120. };
  121. /// Does this computation kind permit us to consider additional
  122. /// visibility settings from attributes and the like?
  123. static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
  124. return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
  125. }
  126. /// Given an LVComputationKind, return one of the same type/value sort
  127. /// that records that it already has explicit visibility.
  128. static LVComputationKind
  129. withExplicitVisibilityAlready(LVComputationKind oldKind) {
  130. LVComputationKind newKind =
  131. static_cast<LVComputationKind>(unsigned(oldKind) |
  132. IgnoreExplicitVisibilityBit);
  133. assert(oldKind != LVForType || newKind == LVForExplicitType);
  134. assert(oldKind != LVForValue || newKind == LVForExplicitValue);
  135. assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
  136. assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
  137. return newKind;
  138. }
  139. static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
  140. LVComputationKind kind) {
  141. assert(!hasExplicitVisibilityAlready(kind) &&
  142. "asking for explicit visibility when we shouldn't be");
  143. return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
  144. }
  145. /// Is the given declaration a "type" or a "value" for the purposes of
  146. /// visibility computation?
  147. static bool usesTypeVisibility(const NamedDecl *D) {
  148. return isa<TypeDecl>(D) ||
  149. isa<ClassTemplateDecl>(D) ||
  150. isa<ObjCInterfaceDecl>(D);
  151. }
  152. /// Does the given declaration have member specialization information,
  153. /// and if so, is it an explicit specialization?
  154. template <class T> static typename
  155. std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
  156. isExplicitMemberSpecialization(const T *D) {
  157. if (const MemberSpecializationInfo *member =
  158. D->getMemberSpecializationInfo()) {
  159. return member->isExplicitSpecialization();
  160. }
  161. return false;
  162. }
  163. /// For templates, this question is easier: a member template can't be
  164. /// explicitly instantiated, so there's a single bit indicating whether
  165. /// or not this is an explicit member specialization.
  166. static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
  167. return D->isMemberSpecialization();
  168. }
  169. /// Given a visibility attribute, return the explicit visibility
  170. /// associated with it.
  171. template <class T>
  172. static Visibility getVisibilityFromAttr(const T *attr) {
  173. switch (attr->getVisibility()) {
  174. case T::Default:
  175. return DefaultVisibility;
  176. case T::Hidden:
  177. return HiddenVisibility;
  178. case T::Protected:
  179. return ProtectedVisibility;
  180. }
  181. llvm_unreachable("bad visibility kind");
  182. }
  183. /// Return the explicit visibility of the given declaration.
  184. static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
  185. NamedDecl::ExplicitVisibilityKind kind) {
  186. // If we're ultimately computing the visibility of a type, look for
  187. // a 'type_visibility' attribute before looking for 'visibility'.
  188. if (kind == NamedDecl::VisibilityForType) {
  189. if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
  190. return getVisibilityFromAttr(A);
  191. }
  192. }
  193. // If this declaration has an explicit visibility attribute, use it.
  194. if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
  195. return getVisibilityFromAttr(A);
  196. }
  197. // If we're on Mac OS X, an 'availability' for Mac OS X attribute
  198. // implies visibility(default).
  199. if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
  200. for (const auto *A : D->specific_attrs<AvailabilityAttr>())
  201. if (A->getPlatform()->getName().equals("macosx"))
  202. return DefaultVisibility;
  203. }
  204. return None;
  205. }
  206. static LinkageInfo
  207. getLVForType(const Type &T, LVComputationKind computation) {
  208. if (computation == LVForLinkageOnly)
  209. return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
  210. return T.getLinkageAndVisibility();
  211. }
  212. /// \brief Get the most restrictive linkage for the types in the given
  213. /// template parameter list. For visibility purposes, template
  214. /// parameters are part of the signature of a template.
  215. static LinkageInfo
  216. getLVForTemplateParameterList(const TemplateParameterList *Params,
  217. LVComputationKind computation) {
  218. LinkageInfo LV;
  219. for (const NamedDecl *P : *Params) {
  220. // Template type parameters are the most common and never
  221. // contribute to visibility, pack or not.
  222. if (isa<TemplateTypeParmDecl>(P))
  223. continue;
  224. // Non-type template parameters can be restricted by the value type, e.g.
  225. // template <enum X> class A { ... };
  226. // We have to be careful here, though, because we can be dealing with
  227. // dependent types.
  228. if (const NonTypeTemplateParmDecl *NTTP =
  229. dyn_cast<NonTypeTemplateParmDecl>(P)) {
  230. // Handle the non-pack case first.
  231. if (!NTTP->isExpandedParameterPack()) {
  232. if (!NTTP->getType()->isDependentType()) {
  233. LV.merge(getLVForType(*NTTP->getType(), computation));
  234. }
  235. continue;
  236. }
  237. // Look at all the types in an expanded pack.
  238. for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
  239. QualType type = NTTP->getExpansionType(i);
  240. if (!type->isDependentType())
  241. LV.merge(type->getLinkageAndVisibility());
  242. }
  243. continue;
  244. }
  245. // Template template parameters can be restricted by their
  246. // template parameters, recursively.
  247. const TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(P);
  248. // Handle the non-pack case first.
  249. if (!TTP->isExpandedParameterPack()) {
  250. LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
  251. computation));
  252. continue;
  253. }
  254. // Look at all expansions in an expanded pack.
  255. for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
  256. i != n; ++i) {
  257. LV.merge(getLVForTemplateParameterList(
  258. TTP->getExpansionTemplateParameters(i), computation));
  259. }
  260. }
  261. return LV;
  262. }
  263. /// getLVForDecl - Get the linkage and visibility for the given declaration.
  264. static LinkageInfo getLVForDecl(const NamedDecl *D,
  265. LVComputationKind computation);
  266. static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
  267. const Decl *Ret = nullptr;
  268. const DeclContext *DC = D->getDeclContext();
  269. while (DC->getDeclKind() != Decl::TranslationUnit) {
  270. if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
  271. Ret = cast<Decl>(DC);
  272. DC = DC->getParent();
  273. }
  274. return Ret;
  275. }
  276. /// \brief Get the most restrictive linkage for the types and
  277. /// declarations in the given template argument list.
  278. ///
  279. /// Note that we don't take an LVComputationKind because we always
  280. /// want to honor the visibility of template arguments in the same way.
  281. static LinkageInfo getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
  282. LVComputationKind computation) {
  283. LinkageInfo LV;
  284. for (const TemplateArgument &Arg : Args) {
  285. switch (Arg.getKind()) {
  286. case TemplateArgument::Null:
  287. case TemplateArgument::Integral:
  288. case TemplateArgument::Expression:
  289. continue;
  290. case TemplateArgument::Type:
  291. LV.merge(getLVForType(*Arg.getAsType(), computation));
  292. continue;
  293. case TemplateArgument::Declaration:
  294. if (NamedDecl *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
  295. assert(!usesTypeVisibility(ND));
  296. LV.merge(getLVForDecl(ND, computation));
  297. }
  298. continue;
  299. case TemplateArgument::NullPtr:
  300. LV.merge(Arg.getNullPtrType()->getLinkageAndVisibility());
  301. continue;
  302. case TemplateArgument::Template:
  303. case TemplateArgument::TemplateExpansion:
  304. if (TemplateDecl *Template =
  305. Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
  306. LV.merge(getLVForDecl(Template, computation));
  307. continue;
  308. case TemplateArgument::Pack:
  309. LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
  310. continue;
  311. }
  312. llvm_unreachable("bad template argument kind");
  313. }
  314. return LV;
  315. }
  316. static LinkageInfo
  317. getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
  318. LVComputationKind computation) {
  319. return getLVForTemplateArgumentList(TArgs.asArray(), computation);
  320. }
  321. static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
  322. const FunctionTemplateSpecializationInfo *specInfo) {
  323. // Include visibility from the template parameters and arguments
  324. // only if this is not an explicit instantiation or specialization
  325. // with direct explicit visibility. (Implicit instantiations won't
  326. // have a direct attribute.)
  327. if (!specInfo->isExplicitInstantiationOrSpecialization())
  328. return true;
  329. return !fn->hasAttr<VisibilityAttr>();
  330. }
  331. /// Merge in template-related linkage and visibility for the given
  332. /// function template specialization.
  333. ///
  334. /// We don't need a computation kind here because we can assume
  335. /// LVForValue.
  336. ///
  337. /// \param[out] LV the computation to use for the parent
  338. static void
  339. mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
  340. const FunctionTemplateSpecializationInfo *specInfo,
  341. LVComputationKind computation) {
  342. bool considerVisibility =
  343. shouldConsiderTemplateVisibility(fn, specInfo);
  344. // Merge information from the template parameters.
  345. FunctionTemplateDecl *temp = specInfo->getTemplate();
  346. LinkageInfo tempLV =
  347. getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
  348. LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
  349. // Merge information from the template arguments.
  350. const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
  351. LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
  352. LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
  353. }
  354. /// Does the given declaration have a direct visibility attribute
  355. /// that would match the given rules?
  356. static bool hasDirectVisibilityAttribute(const NamedDecl *D,
  357. LVComputationKind computation) {
  358. switch (computation) {
  359. case LVForType:
  360. case LVForExplicitType:
  361. if (D->hasAttr<TypeVisibilityAttr>())
  362. return true;
  363. // fallthrough
  364. case LVForValue:
  365. case LVForExplicitValue:
  366. if (D->hasAttr<VisibilityAttr>())
  367. return true;
  368. return false;
  369. case LVForLinkageOnly:
  370. return false;
  371. }
  372. llvm_unreachable("bad visibility computation kind");
  373. }
  374. /// Should we consider visibility associated with the template
  375. /// arguments and parameters of the given class template specialization?
  376. static bool shouldConsiderTemplateVisibility(
  377. const ClassTemplateSpecializationDecl *spec,
  378. LVComputationKind computation) {
  379. // Include visibility from the template parameters and arguments
  380. // only if this is not an explicit instantiation or specialization
  381. // with direct explicit visibility (and note that implicit
  382. // instantiations won't have a direct attribute).
  383. //
  384. // Furthermore, we want to ignore template parameters and arguments
  385. // for an explicit specialization when computing the visibility of a
  386. // member thereof with explicit visibility.
  387. //
  388. // This is a bit complex; let's unpack it.
  389. //
  390. // An explicit class specialization is an independent, top-level
  391. // declaration. As such, if it or any of its members has an
  392. // explicit visibility attribute, that must directly express the
  393. // user's intent, and we should honor it. The same logic applies to
  394. // an explicit instantiation of a member of such a thing.
  395. // Fast path: if this is not an explicit instantiation or
  396. // specialization, we always want to consider template-related
  397. // visibility restrictions.
  398. if (!spec->isExplicitInstantiationOrSpecialization())
  399. return true;
  400. // This is the 'member thereof' check.
  401. if (spec->isExplicitSpecialization() &&
  402. hasExplicitVisibilityAlready(computation))
  403. return false;
  404. return !hasDirectVisibilityAttribute(spec, computation);
  405. }
  406. /// Merge in template-related linkage and visibility for the given
  407. /// class template specialization.
  408. static void mergeTemplateLV(LinkageInfo &LV,
  409. const ClassTemplateSpecializationDecl *spec,
  410. LVComputationKind computation) {
  411. bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
  412. // Merge information from the template parameters, but ignore
  413. // visibility if we're only considering template arguments.
  414. ClassTemplateDecl *temp = spec->getSpecializedTemplate();
  415. LinkageInfo tempLV =
  416. getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
  417. LV.mergeMaybeWithVisibility(tempLV,
  418. considerVisibility && !hasExplicitVisibilityAlready(computation));
  419. // Merge information from the template arguments. We ignore
  420. // template-argument visibility if we've got an explicit
  421. // instantiation with a visibility attribute.
  422. const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
  423. LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
  424. if (considerVisibility)
  425. LV.mergeVisibility(argsLV);
  426. LV.mergeExternalVisibility(argsLV);
  427. }
  428. /// Should we consider visibility associated with the template
  429. /// arguments and parameters of the given variable template
  430. /// specialization? As usual, follow class template specialization
  431. /// logic up to initialization.
  432. static bool shouldConsiderTemplateVisibility(
  433. const VarTemplateSpecializationDecl *spec,
  434. LVComputationKind computation) {
  435. // Include visibility from the template parameters and arguments
  436. // only if this is not an explicit instantiation or specialization
  437. // with direct explicit visibility (and note that implicit
  438. // instantiations won't have a direct attribute).
  439. if (!spec->isExplicitInstantiationOrSpecialization())
  440. return true;
  441. // An explicit variable specialization is an independent, top-level
  442. // declaration. As such, if it has an explicit visibility attribute,
  443. // that must directly express the user's intent, and we should honor
  444. // it.
  445. if (spec->isExplicitSpecialization() &&
  446. hasExplicitVisibilityAlready(computation))
  447. return false;
  448. return !hasDirectVisibilityAttribute(spec, computation);
  449. }
  450. /// Merge in template-related linkage and visibility for the given
  451. /// variable template specialization. As usual, follow class template
  452. /// specialization logic up to initialization.
  453. static void mergeTemplateLV(LinkageInfo &LV,
  454. const VarTemplateSpecializationDecl *spec,
  455. LVComputationKind computation) {
  456. bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
  457. // Merge information from the template parameters, but ignore
  458. // visibility if we're only considering template arguments.
  459. VarTemplateDecl *temp = spec->getSpecializedTemplate();
  460. LinkageInfo tempLV =
  461. getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
  462. LV.mergeMaybeWithVisibility(tempLV,
  463. considerVisibility && !hasExplicitVisibilityAlready(computation));
  464. // Merge information from the template arguments. We ignore
  465. // template-argument visibility if we've got an explicit
  466. // instantiation with a visibility attribute.
  467. const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
  468. LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
  469. if (considerVisibility)
  470. LV.mergeVisibility(argsLV);
  471. LV.mergeExternalVisibility(argsLV);
  472. }
  473. static bool useInlineVisibilityHidden(const NamedDecl *D) {
  474. #if 1 // HLSL Change Starts
  475. return false;
  476. #else
  477. // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
  478. const LangOptions &Opts = D->getASTContext().getLangOpts();
  479. if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
  480. return false;
  481. const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
  482. if (!FD)
  483. return false;
  484. TemplateSpecializationKind TSK = TSK_Undeclared;
  485. if (FunctionTemplateSpecializationInfo *spec
  486. = FD->getTemplateSpecializationInfo()) {
  487. TSK = spec->getTemplateSpecializationKind();
  488. } else if (MemberSpecializationInfo *MSI =
  489. FD->getMemberSpecializationInfo()) {
  490. TSK = MSI->getTemplateSpecializationKind();
  491. }
  492. const FunctionDecl *Def = nullptr;
  493. // InlineVisibilityHidden only applies to definitions, and
  494. // isInlined() only gives meaningful answers on definitions
  495. // anyway.
  496. return TSK != TSK_ExplicitInstantiationDeclaration &&
  497. TSK != TSK_ExplicitInstantiationDefinition &&
  498. FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
  499. #endif // HLSL Change Ends
  500. }
  501. template <typename T> static bool isFirstInExternCContext(T *D) {
  502. const T *First = D->getFirstDecl();
  503. return First->isInExternCContext();
  504. }
  505. static bool isSingleLineLanguageLinkage(const Decl &D) {
  506. if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
  507. if (!SD->hasBraces())
  508. return true;
  509. return false;
  510. }
  511. static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
  512. LVComputationKind computation) {
  513. assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
  514. "Not a name having namespace scope");
  515. ASTContext &Context = D->getASTContext();
  516. // C++ [basic.link]p3:
  517. // A name having namespace scope (3.3.6) has internal linkage if it
  518. // is the name of
  519. // - an object, reference, function or function template that is
  520. // explicitly declared static; or,
  521. // (This bullet corresponds to C99 6.2.2p3.)
  522. if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
  523. // Explicitly declared static.
  524. if (Var->getStorageClass() == SC_Static)
  525. return LinkageInfo::internal();
  526. // - a non-volatile object or reference that is explicitly declared const
  527. // or constexpr and neither explicitly declared extern nor previously
  528. // declared to have external linkage; or (there is no equivalent in C99)
  529. if (Context.getLangOpts().CPlusPlus &&
  530. Var->getType().isConstQualified() &&
  531. !Context.getLangOpts().HLSL && // HLSL Change -Initializer used on a global 'const' variable will be ignored for hlsl.
  532. !Var->getType().isVolatileQualified()) {
  533. const VarDecl *PrevVar = Var->getPreviousDecl();
  534. if (PrevVar)
  535. return getLVForDecl(PrevVar, computation);
  536. if (Var->getStorageClass() != SC_Extern &&
  537. Var->getStorageClass() != SC_PrivateExtern &&
  538. !isSingleLineLanguageLinkage(*Var))
  539. return LinkageInfo::internal();
  540. }
  541. for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
  542. PrevVar = PrevVar->getPreviousDecl()) {
  543. if (PrevVar->getStorageClass() == SC_PrivateExtern &&
  544. Var->getStorageClass() == SC_None)
  545. return PrevVar->getLinkageAndVisibility();
  546. // Explicitly declared static.
  547. if (PrevVar->getStorageClass() == SC_Static)
  548. return LinkageInfo::internal();
  549. }
  550. } else if (const FunctionDecl *Function = D->getAsFunction()) {
  551. // C++ [temp]p4:
  552. // A non-member function template can have internal linkage; any
  553. // other template name shall have external linkage.
  554. // Explicitly declared static.
  555. if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
  556. return LinkageInfo(InternalLinkage, DefaultVisibility, false);
  557. } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
  558. // - a data member of an anonymous union.
  559. const VarDecl *VD = IFD->getVarDecl();
  560. assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
  561. return getLVForNamespaceScopeDecl(VD, computation);
  562. }
  563. assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
  564. if (D->isInAnonymousNamespace()) {
  565. const VarDecl *Var = dyn_cast<VarDecl>(D);
  566. const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
  567. if ((!Var || !isFirstInExternCContext(Var)) &&
  568. (!Func || !isFirstInExternCContext(Func)))
  569. return LinkageInfo::uniqueExternal();
  570. }
  571. // Set up the defaults.
  572. // C99 6.2.2p5:
  573. // If the declaration of an identifier for an object has file
  574. // scope and no storage-class specifier, its linkage is
  575. // external.
  576. LinkageInfo LV;
  577. if (!hasExplicitVisibilityAlready(computation)) {
  578. if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
  579. LV.mergeVisibility(*Vis, true);
  580. } else {
  581. // If we're declared in a namespace with a visibility attribute,
  582. // use that namespace's visibility, and it still counts as explicit.
  583. for (const DeclContext *DC = D->getDeclContext();
  584. !isa<TranslationUnitDecl>(DC);
  585. DC = DC->getParent()) {
  586. const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
  587. if (!ND) continue;
  588. if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
  589. LV.mergeVisibility(*Vis, true);
  590. break;
  591. }
  592. }
  593. }
  594. // Add in global settings if the above didn't give us direct visibility.
  595. if (!LV.isVisibilityExplicit()) {
  596. // Use global type/value visibility as appropriate.
  597. Visibility globalVisibility;
  598. if (computation == LVForValue) {
  599. globalVisibility = Context.getLangOpts().getValueVisibilityMode();
  600. } else {
  601. assert(computation == LVForType);
  602. globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
  603. }
  604. LV.mergeVisibility(globalVisibility, /*explicit*/ false);
  605. // If we're paying attention to global visibility, apply
  606. // -finline-visibility-hidden if this is an inline method.
  607. if (useInlineVisibilityHidden(D))
  608. LV.mergeVisibility(HiddenVisibility, true);
  609. }
  610. }
  611. // C++ [basic.link]p4:
  612. // A name having namespace scope has external linkage if it is the
  613. // name of
  614. //
  615. // - an object or reference, unless it has internal linkage; or
  616. if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
  617. // GCC applies the following optimization to variables and static
  618. // data members, but not to functions:
  619. //
  620. // Modify the variable's LV by the LV of its type unless this is
  621. // C or extern "C". This follows from [basic.link]p9:
  622. // A type without linkage shall not be used as the type of a
  623. // variable or function with external linkage unless
  624. // - the entity has C language linkage, or
  625. // - the entity is declared within an unnamed namespace, or
  626. // - the entity is not used or is defined in the same
  627. // translation unit.
  628. // and [basic.link]p10:
  629. // ...the types specified by all declarations referring to a
  630. // given variable or function shall be identical...
  631. // C does not have an equivalent rule.
  632. //
  633. // Ignore this if we've got an explicit attribute; the user
  634. // probably knows what they're doing.
  635. //
  636. // Note that we don't want to make the variable non-external
  637. // because of this, but unique-external linkage suits us.
  638. if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
  639. LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
  640. if (TypeLV.getLinkage() != ExternalLinkage)
  641. return LinkageInfo::uniqueExternal();
  642. if (!LV.isVisibilityExplicit())
  643. LV.mergeVisibility(TypeLV);
  644. }
  645. if (Var->getStorageClass() == SC_PrivateExtern)
  646. LV.mergeVisibility(HiddenVisibility, true);
  647. // Note that Sema::MergeVarDecl already takes care of implementing
  648. // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
  649. // to do it here.
  650. // As per function and class template specializations (below),
  651. // consider LV for the template and template arguments. We're at file
  652. // scope, so we do not need to worry about nested specializations.
  653. if (const VarTemplateSpecializationDecl *spec
  654. = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
  655. mergeTemplateLV(LV, spec, computation);
  656. }
  657. // - a function, unless it has internal linkage; or
  658. } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
  659. // In theory, we can modify the function's LV by the LV of its
  660. // type unless it has C linkage (see comment above about variables
  661. // for justification). In practice, GCC doesn't do this, so it's
  662. // just too painful to make work.
  663. if (Function->getStorageClass() == SC_PrivateExtern)
  664. LV.mergeVisibility(HiddenVisibility, true);
  665. // Note that Sema::MergeCompatibleFunctionDecls already takes care of
  666. // merging storage classes and visibility attributes, so we don't have to
  667. // look at previous decls in here.
  668. // In C++, then if the type of the function uses a type with
  669. // unique-external linkage, it's not legally usable from outside
  670. // this translation unit. However, we should use the C linkage
  671. // rules instead for extern "C" declarations.
  672. if (Context.getLangOpts().CPlusPlus &&
  673. !Function->isInExternCContext()) {
  674. // Only look at the type-as-written. If this function has an auto-deduced
  675. // return type, we can't compute the linkage of that type because it could
  676. // require looking at the linkage of this function, and we don't need this
  677. // for correctness because the type is not part of the function's
  678. // signature.
  679. // FIXME: This is a hack. We should be able to solve this circularity and
  680. // the one in getLVForClassMember for Functions some other way.
  681. QualType TypeAsWritten = Function->getType();
  682. if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
  683. TypeAsWritten = TSI->getType();
  684. if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
  685. return LinkageInfo::uniqueExternal();
  686. }
  687. // Consider LV from the template and the template arguments.
  688. // We're at file scope, so we do not need to worry about nested
  689. // specializations.
  690. if (FunctionTemplateSpecializationInfo *specInfo
  691. = Function->getTemplateSpecializationInfo()) {
  692. mergeTemplateLV(LV, Function, specInfo, computation);
  693. }
  694. // - a named class (Clause 9), or an unnamed class defined in a
  695. // typedef declaration in which the class has the typedef name
  696. // for linkage purposes (7.1.3); or
  697. // - a named enumeration (7.2), or an unnamed enumeration
  698. // defined in a typedef declaration in which the enumeration
  699. // has the typedef name for linkage purposes (7.1.3); or
  700. } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
  701. // Unnamed tags have no linkage.
  702. if (!Tag->hasNameForLinkage())
  703. return LinkageInfo::none();
  704. // If this is a class template specialization, consider the
  705. // linkage of the template and template arguments. We're at file
  706. // scope, so we do not need to worry about nested specializations.
  707. if (const ClassTemplateSpecializationDecl *spec
  708. = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
  709. mergeTemplateLV(LV, spec, computation);
  710. }
  711. // - an enumerator belonging to an enumeration with external linkage;
  712. } else if (isa<EnumConstantDecl>(D)) {
  713. LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
  714. computation);
  715. if (!isExternalFormalLinkage(EnumLV.getLinkage()))
  716. return LinkageInfo::none();
  717. LV.merge(EnumLV);
  718. // - a template, unless it is a function template that has
  719. // internal linkage (Clause 14);
  720. } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
  721. bool considerVisibility = !hasExplicitVisibilityAlready(computation);
  722. LinkageInfo tempLV =
  723. getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
  724. LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
  725. // - a namespace (7.3), unless it is declared within an unnamed
  726. // namespace.
  727. } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
  728. return LV;
  729. // By extension, we assign external linkage to Objective-C
  730. // interfaces.
  731. } else if (isa<ObjCInterfaceDecl>(D)) {
  732. // fallout
  733. // Everything not covered here has no linkage.
  734. } else {
  735. // FIXME: A typedef declaration has linkage if it gives a type a name for
  736. // linkage purposes.
  737. return LinkageInfo::none();
  738. }
  739. // If we ended up with non-external linkage, visibility should
  740. // always be default.
  741. if (LV.getLinkage() != ExternalLinkage)
  742. return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
  743. return LV;
  744. }
  745. static LinkageInfo getLVForClassMember(const NamedDecl *D,
  746. LVComputationKind computation) {
  747. // Only certain class members have linkage. Note that fields don't
  748. // really have linkage, but it's convenient to say they do for the
  749. // purposes of calculating linkage of pointer-to-data-member
  750. // template arguments.
  751. //
  752. // Templates also don't officially have linkage, but since we ignore
  753. // the C++ standard and look at template arguments when determining
  754. // linkage and visibility of a template specialization, we might hit
  755. // a template template argument that way. If we do, we need to
  756. // consider its linkage.
  757. if (!(isa<CXXMethodDecl>(D) ||
  758. isa<VarDecl>(D) ||
  759. isa<FieldDecl>(D) ||
  760. isa<IndirectFieldDecl>(D) ||
  761. isa<TagDecl>(D) ||
  762. isa<TemplateDecl>(D)))
  763. return LinkageInfo::none();
  764. LinkageInfo LV;
  765. // If we have an explicit visibility attribute, merge that in.
  766. if (!hasExplicitVisibilityAlready(computation)) {
  767. if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
  768. LV.mergeVisibility(*Vis, true);
  769. // If we're paying attention to global visibility, apply
  770. // -finline-visibility-hidden if this is an inline method.
  771. //
  772. // Note that we do this before merging information about
  773. // the class visibility.
  774. if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
  775. LV.mergeVisibility(HiddenVisibility, true);
  776. }
  777. // If this class member has an explicit visibility attribute, the only
  778. // thing that can change its visibility is the template arguments, so
  779. // only look for them when processing the class.
  780. LVComputationKind classComputation = computation;
  781. if (LV.isVisibilityExplicit())
  782. classComputation = withExplicitVisibilityAlready(computation);
  783. LinkageInfo classLV =
  784. getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
  785. // If the class already has unique-external linkage, we can't improve.
  786. if (classLV.getLinkage() == UniqueExternalLinkage)
  787. return LinkageInfo::uniqueExternal();
  788. if (!isExternallyVisible(classLV.getLinkage()))
  789. return LinkageInfo::none();
  790. // Otherwise, don't merge in classLV yet, because in certain cases
  791. // we need to completely ignore the visibility from it.
  792. // Specifically, if this decl exists and has an explicit attribute.
  793. const NamedDecl *explicitSpecSuppressor = nullptr;
  794. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  795. // If the type of the function uses a type with unique-external
  796. // linkage, it's not legally usable from outside this translation unit.
  797. // But only look at the type-as-written. If this function has an
  798. // auto-deduced return type, we can't compute the linkage of that type
  799. // because it could require looking at the linkage of this function, and we
  800. // don't need this for correctness because the type is not part of the
  801. // function's signature.
  802. // FIXME: This is a hack. We should be able to solve this circularity and
  803. // the one in getLVForNamespaceScopeDecl for Functions some other way.
  804. {
  805. QualType TypeAsWritten = MD->getType();
  806. if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
  807. TypeAsWritten = TSI->getType();
  808. if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
  809. return LinkageInfo::uniqueExternal();
  810. }
  811. // If this is a method template specialization, use the linkage for
  812. // the template parameters and arguments.
  813. if (FunctionTemplateSpecializationInfo *spec
  814. = MD->getTemplateSpecializationInfo()) {
  815. mergeTemplateLV(LV, MD, spec, computation);
  816. if (spec->isExplicitSpecialization()) {
  817. explicitSpecSuppressor = MD;
  818. } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
  819. explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
  820. }
  821. } else if (isExplicitMemberSpecialization(MD)) {
  822. explicitSpecSuppressor = MD;
  823. }
  824. } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
  825. if (const ClassTemplateSpecializationDecl *spec
  826. = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
  827. mergeTemplateLV(LV, spec, computation);
  828. if (spec->isExplicitSpecialization()) {
  829. explicitSpecSuppressor = spec;
  830. } else {
  831. const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
  832. if (isExplicitMemberSpecialization(temp)) {
  833. explicitSpecSuppressor = temp->getTemplatedDecl();
  834. }
  835. }
  836. } else if (isExplicitMemberSpecialization(RD)) {
  837. explicitSpecSuppressor = RD;
  838. }
  839. // Static data members.
  840. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  841. // HLSL Change: Make static data member internal linkage. This is to avoid confusion between global constant buffer
  842. if (VD->getStorageClass() == StorageClass::SC_Static)
  843. LV.setLinkage(Linkage::InternalLinkage);
  844. if (const VarTemplateSpecializationDecl *spec
  845. = dyn_cast<VarTemplateSpecializationDecl>(VD))
  846. mergeTemplateLV(LV, spec, computation);
  847. // Modify the variable's linkage by its type, but ignore the
  848. // type's visibility unless it's a definition.
  849. LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
  850. if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
  851. LV.mergeVisibility(typeLV);
  852. LV.mergeExternalVisibility(typeLV);
  853. if (isExplicitMemberSpecialization(VD)) {
  854. explicitSpecSuppressor = VD;
  855. }
  856. // Template members.
  857. } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
  858. bool considerVisibility =
  859. (!LV.isVisibilityExplicit() &&
  860. !classLV.isVisibilityExplicit() &&
  861. !hasExplicitVisibilityAlready(computation));
  862. LinkageInfo tempLV =
  863. getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
  864. LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
  865. if (const RedeclarableTemplateDecl *redeclTemp =
  866. dyn_cast<RedeclarableTemplateDecl>(temp)) {
  867. if (isExplicitMemberSpecialization(redeclTemp)) {
  868. explicitSpecSuppressor = temp->getTemplatedDecl();
  869. }
  870. }
  871. }
  872. // We should never be looking for an attribute directly on a template.
  873. assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
  874. // If this member is an explicit member specialization, and it has
  875. // an explicit attribute, ignore visibility from the parent.
  876. bool considerClassVisibility = true;
  877. if (explicitSpecSuppressor &&
  878. // optimization: hasDVA() is true only with explicit visibility.
  879. LV.isVisibilityExplicit() &&
  880. classLV.getVisibility() != DefaultVisibility &&
  881. hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
  882. considerClassVisibility = false;
  883. }
  884. // Finally, merge in information from the class.
  885. LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
  886. return LV;
  887. }
  888. void NamedDecl::anchor() { }
  889. static LinkageInfo computeLVForDecl(const NamedDecl *D,
  890. LVComputationKind computation);
  891. bool NamedDecl::isLinkageValid() const {
  892. if (!hasCachedLinkage())
  893. return true;
  894. return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
  895. getCachedLinkage();
  896. }
  897. ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
  898. StringRef name = getName();
  899. if (name.empty()) return SFF_None;
  900. if (name.front() == 'C')
  901. if (name == "CFStringCreateWithFormat" ||
  902. name == "CFStringCreateWithFormatAndArguments" ||
  903. name == "CFStringAppendFormat" ||
  904. name == "CFStringAppendFormatAndArguments")
  905. return SFF_CFString;
  906. return SFF_None;
  907. }
  908. Linkage NamedDecl::getLinkageInternal() const {
  909. // We don't care about visibility here, so ask for the cheapest
  910. // possible visibility analysis.
  911. return getLVForDecl(this, LVForLinkageOnly).getLinkage();
  912. }
  913. LinkageInfo NamedDecl::getLinkageAndVisibility() const {
  914. LVComputationKind computation =
  915. (usesTypeVisibility(this) ? LVForType : LVForValue);
  916. return getLVForDecl(this, computation);
  917. }
  918. static Optional<Visibility>
  919. getExplicitVisibilityAux(const NamedDecl *ND,
  920. NamedDecl::ExplicitVisibilityKind kind,
  921. bool IsMostRecent) {
  922. assert(!IsMostRecent || ND == ND->getMostRecentDecl());
  923. // Check the declaration itself first.
  924. if (Optional<Visibility> V = getVisibilityOf(ND, kind))
  925. return V;
  926. // If this is a member class of a specialization of a class template
  927. // and the corresponding decl has explicit visibility, use that.
  928. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND)) {
  929. CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
  930. if (InstantiatedFrom)
  931. return getVisibilityOf(InstantiatedFrom, kind);
  932. }
  933. // If there wasn't explicit visibility there, and this is a
  934. // specialization of a class template, check for visibility
  935. // on the pattern.
  936. if (const ClassTemplateSpecializationDecl *spec
  937. = dyn_cast<ClassTemplateSpecializationDecl>(ND))
  938. return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
  939. kind);
  940. // Use the most recent declaration.
  941. if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
  942. const NamedDecl *MostRecent = ND->getMostRecentDecl();
  943. if (MostRecent != ND)
  944. return getExplicitVisibilityAux(MostRecent, kind, true);
  945. }
  946. if (const VarDecl *Var = dyn_cast<VarDecl>(ND)) {
  947. if (Var->isStaticDataMember()) {
  948. VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
  949. if (InstantiatedFrom)
  950. return getVisibilityOf(InstantiatedFrom, kind);
  951. }
  952. if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
  953. return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
  954. kind);
  955. return None;
  956. }
  957. // Also handle function template specializations.
  958. if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) {
  959. // If the function is a specialization of a template with an
  960. // explicit visibility attribute, use that.
  961. if (FunctionTemplateSpecializationInfo *templateInfo
  962. = fn->getTemplateSpecializationInfo())
  963. return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
  964. kind);
  965. // If the function is a member of a specialization of a class template
  966. // and the corresponding decl has explicit visibility, use that.
  967. FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
  968. if (InstantiatedFrom)
  969. return getVisibilityOf(InstantiatedFrom, kind);
  970. return None;
  971. }
  972. // The visibility of a template is stored in the templated decl.
  973. if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND))
  974. return getVisibilityOf(TD->getTemplatedDecl(), kind);
  975. return None;
  976. }
  977. Optional<Visibility>
  978. NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
  979. return getExplicitVisibilityAux(this, kind, false);
  980. }
  981. static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
  982. LVComputationKind computation) {
  983. // This lambda has its linkage/visibility determined by its owner.
  984. if (ContextDecl) {
  985. if (isa<ParmVarDecl>(ContextDecl))
  986. DC = ContextDecl->getDeclContext()->getRedeclContext();
  987. else
  988. return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
  989. }
  990. if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
  991. return getLVForDecl(ND, computation);
  992. return LinkageInfo::external();
  993. }
  994. static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
  995. LVComputationKind computation) {
  996. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
  997. if (Function->isInAnonymousNamespace() &&
  998. !Function->isInExternCContext())
  999. return LinkageInfo::uniqueExternal();
  1000. // This is a "void f();" which got merged with a file static.
  1001. if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
  1002. return LinkageInfo::internal();
  1003. LinkageInfo LV;
  1004. if (!hasExplicitVisibilityAlready(computation)) {
  1005. if (Optional<Visibility> Vis =
  1006. getExplicitVisibility(Function, computation))
  1007. LV.mergeVisibility(*Vis, true);
  1008. }
  1009. // Note that Sema::MergeCompatibleFunctionDecls already takes care of
  1010. // merging storage classes and visibility attributes, so we don't have to
  1011. // look at previous decls in here.
  1012. return LV;
  1013. }
  1014. if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
  1015. if (Var->hasExternalStorage()) {
  1016. if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
  1017. return LinkageInfo::uniqueExternal();
  1018. LinkageInfo LV;
  1019. if (Var->getStorageClass() == SC_PrivateExtern)
  1020. LV.mergeVisibility(HiddenVisibility, true);
  1021. else if (!hasExplicitVisibilityAlready(computation)) {
  1022. if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
  1023. LV.mergeVisibility(*Vis, true);
  1024. }
  1025. if (const VarDecl *Prev = Var->getPreviousDecl()) {
  1026. LinkageInfo PrevLV = getLVForDecl(Prev, computation);
  1027. if (PrevLV.getLinkage())
  1028. LV.setLinkage(PrevLV.getLinkage());
  1029. LV.mergeVisibility(PrevLV);
  1030. }
  1031. return LV;
  1032. }
  1033. if (!Var->isStaticLocal())
  1034. return LinkageInfo::none();
  1035. }
  1036. ASTContext &Context = D->getASTContext();
  1037. if (!Context.getLangOpts().CPlusPlus)
  1038. return LinkageInfo::none();
  1039. const Decl *OuterD = getOutermostFuncOrBlockContext(D);
  1040. if (!OuterD)
  1041. return LinkageInfo::none();
  1042. LinkageInfo LV;
  1043. if (const BlockDecl *BD = dyn_cast<BlockDecl>(OuterD)) {
  1044. if (!BD->getBlockManglingNumber())
  1045. return LinkageInfo::none();
  1046. LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
  1047. BD->getBlockManglingContextDecl(), computation);
  1048. } else {
  1049. const FunctionDecl *FD = cast<FunctionDecl>(OuterD);
  1050. if (!FD->isInlined() &&
  1051. !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
  1052. return LinkageInfo::none();
  1053. LV = getLVForDecl(FD, computation);
  1054. }
  1055. if (!isExternallyVisible(LV.getLinkage()))
  1056. return LinkageInfo::none();
  1057. return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
  1058. LV.isVisibilityExplicit());
  1059. }
  1060. static inline const CXXRecordDecl*
  1061. getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
  1062. const CXXRecordDecl *Ret = Record;
  1063. while (Record && Record->isLambda()) {
  1064. Ret = Record;
  1065. if (!Record->getParent()) break;
  1066. // Get the Containing Class of this Lambda Class
  1067. Record = dyn_cast_or_null<CXXRecordDecl>(
  1068. Record->getParent()->getParent());
  1069. }
  1070. return Ret;
  1071. }
  1072. static LinkageInfo computeLVForDecl(const NamedDecl *D,
  1073. LVComputationKind computation) {
  1074. // Objective-C: treat all Objective-C declarations as having external
  1075. // linkage.
  1076. switch (D->getKind()) {
  1077. default:
  1078. break;
  1079. case Decl::ParmVar:
  1080. return LinkageInfo::none();
  1081. case Decl::TemplateTemplateParm: // count these as external
  1082. case Decl::NonTypeTemplateParm:
  1083. case Decl::ObjCAtDefsField:
  1084. case Decl::ObjCCategory:
  1085. case Decl::ObjCCategoryImpl:
  1086. case Decl::ObjCCompatibleAlias:
  1087. case Decl::ObjCImplementation:
  1088. case Decl::ObjCMethod:
  1089. case Decl::ObjCProperty:
  1090. case Decl::ObjCPropertyImpl:
  1091. case Decl::ObjCProtocol:
  1092. return LinkageInfo::external();
  1093. case Decl::CXXRecord: {
  1094. const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
  1095. if (Record->isLambda()) {
  1096. if (!Record->getLambdaManglingNumber()) {
  1097. // This lambda has no mangling number, so it's internal.
  1098. return LinkageInfo::internal();
  1099. }
  1100. // This lambda has its linkage/visibility determined:
  1101. // - either by the outermost lambda if that lambda has no mangling
  1102. // number.
  1103. // - or by the parent of the outer most lambda
  1104. // This prevents infinite recursion in settings such as nested lambdas
  1105. // used in NSDMI's, for e.g.
  1106. // struct L {
  1107. // int t{};
  1108. // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
  1109. // };
  1110. const CXXRecordDecl *OuterMostLambda =
  1111. getOutermostEnclosingLambda(Record);
  1112. if (!OuterMostLambda->getLambdaManglingNumber())
  1113. return LinkageInfo::internal();
  1114. return getLVForClosure(
  1115. OuterMostLambda->getDeclContext()->getRedeclContext(),
  1116. OuterMostLambda->getLambdaContextDecl(), computation);
  1117. }
  1118. break;
  1119. }
  1120. }
  1121. // Handle linkage for namespace-scope names.
  1122. if (D->getDeclContext()->getRedeclContext()->isFileContext())
  1123. return getLVForNamespaceScopeDecl(D, computation);
  1124. // C++ [basic.link]p5:
  1125. // In addition, a member function, static data member, a named
  1126. // class or enumeration of class scope, or an unnamed class or
  1127. // enumeration defined in a class-scope typedef declaration such
  1128. // that the class or enumeration has the typedef name for linkage
  1129. // purposes (7.1.3), has external linkage if the name of the class
  1130. // has external linkage.
  1131. if (D->getDeclContext()->isRecord())
  1132. return getLVForClassMember(D, computation);
  1133. // C++ [basic.link]p6:
  1134. // The name of a function declared in block scope and the name of
  1135. // an object declared by a block scope extern declaration have
  1136. // linkage. If there is a visible declaration of an entity with
  1137. // linkage having the same name and type, ignoring entities
  1138. // declared outside the innermost enclosing namespace scope, the
  1139. // block scope declaration declares that same entity and receives
  1140. // the linkage of the previous declaration. If there is more than
  1141. // one such matching entity, the program is ill-formed. Otherwise,
  1142. // if no matching entity is found, the block scope entity receives
  1143. // external linkage.
  1144. if (D->getDeclContext()->isFunctionOrMethod())
  1145. return getLVForLocalDecl(D, computation);
  1146. // C++ [basic.link]p6:
  1147. // Names not covered by these rules have no linkage.
  1148. return LinkageInfo::none();
  1149. }
  1150. namespace clang {
  1151. class LinkageComputer {
  1152. public:
  1153. static LinkageInfo getLVForDecl(const NamedDecl *D,
  1154. LVComputationKind computation) {
  1155. if (computation == LVForLinkageOnly && D->hasCachedLinkage())
  1156. return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
  1157. LinkageInfo LV = computeLVForDecl(D, computation);
  1158. if (D->hasCachedLinkage())
  1159. assert(D->getCachedLinkage() == LV.getLinkage());
  1160. D->setCachedLinkage(LV.getLinkage());
  1161. #ifndef NDEBUG
  1162. // In C (because of gnu inline) and in c++ with microsoft extensions an
  1163. // static can follow an extern, so we can have two decls with different
  1164. // linkages.
  1165. const LangOptions &Opts = D->getASTContext().getLangOpts();
  1166. (Opts); // HLSL Change - this only has static consts referenced
  1167. if (!Opts.CPlusPlus || Opts.MicrosoftExt)
  1168. return LV;
  1169. // We have just computed the linkage for this decl. By induction we know
  1170. // that all other computed linkages match, check that the one we just
  1171. // computed also does.
  1172. NamedDecl *Old = nullptr;
  1173. for (auto I : D->redecls()) {
  1174. NamedDecl *T = cast<NamedDecl>(I);
  1175. if (T == D)
  1176. continue;
  1177. if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
  1178. Old = T;
  1179. break;
  1180. }
  1181. }
  1182. assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
  1183. #endif
  1184. return LV;
  1185. }
  1186. };
  1187. }
  1188. static LinkageInfo getLVForDecl(const NamedDecl *D,
  1189. LVComputationKind computation) {
  1190. return clang::LinkageComputer::getLVForDecl(D, computation);
  1191. }
  1192. std::string NamedDecl::getQualifiedNameAsString() const {
  1193. std::string QualName;
  1194. llvm::raw_string_ostream OS(QualName);
  1195. printQualifiedName(OS, getASTContext().getPrintingPolicy());
  1196. return OS.str();
  1197. }
  1198. void NamedDecl::printQualifiedName(raw_ostream &OS) const {
  1199. printQualifiedName(OS, getASTContext().getPrintingPolicy());
  1200. }
  1201. void NamedDecl::printQualifiedName(raw_ostream &OS,
  1202. const PrintingPolicy &P) const {
  1203. const DeclContext *Ctx = getDeclContext();
  1204. if (Ctx->isFunctionOrMethod()) {
  1205. printName(OS);
  1206. return;
  1207. }
  1208. typedef SmallVector<const DeclContext *, 8> ContextsTy;
  1209. ContextsTy Contexts;
  1210. // Collect contexts.
  1211. while (Ctx && isa<NamedDecl>(Ctx)) {
  1212. Contexts.push_back(Ctx);
  1213. Ctx = Ctx->getParent();
  1214. }
  1215. for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
  1216. I != E; ++I) {
  1217. if (const ClassTemplateSpecializationDecl *Spec
  1218. = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
  1219. OS << Spec->getName();
  1220. const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
  1221. TemplateSpecializationType::PrintTemplateArgumentList(OS,
  1222. TemplateArgs.data(),
  1223. TemplateArgs.size(),
  1224. P);
  1225. } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
  1226. if (P.SuppressUnwrittenScope &&
  1227. (ND->isAnonymousNamespace() || ND->isInline()))
  1228. continue;
  1229. if (ND->isAnonymousNamespace())
  1230. OS << "(anonymous namespace)";
  1231. else
  1232. OS << *ND;
  1233. } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
  1234. if (!RD->getIdentifier())
  1235. OS << "(anonymous " << RD->getKindName() << ')';
  1236. else
  1237. OS << *RD;
  1238. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
  1239. const FunctionProtoType *FT = nullptr;
  1240. if (FD->hasWrittenPrototype())
  1241. FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
  1242. OS << *FD << '(';
  1243. if (FT) {
  1244. unsigned NumParams = FD->getNumParams();
  1245. for (unsigned i = 0; i < NumParams; ++i) {
  1246. if (i)
  1247. OS << ", ";
  1248. OS << FD->getParamDecl(i)->getType().stream(P);
  1249. }
  1250. if (FT->isVariadic()) {
  1251. if (NumParams > 0)
  1252. OS << ", ";
  1253. OS << "...";
  1254. }
  1255. }
  1256. OS << ')';
  1257. } else {
  1258. OS << *cast<NamedDecl>(*I);
  1259. }
  1260. OS << "::";
  1261. }
  1262. if (getDeclName())
  1263. OS << *this;
  1264. else
  1265. OS << "(anonymous)";
  1266. }
  1267. void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
  1268. const PrintingPolicy &Policy,
  1269. bool Qualified) const {
  1270. if (Qualified)
  1271. printQualifiedName(OS, Policy);
  1272. else
  1273. printName(OS);
  1274. }
  1275. static bool isKindReplaceableBy(Decl::Kind OldK, Decl::Kind NewK) {
  1276. // For method declarations, we never replace.
  1277. if (ObjCMethodDecl::classofKind(NewK))
  1278. return false;
  1279. if (OldK == NewK)
  1280. return true;
  1281. // A compatibility alias for a class can be replaced by an interface.
  1282. if (ObjCCompatibleAliasDecl::classofKind(OldK) &&
  1283. ObjCInterfaceDecl::classofKind(NewK))
  1284. return true;
  1285. // A typedef-declaration, alias-declaration, or Objective-C class declaration
  1286. // can replace another declaration of the same type. Semantic analysis checks
  1287. // that we have matching types.
  1288. if ((TypedefNameDecl::classofKind(OldK) ||
  1289. ObjCInterfaceDecl::classofKind(OldK)) &&
  1290. (TypedefNameDecl::classofKind(NewK) ||
  1291. ObjCInterfaceDecl::classofKind(NewK)))
  1292. return true;
  1293. // Otherwise, a kind mismatch implies that the declaration is not replaced.
  1294. return false;
  1295. }
  1296. template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
  1297. return true;
  1298. }
  1299. static bool isRedeclarableImpl(...) { return false; }
  1300. static bool isRedeclarable(Decl::Kind K) {
  1301. switch (K) {
  1302. #define DECL(Type, Base) \
  1303. case Decl::Type: \
  1304. return isRedeclarableImpl((Type##Decl *)nullptr);
  1305. #define ABSTRACT_DECL(DECL)
  1306. #include "clang/AST/DeclNodes.inc"
  1307. }
  1308. llvm_unreachable("unknown decl kind");
  1309. }
  1310. bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
  1311. assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
  1312. // Never replace one imported declaration with another; we need both results
  1313. // when re-exporting.
  1314. if (OldD->isFromASTFile() && isFromASTFile())
  1315. return false;
  1316. if (!isKindReplaceableBy(OldD->getKind(), getKind()))
  1317. return false;
  1318. // Inline namespaces can give us two declarations with the same
  1319. // name and kind in the same scope but different contexts; we should
  1320. // keep both declarations in this case.
  1321. if (!this->getDeclContext()->getRedeclContext()->Equals(
  1322. OldD->getDeclContext()->getRedeclContext()))
  1323. return false;
  1324. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
  1325. // For function declarations, we keep track of redeclarations.
  1326. // FIXME: This returns false for functions that should in fact be replaced.
  1327. // Instead, perform some kind of type check?
  1328. if (FD->getPreviousDecl() != OldD)
  1329. return false;
  1330. // For function templates, the underlying function declarations are linked.
  1331. if (const FunctionTemplateDecl *FunctionTemplate =
  1332. dyn_cast<FunctionTemplateDecl>(this))
  1333. return FunctionTemplate->getTemplatedDecl()->declarationReplaces(
  1334. cast<FunctionTemplateDecl>(OldD)->getTemplatedDecl());
  1335. // Using shadow declarations can be overloaded on their target declarations
  1336. // if they introduce functions.
  1337. // FIXME: If our target replaces the old target, can we replace the old
  1338. // shadow declaration?
  1339. if (auto *USD = dyn_cast<UsingShadowDecl>(this))
  1340. if (USD->getTargetDecl() != cast<UsingShadowDecl>(OldD)->getTargetDecl())
  1341. return false;
  1342. // Using declarations can be overloaded if they introduce functions.
  1343. if (auto *UD = dyn_cast<UsingDecl>(this)) {
  1344. ASTContext &Context = getASTContext();
  1345. return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
  1346. Context.getCanonicalNestedNameSpecifier(
  1347. cast<UsingDecl>(OldD)->getQualifier());
  1348. }
  1349. if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
  1350. ASTContext &Context = getASTContext();
  1351. return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
  1352. Context.getCanonicalNestedNameSpecifier(
  1353. cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
  1354. }
  1355. // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
  1356. // We want to keep it, unless it nominates same namespace.
  1357. if (auto *UD = dyn_cast<UsingDirectiveDecl>(this))
  1358. return UD->getNominatedNamespace()->getOriginalNamespace() ==
  1359. cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
  1360. ->getOriginalNamespace();
  1361. if (!IsKnownNewer && isRedeclarable(getKind())) {
  1362. // Check whether this is actually newer than OldD. We want to keep the
  1363. // newer declaration. This loop will usually only iterate once, because
  1364. // OldD is usually the previous declaration.
  1365. for (auto D : redecls()) {
  1366. if (D == OldD)
  1367. break;
  1368. // If we reach the canonical declaration, then OldD is not actually older
  1369. // than this one.
  1370. //
  1371. // FIXME: In this case, we should not add this decl to the lookup table.
  1372. if (D->isCanonicalDecl())
  1373. return false;
  1374. }
  1375. }
  1376. // It's a newer declaration of the same kind of declaration in the same scope,
  1377. // and not an overload: we want this decl instead of the existing one.
  1378. return true;
  1379. }
  1380. bool NamedDecl::hasLinkage() const {
  1381. return getFormalLinkage() != NoLinkage;
  1382. }
  1383. NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
  1384. NamedDecl *ND = this;
  1385. while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
  1386. ND = UD->getTargetDecl();
  1387. if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
  1388. return AD->getClassInterface();
  1389. return ND;
  1390. }
  1391. bool NamedDecl::isCXXInstanceMember() const {
  1392. if (!isCXXClassMember())
  1393. return false;
  1394. const NamedDecl *D = this;
  1395. if (isa<UsingShadowDecl>(D))
  1396. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  1397. if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
  1398. return true;
  1399. if (const CXXMethodDecl *MD =
  1400. dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
  1401. return MD->isInstance();
  1402. return false;
  1403. }
  1404. //===----------------------------------------------------------------------===//
  1405. // DeclaratorDecl Implementation
  1406. //===----------------------------------------------------------------------===//
  1407. template <typename DeclT>
  1408. static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
  1409. if (decl->getNumTemplateParameterLists() > 0)
  1410. return decl->getTemplateParameterList(0)->getTemplateLoc();
  1411. else
  1412. return decl->getInnerLocStart();
  1413. }
  1414. SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
  1415. TypeSourceInfo *TSI = getTypeSourceInfo();
  1416. if (TSI) return TSI->getTypeLoc().getBeginLoc();
  1417. return SourceLocation();
  1418. }
  1419. void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
  1420. if (QualifierLoc) {
  1421. // Make sure the extended decl info is allocated.
  1422. if (!hasExtInfo()) {
  1423. // Save (non-extended) type source info pointer.
  1424. TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
  1425. // Allocate external info struct.
  1426. DeclInfo = new (getASTContext()) ExtInfo;
  1427. // Restore savedTInfo into (extended) decl info.
  1428. getExtInfo()->TInfo = savedTInfo;
  1429. }
  1430. // Set qualifier info.
  1431. getExtInfo()->QualifierLoc = QualifierLoc;
  1432. } else {
  1433. // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
  1434. if (hasExtInfo()) {
  1435. if (getExtInfo()->NumTemplParamLists == 0) {
  1436. // Save type source info pointer.
  1437. TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
  1438. // Deallocate the extended decl info.
  1439. getASTContext().Deallocate(getExtInfo());
  1440. // Restore savedTInfo into (non-extended) decl info.
  1441. DeclInfo = savedTInfo;
  1442. }
  1443. else
  1444. getExtInfo()->QualifierLoc = QualifierLoc;
  1445. }
  1446. }
  1447. }
  1448. void
  1449. DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
  1450. unsigned NumTPLists,
  1451. TemplateParameterList **TPLists) {
  1452. assert(NumTPLists > 0);
  1453. // Make sure the extended decl info is allocated.
  1454. if (!hasExtInfo()) {
  1455. // Save (non-extended) type source info pointer.
  1456. TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
  1457. // Allocate external info struct.
  1458. DeclInfo = new (getASTContext()) ExtInfo;
  1459. // Restore savedTInfo into (extended) decl info.
  1460. getExtInfo()->TInfo = savedTInfo;
  1461. }
  1462. // Set the template parameter lists info.
  1463. getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
  1464. }
  1465. SourceLocation DeclaratorDecl::getOuterLocStart() const {
  1466. return getTemplateOrInnerLocStart(this);
  1467. }
  1468. namespace {
  1469. // Helper function: returns true if QT is or contains a type
  1470. // having a postfix component.
  1471. bool typeIsPostfix(clang::QualType QT) {
  1472. while (true) {
  1473. const Type* T = QT.getTypePtr();
  1474. switch (T->getTypeClass()) {
  1475. default:
  1476. return false;
  1477. case Type::Pointer:
  1478. QT = cast<PointerType>(T)->getPointeeType();
  1479. break;
  1480. case Type::BlockPointer:
  1481. QT = cast<BlockPointerType>(T)->getPointeeType();
  1482. break;
  1483. case Type::MemberPointer:
  1484. QT = cast<MemberPointerType>(T)->getPointeeType();
  1485. break;
  1486. case Type::LValueReference:
  1487. case Type::RValueReference:
  1488. QT = cast<ReferenceType>(T)->getPointeeType();
  1489. break;
  1490. case Type::PackExpansion:
  1491. QT = cast<PackExpansionType>(T)->getPattern();
  1492. break;
  1493. case Type::Paren:
  1494. case Type::ConstantArray:
  1495. case Type::DependentSizedArray:
  1496. case Type::IncompleteArray:
  1497. case Type::VariableArray:
  1498. case Type::FunctionProto:
  1499. case Type::FunctionNoProto:
  1500. return true;
  1501. }
  1502. }
  1503. }
  1504. } // namespace
  1505. SourceRange DeclaratorDecl::getSourceRange() const {
  1506. SourceLocation RangeEnd = getLocation();
  1507. if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
  1508. // If the declaration has no name or the type extends past the name take the
  1509. // end location of the type.
  1510. if (!getDeclName() || typeIsPostfix(TInfo->getType()))
  1511. RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
  1512. }
  1513. return SourceRange(getOuterLocStart(), RangeEnd);
  1514. }
  1515. void
  1516. QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
  1517. unsigned NumTPLists,
  1518. TemplateParameterList **TPLists) {
  1519. assert((NumTPLists == 0 || TPLists != nullptr) &&
  1520. "Empty array of template parameters with positive size!");
  1521. // Free previous template parameters (if any).
  1522. if (NumTemplParamLists > 0) {
  1523. Context.Deallocate(TemplParamLists);
  1524. TemplParamLists = nullptr;
  1525. NumTemplParamLists = 0;
  1526. }
  1527. // Set info on matched template parameter lists (if any).
  1528. if (NumTPLists > 0) {
  1529. TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
  1530. NumTemplParamLists = NumTPLists;
  1531. std::copy(TPLists, TPLists + NumTPLists, TemplParamLists);
  1532. }
  1533. }
  1534. //===----------------------------------------------------------------------===//
  1535. // VarDecl Implementation
  1536. //===----------------------------------------------------------------------===//
  1537. const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
  1538. switch (SC) {
  1539. case SC_None: break;
  1540. case SC_Auto: return "auto";
  1541. case SC_Extern: return "extern";
  1542. case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
  1543. case SC_PrivateExtern: return "__private_extern__";
  1544. case SC_Register: return "register";
  1545. case SC_Static: return "static";
  1546. }
  1547. llvm_unreachable("Invalid storage class");
  1548. }
  1549. VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
  1550. SourceLocation StartLoc, SourceLocation IdLoc,
  1551. IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
  1552. StorageClass SC)
  1553. : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
  1554. redeclarable_base(C), Init() {
  1555. static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
  1556. "VarDeclBitfields too large!");
  1557. static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
  1558. "ParmVarDeclBitfields too large!");
  1559. static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
  1560. "NonParmVarDeclBitfields too large!");
  1561. AllBits = 0;
  1562. VarDeclBits.SClass = SC;
  1563. // Everything else is implicitly initialized to false.
  1564. }
  1565. VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
  1566. SourceLocation StartL, SourceLocation IdL,
  1567. IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
  1568. StorageClass S) {
  1569. return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
  1570. }
  1571. VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  1572. return new (C, ID)
  1573. VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
  1574. QualType(), nullptr, SC_None);
  1575. }
  1576. void VarDecl::setStorageClass(StorageClass SC) {
  1577. assert(isLegalForVariable(SC));
  1578. VarDeclBits.SClass = SC;
  1579. }
  1580. VarDecl::TLSKind VarDecl::getTLSKind() const {
  1581. switch (VarDeclBits.TSCSpec) {
  1582. case TSCS_unspecified:
  1583. if (!hasAttr<ThreadAttr>() &&
  1584. !(getASTContext().getLangOpts().OpenMPUseTLS &&
  1585. getASTContext().getTargetInfo().isTLSSupported() &&
  1586. hasAttr<OMPThreadPrivateDeclAttr>()))
  1587. return TLS_None;
  1588. return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
  1589. LangOptions::MSVC2015)) ||
  1590. hasAttr<OMPThreadPrivateDeclAttr>())
  1591. ? TLS_Dynamic
  1592. : TLS_Static;
  1593. case TSCS___thread: // Fall through.
  1594. case TSCS__Thread_local:
  1595. return TLS_Static;
  1596. case TSCS_thread_local:
  1597. return TLS_Dynamic;
  1598. }
  1599. llvm_unreachable("Unknown thread storage class specifier!");
  1600. }
  1601. SourceRange VarDecl::getSourceRange() const {
  1602. if (const Expr *Init = getInit()) {
  1603. SourceLocation InitEnd = Init->getLocEnd();
  1604. // If Init is implicit, ignore its source range and fallback on
  1605. // DeclaratorDecl::getSourceRange() to handle postfix elements.
  1606. if (InitEnd.isValid() && InitEnd != getLocation())
  1607. return SourceRange(getOuterLocStart(), InitEnd);
  1608. }
  1609. return DeclaratorDecl::getSourceRange();
  1610. }
  1611. template<typename T>
  1612. static LanguageLinkage getDeclLanguageLinkage(const T &D) {
  1613. // C++ [dcl.link]p1: All function types, function names with external linkage,
  1614. // and variable names with external linkage have a language linkage.
  1615. if (!D.hasExternalFormalLinkage())
  1616. return NoLanguageLinkage;
  1617. // Language linkage is a C++ concept, but saying that everything else in C has
  1618. // C language linkage fits the implementation nicely.
  1619. ASTContext &Context = D.getASTContext();
  1620. if (!Context.getLangOpts().CPlusPlus)
  1621. return CLanguageLinkage;
  1622. // C++ [dcl.link]p4: A C language linkage is ignored in determining the
  1623. // language linkage of the names of class members and the function type of
  1624. // class member functions.
  1625. const DeclContext *DC = D.getDeclContext();
  1626. if (DC->isRecord())
  1627. return CXXLanguageLinkage;
  1628. // If the first decl is in an extern "C" context, any other redeclaration
  1629. // will have C language linkage. If the first one is not in an extern "C"
  1630. // context, we would have reported an error for any other decl being in one.
  1631. if (isFirstInExternCContext(&D))
  1632. return CLanguageLinkage;
  1633. return CXXLanguageLinkage;
  1634. }
  1635. template<typename T>
  1636. static bool isDeclExternC(const T &D) {
  1637. // Since the context is ignored for class members, they can only have C++
  1638. // language linkage or no language linkage.
  1639. const DeclContext *DC = D.getDeclContext();
  1640. if (DC->isRecord()) {
  1641. assert(D.getASTContext().getLangOpts().CPlusPlus);
  1642. return false;
  1643. }
  1644. return D.getLanguageLinkage() == CLanguageLinkage;
  1645. }
  1646. LanguageLinkage VarDecl::getLanguageLinkage() const {
  1647. return getDeclLanguageLinkage(*this);
  1648. }
  1649. bool VarDecl::isExternC() const {
  1650. return isDeclExternC(*this);
  1651. }
  1652. bool VarDecl::isInExternCContext() const {
  1653. return getLexicalDeclContext()->isExternCContext();
  1654. }
  1655. bool VarDecl::isInExternCXXContext() const {
  1656. return getLexicalDeclContext()->isExternCXXContext();
  1657. }
  1658. VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
  1659. VarDecl::DefinitionKind
  1660. VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
  1661. // C++ [basic.def]p2:
  1662. // A declaration is a definition unless [...] it contains the 'extern'
  1663. // specifier or a linkage-specification and neither an initializer [...],
  1664. // it declares a static data member in a class declaration [...].
  1665. // C++1y [temp.expl.spec]p15:
  1666. // An explicit specialization of a static data member or an explicit
  1667. // specialization of a static data member template is a definition if the
  1668. // declaration includes an initializer; otherwise, it is a declaration.
  1669. //
  1670. // FIXME: How do you declare (but not define) a partial specialization of
  1671. // a static data member template outside the containing class?
  1672. if (isStaticDataMember()) {
  1673. if (isOutOfLine() &&
  1674. (hasInit() ||
  1675. // If the first declaration is out-of-line, this may be an
  1676. // instantiation of an out-of-line partial specialization of a variable
  1677. // template for which we have not yet instantiated the initializer.
  1678. (getFirstDecl()->isOutOfLine()
  1679. ? getTemplateSpecializationKind() == TSK_Undeclared
  1680. : getTemplateSpecializationKind() !=
  1681. TSK_ExplicitSpecialization) ||
  1682. isa<VarTemplatePartialSpecializationDecl>(this)))
  1683. return Definition;
  1684. else
  1685. return DeclarationOnly;
  1686. }
  1687. // C99 6.7p5:
  1688. // A definition of an identifier is a declaration for that identifier that
  1689. // [...] causes storage to be reserved for that object.
  1690. // Note: that applies for all non-file-scope objects.
  1691. // C99 6.9.2p1:
  1692. // If the declaration of an identifier for an object has file scope and an
  1693. // initializer, the declaration is an external definition for the identifier
  1694. if (hasInit())
  1695. return Definition;
  1696. if (hasAttr<AliasAttr>())
  1697. return Definition;
  1698. if (const auto *SAA = getAttr<SelectAnyAttr>())
  1699. if (!SAA->isInherited())
  1700. return Definition;
  1701. // A variable template specialization (other than a static data member
  1702. // template or an explicit specialization) is a declaration until we
  1703. // instantiate its initializer.
  1704. if (isa<VarTemplateSpecializationDecl>(this) &&
  1705. getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
  1706. return DeclarationOnly;
  1707. if (!getASTContext().getLangOpts().HLSL) // HLSL Change - take extern as define to match fxc.
  1708. if (hasExternalStorage())
  1709. return DeclarationOnly;
  1710. // [dcl.link] p7:
  1711. // A declaration directly contained in a linkage-specification is treated
  1712. // as if it contains the extern specifier for the purpose of determining
  1713. // the linkage of the declared name and whether it is a definition.
  1714. if (isSingleLineLanguageLinkage(*this))
  1715. return DeclarationOnly;
  1716. // C99 6.9.2p2:
  1717. // A declaration of an object that has file scope without an initializer,
  1718. // and without a storage class specifier or the scs 'static', constitutes
  1719. // a tentative definition.
  1720. // No such thing in C++.
  1721. if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
  1722. return TentativeDefinition;
  1723. // What's left is (in C, block-scope) declarations without initializers or
  1724. // external storage. These are definitions.
  1725. return Definition;
  1726. }
  1727. VarDecl *VarDecl::getActingDefinition() {
  1728. DefinitionKind Kind = isThisDeclarationADefinition();
  1729. if (Kind != TentativeDefinition)
  1730. return nullptr;
  1731. VarDecl *LastTentative = nullptr;
  1732. VarDecl *First = getFirstDecl();
  1733. for (auto I : First->redecls()) {
  1734. Kind = I->isThisDeclarationADefinition();
  1735. if (Kind == Definition)
  1736. return nullptr;
  1737. else if (Kind == TentativeDefinition)
  1738. LastTentative = I;
  1739. }
  1740. return LastTentative;
  1741. }
  1742. VarDecl *VarDecl::getDefinition(ASTContext &C) {
  1743. VarDecl *First = getFirstDecl();
  1744. for (auto I : First->redecls()) {
  1745. if (I->isThisDeclarationADefinition(C) == Definition)
  1746. return I;
  1747. }
  1748. return nullptr;
  1749. }
  1750. VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
  1751. DefinitionKind Kind = DeclarationOnly;
  1752. const VarDecl *First = getFirstDecl();
  1753. for (auto I : First->redecls()) {
  1754. Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
  1755. if (Kind == Definition)
  1756. break;
  1757. }
  1758. return Kind;
  1759. }
  1760. const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
  1761. for (auto I : redecls()) {
  1762. if (auto Expr = I->getInit()) {
  1763. D = I;
  1764. return Expr;
  1765. }
  1766. }
  1767. return nullptr;
  1768. }
  1769. bool VarDecl::isOutOfLine() const {
  1770. if (Decl::isOutOfLine())
  1771. return true;
  1772. if (!isStaticDataMember())
  1773. return false;
  1774. // If this static data member was instantiated from a static data member of
  1775. // a class template, check whether that static data member was defined
  1776. // out-of-line.
  1777. if (VarDecl *VD = getInstantiatedFromStaticDataMember())
  1778. return VD->isOutOfLine();
  1779. return false;
  1780. }
  1781. VarDecl *VarDecl::getOutOfLineDefinition() {
  1782. if (!isStaticDataMember())
  1783. return nullptr;
  1784. for (auto RD : redecls()) {
  1785. if (RD->getLexicalDeclContext()->isFileContext())
  1786. return RD;
  1787. }
  1788. return nullptr;
  1789. }
  1790. void VarDecl::setInit(Expr *I) {
  1791. if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
  1792. Eval->~EvaluatedStmt();
  1793. getASTContext().Deallocate(Eval);
  1794. }
  1795. Init = I;
  1796. }
  1797. bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
  1798. const LangOptions &Lang = C.getLangOpts();
  1799. (Lang); // HLSL Change - this object is only accessed through static consts
  1800. if (!Lang.CPlusPlus)
  1801. return false;
  1802. // In C++11, any variable of reference type can be used in a constant
  1803. // expression if it is initialized by a constant expression.
  1804. if (Lang.CPlusPlus11 && getType()->isReferenceType())
  1805. return true;
  1806. // Only const objects can be used in constant expressions in C++. C++98 does
  1807. // not require the variable to be non-volatile, but we consider this to be a
  1808. // defect.
  1809. if (!getType().isConstQualified() || getType().isVolatileQualified())
  1810. return false;
  1811. // In C++, const, non-volatile variables of integral or enumeration types
  1812. // can be used in constant expressions.
  1813. if (getType()->isIntegralOrEnumerationType())
  1814. return true;
  1815. // Additionally, in C++11, non-volatile constexpr variables can be used in
  1816. // constant expressions.
  1817. return Lang.CPlusPlus11 && isConstexpr();
  1818. }
  1819. /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
  1820. /// form, which contains extra information on the evaluated value of the
  1821. /// initializer.
  1822. EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
  1823. EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
  1824. if (!Eval) {
  1825. Stmt *S = Init.get<Stmt *>();
  1826. // Note: EvaluatedStmt contains an APValue, which usually holds
  1827. // resources not allocated from the ASTContext. We need to do some
  1828. // work to avoid leaking those, but we do so in VarDecl::evaluateValue
  1829. // where we can detect whether there's anything to clean up or not.
  1830. Eval = new (getASTContext()) EvaluatedStmt;
  1831. Eval->Value = S;
  1832. Init = Eval;
  1833. }
  1834. return Eval;
  1835. }
  1836. APValue *VarDecl::evaluateValue() const {
  1837. SmallVector<PartialDiagnosticAt, 8> Notes;
  1838. return evaluateValue(Notes);
  1839. }
  1840. namespace {
  1841. // Destroy an APValue that was allocated in an ASTContext.
  1842. void DestroyAPValue(void* UntypedValue) {
  1843. static_cast<APValue*>(UntypedValue)->~APValue();
  1844. }
  1845. } // namespace
  1846. APValue *VarDecl::evaluateValue(
  1847. SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
  1848. EvaluatedStmt *Eval = ensureEvaluatedStmt();
  1849. // We only produce notes indicating why an initializer is non-constant the
  1850. // first time it is evaluated. FIXME: The notes won't always be emitted the
  1851. // first time we try evaluation, so might not be produced at all.
  1852. if (Eval->WasEvaluated)
  1853. return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
  1854. const Expr *Init = cast<Expr>(Eval->Value);
  1855. assert(!Init->isValueDependent());
  1856. if (Eval->IsEvaluating) {
  1857. // FIXME: Produce a diagnostic for self-initialization.
  1858. Eval->CheckedICE = true;
  1859. Eval->IsICE = false;
  1860. return nullptr;
  1861. }
  1862. Eval->IsEvaluating = true;
  1863. bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
  1864. this, Notes);
  1865. // Ensure the computed APValue is cleaned up later if evaluation succeeded,
  1866. // or that it's empty (so that there's nothing to clean up) if evaluation
  1867. // failed.
  1868. if (!Result)
  1869. Eval->Evaluated = APValue();
  1870. else if (Eval->Evaluated.needsCleanup())
  1871. getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
  1872. Eval->IsEvaluating = false;
  1873. Eval->WasEvaluated = true;
  1874. // In C++11, we have determined whether the initializer was a constant
  1875. // expression as a side-effect.
  1876. if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
  1877. Eval->CheckedICE = true;
  1878. Eval->IsICE = Result && Notes.empty();
  1879. }
  1880. return Result ? &Eval->Evaluated : nullptr;
  1881. }
  1882. bool VarDecl::checkInitIsICE() const {
  1883. // Initializers of weak variables are never ICEs.
  1884. if (isWeak())
  1885. return false;
  1886. EvaluatedStmt *Eval = ensureEvaluatedStmt();
  1887. if (Eval->CheckedICE)
  1888. // We have already checked whether this subexpression is an
  1889. // integral constant expression.
  1890. return Eval->IsICE;
  1891. const Expr *Init = cast<Expr>(Eval->Value);
  1892. assert(!Init->isValueDependent());
  1893. // In C++11, evaluate the initializer to check whether it's a constant
  1894. // expression.
  1895. if (getASTContext().getLangOpts().CPlusPlus11) {
  1896. SmallVector<PartialDiagnosticAt, 8> Notes;
  1897. evaluateValue(Notes);
  1898. return Eval->IsICE;
  1899. }
  1900. // It's an ICE whether or not the definition we found is
  1901. // out-of-line. See DR 721 and the discussion in Clang PR
  1902. // 6206 for details.
  1903. if (Eval->CheckingICE)
  1904. return false;
  1905. Eval->CheckingICE = true;
  1906. Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
  1907. Eval->CheckingICE = false;
  1908. Eval->CheckedICE = true;
  1909. return Eval->IsICE;
  1910. }
  1911. VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
  1912. if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
  1913. return cast<VarDecl>(MSI->getInstantiatedFrom());
  1914. return nullptr;
  1915. }
  1916. TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
  1917. if (const VarTemplateSpecializationDecl *Spec =
  1918. dyn_cast<VarTemplateSpecializationDecl>(this))
  1919. return Spec->getSpecializationKind();
  1920. if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
  1921. return MSI->getTemplateSpecializationKind();
  1922. return TSK_Undeclared;
  1923. }
  1924. SourceLocation VarDecl::getPointOfInstantiation() const {
  1925. if (const VarTemplateSpecializationDecl *Spec =
  1926. dyn_cast<VarTemplateSpecializationDecl>(this))
  1927. return Spec->getPointOfInstantiation();
  1928. if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
  1929. return MSI->getPointOfInstantiation();
  1930. return SourceLocation();
  1931. }
  1932. VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
  1933. return getASTContext().getTemplateOrSpecializationInfo(this)
  1934. .dyn_cast<VarTemplateDecl *>();
  1935. }
  1936. void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
  1937. getASTContext().setTemplateOrSpecializationInfo(this, Template);
  1938. }
  1939. MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
  1940. if (isStaticDataMember())
  1941. // FIXME: Remove ?
  1942. // return getASTContext().getInstantiatedFromStaticDataMember(this);
  1943. return getASTContext().getTemplateOrSpecializationInfo(this)
  1944. .dyn_cast<MemberSpecializationInfo *>();
  1945. return nullptr;
  1946. }
  1947. void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
  1948. SourceLocation PointOfInstantiation) {
  1949. assert((isa<VarTemplateSpecializationDecl>(this) ||
  1950. getMemberSpecializationInfo()) &&
  1951. "not a variable or static data member template specialization");
  1952. if (VarTemplateSpecializationDecl *Spec =
  1953. dyn_cast<VarTemplateSpecializationDecl>(this)) {
  1954. Spec->setSpecializationKind(TSK);
  1955. if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
  1956. Spec->getPointOfInstantiation().isInvalid())
  1957. Spec->setPointOfInstantiation(PointOfInstantiation);
  1958. }
  1959. if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
  1960. MSI->setTemplateSpecializationKind(TSK);
  1961. if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
  1962. MSI->getPointOfInstantiation().isInvalid())
  1963. MSI->setPointOfInstantiation(PointOfInstantiation);
  1964. }
  1965. }
  1966. void
  1967. VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
  1968. TemplateSpecializationKind TSK) {
  1969. assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
  1970. "Previous template or instantiation?");
  1971. getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
  1972. }
  1973. //===----------------------------------------------------------------------===//
  1974. // ParmVarDecl Implementation
  1975. //===----------------------------------------------------------------------===//
  1976. ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
  1977. SourceLocation StartLoc,
  1978. SourceLocation IdLoc, IdentifierInfo *Id,
  1979. QualType T, TypeSourceInfo *TInfo,
  1980. StorageClass S, Expr *DefArg,
  1981. hlsl::ParameterModifier ParamMod) {
  1982. return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
  1983. S, DefArg, ParamMod);
  1984. }
  1985. QualType ParmVarDecl::getOriginalType() const {
  1986. TypeSourceInfo *TSI = getTypeSourceInfo();
  1987. QualType T = TSI ? TSI->getType() : getType();
  1988. if (const DecayedType *DT = dyn_cast<DecayedType>(T))
  1989. return DT->getOriginalType();
  1990. return T;
  1991. }
  1992. ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  1993. return new (C, ID)
  1994. ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
  1995. nullptr, QualType(), nullptr, SC_None, nullptr, hlsl::ParameterModifier());
  1996. }
  1997. SourceRange ParmVarDecl::getSourceRange() const {
  1998. if (!hasInheritedDefaultArg()) {
  1999. SourceRange ArgRange = getDefaultArgRange();
  2000. if (ArgRange.isValid())
  2001. return SourceRange(getOuterLocStart(), ArgRange.getEnd());
  2002. }
  2003. // DeclaratorDecl considers the range of postfix types as overlapping with the
  2004. // declaration name, but this is not the case with parameters in ObjC methods.
  2005. if (isa<ObjCMethodDecl>(getDeclContext()))
  2006. return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
  2007. return DeclaratorDecl::getSourceRange();
  2008. }
  2009. Expr *ParmVarDecl::getDefaultArg() {
  2010. assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
  2011. assert(!hasUninstantiatedDefaultArg() &&
  2012. "Default argument is not yet instantiated!");
  2013. Expr *Arg = getInit();
  2014. if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
  2015. return E->getSubExpr();
  2016. return Arg;
  2017. }
  2018. SourceRange ParmVarDecl::getDefaultArgRange() const {
  2019. if (const Expr *E = getInit())
  2020. return E->getSourceRange();
  2021. if (hasUninstantiatedDefaultArg())
  2022. return getUninstantiatedDefaultArg()->getSourceRange();
  2023. return SourceRange();
  2024. }
  2025. bool ParmVarDecl::isParameterPack() const {
  2026. return isa<PackExpansionType>(getType());
  2027. }
  2028. void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
  2029. getASTContext().setParameterIndex(this, parameterIndex);
  2030. ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
  2031. }
  2032. unsigned ParmVarDecl::getParameterIndexLarge() const {
  2033. return getASTContext().getParameterIndex(this);
  2034. }
  2035. // HLSL Change Begins
  2036. void ParmVarDecl::updateOutParamToRefType(ASTContext &C) {
  2037. // Aggregate type will be indirect param convert to pointer type.
  2038. // So don't update to ReferenceType.
  2039. if ((!getType()->isArrayType() && !getType()->isRecordType()) ||
  2040. hlsl::IsHLSLVecMatType(getType()))
  2041. setType(C.getLValueReferenceType(getType(), false));
  2042. // Add restrict to out param.
  2043. QualType QT = getType();
  2044. QT.addRestrict();
  2045. setType(QT);
  2046. }
  2047. // HLSL Change Ends
  2048. //===----------------------------------------------------------------------===//
  2049. // FunctionDecl Implementation
  2050. //===----------------------------------------------------------------------===//
  2051. void FunctionDecl::getNameForDiagnostic(
  2052. raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
  2053. NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
  2054. const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
  2055. if (TemplateArgs)
  2056. TemplateSpecializationType::PrintTemplateArgumentList(
  2057. OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
  2058. }
  2059. bool FunctionDecl::isVariadic() const {
  2060. if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
  2061. return FT->isVariadic();
  2062. return false;
  2063. }
  2064. bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
  2065. for (auto I : redecls()) {
  2066. if (I->Body || I->IsLateTemplateParsed) {
  2067. Definition = I;
  2068. return true;
  2069. }
  2070. }
  2071. return false;
  2072. }
  2073. bool FunctionDecl::hasTrivialBody() const
  2074. {
  2075. Stmt *S = getBody();
  2076. if (!S) {
  2077. // Since we don't have a body for this function, we don't know if it's
  2078. // trivial or not.
  2079. return false;
  2080. }
  2081. if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
  2082. return true;
  2083. return false;
  2084. }
  2085. bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
  2086. for (auto I : redecls()) {
  2087. if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
  2088. I->hasAttr<AliasAttr>()) {
  2089. Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
  2090. return true;
  2091. }
  2092. }
  2093. return false;
  2094. }
  2095. Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
  2096. if (!hasBody(Definition))
  2097. return nullptr;
  2098. if (Definition->Body)
  2099. return Definition->Body.get(getASTContext().getExternalSource());
  2100. return nullptr;
  2101. }
  2102. void FunctionDecl::setBody(Stmt *B) {
  2103. Body = B;
  2104. if (B)
  2105. EndRangeLoc = B->getLocEnd();
  2106. }
  2107. void FunctionDecl::setPure(bool P) {
  2108. IsPure = P;
  2109. if (P)
  2110. if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
  2111. Parent->markedVirtualFunctionPure();
  2112. }
  2113. template<std::size_t Len>
  2114. static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
  2115. IdentifierInfo *II = ND->getIdentifier();
  2116. return II && II->isStr(Str);
  2117. }
  2118. bool FunctionDecl::isMain() const {
  2119. const TranslationUnitDecl *tunit =
  2120. dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
  2121. return tunit &&
  2122. !tunit->getASTContext().getLangOpts().Freestanding &&
  2123. isNamed(this, "main");
  2124. }
  2125. bool FunctionDecl::isMSVCRTEntryPoint() const {
  2126. const TranslationUnitDecl *TUnit =
  2127. dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
  2128. if (!TUnit)
  2129. return false;
  2130. // Even though we aren't really targeting MSVCRT if we are freestanding,
  2131. // semantic analysis for these functions remains the same.
  2132. // MSVCRT entry points only exist on MSVCRT targets.
  2133. if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
  2134. return false;
  2135. // Nameless functions like constructors cannot be entry points.
  2136. if (!getIdentifier())
  2137. return false;
  2138. return llvm::StringSwitch<bool>(getName())
  2139. .Cases("main", // an ANSI console app
  2140. "wmain", // a Unicode console App
  2141. "WinMain", // an ANSI GUI app
  2142. "wWinMain", // a Unicode GUI app
  2143. "DllMain", // a DLL
  2144. true)
  2145. .Default(false);
  2146. }
  2147. bool FunctionDecl::isReservedGlobalPlacementOperator() const {
  2148. assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
  2149. assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
  2150. getDeclName().getCXXOverloadedOperator() == OO_Delete ||
  2151. getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
  2152. getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
  2153. if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
  2154. return false;
  2155. const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
  2156. if (proto->getNumParams() != 2 || proto->isVariadic())
  2157. return false;
  2158. ASTContext &Context =
  2159. cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
  2160. ->getASTContext();
  2161. // The result type and first argument type are constant across all
  2162. // these operators. The second argument must be exactly void*.
  2163. return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
  2164. }
  2165. bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
  2166. if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
  2167. return false;
  2168. if (getDeclName().getCXXOverloadedOperator() != OO_New &&
  2169. getDeclName().getCXXOverloadedOperator() != OO_Delete &&
  2170. getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
  2171. getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
  2172. return false;
  2173. if (isa<CXXRecordDecl>(getDeclContext()))
  2174. return false;
  2175. // This can only fail for an invalid 'operator new' declaration.
  2176. if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
  2177. return false;
  2178. const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
  2179. if (FPT->getNumParams() == 0 || FPT->getNumParams() > 2 || FPT->isVariadic())
  2180. return false;
  2181. // If this is a single-parameter function, it must be a replaceable global
  2182. // allocation or deallocation function.
  2183. if (FPT->getNumParams() == 1)
  2184. return true;
  2185. // Otherwise, we're looking for a second parameter whose type is
  2186. // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
  2187. QualType Ty = FPT->getParamType(1);
  2188. ASTContext &Ctx = getASTContext();
  2189. if (Ctx.getLangOpts().SizedDeallocation &&
  2190. Ctx.hasSameType(Ty, Ctx.getSizeType()))
  2191. return true;
  2192. if (!Ty->isReferenceType())
  2193. return false;
  2194. Ty = Ty->getPointeeType();
  2195. if (Ty.getCVRQualifiers() != Qualifiers::Const)
  2196. return false;
  2197. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  2198. return RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace();
  2199. }
  2200. LanguageLinkage FunctionDecl::getLanguageLinkage() const {
  2201. return getDeclLanguageLinkage(*this);
  2202. }
  2203. bool FunctionDecl::isExternC() const {
  2204. return isDeclExternC(*this);
  2205. }
  2206. bool FunctionDecl::isInExternCContext() const {
  2207. return getLexicalDeclContext()->isExternCContext();
  2208. }
  2209. bool FunctionDecl::isInExternCXXContext() const {
  2210. return getLexicalDeclContext()->isExternCXXContext();
  2211. }
  2212. bool FunctionDecl::isGlobal() const {
  2213. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
  2214. return Method->isStatic();
  2215. if (getCanonicalDecl()->getStorageClass() == SC_Static)
  2216. return false;
  2217. for (const DeclContext *DC = getDeclContext();
  2218. DC->isNamespace();
  2219. DC = DC->getParent()) {
  2220. if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
  2221. if (!Namespace->getDeclName())
  2222. return false;
  2223. break;
  2224. }
  2225. }
  2226. return true;
  2227. }
  2228. bool FunctionDecl::isNoReturn() const {
  2229. return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
  2230. hasAttr<C11NoReturnAttr>() ||
  2231. getType()->getAs<FunctionType>()->getNoReturnAttr();
  2232. }
  2233. void
  2234. FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
  2235. redeclarable_base::setPreviousDecl(PrevDecl);
  2236. if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
  2237. FunctionTemplateDecl *PrevFunTmpl
  2238. = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
  2239. assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
  2240. FunTmpl->setPreviousDecl(PrevFunTmpl);
  2241. }
  2242. if (PrevDecl && PrevDecl->IsInline)
  2243. IsInline = true;
  2244. }
  2245. FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
  2246. /// \brief Returns a value indicating whether this function
  2247. /// corresponds to a builtin function.
  2248. ///
  2249. /// The function corresponds to a built-in function if it is
  2250. /// declared at translation scope or within an extern "C" block and
  2251. /// its name matches with the name of a builtin. The returned value
  2252. /// will be 0 for functions that do not correspond to a builtin, a
  2253. /// value of type \c Builtin::ID if in the target-independent range
  2254. /// \c [1,Builtin::First), or a target-specific builtin value.
  2255. unsigned FunctionDecl::getBuiltinID() const {
  2256. if (!getIdentifier())
  2257. return 0;
  2258. unsigned BuiltinID = getIdentifier()->getBuiltinID();
  2259. if (!BuiltinID)
  2260. return 0;
  2261. ASTContext &Context = getASTContext();
  2262. if (Context.getLangOpts().CPlusPlus) {
  2263. const LinkageSpecDecl *LinkageDecl = dyn_cast<LinkageSpecDecl>(
  2264. getFirstDecl()->getDeclContext());
  2265. // In C++, the first declaration of a builtin is always inside an implicit
  2266. // extern "C".
  2267. // FIXME: A recognised library function may not be directly in an extern "C"
  2268. // declaration, for instance "extern "C" { namespace std { decl } }".
  2269. if (!LinkageDecl) {
  2270. if (BuiltinID == Builtin::BI__GetExceptionInfo &&
  2271. Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  2272. isInStdNamespace())
  2273. return Builtin::BI__GetExceptionInfo;
  2274. return 0;
  2275. }
  2276. if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
  2277. return 0;
  2278. }
  2279. // If the function is marked "overloadable", it has a different mangled name
  2280. // and is not the C library function.
  2281. if (hasAttr<OverloadableAttr>())
  2282. return 0;
  2283. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
  2284. return BuiltinID;
  2285. // This function has the name of a known C library
  2286. // function. Determine whether it actually refers to the C library
  2287. // function or whether it just has the same name.
  2288. // If this is a static function, it's not a builtin.
  2289. if (getStorageClass() == SC_Static)
  2290. return 0;
  2291. return BuiltinID;
  2292. }
  2293. /// getNumParams - Return the number of parameters this function must have
  2294. /// based on its FunctionType. This is the length of the ParamInfo array
  2295. /// after it has been created.
  2296. unsigned FunctionDecl::getNumParams() const {
  2297. const FunctionProtoType *FPT = getType()->getAs<FunctionProtoType>();
  2298. return FPT ? FPT->getNumParams() : 0;
  2299. }
  2300. void FunctionDecl::setParams(ASTContext &C,
  2301. ArrayRef<ParmVarDecl *> NewParamInfo) {
  2302. assert(!ParamInfo && "Already has param info!");
  2303. assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
  2304. // Zero params -> null pointer.
  2305. if (!NewParamInfo.empty()) {
  2306. ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
  2307. std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
  2308. }
  2309. }
  2310. void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
  2311. assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
  2312. if (!NewDecls.empty()) {
  2313. NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
  2314. std::copy(NewDecls.begin(), NewDecls.end(), A);
  2315. DeclsInPrototypeScope = llvm::makeArrayRef(A, NewDecls.size());
  2316. // Move declarations introduced in prototype to the function context.
  2317. for (auto I : NewDecls) {
  2318. DeclContext *DC = I->getDeclContext();
  2319. // Forward-declared reference to an enumeration is not added to
  2320. // declaration scope, so skip declaration that is absent from its
  2321. // declaration contexts.
  2322. if (DC->containsDecl(I)) {
  2323. DC->removeDecl(I);
  2324. I->setDeclContext(this);
  2325. addDecl(I);
  2326. }
  2327. }
  2328. }
  2329. }
  2330. /// getMinRequiredArguments - Returns the minimum number of arguments
  2331. /// needed to call this function. This may be fewer than the number of
  2332. /// function parameters, if some of the parameters have default
  2333. /// arguments (in C++) or are parameter packs (C++11).
  2334. unsigned FunctionDecl::getMinRequiredArguments() const {
  2335. if (!getASTContext().getLangOpts().CPlusPlus)
  2336. return getNumParams();
  2337. unsigned NumRequiredArgs = 0;
  2338. for (auto *Param : params())
  2339. if (!Param->isParameterPack() && !Param->hasDefaultArg())
  2340. ++NumRequiredArgs;
  2341. return NumRequiredArgs;
  2342. }
  2343. /// \brief The combination of the extern and inline keywords under MSVC forces
  2344. /// the function to be required.
  2345. ///
  2346. /// Note: This function assumes that we will only get called when isInlined()
  2347. /// would return true for this FunctionDecl.
  2348. bool FunctionDecl::isMSExternInline() const {
  2349. assert(isInlined() && "expected to get called on an inlined function!");
  2350. const ASTContext &Context = getASTContext();
  2351. if (!Context.getLangOpts().MSVCCompat && !hasAttr<DLLExportAttr>())
  2352. return false;
  2353. for (const FunctionDecl *FD = getMostRecentDecl(); FD;
  2354. FD = FD->getPreviousDecl())
  2355. if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
  2356. return true;
  2357. return false;
  2358. }
  2359. static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
  2360. if (Redecl->getStorageClass() != SC_Extern)
  2361. return false;
  2362. for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
  2363. FD = FD->getPreviousDecl())
  2364. if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
  2365. return false;
  2366. return true;
  2367. }
  2368. static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
  2369. // Only consider file-scope declarations in this test.
  2370. if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
  2371. return false;
  2372. // Only consider explicit declarations; the presence of a builtin for a
  2373. // libcall shouldn't affect whether a definition is externally visible.
  2374. if (Redecl->isImplicit())
  2375. return false;
  2376. if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
  2377. return true; // Not an inline definition
  2378. return false;
  2379. }
  2380. /// \brief For a function declaration in C or C++, determine whether this
  2381. /// declaration causes the definition to be externally visible.
  2382. ///
  2383. /// For instance, this determines if adding the current declaration to the set
  2384. /// of redeclarations of the given functions causes
  2385. /// isInlineDefinitionExternallyVisible to change from false to true.
  2386. bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
  2387. assert(!doesThisDeclarationHaveABody() &&
  2388. "Must have a declaration without a body.");
  2389. ASTContext &Context = getASTContext();
  2390. if (Context.getLangOpts().MSVCCompat) {
  2391. const FunctionDecl *Definition;
  2392. if (hasBody(Definition) && Definition->isInlined() &&
  2393. redeclForcesDefMSVC(this))
  2394. return true;
  2395. }
  2396. if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
  2397. // With GNU inlining, a declaration with 'inline' but not 'extern', forces
  2398. // an externally visible definition.
  2399. //
  2400. // FIXME: What happens if gnu_inline gets added on after the first
  2401. // declaration?
  2402. if (!isInlineSpecified() || getStorageClass() == SC_Extern)
  2403. return false;
  2404. const FunctionDecl *Prev = this;
  2405. bool FoundBody = false;
  2406. while ((Prev = Prev->getPreviousDecl())) {
  2407. FoundBody |= Prev->Body.isValid();
  2408. if (Prev->Body) {
  2409. // If it's not the case that both 'inline' and 'extern' are
  2410. // specified on the definition, then it is always externally visible.
  2411. if (!Prev->isInlineSpecified() ||
  2412. Prev->getStorageClass() != SC_Extern)
  2413. return false;
  2414. } else if (Prev->isInlineSpecified() &&
  2415. Prev->getStorageClass() != SC_Extern) {
  2416. return false;
  2417. }
  2418. }
  2419. return FoundBody;
  2420. }
  2421. if (Context.getLangOpts().CPlusPlus)
  2422. return false;
  2423. // C99 6.7.4p6:
  2424. // [...] If all of the file scope declarations for a function in a
  2425. // translation unit include the inline function specifier without extern,
  2426. // then the definition in that translation unit is an inline definition.
  2427. if (isInlineSpecified() && getStorageClass() != SC_Extern)
  2428. return false;
  2429. const FunctionDecl *Prev = this;
  2430. bool FoundBody = false;
  2431. while ((Prev = Prev->getPreviousDecl())) {
  2432. FoundBody |= Prev->Body.isValid();
  2433. if (RedeclForcesDefC99(Prev))
  2434. return false;
  2435. }
  2436. return FoundBody;
  2437. }
  2438. SourceRange FunctionDecl::getReturnTypeSourceRange() const {
  2439. const TypeSourceInfo *TSI = getTypeSourceInfo();
  2440. if (!TSI)
  2441. return SourceRange();
  2442. FunctionTypeLoc FTL =
  2443. TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
  2444. if (!FTL)
  2445. return SourceRange();
  2446. // Skip self-referential return types.
  2447. const SourceManager &SM = getASTContext().getSourceManager();
  2448. SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
  2449. SourceLocation Boundary = getNameInfo().getLocStart();
  2450. if (RTRange.isInvalid() || Boundary.isInvalid() ||
  2451. !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
  2452. return SourceRange();
  2453. return RTRange;
  2454. }
  2455. bool FunctionDecl::hasUnusedResultAttr() const {
  2456. QualType RetType = getReturnType();
  2457. if (RetType->isRecordType()) {
  2458. const CXXRecordDecl *Ret = RetType->getAsCXXRecordDecl();
  2459. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(this);
  2460. if (Ret && Ret->hasAttr<WarnUnusedResultAttr>() &&
  2461. !(MD && MD->getCorrespondingMethodInClass(Ret, true)))
  2462. return true;
  2463. }
  2464. return hasAttr<WarnUnusedResultAttr>();
  2465. }
  2466. /// \brief For an inline function definition in C, or for a gnu_inline function
  2467. /// in C++, determine whether the definition will be externally visible.
  2468. ///
  2469. /// Inline function definitions are always available for inlining optimizations.
  2470. /// However, depending on the language dialect, declaration specifiers, and
  2471. /// attributes, the definition of an inline function may or may not be
  2472. /// "externally" visible to other translation units in the program.
  2473. ///
  2474. /// In C99, inline definitions are not externally visible by default. However,
  2475. /// if even one of the global-scope declarations is marked "extern inline", the
  2476. /// inline definition becomes externally visible (C99 6.7.4p6).
  2477. ///
  2478. /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
  2479. /// definition, we use the GNU semantics for inline, which are nearly the
  2480. /// opposite of C99 semantics. In particular, "inline" by itself will create
  2481. /// an externally visible symbol, but "extern inline" will not create an
  2482. /// externally visible symbol.
  2483. bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
  2484. assert(doesThisDeclarationHaveABody() && "Must have the function definition");
  2485. assert(isInlined() && "Function must be inline");
  2486. ASTContext &Context = getASTContext();
  2487. if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
  2488. // Note: If you change the logic here, please change
  2489. // doesDeclarationForceExternallyVisibleDefinition as well.
  2490. //
  2491. // If it's not the case that both 'inline' and 'extern' are
  2492. // specified on the definition, then this inline definition is
  2493. // externally visible.
  2494. if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
  2495. return true;
  2496. // If any declaration is 'inline' but not 'extern', then this definition
  2497. // is externally visible.
  2498. for (auto Redecl : redecls()) {
  2499. if (Redecl->isInlineSpecified() &&
  2500. Redecl->getStorageClass() != SC_Extern)
  2501. return true;
  2502. }
  2503. return false;
  2504. }
  2505. // The rest of this function is C-only.
  2506. assert(!Context.getLangOpts().CPlusPlus &&
  2507. "should not use C inline rules in C++");
  2508. // C99 6.7.4p6:
  2509. // [...] If all of the file scope declarations for a function in a
  2510. // translation unit include the inline function specifier without extern,
  2511. // then the definition in that translation unit is an inline definition.
  2512. for (auto Redecl : redecls()) {
  2513. if (RedeclForcesDefC99(Redecl))
  2514. return true;
  2515. }
  2516. // C99 6.7.4p6:
  2517. // An inline definition does not provide an external definition for the
  2518. // function, and does not forbid an external definition in another
  2519. // translation unit.
  2520. return false;
  2521. }
  2522. /// getOverloadedOperator - Which C++ overloaded operator this
  2523. /// function represents, if any.
  2524. OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
  2525. if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
  2526. return getDeclName().getCXXOverloadedOperator();
  2527. else
  2528. return OO_None;
  2529. }
  2530. /// getLiteralIdentifier - The literal suffix identifier this function
  2531. /// represents, if any.
  2532. const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
  2533. if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
  2534. return getDeclName().getCXXLiteralIdentifier();
  2535. else
  2536. return nullptr;
  2537. }
  2538. FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
  2539. if (TemplateOrSpecialization.isNull())
  2540. return TK_NonTemplate;
  2541. if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
  2542. return TK_FunctionTemplate;
  2543. if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
  2544. return TK_MemberSpecialization;
  2545. if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
  2546. return TK_FunctionTemplateSpecialization;
  2547. if (TemplateOrSpecialization.is
  2548. <DependentFunctionTemplateSpecializationInfo*>())
  2549. return TK_DependentFunctionTemplateSpecialization;
  2550. llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
  2551. }
  2552. FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
  2553. if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
  2554. return cast<FunctionDecl>(Info->getInstantiatedFrom());
  2555. return nullptr;
  2556. }
  2557. void
  2558. FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
  2559. FunctionDecl *FD,
  2560. TemplateSpecializationKind TSK) {
  2561. assert(TemplateOrSpecialization.isNull() &&
  2562. "Member function is already a specialization");
  2563. MemberSpecializationInfo *Info
  2564. = new (C) MemberSpecializationInfo(FD, TSK);
  2565. TemplateOrSpecialization = Info;
  2566. }
  2567. bool FunctionDecl::isImplicitlyInstantiable() const {
  2568. // If the function is invalid, it can't be implicitly instantiated.
  2569. if (isInvalidDecl())
  2570. return false;
  2571. switch (getTemplateSpecializationKind()) {
  2572. case TSK_Undeclared:
  2573. case TSK_ExplicitInstantiationDefinition:
  2574. return false;
  2575. case TSK_ImplicitInstantiation:
  2576. return true;
  2577. // It is possible to instantiate TSK_ExplicitSpecialization kind
  2578. // if the FunctionDecl has a class scope specialization pattern.
  2579. case TSK_ExplicitSpecialization:
  2580. return getClassScopeSpecializationPattern() != nullptr;
  2581. case TSK_ExplicitInstantiationDeclaration:
  2582. // Handled below.
  2583. break;
  2584. }
  2585. // Find the actual template from which we will instantiate.
  2586. const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
  2587. bool HasPattern = false;
  2588. if (PatternDecl)
  2589. HasPattern = PatternDecl->hasBody(PatternDecl);
  2590. // C++0x [temp.explicit]p9:
  2591. // Except for inline functions, other explicit instantiation declarations
  2592. // have the effect of suppressing the implicit instantiation of the entity
  2593. // to which they refer.
  2594. if (!HasPattern || !PatternDecl)
  2595. return true;
  2596. return PatternDecl->isInlined();
  2597. }
  2598. bool FunctionDecl::isTemplateInstantiation() const {
  2599. switch (getTemplateSpecializationKind()) {
  2600. case TSK_Undeclared:
  2601. case TSK_ExplicitSpecialization:
  2602. return false;
  2603. case TSK_ImplicitInstantiation:
  2604. case TSK_ExplicitInstantiationDeclaration:
  2605. case TSK_ExplicitInstantiationDefinition:
  2606. return true;
  2607. }
  2608. llvm_unreachable("All TSK values handled.");
  2609. }
  2610. FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
  2611. // Handle class scope explicit specialization special case.
  2612. if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
  2613. return getClassScopeSpecializationPattern();
  2614. // If this is a generic lambda call operator specialization, its
  2615. // instantiation pattern is always its primary template's pattern
  2616. // even if its primary template was instantiated from another
  2617. // member template (which happens with nested generic lambdas).
  2618. // Since a lambda's call operator's body is transformed eagerly,
  2619. // we don't have to go hunting for a prototype definition template
  2620. // (i.e. instantiated-from-member-template) to use as an instantiation
  2621. // pattern.
  2622. if (isGenericLambdaCallOperatorSpecialization(
  2623. dyn_cast<CXXMethodDecl>(this))) {
  2624. assert(getPrimaryTemplate() && "A generic lambda specialization must be "
  2625. "generated from a primary call operator "
  2626. "template");
  2627. assert(getPrimaryTemplate()->getTemplatedDecl()->getBody() &&
  2628. "A generic lambda call operator template must always have a body - "
  2629. "even if instantiated from a prototype (i.e. as written) member "
  2630. "template");
  2631. return getPrimaryTemplate()->getTemplatedDecl();
  2632. }
  2633. if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
  2634. while (Primary->getInstantiatedFromMemberTemplate()) {
  2635. // If we have hit a point where the user provided a specialization of
  2636. // this template, we're done looking.
  2637. if (Primary->isMemberSpecialization())
  2638. break;
  2639. Primary = Primary->getInstantiatedFromMemberTemplate();
  2640. }
  2641. return Primary->getTemplatedDecl();
  2642. }
  2643. return getInstantiatedFromMemberFunction();
  2644. }
  2645. FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
  2646. if (FunctionTemplateSpecializationInfo *Info
  2647. = TemplateOrSpecialization
  2648. .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
  2649. return Info->Template.getPointer();
  2650. }
  2651. return nullptr;
  2652. }
  2653. FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
  2654. return getASTContext().getClassScopeSpecializationPattern(this);
  2655. }
  2656. const TemplateArgumentList *
  2657. FunctionDecl::getTemplateSpecializationArgs() const {
  2658. if (FunctionTemplateSpecializationInfo *Info
  2659. = TemplateOrSpecialization
  2660. .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
  2661. return Info->TemplateArguments;
  2662. }
  2663. return nullptr;
  2664. }
  2665. const ASTTemplateArgumentListInfo *
  2666. FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
  2667. if (FunctionTemplateSpecializationInfo *Info
  2668. = TemplateOrSpecialization
  2669. .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
  2670. return Info->TemplateArgumentsAsWritten;
  2671. }
  2672. return nullptr;
  2673. }
  2674. void
  2675. FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
  2676. FunctionTemplateDecl *Template,
  2677. const TemplateArgumentList *TemplateArgs,
  2678. void *InsertPos,
  2679. TemplateSpecializationKind TSK,
  2680. const TemplateArgumentListInfo *TemplateArgsAsWritten,
  2681. SourceLocation PointOfInstantiation) {
  2682. assert(TSK != TSK_Undeclared &&
  2683. "Must specify the type of function template specialization");
  2684. FunctionTemplateSpecializationInfo *Info
  2685. = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
  2686. if (!Info)
  2687. Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
  2688. TemplateArgs,
  2689. TemplateArgsAsWritten,
  2690. PointOfInstantiation);
  2691. TemplateOrSpecialization = Info;
  2692. Template->addSpecialization(Info, InsertPos);
  2693. }
  2694. void
  2695. FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
  2696. const UnresolvedSetImpl &Templates,
  2697. const TemplateArgumentListInfo &TemplateArgs) {
  2698. assert(TemplateOrSpecialization.isNull());
  2699. size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
  2700. Size += Templates.size() * sizeof(FunctionTemplateDecl*);
  2701. Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
  2702. void *Buffer = Context.Allocate(Size);
  2703. DependentFunctionTemplateSpecializationInfo *Info =
  2704. new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
  2705. TemplateArgs);
  2706. TemplateOrSpecialization = Info;
  2707. }
  2708. DependentFunctionTemplateSpecializationInfo::
  2709. DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
  2710. const TemplateArgumentListInfo &TArgs)
  2711. : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
  2712. static_assert(sizeof(*this) % llvm::AlignOf<void *>::Alignment == 0,
  2713. "Trailing data is unaligned!");
  2714. d.NumTemplates = Ts.size();
  2715. d.NumArgs = TArgs.size();
  2716. FunctionTemplateDecl **TsArray =
  2717. const_cast<FunctionTemplateDecl**>(getTemplates());
  2718. for (unsigned I = 0, E = Ts.size(); I != E; ++I)
  2719. TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
  2720. TemplateArgumentLoc *ArgsArray =
  2721. const_cast<TemplateArgumentLoc*>(getTemplateArgs());
  2722. for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
  2723. new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
  2724. }
  2725. TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
  2726. // For a function template specialization, query the specialization
  2727. // information object.
  2728. FunctionTemplateSpecializationInfo *FTSInfo
  2729. = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
  2730. if (FTSInfo)
  2731. return FTSInfo->getTemplateSpecializationKind();
  2732. MemberSpecializationInfo *MSInfo
  2733. = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
  2734. if (MSInfo)
  2735. return MSInfo->getTemplateSpecializationKind();
  2736. return TSK_Undeclared;
  2737. }
  2738. void
  2739. FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
  2740. SourceLocation PointOfInstantiation) {
  2741. if (FunctionTemplateSpecializationInfo *FTSInfo
  2742. = TemplateOrSpecialization.dyn_cast<
  2743. FunctionTemplateSpecializationInfo*>()) {
  2744. FTSInfo->setTemplateSpecializationKind(TSK);
  2745. if (TSK != TSK_ExplicitSpecialization &&
  2746. PointOfInstantiation.isValid() &&
  2747. FTSInfo->getPointOfInstantiation().isInvalid())
  2748. FTSInfo->setPointOfInstantiation(PointOfInstantiation);
  2749. } else if (MemberSpecializationInfo *MSInfo
  2750. = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
  2751. MSInfo->setTemplateSpecializationKind(TSK);
  2752. if (TSK != TSK_ExplicitSpecialization &&
  2753. PointOfInstantiation.isValid() &&
  2754. MSInfo->getPointOfInstantiation().isInvalid())
  2755. MSInfo->setPointOfInstantiation(PointOfInstantiation);
  2756. } else
  2757. llvm_unreachable("Function cannot have a template specialization kind");
  2758. }
  2759. SourceLocation FunctionDecl::getPointOfInstantiation() const {
  2760. if (FunctionTemplateSpecializationInfo *FTSInfo
  2761. = TemplateOrSpecialization.dyn_cast<
  2762. FunctionTemplateSpecializationInfo*>())
  2763. return FTSInfo->getPointOfInstantiation();
  2764. else if (MemberSpecializationInfo *MSInfo
  2765. = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
  2766. return MSInfo->getPointOfInstantiation();
  2767. return SourceLocation();
  2768. }
  2769. bool FunctionDecl::isOutOfLine() const {
  2770. if (Decl::isOutOfLine())
  2771. return true;
  2772. // If this function was instantiated from a member function of a
  2773. // class template, check whether that member function was defined out-of-line.
  2774. if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
  2775. const FunctionDecl *Definition;
  2776. if (FD->hasBody(Definition))
  2777. return Definition->isOutOfLine();
  2778. }
  2779. // If this function was instantiated from a function template,
  2780. // check whether that function template was defined out-of-line.
  2781. if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
  2782. const FunctionDecl *Definition;
  2783. if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
  2784. return Definition->isOutOfLine();
  2785. }
  2786. return false;
  2787. }
  2788. SourceRange FunctionDecl::getSourceRange() const {
  2789. return SourceRange(getOuterLocStart(), EndRangeLoc);
  2790. }
  2791. unsigned FunctionDecl::getMemoryFunctionKind() const {
  2792. IdentifierInfo *FnInfo = getIdentifier();
  2793. if (!FnInfo)
  2794. return 0;
  2795. // Builtin handling.
  2796. switch (getBuiltinID()) {
  2797. case Builtin::BI__builtin_memset:
  2798. case Builtin::BI__builtin___memset_chk:
  2799. case Builtin::BImemset:
  2800. return Builtin::BImemset;
  2801. case Builtin::BI__builtin_memcpy:
  2802. case Builtin::BI__builtin___memcpy_chk:
  2803. case Builtin::BImemcpy:
  2804. return Builtin::BImemcpy;
  2805. case Builtin::BI__builtin_memmove:
  2806. case Builtin::BI__builtin___memmove_chk:
  2807. case Builtin::BImemmove:
  2808. return Builtin::BImemmove;
  2809. case Builtin::BIstrlcpy:
  2810. case Builtin::BI__builtin___strlcpy_chk:
  2811. return Builtin::BIstrlcpy;
  2812. case Builtin::BIstrlcat:
  2813. case Builtin::BI__builtin___strlcat_chk:
  2814. return Builtin::BIstrlcat;
  2815. case Builtin::BI__builtin_memcmp:
  2816. case Builtin::BImemcmp:
  2817. return Builtin::BImemcmp;
  2818. case Builtin::BI__builtin_strncpy:
  2819. case Builtin::BI__builtin___strncpy_chk:
  2820. case Builtin::BIstrncpy:
  2821. return Builtin::BIstrncpy;
  2822. case Builtin::BI__builtin_strncmp:
  2823. case Builtin::BIstrncmp:
  2824. return Builtin::BIstrncmp;
  2825. case Builtin::BI__builtin_strncasecmp:
  2826. case Builtin::BIstrncasecmp:
  2827. return Builtin::BIstrncasecmp;
  2828. case Builtin::BI__builtin_strncat:
  2829. case Builtin::BI__builtin___strncat_chk:
  2830. case Builtin::BIstrncat:
  2831. return Builtin::BIstrncat;
  2832. case Builtin::BI__builtin_strndup:
  2833. case Builtin::BIstrndup:
  2834. return Builtin::BIstrndup;
  2835. case Builtin::BI__builtin_strlen:
  2836. case Builtin::BIstrlen:
  2837. return Builtin::BIstrlen;
  2838. default:
  2839. if (isExternC()) {
  2840. if (FnInfo->isStr("memset"))
  2841. return Builtin::BImemset;
  2842. else if (FnInfo->isStr("memcpy"))
  2843. return Builtin::BImemcpy;
  2844. else if (FnInfo->isStr("memmove"))
  2845. return Builtin::BImemmove;
  2846. else if (FnInfo->isStr("memcmp"))
  2847. return Builtin::BImemcmp;
  2848. else if (FnInfo->isStr("strncpy"))
  2849. return Builtin::BIstrncpy;
  2850. else if (FnInfo->isStr("strncmp"))
  2851. return Builtin::BIstrncmp;
  2852. else if (FnInfo->isStr("strncasecmp"))
  2853. return Builtin::BIstrncasecmp;
  2854. else if (FnInfo->isStr("strncat"))
  2855. return Builtin::BIstrncat;
  2856. else if (FnInfo->isStr("strndup"))
  2857. return Builtin::BIstrndup;
  2858. else if (FnInfo->isStr("strlen"))
  2859. return Builtin::BIstrlen;
  2860. }
  2861. break;
  2862. }
  2863. return 0;
  2864. }
  2865. //===----------------------------------------------------------------------===//
  2866. // FieldDecl Implementation
  2867. //===----------------------------------------------------------------------===//
  2868. FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
  2869. SourceLocation StartLoc, SourceLocation IdLoc,
  2870. IdentifierInfo *Id, QualType T,
  2871. TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
  2872. InClassInitStyle InitStyle) {
  2873. return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
  2874. BW, Mutable, InitStyle);
  2875. }
  2876. FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  2877. return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
  2878. SourceLocation(), nullptr, QualType(), nullptr,
  2879. nullptr, false, ICIS_NoInit);
  2880. }
  2881. bool FieldDecl::isAnonymousStructOrUnion() const {
  2882. if (!isImplicit() || getDeclName())
  2883. return false;
  2884. if (const RecordType *Record = getType()->getAs<RecordType>())
  2885. return Record->getDecl()->isAnonymousStructOrUnion();
  2886. return false;
  2887. }
  2888. unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
  2889. assert(isBitField() && "not a bitfield");
  2890. Expr *BitWidth = static_cast<Expr *>(InitStorage.getPointer());
  2891. return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
  2892. }
  2893. unsigned FieldDecl::getFieldIndex() const {
  2894. const FieldDecl *Canonical = getCanonicalDecl();
  2895. if (Canonical != this)
  2896. return Canonical->getFieldIndex();
  2897. if (CachedFieldIndex) return CachedFieldIndex - 1;
  2898. unsigned Index = 0;
  2899. const RecordDecl *RD = getParent();
  2900. for (auto *Field : RD->fields()) {
  2901. Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
  2902. ++Index;
  2903. }
  2904. assert(CachedFieldIndex && "failed to find field in parent");
  2905. return CachedFieldIndex - 1;
  2906. }
  2907. SourceRange FieldDecl::getSourceRange() const {
  2908. switch (InitStorage.getInt()) {
  2909. // All three of these cases store an optional Expr*.
  2910. case ISK_BitWidthOrNothing:
  2911. case ISK_InClassCopyInit:
  2912. case ISK_InClassListInit:
  2913. if (const Expr *E = static_cast<const Expr *>(InitStorage.getPointer()))
  2914. return SourceRange(getInnerLocStart(), E->getLocEnd());
  2915. // FALLTHROUGH
  2916. case ISK_CapturedVLAType:
  2917. return DeclaratorDecl::getSourceRange();
  2918. }
  2919. llvm_unreachable("bad init storage kind");
  2920. }
  2921. void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
  2922. assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
  2923. "capturing type in non-lambda or captured record.");
  2924. assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
  2925. InitStorage.getPointer() == nullptr &&
  2926. "bit width, initializer or captured type already set");
  2927. InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
  2928. ISK_CapturedVLAType);
  2929. }
  2930. //===----------------------------------------------------------------------===//
  2931. // TagDecl Implementation
  2932. //===----------------------------------------------------------------------===//
  2933. SourceLocation TagDecl::getOuterLocStart() const {
  2934. return getTemplateOrInnerLocStart(this);
  2935. }
  2936. SourceRange TagDecl::getSourceRange() const {
  2937. SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
  2938. return SourceRange(getOuterLocStart(), E);
  2939. }
  2940. TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
  2941. void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
  2942. NamedDeclOrQualifier = TDD;
  2943. if (const Type *T = getTypeForDecl()) {
  2944. (void)T;
  2945. assert(T->isLinkageValid());
  2946. }
  2947. assert(isLinkageValid());
  2948. }
  2949. void TagDecl::startDefinition() {
  2950. IsBeingDefined = true;
  2951. if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
  2952. struct CXXRecordDecl::DefinitionData *Data =
  2953. new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
  2954. for (auto I : redecls())
  2955. cast<CXXRecordDecl>(I)->DefinitionData = Data;
  2956. }
  2957. }
  2958. void TagDecl::completeDefinition() {
  2959. assert((!isa<CXXRecordDecl>(this) ||
  2960. cast<CXXRecordDecl>(this)->hasDefinition()) &&
  2961. "definition completed but not started");
  2962. IsCompleteDefinition = true;
  2963. IsBeingDefined = false;
  2964. if (ASTMutationListener *L = getASTMutationListener())
  2965. L->CompletedTagDefinition(this);
  2966. }
  2967. TagDecl *TagDecl::getDefinition() const {
  2968. if (isCompleteDefinition())
  2969. return const_cast<TagDecl *>(this);
  2970. // If it's possible for us to have an out-of-date definition, check now.
  2971. if (MayHaveOutOfDateDef) {
  2972. if (IdentifierInfo *II = getIdentifier()) {
  2973. if (II->isOutOfDate()) {
  2974. updateOutOfDate(*II);
  2975. }
  2976. }
  2977. }
  2978. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
  2979. return CXXRD->getDefinition();
  2980. for (auto R : redecls())
  2981. if (R->isCompleteDefinition())
  2982. return R;
  2983. return nullptr;
  2984. }
  2985. void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
  2986. if (QualifierLoc) {
  2987. // Make sure the extended qualifier info is allocated.
  2988. if (!hasExtInfo())
  2989. NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
  2990. // Set qualifier info.
  2991. getExtInfo()->QualifierLoc = QualifierLoc;
  2992. } else {
  2993. // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
  2994. if (hasExtInfo()) {
  2995. if (getExtInfo()->NumTemplParamLists == 0) {
  2996. getASTContext().Deallocate(getExtInfo());
  2997. NamedDeclOrQualifier = (TypedefNameDecl*)nullptr;
  2998. }
  2999. else
  3000. getExtInfo()->QualifierLoc = QualifierLoc;
  3001. }
  3002. }
  3003. }
  3004. void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
  3005. unsigned NumTPLists,
  3006. TemplateParameterList **TPLists) {
  3007. assert(NumTPLists > 0);
  3008. // Make sure the extended decl info is allocated.
  3009. if (!hasExtInfo())
  3010. // Allocate external info struct.
  3011. NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
  3012. // Set the template parameter lists info.
  3013. getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
  3014. }
  3015. //===----------------------------------------------------------------------===//
  3016. // EnumDecl Implementation
  3017. //===----------------------------------------------------------------------===//
  3018. void EnumDecl::anchor() { }
  3019. EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
  3020. SourceLocation StartLoc, SourceLocation IdLoc,
  3021. IdentifierInfo *Id,
  3022. EnumDecl *PrevDecl, bool IsScoped,
  3023. bool IsScopedUsingClassTag, bool IsFixed) {
  3024. EnumDecl *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
  3025. IsScoped, IsScopedUsingClassTag,
  3026. IsFixed);
  3027. Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
  3028. C.getTypeDeclType(Enum, PrevDecl);
  3029. return Enum;
  3030. }
  3031. EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3032. EnumDecl *Enum =
  3033. new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
  3034. nullptr, nullptr, false, false, false);
  3035. Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
  3036. return Enum;
  3037. }
  3038. SourceRange EnumDecl::getIntegerTypeRange() const {
  3039. if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
  3040. return TI->getTypeLoc().getSourceRange();
  3041. return SourceRange();
  3042. }
  3043. void EnumDecl::completeDefinition(QualType NewType,
  3044. QualType NewPromotionType,
  3045. unsigned NumPositiveBits,
  3046. unsigned NumNegativeBits) {
  3047. assert(!isCompleteDefinition() && "Cannot redefine enums!");
  3048. if (!IntegerType)
  3049. IntegerType = NewType.getTypePtr();
  3050. PromotionType = NewPromotionType;
  3051. setNumPositiveBits(NumPositiveBits);
  3052. setNumNegativeBits(NumNegativeBits);
  3053. TagDecl::completeDefinition();
  3054. }
  3055. TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
  3056. if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
  3057. return MSI->getTemplateSpecializationKind();
  3058. return TSK_Undeclared;
  3059. }
  3060. void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
  3061. SourceLocation PointOfInstantiation) {
  3062. MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
  3063. assert(MSI && "Not an instantiated member enumeration?");
  3064. MSI->setTemplateSpecializationKind(TSK);
  3065. if (TSK != TSK_ExplicitSpecialization &&
  3066. PointOfInstantiation.isValid() &&
  3067. MSI->getPointOfInstantiation().isInvalid())
  3068. MSI->setPointOfInstantiation(PointOfInstantiation);
  3069. }
  3070. EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
  3071. if (SpecializationInfo)
  3072. return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
  3073. return nullptr;
  3074. }
  3075. void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
  3076. TemplateSpecializationKind TSK) {
  3077. assert(!SpecializationInfo && "Member enum is already a specialization");
  3078. SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
  3079. }
  3080. //===----------------------------------------------------------------------===//
  3081. // RecordDecl Implementation
  3082. //===----------------------------------------------------------------------===//
  3083. RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
  3084. DeclContext *DC, SourceLocation StartLoc,
  3085. SourceLocation IdLoc, IdentifierInfo *Id,
  3086. RecordDecl *PrevDecl)
  3087. : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
  3088. HasFlexibleArrayMember = false;
  3089. AnonymousStructOrUnion = false;
  3090. HasObjectMember = false;
  3091. HasVolatileMember = false;
  3092. LoadedFieldsFromExternalStorage = false;
  3093. assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
  3094. }
  3095. RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
  3096. SourceLocation StartLoc, SourceLocation IdLoc,
  3097. IdentifierInfo *Id, RecordDecl* PrevDecl) {
  3098. RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
  3099. StartLoc, IdLoc, Id, PrevDecl);
  3100. R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
  3101. C.getTypeDeclType(R, PrevDecl);
  3102. return R;
  3103. }
  3104. RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
  3105. RecordDecl *R =
  3106. new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
  3107. SourceLocation(), nullptr, nullptr);
  3108. R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
  3109. return R;
  3110. }
  3111. bool RecordDecl::isInjectedClassName() const {
  3112. return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
  3113. cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
  3114. }
  3115. bool RecordDecl::isLambda() const {
  3116. if (auto RD = dyn_cast<CXXRecordDecl>(this))
  3117. return RD->isLambda();
  3118. return false;
  3119. }
  3120. bool RecordDecl::isCapturedRecord() const {
  3121. return hasAttr<CapturedRecordAttr>();
  3122. }
  3123. void RecordDecl::setCapturedRecord() {
  3124. addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
  3125. }
  3126. RecordDecl::field_iterator RecordDecl::field_begin() const {
  3127. if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
  3128. LoadFieldsFromExternalStorage();
  3129. return field_iterator(decl_iterator(FirstDecl));
  3130. }
  3131. /// completeDefinition - Notes that the definition of this type is now
  3132. /// complete.
  3133. void RecordDecl::completeDefinition() {
  3134. assert(!isCompleteDefinition() && "Cannot redefine record!");
  3135. TagDecl::completeDefinition();
  3136. }
  3137. /// isMsStruct - Get whether or not this record uses ms_struct layout.
  3138. /// This which can be turned on with an attribute, pragma, or the
  3139. /// -mms-bitfields command-line option.
  3140. bool RecordDecl::isMsStruct(const ASTContext &C) const {
  3141. return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
  3142. }
  3143. static bool isFieldOrIndirectField(Decl::Kind K) {
  3144. return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
  3145. }
  3146. void RecordDecl::LoadFieldsFromExternalStorage() const {
  3147. ExternalASTSource *Source = getASTContext().getExternalSource();
  3148. assert(hasExternalLexicalStorage() && Source && "No external storage?");
  3149. // Notify that we have a RecordDecl doing some initialization.
  3150. ExternalASTSource::Deserializing TheFields(Source);
  3151. SmallVector<Decl*, 64> Decls;
  3152. LoadedFieldsFromExternalStorage = true;
  3153. switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
  3154. Decls)) {
  3155. case ELR_Success:
  3156. break;
  3157. case ELR_AlreadyLoaded:
  3158. case ELR_Failure:
  3159. return;
  3160. }
  3161. #ifndef NDEBUG
  3162. // Check that all decls we got were FieldDecls.
  3163. for (unsigned i=0, e=Decls.size(); i != e; ++i)
  3164. assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
  3165. #endif
  3166. if (Decls.empty())
  3167. return;
  3168. std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
  3169. /*FieldsAlreadyLoaded=*/false);
  3170. }
  3171. bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
  3172. ASTContext &Context = getASTContext();
  3173. if (!Context.getLangOpts().Sanitize.hasOneOf(
  3174. SanitizerKind::Address | SanitizerKind::KernelAddress) ||
  3175. !Context.getLangOpts().SanitizeAddressFieldPadding)
  3176. return false;
  3177. const auto &Blacklist = Context.getSanitizerBlacklist();
  3178. const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this);
  3179. // We may be able to relax some of these requirements.
  3180. int ReasonToReject = -1;
  3181. if (!CXXRD || CXXRD->isExternCContext())
  3182. ReasonToReject = 0; // is not C++.
  3183. else if (CXXRD->hasAttr<PackedAttr>())
  3184. ReasonToReject = 1; // is packed.
  3185. else if (CXXRD->isUnion())
  3186. ReasonToReject = 2; // is a union.
  3187. else if (CXXRD->isTriviallyCopyable())
  3188. ReasonToReject = 3; // is trivially copyable.
  3189. else if (CXXRD->hasTrivialDestructor())
  3190. ReasonToReject = 4; // has trivial destructor.
  3191. else if (CXXRD->isStandardLayout())
  3192. ReasonToReject = 5; // is standard layout.
  3193. else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding"))
  3194. ReasonToReject = 6; // is in a blacklisted file.
  3195. else if (Blacklist.isBlacklistedType(getQualifiedNameAsString(),
  3196. "field-padding"))
  3197. ReasonToReject = 7; // is blacklisted.
  3198. if (EmitRemark) {
  3199. if (ReasonToReject >= 0)
  3200. Context.getDiagnostics().Report(
  3201. getLocation(),
  3202. diag::remark_sanitize_address_insert_extra_padding_rejected)
  3203. << getQualifiedNameAsString() << ReasonToReject;
  3204. else
  3205. Context.getDiagnostics().Report(
  3206. getLocation(),
  3207. diag::remark_sanitize_address_insert_extra_padding_accepted)
  3208. << getQualifiedNameAsString();
  3209. }
  3210. return ReasonToReject < 0;
  3211. }
  3212. const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
  3213. for (const auto *I : fields()) {
  3214. if (I->getIdentifier())
  3215. return I;
  3216. if (const RecordType *RT = I->getType()->getAs<RecordType>())
  3217. if (const FieldDecl *NamedDataMember =
  3218. RT->getDecl()->findFirstNamedDataMember())
  3219. return NamedDataMember;
  3220. }
  3221. // We didn't find a named data member.
  3222. return nullptr;
  3223. }
  3224. //===----------------------------------------------------------------------===//
  3225. // BlockDecl Implementation
  3226. //===----------------------------------------------------------------------===//
  3227. void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
  3228. assert(!ParamInfo && "Already has param info!");
  3229. // Zero params -> null pointer.
  3230. if (!NewParamInfo.empty()) {
  3231. NumParams = NewParamInfo.size();
  3232. ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
  3233. std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
  3234. }
  3235. }
  3236. void BlockDecl::setCaptures(ASTContext &Context,
  3237. const Capture *begin,
  3238. const Capture *end,
  3239. bool capturesCXXThis) {
  3240. CapturesCXXThis = capturesCXXThis;
  3241. if (begin == end) {
  3242. NumCaptures = 0;
  3243. Captures = nullptr;
  3244. return;
  3245. }
  3246. NumCaptures = end - begin;
  3247. // Avoid new Capture[] because we don't want to provide a default
  3248. // constructor.
  3249. size_t allocationSize = NumCaptures * sizeof(Capture);
  3250. void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
  3251. memcpy(buffer, begin, allocationSize);
  3252. Captures = static_cast<Capture*>(buffer);
  3253. }
  3254. bool BlockDecl::capturesVariable(const VarDecl *variable) const {
  3255. for (const auto &I : captures())
  3256. // Only auto vars can be captured, so no redeclaration worries.
  3257. if (I.getVariable() == variable)
  3258. return true;
  3259. return false;
  3260. }
  3261. SourceRange BlockDecl::getSourceRange() const {
  3262. return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
  3263. }
  3264. //===----------------------------------------------------------------------===//
  3265. // Other Decl Allocation/Deallocation Method Implementations
  3266. //===----------------------------------------------------------------------===//
  3267. void TranslationUnitDecl::anchor() { }
  3268. TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
  3269. return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
  3270. }
  3271. void ExternCContextDecl::anchor() { }
  3272. ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
  3273. TranslationUnitDecl *DC) {
  3274. return new (C, DC) ExternCContextDecl(DC);
  3275. }
  3276. void LabelDecl::anchor() { }
  3277. LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
  3278. SourceLocation IdentL, IdentifierInfo *II) {
  3279. return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
  3280. }
  3281. LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
  3282. SourceLocation IdentL, IdentifierInfo *II,
  3283. SourceLocation GnuLabelL) {
  3284. assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
  3285. return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
  3286. }
  3287. LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3288. return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
  3289. SourceLocation());
  3290. }
  3291. void LabelDecl::setMSAsmLabel(StringRef Name) {
  3292. char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
  3293. memcpy(Buffer, Name.data(), Name.size());
  3294. Buffer[Name.size()] = '\0';
  3295. MSAsmName = Buffer;
  3296. }
  3297. void ValueDecl::anchor() { }
  3298. bool ValueDecl::isWeak() const {
  3299. for (const auto *I : attrs())
  3300. if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
  3301. return true;
  3302. return isWeakImported();
  3303. }
  3304. void ImplicitParamDecl::anchor() { }
  3305. ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
  3306. SourceLocation IdLoc,
  3307. IdentifierInfo *Id,
  3308. QualType Type) {
  3309. return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type);
  3310. }
  3311. ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
  3312. unsigned ID) {
  3313. return new (C, ID) ImplicitParamDecl(C, nullptr, SourceLocation(), nullptr,
  3314. QualType());
  3315. }
  3316. FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
  3317. SourceLocation StartLoc,
  3318. const DeclarationNameInfo &NameInfo,
  3319. QualType T, TypeSourceInfo *TInfo,
  3320. StorageClass SC,
  3321. bool isInlineSpecified,
  3322. bool hasWrittenPrototype,
  3323. bool isConstexprSpecified) {
  3324. FunctionDecl *New =
  3325. new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
  3326. SC, isInlineSpecified, isConstexprSpecified);
  3327. New->HasWrittenPrototype = hasWrittenPrototype;
  3328. return New;
  3329. }
  3330. FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3331. return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
  3332. DeclarationNameInfo(), QualType(), nullptr,
  3333. SC_None, false, false);
  3334. }
  3335. BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
  3336. return new (C, DC) BlockDecl(DC, L);
  3337. }
  3338. BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3339. return new (C, ID) BlockDecl(nullptr, SourceLocation());
  3340. }
  3341. CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
  3342. unsigned NumParams) {
  3343. return new (C, DC, NumParams * sizeof(ImplicitParamDecl *))
  3344. CapturedDecl(DC, NumParams);
  3345. }
  3346. CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
  3347. unsigned NumParams) {
  3348. return new (C, ID, NumParams * sizeof(ImplicitParamDecl *))
  3349. CapturedDecl(nullptr, NumParams);
  3350. }
  3351. EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
  3352. SourceLocation L,
  3353. IdentifierInfo *Id, QualType T,
  3354. Expr *E, const llvm::APSInt &V) {
  3355. return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
  3356. }
  3357. EnumConstantDecl *
  3358. EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3359. return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
  3360. QualType(), nullptr, llvm::APSInt());
  3361. }
  3362. void IndirectFieldDecl::anchor() { }
  3363. IndirectFieldDecl *
  3364. IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
  3365. IdentifierInfo *Id, QualType T, NamedDecl **CH,
  3366. unsigned CHS) {
  3367. return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
  3368. }
  3369. IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
  3370. unsigned ID) {
  3371. return new (C, ID) IndirectFieldDecl(nullptr, SourceLocation(),
  3372. DeclarationName(), QualType(), nullptr,
  3373. 0);
  3374. }
  3375. SourceRange EnumConstantDecl::getSourceRange() const {
  3376. SourceLocation End = getLocation();
  3377. if (Init)
  3378. End = Init->getLocEnd();
  3379. return SourceRange(getLocation(), End);
  3380. }
  3381. void TypeDecl::anchor() { }
  3382. TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
  3383. SourceLocation StartLoc, SourceLocation IdLoc,
  3384. IdentifierInfo *Id, TypeSourceInfo *TInfo) {
  3385. return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
  3386. }
  3387. void TypedefNameDecl::anchor() { }
  3388. TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
  3389. if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
  3390. auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
  3391. auto *ThisTypedef = this;
  3392. if (AnyRedecl && OwningTypedef) {
  3393. OwningTypedef = OwningTypedef->getCanonicalDecl();
  3394. ThisTypedef = ThisTypedef->getCanonicalDecl();
  3395. }
  3396. if (OwningTypedef == ThisTypedef)
  3397. return TT->getDecl();
  3398. }
  3399. return nullptr;
  3400. }
  3401. TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3402. return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
  3403. nullptr, nullptr);
  3404. }
  3405. TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
  3406. SourceLocation StartLoc,
  3407. SourceLocation IdLoc, IdentifierInfo *Id,
  3408. TypeSourceInfo *TInfo) {
  3409. return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
  3410. }
  3411. TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3412. return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
  3413. SourceLocation(), nullptr, nullptr);
  3414. }
  3415. SourceRange TypedefDecl::getSourceRange() const {
  3416. SourceLocation RangeEnd = getLocation();
  3417. if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
  3418. if (typeIsPostfix(TInfo->getType()))
  3419. RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
  3420. }
  3421. return SourceRange(getLocStart(), RangeEnd);
  3422. }
  3423. SourceRange TypeAliasDecl::getSourceRange() const {
  3424. SourceLocation RangeEnd = getLocStart();
  3425. if (TypeSourceInfo *TInfo = getTypeSourceInfo())
  3426. RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
  3427. return SourceRange(getLocStart(), RangeEnd);
  3428. }
  3429. void FileScopeAsmDecl::anchor() { }
  3430. FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
  3431. StringLiteral *Str,
  3432. SourceLocation AsmLoc,
  3433. SourceLocation RParenLoc) {
  3434. return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
  3435. }
  3436. FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
  3437. unsigned ID) {
  3438. return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
  3439. SourceLocation());
  3440. }
  3441. void EmptyDecl::anchor() {}
  3442. EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
  3443. return new (C, DC) EmptyDecl(DC, L);
  3444. }
  3445. EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
  3446. return new (C, ID) EmptyDecl(nullptr, SourceLocation());
  3447. }
  3448. //===----------------------------------------------------------------------===//
  3449. // ImportDecl Implementation
  3450. //===----------------------------------------------------------------------===//
  3451. /// \brief Retrieve the number of module identifiers needed to name the given
  3452. /// module.
  3453. static unsigned getNumModuleIdentifiers(Module *Mod) {
  3454. unsigned Result = 1;
  3455. while (Mod->Parent) {
  3456. Mod = Mod->Parent;
  3457. ++Result;
  3458. }
  3459. return Result;
  3460. }
  3461. ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
  3462. Module *Imported,
  3463. ArrayRef<SourceLocation> IdentifierLocs)
  3464. : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
  3465. NextLocalImport()
  3466. {
  3467. assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
  3468. SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
  3469. memcpy(StoredLocs, IdentifierLocs.data(),
  3470. IdentifierLocs.size() * sizeof(SourceLocation));
  3471. }
  3472. ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
  3473. Module *Imported, SourceLocation EndLoc)
  3474. : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
  3475. NextLocalImport()
  3476. {
  3477. *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
  3478. }
  3479. ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
  3480. SourceLocation StartLoc, Module *Imported,
  3481. ArrayRef<SourceLocation> IdentifierLocs) {
  3482. return new (C, DC, IdentifierLocs.size() * sizeof(SourceLocation))
  3483. ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
  3484. }
  3485. ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
  3486. SourceLocation StartLoc,
  3487. Module *Imported,
  3488. SourceLocation EndLoc) {
  3489. ImportDecl *Import =
  3490. new (C, DC, sizeof(SourceLocation)) ImportDecl(DC, StartLoc,
  3491. Imported, EndLoc);
  3492. Import->setImplicit();
  3493. return Import;
  3494. }
  3495. ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
  3496. unsigned NumLocations) {
  3497. return new (C, ID, NumLocations * sizeof(SourceLocation))
  3498. ImportDecl(EmptyShell());
  3499. }
  3500. ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
  3501. if (!ImportedAndComplete.getInt())
  3502. return None;
  3503. const SourceLocation *StoredLocs
  3504. = reinterpret_cast<const SourceLocation *>(this + 1);
  3505. return llvm::makeArrayRef(StoredLocs,
  3506. getNumModuleIdentifiers(getImportedModule()));
  3507. }
  3508. SourceRange ImportDecl::getSourceRange() const {
  3509. if (!ImportedAndComplete.getInt())
  3510. return SourceRange(getLocation(),
  3511. *reinterpret_cast<const SourceLocation *>(this + 1));
  3512. return SourceRange(getLocation(), getIdentifierLocs().back());
  3513. }