ClangAttrEmitter.cpp 162 KB

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