Decl.cpp 185 KB

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