Decl.cpp 172 KB

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