ClangAttrEmitter.cpp 174 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845
  1. //===- ClangAttrEmitter.cpp - Generate Clang attribute handling =-*- C++ -*--=//
  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. // These tablegen backends emit Clang attribute processing code
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "TableGenBackends.h"
  13. #include "ASTTableGen.h"
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/DenseSet.h"
  17. #include "llvm/ADT/MapVector.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/SmallString.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/ADT/StringSet.h"
  23. #include "llvm/ADT/StringSwitch.h"
  24. #include "llvm/ADT/iterator_range.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include "llvm/TableGen/Error.h"
  28. #include "llvm/TableGen/Record.h"
  29. #include "llvm/TableGen/StringMatcher.h"
  30. #include "llvm/TableGen/TableGenBackend.h"
  31. #include <algorithm>
  32. #include <cassert>
  33. #include <cctype>
  34. #include <cstddef>
  35. #include <cstdint>
  36. #include <map>
  37. #include <memory>
  38. #include <optional>
  39. #include <set>
  40. #include <sstream>
  41. #include <string>
  42. #include <utility>
  43. #include <vector>
  44. using namespace llvm;
  45. namespace {
  46. class FlattenedSpelling {
  47. std::string V, N, NS;
  48. bool K = false;
  49. public:
  50. FlattenedSpelling(const std::string &Variety, const std::string &Name,
  51. const std::string &Namespace, bool KnownToGCC) :
  52. V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
  53. explicit FlattenedSpelling(const Record &Spelling)
  54. : V(std::string(Spelling.getValueAsString("Variety"))),
  55. N(std::string(Spelling.getValueAsString("Name"))) {
  56. assert(V != "GCC" && V != "Clang" &&
  57. "Given a GCC spelling, which means this hasn't been flattened!");
  58. if (V == "CXX11" || V == "C2x" || V == "Pragma")
  59. NS = std::string(Spelling.getValueAsString("Namespace"));
  60. }
  61. const std::string &variety() const { return V; }
  62. const std::string &name() const { return N; }
  63. const std::string &nameSpace() const { return NS; }
  64. bool knownToGCC() const { return K; }
  65. };
  66. } // end anonymous namespace
  67. static std::vector<FlattenedSpelling>
  68. GetFlattenedSpellings(const Record &Attr) {
  69. std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
  70. std::vector<FlattenedSpelling> Ret;
  71. for (const auto &Spelling : Spellings) {
  72. StringRef Variety = Spelling->getValueAsString("Variety");
  73. StringRef Name = Spelling->getValueAsString("Name");
  74. if (Variety == "GCC") {
  75. Ret.emplace_back("GNU", std::string(Name), "", true);
  76. Ret.emplace_back("CXX11", std::string(Name), "gnu", true);
  77. if (Spelling->getValueAsBit("AllowInC"))
  78. Ret.emplace_back("C2x", std::string(Name), "gnu", true);
  79. } else if (Variety == "Clang") {
  80. Ret.emplace_back("GNU", std::string(Name), "", false);
  81. Ret.emplace_back("CXX11", std::string(Name), "clang", false);
  82. if (Spelling->getValueAsBit("AllowInC"))
  83. Ret.emplace_back("C2x", std::string(Name), "clang", false);
  84. } else
  85. Ret.push_back(FlattenedSpelling(*Spelling));
  86. }
  87. return Ret;
  88. }
  89. static std::string ReadPCHRecord(StringRef type) {
  90. return StringSwitch<std::string>(type)
  91. .EndsWith("Decl *", "Record.GetLocalDeclAs<" +
  92. std::string(type.data(), 0, type.size() - 1) +
  93. ">(Record.readInt())")
  94. .Case("TypeSourceInfo *", "Record.readTypeSourceInfo()")
  95. .Case("Expr *", "Record.readExpr()")
  96. .Case("IdentifierInfo *", "Record.readIdentifier()")
  97. .Case("StringRef", "Record.readString()")
  98. .Case("ParamIdx", "ParamIdx::deserialize(Record.readInt())")
  99. .Case("OMPTraitInfo *", "Record.readOMPTraitInfo()")
  100. .Default("Record.readInt()");
  101. }
  102. // Get a type that is suitable for storing an object of the specified type.
  103. static StringRef getStorageType(StringRef type) {
  104. return StringSwitch<StringRef>(type)
  105. .Case("StringRef", "std::string")
  106. .Default(type);
  107. }
  108. // Assumes that the way to get the value is SA->getname()
  109. static std::string WritePCHRecord(StringRef type, StringRef name) {
  110. return "Record." +
  111. StringSwitch<std::string>(type)
  112. .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + ");\n")
  113. .Case("TypeSourceInfo *",
  114. "AddTypeSourceInfo(" + std::string(name) + ");\n")
  115. .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
  116. .Case("IdentifierInfo *",
  117. "AddIdentifierRef(" + std::string(name) + ");\n")
  118. .Case("StringRef", "AddString(" + std::string(name) + ");\n")
  119. .Case("ParamIdx",
  120. "push_back(" + std::string(name) + ".serialize());\n")
  121. .Case("OMPTraitInfo *",
  122. "writeOMPTraitInfo(" + std::string(name) + ");\n")
  123. .Default("push_back(" + std::string(name) + ");\n");
  124. }
  125. // Normalize attribute name by removing leading and trailing
  126. // underscores. For example, __foo, foo__, __foo__ would
  127. // become foo.
  128. static StringRef NormalizeAttrName(StringRef AttrName) {
  129. AttrName.consume_front("__");
  130. AttrName.consume_back("__");
  131. return AttrName;
  132. }
  133. // Normalize the name by removing any and all leading and trailing underscores.
  134. // This is different from NormalizeAttrName in that it also handles names like
  135. // _pascal and __pascal.
  136. static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
  137. return Name.trim("_");
  138. }
  139. // Normalize the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
  140. // removing "__" if it appears at the beginning and end of the attribute's name.
  141. static StringRef NormalizeGNUAttrSpelling(StringRef AttrSpelling) {
  142. if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
  143. AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
  144. }
  145. return AttrSpelling;
  146. }
  147. typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
  148. static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
  149. ParsedAttrMap *Dupes = nullptr) {
  150. std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  151. std::set<std::string> Seen;
  152. ParsedAttrMap R;
  153. for (const auto *Attr : Attrs) {
  154. if (Attr->getValueAsBit("SemaHandler")) {
  155. std::string AN;
  156. if (Attr->isSubClassOf("TargetSpecificAttr") &&
  157. !Attr->isValueUnset("ParseKind")) {
  158. AN = std::string(Attr->getValueAsString("ParseKind"));
  159. // If this attribute has already been handled, it does not need to be
  160. // handled again.
  161. if (Seen.find(AN) != Seen.end()) {
  162. if (Dupes)
  163. Dupes->push_back(std::make_pair(AN, Attr));
  164. continue;
  165. }
  166. Seen.insert(AN);
  167. } else
  168. AN = NormalizeAttrName(Attr->getName()).str();
  169. R.push_back(std::make_pair(AN, Attr));
  170. }
  171. }
  172. return R;
  173. }
  174. namespace {
  175. class Argument {
  176. std::string lowerName, upperName;
  177. StringRef attrName;
  178. bool isOpt;
  179. bool Fake;
  180. public:
  181. Argument(StringRef Arg, StringRef Attr)
  182. : lowerName(std::string(Arg)), upperName(lowerName), attrName(Attr),
  183. isOpt(false), Fake(false) {
  184. if (!lowerName.empty()) {
  185. lowerName[0] = std::tolower(lowerName[0]);
  186. upperName[0] = std::toupper(upperName[0]);
  187. }
  188. // Work around MinGW's macro definition of 'interface' to 'struct'. We
  189. // have an attribute argument called 'Interface', so only the lower case
  190. // name conflicts with the macro definition.
  191. if (lowerName == "interface")
  192. lowerName = "interface_";
  193. }
  194. Argument(const Record &Arg, StringRef Attr)
  195. : Argument(Arg.getValueAsString("Name"), Attr) {}
  196. virtual ~Argument() = default;
  197. StringRef getLowerName() const { return lowerName; }
  198. StringRef getUpperName() const { return upperName; }
  199. StringRef getAttrName() const { return attrName; }
  200. bool isOptional() const { return isOpt; }
  201. void setOptional(bool set) { isOpt = set; }
  202. bool isFake() const { return Fake; }
  203. void setFake(bool fake) { Fake = fake; }
  204. // These functions print the argument contents formatted in different ways.
  205. virtual void writeAccessors(raw_ostream &OS) const = 0;
  206. virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
  207. virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
  208. virtual void writeCloneArgs(raw_ostream &OS) const = 0;
  209. virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
  210. virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
  211. virtual void writeCtorBody(raw_ostream &OS) const {}
  212. virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
  213. virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
  214. virtual void writeCtorParameters(raw_ostream &OS) const = 0;
  215. virtual void writeDeclarations(raw_ostream &OS) const = 0;
  216. virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
  217. virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
  218. virtual void writePCHWrite(raw_ostream &OS) const = 0;
  219. virtual std::string getIsOmitted() const { return "false"; }
  220. virtual void writeValue(raw_ostream &OS) const = 0;
  221. virtual void writeDump(raw_ostream &OS) const = 0;
  222. virtual void writeDumpChildren(raw_ostream &OS) const {}
  223. virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
  224. virtual bool isEnumArg() const { return false; }
  225. virtual bool isVariadicEnumArg() const { return false; }
  226. virtual bool isVariadic() const { return false; }
  227. virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
  228. OS << getUpperName();
  229. }
  230. };
  231. class SimpleArgument : public Argument {
  232. std::string type;
  233. public:
  234. SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
  235. : Argument(Arg, Attr), type(std::move(T)) {}
  236. std::string getType() const { return type; }
  237. void writeAccessors(raw_ostream &OS) const override {
  238. OS << " " << type << " get" << getUpperName() << "() const {\n";
  239. OS << " return " << getLowerName() << ";\n";
  240. OS << " }";
  241. }
  242. void writeCloneArgs(raw_ostream &OS) const override {
  243. OS << getLowerName();
  244. }
  245. void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
  246. OS << "A->get" << getUpperName() << "()";
  247. }
  248. void writeCtorInitializers(raw_ostream &OS) const override {
  249. OS << getLowerName() << "(" << getUpperName() << ")";
  250. }
  251. void writeCtorDefaultInitializers(raw_ostream &OS) const override {
  252. OS << getLowerName() << "()";
  253. }
  254. void writeCtorParameters(raw_ostream &OS) const override {
  255. OS << type << " " << getUpperName();
  256. }
  257. void writeDeclarations(raw_ostream &OS) const override {
  258. OS << type << " " << getLowerName() << ";";
  259. }
  260. void writePCHReadDecls(raw_ostream &OS) const override {
  261. std::string read = ReadPCHRecord(type);
  262. OS << " " << type << " " << getLowerName() << " = " << read << ";\n";
  263. }
  264. void writePCHReadArgs(raw_ostream &OS) const override {
  265. OS << getLowerName();
  266. }
  267. void writePCHWrite(raw_ostream &OS) const override {
  268. OS << " "
  269. << WritePCHRecord(type,
  270. "SA->get" + std::string(getUpperName()) + "()");
  271. }
  272. std::string getIsOmitted() const override {
  273. if (type == "IdentifierInfo *")
  274. return "!get" + getUpperName().str() + "()";
  275. if (type == "TypeSourceInfo *")
  276. return "!get" + getUpperName().str() + "Loc()";
  277. if (type == "ParamIdx")
  278. return "!get" + getUpperName().str() + "().isValid()";
  279. return "false";
  280. }
  281. void writeValue(raw_ostream &OS) const override {
  282. if (type == "FunctionDecl *")
  283. OS << "\" << get" << getUpperName()
  284. << "()->getNameInfo().getAsString() << \"";
  285. else if (type == "IdentifierInfo *")
  286. // Some non-optional (comma required) identifier arguments can be the
  287. // empty string but are then recorded as a nullptr.
  288. OS << "\" << (get" << getUpperName() << "() ? get" << getUpperName()
  289. << "()->getName() : \"\") << \"";
  290. else if (type == "VarDecl *")
  291. OS << "\" << get" << getUpperName() << "()->getName() << \"";
  292. else if (type == "TypeSourceInfo *")
  293. OS << "\" << get" << getUpperName() << "().getAsString() << \"";
  294. else if (type == "ParamIdx")
  295. OS << "\" << get" << getUpperName() << "().getSourceIndex() << \"";
  296. else
  297. OS << "\" << get" << getUpperName() << "() << \"";
  298. }
  299. void writeDump(raw_ostream &OS) const override {
  300. if (StringRef(type).endswith("Decl *")) {
  301. OS << " OS << \" \";\n";
  302. OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
  303. } else if (type == "IdentifierInfo *") {
  304. // Some non-optional (comma required) identifier arguments can be the
  305. // empty string but are then recorded as a nullptr.
  306. OS << " if (SA->get" << getUpperName() << "())\n"
  307. << " OS << \" \" << SA->get" << getUpperName()
  308. << "()->getName();\n";
  309. } else if (type == "TypeSourceInfo *") {
  310. if (isOptional())
  311. OS << " if (SA->get" << getUpperName() << "Loc())";
  312. OS << " OS << \" \" << SA->get" << getUpperName()
  313. << "().getAsString();\n";
  314. } else if (type == "bool") {
  315. OS << " if (SA->get" << getUpperName() << "()) OS << \" "
  316. << getUpperName() << "\";\n";
  317. } else if (type == "int" || type == "unsigned") {
  318. OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
  319. } else if (type == "ParamIdx") {
  320. if (isOptional())
  321. OS << " if (SA->get" << getUpperName() << "().isValid())\n ";
  322. OS << " OS << \" \" << SA->get" << getUpperName()
  323. << "().getSourceIndex();\n";
  324. } else if (type == "OMPTraitInfo *") {
  325. OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
  326. } else {
  327. llvm_unreachable("Unknown SimpleArgument type!");
  328. }
  329. }
  330. };
  331. class DefaultSimpleArgument : public SimpleArgument {
  332. int64_t Default;
  333. public:
  334. DefaultSimpleArgument(const Record &Arg, StringRef Attr,
  335. std::string T, int64_t Default)
  336. : SimpleArgument(Arg, Attr, T), Default(Default) {}
  337. void writeAccessors(raw_ostream &OS) const override {
  338. SimpleArgument::writeAccessors(OS);
  339. OS << "\n\n static const " << getType() << " Default" << getUpperName()
  340. << " = ";
  341. if (getType() == "bool")
  342. OS << (Default != 0 ? "true" : "false");
  343. else
  344. OS << Default;
  345. OS << ";";
  346. }
  347. };
  348. class StringArgument : public Argument {
  349. public:
  350. StringArgument(const Record &Arg, StringRef Attr)
  351. : Argument(Arg, Attr)
  352. {}
  353. void writeAccessors(raw_ostream &OS) const override {
  354. OS << " llvm::StringRef get" << getUpperName() << "() const {\n";
  355. OS << " return llvm::StringRef(" << getLowerName() << ", "
  356. << getLowerName() << "Length);\n";
  357. OS << " }\n";
  358. OS << " unsigned get" << getUpperName() << "Length() const {\n";
  359. OS << " return " << getLowerName() << "Length;\n";
  360. OS << " }\n";
  361. OS << " void set" << getUpperName()
  362. << "(ASTContext &C, llvm::StringRef S) {\n";
  363. OS << " " << getLowerName() << "Length = S.size();\n";
  364. OS << " this->" << getLowerName() << " = new (C, 1) char ["
  365. << getLowerName() << "Length];\n";
  366. OS << " if (!S.empty())\n";
  367. OS << " std::memcpy(this->" << getLowerName() << ", S.data(), "
  368. << getLowerName() << "Length);\n";
  369. OS << " }";
  370. }
  371. void writeCloneArgs(raw_ostream &OS) const override {
  372. OS << "get" << getUpperName() << "()";
  373. }
  374. void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
  375. OS << "A->get" << getUpperName() << "()";
  376. }
  377. void writeCtorBody(raw_ostream &OS) const override {
  378. OS << " if (!" << getUpperName() << ".empty())\n";
  379. OS << " std::memcpy(" << getLowerName() << ", " << getUpperName()
  380. << ".data(), " << getLowerName() << "Length);\n";
  381. }
  382. void writeCtorInitializers(raw_ostream &OS) const override {
  383. OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
  384. << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
  385. << "Length])";
  386. }
  387. void writeCtorDefaultInitializers(raw_ostream &OS) const override {
  388. OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
  389. }
  390. void writeCtorParameters(raw_ostream &OS) const override {
  391. OS << "llvm::StringRef " << getUpperName();
  392. }
  393. void writeDeclarations(raw_ostream &OS) const override {
  394. OS << "unsigned " << getLowerName() << "Length;\n";
  395. OS << "char *" << getLowerName() << ";";
  396. }
  397. void writePCHReadDecls(raw_ostream &OS) const override {
  398. OS << " std::string " << getLowerName()
  399. << "= Record.readString();\n";
  400. }
  401. void writePCHReadArgs(raw_ostream &OS) const override {
  402. OS << getLowerName();
  403. }
  404. void writePCHWrite(raw_ostream &OS) const override {
  405. OS << " Record.AddString(SA->get" << getUpperName() << "());\n";
  406. }
  407. void writeValue(raw_ostream &OS) const override {
  408. OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
  409. }
  410. void writeDump(raw_ostream &OS) const override {
  411. OS << " OS << \" \\\"\" << SA->get" << getUpperName()
  412. << "() << \"\\\"\";\n";
  413. }
  414. };
  415. class AlignedArgument : public Argument {
  416. public:
  417. AlignedArgument(const Record &Arg, StringRef Attr)
  418. : Argument(Arg, Attr)
  419. {}
  420. void writeAccessors(raw_ostream &OS) const override {
  421. OS << " bool is" << getUpperName() << "Dependent() const;\n";
  422. OS << " bool is" << getUpperName() << "ErrorDependent() const;\n";
  423. OS << " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
  424. OS << " bool is" << getUpperName() << "Expr() const {\n";
  425. OS << " return is" << getLowerName() << "Expr;\n";
  426. OS << " }\n";
  427. OS << " Expr *get" << getUpperName() << "Expr() const {\n";
  428. OS << " assert(is" << getLowerName() << "Expr);\n";
  429. OS << " return " << getLowerName() << "Expr;\n";
  430. OS << " }\n";
  431. OS << " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
  432. OS << " assert(!is" << getLowerName() << "Expr);\n";
  433. OS << " return " << getLowerName() << "Type;\n";
  434. OS << " }";
  435. }
  436. void writeAccessorDefinitions(raw_ostream &OS) const override {
  437. OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
  438. << "Dependent() const {\n";
  439. OS << " if (is" << getLowerName() << "Expr)\n";
  440. OS << " return " << getLowerName() << "Expr && (" << getLowerName()
  441. << "Expr->isValueDependent() || " << getLowerName()
  442. << "Expr->isTypeDependent());\n";
  443. OS << " else\n";
  444. OS << " return " << getLowerName()
  445. << "Type->getType()->isDependentType();\n";
  446. OS << "}\n";
  447. OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
  448. << "ErrorDependent() const {\n";
  449. OS << " if (is" << getLowerName() << "Expr)\n";
  450. OS << " return " << getLowerName() << "Expr && " << getLowerName()
  451. << "Expr->containsErrors();\n";
  452. OS << " return " << getLowerName()
  453. << "Type->getType()->containsErrors();\n";
  454. OS << "}\n";
  455. // FIXME: Do not do the calculation here
  456. // FIXME: Handle types correctly
  457. // A null pointer means maximum alignment
  458. OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
  459. << "(ASTContext &Ctx) const {\n";
  460. OS << " assert(!is" << getUpperName() << "Dependent());\n";
  461. OS << " if (is" << getLowerName() << "Expr)\n";
  462. OS << " return " << getLowerName() << "Expr ? " << getLowerName()
  463. << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue()"
  464. << " * Ctx.getCharWidth() : "
  465. << "Ctx.getTargetDefaultAlignForAttributeAligned();\n";
  466. OS << " else\n";
  467. OS << " return 0; // FIXME\n";
  468. OS << "}\n";
  469. }
  470. void writeASTVisitorTraversal(raw_ostream &OS) const override {
  471. StringRef Name = getUpperName();
  472. OS << " if (A->is" << Name << "Expr()) {\n"
  473. << " if (!getDerived().TraverseStmt(A->get" << Name << "Expr()))\n"
  474. << " return false;\n"
  475. << " } else if (auto *TSI = A->get" << Name << "Type()) {\n"
  476. << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
  477. << " return false;\n"
  478. << " }\n";
  479. }
  480. void writeCloneArgs(raw_ostream &OS) const override {
  481. OS << "is" << getLowerName() << "Expr, is" << getLowerName()
  482. << "Expr ? static_cast<void*>(" << getLowerName()
  483. << "Expr) : " << getLowerName()
  484. << "Type";
  485. }
  486. void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
  487. // FIXME: move the definition in Sema::InstantiateAttrs to here.
  488. // In the meantime, aligned attributes are cloned.
  489. }
  490. void writeCtorBody(raw_ostream &OS) const override {
  491. OS << " if (is" << getLowerName() << "Expr)\n";
  492. OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
  493. << getUpperName() << ");\n";
  494. OS << " else\n";
  495. OS << " " << getLowerName()
  496. << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
  497. << ");\n";
  498. }
  499. void writeCtorInitializers(raw_ostream &OS) const override {
  500. OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
  501. }
  502. void writeCtorDefaultInitializers(raw_ostream &OS) const override {
  503. OS << "is" << getLowerName() << "Expr(false)";
  504. }
  505. void writeCtorParameters(raw_ostream &OS) const override {
  506. OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
  507. }
  508. void writeImplicitCtorArgs(raw_ostream &OS) const override {
  509. OS << "Is" << getUpperName() << "Expr, " << getUpperName();
  510. }
  511. void writeDeclarations(raw_ostream &OS) const override {
  512. OS << "bool is" << getLowerName() << "Expr;\n";
  513. OS << "union {\n";
  514. OS << "Expr *" << getLowerName() << "Expr;\n";
  515. OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
  516. OS << "};";
  517. }
  518. void writePCHReadArgs(raw_ostream &OS) const override {
  519. OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
  520. }
  521. void writePCHReadDecls(raw_ostream &OS) const override {
  522. OS << " bool is" << getLowerName() << "Expr = Record.readInt();\n";
  523. OS << " void *" << getLowerName() << "Ptr;\n";
  524. OS << " if (is" << getLowerName() << "Expr)\n";
  525. OS << " " << getLowerName() << "Ptr = Record.readExpr();\n";
  526. OS << " else\n";
  527. OS << " " << getLowerName()
  528. << "Ptr = Record.readTypeSourceInfo();\n";
  529. }
  530. void writePCHWrite(raw_ostream &OS) const override {
  531. OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
  532. OS << " if (SA->is" << getUpperName() << "Expr())\n";
  533. OS << " Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
  534. OS << " else\n";
  535. OS << " Record.AddTypeSourceInfo(SA->get" << getUpperName()
  536. << "Type());\n";
  537. }
  538. std::string getIsOmitted() const override {
  539. return "!is" + getLowerName().str() + "Expr || !" + getLowerName().str()
  540. + "Expr";
  541. }
  542. void writeValue(raw_ostream &OS) const override {
  543. OS << "\";\n";
  544. OS << " " << getLowerName()
  545. << "Expr->printPretty(OS, nullptr, Policy);\n";
  546. OS << " OS << \"";
  547. }
  548. void writeDump(raw_ostream &OS) const override {
  549. OS << " if (!SA->is" << getUpperName() << "Expr())\n";
  550. OS << " dumpType(SA->get" << getUpperName()
  551. << "Type()->getType());\n";
  552. }
  553. void writeDumpChildren(raw_ostream &OS) const override {
  554. OS << " if (SA->is" << getUpperName() << "Expr())\n";
  555. OS << " Visit(SA->get" << getUpperName() << "Expr());\n";
  556. }
  557. void writeHasChildren(raw_ostream &OS) const override {
  558. OS << "SA->is" << getUpperName() << "Expr()";
  559. }
  560. };
  561. class VariadicArgument : public Argument {
  562. std::string Type, ArgName, ArgSizeName, RangeName;
  563. protected:
  564. // Assumed to receive a parameter: raw_ostream OS.
  565. virtual void writeValueImpl(raw_ostream &OS) const {
  566. OS << " OS << Val;\n";
  567. }
  568. // Assumed to receive a parameter: raw_ostream OS.
  569. virtual void writeDumpImpl(raw_ostream &OS) const {
  570. OS << " OS << \" \" << Val;\n";
  571. }
  572. public:
  573. VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
  574. : Argument(Arg, Attr), Type(std::move(T)),
  575. ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
  576. RangeName(std::string(getLowerName())) {}
  577. VariadicArgument(StringRef Arg, StringRef Attr, std::string T)
  578. : Argument(Arg, Attr), Type(std::move(T)),
  579. ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
  580. RangeName(std::string(getLowerName())) {}
  581. const std::string &getType() const { return Type; }
  582. const std::string &getArgName() const { return ArgName; }
  583. const std::string &getArgSizeName() const { return ArgSizeName; }
  584. bool isVariadic() const override { return true; }
  585. void writeAccessors(raw_ostream &OS) const override {
  586. std::string IteratorType = getLowerName().str() + "_iterator";
  587. std::string BeginFn = getLowerName().str() + "_begin()";
  588. std::string EndFn = getLowerName().str() + "_end()";
  589. OS << " typedef " << Type << "* " << IteratorType << ";\n";
  590. OS << " " << IteratorType << " " << BeginFn << " const {"
  591. << " return " << ArgName << "; }\n";
  592. OS << " " << IteratorType << " " << EndFn << " const {"
  593. << " return " << ArgName << " + " << ArgSizeName << "; }\n";
  594. OS << " unsigned " << getLowerName() << "_size() const {"
  595. << " return " << ArgSizeName << "; }\n";
  596. OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName
  597. << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
  598. << "); }\n";
  599. }
  600. void writeSetter(raw_ostream &OS) const {
  601. OS << " void set" << getUpperName() << "(ASTContext &Ctx, ";
  602. writeCtorParameters(OS);
  603. OS << ") {\n";
  604. OS << " " << ArgSizeName << " = " << getUpperName() << "Size;\n";
  605. OS << " " << ArgName << " = new (Ctx, 16) " << getType() << "["
  606. << ArgSizeName << "];\n";
  607. OS << " ";
  608. writeCtorBody(OS);
  609. OS << " }\n";
  610. }
  611. void writeCloneArgs(raw_ostream &OS) const override {
  612. OS << ArgName << ", " << ArgSizeName;
  613. }
  614. void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
  615. // This isn't elegant, but we have to go through public methods...
  616. OS << "A->" << getLowerName() << "_begin(), "
  617. << "A->" << getLowerName() << "_size()";
  618. }
  619. void writeASTVisitorTraversal(raw_ostream &OS) const override {
  620. // FIXME: Traverse the elements.
  621. }
  622. void writeCtorBody(raw_ostream &OS) const override {
  623. OS << " std::copy(" << getUpperName() << ", " << getUpperName() << " + "
  624. << ArgSizeName << ", " << ArgName << ");\n";
  625. }
  626. void writeCtorInitializers(raw_ostream &OS) const override {
  627. OS << ArgSizeName << "(" << getUpperName() << "Size), "
  628. << ArgName << "(new (Ctx, 16) " << getType() << "["
  629. << ArgSizeName << "])";
  630. }
  631. void writeCtorDefaultInitializers(raw_ostream &OS) const override {
  632. OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
  633. }
  634. void writeCtorParameters(raw_ostream &OS) const override {
  635. OS << getType() << " *" << getUpperName() << ", unsigned "
  636. << getUpperName() << "Size";
  637. }
  638. void writeImplicitCtorArgs(raw_ostream &OS) const override {
  639. OS << getUpperName() << ", " << getUpperName() << "Size";
  640. }
  641. void writeDeclarations(raw_ostream &OS) const override {
  642. OS << " unsigned " << ArgSizeName << ";\n";
  643. OS << " " << getType() << " *" << ArgName << ";";
  644. }
  645. void writePCHReadDecls(raw_ostream &OS) const override {
  646. OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
  647. OS << " SmallVector<" << getType() << ", 4> "
  648. << getLowerName() << ";\n";
  649. OS << " " << getLowerName() << ".reserve(" << getLowerName()
  650. << "Size);\n";
  651. // If we can't store the values in the current type (if it's something
  652. // like StringRef), store them in a different type and convert the
  653. // container afterwards.
  654. std::string StorageType = std::string(getStorageType(getType()));
  655. std::string StorageName = std::string(getLowerName());
  656. if (StorageType != getType()) {
  657. StorageName += "Storage";
  658. OS << " SmallVector<" << StorageType << ", 4> "
  659. << StorageName << ";\n";
  660. OS << " " << StorageName << ".reserve(" << getLowerName()
  661. << "Size);\n";
  662. }
  663. OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
  664. std::string read = ReadPCHRecord(Type);
  665. OS << " " << StorageName << ".push_back(" << read << ");\n";
  666. if (StorageType != getType()) {
  667. OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
  668. OS << " " << getLowerName() << ".push_back("
  669. << StorageName << "[i]);\n";
  670. }
  671. }
  672. void writePCHReadArgs(raw_ostream &OS) const override {
  673. OS << getLowerName() << ".data(), " << getLowerName() << "Size";
  674. }
  675. void writePCHWrite(raw_ostream &OS) const override {
  676. OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
  677. OS << " for (auto &Val : SA->" << RangeName << "())\n";
  678. OS << " " << WritePCHRecord(Type, "Val");
  679. }
  680. void writeValue(raw_ostream &OS) const override {
  681. OS << "\";\n";
  682. OS << " for (const auto &Val : " << RangeName << "()) {\n"
  683. << " DelimitAttributeArgument(OS, IsFirstArgument);\n";
  684. writeValueImpl(OS);
  685. OS << " }\n";
  686. OS << " OS << \"";
  687. }
  688. void writeDump(raw_ostream &OS) const override {
  689. OS << " for (const auto &Val : SA->" << RangeName << "())\n";
  690. writeDumpImpl(OS);
  691. }
  692. };
  693. class VariadicOMPInteropInfoArgument : public VariadicArgument {
  694. public:
  695. VariadicOMPInteropInfoArgument(const Record &Arg, StringRef Attr)
  696. : VariadicArgument(Arg, Attr, "OMPInteropInfo") {}
  697. void writeDump(raw_ostream &OS) const override {
  698. OS << " for (" << getAttrName() << "Attr::" << getLowerName()
  699. << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
  700. << getLowerName() << "_end(); I != E; ++I) {\n";
  701. OS << " if (I->IsTarget && I->IsTargetSync)\n";
  702. OS << " OS << \" Target_TargetSync\";\n";
  703. OS << " else if (I->IsTarget)\n";
  704. OS << " OS << \" Target\";\n";
  705. OS << " else\n";
  706. OS << " OS << \" TargetSync\";\n";
  707. OS << " }\n";
  708. }
  709. void writePCHReadDecls(raw_ostream &OS) const override {
  710. OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
  711. OS << " SmallVector<OMPInteropInfo, 4> " << getLowerName() << ";\n";
  712. OS << " " << getLowerName() << ".reserve(" << getLowerName()
  713. << "Size);\n";
  714. OS << " for (unsigned I = 0, E = " << getLowerName() << "Size; ";
  715. OS << "I != E; ++I) {\n";
  716. OS << " bool IsTarget = Record.readBool();\n";
  717. OS << " bool IsTargetSync = Record.readBool();\n";
  718. OS << " " << getLowerName()
  719. << ".emplace_back(IsTarget, IsTargetSync);\n";
  720. OS << " }\n";
  721. }
  722. void writePCHWrite(raw_ostream &OS) const override {
  723. OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
  724. OS << " for (" << getAttrName() << "Attr::" << getLowerName()
  725. << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
  726. << getLowerName() << "_end(); I != E; ++I) {\n";
  727. OS << " Record.writeBool(I->IsTarget);\n";
  728. OS << " Record.writeBool(I->IsTargetSync);\n";
  729. OS << " }\n";
  730. }
  731. };
  732. class VariadicParamIdxArgument : public VariadicArgument {
  733. public:
  734. VariadicParamIdxArgument(const Record &Arg, StringRef Attr)
  735. : VariadicArgument(Arg, Attr, "ParamIdx") {}
  736. public:
  737. void writeValueImpl(raw_ostream &OS) const override {
  738. OS << " OS << Val.getSourceIndex();\n";
  739. }
  740. void writeDumpImpl(raw_ostream &OS) const override {
  741. OS << " OS << \" \" << Val.getSourceIndex();\n";
  742. }
  743. };
  744. struct VariadicParamOrParamIdxArgument : public VariadicArgument {
  745. VariadicParamOrParamIdxArgument(const Record &Arg, StringRef Attr)
  746. : VariadicArgument(Arg, Attr, "int") {}
  747. };
  748. // Unique the enums, but maintain the original declaration ordering.
  749. std::vector<StringRef>
  750. uniqueEnumsInOrder(const std::vector<StringRef> &enums) {
  751. std::vector<StringRef> uniques;
  752. SmallDenseSet<StringRef, 8> unique_set;
  753. for (const auto &i : enums) {
  754. if (unique_set.insert(i).second)
  755. uniques.push_back(i);
  756. }
  757. return uniques;
  758. }
  759. class EnumArgument : public Argument {
  760. std::string type;
  761. std::vector<StringRef> values, enums, uniques;
  762. public:
  763. EnumArgument(const Record &Arg, StringRef Attr)
  764. : Argument(Arg, Attr), type(std::string(Arg.getValueAsString("Type"))),
  765. values(Arg.getValueAsListOfStrings("Values")),
  766. enums(Arg.getValueAsListOfStrings("Enums")),
  767. uniques(uniqueEnumsInOrder(enums)) {
  768. // FIXME: Emit a proper error
  769. assert(!uniques.empty());
  770. }
  771. bool isEnumArg() const override { return true; }
  772. void writeAccessors(raw_ostream &OS) const override {
  773. OS << " " << type << " get" << getUpperName() << "() const {\n";
  774. OS << " return " << getLowerName() << ";\n";
  775. OS << " }";
  776. }
  777. void writeCloneArgs(raw_ostream &OS) const override {
  778. OS << getLowerName();
  779. }
  780. void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
  781. OS << "A->get" << getUpperName() << "()";
  782. }
  783. void writeCtorInitializers(raw_ostream &OS) const override {
  784. OS << getLowerName() << "(" << getUpperName() << ")";
  785. }
  786. void writeCtorDefaultInitializers(raw_ostream &OS) const override {
  787. OS << getLowerName() << "(" << type << "(0))";
  788. }
  789. void writeCtorParameters(raw_ostream &OS) const override {
  790. OS << type << " " << getUpperName();
  791. }
  792. void writeDeclarations(raw_ostream &OS) const override {
  793. auto i = uniques.cbegin(), e = uniques.cend();
  794. // The last one needs to not have a comma.
  795. --e;
  796. OS << "public:\n";
  797. OS << " enum " << type << " {\n";
  798. for (; i != e; ++i)
  799. OS << " " << *i << ",\n";
  800. OS << " " << *e << "\n";
  801. OS << " };\n";
  802. OS << "private:\n";
  803. OS << " " << type << " " << getLowerName() << ";";
  804. }
  805. void writePCHReadDecls(raw_ostream &OS) const override {
  806. OS << " " << getAttrName() << "Attr::" << type << " " << getLowerName()
  807. << "(static_cast<" << getAttrName() << "Attr::" << type
  808. << ">(Record.readInt()));\n";
  809. }
  810. void writePCHReadArgs(raw_ostream &OS) const override {
  811. OS << getLowerName();
  812. }
  813. void writePCHWrite(raw_ostream &OS) const override {
  814. OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
  815. }
  816. void writeValue(raw_ostream &OS) const override {
  817. // FIXME: this isn't 100% correct -- some enum arguments require printing
  818. // as a string literal, while others require printing as an identifier.
  819. // Tablegen currently does not distinguish between the two forms.
  820. OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
  821. << getUpperName() << "()) << \"\\\"";
  822. }
  823. void writeDump(raw_ostream &OS) const override {
  824. OS << " switch(SA->get" << getUpperName() << "()) {\n";
  825. for (const auto &I : uniques) {
  826. OS << " case " << getAttrName() << "Attr::" << I << ":\n";
  827. OS << " OS << \" " << I << "\";\n";
  828. OS << " break;\n";
  829. }
  830. OS << " }\n";
  831. }
  832. void writeConversion(raw_ostream &OS, bool Header) const {
  833. if (Header) {
  834. OS << " static bool ConvertStrTo" << type << "(StringRef Val, " << type
  835. << " &Out);\n";
  836. OS << " static const char *Convert" << type << "ToStr(" << type
  837. << " Val);\n";
  838. return;
  839. }
  840. OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << type
  841. << "(StringRef Val, " << type << " &Out) {\n";
  842. OS << " std::optional<" << type
  843. << "> R = llvm::StringSwitch<std::optional<";
  844. OS << type << ">>(Val)\n";
  845. for (size_t I = 0; I < enums.size(); ++I) {
  846. OS << " .Case(\"" << values[I] << "\", ";
  847. OS << getAttrName() << "Attr::" << enums[I] << ")\n";
  848. }
  849. OS << " .Default(std::optional<" << type << ">());\n";
  850. OS << " if (R) {\n";
  851. OS << " Out = *R;\n return true;\n }\n";
  852. OS << " return false;\n";
  853. OS << "}\n\n";
  854. // Mapping from enumeration values back to enumeration strings isn't
  855. // trivial because some enumeration values have multiple named
  856. // enumerators, such as type_visibility(internal) and
  857. // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
  858. OS << "const char *" << getAttrName() << "Attr::Convert" << type
  859. << "ToStr(" << type << " Val) {\n"
  860. << " switch(Val) {\n";
  861. SmallDenseSet<StringRef, 8> Uniques;
  862. for (size_t I = 0; I < enums.size(); ++I) {
  863. if (Uniques.insert(enums[I]).second)
  864. OS << " case " << getAttrName() << "Attr::" << enums[I]
  865. << ": return \"" << values[I] << "\";\n";
  866. }
  867. OS << " }\n"
  868. << " llvm_unreachable(\"No enumerator with that value\");\n"
  869. << "}\n";
  870. }
  871. };
  872. class VariadicEnumArgument: public VariadicArgument {
  873. std::string type, QualifiedTypeName;
  874. std::vector<StringRef> values, enums, uniques;
  875. protected:
  876. void writeValueImpl(raw_ostream &OS) const override {
  877. // FIXME: this isn't 100% correct -- some enum arguments require printing
  878. // as a string literal, while others require printing as an identifier.
  879. // Tablegen currently does not distinguish between the two forms.
  880. OS << " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
  881. << "ToStr(Val)" << "<< \"\\\"\";\n";
  882. }
  883. public:
  884. VariadicEnumArgument(const Record &Arg, StringRef Attr)
  885. : VariadicArgument(Arg, Attr,
  886. std::string(Arg.getValueAsString("Type"))),
  887. type(std::string(Arg.getValueAsString("Type"))),
  888. values(Arg.getValueAsListOfStrings("Values")),
  889. enums(Arg.getValueAsListOfStrings("Enums")),
  890. uniques(uniqueEnumsInOrder(enums)) {
  891. QualifiedTypeName = getAttrName().str() + "Attr::" + type;
  892. // FIXME: Emit a proper error
  893. assert(!uniques.empty());
  894. }
  895. bool isVariadicEnumArg() const override { return true; }
  896. void writeDeclarations(raw_ostream &OS) const override {
  897. auto i = uniques.cbegin(), e = uniques.cend();
  898. // The last one needs to not have a comma.
  899. --e;
  900. OS << "public:\n";
  901. OS << " enum " << type << " {\n";
  902. for (; i != e; ++i)
  903. OS << " " << *i << ",\n";
  904. OS << " " << *e << "\n";
  905. OS << " };\n";
  906. OS << "private:\n";
  907. VariadicArgument::writeDeclarations(OS);
  908. }
  909. void writeDump(raw_ostream &OS) const override {
  910. OS << " for (" << getAttrName() << "Attr::" << getLowerName()
  911. << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
  912. << getLowerName() << "_end(); I != E; ++I) {\n";
  913. OS << " switch(*I) {\n";
  914. for (const auto &UI : uniques) {
  915. OS << " case " << getAttrName() << "Attr::" << UI << ":\n";
  916. OS << " OS << \" " << UI << "\";\n";
  917. OS << " break;\n";
  918. }
  919. OS << " }\n";
  920. OS << " }\n";
  921. }
  922. void writePCHReadDecls(raw_ostream &OS) const override {
  923. OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
  924. OS << " SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
  925. << ";\n";
  926. OS << " " << getLowerName() << ".reserve(" << getLowerName()
  927. << "Size);\n";
  928. OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
  929. OS << " " << getLowerName() << ".push_back(" << "static_cast<"
  930. << QualifiedTypeName << ">(Record.readInt()));\n";
  931. }
  932. void writePCHWrite(raw_ostream &OS) const override {
  933. OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
  934. OS << " for (" << getAttrName() << "Attr::" << getLowerName()
  935. << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
  936. << getLowerName() << "_end(); i != e; ++i)\n";
  937. OS << " " << WritePCHRecord(QualifiedTypeName, "(*i)");
  938. }
  939. void writeConversion(raw_ostream &OS, bool Header) const {
  940. if (Header) {
  941. OS << " static bool ConvertStrTo" << type << "(StringRef Val, " << type
  942. << " &Out);\n";
  943. OS << " static const char *Convert" << type << "ToStr(" << type
  944. << " Val);\n";
  945. return;
  946. }
  947. OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << type
  948. << "(StringRef Val, ";
  949. OS << type << " &Out) {\n";
  950. OS << " std::optional<" << type
  951. << "> R = llvm::StringSwitch<std::optional<";
  952. OS << type << ">>(Val)\n";
  953. for (size_t I = 0; I < enums.size(); ++I) {
  954. OS << " .Case(\"" << values[I] << "\", ";
  955. OS << getAttrName() << "Attr::" << enums[I] << ")\n";
  956. }
  957. OS << " .Default(std::optional<" << type << ">());\n";
  958. OS << " if (R) {\n";
  959. OS << " Out = *R;\n return true;\n }\n";
  960. OS << " return false;\n";
  961. OS << "}\n\n";
  962. OS << "const char *" << getAttrName() << "Attr::Convert" << type
  963. << "ToStr(" << type << " Val) {\n"
  964. << " switch(Val) {\n";
  965. SmallDenseSet<StringRef, 8> Uniques;
  966. for (size_t I = 0; I < enums.size(); ++I) {
  967. if (Uniques.insert(enums[I]).second)
  968. OS << " case " << getAttrName() << "Attr::" << enums[I]
  969. << ": return \"" << values[I] << "\";\n";
  970. }
  971. OS << " }\n"
  972. << " llvm_unreachable(\"No enumerator with that value\");\n"
  973. << "}\n";
  974. }
  975. };
  976. class VersionArgument : public Argument {
  977. public:
  978. VersionArgument(const Record &Arg, StringRef Attr)
  979. : Argument(Arg, Attr)
  980. {}
  981. void writeAccessors(raw_ostream &OS) const override {
  982. OS << " VersionTuple get" << getUpperName() << "() const {\n";
  983. OS << " return " << getLowerName() << ";\n";
  984. OS << " }\n";
  985. OS << " void set" << getUpperName()
  986. << "(ASTContext &C, VersionTuple V) {\n";
  987. OS << " " << getLowerName() << " = V;\n";
  988. OS << " }";
  989. }
  990. void writeCloneArgs(raw_ostream &OS) const override {
  991. OS << "get" << getUpperName() << "()";
  992. }
  993. void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
  994. OS << "A->get" << getUpperName() << "()";
  995. }
  996. void writeCtorInitializers(raw_ostream &OS) const override {
  997. OS << getLowerName() << "(" << getUpperName() << ")";
  998. }
  999. void writeCtorDefaultInitializers(raw_ostream &OS) const override {
  1000. OS << getLowerName() << "()";
  1001. }
  1002. void writeCtorParameters(raw_ostream &OS) const override {
  1003. OS << "VersionTuple " << getUpperName();
  1004. }
  1005. void writeDeclarations(raw_ostream &OS) const override {
  1006. OS << "VersionTuple " << getLowerName() << ";\n";
  1007. }
  1008. void writePCHReadDecls(raw_ostream &OS) const override {
  1009. OS << " VersionTuple " << getLowerName()
  1010. << "= Record.readVersionTuple();\n";
  1011. }
  1012. void writePCHReadArgs(raw_ostream &OS) const override {
  1013. OS << getLowerName();
  1014. }
  1015. void writePCHWrite(raw_ostream &OS) const override {
  1016. OS << " Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
  1017. }
  1018. void writeValue(raw_ostream &OS) const override {
  1019. OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
  1020. }
  1021. void writeDump(raw_ostream &OS) const override {
  1022. OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
  1023. }
  1024. };
  1025. class ExprArgument : public SimpleArgument {
  1026. public:
  1027. ExprArgument(const Record &Arg, StringRef Attr)
  1028. : SimpleArgument(Arg, Attr, "Expr *")
  1029. {}
  1030. void writeASTVisitorTraversal(raw_ostream &OS) const override {
  1031. OS << " if (!"
  1032. << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
  1033. OS << " return false;\n";
  1034. }
  1035. void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
  1036. OS << "tempInst" << getUpperName();
  1037. }
  1038. void writeTemplateInstantiation(raw_ostream &OS) const override {
  1039. OS << " " << getType() << " tempInst" << getUpperName() << ";\n";
  1040. OS << " {\n";
  1041. OS << " EnterExpressionEvaluationContext "
  1042. << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
  1043. OS << " ExprResult " << "Result = S.SubstExpr("
  1044. << "A->get" << getUpperName() << "(), TemplateArgs);\n";
  1045. OS << " if (Result.isInvalid())\n";
  1046. OS << " return nullptr;\n";
  1047. OS << " tempInst" << getUpperName() << " = Result.get();\n";
  1048. OS << " }\n";
  1049. }
  1050. void writeValue(raw_ostream &OS) const override {
  1051. OS << "\";\n";
  1052. OS << " get" << getUpperName()
  1053. << "()->printPretty(OS, nullptr, Policy);\n";
  1054. OS << " OS << \"";
  1055. }
  1056. void writeDump(raw_ostream &OS) const override {}
  1057. void writeDumpChildren(raw_ostream &OS) const override {
  1058. OS << " Visit(SA->get" << getUpperName() << "());\n";
  1059. }
  1060. void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
  1061. };
  1062. class VariadicExprArgument : public VariadicArgument {
  1063. public:
  1064. VariadicExprArgument(const Record &Arg, StringRef Attr)
  1065. : VariadicArgument(Arg, Attr, "Expr *")
  1066. {}
  1067. VariadicExprArgument(StringRef ArgName, StringRef Attr)
  1068. : VariadicArgument(ArgName, Attr, "Expr *") {}
  1069. void writeASTVisitorTraversal(raw_ostream &OS) const override {
  1070. OS << " {\n";
  1071. OS << " " << getType() << " *I = A->" << getLowerName()
  1072. << "_begin();\n";
  1073. OS << " " << getType() << " *E = A->" << getLowerName()
  1074. << "_end();\n";
  1075. OS << " for (; I != E; ++I) {\n";
  1076. OS << " if (!getDerived().TraverseStmt(*I))\n";
  1077. OS << " return false;\n";
  1078. OS << " }\n";
  1079. OS << " }\n";
  1080. }
  1081. void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
  1082. OS << "tempInst" << getUpperName() << ", "
  1083. << "A->" << getLowerName() << "_size()";
  1084. }
  1085. void writeTemplateInstantiation(raw_ostream &OS) const override {
  1086. OS << " auto *tempInst" << getUpperName()
  1087. << " = new (C, 16) " << getType()
  1088. << "[A->" << getLowerName() << "_size()];\n";
  1089. OS << " {\n";
  1090. OS << " EnterExpressionEvaluationContext "
  1091. << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
  1092. OS << " " << getType() << " *TI = tempInst" << getUpperName()
  1093. << ";\n";
  1094. OS << " " << getType() << " *I = A->" << getLowerName()
  1095. << "_begin();\n";
  1096. OS << " " << getType() << " *E = A->" << getLowerName()
  1097. << "_end();\n";
  1098. OS << " for (; I != E; ++I, ++TI) {\n";
  1099. OS << " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
  1100. OS << " if (Result.isInvalid())\n";
  1101. OS << " return nullptr;\n";
  1102. OS << " *TI = Result.get();\n";
  1103. OS << " }\n";
  1104. OS << " }\n";
  1105. }
  1106. void writeDump(raw_ostream &OS) const override {}
  1107. void writeDumpChildren(raw_ostream &OS) const override {
  1108. OS << " for (" << getAttrName() << "Attr::" << getLowerName()
  1109. << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
  1110. << getLowerName() << "_end(); I != E; ++I)\n";
  1111. OS << " Visit(*I);\n";
  1112. }
  1113. void writeHasChildren(raw_ostream &OS) const override {
  1114. OS << "SA->" << getLowerName() << "_begin() != "
  1115. << "SA->" << getLowerName() << "_end()";
  1116. }
  1117. };
  1118. class VariadicIdentifierArgument : public VariadicArgument {
  1119. public:
  1120. VariadicIdentifierArgument(const Record &Arg, StringRef Attr)
  1121. : VariadicArgument(Arg, Attr, "IdentifierInfo *")
  1122. {}
  1123. };
  1124. class VariadicStringArgument : public VariadicArgument {
  1125. public:
  1126. VariadicStringArgument(const Record &Arg, StringRef Attr)
  1127. : VariadicArgument(Arg, Attr, "StringRef")
  1128. {}
  1129. void writeCtorBody(raw_ostream &OS) const override {
  1130. OS << " for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
  1131. " ++I) {\n"
  1132. " StringRef Ref = " << getUpperName() << "[I];\n"
  1133. " if (!Ref.empty()) {\n"
  1134. " char *Mem = new (Ctx, 1) char[Ref.size()];\n"
  1135. " std::memcpy(Mem, Ref.data(), Ref.size());\n"
  1136. " " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
  1137. " }\n"
  1138. " }\n";
  1139. }
  1140. void writeValueImpl(raw_ostream &OS) const override {
  1141. OS << " OS << \"\\\"\" << Val << \"\\\"\";\n";
  1142. }
  1143. };
  1144. class TypeArgument : public SimpleArgument {
  1145. public:
  1146. TypeArgument(const Record &Arg, StringRef Attr)
  1147. : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
  1148. {}
  1149. void writeAccessors(raw_ostream &OS) const override {
  1150. OS << " QualType get" << getUpperName() << "() const {\n";
  1151. OS << " return " << getLowerName() << "->getType();\n";
  1152. OS << " }";
  1153. OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n";
  1154. OS << " return " << getLowerName() << ";\n";
  1155. OS << " }";
  1156. }
  1157. void writeASTVisitorTraversal(raw_ostream &OS) const override {
  1158. OS << " if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
  1159. OS << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
  1160. OS << " return false;\n";
  1161. }
  1162. void writeTemplateInstantiation(raw_ostream &OS) const override {
  1163. OS << " " << getType() << " tempInst" << getUpperName() << " =\n";
  1164. OS << " S.SubstType(A->get" << getUpperName() << "Loc(), "
  1165. << "TemplateArgs, A->getLoc(), A->getAttrName());\n";
  1166. OS << " if (!tempInst" << getUpperName() << ")\n";
  1167. OS << " return nullptr;\n";
  1168. }
  1169. void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
  1170. OS << "tempInst" << getUpperName();
  1171. }
  1172. void writePCHWrite(raw_ostream &OS) const override {
  1173. OS << " "
  1174. << WritePCHRecord(getType(),
  1175. "SA->get" + std::string(getUpperName()) + "Loc()");
  1176. }
  1177. };
  1178. } // end anonymous namespace
  1179. static std::unique_ptr<Argument>
  1180. createArgument(const Record &Arg, StringRef Attr,
  1181. const Record *Search = nullptr) {
  1182. if (!Search)
  1183. Search = &Arg;
  1184. std::unique_ptr<Argument> Ptr;
  1185. llvm::StringRef ArgName = Search->getName();
  1186. if (ArgName == "AlignedArgument")
  1187. Ptr = std::make_unique<AlignedArgument>(Arg, Attr);
  1188. else if (ArgName == "EnumArgument")
  1189. Ptr = std::make_unique<EnumArgument>(Arg, Attr);
  1190. else if (ArgName == "ExprArgument")
  1191. Ptr = std::make_unique<ExprArgument>(Arg, Attr);
  1192. else if (ArgName == "DeclArgument")
  1193. Ptr = std::make_unique<SimpleArgument>(
  1194. Arg, Attr, (Arg.getValueAsDef("Kind")->getName() + "Decl *").str());
  1195. else if (ArgName == "IdentifierArgument")
  1196. Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
  1197. else if (ArgName == "DefaultBoolArgument")
  1198. Ptr = std::make_unique<DefaultSimpleArgument>(
  1199. Arg, Attr, "bool", Arg.getValueAsBit("Default"));
  1200. else if (ArgName == "BoolArgument")
  1201. Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "bool");
  1202. else if (ArgName == "DefaultIntArgument")
  1203. Ptr = std::make_unique<DefaultSimpleArgument>(
  1204. Arg, Attr, "int", Arg.getValueAsInt("Default"));
  1205. else if (ArgName == "IntArgument")
  1206. Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "int");
  1207. else if (ArgName == "StringArgument")
  1208. Ptr = std::make_unique<StringArgument>(Arg, Attr);
  1209. else if (ArgName == "TypeArgument")
  1210. Ptr = std::make_unique<TypeArgument>(Arg, Attr);
  1211. else if (ArgName == "UnsignedArgument")
  1212. Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
  1213. else if (ArgName == "VariadicUnsignedArgument")
  1214. Ptr = std::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
  1215. else if (ArgName == "VariadicStringArgument")
  1216. Ptr = std::make_unique<VariadicStringArgument>(Arg, Attr);
  1217. else if (ArgName == "VariadicEnumArgument")
  1218. Ptr = std::make_unique<VariadicEnumArgument>(Arg, Attr);
  1219. else if (ArgName == "VariadicExprArgument")
  1220. Ptr = std::make_unique<VariadicExprArgument>(Arg, Attr);
  1221. else if (ArgName == "VariadicParamIdxArgument")
  1222. Ptr = std::make_unique<VariadicParamIdxArgument>(Arg, Attr);
  1223. else if (ArgName == "VariadicParamOrParamIdxArgument")
  1224. Ptr = std::make_unique<VariadicParamOrParamIdxArgument>(Arg, Attr);
  1225. else if (ArgName == "ParamIdxArgument")
  1226. Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "ParamIdx");
  1227. else if (ArgName == "VariadicIdentifierArgument")
  1228. Ptr = std::make_unique<VariadicIdentifierArgument>(Arg, Attr);
  1229. else if (ArgName == "VersionArgument")
  1230. Ptr = std::make_unique<VersionArgument>(Arg, Attr);
  1231. else if (ArgName == "OMPTraitInfoArgument")
  1232. Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "OMPTraitInfo *");
  1233. else if (ArgName == "VariadicOMPInteropInfoArgument")
  1234. Ptr = std::make_unique<VariadicOMPInteropInfoArgument>(Arg, Attr);
  1235. if (!Ptr) {
  1236. // Search in reverse order so that the most-derived type is handled first.
  1237. ArrayRef<std::pair<Record*, SMRange>> Bases = Search->getSuperClasses();
  1238. for (const auto &Base : llvm::reverse(Bases)) {
  1239. if ((Ptr = createArgument(Arg, Attr, Base.first)))
  1240. break;
  1241. }
  1242. }
  1243. if (Ptr && Arg.getValueAsBit("Optional"))
  1244. Ptr->setOptional(true);
  1245. if (Ptr && Arg.getValueAsBit("Fake"))
  1246. Ptr->setFake(true);
  1247. return Ptr;
  1248. }
  1249. static void writeAvailabilityValue(raw_ostream &OS) {
  1250. OS << "\" << getPlatform()->getName();\n"
  1251. << " if (getStrict()) OS << \", strict\";\n"
  1252. << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
  1253. << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
  1254. << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
  1255. << " if (getUnavailable()) OS << \", unavailable\";\n"
  1256. << " OS << \"";
  1257. }
  1258. static void writeDeprecatedAttrValue(raw_ostream &OS, std::string &Variety) {
  1259. OS << "\\\"\" << getMessage() << \"\\\"\";\n";
  1260. // Only GNU deprecated has an optional fixit argument at the second position.
  1261. if (Variety == "GNU")
  1262. OS << " if (!getReplacement().empty()) OS << \", \\\"\""
  1263. " << getReplacement() << \"\\\"\";\n";
  1264. OS << " OS << \"";
  1265. }
  1266. static void writeGetSpellingFunction(const Record &R, raw_ostream &OS) {
  1267. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
  1268. OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
  1269. if (Spellings.empty()) {
  1270. OS << " return \"(No spelling)\";\n}\n\n";
  1271. return;
  1272. }
  1273. OS << " switch (getAttributeSpellingListIndex()) {\n"
  1274. " default:\n"
  1275. " llvm_unreachable(\"Unknown attribute spelling!\");\n"
  1276. " return \"(No spelling)\";\n";
  1277. for (unsigned I = 0; I < Spellings.size(); ++I)
  1278. OS << " case " << I << ":\n"
  1279. " return \"" << Spellings[I].name() << "\";\n";
  1280. // End of the switch statement.
  1281. OS << " }\n";
  1282. // End of the getSpelling function.
  1283. OS << "}\n\n";
  1284. }
  1285. static void
  1286. writePrettyPrintFunction(const Record &R,
  1287. const std::vector<std::unique_ptr<Argument>> &Args,
  1288. raw_ostream &OS) {
  1289. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
  1290. OS << "void " << R.getName() << "Attr::printPretty("
  1291. << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
  1292. if (Spellings.empty()) {
  1293. OS << "}\n\n";
  1294. return;
  1295. }
  1296. OS << " bool IsFirstArgument = true; (void)IsFirstArgument;\n"
  1297. << " unsigned TrailingOmittedArgs = 0; (void)TrailingOmittedArgs;\n"
  1298. << " switch (getAttributeSpellingListIndex()) {\n"
  1299. << " default:\n"
  1300. << " llvm_unreachable(\"Unknown attribute spelling!\");\n"
  1301. << " break;\n";
  1302. for (unsigned I = 0; I < Spellings.size(); ++ I) {
  1303. llvm::SmallString<16> Prefix;
  1304. llvm::SmallString<8> Suffix;
  1305. // The actual spelling of the name and namespace (if applicable)
  1306. // of an attribute without considering prefix and suffix.
  1307. llvm::SmallString<64> Spelling;
  1308. std::string Name = Spellings[I].name();
  1309. std::string Variety = Spellings[I].variety();
  1310. if (Variety == "GNU") {
  1311. Prefix = " __attribute__((";
  1312. Suffix = "))";
  1313. } else if (Variety == "CXX11" || Variety == "C2x") {
  1314. Prefix = " [[";
  1315. Suffix = "]]";
  1316. std::string Namespace = Spellings[I].nameSpace();
  1317. if (!Namespace.empty()) {
  1318. Spelling += Namespace;
  1319. Spelling += "::";
  1320. }
  1321. } else if (Variety == "Declspec") {
  1322. Prefix = " __declspec(";
  1323. Suffix = ")";
  1324. } else if (Variety == "Microsoft") {
  1325. Prefix = "[";
  1326. Suffix = "]";
  1327. } else if (Variety == "Keyword") {
  1328. Prefix = " ";
  1329. Suffix = "";
  1330. } else if (Variety == "Pragma") {
  1331. Prefix = "#pragma ";
  1332. Suffix = "\n";
  1333. std::string Namespace = Spellings[I].nameSpace();
  1334. if (!Namespace.empty()) {
  1335. Spelling += Namespace;
  1336. Spelling += " ";
  1337. }
  1338. } else if (Variety == "HLSLSemantic") {
  1339. Prefix = ":";
  1340. Suffix = "";
  1341. } else {
  1342. llvm_unreachable("Unknown attribute syntax variety!");
  1343. }
  1344. Spelling += Name;
  1345. OS << " case " << I << " : {\n"
  1346. << " OS << \"" << Prefix << Spelling << "\";\n";
  1347. if (Variety == "Pragma") {
  1348. OS << " printPrettyPragma(OS, Policy);\n";
  1349. OS << " OS << \"\\n\";";
  1350. OS << " break;\n";
  1351. OS << " }\n";
  1352. continue;
  1353. }
  1354. if (Spelling == "availability") {
  1355. OS << " OS << \"(";
  1356. writeAvailabilityValue(OS);
  1357. OS << ")\";\n";
  1358. } else if (Spelling == "deprecated" || Spelling == "gnu::deprecated") {
  1359. OS << " OS << \"(";
  1360. writeDeprecatedAttrValue(OS, Variety);
  1361. OS << ")\";\n";
  1362. } else {
  1363. // To avoid printing parentheses around an empty argument list or
  1364. // printing spurious commas at the end of an argument list, we need to
  1365. // determine where the last provided non-fake argument is.
  1366. bool FoundNonOptArg = false;
  1367. for (const auto &arg : llvm::reverse(Args)) {
  1368. if (arg->isFake())
  1369. continue;
  1370. if (FoundNonOptArg)
  1371. continue;
  1372. // FIXME: arg->getIsOmitted() == "false" means we haven't implemented
  1373. // any way to detect whether the argument was omitted.
  1374. if (!arg->isOptional() || arg->getIsOmitted() == "false") {
  1375. FoundNonOptArg = true;
  1376. continue;
  1377. }
  1378. OS << " if (" << arg->getIsOmitted() << ")\n"
  1379. << " ++TrailingOmittedArgs;\n";
  1380. }
  1381. unsigned ArgIndex = 0;
  1382. for (const auto &arg : Args) {
  1383. if (arg->isFake())
  1384. continue;
  1385. std::string IsOmitted = arg->getIsOmitted();
  1386. if (arg->isOptional() && IsOmitted != "false")
  1387. OS << " if (!(" << IsOmitted << ")) {\n";
  1388. // Variadic arguments print their own leading comma.
  1389. if (!arg->isVariadic())
  1390. OS << " DelimitAttributeArgument(OS, IsFirstArgument);\n";
  1391. OS << " OS << \"";
  1392. arg->writeValue(OS);
  1393. OS << "\";\n";
  1394. if (arg->isOptional() && IsOmitted != "false")
  1395. OS << " }\n";
  1396. ++ArgIndex;
  1397. }
  1398. if (ArgIndex != 0)
  1399. OS << " if (!IsFirstArgument)\n"
  1400. << " OS << \")\";\n";
  1401. }
  1402. OS << " OS << \"" << Suffix << "\";\n"
  1403. << " break;\n"
  1404. << " }\n";
  1405. }
  1406. // End of the switch statement.
  1407. OS << "}\n";
  1408. // End of the print function.
  1409. OS << "}\n\n";
  1410. }
  1411. /// Return the index of a spelling in a spelling list.
  1412. static unsigned
  1413. getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
  1414. const FlattenedSpelling &Spelling) {
  1415. assert(!SpellingList.empty() && "Spelling list is empty!");
  1416. for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
  1417. const FlattenedSpelling &S = SpellingList[Index];
  1418. if (S.variety() != Spelling.variety())
  1419. continue;
  1420. if (S.nameSpace() != Spelling.nameSpace())
  1421. continue;
  1422. if (S.name() != Spelling.name())
  1423. continue;
  1424. return Index;
  1425. }
  1426. llvm_unreachable("Unknown spelling!");
  1427. }
  1428. static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
  1429. std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
  1430. if (Accessors.empty())
  1431. return;
  1432. const std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
  1433. assert(!SpellingList.empty() &&
  1434. "Attribute with empty spelling list can't have accessors!");
  1435. for (const auto *Accessor : Accessors) {
  1436. const StringRef Name = Accessor->getValueAsString("Name");
  1437. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Accessor);
  1438. OS << " bool " << Name
  1439. << "() const { return getAttributeSpellingListIndex() == ";
  1440. for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
  1441. OS << getSpellingListIndex(SpellingList, Spellings[Index]);
  1442. if (Index != Spellings.size() - 1)
  1443. OS << " ||\n getAttributeSpellingListIndex() == ";
  1444. else
  1445. OS << "; }\n";
  1446. }
  1447. }
  1448. }
  1449. static bool
  1450. SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
  1451. assert(!Spellings.empty() && "An empty list of spellings was provided");
  1452. std::string FirstName =
  1453. std::string(NormalizeNameForSpellingComparison(Spellings.front().name()));
  1454. for (const auto &Spelling :
  1455. llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
  1456. std::string Name =
  1457. std::string(NormalizeNameForSpellingComparison(Spelling.name()));
  1458. if (Name != FirstName)
  1459. return false;
  1460. }
  1461. return true;
  1462. }
  1463. typedef std::map<unsigned, std::string> SemanticSpellingMap;
  1464. static std::string
  1465. CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
  1466. SemanticSpellingMap &Map) {
  1467. // The enumerants are automatically generated based on the variety,
  1468. // namespace (if present) and name for each attribute spelling. However,
  1469. // care is taken to avoid trampling on the reserved namespace due to
  1470. // underscores.
  1471. std::string Ret(" enum Spelling {\n");
  1472. std::set<std::string> Uniques;
  1473. unsigned Idx = 0;
  1474. // If we have a need to have this many spellings we likely need to add an
  1475. // extra bit to the SpellingIndex in AttributeCommonInfo, then increase the
  1476. // value of SpellingNotCalculated there and here.
  1477. assert(Spellings.size() < 15 &&
  1478. "Too many spellings, would step on SpellingNotCalculated in "
  1479. "AttributeCommonInfo");
  1480. for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
  1481. const FlattenedSpelling &S = *I;
  1482. const std::string &Variety = S.variety();
  1483. const std::string &Spelling = S.name();
  1484. const std::string &Namespace = S.nameSpace();
  1485. std::string EnumName;
  1486. EnumName += (Variety + "_");
  1487. if (!Namespace.empty())
  1488. EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
  1489. "_");
  1490. EnumName += NormalizeNameForSpellingComparison(Spelling);
  1491. // Even if the name is not unique, this spelling index corresponds to a
  1492. // particular enumerant name that we've calculated.
  1493. Map[Idx] = EnumName;
  1494. // Since we have been stripping underscores to avoid trampling on the
  1495. // reserved namespace, we may have inadvertently created duplicate
  1496. // enumerant names. These duplicates are not considered part of the
  1497. // semantic spelling, and can be elided.
  1498. if (Uniques.find(EnumName) != Uniques.end())
  1499. continue;
  1500. Uniques.insert(EnumName);
  1501. if (I != Spellings.begin())
  1502. Ret += ",\n";
  1503. // Duplicate spellings are not considered part of the semantic spelling
  1504. // enumeration, but the spelling index and semantic spelling values are
  1505. // meant to be equivalent, so we must specify a concrete value for each
  1506. // enumerator.
  1507. Ret += " " + EnumName + " = " + llvm::utostr(Idx);
  1508. }
  1509. Ret += ",\n SpellingNotCalculated = 15\n";
  1510. Ret += "\n };\n\n";
  1511. return Ret;
  1512. }
  1513. void WriteSemanticSpellingSwitch(const std::string &VarName,
  1514. const SemanticSpellingMap &Map,
  1515. raw_ostream &OS) {
  1516. OS << " switch (" << VarName << ") {\n default: "
  1517. << "llvm_unreachable(\"Unknown spelling list index\");\n";
  1518. for (const auto &I : Map)
  1519. OS << " case " << I.first << ": return " << I.second << ";\n";
  1520. OS << " }\n";
  1521. }
  1522. // Emits the LateParsed property for attributes.
  1523. static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
  1524. OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
  1525. std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
  1526. for (const auto *Attr : Attrs) {
  1527. bool LateParsed = Attr->getValueAsBit("LateParsed");
  1528. if (LateParsed) {
  1529. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
  1530. // FIXME: Handle non-GNU attributes
  1531. for (const auto &I : Spellings) {
  1532. if (I.variety() != "GNU")
  1533. continue;
  1534. OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
  1535. }
  1536. }
  1537. }
  1538. OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
  1539. }
  1540. static bool hasGNUorCXX11Spelling(const Record &Attribute) {
  1541. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
  1542. for (const auto &I : Spellings) {
  1543. if (I.variety() == "GNU" || I.variety() == "CXX11")
  1544. return true;
  1545. }
  1546. return false;
  1547. }
  1548. namespace {
  1549. struct AttributeSubjectMatchRule {
  1550. const Record *MetaSubject;
  1551. const Record *Constraint;
  1552. AttributeSubjectMatchRule(const Record *MetaSubject, const Record *Constraint)
  1553. : MetaSubject(MetaSubject), Constraint(Constraint) {
  1554. assert(MetaSubject && "Missing subject");
  1555. }
  1556. bool isSubRule() const { return Constraint != nullptr; }
  1557. std::vector<Record *> getSubjects() const {
  1558. return (Constraint ? Constraint : MetaSubject)
  1559. ->getValueAsListOfDefs("Subjects");
  1560. }
  1561. std::vector<Record *> getLangOpts() const {
  1562. if (Constraint) {
  1563. // Lookup the options in the sub-rule first, in case the sub-rule
  1564. // overrides the rules options.
  1565. std::vector<Record *> Opts = Constraint->getValueAsListOfDefs("LangOpts");
  1566. if (!Opts.empty())
  1567. return Opts;
  1568. }
  1569. return MetaSubject->getValueAsListOfDefs("LangOpts");
  1570. }
  1571. // Abstract rules are used only for sub-rules
  1572. bool isAbstractRule() const { return getSubjects().empty(); }
  1573. StringRef getName() const {
  1574. return (Constraint ? Constraint : MetaSubject)->getValueAsString("Name");
  1575. }
  1576. bool isNegatedSubRule() const {
  1577. assert(isSubRule() && "Not a sub-rule");
  1578. return Constraint->getValueAsBit("Negated");
  1579. }
  1580. std::string getSpelling() const {
  1581. std::string Result = std::string(MetaSubject->getValueAsString("Name"));
  1582. if (isSubRule()) {
  1583. Result += '(';
  1584. if (isNegatedSubRule())
  1585. Result += "unless(";
  1586. Result += getName();
  1587. if (isNegatedSubRule())
  1588. Result += ')';
  1589. Result += ')';
  1590. }
  1591. return Result;
  1592. }
  1593. std::string getEnumValueName() const {
  1594. SmallString<128> Result;
  1595. Result += "SubjectMatchRule_";
  1596. Result += MetaSubject->getValueAsString("Name");
  1597. if (isSubRule()) {
  1598. Result += "_";
  1599. if (isNegatedSubRule())
  1600. Result += "not_";
  1601. Result += Constraint->getValueAsString("Name");
  1602. }
  1603. if (isAbstractRule())
  1604. Result += "_abstract";
  1605. return std::string(Result.str());
  1606. }
  1607. std::string getEnumValue() const { return "attr::" + getEnumValueName(); }
  1608. static const char *EnumName;
  1609. };
  1610. const char *AttributeSubjectMatchRule::EnumName = "attr::SubjectMatchRule";
  1611. struct PragmaClangAttributeSupport {
  1612. std::vector<AttributeSubjectMatchRule> Rules;
  1613. class RuleOrAggregateRuleSet {
  1614. std::vector<AttributeSubjectMatchRule> Rules;
  1615. bool IsRule;
  1616. RuleOrAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules,
  1617. bool IsRule)
  1618. : Rules(Rules), IsRule(IsRule) {}
  1619. public:
  1620. bool isRule() const { return IsRule; }
  1621. const AttributeSubjectMatchRule &getRule() const {
  1622. assert(IsRule && "not a rule!");
  1623. return Rules[0];
  1624. }
  1625. ArrayRef<AttributeSubjectMatchRule> getAggregateRuleSet() const {
  1626. return Rules;
  1627. }
  1628. static RuleOrAggregateRuleSet
  1629. getRule(const AttributeSubjectMatchRule &Rule) {
  1630. return RuleOrAggregateRuleSet(Rule, /*IsRule=*/true);
  1631. }
  1632. static RuleOrAggregateRuleSet
  1633. getAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules) {
  1634. return RuleOrAggregateRuleSet(Rules, /*IsRule=*/false);
  1635. }
  1636. };
  1637. llvm::DenseMap<const Record *, RuleOrAggregateRuleSet> SubjectsToRules;
  1638. PragmaClangAttributeSupport(RecordKeeper &Records);
  1639. bool isAttributedSupported(const Record &Attribute);
  1640. void emitMatchRuleList(raw_ostream &OS);
  1641. void generateStrictConformsTo(const Record &Attr, raw_ostream &OS);
  1642. void generateParsingHelpers(raw_ostream &OS);
  1643. };
  1644. } // end anonymous namespace
  1645. static bool isSupportedPragmaClangAttributeSubject(const Record &Subject) {
  1646. // FIXME: #pragma clang attribute does not currently support statement
  1647. // attributes, so test whether the subject is one that appertains to a
  1648. // declaration node. However, it may be reasonable for support for statement
  1649. // attributes to be added.
  1650. if (Subject.isSubClassOf("DeclNode") || Subject.isSubClassOf("DeclBase") ||
  1651. Subject.getName() == "DeclBase")
  1652. return true;
  1653. if (Subject.isSubClassOf("SubsetSubject"))
  1654. return isSupportedPragmaClangAttributeSubject(
  1655. *Subject.getValueAsDef("Base"));
  1656. return false;
  1657. }
  1658. static bool doesDeclDeriveFrom(const Record *D, const Record *Base) {
  1659. const Record *CurrentBase = D->getValueAsOptionalDef(BaseFieldName);
  1660. if (!CurrentBase)
  1661. return false;
  1662. if (CurrentBase == Base)
  1663. return true;
  1664. return doesDeclDeriveFrom(CurrentBase, Base);
  1665. }
  1666. PragmaClangAttributeSupport::PragmaClangAttributeSupport(
  1667. RecordKeeper &Records) {
  1668. std::vector<Record *> MetaSubjects =
  1669. Records.getAllDerivedDefinitions("AttrSubjectMatcherRule");
  1670. auto MapFromSubjectsToRules = [this](const Record *SubjectContainer,
  1671. const Record *MetaSubject,
  1672. const Record *Constraint) {
  1673. Rules.emplace_back(MetaSubject, Constraint);
  1674. std::vector<Record *> ApplicableSubjects =
  1675. SubjectContainer->getValueAsListOfDefs("Subjects");
  1676. for (const auto *Subject : ApplicableSubjects) {
  1677. bool Inserted =
  1678. SubjectsToRules
  1679. .try_emplace(Subject, RuleOrAggregateRuleSet::getRule(
  1680. AttributeSubjectMatchRule(MetaSubject,
  1681. Constraint)))
  1682. .second;
  1683. if (!Inserted) {
  1684. PrintFatalError("Attribute subject match rules should not represent"
  1685. "same attribute subjects.");
  1686. }
  1687. }
  1688. };
  1689. for (const auto *MetaSubject : MetaSubjects) {
  1690. MapFromSubjectsToRules(MetaSubject, MetaSubject, /*Constraints=*/nullptr);
  1691. std::vector<Record *> Constraints =
  1692. MetaSubject->getValueAsListOfDefs("Constraints");
  1693. for (const auto *Constraint : Constraints)
  1694. MapFromSubjectsToRules(Constraint, MetaSubject, Constraint);
  1695. }
  1696. std::vector<Record *> Aggregates =
  1697. Records.getAllDerivedDefinitions("AttrSubjectMatcherAggregateRule");
  1698. std::vector<Record *> DeclNodes =
  1699. Records.getAllDerivedDefinitions(DeclNodeClassName);
  1700. for (const auto *Aggregate : Aggregates) {
  1701. Record *SubjectDecl = Aggregate->getValueAsDef("Subject");
  1702. // Gather sub-classes of the aggregate subject that act as attribute
  1703. // subject rules.
  1704. std::vector<AttributeSubjectMatchRule> Rules;
  1705. for (const auto *D : DeclNodes) {
  1706. if (doesDeclDeriveFrom(D, SubjectDecl)) {
  1707. auto It = SubjectsToRules.find(D);
  1708. if (It == SubjectsToRules.end())
  1709. continue;
  1710. if (!It->second.isRule() || It->second.getRule().isSubRule())
  1711. continue; // Assume that the rule will be included as well.
  1712. Rules.push_back(It->second.getRule());
  1713. }
  1714. }
  1715. bool Inserted =
  1716. SubjectsToRules
  1717. .try_emplace(SubjectDecl,
  1718. RuleOrAggregateRuleSet::getAggregateRuleSet(Rules))
  1719. .second;
  1720. if (!Inserted) {
  1721. PrintFatalError("Attribute subject match rules should not represent"
  1722. "same attribute subjects.");
  1723. }
  1724. }
  1725. }
  1726. static PragmaClangAttributeSupport &
  1727. getPragmaAttributeSupport(RecordKeeper &Records) {
  1728. static PragmaClangAttributeSupport Instance(Records);
  1729. return Instance;
  1730. }
  1731. void PragmaClangAttributeSupport::emitMatchRuleList(raw_ostream &OS) {
  1732. OS << "#ifndef ATTR_MATCH_SUB_RULE\n";
  1733. OS << "#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, "
  1734. "IsNegated) "
  1735. << "ATTR_MATCH_RULE(Value, Spelling, IsAbstract)\n";
  1736. OS << "#endif\n";
  1737. for (const auto &Rule : Rules) {
  1738. OS << (Rule.isSubRule() ? "ATTR_MATCH_SUB_RULE" : "ATTR_MATCH_RULE") << '(';
  1739. OS << Rule.getEnumValueName() << ", \"" << Rule.getSpelling() << "\", "
  1740. << Rule.isAbstractRule();
  1741. if (Rule.isSubRule())
  1742. OS << ", "
  1743. << AttributeSubjectMatchRule(Rule.MetaSubject, nullptr).getEnumValue()
  1744. << ", " << Rule.isNegatedSubRule();
  1745. OS << ")\n";
  1746. }
  1747. OS << "#undef ATTR_MATCH_SUB_RULE\n";
  1748. }
  1749. bool PragmaClangAttributeSupport::isAttributedSupported(
  1750. const Record &Attribute) {
  1751. // If the attribute explicitly specified whether to support #pragma clang
  1752. // attribute, use that setting.
  1753. bool Unset;
  1754. bool SpecifiedResult =
  1755. Attribute.getValueAsBitOrUnset("PragmaAttributeSupport", Unset);
  1756. if (!Unset)
  1757. return SpecifiedResult;
  1758. // Opt-out rules:
  1759. // An attribute requires delayed parsing (LateParsed is on)
  1760. if (Attribute.getValueAsBit("LateParsed"))
  1761. return false;
  1762. // An attribute has no GNU/CXX11 spelling
  1763. if (!hasGNUorCXX11Spelling(Attribute))
  1764. return false;
  1765. // An attribute subject list has a subject that isn't covered by one of the
  1766. // subject match rules or has no subjects at all.
  1767. if (Attribute.isValueUnset("Subjects"))
  1768. return false;
  1769. const Record *SubjectObj = Attribute.getValueAsDef("Subjects");
  1770. std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
  1771. bool HasAtLeastOneValidSubject = false;
  1772. for (const auto *Subject : Subjects) {
  1773. if (!isSupportedPragmaClangAttributeSubject(*Subject))
  1774. continue;
  1775. if (SubjectsToRules.find(Subject) == SubjectsToRules.end())
  1776. return false;
  1777. HasAtLeastOneValidSubject = true;
  1778. }
  1779. return HasAtLeastOneValidSubject;
  1780. }
  1781. static std::string GenerateTestExpression(ArrayRef<Record *> LangOpts) {
  1782. std::string Test;
  1783. for (auto *E : LangOpts) {
  1784. if (!Test.empty())
  1785. Test += " || ";
  1786. const StringRef Code = E->getValueAsString("CustomCode");
  1787. if (!Code.empty()) {
  1788. Test += "(";
  1789. Test += Code;
  1790. Test += ")";
  1791. if (!E->getValueAsString("Name").empty()) {
  1792. PrintWarning(
  1793. E->getLoc(),
  1794. "non-empty 'Name' field ignored because 'CustomCode' was supplied");
  1795. }
  1796. } else {
  1797. Test += "LangOpts.";
  1798. Test += E->getValueAsString("Name");
  1799. }
  1800. }
  1801. if (Test.empty())
  1802. return "true";
  1803. return Test;
  1804. }
  1805. void
  1806. PragmaClangAttributeSupport::generateStrictConformsTo(const Record &Attr,
  1807. raw_ostream &OS) {
  1808. if (!isAttributedSupported(Attr) || Attr.isValueUnset("Subjects"))
  1809. return;
  1810. // Generate a function that constructs a set of matching rules that describe
  1811. // to which declarations the attribute should apply to.
  1812. OS << "void getPragmaAttributeMatchRules("
  1813. << "llvm::SmallVectorImpl<std::pair<"
  1814. << AttributeSubjectMatchRule::EnumName
  1815. << ", bool>> &MatchRules, const LangOptions &LangOpts) const override {\n";
  1816. const Record *SubjectObj = Attr.getValueAsDef("Subjects");
  1817. std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
  1818. for (const auto *Subject : Subjects) {
  1819. if (!isSupportedPragmaClangAttributeSubject(*Subject))
  1820. continue;
  1821. auto It = SubjectsToRules.find(Subject);
  1822. assert(It != SubjectsToRules.end() &&
  1823. "This attribute is unsupported by #pragma clang attribute");
  1824. for (const auto &Rule : It->getSecond().getAggregateRuleSet()) {
  1825. // The rule might be language specific, so only subtract it from the given
  1826. // rules if the specific language options are specified.
  1827. std::vector<Record *> LangOpts = Rule.getLangOpts();
  1828. OS << " MatchRules.push_back(std::make_pair(" << Rule.getEnumValue()
  1829. << ", /*IsSupported=*/" << GenerateTestExpression(LangOpts)
  1830. << "));\n";
  1831. }
  1832. }
  1833. OS << "}\n\n";
  1834. }
  1835. void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) {
  1836. // Generate routines that check the names of sub-rules.
  1837. OS << "std::optional<attr::SubjectMatchRule> "
  1838. "defaultIsAttributeSubjectMatchSubRuleFor(StringRef, bool) {\n";
  1839. OS << " return std::nullopt;\n";
  1840. OS << "}\n\n";
  1841. llvm::MapVector<const Record *, std::vector<AttributeSubjectMatchRule>>
  1842. SubMatchRules;
  1843. for (const auto &Rule : Rules) {
  1844. if (!Rule.isSubRule())
  1845. continue;
  1846. SubMatchRules[Rule.MetaSubject].push_back(Rule);
  1847. }
  1848. for (const auto &SubMatchRule : SubMatchRules) {
  1849. OS << "std::optional<attr::SubjectMatchRule> "
  1850. "isAttributeSubjectMatchSubRuleFor_"
  1851. << SubMatchRule.first->getValueAsString("Name")
  1852. << "(StringRef Name, bool IsUnless) {\n";
  1853. OS << " if (IsUnless)\n";
  1854. OS << " return "
  1855. "llvm::StringSwitch<std::optional<attr::SubjectMatchRule>>(Name).\n";
  1856. for (const auto &Rule : SubMatchRule.second) {
  1857. if (Rule.isNegatedSubRule())
  1858. OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
  1859. << ").\n";
  1860. }
  1861. OS << " Default(std::nullopt);\n";
  1862. OS << " return "
  1863. "llvm::StringSwitch<std::optional<attr::SubjectMatchRule>>(Name).\n";
  1864. for (const auto &Rule : SubMatchRule.second) {
  1865. if (!Rule.isNegatedSubRule())
  1866. OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
  1867. << ").\n";
  1868. }
  1869. OS << " Default(std::nullopt);\n";
  1870. OS << "}\n\n";
  1871. }
  1872. // Generate the function that checks for the top-level rules.
  1873. OS << "std::pair<std::optional<attr::SubjectMatchRule>, "
  1874. "std::optional<attr::SubjectMatchRule> (*)(StringRef, "
  1875. "bool)> isAttributeSubjectMatchRule(StringRef Name) {\n";
  1876. OS << " return "
  1877. "llvm::StringSwitch<std::pair<std::optional<attr::SubjectMatchRule>, "
  1878. "std::optional<attr::SubjectMatchRule> (*) (StringRef, "
  1879. "bool)>>(Name).\n";
  1880. for (const auto &Rule : Rules) {
  1881. if (Rule.isSubRule())
  1882. continue;
  1883. std::string SubRuleFunction;
  1884. if (SubMatchRules.count(Rule.MetaSubject))
  1885. SubRuleFunction =
  1886. ("isAttributeSubjectMatchSubRuleFor_" + Rule.getName()).str();
  1887. else
  1888. SubRuleFunction = "defaultIsAttributeSubjectMatchSubRuleFor";
  1889. OS << " Case(\"" << Rule.getName() << "\", std::make_pair("
  1890. << Rule.getEnumValue() << ", " << SubRuleFunction << ")).\n";
  1891. }
  1892. OS << " Default(std::make_pair(std::nullopt, "
  1893. "defaultIsAttributeSubjectMatchSubRuleFor));\n";
  1894. OS << "}\n\n";
  1895. // Generate the function that checks for the submatch rules.
  1896. OS << "const char *validAttributeSubjectMatchSubRules("
  1897. << AttributeSubjectMatchRule::EnumName << " Rule) {\n";
  1898. OS << " switch (Rule) {\n";
  1899. for (const auto &SubMatchRule : SubMatchRules) {
  1900. OS << " case "
  1901. << AttributeSubjectMatchRule(SubMatchRule.first, nullptr).getEnumValue()
  1902. << ":\n";
  1903. OS << " return \"'";
  1904. bool IsFirst = true;
  1905. for (const auto &Rule : SubMatchRule.second) {
  1906. if (!IsFirst)
  1907. OS << ", '";
  1908. IsFirst = false;
  1909. if (Rule.isNegatedSubRule())
  1910. OS << "unless(";
  1911. OS << Rule.getName();
  1912. if (Rule.isNegatedSubRule())
  1913. OS << ')';
  1914. OS << "'";
  1915. }
  1916. OS << "\";\n";
  1917. }
  1918. OS << " default: return nullptr;\n";
  1919. OS << " }\n";
  1920. OS << "}\n\n";
  1921. }
  1922. template <typename Fn>
  1923. static void forEachUniqueSpelling(const Record &Attr, Fn &&F) {
  1924. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
  1925. SmallDenseSet<StringRef, 8> Seen;
  1926. for (const FlattenedSpelling &S : Spellings) {
  1927. if (Seen.insert(S.name()).second)
  1928. F(S);
  1929. }
  1930. }
  1931. static bool isTypeArgument(const Record *Arg) {
  1932. return !Arg->getSuperClasses().empty() &&
  1933. Arg->getSuperClasses().back().first->getName() == "TypeArgument";
  1934. }
  1935. /// Emits the first-argument-is-type property for attributes.
  1936. static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
  1937. OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
  1938. std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  1939. for (const auto *Attr : Attrs) {
  1940. // Determine whether the first argument is a type.
  1941. std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
  1942. if (Args.empty())
  1943. continue;
  1944. if (!isTypeArgument(Args[0]))
  1945. continue;
  1946. // All these spellings take a single type argument.
  1947. forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
  1948. OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
  1949. });
  1950. }
  1951. OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
  1952. }
  1953. /// Emits the parse-arguments-in-unevaluated-context property for
  1954. /// attributes.
  1955. static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
  1956. OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
  1957. ParsedAttrMap Attrs = getParsedAttrList(Records);
  1958. for (const auto &I : Attrs) {
  1959. const Record &Attr = *I.second;
  1960. if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
  1961. continue;
  1962. // All these spellings take are parsed unevaluated.
  1963. forEachUniqueSpelling(Attr, [&](const FlattenedSpelling &S) {
  1964. OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
  1965. });
  1966. }
  1967. OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
  1968. }
  1969. static bool isIdentifierArgument(const Record *Arg) {
  1970. return !Arg->getSuperClasses().empty() &&
  1971. llvm::StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
  1972. .Case("IdentifierArgument", true)
  1973. .Case("EnumArgument", true)
  1974. .Case("VariadicEnumArgument", true)
  1975. .Default(false);
  1976. }
  1977. static bool isVariadicIdentifierArgument(const Record *Arg) {
  1978. return !Arg->getSuperClasses().empty() &&
  1979. llvm::StringSwitch<bool>(
  1980. Arg->getSuperClasses().back().first->getName())
  1981. .Case("VariadicIdentifierArgument", true)
  1982. .Case("VariadicParamOrParamIdxArgument", true)
  1983. .Default(false);
  1984. }
  1985. static bool isVariadicExprArgument(const Record *Arg) {
  1986. return !Arg->getSuperClasses().empty() &&
  1987. llvm::StringSwitch<bool>(
  1988. Arg->getSuperClasses().back().first->getName())
  1989. .Case("VariadicExprArgument", true)
  1990. .Default(false);
  1991. }
  1992. static void emitClangAttrVariadicIdentifierArgList(RecordKeeper &Records,
  1993. raw_ostream &OS) {
  1994. OS << "#if defined(CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST)\n";
  1995. std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  1996. for (const auto *A : Attrs) {
  1997. // Determine whether the first argument is a variadic identifier.
  1998. std::vector<Record *> Args = A->getValueAsListOfDefs("Args");
  1999. if (Args.empty() || !isVariadicIdentifierArgument(Args[0]))
  2000. continue;
  2001. // All these spellings take an identifier argument.
  2002. forEachUniqueSpelling(*A, [&](const FlattenedSpelling &S) {
  2003. OS << ".Case(\"" << S.name() << "\", "
  2004. << "true"
  2005. << ")\n";
  2006. });
  2007. }
  2008. OS << "#endif // CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST\n\n";
  2009. }
  2010. // Emits the first-argument-is-identifier property for attributes.
  2011. static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
  2012. OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
  2013. std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
  2014. for (const auto *Attr : Attrs) {
  2015. // Determine whether the first argument is an identifier.
  2016. std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
  2017. if (Args.empty() || !isIdentifierArgument(Args[0]))
  2018. continue;
  2019. // All these spellings take an identifier argument.
  2020. forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
  2021. OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
  2022. });
  2023. }
  2024. OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
  2025. }
  2026. static bool keywordThisIsaIdentifierInArgument(const Record *Arg) {
  2027. return !Arg->getSuperClasses().empty() &&
  2028. llvm::StringSwitch<bool>(
  2029. Arg->getSuperClasses().back().first->getName())
  2030. .Case("VariadicParamOrParamIdxArgument", true)
  2031. .Default(false);
  2032. }
  2033. static void emitClangAttrThisIsaIdentifierArgList(RecordKeeper &Records,
  2034. raw_ostream &OS) {
  2035. OS << "#if defined(CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST)\n";
  2036. std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  2037. for (const auto *A : Attrs) {
  2038. // Determine whether the first argument is a variadic identifier.
  2039. std::vector<Record *> Args = A->getValueAsListOfDefs("Args");
  2040. if (Args.empty() || !keywordThisIsaIdentifierInArgument(Args[0]))
  2041. continue;
  2042. // All these spellings take an identifier argument.
  2043. forEachUniqueSpelling(*A, [&](const FlattenedSpelling &S) {
  2044. OS << ".Case(\"" << S.name() << "\", "
  2045. << "true"
  2046. << ")\n";
  2047. });
  2048. }
  2049. OS << "#endif // CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST\n\n";
  2050. }
  2051. static void emitClangAttrAcceptsExprPack(RecordKeeper &Records,
  2052. raw_ostream &OS) {
  2053. OS << "#if defined(CLANG_ATTR_ACCEPTS_EXPR_PACK)\n";
  2054. ParsedAttrMap Attrs = getParsedAttrList(Records);
  2055. for (const auto &I : Attrs) {
  2056. const Record &Attr = *I.second;
  2057. if (!Attr.getValueAsBit("AcceptsExprPack"))
  2058. continue;
  2059. forEachUniqueSpelling(Attr, [&](const FlattenedSpelling &S) {
  2060. OS << ".Case(\"" << S.name() << "\", true)\n";
  2061. });
  2062. }
  2063. OS << "#endif // CLANG_ATTR_ACCEPTS_EXPR_PACK\n\n";
  2064. }
  2065. static void emitAttributes(RecordKeeper &Records, raw_ostream &OS,
  2066. bool Header) {
  2067. std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
  2068. ParsedAttrMap AttrMap = getParsedAttrList(Records);
  2069. // Helper to print the starting character of an attribute argument. If there
  2070. // hasn't been an argument yet, it prints an opening parenthese; otherwise it
  2071. // prints a comma.
  2072. OS << "static inline void DelimitAttributeArgument("
  2073. << "raw_ostream& OS, bool& IsFirst) {\n"
  2074. << " if (IsFirst) {\n"
  2075. << " IsFirst = false;\n"
  2076. << " OS << \"(\";\n"
  2077. << " } else\n"
  2078. << " OS << \", \";\n"
  2079. << "}\n";
  2080. for (const auto *Attr : Attrs) {
  2081. const Record &R = *Attr;
  2082. // FIXME: Currently, documentation is generated as-needed due to the fact
  2083. // that there is no way to allow a generated project "reach into" the docs
  2084. // directory (for instance, it may be an out-of-tree build). However, we want
  2085. // to ensure that every attribute has a Documentation field, and produce an
  2086. // error if it has been neglected. Otherwise, the on-demand generation which
  2087. // happens server-side will fail. This code is ensuring that functionality,
  2088. // even though this Emitter doesn't technically need the documentation.
  2089. // When attribute documentation can be generated as part of the build
  2090. // itself, this code can be removed.
  2091. (void)R.getValueAsListOfDefs("Documentation");
  2092. if (!R.getValueAsBit("ASTNode"))
  2093. continue;
  2094. ArrayRef<std::pair<Record *, SMRange>> Supers = R.getSuperClasses();
  2095. assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
  2096. std::string SuperName;
  2097. bool Inheritable = false;
  2098. for (const auto &Super : llvm::reverse(Supers)) {
  2099. const Record *R = Super.first;
  2100. if (R->getName() != "TargetSpecificAttr" &&
  2101. R->getName() != "DeclOrTypeAttr" && SuperName.empty())
  2102. SuperName = std::string(R->getName());
  2103. if (R->getName() == "InheritableAttr")
  2104. Inheritable = true;
  2105. }
  2106. if (Header)
  2107. OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
  2108. else
  2109. OS << "\n// " << R.getName() << "Attr implementation\n\n";
  2110. std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
  2111. std::vector<std::unique_ptr<Argument>> Args;
  2112. Args.reserve(ArgRecords.size());
  2113. bool AttrAcceptsExprPack = Attr->getValueAsBit("AcceptsExprPack");
  2114. if (AttrAcceptsExprPack) {
  2115. for (size_t I = 0; I < ArgRecords.size(); ++I) {
  2116. const Record *ArgR = ArgRecords[I];
  2117. if (isIdentifierArgument(ArgR) || isVariadicIdentifierArgument(ArgR) ||
  2118. isTypeArgument(ArgR))
  2119. PrintFatalError(Attr->getLoc(),
  2120. "Attributes accepting packs cannot also "
  2121. "have identifier or type arguments.");
  2122. // When trying to determine if value-dependent expressions can populate
  2123. // the attribute without prior instantiation, the decision is made based
  2124. // on the assumption that only the last argument is ever variadic.
  2125. if (I < (ArgRecords.size() - 1) && isVariadicExprArgument(ArgR))
  2126. PrintFatalError(Attr->getLoc(),
  2127. "Attributes accepting packs can only have the last "
  2128. "argument be variadic.");
  2129. }
  2130. }
  2131. bool HasOptArg = false;
  2132. bool HasFakeArg = false;
  2133. for (const auto *ArgRecord : ArgRecords) {
  2134. Args.emplace_back(createArgument(*ArgRecord, R.getName()));
  2135. if (Header) {
  2136. Args.back()->writeDeclarations(OS);
  2137. OS << "\n\n";
  2138. }
  2139. // For these purposes, fake takes priority over optional.
  2140. if (Args.back()->isFake()) {
  2141. HasFakeArg = true;
  2142. } else if (Args.back()->isOptional()) {
  2143. HasOptArg = true;
  2144. }
  2145. }
  2146. std::unique_ptr<VariadicExprArgument> DelayedArgs = nullptr;
  2147. if (AttrAcceptsExprPack) {
  2148. DelayedArgs =
  2149. std::make_unique<VariadicExprArgument>("DelayedArgs", R.getName());
  2150. if (Header) {
  2151. DelayedArgs->writeDeclarations(OS);
  2152. OS << "\n\n";
  2153. }
  2154. }
  2155. if (Header)
  2156. OS << "public:\n";
  2157. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
  2158. // If there are zero or one spellings, all spelling-related functionality
  2159. // can be elided. If all of the spellings share the same name, the spelling
  2160. // functionality can also be elided.
  2161. bool ElideSpelling = (Spellings.size() <= 1) ||
  2162. SpellingNamesAreCommon(Spellings);
  2163. // This maps spelling index values to semantic Spelling enumerants.
  2164. SemanticSpellingMap SemanticToSyntacticMap;
  2165. std::string SpellingEnum;
  2166. if (Spellings.size() > 1)
  2167. SpellingEnum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
  2168. if (Header)
  2169. OS << SpellingEnum;
  2170. const auto &ParsedAttrSpellingItr = llvm::find_if(
  2171. AttrMap, [R](const std::pair<std::string, const Record *> &P) {
  2172. return &R == P.second;
  2173. });
  2174. // Emit CreateImplicit factory methods.
  2175. auto emitCreate = [&](bool Implicit, bool DelayedArgsOnly, bool emitFake) {
  2176. if (Header)
  2177. OS << " static ";
  2178. OS << R.getName() << "Attr *";
  2179. if (!Header)
  2180. OS << R.getName() << "Attr::";
  2181. OS << "Create";
  2182. if (Implicit)
  2183. OS << "Implicit";
  2184. if (DelayedArgsOnly)
  2185. OS << "WithDelayedArgs";
  2186. OS << "(";
  2187. OS << "ASTContext &Ctx";
  2188. if (!DelayedArgsOnly) {
  2189. for (auto const &ai : Args) {
  2190. if (ai->isFake() && !emitFake)
  2191. continue;
  2192. OS << ", ";
  2193. ai->writeCtorParameters(OS);
  2194. }
  2195. } else {
  2196. OS << ", ";
  2197. DelayedArgs->writeCtorParameters(OS);
  2198. }
  2199. OS << ", const AttributeCommonInfo &CommonInfo";
  2200. if (Header && Implicit)
  2201. OS << " = {SourceRange{}}";
  2202. OS << ")";
  2203. if (Header) {
  2204. OS << ";\n";
  2205. return;
  2206. }
  2207. OS << " {\n";
  2208. OS << " auto *A = new (Ctx) " << R.getName();
  2209. OS << "Attr(Ctx, CommonInfo";
  2210. if (!DelayedArgsOnly) {
  2211. for (auto const &ai : Args) {
  2212. if (ai->isFake() && !emitFake)
  2213. continue;
  2214. OS << ", ";
  2215. ai->writeImplicitCtorArgs(OS);
  2216. }
  2217. }
  2218. OS << ");\n";
  2219. if (Implicit) {
  2220. OS << " A->setImplicit(true);\n";
  2221. }
  2222. if (Implicit || ElideSpelling) {
  2223. OS << " if (!A->isAttributeSpellingListCalculated() && "
  2224. "!A->getAttrName())\n";
  2225. OS << " A->setAttributeSpellingListIndex(0);\n";
  2226. }
  2227. if (DelayedArgsOnly) {
  2228. OS << " A->setDelayedArgs(Ctx, ";
  2229. DelayedArgs->writeImplicitCtorArgs(OS);
  2230. OS << ");\n";
  2231. }
  2232. OS << " return A;\n}\n\n";
  2233. };
  2234. auto emitCreateNoCI = [&](bool Implicit, bool DelayedArgsOnly,
  2235. bool emitFake) {
  2236. if (Header)
  2237. OS << " static ";
  2238. OS << R.getName() << "Attr *";
  2239. if (!Header)
  2240. OS << R.getName() << "Attr::";
  2241. OS << "Create";
  2242. if (Implicit)
  2243. OS << "Implicit";
  2244. if (DelayedArgsOnly)
  2245. OS << "WithDelayedArgs";
  2246. OS << "(";
  2247. OS << "ASTContext &Ctx";
  2248. if (!DelayedArgsOnly) {
  2249. for (auto const &ai : Args) {
  2250. if (ai->isFake() && !emitFake)
  2251. continue;
  2252. OS << ", ";
  2253. ai->writeCtorParameters(OS);
  2254. }
  2255. } else {
  2256. OS << ", ";
  2257. DelayedArgs->writeCtorParameters(OS);
  2258. }
  2259. OS << ", SourceRange Range, AttributeCommonInfo::Syntax Syntax";
  2260. if (!ElideSpelling) {
  2261. OS << ", " << R.getName() << "Attr::Spelling S";
  2262. if (Header)
  2263. OS << " = static_cast<Spelling>(SpellingNotCalculated)";
  2264. }
  2265. OS << ")";
  2266. if (Header) {
  2267. OS << ";\n";
  2268. return;
  2269. }
  2270. OS << " {\n";
  2271. OS << " AttributeCommonInfo I(Range, ";
  2272. if (ParsedAttrSpellingItr != std::end(AttrMap))
  2273. OS << "AT_" << ParsedAttrSpellingItr->first;
  2274. else
  2275. OS << "NoSemaHandlerAttribute";
  2276. OS << ", Syntax";
  2277. if (!ElideSpelling)
  2278. OS << ", S";
  2279. OS << ");\n";
  2280. OS << " return Create";
  2281. if (Implicit)
  2282. OS << "Implicit";
  2283. if (DelayedArgsOnly)
  2284. OS << "WithDelayedArgs";
  2285. OS << "(Ctx";
  2286. if (!DelayedArgsOnly) {
  2287. for (auto const &ai : Args) {
  2288. if (ai->isFake() && !emitFake)
  2289. continue;
  2290. OS << ", ";
  2291. ai->writeImplicitCtorArgs(OS);
  2292. }
  2293. } else {
  2294. OS << ", ";
  2295. DelayedArgs->writeImplicitCtorArgs(OS);
  2296. }
  2297. OS << ", I);\n";
  2298. OS << "}\n\n";
  2299. };
  2300. auto emitCreates = [&](bool DelayedArgsOnly, bool emitFake) {
  2301. emitCreate(true, DelayedArgsOnly, emitFake);
  2302. emitCreate(false, DelayedArgsOnly, emitFake);
  2303. emitCreateNoCI(true, DelayedArgsOnly, emitFake);
  2304. emitCreateNoCI(false, DelayedArgsOnly, emitFake);
  2305. };
  2306. if (Header)
  2307. OS << " // Factory methods\n";
  2308. // Emit a CreateImplicit that takes all the arguments.
  2309. emitCreates(false, true);
  2310. // Emit a CreateImplicit that takes all the non-fake arguments.
  2311. if (HasFakeArg)
  2312. emitCreates(false, false);
  2313. // Emit a CreateWithDelayedArgs that takes only the dependent argument
  2314. // expressions.
  2315. if (DelayedArgs)
  2316. emitCreates(true, false);
  2317. // Emit constructors.
  2318. auto emitCtor = [&](bool emitOpt, bool emitFake, bool emitNoArgs) {
  2319. auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
  2320. if (emitNoArgs)
  2321. return false;
  2322. if (arg->isFake())
  2323. return emitFake;
  2324. if (arg->isOptional())
  2325. return emitOpt;
  2326. return true;
  2327. };
  2328. if (Header)
  2329. OS << " ";
  2330. else
  2331. OS << R.getName() << "Attr::";
  2332. OS << R.getName()
  2333. << "Attr(ASTContext &Ctx, const AttributeCommonInfo &CommonInfo";
  2334. OS << '\n';
  2335. for (auto const &ai : Args) {
  2336. if (!shouldEmitArg(ai))
  2337. continue;
  2338. OS << " , ";
  2339. ai->writeCtorParameters(OS);
  2340. OS << "\n";
  2341. }
  2342. OS << " )";
  2343. if (Header) {
  2344. OS << ";\n";
  2345. return;
  2346. }
  2347. OS << "\n : " << SuperName << "(Ctx, CommonInfo, ";
  2348. OS << "attr::" << R.getName() << ", "
  2349. << (R.getValueAsBit("LateParsed") ? "true" : "false");
  2350. if (Inheritable) {
  2351. OS << ", "
  2352. << (R.getValueAsBit("InheritEvenIfAlreadyPresent") ? "true"
  2353. : "false");
  2354. }
  2355. OS << ")\n";
  2356. for (auto const &ai : Args) {
  2357. OS << " , ";
  2358. if (!shouldEmitArg(ai)) {
  2359. ai->writeCtorDefaultInitializers(OS);
  2360. } else {
  2361. ai->writeCtorInitializers(OS);
  2362. }
  2363. OS << "\n";
  2364. }
  2365. if (DelayedArgs) {
  2366. OS << " , ";
  2367. DelayedArgs->writeCtorDefaultInitializers(OS);
  2368. OS << "\n";
  2369. }
  2370. OS << " {\n";
  2371. for (auto const &ai : Args) {
  2372. if (!shouldEmitArg(ai))
  2373. continue;
  2374. ai->writeCtorBody(OS);
  2375. }
  2376. OS << "}\n\n";
  2377. };
  2378. if (Header)
  2379. OS << "\n // Constructors\n";
  2380. // Emit a constructor that includes all the arguments.
  2381. // This is necessary for cloning.
  2382. emitCtor(true, true, false);
  2383. // Emit a constructor that takes all the non-fake arguments.
  2384. if (HasFakeArg)
  2385. emitCtor(true, false, false);
  2386. // Emit a constructor that takes all the non-fake, non-optional arguments.
  2387. if (HasOptArg)
  2388. emitCtor(false, false, false);
  2389. // Emit constructors that takes no arguments if none already exists.
  2390. // This is used for delaying arguments.
  2391. bool HasRequiredArgs =
  2392. llvm::count_if(Args, [=](const std::unique_ptr<Argument> &arg) {
  2393. return !arg->isFake() && !arg->isOptional();
  2394. });
  2395. if (DelayedArgs && HasRequiredArgs)
  2396. emitCtor(false, false, true);
  2397. if (Header) {
  2398. OS << '\n';
  2399. OS << " " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
  2400. OS << " void printPretty(raw_ostream &OS,\n"
  2401. << " const PrintingPolicy &Policy) const;\n";
  2402. OS << " const char *getSpelling() const;\n";
  2403. }
  2404. if (!ElideSpelling) {
  2405. assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
  2406. if (Header)
  2407. OS << " Spelling getSemanticSpelling() const;\n";
  2408. else {
  2409. OS << R.getName() << "Attr::Spelling " << R.getName()
  2410. << "Attr::getSemanticSpelling() const {\n";
  2411. WriteSemanticSpellingSwitch("getAttributeSpellingListIndex()",
  2412. SemanticToSyntacticMap, OS);
  2413. OS << "}\n";
  2414. }
  2415. }
  2416. if (Header)
  2417. writeAttrAccessorDefinition(R, OS);
  2418. for (auto const &ai : Args) {
  2419. if (Header) {
  2420. ai->writeAccessors(OS);
  2421. } else {
  2422. ai->writeAccessorDefinitions(OS);
  2423. }
  2424. OS << "\n\n";
  2425. // Don't write conversion routines for fake arguments.
  2426. if (ai->isFake()) continue;
  2427. if (ai->isEnumArg())
  2428. static_cast<const EnumArgument *>(ai.get())->writeConversion(OS,
  2429. Header);
  2430. else if (ai->isVariadicEnumArg())
  2431. static_cast<const VariadicEnumArgument *>(ai.get())->writeConversion(
  2432. OS, Header);
  2433. }
  2434. if (Header) {
  2435. if (DelayedArgs) {
  2436. DelayedArgs->writeAccessors(OS);
  2437. DelayedArgs->writeSetter(OS);
  2438. }
  2439. OS << R.getValueAsString("AdditionalMembers");
  2440. OS << "\n\n";
  2441. OS << " static bool classof(const Attr *A) { return A->getKind() == "
  2442. << "attr::" << R.getName() << "; }\n";
  2443. OS << "};\n\n";
  2444. } else {
  2445. if (DelayedArgs)
  2446. DelayedArgs->writeAccessorDefinitions(OS);
  2447. OS << R.getName() << "Attr *" << R.getName()
  2448. << "Attr::clone(ASTContext &C) const {\n";
  2449. OS << " auto *A = new (C) " << R.getName() << "Attr(C, *this";
  2450. for (auto const &ai : Args) {
  2451. OS << ", ";
  2452. ai->writeCloneArgs(OS);
  2453. }
  2454. OS << ");\n";
  2455. OS << " A->Inherited = Inherited;\n";
  2456. OS << " A->IsPackExpansion = IsPackExpansion;\n";
  2457. OS << " A->setImplicit(Implicit);\n";
  2458. if (DelayedArgs) {
  2459. OS << " A->setDelayedArgs(C, ";
  2460. DelayedArgs->writeCloneArgs(OS);
  2461. OS << ");\n";
  2462. }
  2463. OS << " return A;\n}\n\n";
  2464. writePrettyPrintFunction(R, Args, OS);
  2465. writeGetSpellingFunction(R, OS);
  2466. }
  2467. }
  2468. }
  2469. // Emits the class definitions for attributes.
  2470. void clang::EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
  2471. emitSourceFileHeader("Attribute classes' definitions", OS);
  2472. OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
  2473. OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
  2474. emitAttributes(Records, OS, true);
  2475. OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
  2476. }
  2477. // Emits the class method definitions for attributes.
  2478. void clang::EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
  2479. emitSourceFileHeader("Attribute classes' member function definitions", OS);
  2480. emitAttributes(Records, OS, false);
  2481. std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  2482. // Instead of relying on virtual dispatch we just create a huge dispatch
  2483. // switch. This is both smaller and faster than virtual functions.
  2484. auto EmitFunc = [&](const char *Method) {
  2485. OS << " switch (getKind()) {\n";
  2486. for (const auto *Attr : Attrs) {
  2487. const Record &R = *Attr;
  2488. if (!R.getValueAsBit("ASTNode"))
  2489. continue;
  2490. OS << " case attr::" << R.getName() << ":\n";
  2491. OS << " return cast<" << R.getName() << "Attr>(this)->" << Method
  2492. << ";\n";
  2493. }
  2494. OS << " }\n";
  2495. OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
  2496. OS << "}\n\n";
  2497. };
  2498. OS << "const char *Attr::getSpelling() const {\n";
  2499. EmitFunc("getSpelling()");
  2500. OS << "Attr *Attr::clone(ASTContext &C) const {\n";
  2501. EmitFunc("clone(C)");
  2502. OS << "void Attr::printPretty(raw_ostream &OS, "
  2503. "const PrintingPolicy &Policy) const {\n";
  2504. EmitFunc("printPretty(OS, Policy)");
  2505. }
  2506. static void emitAttrList(raw_ostream &OS, StringRef Class,
  2507. const std::vector<Record*> &AttrList) {
  2508. for (auto Cur : AttrList) {
  2509. OS << Class << "(" << Cur->getName() << ")\n";
  2510. }
  2511. }
  2512. // Determines if an attribute has a Pragma spelling.
  2513. static bool AttrHasPragmaSpelling(const Record *R) {
  2514. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
  2515. return llvm::any_of(Spellings, [](const FlattenedSpelling &S) {
  2516. return S.variety() == "Pragma";
  2517. });
  2518. }
  2519. namespace {
  2520. struct AttrClassDescriptor {
  2521. const char * const MacroName;
  2522. const char * const TableGenName;
  2523. };
  2524. } // end anonymous namespace
  2525. static const AttrClassDescriptor AttrClassDescriptors[] = {
  2526. { "ATTR", "Attr" },
  2527. { "TYPE_ATTR", "TypeAttr" },
  2528. { "STMT_ATTR", "StmtAttr" },
  2529. { "DECL_OR_STMT_ATTR", "DeclOrStmtAttr" },
  2530. { "INHERITABLE_ATTR", "InheritableAttr" },
  2531. { "DECL_OR_TYPE_ATTR", "DeclOrTypeAttr" },
  2532. { "INHERITABLE_PARAM_ATTR", "InheritableParamAttr" },
  2533. { "PARAMETER_ABI_ATTR", "ParameterABIAttr" },
  2534. { "HLSL_ANNOTATION_ATTR", "HLSLAnnotationAttr"}
  2535. };
  2536. static void emitDefaultDefine(raw_ostream &OS, StringRef name,
  2537. const char *superName) {
  2538. OS << "#ifndef " << name << "\n";
  2539. OS << "#define " << name << "(NAME) ";
  2540. if (superName) OS << superName << "(NAME)";
  2541. OS << "\n#endif\n\n";
  2542. }
  2543. namespace {
  2544. /// A class of attributes.
  2545. struct AttrClass {
  2546. const AttrClassDescriptor &Descriptor;
  2547. Record *TheRecord;
  2548. AttrClass *SuperClass = nullptr;
  2549. std::vector<AttrClass*> SubClasses;
  2550. std::vector<Record*> Attrs;
  2551. AttrClass(const AttrClassDescriptor &Descriptor, Record *R)
  2552. : Descriptor(Descriptor), TheRecord(R) {}
  2553. void emitDefaultDefines(raw_ostream &OS) const {
  2554. // Default the macro unless this is a root class (i.e. Attr).
  2555. if (SuperClass) {
  2556. emitDefaultDefine(OS, Descriptor.MacroName,
  2557. SuperClass->Descriptor.MacroName);
  2558. }
  2559. }
  2560. void emitUndefs(raw_ostream &OS) const {
  2561. OS << "#undef " << Descriptor.MacroName << "\n";
  2562. }
  2563. void emitAttrList(raw_ostream &OS) const {
  2564. for (auto SubClass : SubClasses) {
  2565. SubClass->emitAttrList(OS);
  2566. }
  2567. ::emitAttrList(OS, Descriptor.MacroName, Attrs);
  2568. }
  2569. void classifyAttrOnRoot(Record *Attr) {
  2570. bool result = classifyAttr(Attr);
  2571. assert(result && "failed to classify on root"); (void) result;
  2572. }
  2573. void emitAttrRange(raw_ostream &OS) const {
  2574. OS << "ATTR_RANGE(" << Descriptor.TableGenName
  2575. << ", " << getFirstAttr()->getName()
  2576. << ", " << getLastAttr()->getName() << ")\n";
  2577. }
  2578. private:
  2579. bool classifyAttr(Record *Attr) {
  2580. // Check all the subclasses.
  2581. for (auto SubClass : SubClasses) {
  2582. if (SubClass->classifyAttr(Attr))
  2583. return true;
  2584. }
  2585. // It's not more specific than this class, but it might still belong here.
  2586. if (Attr->isSubClassOf(TheRecord)) {
  2587. Attrs.push_back(Attr);
  2588. return true;
  2589. }
  2590. return false;
  2591. }
  2592. Record *getFirstAttr() const {
  2593. if (!SubClasses.empty())
  2594. return SubClasses.front()->getFirstAttr();
  2595. return Attrs.front();
  2596. }
  2597. Record *getLastAttr() const {
  2598. if (!Attrs.empty())
  2599. return Attrs.back();
  2600. return SubClasses.back()->getLastAttr();
  2601. }
  2602. };
  2603. /// The entire hierarchy of attribute classes.
  2604. class AttrClassHierarchy {
  2605. std::vector<std::unique_ptr<AttrClass>> Classes;
  2606. public:
  2607. AttrClassHierarchy(RecordKeeper &Records) {
  2608. // Find records for all the classes.
  2609. for (auto &Descriptor : AttrClassDescriptors) {
  2610. Record *ClassRecord = Records.getClass(Descriptor.TableGenName);
  2611. AttrClass *Class = new AttrClass(Descriptor, ClassRecord);
  2612. Classes.emplace_back(Class);
  2613. }
  2614. // Link up the hierarchy.
  2615. for (auto &Class : Classes) {
  2616. if (AttrClass *SuperClass = findSuperClass(Class->TheRecord)) {
  2617. Class->SuperClass = SuperClass;
  2618. SuperClass->SubClasses.push_back(Class.get());
  2619. }
  2620. }
  2621. #ifndef NDEBUG
  2622. for (auto i = Classes.begin(), e = Classes.end(); i != e; ++i) {
  2623. assert((i == Classes.begin()) == ((*i)->SuperClass == nullptr) &&
  2624. "only the first class should be a root class!");
  2625. }
  2626. #endif
  2627. }
  2628. void emitDefaultDefines(raw_ostream &OS) const {
  2629. for (auto &Class : Classes) {
  2630. Class->emitDefaultDefines(OS);
  2631. }
  2632. }
  2633. void emitUndefs(raw_ostream &OS) const {
  2634. for (auto &Class : Classes) {
  2635. Class->emitUndefs(OS);
  2636. }
  2637. }
  2638. void emitAttrLists(raw_ostream &OS) const {
  2639. // Just start from the root class.
  2640. Classes[0]->emitAttrList(OS);
  2641. }
  2642. void emitAttrRanges(raw_ostream &OS) const {
  2643. for (auto &Class : Classes)
  2644. Class->emitAttrRange(OS);
  2645. }
  2646. void classifyAttr(Record *Attr) {
  2647. // Add the attribute to the root class.
  2648. Classes[0]->classifyAttrOnRoot(Attr);
  2649. }
  2650. private:
  2651. AttrClass *findClassByRecord(Record *R) const {
  2652. for (auto &Class : Classes) {
  2653. if (Class->TheRecord == R)
  2654. return Class.get();
  2655. }
  2656. return nullptr;
  2657. }
  2658. AttrClass *findSuperClass(Record *R) const {
  2659. // TableGen flattens the superclass list, so we just need to walk it
  2660. // in reverse.
  2661. auto SuperClasses = R->getSuperClasses();
  2662. for (signed i = 0, e = SuperClasses.size(); i != e; ++i) {
  2663. auto SuperClass = findClassByRecord(SuperClasses[e - i - 1].first);
  2664. if (SuperClass) return SuperClass;
  2665. }
  2666. return nullptr;
  2667. }
  2668. };
  2669. } // end anonymous namespace
  2670. namespace clang {
  2671. // Emits the enumeration list for attributes.
  2672. void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
  2673. emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
  2674. AttrClassHierarchy Hierarchy(Records);
  2675. // Add defaulting macro definitions.
  2676. Hierarchy.emitDefaultDefines(OS);
  2677. emitDefaultDefine(OS, "PRAGMA_SPELLING_ATTR", nullptr);
  2678. std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  2679. std::vector<Record *> PragmaAttrs;
  2680. for (auto *Attr : Attrs) {
  2681. if (!Attr->getValueAsBit("ASTNode"))
  2682. continue;
  2683. // Add the attribute to the ad-hoc groups.
  2684. if (AttrHasPragmaSpelling(Attr))
  2685. PragmaAttrs.push_back(Attr);
  2686. // Place it in the hierarchy.
  2687. Hierarchy.classifyAttr(Attr);
  2688. }
  2689. // Emit the main attribute list.
  2690. Hierarchy.emitAttrLists(OS);
  2691. // Emit the ad hoc groups.
  2692. emitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
  2693. // Emit the attribute ranges.
  2694. OS << "#ifdef ATTR_RANGE\n";
  2695. Hierarchy.emitAttrRanges(OS);
  2696. OS << "#undef ATTR_RANGE\n";
  2697. OS << "#endif\n";
  2698. Hierarchy.emitUndefs(OS);
  2699. OS << "#undef PRAGMA_SPELLING_ATTR\n";
  2700. }
  2701. // Emits the enumeration list for attributes.
  2702. void EmitClangAttrSubjectMatchRuleList(RecordKeeper &Records, raw_ostream &OS) {
  2703. emitSourceFileHeader(
  2704. "List of all attribute subject matching rules that Clang recognizes", OS);
  2705. PragmaClangAttributeSupport &PragmaAttributeSupport =
  2706. getPragmaAttributeSupport(Records);
  2707. emitDefaultDefine(OS, "ATTR_MATCH_RULE", nullptr);
  2708. PragmaAttributeSupport.emitMatchRuleList(OS);
  2709. OS << "#undef ATTR_MATCH_RULE\n";
  2710. }
  2711. // Emits the code to read an attribute from a precompiled header.
  2712. void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
  2713. emitSourceFileHeader("Attribute deserialization code", OS);
  2714. Record *InhClass = Records.getClass("InheritableAttr");
  2715. std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
  2716. ArgRecords;
  2717. std::vector<std::unique_ptr<Argument>> Args;
  2718. std::unique_ptr<VariadicExprArgument> DelayedArgs;
  2719. OS << " switch (Kind) {\n";
  2720. for (const auto *Attr : Attrs) {
  2721. const Record &R = *Attr;
  2722. if (!R.getValueAsBit("ASTNode"))
  2723. continue;
  2724. OS << " case attr::" << R.getName() << ": {\n";
  2725. if (R.isSubClassOf(InhClass))
  2726. OS << " bool isInherited = Record.readInt();\n";
  2727. OS << " bool isImplicit = Record.readInt();\n";
  2728. OS << " bool isPackExpansion = Record.readInt();\n";
  2729. DelayedArgs = nullptr;
  2730. if (Attr->getValueAsBit("AcceptsExprPack")) {
  2731. DelayedArgs =
  2732. std::make_unique<VariadicExprArgument>("DelayedArgs", R.getName());
  2733. DelayedArgs->writePCHReadDecls(OS);
  2734. }
  2735. ArgRecords = R.getValueAsListOfDefs("Args");
  2736. Args.clear();
  2737. for (const auto *Arg : ArgRecords) {
  2738. Args.emplace_back(createArgument(*Arg, R.getName()));
  2739. Args.back()->writePCHReadDecls(OS);
  2740. }
  2741. OS << " New = new (Context) " << R.getName() << "Attr(Context, Info";
  2742. for (auto const &ri : Args) {
  2743. OS << ", ";
  2744. ri->writePCHReadArgs(OS);
  2745. }
  2746. OS << ");\n";
  2747. if (R.isSubClassOf(InhClass))
  2748. OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
  2749. OS << " New->setImplicit(isImplicit);\n";
  2750. OS << " New->setPackExpansion(isPackExpansion);\n";
  2751. if (DelayedArgs) {
  2752. OS << " cast<" << R.getName()
  2753. << "Attr>(New)->setDelayedArgs(Context, ";
  2754. DelayedArgs->writePCHReadArgs(OS);
  2755. OS << ");\n";
  2756. }
  2757. OS << " break;\n";
  2758. OS << " }\n";
  2759. }
  2760. OS << " }\n";
  2761. }
  2762. // Emits the code to write an attribute to a precompiled header.
  2763. void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
  2764. emitSourceFileHeader("Attribute serialization code", OS);
  2765. Record *InhClass = Records.getClass("InheritableAttr");
  2766. std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
  2767. OS << " switch (A->getKind()) {\n";
  2768. for (const auto *Attr : Attrs) {
  2769. const Record &R = *Attr;
  2770. if (!R.getValueAsBit("ASTNode"))
  2771. continue;
  2772. OS << " case attr::" << R.getName() << ": {\n";
  2773. Args = R.getValueAsListOfDefs("Args");
  2774. if (R.isSubClassOf(InhClass) || !Args.empty())
  2775. OS << " const auto *SA = cast<" << R.getName()
  2776. << "Attr>(A);\n";
  2777. if (R.isSubClassOf(InhClass))
  2778. OS << " Record.push_back(SA->isInherited());\n";
  2779. OS << " Record.push_back(A->isImplicit());\n";
  2780. OS << " Record.push_back(A->isPackExpansion());\n";
  2781. if (Attr->getValueAsBit("AcceptsExprPack"))
  2782. VariadicExprArgument("DelayedArgs", R.getName()).writePCHWrite(OS);
  2783. for (const auto *Arg : Args)
  2784. createArgument(*Arg, R.getName())->writePCHWrite(OS);
  2785. OS << " break;\n";
  2786. OS << " }\n";
  2787. }
  2788. OS << " }\n";
  2789. }
  2790. // Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
  2791. // parameter with only a single check type, if applicable.
  2792. static bool GenerateTargetSpecificAttrCheck(const Record *R, std::string &Test,
  2793. std::string *FnName,
  2794. StringRef ListName,
  2795. StringRef CheckAgainst,
  2796. StringRef Scope) {
  2797. if (!R->isValueUnset(ListName)) {
  2798. Test += " && (";
  2799. std::vector<StringRef> Items = R->getValueAsListOfStrings(ListName);
  2800. for (auto I = Items.begin(), E = Items.end(); I != E; ++I) {
  2801. StringRef Part = *I;
  2802. Test += CheckAgainst;
  2803. Test += " == ";
  2804. Test += Scope;
  2805. Test += Part;
  2806. if (I + 1 != E)
  2807. Test += " || ";
  2808. if (FnName)
  2809. *FnName += Part;
  2810. }
  2811. Test += ")";
  2812. return true;
  2813. }
  2814. return false;
  2815. }
  2816. // Generate a conditional expression to check if the current target satisfies
  2817. // the conditions for a TargetSpecificAttr record, and append the code for
  2818. // those checks to the Test string. If the FnName string pointer is non-null,
  2819. // append a unique suffix to distinguish this set of target checks from other
  2820. // TargetSpecificAttr records.
  2821. static bool GenerateTargetSpecificAttrChecks(const Record *R,
  2822. std::vector<StringRef> &Arches,
  2823. std::string &Test,
  2824. std::string *FnName) {
  2825. bool AnyTargetChecks = false;
  2826. // It is assumed that there will be an llvm::Triple object
  2827. // named "T" and a TargetInfo object named "Target" within
  2828. // scope that can be used to determine whether the attribute exists in
  2829. // a given target.
  2830. Test += "true";
  2831. // If one or more architectures is specified, check those. Arches are handled
  2832. // differently because GenerateTargetRequirements needs to combine the list
  2833. // with ParseKind.
  2834. if (!Arches.empty()) {
  2835. AnyTargetChecks = true;
  2836. Test += " && (";
  2837. for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
  2838. StringRef Part = *I;
  2839. Test += "T.getArch() == llvm::Triple::";
  2840. Test += Part;
  2841. if (I + 1 != E)
  2842. Test += " || ";
  2843. if (FnName)
  2844. *FnName += Part;
  2845. }
  2846. Test += ")";
  2847. }
  2848. // If the attribute is specific to particular OSes, check those.
  2849. AnyTargetChecks |= GenerateTargetSpecificAttrCheck(
  2850. R, Test, FnName, "OSes", "T.getOS()", "llvm::Triple::");
  2851. // If one or more object formats is specified, check those.
  2852. AnyTargetChecks |=
  2853. GenerateTargetSpecificAttrCheck(R, Test, FnName, "ObjectFormats",
  2854. "T.getObjectFormat()", "llvm::Triple::");
  2855. // If custom code is specified, emit it.
  2856. StringRef Code = R->getValueAsString("CustomCode");
  2857. if (!Code.empty()) {
  2858. AnyTargetChecks = true;
  2859. Test += " && (";
  2860. Test += Code;
  2861. Test += ")";
  2862. }
  2863. return AnyTargetChecks;
  2864. }
  2865. static void GenerateHasAttrSpellingStringSwitch(
  2866. const std::vector<Record *> &Attrs, raw_ostream &OS,
  2867. const std::string &Variety = "", const std::string &Scope = "") {
  2868. for (const auto *Attr : Attrs) {
  2869. // C++11-style attributes have specific version information associated with
  2870. // them. If the attribute has no scope, the version information must not
  2871. // have the default value (1), as that's incorrect. Instead, the unscoped
  2872. // attribute version information should be taken from the SD-6 standing
  2873. // document, which can be found at:
  2874. // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
  2875. //
  2876. // C2x-style attributes have the same kind of version information
  2877. // associated with them. The unscoped attribute version information should
  2878. // be taken from the specification of the attribute in the C Standard.
  2879. int Version = 1;
  2880. if (Variety == "CXX11" || Variety == "C2x") {
  2881. std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
  2882. for (const auto &Spelling : Spellings) {
  2883. if (Spelling->getValueAsString("Variety") == Variety) {
  2884. Version = static_cast<int>(Spelling->getValueAsInt("Version"));
  2885. if (Scope.empty() && Version == 1)
  2886. PrintError(Spelling->getLoc(), "Standard attributes must have "
  2887. "valid version information.");
  2888. break;
  2889. }
  2890. }
  2891. }
  2892. std::string Test;
  2893. if (Attr->isSubClassOf("TargetSpecificAttr")) {
  2894. const Record *R = Attr->getValueAsDef("Target");
  2895. std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
  2896. GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
  2897. // If this is the C++11 variety, also add in the LangOpts test.
  2898. if (Variety == "CXX11")
  2899. Test += " && LangOpts.CPlusPlus11";
  2900. else if (Variety == "C2x")
  2901. Test += " && LangOpts.DoubleSquareBracketAttributes";
  2902. } else if (Variety == "CXX11")
  2903. // C++11 mode should be checked against LangOpts, which is presumed to be
  2904. // present in the caller.
  2905. Test = "LangOpts.CPlusPlus11";
  2906. else if (Variety == "C2x")
  2907. Test = "LangOpts.DoubleSquareBracketAttributes";
  2908. std::string TestStr =
  2909. !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
  2910. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
  2911. for (const auto &S : Spellings)
  2912. if (Variety.empty() || (Variety == S.variety() &&
  2913. (Scope.empty() || Scope == S.nameSpace())))
  2914. OS << " .Case(\"" << S.name() << "\", " << TestStr << ")\n";
  2915. }
  2916. OS << " .Default(0);\n";
  2917. }
  2918. // Emits the list of spellings for attributes.
  2919. void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
  2920. emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
  2921. // Separate all of the attributes out into four group: generic, C++11, GNU,
  2922. // and declspecs. Then generate a big switch statement for each of them.
  2923. std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  2924. std::vector<Record *> Declspec, Microsoft, GNU, Pragma, HLSLSemantic;
  2925. std::map<std::string, std::vector<Record *>> CXX, C2x;
  2926. // Walk over the list of all attributes, and split them out based on the
  2927. // spelling variety.
  2928. for (auto *R : Attrs) {
  2929. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
  2930. for (const auto &SI : Spellings) {
  2931. const std::string &Variety = SI.variety();
  2932. if (Variety == "GNU")
  2933. GNU.push_back(R);
  2934. else if (Variety == "Declspec")
  2935. Declspec.push_back(R);
  2936. else if (Variety == "Microsoft")
  2937. Microsoft.push_back(R);
  2938. else if (Variety == "CXX11")
  2939. CXX[SI.nameSpace()].push_back(R);
  2940. else if (Variety == "C2x")
  2941. C2x[SI.nameSpace()].push_back(R);
  2942. else if (Variety == "Pragma")
  2943. Pragma.push_back(R);
  2944. else if (Variety == "HLSLSemantic")
  2945. HLSLSemantic.push_back(R);
  2946. }
  2947. }
  2948. OS << "const llvm::Triple &T = Target.getTriple();\n";
  2949. OS << "switch (Syntax) {\n";
  2950. OS << "case AttributeCommonInfo::Syntax::AS_GNU:\n";
  2951. OS << " return llvm::StringSwitch<int>(Name)\n";
  2952. GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
  2953. OS << "case AttributeCommonInfo::Syntax::AS_Declspec:\n";
  2954. OS << " return llvm::StringSwitch<int>(Name)\n";
  2955. GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
  2956. OS << "case AttributeCommonInfo::Syntax::AS_Microsoft:\n";
  2957. OS << " return llvm::StringSwitch<int>(Name)\n";
  2958. GenerateHasAttrSpellingStringSwitch(Microsoft, OS, "Microsoft");
  2959. OS << "case AttributeCommonInfo::Syntax::AS_Pragma:\n";
  2960. OS << " return llvm::StringSwitch<int>(Name)\n";
  2961. GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
  2962. OS << "case AttributeCommonInfo::Syntax::AS_HLSLSemantic:\n";
  2963. OS << " return llvm::StringSwitch<int>(Name)\n";
  2964. GenerateHasAttrSpellingStringSwitch(HLSLSemantic, OS, "HLSLSemantic");
  2965. auto fn = [&OS](const char *Spelling,
  2966. const std::map<std::string, std::vector<Record *>> &List) {
  2967. OS << "case AttributeCommonInfo::Syntax::AS_" << Spelling << ": {\n";
  2968. // C++11-style attributes are further split out based on the Scope.
  2969. for (auto I = List.cbegin(), E = List.cend(); I != E; ++I) {
  2970. if (I != List.cbegin())
  2971. OS << " else ";
  2972. if (I->first.empty())
  2973. OS << "if (ScopeName == \"\") {\n";
  2974. else
  2975. OS << "if (ScopeName == \"" << I->first << "\") {\n";
  2976. OS << " return llvm::StringSwitch<int>(Name)\n";
  2977. GenerateHasAttrSpellingStringSwitch(I->second, OS, Spelling, I->first);
  2978. OS << "}";
  2979. }
  2980. OS << "\n} break;\n";
  2981. };
  2982. fn("CXX11", CXX);
  2983. fn("C2x", C2x);
  2984. OS << "case AttributeCommonInfo::Syntax::AS_Keyword:\n";
  2985. OS << "case AttributeCommonInfo::Syntax::AS_ContextSensitiveKeyword:\n";
  2986. OS << " llvm_unreachable(\"hasAttribute not supported for keyword\");\n";
  2987. OS << " return 0;\n";
  2988. OS << "}\n";
  2989. }
  2990. void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
  2991. emitSourceFileHeader("Code to translate different attribute spellings "
  2992. "into internal identifiers", OS);
  2993. OS << " switch (getParsedKind()) {\n";
  2994. OS << " case IgnoredAttribute:\n";
  2995. OS << " case UnknownAttribute:\n";
  2996. OS << " case NoSemaHandlerAttribute:\n";
  2997. OS << " llvm_unreachable(\"Ignored/unknown shouldn't get here\");\n";
  2998. ParsedAttrMap Attrs = getParsedAttrList(Records);
  2999. for (const auto &I : Attrs) {
  3000. const Record &R = *I.second;
  3001. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
  3002. OS << " case AT_" << I.first << ": {\n";
  3003. for (unsigned I = 0; I < Spellings.size(); ++ I) {
  3004. OS << " if (Name == \"" << Spellings[I].name() << "\" && "
  3005. << "getSyntax() == AttributeCommonInfo::AS_" << Spellings[I].variety()
  3006. << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
  3007. << " return " << I << ";\n";
  3008. }
  3009. OS << " break;\n";
  3010. OS << " }\n";
  3011. }
  3012. OS << " }\n";
  3013. OS << " return 0;\n";
  3014. }
  3015. // Emits code used by RecursiveASTVisitor to visit attributes
  3016. void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
  3017. emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
  3018. std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
  3019. // Write method declarations for Traverse* methods.
  3020. // We emit this here because we only generate methods for attributes that
  3021. // are declared as ASTNodes.
  3022. OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
  3023. for (const auto *Attr : Attrs) {
  3024. const Record &R = *Attr;
  3025. if (!R.getValueAsBit("ASTNode"))
  3026. continue;
  3027. OS << " bool Traverse"
  3028. << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
  3029. OS << " bool Visit"
  3030. << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
  3031. << " return true; \n"
  3032. << " }\n";
  3033. }
  3034. OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
  3035. // Write individual Traverse* methods for each attribute class.
  3036. for (const auto *Attr : Attrs) {
  3037. const Record &R = *Attr;
  3038. if (!R.getValueAsBit("ASTNode"))
  3039. continue;
  3040. OS << "template <typename Derived>\n"
  3041. << "bool VISITORCLASS<Derived>::Traverse"
  3042. << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
  3043. << " if (!getDerived().VisitAttr(A))\n"
  3044. << " return false;\n"
  3045. << " if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
  3046. << " return false;\n";
  3047. std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
  3048. for (const auto *Arg : ArgRecords)
  3049. createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
  3050. if (Attr->getValueAsBit("AcceptsExprPack"))
  3051. VariadicExprArgument("DelayedArgs", R.getName())
  3052. .writeASTVisitorTraversal(OS);
  3053. OS << " return true;\n";
  3054. OS << "}\n\n";
  3055. }
  3056. // Write generic Traverse routine
  3057. OS << "template <typename Derived>\n"
  3058. << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
  3059. << " if (!A)\n"
  3060. << " return true;\n"
  3061. << "\n"
  3062. << " switch (A->getKind()) {\n";
  3063. for (const auto *Attr : Attrs) {
  3064. const Record &R = *Attr;
  3065. if (!R.getValueAsBit("ASTNode"))
  3066. continue;
  3067. OS << " case attr::" << R.getName() << ":\n"
  3068. << " return getDerived().Traverse" << R.getName() << "Attr("
  3069. << "cast<" << R.getName() << "Attr>(A));\n";
  3070. }
  3071. OS << " }\n"; // end switch
  3072. OS << " llvm_unreachable(\"bad attribute kind\");\n";
  3073. OS << "}\n"; // end function
  3074. OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n";
  3075. }
  3076. void EmitClangAttrTemplateInstantiateHelper(const std::vector<Record *> &Attrs,
  3077. raw_ostream &OS,
  3078. bool AppliesToDecl) {
  3079. OS << " switch (At->getKind()) {\n";
  3080. for (const auto *Attr : Attrs) {
  3081. const Record &R = *Attr;
  3082. if (!R.getValueAsBit("ASTNode"))
  3083. continue;
  3084. OS << " case attr::" << R.getName() << ": {\n";
  3085. bool ShouldClone = R.getValueAsBit("Clone") &&
  3086. (!AppliesToDecl ||
  3087. R.getValueAsBit("MeaningfulToClassTemplateDefinition"));
  3088. if (!ShouldClone) {
  3089. OS << " return nullptr;\n";
  3090. OS << " }\n";
  3091. continue;
  3092. }
  3093. OS << " const auto *A = cast<"
  3094. << R.getName() << "Attr>(At);\n";
  3095. bool TDependent = R.getValueAsBit("TemplateDependent");
  3096. if (!TDependent) {
  3097. OS << " return A->clone(C);\n";
  3098. OS << " }\n";
  3099. continue;
  3100. }
  3101. std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
  3102. std::vector<std::unique_ptr<Argument>> Args;
  3103. Args.reserve(ArgRecords.size());
  3104. for (const auto *ArgRecord : ArgRecords)
  3105. Args.emplace_back(createArgument(*ArgRecord, R.getName()));
  3106. for (auto const &ai : Args)
  3107. ai->writeTemplateInstantiation(OS);
  3108. OS << " return new (C) " << R.getName() << "Attr(C, *A";
  3109. for (auto const &ai : Args) {
  3110. OS << ", ";
  3111. ai->writeTemplateInstantiationArgs(OS);
  3112. }
  3113. OS << ");\n"
  3114. << " }\n";
  3115. }
  3116. OS << " } // end switch\n"
  3117. << " llvm_unreachable(\"Unknown attribute!\");\n"
  3118. << " return nullptr;\n";
  3119. }
  3120. // Emits code to instantiate dependent attributes on templates.
  3121. void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
  3122. emitSourceFileHeader("Template instantiation code for attributes", OS);
  3123. std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
  3124. OS << "namespace clang {\n"
  3125. << "namespace sema {\n\n"
  3126. << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
  3127. << "Sema &S,\n"
  3128. << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
  3129. EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/false);
  3130. OS << "}\n\n"
  3131. << "Attr *instantiateTemplateAttributeForDecl(const Attr *At,\n"
  3132. << " ASTContext &C, Sema &S,\n"
  3133. << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
  3134. EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/true);
  3135. OS << "}\n\n"
  3136. << "} // end namespace sema\n"
  3137. << "} // end namespace clang\n";
  3138. }
  3139. // Emits the list of parsed attributes.
  3140. void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
  3141. emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
  3142. OS << "#ifndef PARSED_ATTR\n";
  3143. OS << "#define PARSED_ATTR(NAME) NAME\n";
  3144. OS << "#endif\n\n";
  3145. ParsedAttrMap Names = getParsedAttrList(Records);
  3146. for (const auto &I : Names) {
  3147. OS << "PARSED_ATTR(" << I.first << ")\n";
  3148. }
  3149. }
  3150. static bool isArgVariadic(const Record &R, StringRef AttrName) {
  3151. return createArgument(R, AttrName)->isVariadic();
  3152. }
  3153. static void emitArgInfo(const Record &R, raw_ostream &OS) {
  3154. // This function will count the number of arguments specified for the
  3155. // attribute and emit the number of required arguments followed by the
  3156. // number of optional arguments.
  3157. std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
  3158. unsigned ArgCount = 0, OptCount = 0, ArgMemberCount = 0;
  3159. bool HasVariadic = false;
  3160. for (const auto *Arg : Args) {
  3161. // If the arg is fake, it's the user's job to supply it: general parsing
  3162. // logic shouldn't need to know anything about it.
  3163. if (Arg->getValueAsBit("Fake"))
  3164. continue;
  3165. Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
  3166. ++ArgMemberCount;
  3167. if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
  3168. HasVariadic = true;
  3169. }
  3170. // If there is a variadic argument, we will set the optional argument count
  3171. // to its largest value. Since it's currently a 4-bit number, we set it to 15.
  3172. OS << " /*NumArgs=*/" << ArgCount << ",\n";
  3173. OS << " /*OptArgs=*/" << (HasVariadic ? 15 : OptCount) << ",\n";
  3174. OS << " /*NumArgMembers=*/" << ArgMemberCount << ",\n";
  3175. }
  3176. static std::string GetDiagnosticSpelling(const Record &R) {
  3177. std::string Ret = std::string(R.getValueAsString("DiagSpelling"));
  3178. if (!Ret.empty())
  3179. return Ret;
  3180. // If we couldn't find the DiagSpelling in this object, we can check to see
  3181. // if the object is one that has a base, and if it is, loop up to the Base
  3182. // member recursively.
  3183. if (auto Base = R.getValueAsOptionalDef(BaseFieldName))
  3184. return GetDiagnosticSpelling(*Base);
  3185. return "";
  3186. }
  3187. static std::string CalculateDiagnostic(const Record &S) {
  3188. // If the SubjectList object has a custom diagnostic associated with it,
  3189. // return that directly.
  3190. const StringRef CustomDiag = S.getValueAsString("CustomDiag");
  3191. if (!CustomDiag.empty())
  3192. return ("\"" + Twine(CustomDiag) + "\"").str();
  3193. std::vector<std::string> DiagList;
  3194. std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
  3195. for (const auto *Subject : Subjects) {
  3196. const Record &R = *Subject;
  3197. // Get the diagnostic text from the Decl or Stmt node given.
  3198. std::string V = GetDiagnosticSpelling(R);
  3199. if (V.empty()) {
  3200. PrintError(R.getLoc(),
  3201. "Could not determine diagnostic spelling for the node: " +
  3202. R.getName() + "; please add one to DeclNodes.td");
  3203. } else {
  3204. // The node may contain a list of elements itself, so split the elements
  3205. // by a comma, and trim any whitespace.
  3206. SmallVector<StringRef, 2> Frags;
  3207. llvm::SplitString(V, Frags, ",");
  3208. for (auto Str : Frags) {
  3209. DiagList.push_back(std::string(Str.trim()));
  3210. }
  3211. }
  3212. }
  3213. if (DiagList.empty()) {
  3214. PrintFatalError(S.getLoc(),
  3215. "Could not deduce diagnostic argument for Attr subjects");
  3216. return "";
  3217. }
  3218. // FIXME: this is not particularly good for localization purposes and ideally
  3219. // should be part of the diagnostics engine itself with some sort of list
  3220. // specifier.
  3221. // A single member of the list can be returned directly.
  3222. if (DiagList.size() == 1)
  3223. return '"' + DiagList.front() + '"';
  3224. if (DiagList.size() == 2)
  3225. return '"' + DiagList[0] + " and " + DiagList[1] + '"';
  3226. // If there are more than two in the list, we serialize the first N - 1
  3227. // elements with a comma. This leaves the string in the state: foo, bar,
  3228. // baz (but misses quux). We can then add ", and " for the last element
  3229. // manually.
  3230. std::string Diag = llvm::join(DiagList.begin(), DiagList.end() - 1, ", ");
  3231. return '"' + Diag + ", and " + *(DiagList.end() - 1) + '"';
  3232. }
  3233. static std::string GetSubjectWithSuffix(const Record *R) {
  3234. const std::string &B = std::string(R->getName());
  3235. if (B == "DeclBase")
  3236. return "Decl";
  3237. return B + "Decl";
  3238. }
  3239. static std::string functionNameForCustomAppertainsTo(const Record &Subject) {
  3240. return "is" + Subject.getName().str();
  3241. }
  3242. static void GenerateCustomAppertainsTo(const Record &Subject, raw_ostream &OS) {
  3243. std::string FnName = functionNameForCustomAppertainsTo(Subject);
  3244. // If this code has already been generated, we don't need to do anything.
  3245. static std::set<std::string> CustomSubjectSet;
  3246. auto I = CustomSubjectSet.find(FnName);
  3247. if (I != CustomSubjectSet.end())
  3248. return;
  3249. // This only works with non-root Decls.
  3250. Record *Base = Subject.getValueAsDef(BaseFieldName);
  3251. // Not currently support custom subjects within custom subjects.
  3252. if (Base->isSubClassOf("SubsetSubject")) {
  3253. PrintFatalError(Subject.getLoc(),
  3254. "SubsetSubjects within SubsetSubjects is not supported");
  3255. return;
  3256. }
  3257. OS << "static bool " << FnName << "(const Decl *D) {\n";
  3258. OS << " if (const auto *S = dyn_cast<";
  3259. OS << GetSubjectWithSuffix(Base);
  3260. OS << ">(D))\n";
  3261. OS << " return " << Subject.getValueAsString("CheckCode") << ";\n";
  3262. OS << " return false;\n";
  3263. OS << "}\n\n";
  3264. CustomSubjectSet.insert(FnName);
  3265. }
  3266. static void GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
  3267. // If the attribute does not contain a Subjects definition, then use the
  3268. // default appertainsTo logic.
  3269. if (Attr.isValueUnset("Subjects"))
  3270. return;
  3271. const Record *SubjectObj = Attr.getValueAsDef("Subjects");
  3272. std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
  3273. // If the list of subjects is empty, it is assumed that the attribute
  3274. // appertains to everything.
  3275. if (Subjects.empty())
  3276. return;
  3277. bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
  3278. // Split the subjects into declaration subjects and statement subjects.
  3279. // FIXME: subset subjects are added to the declaration list until there are
  3280. // enough statement attributes with custom subject needs to warrant
  3281. // the implementation effort.
  3282. std::vector<Record *> DeclSubjects, StmtSubjects;
  3283. llvm::copy_if(
  3284. Subjects, std::back_inserter(DeclSubjects), [](const Record *R) {
  3285. return R->isSubClassOf("SubsetSubject") || !R->isSubClassOf("StmtNode");
  3286. });
  3287. llvm::copy_if(Subjects, std::back_inserter(StmtSubjects),
  3288. [](const Record *R) { return R->isSubClassOf("StmtNode"); });
  3289. // We should have sorted all of the subjects into two lists.
  3290. // FIXME: this assertion will be wrong if we ever add type attribute subjects.
  3291. assert(DeclSubjects.size() + StmtSubjects.size() == Subjects.size());
  3292. if (DeclSubjects.empty()) {
  3293. // If there are no decl subjects but there are stmt subjects, diagnose
  3294. // trying to apply a statement attribute to a declaration.
  3295. if (!StmtSubjects.empty()) {
  3296. OS << "bool diagAppertainsToDecl(Sema &S, const ParsedAttr &AL, ";
  3297. OS << "const Decl *D) const override {\n";
  3298. OS << " S.Diag(AL.getLoc(), diag::err_attribute_invalid_on_decl)\n";
  3299. OS << " << AL << D->getLocation();\n";
  3300. OS << " return false;\n";
  3301. OS << "}\n\n";
  3302. }
  3303. } else {
  3304. // Otherwise, generate an appertainsTo check specific to this attribute
  3305. // which checks all of the given subjects against the Decl passed in.
  3306. OS << "bool diagAppertainsToDecl(Sema &S, ";
  3307. OS << "const ParsedAttr &Attr, const Decl *D) const override {\n";
  3308. OS << " if (";
  3309. for (auto I = DeclSubjects.begin(), E = DeclSubjects.end(); I != E; ++I) {
  3310. // If the subject has custom code associated with it, use the generated
  3311. // function for it. The function cannot be inlined into this check (yet)
  3312. // because it requires the subject to be of a specific type, and were that
  3313. // information inlined here, it would not support an attribute with
  3314. // multiple custom subjects.
  3315. if ((*I)->isSubClassOf("SubsetSubject"))
  3316. OS << "!" << functionNameForCustomAppertainsTo(**I) << "(D)";
  3317. else
  3318. OS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
  3319. if (I + 1 != E)
  3320. OS << " && ";
  3321. }
  3322. OS << ") {\n";
  3323. OS << " S.Diag(Attr.getLoc(), diag::";
  3324. OS << (Warn ? "warn_attribute_wrong_decl_type_str"
  3325. : "err_attribute_wrong_decl_type_str");
  3326. OS << ")\n";
  3327. OS << " << Attr << ";
  3328. OS << CalculateDiagnostic(*SubjectObj) << ";\n";
  3329. OS << " return false;\n";
  3330. OS << " }\n";
  3331. OS << " return true;\n";
  3332. OS << "}\n\n";
  3333. }
  3334. if (StmtSubjects.empty()) {
  3335. // If there are no stmt subjects but there are decl subjects, diagnose
  3336. // trying to apply a declaration attribute to a statement.
  3337. if (!DeclSubjects.empty()) {
  3338. OS << "bool diagAppertainsToStmt(Sema &S, const ParsedAttr &AL, ";
  3339. OS << "const Stmt *St) const override {\n";
  3340. OS << " S.Diag(AL.getLoc(), diag::err_decl_attribute_invalid_on_stmt)\n";
  3341. OS << " << AL << St->getBeginLoc();\n";
  3342. OS << " return false;\n";
  3343. OS << "}\n\n";
  3344. }
  3345. } else {
  3346. // Now, do the same for statements.
  3347. OS << "bool diagAppertainsToStmt(Sema &S, ";
  3348. OS << "const ParsedAttr &Attr, const Stmt *St) const override {\n";
  3349. OS << " if (";
  3350. for (auto I = StmtSubjects.begin(), E = StmtSubjects.end(); I != E; ++I) {
  3351. OS << "!isa<" << (*I)->getName() << ">(St)";
  3352. if (I + 1 != E)
  3353. OS << " && ";
  3354. }
  3355. OS << ") {\n";
  3356. OS << " S.Diag(Attr.getLoc(), diag::";
  3357. OS << (Warn ? "warn_attribute_wrong_decl_type_str"
  3358. : "err_attribute_wrong_decl_type_str");
  3359. OS << ")\n";
  3360. OS << " << Attr << ";
  3361. OS << CalculateDiagnostic(*SubjectObj) << ";\n";
  3362. OS << " return false;\n";
  3363. OS << " }\n";
  3364. OS << " return true;\n";
  3365. OS << "}\n\n";
  3366. }
  3367. }
  3368. // Generates the mutual exclusion checks. The checks for parsed attributes are
  3369. // written into OS and the checks for merging declaration attributes are
  3370. // written into MergeOS.
  3371. static void GenerateMutualExclusionsChecks(const Record &Attr,
  3372. const RecordKeeper &Records,
  3373. raw_ostream &OS,
  3374. raw_ostream &MergeDeclOS,
  3375. raw_ostream &MergeStmtOS) {
  3376. // Find all of the definitions that inherit from MutualExclusions and include
  3377. // the given attribute in the list of exclusions to generate the
  3378. // diagMutualExclusion() check.
  3379. std::vector<Record *> ExclusionsList =
  3380. Records.getAllDerivedDefinitions("MutualExclusions");
  3381. // We don't do any of this magic for type attributes yet.
  3382. if (Attr.isSubClassOf("TypeAttr"))
  3383. return;
  3384. // This means the attribute is either a statement attribute, a decl
  3385. // attribute, or both; find out which.
  3386. bool CurAttrIsStmtAttr =
  3387. Attr.isSubClassOf("StmtAttr") || Attr.isSubClassOf("DeclOrStmtAttr");
  3388. bool CurAttrIsDeclAttr =
  3389. !CurAttrIsStmtAttr || Attr.isSubClassOf("DeclOrStmtAttr");
  3390. std::vector<std::string> DeclAttrs, StmtAttrs;
  3391. for (const Record *Exclusion : ExclusionsList) {
  3392. std::vector<Record *> MutuallyExclusiveAttrs =
  3393. Exclusion->getValueAsListOfDefs("Exclusions");
  3394. auto IsCurAttr = [Attr](const Record *R) {
  3395. return R->getName() == Attr.getName();
  3396. };
  3397. if (llvm::any_of(MutuallyExclusiveAttrs, IsCurAttr)) {
  3398. // This list of exclusions includes the attribute we're looking for, so
  3399. // add the exclusive attributes to the proper list for checking.
  3400. for (const Record *AttrToExclude : MutuallyExclusiveAttrs) {
  3401. if (IsCurAttr(AttrToExclude))
  3402. continue;
  3403. if (CurAttrIsStmtAttr)
  3404. StmtAttrs.push_back((AttrToExclude->getName() + "Attr").str());
  3405. if (CurAttrIsDeclAttr)
  3406. DeclAttrs.push_back((AttrToExclude->getName() + "Attr").str());
  3407. }
  3408. }
  3409. }
  3410. // If there are any decl or stmt attributes, silence -Woverloaded-virtual
  3411. // warnings for them both.
  3412. if (!DeclAttrs.empty() || !StmtAttrs.empty())
  3413. OS << " using ParsedAttrInfo::diagMutualExclusion;\n\n";
  3414. // If we discovered any decl or stmt attributes to test for, generate the
  3415. // predicates for them now.
  3416. if (!DeclAttrs.empty()) {
  3417. // Generate the ParsedAttrInfo subclass logic for declarations.
  3418. OS << " bool diagMutualExclusion(Sema &S, const ParsedAttr &AL, "
  3419. << "const Decl *D) const override {\n";
  3420. for (const std::string &A : DeclAttrs) {
  3421. OS << " if (const auto *A = D->getAttr<" << A << ">()) {\n";
  3422. OS << " S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)"
  3423. << " << AL << A;\n";
  3424. OS << " S.Diag(A->getLocation(), diag::note_conflicting_attribute);";
  3425. OS << " \nreturn false;\n";
  3426. OS << " }\n";
  3427. }
  3428. OS << " return true;\n";
  3429. OS << " }\n\n";
  3430. // Also generate the declaration attribute merging logic if the current
  3431. // attribute is one that can be inheritted on a declaration. It is assumed
  3432. // this code will be executed in the context of a function with parameters:
  3433. // Sema &S, Decl *D, Attr *A and that returns a bool (false on diagnostic,
  3434. // true on success).
  3435. if (Attr.isSubClassOf("InheritableAttr")) {
  3436. MergeDeclOS << " if (const auto *Second = dyn_cast<"
  3437. << (Attr.getName() + "Attr").str() << ">(A)) {\n";
  3438. for (const std::string &A : DeclAttrs) {
  3439. MergeDeclOS << " if (const auto *First = D->getAttr<" << A
  3440. << ">()) {\n";
  3441. MergeDeclOS << " S.Diag(First->getLocation(), "
  3442. << "diag::err_attributes_are_not_compatible) << First << "
  3443. << "Second;\n";
  3444. MergeDeclOS << " S.Diag(Second->getLocation(), "
  3445. << "diag::note_conflicting_attribute);\n";
  3446. MergeDeclOS << " return false;\n";
  3447. MergeDeclOS << " }\n";
  3448. }
  3449. MergeDeclOS << " return true;\n";
  3450. MergeDeclOS << " }\n";
  3451. }
  3452. }
  3453. // Statement attributes are a bit different from declarations. With
  3454. // declarations, each attribute is added to the declaration as it is
  3455. // processed, and so you can look on the Decl * itself to see if there is a
  3456. // conflicting attribute. Statement attributes are processed as a group
  3457. // because AttributedStmt needs to tail-allocate all of the attribute nodes
  3458. // at once. This means we cannot check whether the statement already contains
  3459. // an attribute to check for the conflict. Instead, we need to check whether
  3460. // the given list of semantic attributes contain any conflicts. It is assumed
  3461. // this code will be executed in the context of a function with parameters:
  3462. // Sema &S, const SmallVectorImpl<const Attr *> &C. The code will be within a
  3463. // loop which loops over the container C with a loop variable named A to
  3464. // represent the current attribute to check for conflicts.
  3465. //
  3466. // FIXME: it would be nice not to walk over the list of potential attributes
  3467. // to apply to the statement more than once, but statements typically don't
  3468. // have long lists of attributes on them, so re-walking the list should not
  3469. // be an expensive operation.
  3470. if (!StmtAttrs.empty()) {
  3471. MergeStmtOS << " if (const auto *Second = dyn_cast<"
  3472. << (Attr.getName() + "Attr").str() << ">(A)) {\n";
  3473. MergeStmtOS << " auto Iter = llvm::find_if(C, [](const Attr *Check) "
  3474. << "{ return isa<";
  3475. interleave(
  3476. StmtAttrs, [&](const std::string &Name) { MergeStmtOS << Name; },
  3477. [&] { MergeStmtOS << ", "; });
  3478. MergeStmtOS << ">(Check); });\n";
  3479. MergeStmtOS << " if (Iter != C.end()) {\n";
  3480. MergeStmtOS << " S.Diag((*Iter)->getLocation(), "
  3481. << "diag::err_attributes_are_not_compatible) << *Iter << "
  3482. << "Second;\n";
  3483. MergeStmtOS << " S.Diag(Second->getLocation(), "
  3484. << "diag::note_conflicting_attribute);\n";
  3485. MergeStmtOS << " return false;\n";
  3486. MergeStmtOS << " }\n";
  3487. MergeStmtOS << " }\n";
  3488. }
  3489. }
  3490. static void
  3491. emitAttributeMatchRules(PragmaClangAttributeSupport &PragmaAttributeSupport,
  3492. raw_ostream &OS) {
  3493. OS << "static bool checkAttributeMatchRuleAppliesTo(const Decl *D, "
  3494. << AttributeSubjectMatchRule::EnumName << " rule) {\n";
  3495. OS << " switch (rule) {\n";
  3496. for (const auto &Rule : PragmaAttributeSupport.Rules) {
  3497. if (Rule.isAbstractRule()) {
  3498. OS << " case " << Rule.getEnumValue() << ":\n";
  3499. OS << " assert(false && \"Abstract matcher rule isn't allowed\");\n";
  3500. OS << " return false;\n";
  3501. continue;
  3502. }
  3503. std::vector<Record *> Subjects = Rule.getSubjects();
  3504. assert(!Subjects.empty() && "Missing subjects");
  3505. OS << " case " << Rule.getEnumValue() << ":\n";
  3506. OS << " return ";
  3507. for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
  3508. // If the subject has custom code associated with it, use the function
  3509. // that was generated for GenerateAppertainsTo to check if the declaration
  3510. // is valid.
  3511. if ((*I)->isSubClassOf("SubsetSubject"))
  3512. OS << functionNameForCustomAppertainsTo(**I) << "(D)";
  3513. else
  3514. OS << "isa<" << GetSubjectWithSuffix(*I) << ">(D)";
  3515. if (I + 1 != E)
  3516. OS << " || ";
  3517. }
  3518. OS << ";\n";
  3519. }
  3520. OS << " }\n";
  3521. OS << " llvm_unreachable(\"Invalid match rule\");\nreturn false;\n";
  3522. OS << "}\n\n";
  3523. }
  3524. static void GenerateLangOptRequirements(const Record &R,
  3525. raw_ostream &OS) {
  3526. // If the attribute has an empty or unset list of language requirements,
  3527. // use the default handler.
  3528. std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
  3529. if (LangOpts.empty())
  3530. return;
  3531. OS << "bool acceptsLangOpts(const LangOptions &LangOpts) const override {\n";
  3532. OS << " return " << GenerateTestExpression(LangOpts) << ";\n";
  3533. OS << "}\n\n";
  3534. }
  3535. static void GenerateTargetRequirements(const Record &Attr,
  3536. const ParsedAttrMap &Dupes,
  3537. raw_ostream &OS) {
  3538. // If the attribute is not a target specific attribute, use the default
  3539. // target handler.
  3540. if (!Attr.isSubClassOf("TargetSpecificAttr"))
  3541. return;
  3542. // Get the list of architectures to be tested for.
  3543. const Record *R = Attr.getValueAsDef("Target");
  3544. std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
  3545. // If there are other attributes which share the same parsed attribute kind,
  3546. // such as target-specific attributes with a shared spelling, collapse the
  3547. // duplicate architectures. This is required because a shared target-specific
  3548. // attribute has only one ParsedAttr::Kind enumeration value, but it
  3549. // applies to multiple target architectures. In order for the attribute to be
  3550. // considered valid, all of its architectures need to be included.
  3551. if (!Attr.isValueUnset("ParseKind")) {
  3552. const StringRef APK = Attr.getValueAsString("ParseKind");
  3553. for (const auto &I : Dupes) {
  3554. if (I.first == APK) {
  3555. std::vector<StringRef> DA =
  3556. I.second->getValueAsDef("Target")->getValueAsListOfStrings(
  3557. "Arches");
  3558. Arches.insert(Arches.end(), DA.begin(), DA.end());
  3559. }
  3560. }
  3561. }
  3562. std::string FnName = "isTarget";
  3563. std::string Test;
  3564. bool UsesT = GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
  3565. OS << "bool existsInTarget(const TargetInfo &Target) const override {\n";
  3566. if (UsesT)
  3567. OS << " const llvm::Triple &T = Target.getTriple(); (void)T;\n";
  3568. OS << " return " << Test << ";\n";
  3569. OS << "}\n\n";
  3570. }
  3571. static void GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
  3572. raw_ostream &OS) {
  3573. // If the attribute does not have a semantic form, we can bail out early.
  3574. if (!Attr.getValueAsBit("ASTNode"))
  3575. return;
  3576. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
  3577. // If there are zero or one spellings, or all of the spellings share the same
  3578. // name, we can also bail out early.
  3579. if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
  3580. return;
  3581. // Generate the enumeration we will use for the mapping.
  3582. SemanticSpellingMap SemanticToSyntacticMap;
  3583. std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
  3584. std::string Name = Attr.getName().str() + "AttrSpellingMap";
  3585. OS << "unsigned spellingIndexToSemanticSpelling(";
  3586. OS << "const ParsedAttr &Attr) const override {\n";
  3587. OS << Enum;
  3588. OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
  3589. WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
  3590. OS << "}\n\n";
  3591. }
  3592. static void GenerateHandleDeclAttribute(const Record &Attr, raw_ostream &OS) {
  3593. // Only generate if Attr can be handled simply.
  3594. if (!Attr.getValueAsBit("SimpleHandler"))
  3595. return;
  3596. // Generate a function which just converts from ParsedAttr to the Attr type.
  3597. OS << "AttrHandling handleDeclAttribute(Sema &S, Decl *D,";
  3598. OS << "const ParsedAttr &Attr) const override {\n";
  3599. OS << " D->addAttr(::new (S.Context) " << Attr.getName();
  3600. OS << "Attr(S.Context, Attr));\n";
  3601. OS << " return AttributeApplied;\n";
  3602. OS << "}\n\n";
  3603. }
  3604. static bool isParamExpr(const Record *Arg) {
  3605. return !Arg->getSuperClasses().empty() &&
  3606. llvm::StringSwitch<bool>(
  3607. Arg->getSuperClasses().back().first->getName())
  3608. .Case("ExprArgument", true)
  3609. .Case("VariadicExprArgument", true)
  3610. .Default(false);
  3611. }
  3612. void GenerateIsParamExpr(const Record &Attr, raw_ostream &OS) {
  3613. OS << "bool isParamExpr(size_t N) const override {\n";
  3614. OS << " return ";
  3615. auto Args = Attr.getValueAsListOfDefs("Args");
  3616. for (size_t I = 0; I < Args.size(); ++I)
  3617. if (isParamExpr(Args[I]))
  3618. OS << "(N == " << I << ") || ";
  3619. OS << "false;\n";
  3620. OS << "}\n\n";
  3621. }
  3622. void GenerateHandleAttrWithDelayedArgs(RecordKeeper &Records, raw_ostream &OS) {
  3623. OS << "static void handleAttrWithDelayedArgs(Sema &S, Decl *D, ";
  3624. OS << "const ParsedAttr &Attr) {\n";
  3625. OS << " SmallVector<Expr *, 4> ArgExprs;\n";
  3626. OS << " ArgExprs.reserve(Attr.getNumArgs());\n";
  3627. OS << " for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {\n";
  3628. OS << " assert(!Attr.isArgIdent(I));\n";
  3629. OS << " ArgExprs.push_back(Attr.getArgAsExpr(I));\n";
  3630. OS << " }\n";
  3631. OS << " clang::Attr *CreatedAttr = nullptr;\n";
  3632. OS << " switch (Attr.getKind()) {\n";
  3633. OS << " default:\n";
  3634. OS << " llvm_unreachable(\"Attribute cannot hold delayed arguments.\");\n";
  3635. ParsedAttrMap Attrs = getParsedAttrList(Records);
  3636. for (const auto &I : Attrs) {
  3637. const Record &R = *I.second;
  3638. if (!R.getValueAsBit("AcceptsExprPack"))
  3639. continue;
  3640. OS << " case ParsedAttr::AT_" << I.first << ": {\n";
  3641. OS << " CreatedAttr = " << R.getName() << "Attr::CreateWithDelayedArgs";
  3642. OS << "(S.Context, ArgExprs.data(), ArgExprs.size(), Attr);\n";
  3643. OS << " break;\n";
  3644. OS << " }\n";
  3645. }
  3646. OS << " }\n";
  3647. OS << " D->addAttr(CreatedAttr);\n";
  3648. OS << "}\n\n";
  3649. }
  3650. static bool IsKnownToGCC(const Record &Attr) {
  3651. // Look at the spellings for this subject; if there are any spellings which
  3652. // claim to be known to GCC, the attribute is known to GCC.
  3653. return llvm::any_of(
  3654. GetFlattenedSpellings(Attr),
  3655. [](const FlattenedSpelling &S) { return S.knownToGCC(); });
  3656. }
  3657. /// Emits the parsed attribute helpers
  3658. void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
  3659. emitSourceFileHeader("Parsed attribute helpers", OS);
  3660. OS << "#if !defined(WANT_DECL_MERGE_LOGIC) && "
  3661. << "!defined(WANT_STMT_MERGE_LOGIC)\n";
  3662. PragmaClangAttributeSupport &PragmaAttributeSupport =
  3663. getPragmaAttributeSupport(Records);
  3664. // Get the list of parsed attributes, and accept the optional list of
  3665. // duplicates due to the ParseKind.
  3666. ParsedAttrMap Dupes;
  3667. ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
  3668. // Generate all of the custom appertainsTo functions that the attributes
  3669. // will be using.
  3670. for (auto I : Attrs) {
  3671. const Record &Attr = *I.second;
  3672. if (Attr.isValueUnset("Subjects"))
  3673. continue;
  3674. const Record *SubjectObj = Attr.getValueAsDef("Subjects");
  3675. for (auto Subject : SubjectObj->getValueAsListOfDefs("Subjects"))
  3676. if (Subject->isSubClassOf("SubsetSubject"))
  3677. GenerateCustomAppertainsTo(*Subject, OS);
  3678. }
  3679. // This stream is used to collect all of the declaration attribute merging
  3680. // logic for performing mutual exclusion checks. This gets emitted at the
  3681. // end of the file in a helper function of its own.
  3682. std::string DeclMergeChecks, StmtMergeChecks;
  3683. raw_string_ostream MergeDeclOS(DeclMergeChecks), MergeStmtOS(StmtMergeChecks);
  3684. // Generate a ParsedAttrInfo struct for each of the attributes.
  3685. for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
  3686. // TODO: If the attribute's kind appears in the list of duplicates, that is
  3687. // because it is a target-specific attribute that appears multiple times.
  3688. // It would be beneficial to test whether the duplicates are "similar
  3689. // enough" to each other to not cause problems. For instance, check that
  3690. // the spellings are identical, and custom parsing rules match, etc.
  3691. // We need to generate struct instances based off ParsedAttrInfo from
  3692. // ParsedAttr.cpp.
  3693. const std::string &AttrName = I->first;
  3694. const Record &Attr = *I->second;
  3695. auto Spellings = GetFlattenedSpellings(Attr);
  3696. if (!Spellings.empty()) {
  3697. OS << "static constexpr ParsedAttrInfo::Spelling " << I->first
  3698. << "Spellings[] = {\n";
  3699. for (const auto &S : Spellings) {
  3700. const std::string &RawSpelling = S.name();
  3701. std::string Spelling;
  3702. if (!S.nameSpace().empty())
  3703. Spelling += S.nameSpace() + "::";
  3704. if (S.variety() == "GNU")
  3705. Spelling += NormalizeGNUAttrSpelling(RawSpelling);
  3706. else
  3707. Spelling += RawSpelling;
  3708. OS << " {AttributeCommonInfo::AS_" << S.variety();
  3709. OS << ", \"" << Spelling << "\"},\n";
  3710. }
  3711. OS << "};\n";
  3712. }
  3713. std::vector<std::string> ArgNames;
  3714. for (const auto &Arg : Attr.getValueAsListOfDefs("Args")) {
  3715. bool UnusedUnset;
  3716. if (Arg->getValueAsBitOrUnset("Fake", UnusedUnset))
  3717. continue;
  3718. ArgNames.push_back(Arg->getValueAsString("Name").str());
  3719. for (const auto &Class : Arg->getSuperClasses()) {
  3720. if (Class.first->getName().startswith("Variadic")) {
  3721. ArgNames.back().append("...");
  3722. break;
  3723. }
  3724. }
  3725. }
  3726. if (!ArgNames.empty()) {
  3727. OS << "static constexpr const char *" << I->first << "ArgNames[] = {\n";
  3728. for (const auto &N : ArgNames)
  3729. OS << '"' << N << "\",";
  3730. OS << "};\n";
  3731. }
  3732. OS << "struct ParsedAttrInfo" << I->first
  3733. << " final : public ParsedAttrInfo {\n";
  3734. OS << " constexpr ParsedAttrInfo" << I->first << "() : ParsedAttrInfo(\n";
  3735. OS << " /*AttrKind=*/ParsedAttr::AT_" << AttrName << ",\n";
  3736. emitArgInfo(Attr, OS);
  3737. OS << " /*HasCustomParsing=*/";
  3738. OS << Attr.getValueAsBit("HasCustomParsing") << ",\n";
  3739. OS << " /*AcceptsExprPack=*/";
  3740. OS << Attr.getValueAsBit("AcceptsExprPack") << ",\n";
  3741. OS << " /*IsTargetSpecific=*/";
  3742. OS << Attr.isSubClassOf("TargetSpecificAttr") << ",\n";
  3743. OS << " /*IsType=*/";
  3744. OS << (Attr.isSubClassOf("TypeAttr") || Attr.isSubClassOf("DeclOrTypeAttr"))
  3745. << ",\n";
  3746. OS << " /*IsStmt=*/";
  3747. OS << (Attr.isSubClassOf("StmtAttr") || Attr.isSubClassOf("DeclOrStmtAttr"))
  3748. << ",\n";
  3749. OS << " /*IsKnownToGCC=*/";
  3750. OS << IsKnownToGCC(Attr) << ",\n";
  3751. OS << " /*IsSupportedByPragmaAttribute=*/";
  3752. OS << PragmaAttributeSupport.isAttributedSupported(*I->second) << ",\n";
  3753. if (!Spellings.empty())
  3754. OS << " /*Spellings=*/" << I->first << "Spellings,\n";
  3755. else
  3756. OS << " /*Spellings=*/{},\n";
  3757. if (!ArgNames.empty())
  3758. OS << " /*ArgNames=*/" << I->first << "ArgNames";
  3759. else
  3760. OS << " /*ArgNames=*/{}";
  3761. OS << ") {}\n";
  3762. GenerateAppertainsTo(Attr, OS);
  3763. GenerateMutualExclusionsChecks(Attr, Records, OS, MergeDeclOS, MergeStmtOS);
  3764. GenerateLangOptRequirements(Attr, OS);
  3765. GenerateTargetRequirements(Attr, Dupes, OS);
  3766. GenerateSpellingIndexToSemanticSpelling(Attr, OS);
  3767. PragmaAttributeSupport.generateStrictConformsTo(*I->second, OS);
  3768. GenerateHandleDeclAttribute(Attr, OS);
  3769. GenerateIsParamExpr(Attr, OS);
  3770. OS << "static const ParsedAttrInfo" << I->first << " Instance;\n";
  3771. OS << "};\n";
  3772. OS << "const ParsedAttrInfo" << I->first << " ParsedAttrInfo" << I->first
  3773. << "::Instance;\n";
  3774. }
  3775. OS << "static const ParsedAttrInfo *AttrInfoMap[] = {\n";
  3776. for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
  3777. OS << "&ParsedAttrInfo" << I->first << "::Instance,\n";
  3778. }
  3779. OS << "};\n\n";
  3780. // Generate function for handling attributes with delayed arguments
  3781. GenerateHandleAttrWithDelayedArgs(Records, OS);
  3782. // Generate the attribute match rules.
  3783. emitAttributeMatchRules(PragmaAttributeSupport, OS);
  3784. OS << "#elif defined(WANT_DECL_MERGE_LOGIC)\n\n";
  3785. // Write out the declaration merging check logic.
  3786. OS << "static bool DiagnoseMutualExclusions(Sema &S, const NamedDecl *D, "
  3787. << "const Attr *A) {\n";
  3788. OS << MergeDeclOS.str();
  3789. OS << " return true;\n";
  3790. OS << "}\n\n";
  3791. OS << "#elif defined(WANT_STMT_MERGE_LOGIC)\n\n";
  3792. // Write out the statement merging check logic.
  3793. OS << "static bool DiagnoseMutualExclusions(Sema &S, "
  3794. << "const SmallVectorImpl<const Attr *> &C) {\n";
  3795. OS << " for (const Attr *A : C) {\n";
  3796. OS << MergeStmtOS.str();
  3797. OS << " }\n";
  3798. OS << " return true;\n";
  3799. OS << "}\n\n";
  3800. OS << "#endif\n";
  3801. }
  3802. // Emits the kind list of parsed attributes
  3803. void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
  3804. emitSourceFileHeader("Attribute name matcher", OS);
  3805. std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  3806. std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
  3807. Keywords, Pragma, C2x, HLSLSemantic;
  3808. std::set<std::string> Seen;
  3809. for (const auto *A : Attrs) {
  3810. const Record &Attr = *A;
  3811. bool SemaHandler = Attr.getValueAsBit("SemaHandler");
  3812. bool Ignored = Attr.getValueAsBit("Ignored");
  3813. if (SemaHandler || Ignored) {
  3814. // Attribute spellings can be shared between target-specific attributes,
  3815. // and can be shared between syntaxes for the same attribute. For
  3816. // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
  3817. // specific attribute, or MSP430-specific attribute. Additionally, an
  3818. // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
  3819. // for the same semantic attribute. Ultimately, we need to map each of
  3820. // these to a single AttributeCommonInfo::Kind value, but the
  3821. // StringMatcher class cannot handle duplicate match strings. So we
  3822. // generate a list of string to match based on the syntax, and emit
  3823. // multiple string matchers depending on the syntax used.
  3824. std::string AttrName;
  3825. if (Attr.isSubClassOf("TargetSpecificAttr") &&
  3826. !Attr.isValueUnset("ParseKind")) {
  3827. AttrName = std::string(Attr.getValueAsString("ParseKind"));
  3828. if (!Seen.insert(AttrName).second)
  3829. continue;
  3830. } else
  3831. AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
  3832. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
  3833. for (const auto &S : Spellings) {
  3834. const std::string &RawSpelling = S.name();
  3835. std::vector<StringMatcher::StringPair> *Matches = nullptr;
  3836. std::string Spelling;
  3837. const std::string &Variety = S.variety();
  3838. if (Variety == "CXX11") {
  3839. Matches = &CXX11;
  3840. if (!S.nameSpace().empty())
  3841. Spelling += S.nameSpace() + "::";
  3842. } else if (Variety == "C2x") {
  3843. Matches = &C2x;
  3844. if (!S.nameSpace().empty())
  3845. Spelling += S.nameSpace() + "::";
  3846. } else if (Variety == "GNU")
  3847. Matches = &GNU;
  3848. else if (Variety == "Declspec")
  3849. Matches = &Declspec;
  3850. else if (Variety == "Microsoft")
  3851. Matches = &Microsoft;
  3852. else if (Variety == "Keyword")
  3853. Matches = &Keywords;
  3854. else if (Variety == "Pragma")
  3855. Matches = &Pragma;
  3856. else if (Variety == "HLSLSemantic")
  3857. Matches = &HLSLSemantic;
  3858. assert(Matches && "Unsupported spelling variety found");
  3859. if (Variety == "GNU")
  3860. Spelling += NormalizeGNUAttrSpelling(RawSpelling);
  3861. else
  3862. Spelling += RawSpelling;
  3863. if (SemaHandler)
  3864. Matches->push_back(StringMatcher::StringPair(
  3865. Spelling, "return AttributeCommonInfo::AT_" + AttrName + ";"));
  3866. else
  3867. Matches->push_back(StringMatcher::StringPair(
  3868. Spelling, "return AttributeCommonInfo::IgnoredAttribute;"));
  3869. }
  3870. }
  3871. }
  3872. OS << "static AttributeCommonInfo::Kind getAttrKind(StringRef Name, ";
  3873. OS << "AttributeCommonInfo::Syntax Syntax) {\n";
  3874. OS << " if (AttributeCommonInfo::AS_GNU == Syntax) {\n";
  3875. StringMatcher("Name", GNU, OS).Emit();
  3876. OS << " } else if (AttributeCommonInfo::AS_Declspec == Syntax) {\n";
  3877. StringMatcher("Name", Declspec, OS).Emit();
  3878. OS << " } else if (AttributeCommonInfo::AS_Microsoft == Syntax) {\n";
  3879. StringMatcher("Name", Microsoft, OS).Emit();
  3880. OS << " } else if (AttributeCommonInfo::AS_CXX11 == Syntax) {\n";
  3881. StringMatcher("Name", CXX11, OS).Emit();
  3882. OS << " } else if (AttributeCommonInfo::AS_C2x == Syntax) {\n";
  3883. StringMatcher("Name", C2x, OS).Emit();
  3884. OS << " } else if (AttributeCommonInfo::AS_Keyword == Syntax || ";
  3885. OS << "AttributeCommonInfo::AS_ContextSensitiveKeyword == Syntax) {\n";
  3886. StringMatcher("Name", Keywords, OS).Emit();
  3887. OS << " } else if (AttributeCommonInfo::AS_Pragma == Syntax) {\n";
  3888. StringMatcher("Name", Pragma, OS).Emit();
  3889. OS << " } else if (AttributeCommonInfo::AS_HLSLSemantic == Syntax) {\n";
  3890. StringMatcher("Name", HLSLSemantic, OS).Emit();
  3891. OS << " }\n";
  3892. OS << " return AttributeCommonInfo::UnknownAttribute;\n"
  3893. << "}\n";
  3894. }
  3895. // Emits the code to dump an attribute.
  3896. void EmitClangAttrTextNodeDump(RecordKeeper &Records, raw_ostream &OS) {
  3897. emitSourceFileHeader("Attribute text node dumper", OS);
  3898. std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
  3899. for (const auto *Attr : Attrs) {
  3900. const Record &R = *Attr;
  3901. if (!R.getValueAsBit("ASTNode"))
  3902. continue;
  3903. // If the attribute has a semantically-meaningful name (which is determined
  3904. // by whether there is a Spelling enumeration for it), then write out the
  3905. // spelling used for the attribute.
  3906. std::string FunctionContent;
  3907. llvm::raw_string_ostream SS(FunctionContent);
  3908. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
  3909. if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
  3910. SS << " OS << \" \" << A->getSpelling();\n";
  3911. Args = R.getValueAsListOfDefs("Args");
  3912. for (const auto *Arg : Args)
  3913. createArgument(*Arg, R.getName())->writeDump(SS);
  3914. if (Attr->getValueAsBit("AcceptsExprPack"))
  3915. VariadicExprArgument("DelayedArgs", R.getName()).writeDump(OS);
  3916. if (SS.tell()) {
  3917. OS << " void Visit" << R.getName() << "Attr(const " << R.getName()
  3918. << "Attr *A) {\n";
  3919. if (!Args.empty())
  3920. OS << " const auto *SA = cast<" << R.getName()
  3921. << "Attr>(A); (void)SA;\n";
  3922. OS << SS.str();
  3923. OS << " }\n";
  3924. }
  3925. }
  3926. }
  3927. void EmitClangAttrNodeTraverse(RecordKeeper &Records, raw_ostream &OS) {
  3928. emitSourceFileHeader("Attribute text node traverser", OS);
  3929. std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
  3930. for (const auto *Attr : Attrs) {
  3931. const Record &R = *Attr;
  3932. if (!R.getValueAsBit("ASTNode"))
  3933. continue;
  3934. std::string FunctionContent;
  3935. llvm::raw_string_ostream SS(FunctionContent);
  3936. Args = R.getValueAsListOfDefs("Args");
  3937. for (const auto *Arg : Args)
  3938. createArgument(*Arg, R.getName())->writeDumpChildren(SS);
  3939. if (Attr->getValueAsBit("AcceptsExprPack"))
  3940. VariadicExprArgument("DelayedArgs", R.getName()).writeDumpChildren(SS);
  3941. if (SS.tell()) {
  3942. OS << " void Visit" << R.getName() << "Attr(const " << R.getName()
  3943. << "Attr *A) {\n";
  3944. if (!Args.empty())
  3945. OS << " const auto *SA = cast<" << R.getName()
  3946. << "Attr>(A); (void)SA;\n";
  3947. OS << SS.str();
  3948. OS << " }\n";
  3949. }
  3950. }
  3951. }
  3952. void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
  3953. raw_ostream &OS) {
  3954. emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
  3955. emitClangAttrArgContextList(Records, OS);
  3956. emitClangAttrIdentifierArgList(Records, OS);
  3957. emitClangAttrVariadicIdentifierArgList(Records, OS);
  3958. emitClangAttrThisIsaIdentifierArgList(Records, OS);
  3959. emitClangAttrAcceptsExprPack(Records, OS);
  3960. emitClangAttrTypeArgList(Records, OS);
  3961. emitClangAttrLateParsedList(Records, OS);
  3962. }
  3963. void EmitClangAttrSubjectMatchRulesParserStringSwitches(RecordKeeper &Records,
  3964. raw_ostream &OS) {
  3965. getPragmaAttributeSupport(Records).generateParsingHelpers(OS);
  3966. }
  3967. void EmitClangAttrDocTable(RecordKeeper &Records, raw_ostream &OS) {
  3968. emitSourceFileHeader("Clang attribute documentation", OS);
  3969. std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  3970. for (const auto *A : Attrs) {
  3971. if (!A->getValueAsBit("ASTNode"))
  3972. continue;
  3973. std::vector<Record *> Docs = A->getValueAsListOfDefs("Documentation");
  3974. assert(!Docs.empty());
  3975. // Only look at the first documentation if there are several.
  3976. // (Currently there's only one such attr, revisit if this becomes common).
  3977. StringRef Text =
  3978. Docs.front()->getValueAsOptionalString("Content").value_or("");
  3979. OS << "\nstatic const char AttrDoc_" << A->getName() << "[] = "
  3980. << "R\"reST(" << Text.trim() << ")reST\";\n";
  3981. }
  3982. }
  3983. enum class SpellingKind : size_t {
  3984. GNU,
  3985. CXX11,
  3986. C2x,
  3987. Declspec,
  3988. Microsoft,
  3989. Keyword,
  3990. Pragma,
  3991. HLSLSemantic,
  3992. NumSpellingKinds
  3993. };
  3994. static const size_t NumSpellingKinds = (size_t)SpellingKind::NumSpellingKinds;
  3995. class SpellingList {
  3996. std::vector<std::string> Spellings[NumSpellingKinds];
  3997. public:
  3998. ArrayRef<std::string> operator[](SpellingKind K) const {
  3999. return Spellings[(size_t)K];
  4000. }
  4001. void add(const Record &Attr, FlattenedSpelling Spelling) {
  4002. SpellingKind Kind = StringSwitch<SpellingKind>(Spelling.variety())
  4003. .Case("GNU", SpellingKind::GNU)
  4004. .Case("CXX11", SpellingKind::CXX11)
  4005. .Case("C2x", SpellingKind::C2x)
  4006. .Case("Declspec", SpellingKind::Declspec)
  4007. .Case("Microsoft", SpellingKind::Microsoft)
  4008. .Case("Keyword", SpellingKind::Keyword)
  4009. .Case("Pragma", SpellingKind::Pragma)
  4010. .Case("HLSLSemantic", SpellingKind::HLSLSemantic);
  4011. std::string Name;
  4012. if (!Spelling.nameSpace().empty()) {
  4013. switch (Kind) {
  4014. case SpellingKind::CXX11:
  4015. case SpellingKind::C2x:
  4016. Name = Spelling.nameSpace() + "::";
  4017. break;
  4018. case SpellingKind::Pragma:
  4019. Name = Spelling.nameSpace() + " ";
  4020. break;
  4021. default:
  4022. PrintFatalError(Attr.getLoc(), "Unexpected namespace in spelling");
  4023. }
  4024. }
  4025. Name += Spelling.name();
  4026. Spellings[(size_t)Kind].push_back(Name);
  4027. }
  4028. };
  4029. class DocumentationData {
  4030. public:
  4031. const Record *Documentation;
  4032. const Record *Attribute;
  4033. std::string Heading;
  4034. SpellingList SupportedSpellings;
  4035. DocumentationData(const Record &Documentation, const Record &Attribute,
  4036. std::pair<std::string, SpellingList> HeadingAndSpellings)
  4037. : Documentation(&Documentation), Attribute(&Attribute),
  4038. Heading(std::move(HeadingAndSpellings.first)),
  4039. SupportedSpellings(std::move(HeadingAndSpellings.second)) {}
  4040. };
  4041. static void WriteCategoryHeader(const Record *DocCategory,
  4042. raw_ostream &OS) {
  4043. const StringRef Name = DocCategory->getValueAsString("Name");
  4044. OS << Name << "\n" << std::string(Name.size(), '=') << "\n";
  4045. // If there is content, print that as well.
  4046. const StringRef ContentStr = DocCategory->getValueAsString("Content");
  4047. // Trim leading and trailing newlines and spaces.
  4048. OS << ContentStr.trim();
  4049. OS << "\n\n";
  4050. }
  4051. static std::pair<std::string, SpellingList>
  4052. GetAttributeHeadingAndSpellings(const Record &Documentation,
  4053. const Record &Attribute,
  4054. StringRef Cat) {
  4055. // FIXME: there is no way to have a per-spelling category for the attribute
  4056. // documentation. This may not be a limiting factor since the spellings
  4057. // should generally be consistently applied across the category.
  4058. std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
  4059. if (Spellings.empty())
  4060. PrintFatalError(Attribute.getLoc(),
  4061. "Attribute has no supported spellings; cannot be "
  4062. "documented");
  4063. // Determine the heading to be used for this attribute.
  4064. std::string Heading = std::string(Documentation.getValueAsString("Heading"));
  4065. if (Heading.empty()) {
  4066. // If there's only one spelling, we can simply use that.
  4067. if (Spellings.size() == 1)
  4068. Heading = Spellings.begin()->name();
  4069. else {
  4070. std::set<std::string> Uniques;
  4071. for (auto I = Spellings.begin(), E = Spellings.end();
  4072. I != E; ++I) {
  4073. std::string Spelling =
  4074. std::string(NormalizeNameForSpellingComparison(I->name()));
  4075. Uniques.insert(Spelling);
  4076. }
  4077. // If the semantic map has only one spelling, that is sufficient for our
  4078. // needs.
  4079. if (Uniques.size() == 1)
  4080. Heading = *Uniques.begin();
  4081. // If it's in the undocumented category, just construct a header by
  4082. // concatenating all the spellings. Might not be great, but better than
  4083. // nothing.
  4084. else if (Cat == "Undocumented")
  4085. Heading = llvm::join(Uniques.begin(), Uniques.end(), ", ");
  4086. }
  4087. }
  4088. // If the heading is still empty, it is an error.
  4089. if (Heading.empty())
  4090. PrintFatalError(Attribute.getLoc(),
  4091. "This attribute requires a heading to be specified");
  4092. SpellingList SupportedSpellings;
  4093. for (const auto &I : Spellings)
  4094. SupportedSpellings.add(Attribute, I);
  4095. return std::make_pair(std::move(Heading), std::move(SupportedSpellings));
  4096. }
  4097. static void WriteDocumentation(RecordKeeper &Records,
  4098. const DocumentationData &Doc, raw_ostream &OS) {
  4099. OS << Doc.Heading << "\n" << std::string(Doc.Heading.length(), '-') << "\n";
  4100. // List what spelling syntaxes the attribute supports.
  4101. // Note: "#pragma clang attribute" is handled outside the spelling kinds loop
  4102. // so it must be last.
  4103. OS << ".. csv-table:: Supported Syntaxes\n";
  4104. OS << " :header: \"GNU\", \"C++11\", \"C2x\", \"``__declspec``\",";
  4105. OS << " \"Keyword\", \"``#pragma``\", \"HLSL Semantic\", \"``#pragma clang ";
  4106. OS << "attribute``\"\n\n \"";
  4107. for (size_t Kind = 0; Kind != NumSpellingKinds; ++Kind) {
  4108. SpellingKind K = (SpellingKind)Kind;
  4109. // TODO: List Microsoft (IDL-style attribute) spellings once we fully
  4110. // support them.
  4111. if (K == SpellingKind::Microsoft)
  4112. continue;
  4113. bool PrintedAny = false;
  4114. for (StringRef Spelling : Doc.SupportedSpellings[K]) {
  4115. if (PrintedAny)
  4116. OS << " |br| ";
  4117. OS << "``" << Spelling << "``";
  4118. PrintedAny = true;
  4119. }
  4120. OS << "\",\"";
  4121. }
  4122. if (getPragmaAttributeSupport(Records).isAttributedSupported(
  4123. *Doc.Attribute))
  4124. OS << "Yes";
  4125. OS << "\"\n\n";
  4126. // If the attribute is deprecated, print a message about it, and possibly
  4127. // provide a replacement attribute.
  4128. if (!Doc.Documentation->isValueUnset("Deprecated")) {
  4129. OS << "This attribute has been deprecated, and may be removed in a future "
  4130. << "version of Clang.";
  4131. const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
  4132. const StringRef Replacement = Deprecated.getValueAsString("Replacement");
  4133. if (!Replacement.empty())
  4134. OS << " This attribute has been superseded by ``" << Replacement
  4135. << "``.";
  4136. OS << "\n\n";
  4137. }
  4138. const StringRef ContentStr = Doc.Documentation->getValueAsString("Content");
  4139. // Trim leading and trailing newlines and spaces.
  4140. OS << ContentStr.trim();
  4141. OS << "\n\n\n";
  4142. }
  4143. void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
  4144. // Get the documentation introduction paragraph.
  4145. const Record *Documentation = Records.getDef("GlobalDocumentation");
  4146. if (!Documentation) {
  4147. PrintFatalError("The Documentation top-level definition is missing, "
  4148. "no documentation will be generated.");
  4149. return;
  4150. }
  4151. OS << Documentation->getValueAsString("Intro") << "\n";
  4152. // Gather the Documentation lists from each of the attributes, based on the
  4153. // category provided.
  4154. std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
  4155. struct CategoryLess {
  4156. bool operator()(const Record *L, const Record *R) const {
  4157. return L->getValueAsString("Name") < R->getValueAsString("Name");
  4158. }
  4159. };
  4160. std::map<const Record *, std::vector<DocumentationData>, CategoryLess>
  4161. SplitDocs;
  4162. for (const auto *A : Attrs) {
  4163. const Record &Attr = *A;
  4164. std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
  4165. for (const auto *D : Docs) {
  4166. const Record &Doc = *D;
  4167. const Record *Category = Doc.getValueAsDef("Category");
  4168. // If the category is "InternalOnly", then there cannot be any other
  4169. // documentation categories (otherwise, the attribute would be
  4170. // emitted into the docs).
  4171. const StringRef Cat = Category->getValueAsString("Name");
  4172. bool InternalOnly = Cat == "InternalOnly";
  4173. if (InternalOnly && Docs.size() > 1)
  4174. PrintFatalError(Doc.getLoc(),
  4175. "Attribute is \"InternalOnly\", but has multiple "
  4176. "documentation categories");
  4177. if (!InternalOnly)
  4178. SplitDocs[Category].push_back(DocumentationData(
  4179. Doc, Attr, GetAttributeHeadingAndSpellings(Doc, Attr, Cat)));
  4180. }
  4181. }
  4182. // Having split the attributes out based on what documentation goes where,
  4183. // we can begin to generate sections of documentation.
  4184. for (auto &I : SplitDocs) {
  4185. WriteCategoryHeader(I.first, OS);
  4186. llvm::sort(I.second,
  4187. [](const DocumentationData &D1, const DocumentationData &D2) {
  4188. return D1.Heading < D2.Heading;
  4189. });
  4190. // Walk over each of the attributes in the category and write out their
  4191. // documentation.
  4192. for (const auto &Doc : I.second)
  4193. WriteDocumentation(Records, Doc, OS);
  4194. }
  4195. }
  4196. void EmitTestPragmaAttributeSupportedAttributes(RecordKeeper &Records,
  4197. raw_ostream &OS) {
  4198. PragmaClangAttributeSupport Support = getPragmaAttributeSupport(Records);
  4199. ParsedAttrMap Attrs = getParsedAttrList(Records);
  4200. OS << "#pragma clang attribute supports the following attributes:\n";
  4201. for (const auto &I : Attrs) {
  4202. if (!Support.isAttributedSupported(*I.second))
  4203. continue;
  4204. OS << I.first;
  4205. if (I.second->isValueUnset("Subjects")) {
  4206. OS << " ()\n";
  4207. continue;
  4208. }
  4209. const Record *SubjectObj = I.second->getValueAsDef("Subjects");
  4210. std::vector<Record *> Subjects =
  4211. SubjectObj->getValueAsListOfDefs("Subjects");
  4212. OS << " (";
  4213. bool PrintComma = false;
  4214. for (const auto &Subject : llvm::enumerate(Subjects)) {
  4215. if (!isSupportedPragmaClangAttributeSubject(*Subject.value()))
  4216. continue;
  4217. if (PrintComma)
  4218. OS << ", ";
  4219. PrintComma = true;
  4220. PragmaClangAttributeSupport::RuleOrAggregateRuleSet &RuleSet =
  4221. Support.SubjectsToRules.find(Subject.value())->getSecond();
  4222. if (RuleSet.isRule()) {
  4223. OS << RuleSet.getRule().getEnumValueName();
  4224. continue;
  4225. }
  4226. OS << "(";
  4227. for (const auto &Rule : llvm::enumerate(RuleSet.getAggregateRuleSet())) {
  4228. if (Rule.index())
  4229. OS << ", ";
  4230. OS << Rule.value().getEnumValueName();
  4231. }
  4232. OS << ")";
  4233. }
  4234. OS << ")\n";
  4235. }
  4236. OS << "End of supported attributes.\n";
  4237. }
  4238. } // end namespace clang