SemaDeclAttr.cpp 301 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628
  1. //===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements decl-related attribute processing.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ASTConsumer.h"
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/ASTMutationListener.h"
  15. #include "clang/AST/CXXInheritance.h"
  16. #include "clang/AST/DeclCXX.h"
  17. #include "clang/AST/DeclObjC.h"
  18. #include "clang/AST/DeclTemplate.h"
  19. #include "clang/AST/Expr.h"
  20. #include "clang/AST/ExprCXX.h"
  21. #include "clang/AST/Mangle.h"
  22. #include "clang/AST/RecursiveASTVisitor.h"
  23. #include "clang/Basic/CharInfo.h"
  24. #include "clang/Basic/SourceManager.h"
  25. #include "clang/Basic/TargetInfo.h"
  26. #include "clang/Lex/Preprocessor.h"
  27. #include "clang/Sema/DeclSpec.h"
  28. #include "clang/Sema/DelayedDiagnostic.h"
  29. #include "clang/Sema/Initialization.h"
  30. #include "clang/Sema/Lookup.h"
  31. #include "clang/Sema/Scope.h"
  32. #include "clang/Sema/ScopeInfo.h"
  33. #include "clang/Sema/SemaInternal.h"
  34. #include "llvm/ADT/STLExtras.h"
  35. #include "llvm/ADT/StringExtras.h"
  36. #include "llvm/Support/MathExtras.h"
  37. using namespace clang;
  38. using namespace sema;
  39. namespace AttributeLangSupport {
  40. enum LANG {
  41. C,
  42. Cpp,
  43. ObjC
  44. };
  45. } // end namespace AttributeLangSupport
  46. //===----------------------------------------------------------------------===//
  47. // Helper functions
  48. //===----------------------------------------------------------------------===//
  49. /// isFunctionOrMethod - Return true if the given decl has function
  50. /// type (function or function-typed variable) or an Objective-C
  51. /// method.
  52. static bool isFunctionOrMethod(const Decl *D) {
  53. return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
  54. }
  55. /// Return true if the given decl has function type (function or
  56. /// function-typed variable) or an Objective-C method or a block.
  57. static bool isFunctionOrMethodOrBlock(const Decl *D) {
  58. return isFunctionOrMethod(D) || isa<BlockDecl>(D);
  59. }
  60. /// Return true if the given decl has a declarator that should have
  61. /// been processed by Sema::GetTypeForDeclarator.
  62. static bool hasDeclarator(const Decl *D) {
  63. // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
  64. return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
  65. isa<ObjCPropertyDecl>(D);
  66. }
  67. /// hasFunctionProto - Return true if the given decl has a argument
  68. /// information. This decl should have already passed
  69. /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
  70. static bool hasFunctionProto(const Decl *D) {
  71. if (const FunctionType *FnTy = D->getFunctionType())
  72. return isa<FunctionProtoType>(FnTy);
  73. return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
  74. }
  75. /// getFunctionOrMethodNumParams - Return number of function or method
  76. /// parameters. It is an error to call this on a K&R function (use
  77. /// hasFunctionProto first).
  78. static unsigned getFunctionOrMethodNumParams(const Decl *D) {
  79. if (const FunctionType *FnTy = D->getFunctionType())
  80. return cast<FunctionProtoType>(FnTy)->getNumParams();
  81. if (const auto *BD = dyn_cast<BlockDecl>(D))
  82. return BD->getNumParams();
  83. return cast<ObjCMethodDecl>(D)->param_size();
  84. }
  85. static const ParmVarDecl *getFunctionOrMethodParam(const Decl *D,
  86. unsigned Idx) {
  87. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  88. return FD->getParamDecl(Idx);
  89. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  90. return MD->getParamDecl(Idx);
  91. if (const auto *BD = dyn_cast<BlockDecl>(D))
  92. return BD->getParamDecl(Idx);
  93. return nullptr;
  94. }
  95. static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
  96. if (const FunctionType *FnTy = D->getFunctionType())
  97. return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
  98. if (const auto *BD = dyn_cast<BlockDecl>(D))
  99. return BD->getParamDecl(Idx)->getType();
  100. return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
  101. }
  102. static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
  103. if (auto *PVD = getFunctionOrMethodParam(D, Idx))
  104. return PVD->getSourceRange();
  105. return SourceRange();
  106. }
  107. static QualType getFunctionOrMethodResultType(const Decl *D) {
  108. if (const FunctionType *FnTy = D->getFunctionType())
  109. return FnTy->getReturnType();
  110. return cast<ObjCMethodDecl>(D)->getReturnType();
  111. }
  112. static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
  113. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  114. return FD->getReturnTypeSourceRange();
  115. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  116. return MD->getReturnTypeSourceRange();
  117. return SourceRange();
  118. }
  119. static bool isFunctionOrMethodVariadic(const Decl *D) {
  120. if (const FunctionType *FnTy = D->getFunctionType())
  121. return cast<FunctionProtoType>(FnTy)->isVariadic();
  122. if (const auto *BD = dyn_cast<BlockDecl>(D))
  123. return BD->isVariadic();
  124. return cast<ObjCMethodDecl>(D)->isVariadic();
  125. }
  126. static bool isInstanceMethod(const Decl *D) {
  127. if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(D))
  128. return MethodDecl->isInstance();
  129. return false;
  130. }
  131. static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
  132. const auto *PT = T->getAs<ObjCObjectPointerType>();
  133. if (!PT)
  134. return false;
  135. ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
  136. if (!Cls)
  137. return false;
  138. IdentifierInfo* ClsName = Cls->getIdentifier();
  139. // FIXME: Should we walk the chain of classes?
  140. return ClsName == &Ctx.Idents.get("NSString") ||
  141. ClsName == &Ctx.Idents.get("NSMutableString");
  142. }
  143. static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
  144. const auto *PT = T->getAs<PointerType>();
  145. if (!PT)
  146. return false;
  147. const auto *RT = PT->getPointeeType()->getAs<RecordType>();
  148. if (!RT)
  149. return false;
  150. const RecordDecl *RD = RT->getDecl();
  151. if (RD->getTagKind() != TTK_Struct)
  152. return false;
  153. return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
  154. }
  155. static unsigned getNumAttributeArgs(const ParsedAttr &AL) {
  156. // FIXME: Include the type in the argument list.
  157. return AL.getNumArgs() + AL.hasParsedType();
  158. }
  159. template <typename Compare>
  160. static bool checkAttributeNumArgsImpl(Sema &S, const ParsedAttr &AL,
  161. unsigned Num, unsigned Diag,
  162. Compare Comp) {
  163. if (Comp(getNumAttributeArgs(AL), Num)) {
  164. S.Diag(AL.getLoc(), Diag) << AL << Num;
  165. return false;
  166. }
  167. return true;
  168. }
  169. /// Check if the attribute has exactly as many args as Num. May
  170. /// output an error.
  171. static bool checkAttributeNumArgs(Sema &S, const ParsedAttr &AL, unsigned Num) {
  172. return checkAttributeNumArgsImpl(S, AL, Num,
  173. diag::err_attribute_wrong_number_arguments,
  174. std::not_equal_to<unsigned>());
  175. }
  176. /// Check if the attribute has at least as many args as Num. May
  177. /// output an error.
  178. static bool checkAttributeAtLeastNumArgs(Sema &S, const ParsedAttr &AL,
  179. unsigned Num) {
  180. return checkAttributeNumArgsImpl(S, AL, Num,
  181. diag::err_attribute_too_few_arguments,
  182. std::less<unsigned>());
  183. }
  184. /// Check if the attribute has at most as many args as Num. May
  185. /// output an error.
  186. static bool checkAttributeAtMostNumArgs(Sema &S, const ParsedAttr &AL,
  187. unsigned Num) {
  188. return checkAttributeNumArgsImpl(S, AL, Num,
  189. diag::err_attribute_too_many_arguments,
  190. std::greater<unsigned>());
  191. }
  192. /// A helper function to provide Attribute Location for the Attr types
  193. /// AND the ParsedAttr.
  194. template <typename AttrInfo>
  195. static typename std::enable_if<std::is_base_of<Attr, AttrInfo>::value,
  196. SourceLocation>::type
  197. getAttrLoc(const AttrInfo &AL) {
  198. return AL.getLocation();
  199. }
  200. static SourceLocation getAttrLoc(const ParsedAttr &AL) { return AL.getLoc(); }
  201. /// If Expr is a valid integer constant, get the value of the integer
  202. /// expression and return success or failure. May output an error.
  203. ///
  204. /// Negative argument is implicitly converted to unsigned, unless
  205. /// \p StrictlyUnsigned is true.
  206. template <typename AttrInfo>
  207. static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr,
  208. uint32_t &Val, unsigned Idx = UINT_MAX,
  209. bool StrictlyUnsigned = false) {
  210. llvm::APSInt I(32);
  211. if (Expr->isTypeDependent() || Expr->isValueDependent() ||
  212. !Expr->isIntegerConstantExpr(I, S.Context)) {
  213. if (Idx != UINT_MAX)
  214. S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
  215. << &AI << Idx << AANT_ArgumentIntegerConstant
  216. << Expr->getSourceRange();
  217. else
  218. S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
  219. << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
  220. return false;
  221. }
  222. if (!I.isIntN(32)) {
  223. S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
  224. << I.toString(10, false) << 32 << /* Unsigned */ 1;
  225. return false;
  226. }
  227. if (StrictlyUnsigned && I.isSigned() && I.isNegative()) {
  228. S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
  229. << &AI << /*non-negative*/ 1;
  230. return false;
  231. }
  232. Val = (uint32_t)I.getZExtValue();
  233. return true;
  234. }
  235. /// Wrapper around checkUInt32Argument, with an extra check to be sure
  236. /// that the result will fit into a regular (signed) int. All args have the same
  237. /// purpose as they do in checkUInt32Argument.
  238. template <typename AttrInfo>
  239. static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
  240. int &Val, unsigned Idx = UINT_MAX) {
  241. uint32_t UVal;
  242. if (!checkUInt32Argument(S, AI, Expr, UVal, Idx))
  243. return false;
  244. if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
  245. llvm::APSInt I(32); // for toString
  246. I = UVal;
  247. S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
  248. << I.toString(10, false) << 32 << /* Unsigned */ 0;
  249. return false;
  250. }
  251. Val = UVal;
  252. return true;
  253. }
  254. /// Diagnose mutually exclusive attributes when present on a given
  255. /// declaration. Returns true if diagnosed.
  256. template <typename AttrTy>
  257. static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) {
  258. if (const auto *A = D->getAttr<AttrTy>()) {
  259. S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << A;
  260. S.Diag(A->getLocation(), diag::note_conflicting_attribute);
  261. return true;
  262. }
  263. return false;
  264. }
  265. template <typename AttrTy>
  266. static bool checkAttrMutualExclusion(Sema &S, Decl *D, const Attr &AL) {
  267. if (const auto *A = D->getAttr<AttrTy>()) {
  268. S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible) << &AL
  269. << A;
  270. S.Diag(A->getLocation(), diag::note_conflicting_attribute);
  271. return true;
  272. }
  273. return false;
  274. }
  275. /// Check if IdxExpr is a valid parameter index for a function or
  276. /// instance method D. May output an error.
  277. ///
  278. /// \returns true if IdxExpr is a valid index.
  279. template <typename AttrInfo>
  280. static bool checkFunctionOrMethodParameterIndex(
  281. Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
  282. const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) {
  283. assert(isFunctionOrMethodOrBlock(D));
  284. // In C++ the implicit 'this' function parameter also counts.
  285. // Parameters are counted from one.
  286. bool HP = hasFunctionProto(D);
  287. bool HasImplicitThisParam = isInstanceMethod(D);
  288. bool IV = HP && isFunctionOrMethodVariadic(D);
  289. unsigned NumParams =
  290. (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
  291. llvm::APSInt IdxInt;
  292. if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
  293. !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
  294. S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
  295. << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
  296. << IdxExpr->getSourceRange();
  297. return false;
  298. }
  299. unsigned IdxSource = IdxInt.getLimitedValue(UINT_MAX);
  300. if (IdxSource < 1 || (!IV && IdxSource > NumParams)) {
  301. S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
  302. << &AI << AttrArgNum << IdxExpr->getSourceRange();
  303. return false;
  304. }
  305. if (HasImplicitThisParam && !CanIndexImplicitThis) {
  306. if (IdxSource == 1) {
  307. S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
  308. << &AI << IdxExpr->getSourceRange();
  309. return false;
  310. }
  311. }
  312. Idx = ParamIdx(IdxSource, D);
  313. return true;
  314. }
  315. /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
  316. /// If not emit an error and return false. If the argument is an identifier it
  317. /// will emit an error with a fixit hint and treat it as if it was a string
  318. /// literal.
  319. bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
  320. StringRef &Str,
  321. SourceLocation *ArgLocation) {
  322. // Look for identifiers. If we have one emit a hint to fix it to a literal.
  323. if (AL.isArgIdent(ArgNum)) {
  324. IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum);
  325. Diag(Loc->Loc, diag::err_attribute_argument_type)
  326. << AL << AANT_ArgumentString
  327. << FixItHint::CreateInsertion(Loc->Loc, "\"")
  328. << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
  329. Str = Loc->Ident->getName();
  330. if (ArgLocation)
  331. *ArgLocation = Loc->Loc;
  332. return true;
  333. }
  334. // Now check for an actual string literal.
  335. Expr *ArgExpr = AL.getArgAsExpr(ArgNum);
  336. const auto *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
  337. if (ArgLocation)
  338. *ArgLocation = ArgExpr->getBeginLoc();
  339. if (!Literal || !Literal->isAscii()) {
  340. Diag(ArgExpr->getBeginLoc(), diag::err_attribute_argument_type)
  341. << AL << AANT_ArgumentString;
  342. return false;
  343. }
  344. Str = Literal->getString();
  345. return true;
  346. }
  347. /// Applies the given attribute to the Decl without performing any
  348. /// additional semantic checking.
  349. template <typename AttrType>
  350. static void handleSimpleAttribute(Sema &S, Decl *D, SourceRange SR,
  351. unsigned SpellingIndex) {
  352. D->addAttr(::new (S.Context) AttrType(SR, S.Context, SpellingIndex));
  353. }
  354. template <typename AttrType>
  355. static void handleSimpleAttribute(Sema &S, Decl *D, const ParsedAttr &AL) {
  356. handleSimpleAttribute<AttrType>(S, D, AL.getRange(),
  357. AL.getAttributeSpellingListIndex());
  358. }
  359. template <typename... DiagnosticArgs>
  360. static const Sema::SemaDiagnosticBuilder&
  361. appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr) {
  362. return Bldr;
  363. }
  364. template <typename T, typename... DiagnosticArgs>
  365. static const Sema::SemaDiagnosticBuilder&
  366. appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr, T &&ExtraArg,
  367. DiagnosticArgs &&... ExtraArgs) {
  368. return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
  369. std::forward<DiagnosticArgs>(ExtraArgs)...);
  370. }
  371. /// Add an attribute {@code AttrType} to declaration {@code D}, provided that
  372. /// {@code PassesCheck} is true.
  373. /// Otherwise, emit diagnostic {@code DiagID}, passing in all parameters
  374. /// specified in {@code ExtraArgs}.
  375. template <typename AttrType, typename... DiagnosticArgs>
  376. static void
  377. handleSimpleAttributeOrDiagnose(Sema &S, Decl *D, SourceRange SR,
  378. unsigned SpellingIndex,
  379. bool PassesCheck,
  380. unsigned DiagID, DiagnosticArgs&&... ExtraArgs) {
  381. if (!PassesCheck) {
  382. Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
  383. appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
  384. return;
  385. }
  386. handleSimpleAttribute<AttrType>(S, D, SR, SpellingIndex);
  387. }
  388. template <typename AttrType, typename... DiagnosticArgs>
  389. static void
  390. handleSimpleAttributeOrDiagnose(Sema &S, Decl *D, const ParsedAttr &AL,
  391. bool PassesCheck,
  392. unsigned DiagID,
  393. DiagnosticArgs&&... ExtraArgs) {
  394. return handleSimpleAttributeOrDiagnose<AttrType>(
  395. S, D, AL.getRange(), AL.getAttributeSpellingListIndex(), PassesCheck,
  396. DiagID, std::forward<DiagnosticArgs>(ExtraArgs)...);
  397. }
  398. template <typename AttrType>
  399. static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
  400. const ParsedAttr &AL) {
  401. handleSimpleAttribute<AttrType>(S, D, AL);
  402. }
  403. /// Applies the given attribute to the Decl so long as the Decl doesn't
  404. /// already have one of the given incompatible attributes.
  405. template <typename AttrType, typename IncompatibleAttrType,
  406. typename... IncompatibleAttrTypes>
  407. static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
  408. const ParsedAttr &AL) {
  409. if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, AL))
  410. return;
  411. handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
  412. AL);
  413. }
  414. /// Check if the passed-in expression is of type int or bool.
  415. static bool isIntOrBool(Expr *Exp) {
  416. QualType QT = Exp->getType();
  417. return QT->isBooleanType() || QT->isIntegerType();
  418. }
  419. // Check to see if the type is a smart pointer of some kind. We assume
  420. // it's a smart pointer if it defines both operator-> and operator*.
  421. static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
  422. auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record,
  423. OverloadedOperatorKind Op) {
  424. DeclContextLookupResult Result =
  425. Record->lookup(S.Context.DeclarationNames.getCXXOperatorName(Op));
  426. return !Result.empty();
  427. };
  428. const RecordDecl *Record = RT->getDecl();
  429. bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
  430. bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
  431. if (foundStarOperator && foundArrowOperator)
  432. return true;
  433. const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record);
  434. if (!CXXRecord)
  435. return false;
  436. for (auto BaseSpecifier : CXXRecord->bases()) {
  437. if (!foundStarOperator)
  438. foundStarOperator = IsOverloadedOperatorPresent(
  439. BaseSpecifier.getType()->getAsRecordDecl(), OO_Star);
  440. if (!foundArrowOperator)
  441. foundArrowOperator = IsOverloadedOperatorPresent(
  442. BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow);
  443. }
  444. if (foundStarOperator && foundArrowOperator)
  445. return true;
  446. return false;
  447. }
  448. /// Check if passed in Decl is a pointer type.
  449. /// Note that this function may produce an error message.
  450. /// \return true if the Decl is a pointer type; false otherwise
  451. static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
  452. const ParsedAttr &AL) {
  453. const auto *VD = cast<ValueDecl>(D);
  454. QualType QT = VD->getType();
  455. if (QT->isAnyPointerType())
  456. return true;
  457. if (const auto *RT = QT->getAs<RecordType>()) {
  458. // If it's an incomplete type, it could be a smart pointer; skip it.
  459. // (We don't want to force template instantiation if we can avoid it,
  460. // since that would alter the order in which templates are instantiated.)
  461. if (RT->isIncompleteType())
  462. return true;
  463. if (threadSafetyCheckIsSmartPointer(S, RT))
  464. return true;
  465. }
  466. S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT;
  467. return false;
  468. }
  469. /// Checks that the passed in QualType either is of RecordType or points
  470. /// to RecordType. Returns the relevant RecordType, null if it does not exit.
  471. static const RecordType *getRecordType(QualType QT) {
  472. if (const auto *RT = QT->getAs<RecordType>())
  473. return RT;
  474. // Now check if we point to record type.
  475. if (const auto *PT = QT->getAs<PointerType>())
  476. return PT->getPointeeType()->getAs<RecordType>();
  477. return nullptr;
  478. }
  479. template <typename AttrType>
  480. static bool checkRecordDeclForAttr(const RecordDecl *RD) {
  481. // Check if the record itself has the attribute.
  482. if (RD->hasAttr<AttrType>())
  483. return true;
  484. // Else check if any base classes have the attribute.
  485. if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  486. CXXBasePaths BPaths(false, false);
  487. if (CRD->lookupInBases(
  488. [](const CXXBaseSpecifier *BS, CXXBasePath &) {
  489. const auto &Ty = *BS->getType();
  490. // If it's type-dependent, we assume it could have the attribute.
  491. if (Ty.isDependentType())
  492. return true;
  493. return Ty.getAs<RecordType>()->getDecl()->hasAttr<AttrType>();
  494. },
  495. BPaths, true))
  496. return true;
  497. }
  498. return false;
  499. }
  500. static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
  501. const RecordType *RT = getRecordType(Ty);
  502. if (!RT)
  503. return false;
  504. // Don't check for the capability if the class hasn't been defined yet.
  505. if (RT->isIncompleteType())
  506. return true;
  507. // Allow smart pointers to be used as capability objects.
  508. // FIXME -- Check the type that the smart pointer points to.
  509. if (threadSafetyCheckIsSmartPointer(S, RT))
  510. return true;
  511. return checkRecordDeclForAttr<CapabilityAttr>(RT->getDecl());
  512. }
  513. static bool checkTypedefTypeForCapability(QualType Ty) {
  514. const auto *TD = Ty->getAs<TypedefType>();
  515. if (!TD)
  516. return false;
  517. TypedefNameDecl *TN = TD->getDecl();
  518. if (!TN)
  519. return false;
  520. return TN->hasAttr<CapabilityAttr>();
  521. }
  522. static bool typeHasCapability(Sema &S, QualType Ty) {
  523. if (checkTypedefTypeForCapability(Ty))
  524. return true;
  525. if (checkRecordTypeForCapability(S, Ty))
  526. return true;
  527. return false;
  528. }
  529. static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
  530. // Capability expressions are simple expressions involving the boolean logic
  531. // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
  532. // a DeclRefExpr is found, its type should be checked to determine whether it
  533. // is a capability or not.
  534. if (const auto *E = dyn_cast<CastExpr>(Ex))
  535. return isCapabilityExpr(S, E->getSubExpr());
  536. else if (const auto *E = dyn_cast<ParenExpr>(Ex))
  537. return isCapabilityExpr(S, E->getSubExpr());
  538. else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
  539. if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
  540. E->getOpcode() == UO_Deref)
  541. return isCapabilityExpr(S, E->getSubExpr());
  542. return false;
  543. } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
  544. if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
  545. return isCapabilityExpr(S, E->getLHS()) &&
  546. isCapabilityExpr(S, E->getRHS());
  547. return false;
  548. }
  549. return typeHasCapability(S, Ex->getType());
  550. }
  551. /// Checks that all attribute arguments, starting from Sidx, resolve to
  552. /// a capability object.
  553. /// \param Sidx The attribute argument index to start checking with.
  554. /// \param ParamIdxOk Whether an argument can be indexing into a function
  555. /// parameter list.
  556. static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
  557. const ParsedAttr &AL,
  558. SmallVectorImpl<Expr *> &Args,
  559. unsigned Sidx = 0,
  560. bool ParamIdxOk = false) {
  561. if (Sidx == AL.getNumArgs()) {
  562. // If we don't have any capability arguments, the attribute implicitly
  563. // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
  564. // a non-static method, and that the class is a (scoped) capability.
  565. const auto *MD = dyn_cast<const CXXMethodDecl>(D);
  566. if (MD && !MD->isStatic()) {
  567. const CXXRecordDecl *RD = MD->getParent();
  568. // FIXME -- need to check this again on template instantiation
  569. if (!checkRecordDeclForAttr<CapabilityAttr>(RD) &&
  570. !checkRecordDeclForAttr<ScopedLockableAttr>(RD))
  571. S.Diag(AL.getLoc(),
  572. diag::warn_thread_attribute_not_on_capability_member)
  573. << AL << MD->getParent();
  574. } else {
  575. S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member)
  576. << AL;
  577. }
  578. }
  579. for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) {
  580. Expr *ArgExp = AL.getArgAsExpr(Idx);
  581. if (ArgExp->isTypeDependent()) {
  582. // FIXME -- need to check this again on template instantiation
  583. Args.push_back(ArgExp);
  584. continue;
  585. }
  586. if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
  587. if (StrLit->getLength() == 0 ||
  588. (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
  589. // Pass empty strings to the analyzer without warnings.
  590. // Treat "*" as the universal lock.
  591. Args.push_back(ArgExp);
  592. continue;
  593. }
  594. // We allow constant strings to be used as a placeholder for expressions
  595. // that are not valid C++ syntax, but warn that they are ignored.
  596. S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL;
  597. Args.push_back(ArgExp);
  598. continue;
  599. }
  600. QualType ArgTy = ArgExp->getType();
  601. // A pointer to member expression of the form &MyClass::mu is treated
  602. // specially -- we need to look at the type of the member.
  603. if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp))
  604. if (UOp->getOpcode() == UO_AddrOf)
  605. if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
  606. if (DRE->getDecl()->isCXXInstanceMember())
  607. ArgTy = DRE->getDecl()->getType();
  608. // First see if we can just cast to record type, or pointer to record type.
  609. const RecordType *RT = getRecordType(ArgTy);
  610. // Now check if we index into a record type function param.
  611. if(!RT && ParamIdxOk) {
  612. const auto *FD = dyn_cast<FunctionDecl>(D);
  613. const auto *IL = dyn_cast<IntegerLiteral>(ArgExp);
  614. if(FD && IL) {
  615. unsigned int NumParams = FD->getNumParams();
  616. llvm::APInt ArgValue = IL->getValue();
  617. uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
  618. uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
  619. if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
  620. S.Diag(AL.getLoc(),
  621. diag::err_attribute_argument_out_of_bounds_extra_info)
  622. << AL << Idx + 1 << NumParams;
  623. continue;
  624. }
  625. ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
  626. }
  627. }
  628. // If the type does not have a capability, see if the components of the
  629. // expression have capabilities. This allows for writing C code where the
  630. // capability may be on the type, and the expression is a capability
  631. // boolean logic expression. Eg) requires_capability(A || B && !C)
  632. if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
  633. S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
  634. << AL << ArgTy;
  635. Args.push_back(ArgExp);
  636. }
  637. }
  638. //===----------------------------------------------------------------------===//
  639. // Attribute Implementations
  640. //===----------------------------------------------------------------------===//
  641. static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  642. if (!threadSafetyCheckIsPointer(S, D, AL))
  643. return;
  644. D->addAttr(::new (S.Context)
  645. PtGuardedVarAttr(AL.getRange(), S.Context,
  646. AL.getAttributeSpellingListIndex()));
  647. }
  648. static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
  649. Expr *&Arg) {
  650. SmallVector<Expr *, 1> Args;
  651. // check that all arguments are lockable objects
  652. checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
  653. unsigned Size = Args.size();
  654. if (Size != 1)
  655. return false;
  656. Arg = Args[0];
  657. return true;
  658. }
  659. static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  660. Expr *Arg = nullptr;
  661. if (!checkGuardedByAttrCommon(S, D, AL, Arg))
  662. return;
  663. D->addAttr(::new (S.Context) GuardedByAttr(
  664. AL.getRange(), S.Context, Arg, AL.getAttributeSpellingListIndex()));
  665. }
  666. static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  667. Expr *Arg = nullptr;
  668. if (!checkGuardedByAttrCommon(S, D, AL, Arg))
  669. return;
  670. if (!threadSafetyCheckIsPointer(S, D, AL))
  671. return;
  672. D->addAttr(::new (S.Context) PtGuardedByAttr(
  673. AL.getRange(), S.Context, Arg, AL.getAttributeSpellingListIndex()));
  674. }
  675. static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
  676. SmallVectorImpl<Expr *> &Args) {
  677. if (!checkAttributeAtLeastNumArgs(S, AL, 1))
  678. return false;
  679. // Check that this attribute only applies to lockable types.
  680. QualType QT = cast<ValueDecl>(D)->getType();
  681. if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
  682. S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << AL;
  683. return false;
  684. }
  685. // Check that all arguments are lockable objects.
  686. checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
  687. if (Args.empty())
  688. return false;
  689. return true;
  690. }
  691. static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  692. SmallVector<Expr *, 1> Args;
  693. if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
  694. return;
  695. Expr **StartArg = &Args[0];
  696. D->addAttr(::new (S.Context) AcquiredAfterAttr(
  697. AL.getRange(), S.Context, StartArg, Args.size(),
  698. AL.getAttributeSpellingListIndex()));
  699. }
  700. static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  701. SmallVector<Expr *, 1> Args;
  702. if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
  703. return;
  704. Expr **StartArg = &Args[0];
  705. D->addAttr(::new (S.Context) AcquiredBeforeAttr(
  706. AL.getRange(), S.Context, StartArg, Args.size(),
  707. AL.getAttributeSpellingListIndex()));
  708. }
  709. static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
  710. SmallVectorImpl<Expr *> &Args) {
  711. // zero or more arguments ok
  712. // check that all arguments are lockable objects
  713. checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true);
  714. return true;
  715. }
  716. static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  717. SmallVector<Expr *, 1> Args;
  718. if (!checkLockFunAttrCommon(S, D, AL, Args))
  719. return;
  720. unsigned Size = Args.size();
  721. Expr **StartArg = Size == 0 ? nullptr : &Args[0];
  722. D->addAttr(::new (S.Context)
  723. AssertSharedLockAttr(AL.getRange(), S.Context, StartArg, Size,
  724. AL.getAttributeSpellingListIndex()));
  725. }
  726. static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
  727. const ParsedAttr &AL) {
  728. SmallVector<Expr *, 1> Args;
  729. if (!checkLockFunAttrCommon(S, D, AL, Args))
  730. return;
  731. unsigned Size = Args.size();
  732. Expr **StartArg = Size == 0 ? nullptr : &Args[0];
  733. D->addAttr(::new (S.Context) AssertExclusiveLockAttr(
  734. AL.getRange(), S.Context, StartArg, Size,
  735. AL.getAttributeSpellingListIndex()));
  736. }
  737. /// Checks to be sure that the given parameter number is in bounds, and
  738. /// is an integral type. Will emit appropriate diagnostics if this returns
  739. /// false.
  740. ///
  741. /// AttrArgNo is used to actually retrieve the argument, so it's base-0.
  742. template <typename AttrInfo>
  743. static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
  744. const AttrInfo &AI, unsigned AttrArgNo) {
  745. assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument");
  746. Expr *AttrArg = AI.getArgAsExpr(AttrArgNo);
  747. ParamIdx Idx;
  748. if (!checkFunctionOrMethodParameterIndex(S, FD, AI, AttrArgNo + 1, AttrArg,
  749. Idx))
  750. return false;
  751. const ParmVarDecl *Param = FD->getParamDecl(Idx.getASTIndex());
  752. if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) {
  753. SourceLocation SrcLoc = AttrArg->getBeginLoc();
  754. S.Diag(SrcLoc, diag::err_attribute_integers_only)
  755. << AI << Param->getSourceRange();
  756. return false;
  757. }
  758. return true;
  759. }
  760. static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  761. if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
  762. !checkAttributeAtMostNumArgs(S, AL, 2))
  763. return;
  764. const auto *FD = cast<FunctionDecl>(D);
  765. if (!FD->getReturnType()->isPointerType()) {
  766. S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL;
  767. return;
  768. }
  769. const Expr *SizeExpr = AL.getArgAsExpr(0);
  770. int SizeArgNoVal;
  771. // Parameter indices are 1-indexed, hence Index=1
  772. if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNoVal, /*Index=*/1))
  773. return;
  774. if (!checkParamIsIntegerType(S, FD, AL, /*AttrArgNo=*/0))
  775. return;
  776. ParamIdx SizeArgNo(SizeArgNoVal, D);
  777. ParamIdx NumberArgNo;
  778. if (AL.getNumArgs() == 2) {
  779. const Expr *NumberExpr = AL.getArgAsExpr(1);
  780. int Val;
  781. // Parameter indices are 1-based, hence Index=2
  782. if (!checkPositiveIntArgument(S, AL, NumberExpr, Val, /*Index=*/2))
  783. return;
  784. if (!checkParamIsIntegerType(S, FD, AL, /*AttrArgNo=*/1))
  785. return;
  786. NumberArgNo = ParamIdx(Val, D);
  787. }
  788. D->addAttr(::new (S.Context)
  789. AllocSizeAttr(AL.getRange(), S.Context, SizeArgNo, NumberArgNo,
  790. AL.getAttributeSpellingListIndex()));
  791. }
  792. static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
  793. SmallVectorImpl<Expr *> &Args) {
  794. if (!checkAttributeAtLeastNumArgs(S, AL, 1))
  795. return false;
  796. if (!isIntOrBool(AL.getArgAsExpr(0))) {
  797. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  798. << AL << 1 << AANT_ArgumentIntOrBool;
  799. return false;
  800. }
  801. // check that all arguments are lockable objects
  802. checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1);
  803. return true;
  804. }
  805. static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
  806. const ParsedAttr &AL) {
  807. SmallVector<Expr*, 2> Args;
  808. if (!checkTryLockFunAttrCommon(S, D, AL, Args))
  809. return;
  810. D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(
  811. AL.getRange(), S.Context, AL.getArgAsExpr(0), Args.data(), Args.size(),
  812. AL.getAttributeSpellingListIndex()));
  813. }
  814. static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
  815. const ParsedAttr &AL) {
  816. SmallVector<Expr*, 2> Args;
  817. if (!checkTryLockFunAttrCommon(S, D, AL, Args))
  818. return;
  819. D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
  820. AL.getRange(), S.Context, AL.getArgAsExpr(0), Args.data(),
  821. Args.size(), AL.getAttributeSpellingListIndex()));
  822. }
  823. static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  824. // check that the argument is lockable object
  825. SmallVector<Expr*, 1> Args;
  826. checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
  827. unsigned Size = Args.size();
  828. if (Size == 0)
  829. return;
  830. D->addAttr(::new (S.Context)
  831. LockReturnedAttr(AL.getRange(), S.Context, Args[0],
  832. AL.getAttributeSpellingListIndex()));
  833. }
  834. static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  835. if (!checkAttributeAtLeastNumArgs(S, AL, 1))
  836. return;
  837. // check that all arguments are lockable objects
  838. SmallVector<Expr*, 1> Args;
  839. checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
  840. unsigned Size = Args.size();
  841. if (Size == 0)
  842. return;
  843. Expr **StartArg = &Args[0];
  844. D->addAttr(::new (S.Context)
  845. LocksExcludedAttr(AL.getRange(), S.Context, StartArg, Size,
  846. AL.getAttributeSpellingListIndex()));
  847. }
  848. static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL,
  849. Expr *&Cond, StringRef &Msg) {
  850. Cond = AL.getArgAsExpr(0);
  851. if (!Cond->isTypeDependent()) {
  852. ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
  853. if (Converted.isInvalid())
  854. return false;
  855. Cond = Converted.get();
  856. }
  857. if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg))
  858. return false;
  859. if (Msg.empty())
  860. Msg = "<no message provided>";
  861. SmallVector<PartialDiagnosticAt, 8> Diags;
  862. if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
  863. !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
  864. Diags)) {
  865. S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) << AL;
  866. for (const PartialDiagnosticAt &PDiag : Diags)
  867. S.Diag(PDiag.first, PDiag.second);
  868. return false;
  869. }
  870. return true;
  871. }
  872. static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  873. S.Diag(AL.getLoc(), diag::ext_clang_enable_if);
  874. Expr *Cond;
  875. StringRef Msg;
  876. if (checkFunctionConditionAttr(S, D, AL, Cond, Msg))
  877. D->addAttr(::new (S.Context)
  878. EnableIfAttr(AL.getRange(), S.Context, Cond, Msg,
  879. AL.getAttributeSpellingListIndex()));
  880. }
  881. namespace {
  882. /// Determines if a given Expr references any of the given function's
  883. /// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
  884. class ArgumentDependenceChecker
  885. : public RecursiveASTVisitor<ArgumentDependenceChecker> {
  886. #ifndef NDEBUG
  887. const CXXRecordDecl *ClassType;
  888. #endif
  889. llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
  890. bool Result;
  891. public:
  892. ArgumentDependenceChecker(const FunctionDecl *FD) {
  893. #ifndef NDEBUG
  894. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  895. ClassType = MD->getParent();
  896. else
  897. ClassType = nullptr;
  898. #endif
  899. Parms.insert(FD->param_begin(), FD->param_end());
  900. }
  901. bool referencesArgs(Expr *E) {
  902. Result = false;
  903. TraverseStmt(E);
  904. return Result;
  905. }
  906. bool VisitCXXThisExpr(CXXThisExpr *E) {
  907. assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
  908. "`this` doesn't refer to the enclosing class?");
  909. Result = true;
  910. return false;
  911. }
  912. bool VisitDeclRefExpr(DeclRefExpr *DRE) {
  913. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  914. if (Parms.count(PVD)) {
  915. Result = true;
  916. return false;
  917. }
  918. return true;
  919. }
  920. };
  921. }
  922. static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  923. S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if);
  924. Expr *Cond;
  925. StringRef Msg;
  926. if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg))
  927. return;
  928. StringRef DiagTypeStr;
  929. if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr))
  930. return;
  931. DiagnoseIfAttr::DiagnosticType DiagType;
  932. if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
  933. S.Diag(AL.getArgAsExpr(2)->getBeginLoc(),
  934. diag::err_diagnose_if_invalid_diagnostic_type);
  935. return;
  936. }
  937. bool ArgDependent = false;
  938. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  939. ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
  940. D->addAttr(::new (S.Context) DiagnoseIfAttr(
  941. AL.getRange(), S.Context, Cond, Msg, DiagType, ArgDependent,
  942. cast<NamedDecl>(D), AL.getAttributeSpellingListIndex()));
  943. }
  944. static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  945. if (D->hasAttr<PassObjectSizeAttr>()) {
  946. S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL;
  947. return;
  948. }
  949. Expr *E = AL.getArgAsExpr(0);
  950. uint32_t Type;
  951. if (!checkUInt32Argument(S, AL, E, Type, /*Idx=*/1))
  952. return;
  953. // pass_object_size's argument is passed in as the second argument of
  954. // __builtin_object_size. So, it has the same constraints as that second
  955. // argument; namely, it must be in the range [0, 3].
  956. if (Type > 3) {
  957. S.Diag(E->getBeginLoc(), diag::err_attribute_argument_out_of_range)
  958. << AL << 0 << 3 << E->getSourceRange();
  959. return;
  960. }
  961. // pass_object_size is only supported on constant pointer parameters; as a
  962. // kindness to users, we allow the parameter to be non-const for declarations.
  963. // At this point, we have no clue if `D` belongs to a function declaration or
  964. // definition, so we defer the constness check until later.
  965. if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
  966. S.Diag(D->getBeginLoc(), diag::err_attribute_pointers_only) << AL << 1;
  967. return;
  968. }
  969. D->addAttr(::new (S.Context) PassObjectSizeAttr(
  970. AL.getRange(), S.Context, (int)Type, AL.getAttributeSpellingListIndex()));
  971. }
  972. static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  973. ConsumableAttr::ConsumedState DefaultState;
  974. if (AL.isArgIdent(0)) {
  975. IdentifierLoc *IL = AL.getArgAsIdent(0);
  976. if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
  977. DefaultState)) {
  978. S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
  979. << IL->Ident;
  980. return;
  981. }
  982. } else {
  983. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  984. << AL << AANT_ArgumentIdentifier;
  985. return;
  986. }
  987. D->addAttr(::new (S.Context)
  988. ConsumableAttr(AL.getRange(), S.Context, DefaultState,
  989. AL.getAttributeSpellingListIndex()));
  990. }
  991. static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
  992. const ParsedAttr &AL) {
  993. QualType ThisType = MD->getThisType()->getPointeeType();
  994. if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
  995. if (!RD->hasAttr<ConsumableAttr>()) {
  996. S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) <<
  997. RD->getNameAsString();
  998. return false;
  999. }
  1000. }
  1001. return true;
  1002. }
  1003. static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1004. if (!checkAttributeAtLeastNumArgs(S, AL, 1))
  1005. return;
  1006. if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
  1007. return;
  1008. SmallVector<CallableWhenAttr::ConsumedState, 3> States;
  1009. for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
  1010. CallableWhenAttr::ConsumedState CallableState;
  1011. StringRef StateString;
  1012. SourceLocation Loc;
  1013. if (AL.isArgIdent(ArgIndex)) {
  1014. IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
  1015. StateString = Ident->Ident->getName();
  1016. Loc = Ident->Loc;
  1017. } else {
  1018. if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc))
  1019. return;
  1020. }
  1021. if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
  1022. CallableState)) {
  1023. S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << StateString;
  1024. return;
  1025. }
  1026. States.push_back(CallableState);
  1027. }
  1028. D->addAttr(::new (S.Context)
  1029. CallableWhenAttr(AL.getRange(), S.Context, States.data(),
  1030. States.size(), AL.getAttributeSpellingListIndex()));
  1031. }
  1032. static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1033. ParamTypestateAttr::ConsumedState ParamState;
  1034. if (AL.isArgIdent(0)) {
  1035. IdentifierLoc *Ident = AL.getArgAsIdent(0);
  1036. StringRef StateString = Ident->Ident->getName();
  1037. if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
  1038. ParamState)) {
  1039. S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
  1040. << AL << StateString;
  1041. return;
  1042. }
  1043. } else {
  1044. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  1045. << AL << AANT_ArgumentIdentifier;
  1046. return;
  1047. }
  1048. // FIXME: This check is currently being done in the analysis. It can be
  1049. // enabled here only after the parser propagates attributes at
  1050. // template specialization definition, not declaration.
  1051. //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
  1052. //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
  1053. //
  1054. //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
  1055. // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
  1056. // ReturnType.getAsString();
  1057. // return;
  1058. //}
  1059. D->addAttr(::new (S.Context)
  1060. ParamTypestateAttr(AL.getRange(), S.Context, ParamState,
  1061. AL.getAttributeSpellingListIndex()));
  1062. }
  1063. static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1064. ReturnTypestateAttr::ConsumedState ReturnState;
  1065. if (AL.isArgIdent(0)) {
  1066. IdentifierLoc *IL = AL.getArgAsIdent(0);
  1067. if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
  1068. ReturnState)) {
  1069. S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
  1070. << IL->Ident;
  1071. return;
  1072. }
  1073. } else {
  1074. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  1075. << AL << AANT_ArgumentIdentifier;
  1076. return;
  1077. }
  1078. // FIXME: This check is currently being done in the analysis. It can be
  1079. // enabled here only after the parser propagates attributes at
  1080. // template specialization definition, not declaration.
  1081. //QualType ReturnType;
  1082. //
  1083. //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
  1084. // ReturnType = Param->getType();
  1085. //
  1086. //} else if (const CXXConstructorDecl *Constructor =
  1087. // dyn_cast<CXXConstructorDecl>(D)) {
  1088. // ReturnType = Constructor->getThisType()->getPointeeType();
  1089. //
  1090. //} else {
  1091. //
  1092. // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
  1093. //}
  1094. //
  1095. //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
  1096. //
  1097. //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
  1098. // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
  1099. // ReturnType.getAsString();
  1100. // return;
  1101. //}
  1102. D->addAttr(::new (S.Context)
  1103. ReturnTypestateAttr(AL.getRange(), S.Context, ReturnState,
  1104. AL.getAttributeSpellingListIndex()));
  1105. }
  1106. static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1107. if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
  1108. return;
  1109. SetTypestateAttr::ConsumedState NewState;
  1110. if (AL.isArgIdent(0)) {
  1111. IdentifierLoc *Ident = AL.getArgAsIdent(0);
  1112. StringRef Param = Ident->Ident->getName();
  1113. if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
  1114. S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
  1115. << Param;
  1116. return;
  1117. }
  1118. } else {
  1119. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  1120. << AL << AANT_ArgumentIdentifier;
  1121. return;
  1122. }
  1123. D->addAttr(::new (S.Context)
  1124. SetTypestateAttr(AL.getRange(), S.Context, NewState,
  1125. AL.getAttributeSpellingListIndex()));
  1126. }
  1127. static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1128. if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
  1129. return;
  1130. TestTypestateAttr::ConsumedState TestState;
  1131. if (AL.isArgIdent(0)) {
  1132. IdentifierLoc *Ident = AL.getArgAsIdent(0);
  1133. StringRef Param = Ident->Ident->getName();
  1134. if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
  1135. S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
  1136. << Param;
  1137. return;
  1138. }
  1139. } else {
  1140. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  1141. << AL << AANT_ArgumentIdentifier;
  1142. return;
  1143. }
  1144. D->addAttr(::new (S.Context)
  1145. TestTypestateAttr(AL.getRange(), S.Context, TestState,
  1146. AL.getAttributeSpellingListIndex()));
  1147. }
  1148. static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1149. // Remember this typedef decl, we will need it later for diagnostics.
  1150. S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
  1151. }
  1152. static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1153. if (auto *TD = dyn_cast<TagDecl>(D))
  1154. TD->addAttr(::new (S.Context) PackedAttr(AL.getRange(), S.Context,
  1155. AL.getAttributeSpellingListIndex()));
  1156. else if (auto *FD = dyn_cast<FieldDecl>(D)) {
  1157. bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
  1158. !FD->getType()->isIncompleteType() &&
  1159. FD->isBitField() &&
  1160. S.Context.getTypeAlign(FD->getType()) <= 8);
  1161. if (S.getASTContext().getTargetInfo().getTriple().isPS4()) {
  1162. if (BitfieldByteAligned)
  1163. // The PS4 target needs to maintain ABI backwards compatibility.
  1164. S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
  1165. << AL << FD->getType();
  1166. else
  1167. FD->addAttr(::new (S.Context) PackedAttr(
  1168. AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
  1169. } else {
  1170. // Report warning about changed offset in the newer compiler versions.
  1171. if (BitfieldByteAligned)
  1172. S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield);
  1173. FD->addAttr(::new (S.Context) PackedAttr(
  1174. AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
  1175. }
  1176. } else
  1177. S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
  1178. }
  1179. static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) {
  1180. // The IBOutlet/IBOutletCollection attributes only apply to instance
  1181. // variables or properties of Objective-C classes. The outlet must also
  1182. // have an object reference type.
  1183. if (const auto *VD = dyn_cast<ObjCIvarDecl>(D)) {
  1184. if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
  1185. S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
  1186. << AL << VD->getType() << 0;
  1187. return false;
  1188. }
  1189. }
  1190. else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
  1191. if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
  1192. S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
  1193. << AL << PD->getType() << 1;
  1194. return false;
  1195. }
  1196. }
  1197. else {
  1198. S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL;
  1199. return false;
  1200. }
  1201. return true;
  1202. }
  1203. static void handleIBOutlet(Sema &S, Decl *D, const ParsedAttr &AL) {
  1204. if (!checkIBOutletCommon(S, D, AL))
  1205. return;
  1206. D->addAttr(::new (S.Context)
  1207. IBOutletAttr(AL.getRange(), S.Context,
  1208. AL.getAttributeSpellingListIndex()));
  1209. }
  1210. static void handleIBOutletCollection(Sema &S, Decl *D, const ParsedAttr &AL) {
  1211. // The iboutletcollection attribute can have zero or one arguments.
  1212. if (AL.getNumArgs() > 1) {
  1213. S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
  1214. return;
  1215. }
  1216. if (!checkIBOutletCommon(S, D, AL))
  1217. return;
  1218. ParsedType PT;
  1219. if (AL.hasParsedType())
  1220. PT = AL.getTypeArg();
  1221. else {
  1222. PT = S.getTypeName(S.Context.Idents.get("NSObject"), AL.getLoc(),
  1223. S.getScopeForContext(D->getDeclContext()->getParent()));
  1224. if (!PT) {
  1225. S.Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
  1226. return;
  1227. }
  1228. }
  1229. TypeSourceInfo *QTLoc = nullptr;
  1230. QualType QT = S.GetTypeFromParser(PT, &QTLoc);
  1231. if (!QTLoc)
  1232. QTLoc = S.Context.getTrivialTypeSourceInfo(QT, AL.getLoc());
  1233. // Diagnose use of non-object type in iboutletcollection attribute.
  1234. // FIXME. Gnu attribute extension ignores use of builtin types in
  1235. // attributes. So, __attribute__((iboutletcollection(char))) will be
  1236. // treated as __attribute__((iboutletcollection())).
  1237. if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
  1238. S.Diag(AL.getLoc(),
  1239. QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
  1240. : diag::err_iboutletcollection_type) << QT;
  1241. return;
  1242. }
  1243. D->addAttr(::new (S.Context)
  1244. IBOutletCollectionAttr(AL.getRange(), S.Context, QTLoc,
  1245. AL.getAttributeSpellingListIndex()));
  1246. }
  1247. bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
  1248. if (RefOkay) {
  1249. if (T->isReferenceType())
  1250. return true;
  1251. } else {
  1252. T = T.getNonReferenceType();
  1253. }
  1254. // The nonnull attribute, and other similar attributes, can be applied to a
  1255. // transparent union that contains a pointer type.
  1256. if (const RecordType *UT = T->getAsUnionType()) {
  1257. if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
  1258. RecordDecl *UD = UT->getDecl();
  1259. for (const auto *I : UD->fields()) {
  1260. QualType QT = I->getType();
  1261. if (QT->isAnyPointerType() || QT->isBlockPointerType())
  1262. return true;
  1263. }
  1264. }
  1265. }
  1266. return T->isAnyPointerType() || T->isBlockPointerType();
  1267. }
  1268. static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL,
  1269. SourceRange AttrParmRange,
  1270. SourceRange TypeRange,
  1271. bool isReturnValue = false) {
  1272. if (!S.isValidPointerAttrType(T)) {
  1273. if (isReturnValue)
  1274. S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
  1275. << AL << AttrParmRange << TypeRange;
  1276. else
  1277. S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
  1278. << AL << AttrParmRange << TypeRange << 0;
  1279. return false;
  1280. }
  1281. return true;
  1282. }
  1283. static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1284. SmallVector<ParamIdx, 8> NonNullArgs;
  1285. for (unsigned I = 0; I < AL.getNumArgs(); ++I) {
  1286. Expr *Ex = AL.getArgAsExpr(I);
  1287. ParamIdx Idx;
  1288. if (!checkFunctionOrMethodParameterIndex(S, D, AL, I + 1, Ex, Idx))
  1289. return;
  1290. // Is the function argument a pointer type?
  1291. if (Idx.getASTIndex() < getFunctionOrMethodNumParams(D) &&
  1292. !attrNonNullArgCheck(
  1293. S, getFunctionOrMethodParamType(D, Idx.getASTIndex()), AL,
  1294. Ex->getSourceRange(),
  1295. getFunctionOrMethodParamRange(D, Idx.getASTIndex())))
  1296. continue;
  1297. NonNullArgs.push_back(Idx);
  1298. }
  1299. // If no arguments were specified to __attribute__((nonnull)) then all pointer
  1300. // arguments have a nonnull attribute; warn if there aren't any. Skip this
  1301. // check if the attribute came from a macro expansion or a template
  1302. // instantiation.
  1303. if (NonNullArgs.empty() && AL.getLoc().isFileID() &&
  1304. !S.inTemplateInstantiation()) {
  1305. bool AnyPointers = isFunctionOrMethodVariadic(D);
  1306. for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
  1307. I != E && !AnyPointers; ++I) {
  1308. QualType T = getFunctionOrMethodParamType(D, I);
  1309. if (T->isDependentType() || S.isValidPointerAttrType(T))
  1310. AnyPointers = true;
  1311. }
  1312. if (!AnyPointers)
  1313. S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers);
  1314. }
  1315. ParamIdx *Start = NonNullArgs.data();
  1316. unsigned Size = NonNullArgs.size();
  1317. llvm::array_pod_sort(Start, Start + Size);
  1318. D->addAttr(::new (S.Context)
  1319. NonNullAttr(AL.getRange(), S.Context, Start, Size,
  1320. AL.getAttributeSpellingListIndex()));
  1321. }
  1322. static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
  1323. const ParsedAttr &AL) {
  1324. if (AL.getNumArgs() > 0) {
  1325. if (D->getFunctionType()) {
  1326. handleNonNullAttr(S, D, AL);
  1327. } else {
  1328. S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
  1329. << D->getSourceRange();
  1330. }
  1331. return;
  1332. }
  1333. // Is the argument a pointer type?
  1334. if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(),
  1335. D->getSourceRange()))
  1336. return;
  1337. D->addAttr(::new (S.Context)
  1338. NonNullAttr(AL.getRange(), S.Context, nullptr, 0,
  1339. AL.getAttributeSpellingListIndex()));
  1340. }
  1341. static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1342. QualType ResultType = getFunctionOrMethodResultType(D);
  1343. SourceRange SR = getFunctionOrMethodResultSourceRange(D);
  1344. if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR,
  1345. /* isReturnValue */ true))
  1346. return;
  1347. D->addAttr(::new (S.Context)
  1348. ReturnsNonNullAttr(AL.getRange(), S.Context,
  1349. AL.getAttributeSpellingListIndex()));
  1350. }
  1351. static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1352. if (D->isInvalidDecl())
  1353. return;
  1354. // noescape only applies to pointer types.
  1355. QualType T = cast<ParmVarDecl>(D)->getType();
  1356. if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
  1357. S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
  1358. << AL << AL.getRange() << 0;
  1359. return;
  1360. }
  1361. D->addAttr(::new (S.Context) NoEscapeAttr(
  1362. AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
  1363. }
  1364. static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1365. Expr *E = AL.getArgAsExpr(0),
  1366. *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr;
  1367. S.AddAssumeAlignedAttr(AL.getRange(), D, E, OE,
  1368. AL.getAttributeSpellingListIndex());
  1369. }
  1370. static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1371. S.AddAllocAlignAttr(AL.getRange(), D, AL.getArgAsExpr(0),
  1372. AL.getAttributeSpellingListIndex());
  1373. }
  1374. void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
  1375. Expr *OE, unsigned SpellingListIndex) {
  1376. QualType ResultType = getFunctionOrMethodResultType(D);
  1377. SourceRange SR = getFunctionOrMethodResultSourceRange(D);
  1378. AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
  1379. SourceLocation AttrLoc = AttrRange.getBegin();
  1380. if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
  1381. Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
  1382. << &TmpAttr << AttrRange << SR;
  1383. return;
  1384. }
  1385. if (!E->isValueDependent()) {
  1386. llvm::APSInt I(64);
  1387. if (!E->isIntegerConstantExpr(I, Context)) {
  1388. if (OE)
  1389. Diag(AttrLoc, diag::err_attribute_argument_n_type)
  1390. << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
  1391. << E->getSourceRange();
  1392. else
  1393. Diag(AttrLoc, diag::err_attribute_argument_type)
  1394. << &TmpAttr << AANT_ArgumentIntegerConstant
  1395. << E->getSourceRange();
  1396. return;
  1397. }
  1398. if (!I.isPowerOf2()) {
  1399. Diag(AttrLoc, diag::err_alignment_not_power_of_two)
  1400. << E->getSourceRange();
  1401. return;
  1402. }
  1403. }
  1404. if (OE) {
  1405. if (!OE->isValueDependent()) {
  1406. llvm::APSInt I(64);
  1407. if (!OE->isIntegerConstantExpr(I, Context)) {
  1408. Diag(AttrLoc, diag::err_attribute_argument_n_type)
  1409. << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
  1410. << OE->getSourceRange();
  1411. return;
  1412. }
  1413. }
  1414. }
  1415. D->addAttr(::new (Context)
  1416. AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
  1417. }
  1418. void Sema::AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
  1419. unsigned SpellingListIndex) {
  1420. QualType ResultType = getFunctionOrMethodResultType(D);
  1421. AllocAlignAttr TmpAttr(AttrRange, Context, ParamIdx(), SpellingListIndex);
  1422. SourceLocation AttrLoc = AttrRange.getBegin();
  1423. if (!ResultType->isDependentType() &&
  1424. !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
  1425. Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
  1426. << &TmpAttr << AttrRange << getFunctionOrMethodResultSourceRange(D);
  1427. return;
  1428. }
  1429. ParamIdx Idx;
  1430. const auto *FuncDecl = cast<FunctionDecl>(D);
  1431. if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
  1432. /*AttrArgNo=*/1, ParamExpr, Idx))
  1433. return;
  1434. QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
  1435. if (!Ty->isDependentType() && !Ty->isIntegralType(Context)) {
  1436. Diag(ParamExpr->getBeginLoc(), diag::err_attribute_integers_only)
  1437. << &TmpAttr
  1438. << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange();
  1439. return;
  1440. }
  1441. D->addAttr(::new (Context)
  1442. AllocAlignAttr(AttrRange, Context, Idx, SpellingListIndex));
  1443. }
  1444. /// Normalize the attribute, __foo__ becomes foo.
  1445. /// Returns true if normalization was applied.
  1446. static bool normalizeName(StringRef &AttrName) {
  1447. if (AttrName.size() > 4 && AttrName.startswith("__") &&
  1448. AttrName.endswith("__")) {
  1449. AttrName = AttrName.drop_front(2).drop_back(2);
  1450. return true;
  1451. }
  1452. return false;
  1453. }
  1454. static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1455. // This attribute must be applied to a function declaration. The first
  1456. // argument to the attribute must be an identifier, the name of the resource,
  1457. // for example: malloc. The following arguments must be argument indexes, the
  1458. // arguments must be of integer type for Returns, otherwise of pointer type.
  1459. // The difference between Holds and Takes is that a pointer may still be used
  1460. // after being held. free() should be __attribute((ownership_takes)), whereas
  1461. // a list append function may well be __attribute((ownership_holds)).
  1462. if (!AL.isArgIdent(0)) {
  1463. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  1464. << AL << 1 << AANT_ArgumentIdentifier;
  1465. return;
  1466. }
  1467. // Figure out our Kind.
  1468. OwnershipAttr::OwnershipKind K =
  1469. OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
  1470. AL.getAttributeSpellingListIndex()).getOwnKind();
  1471. // Check arguments.
  1472. switch (K) {
  1473. case OwnershipAttr::Takes:
  1474. case OwnershipAttr::Holds:
  1475. if (AL.getNumArgs() < 2) {
  1476. S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL << 2;
  1477. return;
  1478. }
  1479. break;
  1480. case OwnershipAttr::Returns:
  1481. if (AL.getNumArgs() > 2) {
  1482. S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
  1483. return;
  1484. }
  1485. break;
  1486. }
  1487. IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
  1488. StringRef ModuleName = Module->getName();
  1489. if (normalizeName(ModuleName)) {
  1490. Module = &S.PP.getIdentifierTable().get(ModuleName);
  1491. }
  1492. SmallVector<ParamIdx, 8> OwnershipArgs;
  1493. for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
  1494. Expr *Ex = AL.getArgAsExpr(i);
  1495. ParamIdx Idx;
  1496. if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
  1497. return;
  1498. // Is the function argument a pointer type?
  1499. QualType T = getFunctionOrMethodParamType(D, Idx.getASTIndex());
  1500. int Err = -1; // No error
  1501. switch (K) {
  1502. case OwnershipAttr::Takes:
  1503. case OwnershipAttr::Holds:
  1504. if (!T->isAnyPointerType() && !T->isBlockPointerType())
  1505. Err = 0;
  1506. break;
  1507. case OwnershipAttr::Returns:
  1508. if (!T->isIntegerType())
  1509. Err = 1;
  1510. break;
  1511. }
  1512. if (-1 != Err) {
  1513. S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err
  1514. << Ex->getSourceRange();
  1515. return;
  1516. }
  1517. // Check we don't have a conflict with another ownership attribute.
  1518. for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
  1519. // Cannot have two ownership attributes of different kinds for the same
  1520. // index.
  1521. if (I->getOwnKind() != K && I->args_end() !=
  1522. std::find(I->args_begin(), I->args_end(), Idx)) {
  1523. S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << I;
  1524. return;
  1525. } else if (K == OwnershipAttr::Returns &&
  1526. I->getOwnKind() == OwnershipAttr::Returns) {
  1527. // A returns attribute conflicts with any other returns attribute using
  1528. // a different index.
  1529. if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
  1530. S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
  1531. << I->args_begin()->getSourceIndex();
  1532. if (I->args_size())
  1533. S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
  1534. << Idx.getSourceIndex() << Ex->getSourceRange();
  1535. return;
  1536. }
  1537. }
  1538. }
  1539. OwnershipArgs.push_back(Idx);
  1540. }
  1541. ParamIdx *Start = OwnershipArgs.data();
  1542. unsigned Size = OwnershipArgs.size();
  1543. llvm::array_pod_sort(Start, Start + Size);
  1544. D->addAttr(::new (S.Context)
  1545. OwnershipAttr(AL.getLoc(), S.Context, Module, Start, Size,
  1546. AL.getAttributeSpellingListIndex()));
  1547. }
  1548. static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1549. // Check the attribute arguments.
  1550. if (AL.getNumArgs() > 1) {
  1551. S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
  1552. return;
  1553. }
  1554. // gcc rejects
  1555. // class c {
  1556. // static int a __attribute__((weakref ("v2")));
  1557. // static int b() __attribute__((weakref ("f3")));
  1558. // };
  1559. // and ignores the attributes of
  1560. // void f(void) {
  1561. // static int a __attribute__((weakref ("v2")));
  1562. // }
  1563. // we reject them
  1564. const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
  1565. if (!Ctx->isFileContext()) {
  1566. S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context)
  1567. << cast<NamedDecl>(D);
  1568. return;
  1569. }
  1570. // The GCC manual says
  1571. //
  1572. // At present, a declaration to which `weakref' is attached can only
  1573. // be `static'.
  1574. //
  1575. // It also says
  1576. //
  1577. // Without a TARGET,
  1578. // given as an argument to `weakref' or to `alias', `weakref' is
  1579. // equivalent to `weak'.
  1580. //
  1581. // gcc 4.4.1 will accept
  1582. // int a7 __attribute__((weakref));
  1583. // as
  1584. // int a7 __attribute__((weak));
  1585. // This looks like a bug in gcc. We reject that for now. We should revisit
  1586. // it if this behaviour is actually used.
  1587. // GCC rejects
  1588. // static ((alias ("y"), weakref)).
  1589. // Should we? How to check that weakref is before or after alias?
  1590. // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
  1591. // of transforming it into an AliasAttr. The WeakRefAttr never uses the
  1592. // StringRef parameter it was given anyway.
  1593. StringRef Str;
  1594. if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str))
  1595. // GCC will accept anything as the argument of weakref. Should we
  1596. // check for an existing decl?
  1597. D->addAttr(::new (S.Context) AliasAttr(AL.getRange(), S.Context, Str,
  1598. AL.getAttributeSpellingListIndex()));
  1599. D->addAttr(::new (S.Context)
  1600. WeakRefAttr(AL.getRange(), S.Context,
  1601. AL.getAttributeSpellingListIndex()));
  1602. }
  1603. static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1604. StringRef Str;
  1605. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
  1606. return;
  1607. // Aliases should be on declarations, not definitions.
  1608. const auto *FD = cast<FunctionDecl>(D);
  1609. if (FD->isThisDeclarationADefinition()) {
  1610. S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1;
  1611. return;
  1612. }
  1613. D->addAttr(::new (S.Context) IFuncAttr(AL.getRange(), S.Context, Str,
  1614. AL.getAttributeSpellingListIndex()));
  1615. }
  1616. static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1617. StringRef Str;
  1618. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
  1619. return;
  1620. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  1621. S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin);
  1622. return;
  1623. }
  1624. if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
  1625. S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx);
  1626. }
  1627. // Aliases should be on declarations, not definitions.
  1628. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  1629. if (FD->isThisDeclarationADefinition()) {
  1630. S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0;
  1631. return;
  1632. }
  1633. } else {
  1634. const auto *VD = cast<VarDecl>(D);
  1635. if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
  1636. S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0;
  1637. return;
  1638. }
  1639. }
  1640. // Mark target used to prevent unneeded-internal-declaration warnings.
  1641. if (!S.LangOpts.CPlusPlus) {
  1642. // FIXME: demangle Str for C++, as the attribute refers to the mangled
  1643. // linkage name, not the pre-mangled identifier.
  1644. const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
  1645. LookupResult LR(S, target, Sema::LookupOrdinaryName);
  1646. if (S.LookupQualifiedName(LR, S.getCurLexicalContext()))
  1647. for (NamedDecl *ND : LR)
  1648. ND->markUsed(S.Context);
  1649. }
  1650. D->addAttr(::new (S.Context) AliasAttr(AL.getRange(), S.Context, Str,
  1651. AL.getAttributeSpellingListIndex()));
  1652. }
  1653. static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1654. StringRef Model;
  1655. SourceLocation LiteralLoc;
  1656. // Check that it is a string.
  1657. if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc))
  1658. return;
  1659. // Check that the value.
  1660. if (Model != "global-dynamic" && Model != "local-dynamic"
  1661. && Model != "initial-exec" && Model != "local-exec") {
  1662. S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
  1663. return;
  1664. }
  1665. D->addAttr(::new (S.Context)
  1666. TLSModelAttr(AL.getRange(), S.Context, Model,
  1667. AL.getAttributeSpellingListIndex()));
  1668. }
  1669. static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1670. QualType ResultType = getFunctionOrMethodResultType(D);
  1671. if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
  1672. D->addAttr(::new (S.Context) RestrictAttr(
  1673. AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
  1674. return;
  1675. }
  1676. S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
  1677. << AL << getFunctionOrMethodResultSourceRange(D);
  1678. }
  1679. static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1680. FunctionDecl *FD = cast<FunctionDecl>(D);
  1681. if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  1682. if (MD->getParent()->isLambda()) {
  1683. S.Diag(AL.getLoc(), diag::err_attribute_dll_lambda) << AL;
  1684. return;
  1685. }
  1686. }
  1687. if (!checkAttributeAtLeastNumArgs(S, AL, 1))
  1688. return;
  1689. SmallVector<IdentifierInfo *, 8> CPUs;
  1690. for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) {
  1691. if (!AL.isArgIdent(ArgNo)) {
  1692. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  1693. << AL << AANT_ArgumentIdentifier;
  1694. return;
  1695. }
  1696. IdentifierLoc *CPUArg = AL.getArgAsIdent(ArgNo);
  1697. StringRef CPUName = CPUArg->Ident->getName().trim();
  1698. if (!S.Context.getTargetInfo().validateCPUSpecificCPUDispatch(CPUName)) {
  1699. S.Diag(CPUArg->Loc, diag::err_invalid_cpu_specific_dispatch_value)
  1700. << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch);
  1701. return;
  1702. }
  1703. const TargetInfo &Target = S.Context.getTargetInfo();
  1704. if (llvm::any_of(CPUs, [CPUName, &Target](const IdentifierInfo *Cur) {
  1705. return Target.CPUSpecificManglingCharacter(CPUName) ==
  1706. Target.CPUSpecificManglingCharacter(Cur->getName());
  1707. })) {
  1708. S.Diag(AL.getLoc(), diag::warn_multiversion_duplicate_entries);
  1709. return;
  1710. }
  1711. CPUs.push_back(CPUArg->Ident);
  1712. }
  1713. FD->setIsMultiVersion(true);
  1714. if (AL.getKind() == ParsedAttr::AT_CPUSpecific)
  1715. D->addAttr(::new (S.Context) CPUSpecificAttr(
  1716. AL.getRange(), S.Context, CPUs.data(), CPUs.size(),
  1717. AL.getAttributeSpellingListIndex()));
  1718. else
  1719. D->addAttr(::new (S.Context) CPUDispatchAttr(
  1720. AL.getRange(), S.Context, CPUs.data(), CPUs.size(),
  1721. AL.getAttributeSpellingListIndex()));
  1722. }
  1723. static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1724. if (S.LangOpts.CPlusPlus) {
  1725. S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
  1726. << AL << AttributeLangSupport::Cpp;
  1727. return;
  1728. }
  1729. if (CommonAttr *CA = S.mergeCommonAttr(D, AL))
  1730. D->addAttr(CA);
  1731. }
  1732. static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1733. if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, AL))
  1734. return;
  1735. if (AL.isDeclspecAttribute()) {
  1736. const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
  1737. const auto &Arch = Triple.getArch();
  1738. if (Arch != llvm::Triple::x86 &&
  1739. (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
  1740. S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch)
  1741. << AL << Triple.getArchName();
  1742. return;
  1743. }
  1744. }
  1745. D->addAttr(::new (S.Context) NakedAttr(AL.getRange(), S.Context,
  1746. AL.getAttributeSpellingListIndex()));
  1747. }
  1748. static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
  1749. if (hasDeclarator(D)) return;
  1750. if (!isa<ObjCMethodDecl>(D)) {
  1751. S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
  1752. << Attrs << ExpectedFunctionOrMethod;
  1753. return;
  1754. }
  1755. D->addAttr(::new (S.Context) NoReturnAttr(
  1756. Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
  1757. }
  1758. static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
  1759. if (!S.getLangOpts().CFProtectionBranch)
  1760. S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored);
  1761. else
  1762. handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs);
  1763. }
  1764. bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) {
  1765. if (!checkAttributeNumArgs(*this, Attrs, 0)) {
  1766. Attrs.setInvalid();
  1767. return true;
  1768. }
  1769. return false;
  1770. }
  1771. bool Sema::CheckAttrTarget(const ParsedAttr &AL) {
  1772. // Check whether the attribute is valid on the current target.
  1773. if (!AL.existsInTarget(Context.getTargetInfo())) {
  1774. Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL;
  1775. AL.setInvalid();
  1776. return true;
  1777. }
  1778. return false;
  1779. }
  1780. static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1781. // The checking path for 'noreturn' and 'analyzer_noreturn' are different
  1782. // because 'analyzer_noreturn' does not impact the type.
  1783. if (!isFunctionOrMethodOrBlock(D)) {
  1784. ValueDecl *VD = dyn_cast<ValueDecl>(D);
  1785. if (!VD || (!VD->getType()->isBlockPointerType() &&
  1786. !VD->getType()->isFunctionPointerType())) {
  1787. S.Diag(AL.getLoc(), AL.isCXX11Attribute()
  1788. ? diag::err_attribute_wrong_decl_type
  1789. : diag::warn_attribute_wrong_decl_type)
  1790. << AL << ExpectedFunctionMethodOrBlock;
  1791. return;
  1792. }
  1793. }
  1794. D->addAttr(::new (S.Context)
  1795. AnalyzerNoReturnAttr(AL.getRange(), S.Context,
  1796. AL.getAttributeSpellingListIndex()));
  1797. }
  1798. // PS3 PPU-specific.
  1799. static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1800. /*
  1801. Returning a Vector Class in Registers
  1802. According to the PPU ABI specifications, a class with a single member of
  1803. vector type is returned in memory when used as the return value of a
  1804. function.
  1805. This results in inefficient code when implementing vector classes. To return
  1806. the value in a single vector register, add the vecreturn attribute to the
  1807. class definition. This attribute is also applicable to struct types.
  1808. Example:
  1809. struct Vector
  1810. {
  1811. __vector float xyzw;
  1812. } __attribute__((vecreturn));
  1813. Vector Add(Vector lhs, Vector rhs)
  1814. {
  1815. Vector result;
  1816. result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
  1817. return result; // This will be returned in a register
  1818. }
  1819. */
  1820. if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
  1821. S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A;
  1822. return;
  1823. }
  1824. const auto *R = cast<RecordDecl>(D);
  1825. int count = 0;
  1826. if (!isa<CXXRecordDecl>(R)) {
  1827. S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
  1828. return;
  1829. }
  1830. if (!cast<CXXRecordDecl>(R)->isPOD()) {
  1831. S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
  1832. return;
  1833. }
  1834. for (const auto *I : R->fields()) {
  1835. if ((count == 1) || !I->getType()->isVectorType()) {
  1836. S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
  1837. return;
  1838. }
  1839. count++;
  1840. }
  1841. D->addAttr(::new (S.Context) VecReturnAttr(
  1842. AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
  1843. }
  1844. static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
  1845. const ParsedAttr &AL) {
  1846. if (isa<ParmVarDecl>(D)) {
  1847. // [[carries_dependency]] can only be applied to a parameter if it is a
  1848. // parameter of a function declaration or lambda.
  1849. if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
  1850. S.Diag(AL.getLoc(),
  1851. diag::err_carries_dependency_param_not_function_decl);
  1852. return;
  1853. }
  1854. }
  1855. D->addAttr(::new (S.Context) CarriesDependencyAttr(
  1856. AL.getRange(), S.Context,
  1857. AL.getAttributeSpellingListIndex()));
  1858. }
  1859. static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1860. bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName();
  1861. // If this is spelled as the standard C++17 attribute, but not in C++17, warn
  1862. // about using it as an extension.
  1863. if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
  1864. S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
  1865. D->addAttr(::new (S.Context) UnusedAttr(
  1866. AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
  1867. }
  1868. static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1869. uint32_t priority = ConstructorAttr::DefaultPriority;
  1870. if (AL.getNumArgs() &&
  1871. !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
  1872. return;
  1873. D->addAttr(::new (S.Context)
  1874. ConstructorAttr(AL.getRange(), S.Context, priority,
  1875. AL.getAttributeSpellingListIndex()));
  1876. }
  1877. static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  1878. uint32_t priority = DestructorAttr::DefaultPriority;
  1879. if (AL.getNumArgs() &&
  1880. !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
  1881. return;
  1882. D->addAttr(::new (S.Context)
  1883. DestructorAttr(AL.getRange(), S.Context, priority,
  1884. AL.getAttributeSpellingListIndex()));
  1885. }
  1886. template <typename AttrTy>
  1887. static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
  1888. // Handle the case where the attribute has a text message.
  1889. StringRef Str;
  1890. if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str))
  1891. return;
  1892. D->addAttr(::new (S.Context) AttrTy(AL.getRange(), S.Context, Str,
  1893. AL.getAttributeSpellingListIndex()));
  1894. }
  1895. static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
  1896. const ParsedAttr &AL) {
  1897. if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
  1898. S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition)
  1899. << AL << AL.getRange();
  1900. return;
  1901. }
  1902. D->addAttr(::new (S.Context)
  1903. ObjCExplicitProtocolImplAttr(AL.getRange(), S.Context,
  1904. AL.getAttributeSpellingListIndex()));
  1905. }
  1906. static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
  1907. IdentifierInfo *Platform,
  1908. VersionTuple Introduced,
  1909. VersionTuple Deprecated,
  1910. VersionTuple Obsoleted) {
  1911. StringRef PlatformName
  1912. = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
  1913. if (PlatformName.empty())
  1914. PlatformName = Platform->getName();
  1915. // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
  1916. // of these steps are needed).
  1917. if (!Introduced.empty() && !Deprecated.empty() &&
  1918. !(Introduced <= Deprecated)) {
  1919. S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
  1920. << 1 << PlatformName << Deprecated.getAsString()
  1921. << 0 << Introduced.getAsString();
  1922. return true;
  1923. }
  1924. if (!Introduced.empty() && !Obsoleted.empty() &&
  1925. !(Introduced <= Obsoleted)) {
  1926. S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
  1927. << 2 << PlatformName << Obsoleted.getAsString()
  1928. << 0 << Introduced.getAsString();
  1929. return true;
  1930. }
  1931. if (!Deprecated.empty() && !Obsoleted.empty() &&
  1932. !(Deprecated <= Obsoleted)) {
  1933. S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
  1934. << 2 << PlatformName << Obsoleted.getAsString()
  1935. << 1 << Deprecated.getAsString();
  1936. return true;
  1937. }
  1938. return false;
  1939. }
  1940. /// Check whether the two versions match.
  1941. ///
  1942. /// If either version tuple is empty, then they are assumed to match. If
  1943. /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
  1944. static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
  1945. bool BeforeIsOkay) {
  1946. if (X.empty() || Y.empty())
  1947. return true;
  1948. if (X == Y)
  1949. return true;
  1950. if (BeforeIsOkay && X < Y)
  1951. return true;
  1952. return false;
  1953. }
  1954. AvailabilityAttr *Sema::mergeAvailabilityAttr(
  1955. NamedDecl *D, SourceRange Range, IdentifierInfo *Platform, bool Implicit,
  1956. VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted,
  1957. bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement,
  1958. AvailabilityMergeKind AMK, int Priority, unsigned AttrSpellingListIndex) {
  1959. VersionTuple MergedIntroduced = Introduced;
  1960. VersionTuple MergedDeprecated = Deprecated;
  1961. VersionTuple MergedObsoleted = Obsoleted;
  1962. bool FoundAny = false;
  1963. bool OverrideOrImpl = false;
  1964. switch (AMK) {
  1965. case AMK_None:
  1966. case AMK_Redeclaration:
  1967. OverrideOrImpl = false;
  1968. break;
  1969. case AMK_Override:
  1970. case AMK_ProtocolImplementation:
  1971. OverrideOrImpl = true;
  1972. break;
  1973. }
  1974. if (D->hasAttrs()) {
  1975. AttrVec &Attrs = D->getAttrs();
  1976. for (unsigned i = 0, e = Attrs.size(); i != e;) {
  1977. const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
  1978. if (!OldAA) {
  1979. ++i;
  1980. continue;
  1981. }
  1982. IdentifierInfo *OldPlatform = OldAA->getPlatform();
  1983. if (OldPlatform != Platform) {
  1984. ++i;
  1985. continue;
  1986. }
  1987. // If there is an existing availability attribute for this platform that
  1988. // has a lower priority use the existing one and discard the new
  1989. // attribute.
  1990. if (OldAA->getPriority() < Priority)
  1991. return nullptr;
  1992. // If there is an existing attribute for this platform that has a higher
  1993. // priority than the new attribute then erase the old one and continue
  1994. // processing the attributes.
  1995. if (OldAA->getPriority() > Priority) {
  1996. Attrs.erase(Attrs.begin() + i);
  1997. --e;
  1998. continue;
  1999. }
  2000. FoundAny = true;
  2001. VersionTuple OldIntroduced = OldAA->getIntroduced();
  2002. VersionTuple OldDeprecated = OldAA->getDeprecated();
  2003. VersionTuple OldObsoleted = OldAA->getObsoleted();
  2004. bool OldIsUnavailable = OldAA->getUnavailable();
  2005. if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
  2006. !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
  2007. !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
  2008. !(OldIsUnavailable == IsUnavailable ||
  2009. (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
  2010. if (OverrideOrImpl) {
  2011. int Which = -1;
  2012. VersionTuple FirstVersion;
  2013. VersionTuple SecondVersion;
  2014. if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
  2015. Which = 0;
  2016. FirstVersion = OldIntroduced;
  2017. SecondVersion = Introduced;
  2018. } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
  2019. Which = 1;
  2020. FirstVersion = Deprecated;
  2021. SecondVersion = OldDeprecated;
  2022. } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
  2023. Which = 2;
  2024. FirstVersion = Obsoleted;
  2025. SecondVersion = OldObsoleted;
  2026. }
  2027. if (Which == -1) {
  2028. Diag(OldAA->getLocation(),
  2029. diag::warn_mismatched_availability_override_unavail)
  2030. << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
  2031. << (AMK == AMK_Override);
  2032. } else {
  2033. Diag(OldAA->getLocation(),
  2034. diag::warn_mismatched_availability_override)
  2035. << Which
  2036. << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
  2037. << FirstVersion.getAsString() << SecondVersion.getAsString()
  2038. << (AMK == AMK_Override);
  2039. }
  2040. if (AMK == AMK_Override)
  2041. Diag(Range.getBegin(), diag::note_overridden_method);
  2042. else
  2043. Diag(Range.getBegin(), diag::note_protocol_method);
  2044. } else {
  2045. Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
  2046. Diag(Range.getBegin(), diag::note_previous_attribute);
  2047. }
  2048. Attrs.erase(Attrs.begin() + i);
  2049. --e;
  2050. continue;
  2051. }
  2052. VersionTuple MergedIntroduced2 = MergedIntroduced;
  2053. VersionTuple MergedDeprecated2 = MergedDeprecated;
  2054. VersionTuple MergedObsoleted2 = MergedObsoleted;
  2055. if (MergedIntroduced2.empty())
  2056. MergedIntroduced2 = OldIntroduced;
  2057. if (MergedDeprecated2.empty())
  2058. MergedDeprecated2 = OldDeprecated;
  2059. if (MergedObsoleted2.empty())
  2060. MergedObsoleted2 = OldObsoleted;
  2061. if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
  2062. MergedIntroduced2, MergedDeprecated2,
  2063. MergedObsoleted2)) {
  2064. Attrs.erase(Attrs.begin() + i);
  2065. --e;
  2066. continue;
  2067. }
  2068. MergedIntroduced = MergedIntroduced2;
  2069. MergedDeprecated = MergedDeprecated2;
  2070. MergedObsoleted = MergedObsoleted2;
  2071. ++i;
  2072. }
  2073. }
  2074. if (FoundAny &&
  2075. MergedIntroduced == Introduced &&
  2076. MergedDeprecated == Deprecated &&
  2077. MergedObsoleted == Obsoleted)
  2078. return nullptr;
  2079. // Only create a new attribute if !OverrideOrImpl, but we want to do
  2080. // the checking.
  2081. if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
  2082. MergedDeprecated, MergedObsoleted) &&
  2083. !OverrideOrImpl) {
  2084. auto *Avail = ::new (Context)
  2085. AvailabilityAttr(Range, Context, Platform, Introduced, Deprecated,
  2086. Obsoleted, IsUnavailable, Message, IsStrict,
  2087. Replacement, Priority, AttrSpellingListIndex);
  2088. Avail->setImplicit(Implicit);
  2089. return Avail;
  2090. }
  2091. return nullptr;
  2092. }
  2093. static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2094. if (!checkAttributeNumArgs(S, AL, 1))
  2095. return;
  2096. IdentifierLoc *Platform = AL.getArgAsIdent(0);
  2097. unsigned Index = AL.getAttributeSpellingListIndex();
  2098. IdentifierInfo *II = Platform->Ident;
  2099. if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
  2100. S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
  2101. << Platform->Ident;
  2102. auto *ND = dyn_cast<NamedDecl>(D);
  2103. if (!ND) // We warned about this already, so just return.
  2104. return;
  2105. AvailabilityChange Introduced = AL.getAvailabilityIntroduced();
  2106. AvailabilityChange Deprecated = AL.getAvailabilityDeprecated();
  2107. AvailabilityChange Obsoleted = AL.getAvailabilityObsoleted();
  2108. bool IsUnavailable = AL.getUnavailableLoc().isValid();
  2109. bool IsStrict = AL.getStrictLoc().isValid();
  2110. StringRef Str;
  2111. if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getMessageExpr()))
  2112. Str = SE->getString();
  2113. StringRef Replacement;
  2114. if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getReplacementExpr()))
  2115. Replacement = SE->getString();
  2116. if (II->isStr("swift")) {
  2117. if (Introduced.isValid() || Obsoleted.isValid() ||
  2118. (!IsUnavailable && !Deprecated.isValid())) {
  2119. S.Diag(AL.getLoc(),
  2120. diag::warn_availability_swift_unavailable_deprecated_only);
  2121. return;
  2122. }
  2123. }
  2124. int PriorityModifier = AL.isPragmaClangAttribute()
  2125. ? Sema::AP_PragmaClangAttribute
  2126. : Sema::AP_Explicit;
  2127. AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
  2128. ND, AL.getRange(), II, false /*Implicit*/, Introduced.Version,
  2129. Deprecated.Version, Obsoleted.Version, IsUnavailable, Str, IsStrict,
  2130. Replacement, Sema::AMK_None, PriorityModifier, Index);
  2131. if (NewAttr)
  2132. D->addAttr(NewAttr);
  2133. // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
  2134. // matches before the start of the watchOS platform.
  2135. if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
  2136. IdentifierInfo *NewII = nullptr;
  2137. if (II->getName() == "ios")
  2138. NewII = &S.Context.Idents.get("watchos");
  2139. else if (II->getName() == "ios_app_extension")
  2140. NewII = &S.Context.Idents.get("watchos_app_extension");
  2141. if (NewII) {
  2142. auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
  2143. if (Version.empty())
  2144. return Version;
  2145. auto Major = Version.getMajor();
  2146. auto NewMajor = Major >= 9 ? Major - 7 : 0;
  2147. if (NewMajor >= 2) {
  2148. if (Version.getMinor().hasValue()) {
  2149. if (Version.getSubminor().hasValue())
  2150. return VersionTuple(NewMajor, Version.getMinor().getValue(),
  2151. Version.getSubminor().getValue());
  2152. else
  2153. return VersionTuple(NewMajor, Version.getMinor().getValue());
  2154. }
  2155. }
  2156. return VersionTuple(2, 0);
  2157. };
  2158. auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
  2159. auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
  2160. auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
  2161. AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
  2162. ND, AL.getRange(), NewII, true /*Implicit*/, NewIntroduced,
  2163. NewDeprecated, NewObsoleted, IsUnavailable, Str, IsStrict,
  2164. Replacement, Sema::AMK_None,
  2165. PriorityModifier + Sema::AP_InferredFromOtherPlatform, Index);
  2166. if (NewAttr)
  2167. D->addAttr(NewAttr);
  2168. }
  2169. } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
  2170. // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
  2171. // matches before the start of the tvOS platform.
  2172. IdentifierInfo *NewII = nullptr;
  2173. if (II->getName() == "ios")
  2174. NewII = &S.Context.Idents.get("tvos");
  2175. else if (II->getName() == "ios_app_extension")
  2176. NewII = &S.Context.Idents.get("tvos_app_extension");
  2177. if (NewII) {
  2178. AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
  2179. ND, AL.getRange(), NewII, true /*Implicit*/, Introduced.Version,
  2180. Deprecated.Version, Obsoleted.Version, IsUnavailable, Str, IsStrict,
  2181. Replacement, Sema::AMK_None,
  2182. PriorityModifier + Sema::AP_InferredFromOtherPlatform, Index);
  2183. if (NewAttr)
  2184. D->addAttr(NewAttr);
  2185. }
  2186. }
  2187. }
  2188. static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
  2189. const ParsedAttr &AL) {
  2190. if (!checkAttributeAtLeastNumArgs(S, AL, 1))
  2191. return;
  2192. assert(checkAttributeAtMostNumArgs(S, AL, 3) &&
  2193. "Invalid number of arguments in an external_source_symbol attribute");
  2194. StringRef Language;
  2195. if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0)))
  2196. Language = SE->getString();
  2197. StringRef DefinedIn;
  2198. if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1)))
  2199. DefinedIn = SE->getString();
  2200. bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
  2201. D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
  2202. AL.getRange(), S.Context, Language, DefinedIn, IsGeneratedDeclaration,
  2203. AL.getAttributeSpellingListIndex()));
  2204. }
  2205. template <class T>
  2206. static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
  2207. typename T::VisibilityType value,
  2208. unsigned attrSpellingListIndex) {
  2209. T *existingAttr = D->getAttr<T>();
  2210. if (existingAttr) {
  2211. typename T::VisibilityType existingValue = existingAttr->getVisibility();
  2212. if (existingValue == value)
  2213. return nullptr;
  2214. S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
  2215. S.Diag(range.getBegin(), diag::note_previous_attribute);
  2216. D->dropAttr<T>();
  2217. }
  2218. return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
  2219. }
  2220. VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
  2221. VisibilityAttr::VisibilityType Vis,
  2222. unsigned AttrSpellingListIndex) {
  2223. return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
  2224. AttrSpellingListIndex);
  2225. }
  2226. TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
  2227. TypeVisibilityAttr::VisibilityType Vis,
  2228. unsigned AttrSpellingListIndex) {
  2229. return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
  2230. AttrSpellingListIndex);
  2231. }
  2232. static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
  2233. bool isTypeVisibility) {
  2234. // Visibility attributes don't mean anything on a typedef.
  2235. if (isa<TypedefNameDecl>(D)) {
  2236. S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
  2237. return;
  2238. }
  2239. // 'type_visibility' can only go on a type or namespace.
  2240. if (isTypeVisibility &&
  2241. !(isa<TagDecl>(D) ||
  2242. isa<ObjCInterfaceDecl>(D) ||
  2243. isa<NamespaceDecl>(D))) {
  2244. S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
  2245. << AL << ExpectedTypeOrNamespace;
  2246. return;
  2247. }
  2248. // Check that the argument is a string literal.
  2249. StringRef TypeStr;
  2250. SourceLocation LiteralLoc;
  2251. if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
  2252. return;
  2253. VisibilityAttr::VisibilityType type;
  2254. if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
  2255. S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
  2256. << TypeStr;
  2257. return;
  2258. }
  2259. // Complain about attempts to use protected visibility on targets
  2260. // (like Darwin) that don't support it.
  2261. if (type == VisibilityAttr::Protected &&
  2262. !S.Context.getTargetInfo().hasProtectedVisibility()) {
  2263. S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
  2264. type = VisibilityAttr::Default;
  2265. }
  2266. unsigned Index = AL.getAttributeSpellingListIndex();
  2267. Attr *newAttr;
  2268. if (isTypeVisibility) {
  2269. newAttr = S.mergeTypeVisibilityAttr(D, AL.getRange(),
  2270. (TypeVisibilityAttr::VisibilityType) type,
  2271. Index);
  2272. } else {
  2273. newAttr = S.mergeVisibilityAttr(D, AL.getRange(), type, Index);
  2274. }
  2275. if (newAttr)
  2276. D->addAttr(newAttr);
  2277. }
  2278. static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2279. const auto *M = cast<ObjCMethodDecl>(D);
  2280. if (!AL.isArgIdent(0)) {
  2281. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  2282. << AL << 1 << AANT_ArgumentIdentifier;
  2283. return;
  2284. }
  2285. IdentifierLoc *IL = AL.getArgAsIdent(0);
  2286. ObjCMethodFamilyAttr::FamilyKind F;
  2287. if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
  2288. S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident;
  2289. return;
  2290. }
  2291. if (F == ObjCMethodFamilyAttr::OMF_init &&
  2292. !M->getReturnType()->isObjCObjectPointerType()) {
  2293. S.Diag(M->getLocation(), diag::err_init_method_bad_return_type)
  2294. << M->getReturnType();
  2295. // Ignore the attribute.
  2296. return;
  2297. }
  2298. D->addAttr(new (S.Context) ObjCMethodFamilyAttr(
  2299. AL.getRange(), S.Context, F, AL.getAttributeSpellingListIndex()));
  2300. }
  2301. static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) {
  2302. if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  2303. QualType T = TD->getUnderlyingType();
  2304. if (!T->isCARCBridgableType()) {
  2305. S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
  2306. return;
  2307. }
  2308. }
  2309. else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
  2310. QualType T = PD->getType();
  2311. if (!T->isCARCBridgableType()) {
  2312. S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
  2313. return;
  2314. }
  2315. }
  2316. else {
  2317. // It is okay to include this attribute on properties, e.g.:
  2318. //
  2319. // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
  2320. //
  2321. // In this case it follows tradition and suppresses an error in the above
  2322. // case.
  2323. S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
  2324. }
  2325. D->addAttr(::new (S.Context)
  2326. ObjCNSObjectAttr(AL.getRange(), S.Context,
  2327. AL.getAttributeSpellingListIndex()));
  2328. }
  2329. static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) {
  2330. if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  2331. QualType T = TD->getUnderlyingType();
  2332. if (!T->isObjCObjectPointerType()) {
  2333. S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
  2334. return;
  2335. }
  2336. } else {
  2337. S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
  2338. return;
  2339. }
  2340. D->addAttr(::new (S.Context)
  2341. ObjCIndependentClassAttr(AL.getRange(), S.Context,
  2342. AL.getAttributeSpellingListIndex()));
  2343. }
  2344. static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2345. if (!AL.isArgIdent(0)) {
  2346. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  2347. << AL << 1 << AANT_ArgumentIdentifier;
  2348. return;
  2349. }
  2350. IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
  2351. BlocksAttr::BlockType type;
  2352. if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
  2353. S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
  2354. return;
  2355. }
  2356. D->addAttr(::new (S.Context)
  2357. BlocksAttr(AL.getRange(), S.Context, type,
  2358. AL.getAttributeSpellingListIndex()));
  2359. }
  2360. static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2361. unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
  2362. if (AL.getNumArgs() > 0) {
  2363. Expr *E = AL.getArgAsExpr(0);
  2364. llvm::APSInt Idx(32);
  2365. if (E->isTypeDependent() || E->isValueDependent() ||
  2366. !E->isIntegerConstantExpr(Idx, S.Context)) {
  2367. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  2368. << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
  2369. return;
  2370. }
  2371. if (Idx.isSigned() && Idx.isNegative()) {
  2372. S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
  2373. << E->getSourceRange();
  2374. return;
  2375. }
  2376. sentinel = Idx.getZExtValue();
  2377. }
  2378. unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
  2379. if (AL.getNumArgs() > 1) {
  2380. Expr *E = AL.getArgAsExpr(1);
  2381. llvm::APSInt Idx(32);
  2382. if (E->isTypeDependent() || E->isValueDependent() ||
  2383. !E->isIntegerConstantExpr(Idx, S.Context)) {
  2384. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  2385. << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
  2386. return;
  2387. }
  2388. nullPos = Idx.getZExtValue();
  2389. if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
  2390. // FIXME: This error message could be improved, it would be nice
  2391. // to say what the bounds actually are.
  2392. S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
  2393. << E->getSourceRange();
  2394. return;
  2395. }
  2396. }
  2397. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  2398. const FunctionType *FT = FD->getType()->castAs<FunctionType>();
  2399. if (isa<FunctionNoProtoType>(FT)) {
  2400. S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
  2401. return;
  2402. }
  2403. if (!cast<FunctionProtoType>(FT)->isVariadic()) {
  2404. S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
  2405. return;
  2406. }
  2407. } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
  2408. if (!MD->isVariadic()) {
  2409. S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
  2410. return;
  2411. }
  2412. } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
  2413. if (!BD->isVariadic()) {
  2414. S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
  2415. return;
  2416. }
  2417. } else if (const auto *V = dyn_cast<VarDecl>(D)) {
  2418. QualType Ty = V->getType();
  2419. if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
  2420. const FunctionType *FT = Ty->isFunctionPointerType()
  2421. ? D->getFunctionType()
  2422. : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
  2423. if (!cast<FunctionProtoType>(FT)->isVariadic()) {
  2424. int m = Ty->isFunctionPointerType() ? 0 : 1;
  2425. S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
  2426. return;
  2427. }
  2428. } else {
  2429. S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
  2430. << AL << ExpectedFunctionMethodOrBlock;
  2431. return;
  2432. }
  2433. } else {
  2434. S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
  2435. << AL << ExpectedFunctionMethodOrBlock;
  2436. return;
  2437. }
  2438. D->addAttr(::new (S.Context)
  2439. SentinelAttr(AL.getRange(), S.Context, sentinel, nullPos,
  2440. AL.getAttributeSpellingListIndex()));
  2441. }
  2442. static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
  2443. if (D->getFunctionType() &&
  2444. D->getFunctionType()->getReturnType()->isVoidType()) {
  2445. S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
  2446. return;
  2447. }
  2448. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  2449. if (MD->getReturnType()->isVoidType()) {
  2450. S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
  2451. return;
  2452. }
  2453. // If this is spelled as the standard C++17 attribute, but not in C++17, warn
  2454. // about using it as an extension.
  2455. if (!S.getLangOpts().CPlusPlus17 && AL.isCXX11Attribute() &&
  2456. !AL.getScopeName())
  2457. S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
  2458. D->addAttr(::new (S.Context)
  2459. WarnUnusedResultAttr(AL.getRange(), S.Context,
  2460. AL.getAttributeSpellingListIndex()));
  2461. }
  2462. static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2463. // weak_import only applies to variable & function declarations.
  2464. bool isDef = false;
  2465. if (!D->canBeWeakImported(isDef)) {
  2466. if (isDef)
  2467. S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
  2468. << "weak_import";
  2469. else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
  2470. (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
  2471. (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
  2472. // Nothing to warn about here.
  2473. } else
  2474. S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
  2475. << AL << ExpectedVariableOrFunction;
  2476. return;
  2477. }
  2478. D->addAttr(::new (S.Context)
  2479. WeakImportAttr(AL.getRange(), S.Context,
  2480. AL.getAttributeSpellingListIndex()));
  2481. }
  2482. // Handles reqd_work_group_size and work_group_size_hint.
  2483. template <typename WorkGroupAttr>
  2484. static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
  2485. uint32_t WGSize[3];
  2486. for (unsigned i = 0; i < 3; ++i) {
  2487. const Expr *E = AL.getArgAsExpr(i);
  2488. if (!checkUInt32Argument(S, AL, E, WGSize[i], i,
  2489. /*StrictlyUnsigned=*/true))
  2490. return;
  2491. if (WGSize[i] == 0) {
  2492. S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
  2493. << AL << E->getSourceRange();
  2494. return;
  2495. }
  2496. }
  2497. WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
  2498. if (Existing && !(Existing->getXDim() == WGSize[0] &&
  2499. Existing->getYDim() == WGSize[1] &&
  2500. Existing->getZDim() == WGSize[2]))
  2501. S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
  2502. D->addAttr(::new (S.Context) WorkGroupAttr(AL.getRange(), S.Context,
  2503. WGSize[0], WGSize[1], WGSize[2],
  2504. AL.getAttributeSpellingListIndex()));
  2505. }
  2506. // Handles intel_reqd_sub_group_size.
  2507. static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
  2508. uint32_t SGSize;
  2509. const Expr *E = AL.getArgAsExpr(0);
  2510. if (!checkUInt32Argument(S, AL, E, SGSize))
  2511. return;
  2512. if (SGSize == 0) {
  2513. S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
  2514. << AL << E->getSourceRange();
  2515. return;
  2516. }
  2517. OpenCLIntelReqdSubGroupSizeAttr *Existing =
  2518. D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
  2519. if (Existing && Existing->getSubGroupSize() != SGSize)
  2520. S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
  2521. D->addAttr(::new (S.Context) OpenCLIntelReqdSubGroupSizeAttr(
  2522. AL.getRange(), S.Context, SGSize,
  2523. AL.getAttributeSpellingListIndex()));
  2524. }
  2525. static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
  2526. if (!AL.hasParsedType()) {
  2527. S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
  2528. return;
  2529. }
  2530. TypeSourceInfo *ParmTSI = nullptr;
  2531. QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
  2532. assert(ParmTSI && "no type source info for attribute argument");
  2533. if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
  2534. (ParmType->isBooleanType() ||
  2535. !ParmType->isIntegralType(S.getASTContext()))) {
  2536. S.Diag(AL.getLoc(), diag::err_attribute_argument_vec_type_hint)
  2537. << ParmType;
  2538. return;
  2539. }
  2540. if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
  2541. if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
  2542. S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
  2543. return;
  2544. }
  2545. }
  2546. D->addAttr(::new (S.Context) VecTypeHintAttr(AL.getLoc(), S.Context,
  2547. ParmTSI,
  2548. AL.getAttributeSpellingListIndex()));
  2549. }
  2550. SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
  2551. StringRef Name,
  2552. unsigned AttrSpellingListIndex) {
  2553. // Explicit or partial specializations do not inherit
  2554. // the section attribute from the primary template.
  2555. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  2556. if (AttrSpellingListIndex == SectionAttr::Declspec_allocate &&
  2557. FD->isFunctionTemplateSpecialization())
  2558. return nullptr;
  2559. }
  2560. if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
  2561. if (ExistingAttr->getName() == Name)
  2562. return nullptr;
  2563. Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
  2564. << 1 /*section*/;
  2565. Diag(Range.getBegin(), diag::note_previous_attribute);
  2566. return nullptr;
  2567. }
  2568. return ::new (Context) SectionAttr(Range, Context, Name,
  2569. AttrSpellingListIndex);
  2570. }
  2571. bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
  2572. std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
  2573. if (!Error.empty()) {
  2574. Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error
  2575. << 1 /*'section'*/;
  2576. return false;
  2577. }
  2578. return true;
  2579. }
  2580. static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2581. // Make sure that there is a string literal as the sections's single
  2582. // argument.
  2583. StringRef Str;
  2584. SourceLocation LiteralLoc;
  2585. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
  2586. return;
  2587. if (!S.checkSectionName(LiteralLoc, Str))
  2588. return;
  2589. // If the target wants to validate the section specifier, make it happen.
  2590. std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
  2591. if (!Error.empty()) {
  2592. S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
  2593. << Error;
  2594. return;
  2595. }
  2596. unsigned Index = AL.getAttributeSpellingListIndex();
  2597. SectionAttr *NewAttr = S.mergeSectionAttr(D, AL.getRange(), Str, Index);
  2598. if (NewAttr)
  2599. D->addAttr(NewAttr);
  2600. }
  2601. static bool checkCodeSegName(Sema&S, SourceLocation LiteralLoc, StringRef CodeSegName) {
  2602. std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(CodeSegName);
  2603. if (!Error.empty()) {
  2604. S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error
  2605. << 0 /*'code-seg'*/;
  2606. return false;
  2607. }
  2608. return true;
  2609. }
  2610. CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, SourceRange Range,
  2611. StringRef Name,
  2612. unsigned AttrSpellingListIndex) {
  2613. // Explicit or partial specializations do not inherit
  2614. // the code_seg attribute from the primary template.
  2615. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  2616. if (FD->isFunctionTemplateSpecialization())
  2617. return nullptr;
  2618. }
  2619. if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
  2620. if (ExistingAttr->getName() == Name)
  2621. return nullptr;
  2622. Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
  2623. << 0 /*codeseg*/;
  2624. Diag(Range.getBegin(), diag::note_previous_attribute);
  2625. return nullptr;
  2626. }
  2627. return ::new (Context) CodeSegAttr(Range, Context, Name,
  2628. AttrSpellingListIndex);
  2629. }
  2630. static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2631. StringRef Str;
  2632. SourceLocation LiteralLoc;
  2633. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
  2634. return;
  2635. if (!checkCodeSegName(S, LiteralLoc, Str))
  2636. return;
  2637. if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
  2638. if (!ExistingAttr->isImplicit()) {
  2639. S.Diag(AL.getLoc(),
  2640. ExistingAttr->getName() == Str
  2641. ? diag::warn_duplicate_codeseg_attribute
  2642. : diag::err_conflicting_codeseg_attribute);
  2643. return;
  2644. }
  2645. D->dropAttr<CodeSegAttr>();
  2646. }
  2647. if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL.getRange(), Str,
  2648. AL.getAttributeSpellingListIndex()))
  2649. D->addAttr(CSA);
  2650. }
  2651. // Check for things we'd like to warn about. Multiversioning issues are
  2652. // handled later in the process, once we know how many exist.
  2653. bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
  2654. enum FirstParam { Unsupported, Duplicate };
  2655. enum SecondParam { None, Architecture };
  2656. for (auto Str : {"tune=", "fpmath="})
  2657. if (AttrStr.find(Str) != StringRef::npos)
  2658. return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
  2659. << Unsupported << None << Str;
  2660. TargetAttr::ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr);
  2661. if (!ParsedAttrs.Architecture.empty() &&
  2662. !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture))
  2663. return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
  2664. << Unsupported << Architecture << ParsedAttrs.Architecture;
  2665. if (ParsedAttrs.DuplicateArchitecture)
  2666. return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
  2667. << Duplicate << None << "arch=";
  2668. for (const auto &Feature : ParsedAttrs.Features) {
  2669. auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
  2670. if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
  2671. return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
  2672. << Unsupported << None << CurFeature;
  2673. }
  2674. return false;
  2675. }
  2676. static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2677. StringRef Str;
  2678. SourceLocation LiteralLoc;
  2679. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
  2680. S.checkTargetAttr(LiteralLoc, Str))
  2681. return;
  2682. unsigned Index = AL.getAttributeSpellingListIndex();
  2683. TargetAttr *NewAttr =
  2684. ::new (S.Context) TargetAttr(AL.getRange(), S.Context, Str, Index);
  2685. D->addAttr(NewAttr);
  2686. }
  2687. static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2688. Expr *E = AL.getArgAsExpr(0);
  2689. uint32_t VecWidth;
  2690. if (!checkUInt32Argument(S, AL, E, VecWidth)) {
  2691. AL.setInvalid();
  2692. return;
  2693. }
  2694. MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
  2695. if (Existing && Existing->getVectorWidth() != VecWidth) {
  2696. S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
  2697. return;
  2698. }
  2699. D->addAttr(::new (S.Context)
  2700. MinVectorWidthAttr(AL.getRange(), S.Context, VecWidth,
  2701. AL.getAttributeSpellingListIndex()));
  2702. }
  2703. static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2704. Expr *E = AL.getArgAsExpr(0);
  2705. SourceLocation Loc = E->getExprLoc();
  2706. FunctionDecl *FD = nullptr;
  2707. DeclarationNameInfo NI;
  2708. // gcc only allows for simple identifiers. Since we support more than gcc, we
  2709. // will warn the user.
  2710. if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
  2711. if (DRE->hasQualifier())
  2712. S.Diag(Loc, diag::warn_cleanup_ext);
  2713. FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  2714. NI = DRE->getNameInfo();
  2715. if (!FD) {
  2716. S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
  2717. << NI.getName();
  2718. return;
  2719. }
  2720. } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  2721. if (ULE->hasExplicitTemplateArgs())
  2722. S.Diag(Loc, diag::warn_cleanup_ext);
  2723. FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
  2724. NI = ULE->getNameInfo();
  2725. if (!FD) {
  2726. S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
  2727. << NI.getName();
  2728. if (ULE->getType() == S.Context.OverloadTy)
  2729. S.NoteAllOverloadCandidates(ULE);
  2730. return;
  2731. }
  2732. } else {
  2733. S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
  2734. return;
  2735. }
  2736. if (FD->getNumParams() != 1) {
  2737. S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
  2738. << NI.getName();
  2739. return;
  2740. }
  2741. // We're currently more strict than GCC about what function types we accept.
  2742. // If this ever proves to be a problem it should be easy to fix.
  2743. QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
  2744. QualType ParamTy = FD->getParamDecl(0)->getType();
  2745. if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
  2746. ParamTy, Ty) != Sema::Compatible) {
  2747. S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
  2748. << NI.getName() << ParamTy << Ty;
  2749. return;
  2750. }
  2751. D->addAttr(::new (S.Context)
  2752. CleanupAttr(AL.getRange(), S.Context, FD,
  2753. AL.getAttributeSpellingListIndex()));
  2754. }
  2755. static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
  2756. const ParsedAttr &AL) {
  2757. if (!AL.isArgIdent(0)) {
  2758. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  2759. << AL << 0 << AANT_ArgumentIdentifier;
  2760. return;
  2761. }
  2762. EnumExtensibilityAttr::Kind ExtensibilityKind;
  2763. IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
  2764. if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
  2765. ExtensibilityKind)) {
  2766. S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
  2767. return;
  2768. }
  2769. D->addAttr(::new (S.Context) EnumExtensibilityAttr(
  2770. AL.getRange(), S.Context, ExtensibilityKind,
  2771. AL.getAttributeSpellingListIndex()));
  2772. }
  2773. /// Handle __attribute__((format_arg((idx)))) attribute based on
  2774. /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
  2775. static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2776. Expr *IdxExpr = AL.getArgAsExpr(0);
  2777. ParamIdx Idx;
  2778. if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
  2779. return;
  2780. // Make sure the format string is really a string.
  2781. QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
  2782. bool NotNSStringTy = !isNSStringType(Ty, S.Context);
  2783. if (NotNSStringTy &&
  2784. !isCFStringType(Ty, S.Context) &&
  2785. (!Ty->isPointerType() ||
  2786. !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
  2787. S.Diag(AL.getLoc(), diag::err_format_attribute_not)
  2788. << "a string type" << IdxExpr->getSourceRange()
  2789. << getFunctionOrMethodParamRange(D, 0);
  2790. return;
  2791. }
  2792. Ty = getFunctionOrMethodResultType(D);
  2793. if (!isNSStringType(Ty, S.Context) &&
  2794. !isCFStringType(Ty, S.Context) &&
  2795. (!Ty->isPointerType() ||
  2796. !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
  2797. S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
  2798. << (NotNSStringTy ? "string type" : "NSString")
  2799. << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
  2800. return;
  2801. }
  2802. D->addAttr(::new (S.Context) FormatArgAttr(
  2803. AL.getRange(), S.Context, Idx, AL.getAttributeSpellingListIndex()));
  2804. }
  2805. enum FormatAttrKind {
  2806. CFStringFormat,
  2807. NSStringFormat,
  2808. StrftimeFormat,
  2809. SupportedFormat,
  2810. IgnoredFormat,
  2811. InvalidFormat
  2812. };
  2813. /// getFormatAttrKind - Map from format attribute names to supported format
  2814. /// types.
  2815. static FormatAttrKind getFormatAttrKind(StringRef Format) {
  2816. return llvm::StringSwitch<FormatAttrKind>(Format)
  2817. // Check for formats that get handled specially.
  2818. .Case("NSString", NSStringFormat)
  2819. .Case("CFString", CFStringFormat)
  2820. .Case("strftime", StrftimeFormat)
  2821. // Otherwise, check for supported formats.
  2822. .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
  2823. .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
  2824. .Case("kprintf", SupportedFormat) // OpenBSD.
  2825. .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
  2826. .Case("os_trace", SupportedFormat)
  2827. .Case("os_log", SupportedFormat)
  2828. .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
  2829. .Default(InvalidFormat);
  2830. }
  2831. /// Handle __attribute__((init_priority(priority))) attributes based on
  2832. /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
  2833. static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2834. if (!S.getLangOpts().CPlusPlus) {
  2835. S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
  2836. return;
  2837. }
  2838. if (S.getCurFunctionOrMethodDecl()) {
  2839. S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
  2840. AL.setInvalid();
  2841. return;
  2842. }
  2843. QualType T = cast<VarDecl>(D)->getType();
  2844. if (S.Context.getAsArrayType(T))
  2845. T = S.Context.getBaseElementType(T);
  2846. if (!T->getAs<RecordType>()) {
  2847. S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
  2848. AL.setInvalid();
  2849. return;
  2850. }
  2851. Expr *E = AL.getArgAsExpr(0);
  2852. uint32_t prioritynum;
  2853. if (!checkUInt32Argument(S, AL, E, prioritynum)) {
  2854. AL.setInvalid();
  2855. return;
  2856. }
  2857. if (prioritynum < 101 || prioritynum > 65535) {
  2858. S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
  2859. << E->getSourceRange() << AL << 101 << 65535;
  2860. AL.setInvalid();
  2861. return;
  2862. }
  2863. D->addAttr(::new (S.Context)
  2864. InitPriorityAttr(AL.getRange(), S.Context, prioritynum,
  2865. AL.getAttributeSpellingListIndex()));
  2866. }
  2867. FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
  2868. IdentifierInfo *Format, int FormatIdx,
  2869. int FirstArg,
  2870. unsigned AttrSpellingListIndex) {
  2871. // Check whether we already have an equivalent format attribute.
  2872. for (auto *F : D->specific_attrs<FormatAttr>()) {
  2873. if (F->getType() == Format &&
  2874. F->getFormatIdx() == FormatIdx &&
  2875. F->getFirstArg() == FirstArg) {
  2876. // If we don't have a valid location for this attribute, adopt the
  2877. // location.
  2878. if (F->getLocation().isInvalid())
  2879. F->setRange(Range);
  2880. return nullptr;
  2881. }
  2882. }
  2883. return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
  2884. FirstArg, AttrSpellingListIndex);
  2885. }
  2886. /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
  2887. /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
  2888. static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2889. if (!AL.isArgIdent(0)) {
  2890. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  2891. << AL << 1 << AANT_ArgumentIdentifier;
  2892. return;
  2893. }
  2894. // In C++ the implicit 'this' function parameter also counts, and they are
  2895. // counted from one.
  2896. bool HasImplicitThisParam = isInstanceMethod(D);
  2897. unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
  2898. IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
  2899. StringRef Format = II->getName();
  2900. if (normalizeName(Format)) {
  2901. // If we've modified the string name, we need a new identifier for it.
  2902. II = &S.Context.Idents.get(Format);
  2903. }
  2904. // Check for supported formats.
  2905. FormatAttrKind Kind = getFormatAttrKind(Format);
  2906. if (Kind == IgnoredFormat)
  2907. return;
  2908. if (Kind == InvalidFormat) {
  2909. S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
  2910. << AL << II->getName();
  2911. return;
  2912. }
  2913. // checks for the 2nd argument
  2914. Expr *IdxExpr = AL.getArgAsExpr(1);
  2915. uint32_t Idx;
  2916. if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2))
  2917. return;
  2918. if (Idx < 1 || Idx > NumArgs) {
  2919. S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
  2920. << AL << 2 << IdxExpr->getSourceRange();
  2921. return;
  2922. }
  2923. // FIXME: Do we need to bounds check?
  2924. unsigned ArgIdx = Idx - 1;
  2925. if (HasImplicitThisParam) {
  2926. if (ArgIdx == 0) {
  2927. S.Diag(AL.getLoc(),
  2928. diag::err_format_attribute_implicit_this_format_string)
  2929. << IdxExpr->getSourceRange();
  2930. return;
  2931. }
  2932. ArgIdx--;
  2933. }
  2934. // make sure the format string is really a string
  2935. QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
  2936. if (Kind == CFStringFormat) {
  2937. if (!isCFStringType(Ty, S.Context)) {
  2938. S.Diag(AL.getLoc(), diag::err_format_attribute_not)
  2939. << "a CFString" << IdxExpr->getSourceRange()
  2940. << getFunctionOrMethodParamRange(D, ArgIdx);
  2941. return;
  2942. }
  2943. } else if (Kind == NSStringFormat) {
  2944. // FIXME: do we need to check if the type is NSString*? What are the
  2945. // semantics?
  2946. if (!isNSStringType(Ty, S.Context)) {
  2947. S.Diag(AL.getLoc(), diag::err_format_attribute_not)
  2948. << "an NSString" << IdxExpr->getSourceRange()
  2949. << getFunctionOrMethodParamRange(D, ArgIdx);
  2950. return;
  2951. }
  2952. } else if (!Ty->isPointerType() ||
  2953. !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
  2954. S.Diag(AL.getLoc(), diag::err_format_attribute_not)
  2955. << "a string type" << IdxExpr->getSourceRange()
  2956. << getFunctionOrMethodParamRange(D, ArgIdx);
  2957. return;
  2958. }
  2959. // check the 3rd argument
  2960. Expr *FirstArgExpr = AL.getArgAsExpr(2);
  2961. uint32_t FirstArg;
  2962. if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
  2963. return;
  2964. // check if the function is variadic if the 3rd argument non-zero
  2965. if (FirstArg != 0) {
  2966. if (isFunctionOrMethodVariadic(D)) {
  2967. ++NumArgs; // +1 for ...
  2968. } else {
  2969. S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
  2970. return;
  2971. }
  2972. }
  2973. // strftime requires FirstArg to be 0 because it doesn't read from any
  2974. // variable the input is just the current time + the format string.
  2975. if (Kind == StrftimeFormat) {
  2976. if (FirstArg != 0) {
  2977. S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
  2978. << FirstArgExpr->getSourceRange();
  2979. return;
  2980. }
  2981. // if 0 it disables parameter checking (to use with e.g. va_list)
  2982. } else if (FirstArg != 0 && FirstArg != NumArgs) {
  2983. S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
  2984. << AL << 3 << FirstArgExpr->getSourceRange();
  2985. return;
  2986. }
  2987. FormatAttr *NewAttr = S.mergeFormatAttr(D, AL.getRange(), II,
  2988. Idx, FirstArg,
  2989. AL.getAttributeSpellingListIndex());
  2990. if (NewAttr)
  2991. D->addAttr(NewAttr);
  2992. }
  2993. /// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
  2994. static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  2995. // The index that identifies the callback callee is mandatory.
  2996. if (AL.getNumArgs() == 0) {
  2997. S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
  2998. << AL.getRange();
  2999. return;
  3000. }
  3001. bool HasImplicitThisParam = isInstanceMethod(D);
  3002. int32_t NumArgs = getFunctionOrMethodNumParams(D);
  3003. FunctionDecl *FD = D->getAsFunction();
  3004. assert(FD && "Expected a function declaration!");
  3005. llvm::StringMap<int> NameIdxMapping;
  3006. NameIdxMapping["__"] = -1;
  3007. NameIdxMapping["this"] = 0;
  3008. int Idx = 1;
  3009. for (const ParmVarDecl *PVD : FD->parameters())
  3010. NameIdxMapping[PVD->getName()] = Idx++;
  3011. auto UnknownName = NameIdxMapping.end();
  3012. SmallVector<int, 8> EncodingIndices;
  3013. for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
  3014. SourceRange SR;
  3015. int32_t ArgIdx;
  3016. if (AL.isArgIdent(I)) {
  3017. IdentifierLoc *IdLoc = AL.getArgAsIdent(I);
  3018. auto It = NameIdxMapping.find(IdLoc->Ident->getName());
  3019. if (It == UnknownName) {
  3020. S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown)
  3021. << IdLoc->Ident << IdLoc->Loc;
  3022. return;
  3023. }
  3024. SR = SourceRange(IdLoc->Loc);
  3025. ArgIdx = It->second;
  3026. } else if (AL.isArgExpr(I)) {
  3027. Expr *IdxExpr = AL.getArgAsExpr(I);
  3028. // If the expression is not parseable as an int32_t we have a problem.
  3029. if (!checkUInt32Argument(S, AL, IdxExpr, (uint32_t &)ArgIdx, I + 1,
  3030. false)) {
  3031. S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
  3032. << AL << (I + 1) << IdxExpr->getSourceRange();
  3033. return;
  3034. }
  3035. // Check oob, excluding the special values, 0 and -1.
  3036. if (ArgIdx < -1 || ArgIdx > NumArgs) {
  3037. S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
  3038. << AL << (I + 1) << IdxExpr->getSourceRange();
  3039. return;
  3040. }
  3041. SR = IdxExpr->getSourceRange();
  3042. } else {
  3043. llvm_unreachable("Unexpected ParsedAttr argument type!");
  3044. }
  3045. if (ArgIdx == 0 && !HasImplicitThisParam) {
  3046. S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available)
  3047. << (I + 1) << SR;
  3048. return;
  3049. }
  3050. // Adjust for the case we do not have an implicit "this" parameter. In this
  3051. // case we decrease all positive values by 1 to get LLVM argument indices.
  3052. if (!HasImplicitThisParam && ArgIdx > 0)
  3053. ArgIdx -= 1;
  3054. EncodingIndices.push_back(ArgIdx);
  3055. }
  3056. int CalleeIdx = EncodingIndices.front();
  3057. // Check if the callee index is proper, thus not "this" and not "unknown".
  3058. // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
  3059. // is false and positive if "HasImplicitThisParam" is true.
  3060. if (CalleeIdx < (int)HasImplicitThisParam) {
  3061. S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee)
  3062. << AL.getRange();
  3063. return;
  3064. }
  3065. // Get the callee type, note the index adjustment as the AST doesn't contain
  3066. // the this type (which the callee cannot reference anyway!).
  3067. const Type *CalleeType =
  3068. getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam)
  3069. .getTypePtr();
  3070. if (!CalleeType || !CalleeType->isFunctionPointerType()) {
  3071. S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
  3072. << AL.getRange();
  3073. return;
  3074. }
  3075. const Type *CalleeFnType =
  3076. CalleeType->getPointeeType()->getUnqualifiedDesugaredType();
  3077. // TODO: Check the type of the callee arguments.
  3078. const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType);
  3079. if (!CalleeFnProtoType) {
  3080. S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
  3081. << AL.getRange();
  3082. return;
  3083. }
  3084. if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) {
  3085. S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
  3086. << AL << (unsigned)(EncodingIndices.size() - 1);
  3087. return;
  3088. }
  3089. if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) {
  3090. S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
  3091. << AL << (unsigned)(EncodingIndices.size() - 1);
  3092. return;
  3093. }
  3094. if (CalleeFnProtoType->isVariadic()) {
  3095. S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange();
  3096. return;
  3097. }
  3098. // Do not allow multiple callback attributes.
  3099. if (D->hasAttr<CallbackAttr>()) {
  3100. S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange();
  3101. return;
  3102. }
  3103. D->addAttr(::new (S.Context) CallbackAttr(
  3104. AL.getRange(), S.Context, EncodingIndices.data(), EncodingIndices.size(),
  3105. AL.getAttributeSpellingListIndex()));
  3106. }
  3107. static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3108. // Try to find the underlying union declaration.
  3109. RecordDecl *RD = nullptr;
  3110. const auto *TD = dyn_cast<TypedefNameDecl>(D);
  3111. if (TD && TD->getUnderlyingType()->isUnionType())
  3112. RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
  3113. else
  3114. RD = dyn_cast<RecordDecl>(D);
  3115. if (!RD || !RD->isUnion()) {
  3116. S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL
  3117. << ExpectedUnion;
  3118. return;
  3119. }
  3120. if (!RD->isCompleteDefinition()) {
  3121. if (!RD->isBeingDefined())
  3122. S.Diag(AL.getLoc(),
  3123. diag::warn_transparent_union_attribute_not_definition);
  3124. return;
  3125. }
  3126. RecordDecl::field_iterator Field = RD->field_begin(),
  3127. FieldEnd = RD->field_end();
  3128. if (Field == FieldEnd) {
  3129. S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
  3130. return;
  3131. }
  3132. FieldDecl *FirstField = *Field;
  3133. QualType FirstType = FirstField->getType();
  3134. if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
  3135. S.Diag(FirstField->getLocation(),
  3136. diag::warn_transparent_union_attribute_floating)
  3137. << FirstType->isVectorType() << FirstType;
  3138. return;
  3139. }
  3140. if (FirstType->isIncompleteType())
  3141. return;
  3142. uint64_t FirstSize = S.Context.getTypeSize(FirstType);
  3143. uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
  3144. for (; Field != FieldEnd; ++Field) {
  3145. QualType FieldType = Field->getType();
  3146. if (FieldType->isIncompleteType())
  3147. return;
  3148. // FIXME: this isn't fully correct; we also need to test whether the
  3149. // members of the union would all have the same calling convention as the
  3150. // first member of the union. Checking just the size and alignment isn't
  3151. // sufficient (consider structs passed on the stack instead of in registers
  3152. // as an example).
  3153. if (S.Context.getTypeSize(FieldType) != FirstSize ||
  3154. S.Context.getTypeAlign(FieldType) > FirstAlign) {
  3155. // Warn if we drop the attribute.
  3156. bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
  3157. unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
  3158. : S.Context.getTypeAlign(FieldType);
  3159. S.Diag(Field->getLocation(),
  3160. diag::warn_transparent_union_attribute_field_size_align)
  3161. << isSize << Field->getDeclName() << FieldBits;
  3162. unsigned FirstBits = isSize? FirstSize : FirstAlign;
  3163. S.Diag(FirstField->getLocation(),
  3164. diag::note_transparent_union_first_field_size_align)
  3165. << isSize << FirstBits;
  3166. return;
  3167. }
  3168. }
  3169. RD->addAttr(::new (S.Context)
  3170. TransparentUnionAttr(AL.getRange(), S.Context,
  3171. AL.getAttributeSpellingListIndex()));
  3172. }
  3173. static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3174. // Make sure that there is a string literal as the annotation's single
  3175. // argument.
  3176. StringRef Str;
  3177. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
  3178. return;
  3179. // Don't duplicate annotations that are already set.
  3180. for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
  3181. if (I->getAnnotation() == Str)
  3182. return;
  3183. }
  3184. D->addAttr(::new (S.Context)
  3185. AnnotateAttr(AL.getRange(), S.Context, Str,
  3186. AL.getAttributeSpellingListIndex()));
  3187. }
  3188. static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3189. S.AddAlignValueAttr(AL.getRange(), D, AL.getArgAsExpr(0),
  3190. AL.getAttributeSpellingListIndex());
  3191. }
  3192. void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
  3193. unsigned SpellingListIndex) {
  3194. AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
  3195. SourceLocation AttrLoc = AttrRange.getBegin();
  3196. QualType T;
  3197. if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
  3198. T = TD->getUnderlyingType();
  3199. else if (const auto *VD = dyn_cast<ValueDecl>(D))
  3200. T = VD->getType();
  3201. else
  3202. llvm_unreachable("Unknown decl type for align_value");
  3203. if (!T->isDependentType() && !T->isAnyPointerType() &&
  3204. !T->isReferenceType() && !T->isMemberPointerType()) {
  3205. Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
  3206. << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
  3207. return;
  3208. }
  3209. if (!E->isValueDependent()) {
  3210. llvm::APSInt Alignment;
  3211. ExprResult ICE
  3212. = VerifyIntegerConstantExpression(E, &Alignment,
  3213. diag::err_align_value_attribute_argument_not_int,
  3214. /*AllowFold*/ false);
  3215. if (ICE.isInvalid())
  3216. return;
  3217. if (!Alignment.isPowerOf2()) {
  3218. Diag(AttrLoc, diag::err_alignment_not_power_of_two)
  3219. << E->getSourceRange();
  3220. return;
  3221. }
  3222. D->addAttr(::new (Context)
  3223. AlignValueAttr(AttrRange, Context, ICE.get(),
  3224. SpellingListIndex));
  3225. return;
  3226. }
  3227. // Save dependent expressions in the AST to be instantiated.
  3228. D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
  3229. }
  3230. static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3231. // check the attribute arguments.
  3232. if (AL.getNumArgs() > 1) {
  3233. S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
  3234. return;
  3235. }
  3236. if (AL.getNumArgs() == 0) {
  3237. D->addAttr(::new (S.Context) AlignedAttr(AL.getRange(), S.Context,
  3238. true, nullptr, AL.getAttributeSpellingListIndex()));
  3239. return;
  3240. }
  3241. Expr *E = AL.getArgAsExpr(0);
  3242. if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
  3243. S.Diag(AL.getEllipsisLoc(),
  3244. diag::err_pack_expansion_without_parameter_packs);
  3245. return;
  3246. }
  3247. if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
  3248. return;
  3249. S.AddAlignedAttr(AL.getRange(), D, E, AL.getAttributeSpellingListIndex(),
  3250. AL.isPackExpansion());
  3251. }
  3252. void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
  3253. unsigned SpellingListIndex, bool IsPackExpansion) {
  3254. AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
  3255. SourceLocation AttrLoc = AttrRange.getBegin();
  3256. // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
  3257. if (TmpAttr.isAlignas()) {
  3258. // C++11 [dcl.align]p1:
  3259. // An alignment-specifier may be applied to a variable or to a class
  3260. // data member, but it shall not be applied to a bit-field, a function
  3261. // parameter, the formal parameter of a catch clause, or a variable
  3262. // declared with the register storage class specifier. An
  3263. // alignment-specifier may also be applied to the declaration of a class
  3264. // or enumeration type.
  3265. // C11 6.7.5/2:
  3266. // An alignment attribute shall not be specified in a declaration of
  3267. // a typedef, or a bit-field, or a function, or a parameter, or an
  3268. // object declared with the register storage-class specifier.
  3269. int DiagKind = -1;
  3270. if (isa<ParmVarDecl>(D)) {
  3271. DiagKind = 0;
  3272. } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
  3273. if (VD->getStorageClass() == SC_Register)
  3274. DiagKind = 1;
  3275. if (VD->isExceptionVariable())
  3276. DiagKind = 2;
  3277. } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
  3278. if (FD->isBitField())
  3279. DiagKind = 3;
  3280. } else if (!isa<TagDecl>(D)) {
  3281. Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
  3282. << (TmpAttr.isC11() ? ExpectedVariableOrField
  3283. : ExpectedVariableFieldOrTag);
  3284. return;
  3285. }
  3286. if (DiagKind != -1) {
  3287. Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
  3288. << &TmpAttr << DiagKind;
  3289. return;
  3290. }
  3291. }
  3292. if (E->isValueDependent()) {
  3293. // We can't support a dependent alignment on a non-dependent type,
  3294. // because we have no way to model that a type is "alignment-dependent"
  3295. // but not dependent in any other way.
  3296. if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
  3297. if (!TND->getUnderlyingType()->isDependentType()) {
  3298. Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
  3299. << E->getSourceRange();
  3300. return;
  3301. }
  3302. }
  3303. // Save dependent expressions in the AST to be instantiated.
  3304. AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
  3305. AA->setPackExpansion(IsPackExpansion);
  3306. D->addAttr(AA);
  3307. return;
  3308. }
  3309. // FIXME: Cache the number on the AL object?
  3310. llvm::APSInt Alignment;
  3311. ExprResult ICE
  3312. = VerifyIntegerConstantExpression(E, &Alignment,
  3313. diag::err_aligned_attribute_argument_not_int,
  3314. /*AllowFold*/ false);
  3315. if (ICE.isInvalid())
  3316. return;
  3317. uint64_t AlignVal = Alignment.getZExtValue();
  3318. // C++11 [dcl.align]p2:
  3319. // -- if the constant expression evaluates to zero, the alignment
  3320. // specifier shall have no effect
  3321. // C11 6.7.5p6:
  3322. // An alignment specification of zero has no effect.
  3323. if (!(TmpAttr.isAlignas() && !Alignment)) {
  3324. if (!llvm::isPowerOf2_64(AlignVal)) {
  3325. Diag(AttrLoc, diag::err_alignment_not_power_of_two)
  3326. << E->getSourceRange();
  3327. return;
  3328. }
  3329. }
  3330. // Alignment calculations can wrap around if it's greater than 2**28.
  3331. unsigned MaxValidAlignment =
  3332. Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
  3333. : 268435456;
  3334. if (AlignVal > MaxValidAlignment) {
  3335. Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
  3336. << E->getSourceRange();
  3337. return;
  3338. }
  3339. if (Context.getTargetInfo().isTLSSupported()) {
  3340. unsigned MaxTLSAlign =
  3341. Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
  3342. .getQuantity();
  3343. const auto *VD = dyn_cast<VarDecl>(D);
  3344. if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
  3345. VD->getTLSKind() != VarDecl::TLS_None) {
  3346. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  3347. << (unsigned)AlignVal << VD << MaxTLSAlign;
  3348. return;
  3349. }
  3350. }
  3351. AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
  3352. ICE.get(), SpellingListIndex);
  3353. AA->setPackExpansion(IsPackExpansion);
  3354. D->addAttr(AA);
  3355. }
  3356. void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
  3357. unsigned SpellingListIndex, bool IsPackExpansion) {
  3358. // FIXME: Cache the number on the AL object if non-dependent?
  3359. // FIXME: Perform checking of type validity
  3360. AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
  3361. SpellingListIndex);
  3362. AA->setPackExpansion(IsPackExpansion);
  3363. D->addAttr(AA);
  3364. }
  3365. void Sema::CheckAlignasUnderalignment(Decl *D) {
  3366. assert(D->hasAttrs() && "no attributes on decl");
  3367. QualType UnderlyingTy, DiagTy;
  3368. if (const auto *VD = dyn_cast<ValueDecl>(D)) {
  3369. UnderlyingTy = DiagTy = VD->getType();
  3370. } else {
  3371. UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
  3372. if (const auto *ED = dyn_cast<EnumDecl>(D))
  3373. UnderlyingTy = ED->getIntegerType();
  3374. }
  3375. if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
  3376. return;
  3377. // C++11 [dcl.align]p5, C11 6.7.5/4:
  3378. // The combined effect of all alignment attributes in a declaration shall
  3379. // not specify an alignment that is less strict than the alignment that
  3380. // would otherwise be required for the entity being declared.
  3381. AlignedAttr *AlignasAttr = nullptr;
  3382. unsigned Align = 0;
  3383. for (auto *I : D->specific_attrs<AlignedAttr>()) {
  3384. if (I->isAlignmentDependent())
  3385. return;
  3386. if (I->isAlignas())
  3387. AlignasAttr = I;
  3388. Align = std::max(Align, I->getAlignment(Context));
  3389. }
  3390. if (AlignasAttr && Align) {
  3391. CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
  3392. CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
  3393. if (NaturalAlign > RequestedAlign)
  3394. Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
  3395. << DiagTy << (unsigned)NaturalAlign.getQuantity();
  3396. }
  3397. }
  3398. bool Sema::checkMSInheritanceAttrOnDefinition(
  3399. CXXRecordDecl *RD, SourceRange Range, bool BestCase,
  3400. MSInheritanceAttr::Spelling SemanticSpelling) {
  3401. assert(RD->hasDefinition() && "RD has no definition!");
  3402. // We may not have seen base specifiers or any virtual methods yet. We will
  3403. // have to wait until the record is defined to catch any mismatches.
  3404. if (!RD->getDefinition()->isCompleteDefinition())
  3405. return false;
  3406. // The unspecified model never matches what a definition could need.
  3407. if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
  3408. return false;
  3409. if (BestCase) {
  3410. if (RD->calculateInheritanceModel() == SemanticSpelling)
  3411. return false;
  3412. } else {
  3413. if (RD->calculateInheritanceModel() <= SemanticSpelling)
  3414. return false;
  3415. }
  3416. Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
  3417. << 0 /*definition*/;
  3418. Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
  3419. << RD->getNameAsString();
  3420. return true;
  3421. }
  3422. /// parseModeAttrArg - Parses attribute mode string and returns parsed type
  3423. /// attribute.
  3424. static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
  3425. bool &IntegerMode, bool &ComplexMode) {
  3426. IntegerMode = true;
  3427. ComplexMode = false;
  3428. switch (Str.size()) {
  3429. case 2:
  3430. switch (Str[0]) {
  3431. case 'Q':
  3432. DestWidth = 8;
  3433. break;
  3434. case 'H':
  3435. DestWidth = 16;
  3436. break;
  3437. case 'S':
  3438. DestWidth = 32;
  3439. break;
  3440. case 'D':
  3441. DestWidth = 64;
  3442. break;
  3443. case 'X':
  3444. DestWidth = 96;
  3445. break;
  3446. case 'T':
  3447. DestWidth = 128;
  3448. break;
  3449. }
  3450. if (Str[1] == 'F') {
  3451. IntegerMode = false;
  3452. } else if (Str[1] == 'C') {
  3453. IntegerMode = false;
  3454. ComplexMode = true;
  3455. } else if (Str[1] != 'I') {
  3456. DestWidth = 0;
  3457. }
  3458. break;
  3459. case 4:
  3460. // FIXME: glibc uses 'word' to define register_t; this is narrower than a
  3461. // pointer on PIC16 and other embedded platforms.
  3462. if (Str == "word")
  3463. DestWidth = S.Context.getTargetInfo().getRegisterWidth();
  3464. else if (Str == "byte")
  3465. DestWidth = S.Context.getTargetInfo().getCharWidth();
  3466. break;
  3467. case 7:
  3468. if (Str == "pointer")
  3469. DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
  3470. break;
  3471. case 11:
  3472. if (Str == "unwind_word")
  3473. DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
  3474. break;
  3475. }
  3476. }
  3477. /// handleModeAttr - This attribute modifies the width of a decl with primitive
  3478. /// type.
  3479. ///
  3480. /// Despite what would be logical, the mode attribute is a decl attribute, not a
  3481. /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
  3482. /// HImode, not an intermediate pointer.
  3483. static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3484. // This attribute isn't documented, but glibc uses it. It changes
  3485. // the width of an int or unsigned int to the specified size.
  3486. if (!AL.isArgIdent(0)) {
  3487. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  3488. << AL << AANT_ArgumentIdentifier;
  3489. return;
  3490. }
  3491. IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
  3492. S.AddModeAttr(AL.getRange(), D, Name, AL.getAttributeSpellingListIndex());
  3493. }
  3494. void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
  3495. unsigned SpellingListIndex, bool InInstantiation) {
  3496. StringRef Str = Name->getName();
  3497. normalizeName(Str);
  3498. SourceLocation AttrLoc = AttrRange.getBegin();
  3499. unsigned DestWidth = 0;
  3500. bool IntegerMode = true;
  3501. bool ComplexMode = false;
  3502. llvm::APInt VectorSize(64, 0);
  3503. if (Str.size() >= 4 && Str[0] == 'V') {
  3504. // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
  3505. size_t StrSize = Str.size();
  3506. size_t VectorStringLength = 0;
  3507. while ((VectorStringLength + 1) < StrSize &&
  3508. isdigit(Str[VectorStringLength + 1]))
  3509. ++VectorStringLength;
  3510. if (VectorStringLength &&
  3511. !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
  3512. VectorSize.isPowerOf2()) {
  3513. parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
  3514. IntegerMode, ComplexMode);
  3515. // Avoid duplicate warning from template instantiation.
  3516. if (!InInstantiation)
  3517. Diag(AttrLoc, diag::warn_vector_mode_deprecated);
  3518. } else {
  3519. VectorSize = 0;
  3520. }
  3521. }
  3522. if (!VectorSize)
  3523. parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
  3524. // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
  3525. // and friends, at least with glibc.
  3526. // FIXME: Make sure floating-point mappings are accurate
  3527. // FIXME: Support XF and TF types
  3528. if (!DestWidth) {
  3529. Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
  3530. return;
  3531. }
  3532. QualType OldTy;
  3533. if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
  3534. OldTy = TD->getUnderlyingType();
  3535. else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
  3536. // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
  3537. // Try to get type from enum declaration, default to int.
  3538. OldTy = ED->getIntegerType();
  3539. if (OldTy.isNull())
  3540. OldTy = Context.IntTy;
  3541. } else
  3542. OldTy = cast<ValueDecl>(D)->getType();
  3543. if (OldTy->isDependentType()) {
  3544. D->addAttr(::new (Context)
  3545. ModeAttr(AttrRange, Context, Name, SpellingListIndex));
  3546. return;
  3547. }
  3548. // Base type can also be a vector type (see PR17453).
  3549. // Distinguish between base type and base element type.
  3550. QualType OldElemTy = OldTy;
  3551. if (const auto *VT = OldTy->getAs<VectorType>())
  3552. OldElemTy = VT->getElementType();
  3553. // GCC allows 'mode' attribute on enumeration types (even incomplete), except
  3554. // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
  3555. // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
  3556. if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
  3557. VectorSize.getBoolValue()) {
  3558. Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
  3559. return;
  3560. }
  3561. bool IntegralOrAnyEnumType =
  3562. OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
  3563. if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
  3564. !IntegralOrAnyEnumType)
  3565. Diag(AttrLoc, diag::err_mode_not_primitive);
  3566. else if (IntegerMode) {
  3567. if (!IntegralOrAnyEnumType)
  3568. Diag(AttrLoc, diag::err_mode_wrong_type);
  3569. } else if (ComplexMode) {
  3570. if (!OldElemTy->isComplexType())
  3571. Diag(AttrLoc, diag::err_mode_wrong_type);
  3572. } else {
  3573. if (!OldElemTy->isFloatingType())
  3574. Diag(AttrLoc, diag::err_mode_wrong_type);
  3575. }
  3576. QualType NewElemTy;
  3577. if (IntegerMode)
  3578. NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
  3579. OldElemTy->isSignedIntegerType());
  3580. else
  3581. NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
  3582. if (NewElemTy.isNull()) {
  3583. Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
  3584. return;
  3585. }
  3586. if (ComplexMode) {
  3587. NewElemTy = Context.getComplexType(NewElemTy);
  3588. }
  3589. QualType NewTy = NewElemTy;
  3590. if (VectorSize.getBoolValue()) {
  3591. NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
  3592. VectorType::GenericVector);
  3593. } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
  3594. // Complex machine mode does not support base vector types.
  3595. if (ComplexMode) {
  3596. Diag(AttrLoc, diag::err_complex_mode_vector_type);
  3597. return;
  3598. }
  3599. unsigned NumElements = Context.getTypeSize(OldElemTy) *
  3600. OldVT->getNumElements() /
  3601. Context.getTypeSize(NewElemTy);
  3602. NewTy =
  3603. Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
  3604. }
  3605. if (NewTy.isNull()) {
  3606. Diag(AttrLoc, diag::err_mode_wrong_type);
  3607. return;
  3608. }
  3609. // Install the new type.
  3610. if (auto *TD = dyn_cast<TypedefNameDecl>(D))
  3611. TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
  3612. else if (auto *ED = dyn_cast<EnumDecl>(D))
  3613. ED->setIntegerType(NewTy);
  3614. else
  3615. cast<ValueDecl>(D)->setType(NewTy);
  3616. D->addAttr(::new (Context)
  3617. ModeAttr(AttrRange, Context, Name, SpellingListIndex));
  3618. }
  3619. static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3620. D->addAttr(::new (S.Context)
  3621. NoDebugAttr(AL.getRange(), S.Context,
  3622. AL.getAttributeSpellingListIndex()));
  3623. }
  3624. AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
  3625. IdentifierInfo *Ident,
  3626. unsigned AttrSpellingListIndex) {
  3627. if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
  3628. Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
  3629. Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
  3630. return nullptr;
  3631. }
  3632. if (D->hasAttr<AlwaysInlineAttr>())
  3633. return nullptr;
  3634. return ::new (Context) AlwaysInlineAttr(Range, Context,
  3635. AttrSpellingListIndex);
  3636. }
  3637. CommonAttr *Sema::mergeCommonAttr(Decl *D, const ParsedAttr &AL) {
  3638. if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, AL))
  3639. return nullptr;
  3640. return ::new (Context)
  3641. CommonAttr(AL.getRange(), Context, AL.getAttributeSpellingListIndex());
  3642. }
  3643. CommonAttr *Sema::mergeCommonAttr(Decl *D, const CommonAttr &AL) {
  3644. if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, AL))
  3645. return nullptr;
  3646. return ::new (Context)
  3647. CommonAttr(AL.getRange(), Context, AL.getSpellingListIndex());
  3648. }
  3649. InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
  3650. const ParsedAttr &AL) {
  3651. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  3652. // Attribute applies to Var but not any subclass of it (like ParmVar,
  3653. // ImplicitParm or VarTemplateSpecialization).
  3654. if (VD->getKind() != Decl::Var) {
  3655. Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
  3656. << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
  3657. : ExpectedVariableOrFunction);
  3658. return nullptr;
  3659. }
  3660. // Attribute does not apply to non-static local variables.
  3661. if (VD->hasLocalStorage()) {
  3662. Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
  3663. return nullptr;
  3664. }
  3665. }
  3666. if (checkAttrMutualExclusion<CommonAttr>(*this, D, AL))
  3667. return nullptr;
  3668. return ::new (Context) InternalLinkageAttr(
  3669. AL.getRange(), Context, AL.getAttributeSpellingListIndex());
  3670. }
  3671. InternalLinkageAttr *
  3672. Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
  3673. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  3674. // Attribute applies to Var but not any subclass of it (like ParmVar,
  3675. // ImplicitParm or VarTemplateSpecialization).
  3676. if (VD->getKind() != Decl::Var) {
  3677. Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
  3678. << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
  3679. : ExpectedVariableOrFunction);
  3680. return nullptr;
  3681. }
  3682. // Attribute does not apply to non-static local variables.
  3683. if (VD->hasLocalStorage()) {
  3684. Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
  3685. return nullptr;
  3686. }
  3687. }
  3688. if (checkAttrMutualExclusion<CommonAttr>(*this, D, AL))
  3689. return nullptr;
  3690. return ::new (Context)
  3691. InternalLinkageAttr(AL.getRange(), Context, AL.getSpellingListIndex());
  3692. }
  3693. MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
  3694. unsigned AttrSpellingListIndex) {
  3695. if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
  3696. Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
  3697. Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
  3698. return nullptr;
  3699. }
  3700. if (D->hasAttr<MinSizeAttr>())
  3701. return nullptr;
  3702. return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
  3703. }
  3704. NoSpeculativeLoadHardeningAttr *Sema::mergeNoSpeculativeLoadHardeningAttr(
  3705. Decl *D, const NoSpeculativeLoadHardeningAttr &AL) {
  3706. if (checkAttrMutualExclusion<SpeculativeLoadHardeningAttr>(*this, D, AL))
  3707. return nullptr;
  3708. return ::new (Context) NoSpeculativeLoadHardeningAttr(
  3709. AL.getRange(), Context, AL.getSpellingListIndex());
  3710. }
  3711. OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
  3712. unsigned AttrSpellingListIndex) {
  3713. if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
  3714. Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
  3715. Diag(Range.getBegin(), diag::note_conflicting_attribute);
  3716. D->dropAttr<AlwaysInlineAttr>();
  3717. }
  3718. if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
  3719. Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
  3720. Diag(Range.getBegin(), diag::note_conflicting_attribute);
  3721. D->dropAttr<MinSizeAttr>();
  3722. }
  3723. if (D->hasAttr<OptimizeNoneAttr>())
  3724. return nullptr;
  3725. return ::new (Context) OptimizeNoneAttr(Range, Context,
  3726. AttrSpellingListIndex);
  3727. }
  3728. SpeculativeLoadHardeningAttr *Sema::mergeSpeculativeLoadHardeningAttr(
  3729. Decl *D, const SpeculativeLoadHardeningAttr &AL) {
  3730. if (checkAttrMutualExclusion<NoSpeculativeLoadHardeningAttr>(*this, D, AL))
  3731. return nullptr;
  3732. return ::new (Context) SpeculativeLoadHardeningAttr(
  3733. AL.getRange(), Context, AL.getSpellingListIndex());
  3734. }
  3735. static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3736. if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, AL))
  3737. return;
  3738. if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
  3739. D, AL.getRange(), AL.getName(),
  3740. AL.getAttributeSpellingListIndex()))
  3741. D->addAttr(Inline);
  3742. }
  3743. static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3744. if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
  3745. D, AL.getRange(), AL.getAttributeSpellingListIndex()))
  3746. D->addAttr(MinSize);
  3747. }
  3748. static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3749. if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
  3750. D, AL.getRange(), AL.getAttributeSpellingListIndex()))
  3751. D->addAttr(Optnone);
  3752. }
  3753. static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3754. if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, AL))
  3755. return;
  3756. const auto *VD = cast<VarDecl>(D);
  3757. if (!VD->hasGlobalStorage()) {
  3758. S.Diag(AL.getLoc(), diag::err_cuda_nonglobal_constant);
  3759. return;
  3760. }
  3761. D->addAttr(::new (S.Context) CUDAConstantAttr(
  3762. AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
  3763. }
  3764. static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3765. if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, AL))
  3766. return;
  3767. const auto *VD = cast<VarDecl>(D);
  3768. // extern __shared__ is only allowed on arrays with no length (e.g.
  3769. // "int x[]").
  3770. if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
  3771. !isa<IncompleteArrayType>(VD->getType())) {
  3772. S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
  3773. return;
  3774. }
  3775. if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
  3776. S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
  3777. << S.CurrentCUDATarget())
  3778. return;
  3779. D->addAttr(::new (S.Context) CUDASharedAttr(
  3780. AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
  3781. }
  3782. static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3783. if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, AL) ||
  3784. checkAttrMutualExclusion<CUDAHostAttr>(S, D, AL)) {
  3785. return;
  3786. }
  3787. const auto *FD = cast<FunctionDecl>(D);
  3788. if (!FD->getReturnType()->isVoidType()) {
  3789. SourceRange RTRange = FD->getReturnTypeSourceRange();
  3790. S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
  3791. << FD->getType()
  3792. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  3793. : FixItHint());
  3794. return;
  3795. }
  3796. if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
  3797. if (Method->isInstance()) {
  3798. S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
  3799. << Method;
  3800. return;
  3801. }
  3802. S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
  3803. }
  3804. // Only warn for "inline" when compiling for host, to cut down on noise.
  3805. if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
  3806. S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
  3807. D->addAttr(::new (S.Context)
  3808. CUDAGlobalAttr(AL.getRange(), S.Context,
  3809. AL.getAttributeSpellingListIndex()));
  3810. }
  3811. static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3812. const auto *Fn = cast<FunctionDecl>(D);
  3813. if (!Fn->isInlineSpecified()) {
  3814. S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
  3815. return;
  3816. }
  3817. D->addAttr(::new (S.Context)
  3818. GNUInlineAttr(AL.getRange(), S.Context,
  3819. AL.getAttributeSpellingListIndex()));
  3820. }
  3821. static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3822. if (hasDeclarator(D)) return;
  3823. // Diagnostic is emitted elsewhere: here we store the (valid) AL
  3824. // in the Decl node for syntactic reasoning, e.g., pretty-printing.
  3825. CallingConv CC;
  3826. if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr))
  3827. return;
  3828. if (!isa<ObjCMethodDecl>(D)) {
  3829. S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
  3830. << AL << ExpectedFunctionOrMethod;
  3831. return;
  3832. }
  3833. switch (AL.getKind()) {
  3834. case ParsedAttr::AT_FastCall:
  3835. D->addAttr(::new (S.Context)
  3836. FastCallAttr(AL.getRange(), S.Context,
  3837. AL.getAttributeSpellingListIndex()));
  3838. return;
  3839. case ParsedAttr::AT_StdCall:
  3840. D->addAttr(::new (S.Context)
  3841. StdCallAttr(AL.getRange(), S.Context,
  3842. AL.getAttributeSpellingListIndex()));
  3843. return;
  3844. case ParsedAttr::AT_ThisCall:
  3845. D->addAttr(::new (S.Context)
  3846. ThisCallAttr(AL.getRange(), S.Context,
  3847. AL.getAttributeSpellingListIndex()));
  3848. return;
  3849. case ParsedAttr::AT_CDecl:
  3850. D->addAttr(::new (S.Context)
  3851. CDeclAttr(AL.getRange(), S.Context,
  3852. AL.getAttributeSpellingListIndex()));
  3853. return;
  3854. case ParsedAttr::AT_Pascal:
  3855. D->addAttr(::new (S.Context)
  3856. PascalAttr(AL.getRange(), S.Context,
  3857. AL.getAttributeSpellingListIndex()));
  3858. return;
  3859. case ParsedAttr::AT_SwiftCall:
  3860. D->addAttr(::new (S.Context)
  3861. SwiftCallAttr(AL.getRange(), S.Context,
  3862. AL.getAttributeSpellingListIndex()));
  3863. return;
  3864. case ParsedAttr::AT_VectorCall:
  3865. D->addAttr(::new (S.Context)
  3866. VectorCallAttr(AL.getRange(), S.Context,
  3867. AL.getAttributeSpellingListIndex()));
  3868. return;
  3869. case ParsedAttr::AT_MSABI:
  3870. D->addAttr(::new (S.Context)
  3871. MSABIAttr(AL.getRange(), S.Context,
  3872. AL.getAttributeSpellingListIndex()));
  3873. return;
  3874. case ParsedAttr::AT_SysVABI:
  3875. D->addAttr(::new (S.Context)
  3876. SysVABIAttr(AL.getRange(), S.Context,
  3877. AL.getAttributeSpellingListIndex()));
  3878. return;
  3879. case ParsedAttr::AT_RegCall:
  3880. D->addAttr(::new (S.Context) RegCallAttr(
  3881. AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
  3882. return;
  3883. case ParsedAttr::AT_Pcs: {
  3884. PcsAttr::PCSType PCS;
  3885. switch (CC) {
  3886. case CC_AAPCS:
  3887. PCS = PcsAttr::AAPCS;
  3888. break;
  3889. case CC_AAPCS_VFP:
  3890. PCS = PcsAttr::AAPCS_VFP;
  3891. break;
  3892. default:
  3893. llvm_unreachable("unexpected calling convention in pcs attribute");
  3894. }
  3895. D->addAttr(::new (S.Context)
  3896. PcsAttr(AL.getRange(), S.Context, PCS,
  3897. AL.getAttributeSpellingListIndex()));
  3898. return;
  3899. }
  3900. case ParsedAttr::AT_AArch64VectorPcs:
  3901. D->addAttr(::new(S.Context)
  3902. AArch64VectorPcsAttr(AL.getRange(), S.Context,
  3903. AL.getAttributeSpellingListIndex()));
  3904. return;
  3905. case ParsedAttr::AT_IntelOclBicc:
  3906. D->addAttr(::new (S.Context)
  3907. IntelOclBiccAttr(AL.getRange(), S.Context,
  3908. AL.getAttributeSpellingListIndex()));
  3909. return;
  3910. case ParsedAttr::AT_PreserveMost:
  3911. D->addAttr(::new (S.Context) PreserveMostAttr(
  3912. AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
  3913. return;
  3914. case ParsedAttr::AT_PreserveAll:
  3915. D->addAttr(::new (S.Context) PreserveAllAttr(
  3916. AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
  3917. return;
  3918. default:
  3919. llvm_unreachable("unexpected attribute kind");
  3920. }
  3921. }
  3922. static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  3923. if (!checkAttributeAtLeastNumArgs(S, AL, 1))
  3924. return;
  3925. std::vector<StringRef> DiagnosticIdentifiers;
  3926. for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
  3927. StringRef RuleName;
  3928. if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr))
  3929. return;
  3930. // FIXME: Warn if the rule name is unknown. This is tricky because only
  3931. // clang-tidy knows about available rules.
  3932. DiagnosticIdentifiers.push_back(RuleName);
  3933. }
  3934. D->addAttr(::new (S.Context) SuppressAttr(
  3935. AL.getRange(), S.Context, DiagnosticIdentifiers.data(),
  3936. DiagnosticIdentifiers.size(), AL.getAttributeSpellingListIndex()));
  3937. }
  3938. bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC,
  3939. const FunctionDecl *FD) {
  3940. if (Attrs.isInvalid())
  3941. return true;
  3942. if (Attrs.hasProcessingCache()) {
  3943. CC = (CallingConv) Attrs.getProcessingCache();
  3944. return false;
  3945. }
  3946. unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
  3947. if (!checkAttributeNumArgs(*this, Attrs, ReqArgs)) {
  3948. Attrs.setInvalid();
  3949. return true;
  3950. }
  3951. // TODO: diagnose uses of these conventions on the wrong target.
  3952. switch (Attrs.getKind()) {
  3953. case ParsedAttr::AT_CDecl:
  3954. CC = CC_C;
  3955. break;
  3956. case ParsedAttr::AT_FastCall:
  3957. CC = CC_X86FastCall;
  3958. break;
  3959. case ParsedAttr::AT_StdCall:
  3960. CC = CC_X86StdCall;
  3961. break;
  3962. case ParsedAttr::AT_ThisCall:
  3963. CC = CC_X86ThisCall;
  3964. break;
  3965. case ParsedAttr::AT_Pascal:
  3966. CC = CC_X86Pascal;
  3967. break;
  3968. case ParsedAttr::AT_SwiftCall:
  3969. CC = CC_Swift;
  3970. break;
  3971. case ParsedAttr::AT_VectorCall:
  3972. CC = CC_X86VectorCall;
  3973. break;
  3974. case ParsedAttr::AT_AArch64VectorPcs:
  3975. CC = CC_AArch64VectorCall;
  3976. break;
  3977. case ParsedAttr::AT_RegCall:
  3978. CC = CC_X86RegCall;
  3979. break;
  3980. case ParsedAttr::AT_MSABI:
  3981. CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
  3982. CC_Win64;
  3983. break;
  3984. case ParsedAttr::AT_SysVABI:
  3985. CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
  3986. CC_C;
  3987. break;
  3988. case ParsedAttr::AT_Pcs: {
  3989. StringRef StrRef;
  3990. if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
  3991. Attrs.setInvalid();
  3992. return true;
  3993. }
  3994. if (StrRef == "aapcs") {
  3995. CC = CC_AAPCS;
  3996. break;
  3997. } else if (StrRef == "aapcs-vfp") {
  3998. CC = CC_AAPCS_VFP;
  3999. break;
  4000. }
  4001. Attrs.setInvalid();
  4002. Diag(Attrs.getLoc(), diag::err_invalid_pcs);
  4003. return true;
  4004. }
  4005. case ParsedAttr::AT_IntelOclBicc:
  4006. CC = CC_IntelOclBicc;
  4007. break;
  4008. case ParsedAttr::AT_PreserveMost:
  4009. CC = CC_PreserveMost;
  4010. break;
  4011. case ParsedAttr::AT_PreserveAll:
  4012. CC = CC_PreserveAll;
  4013. break;
  4014. default: llvm_unreachable("unexpected attribute kind");
  4015. }
  4016. TargetInfo::CallingConvCheckResult A = TargetInfo::CCCR_OK;
  4017. const TargetInfo &TI = Context.getTargetInfo();
  4018. // CUDA functions may have host and/or device attributes which indicate
  4019. // their targeted execution environment, therefore the calling convention
  4020. // of functions in CUDA should be checked against the target deduced based
  4021. // on their host/device attributes.
  4022. if (LangOpts.CUDA) {
  4023. auto *Aux = Context.getAuxTargetInfo();
  4024. auto CudaTarget = IdentifyCUDATarget(FD);
  4025. bool CheckHost = false, CheckDevice = false;
  4026. switch (CudaTarget) {
  4027. case CFT_HostDevice:
  4028. CheckHost = true;
  4029. CheckDevice = true;
  4030. break;
  4031. case CFT_Host:
  4032. CheckHost = true;
  4033. break;
  4034. case CFT_Device:
  4035. case CFT_Global:
  4036. CheckDevice = true;
  4037. break;
  4038. case CFT_InvalidTarget:
  4039. llvm_unreachable("unexpected cuda target");
  4040. }
  4041. auto *HostTI = LangOpts.CUDAIsDevice ? Aux : &TI;
  4042. auto *DeviceTI = LangOpts.CUDAIsDevice ? &TI : Aux;
  4043. if (CheckHost && HostTI)
  4044. A = HostTI->checkCallingConvention(CC);
  4045. if (A == TargetInfo::CCCR_OK && CheckDevice && DeviceTI)
  4046. A = DeviceTI->checkCallingConvention(CC);
  4047. } else {
  4048. A = TI.checkCallingConvention(CC);
  4049. }
  4050. if (A != TargetInfo::CCCR_OK) {
  4051. if (A == TargetInfo::CCCR_Warning)
  4052. Diag(Attrs.getLoc(), diag::warn_cconv_ignored) << Attrs;
  4053. // This convention is not valid for the target. Use the default function or
  4054. // method calling convention.
  4055. bool IsCXXMethod = false, IsVariadic = false;
  4056. if (FD) {
  4057. IsCXXMethod = FD->isCXXInstanceMember();
  4058. IsVariadic = FD->isVariadic();
  4059. }
  4060. CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
  4061. }
  4062. Attrs.setProcessingCache((unsigned) CC);
  4063. return false;
  4064. }
  4065. /// Pointer-like types in the default address space.
  4066. static bool isValidSwiftContextType(QualType Ty) {
  4067. if (!Ty->hasPointerRepresentation())
  4068. return Ty->isDependentType();
  4069. return Ty->getPointeeType().getAddressSpace() == LangAS::Default;
  4070. }
  4071. /// Pointers and references in the default address space.
  4072. static bool isValidSwiftIndirectResultType(QualType Ty) {
  4073. if (const auto *PtrType = Ty->getAs<PointerType>()) {
  4074. Ty = PtrType->getPointeeType();
  4075. } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
  4076. Ty = RefType->getPointeeType();
  4077. } else {
  4078. return Ty->isDependentType();
  4079. }
  4080. return Ty.getAddressSpace() == LangAS::Default;
  4081. }
  4082. /// Pointers and references to pointers in the default address space.
  4083. static bool isValidSwiftErrorResultType(QualType Ty) {
  4084. if (const auto *PtrType = Ty->getAs<PointerType>()) {
  4085. Ty = PtrType->getPointeeType();
  4086. } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
  4087. Ty = RefType->getPointeeType();
  4088. } else {
  4089. return Ty->isDependentType();
  4090. }
  4091. if (!Ty.getQualifiers().empty())
  4092. return false;
  4093. return isValidSwiftContextType(Ty);
  4094. }
  4095. static void handleParameterABIAttr(Sema &S, Decl *D, const ParsedAttr &Attrs,
  4096. ParameterABI Abi) {
  4097. S.AddParameterABIAttr(Attrs.getRange(), D, Abi,
  4098. Attrs.getAttributeSpellingListIndex());
  4099. }
  4100. void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi,
  4101. unsigned spellingIndex) {
  4102. QualType type = cast<ParmVarDecl>(D)->getType();
  4103. if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
  4104. if (existingAttr->getABI() != abi) {
  4105. Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
  4106. << getParameterABISpelling(abi) << existingAttr;
  4107. Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
  4108. return;
  4109. }
  4110. }
  4111. switch (abi) {
  4112. case ParameterABI::Ordinary:
  4113. llvm_unreachable("explicit attribute for ordinary parameter ABI?");
  4114. case ParameterABI::SwiftContext:
  4115. if (!isValidSwiftContextType(type)) {
  4116. Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
  4117. << getParameterABISpelling(abi)
  4118. << /*pointer to pointer */ 0 << type;
  4119. }
  4120. D->addAttr(::new (Context)
  4121. SwiftContextAttr(range, Context, spellingIndex));
  4122. return;
  4123. case ParameterABI::SwiftErrorResult:
  4124. if (!isValidSwiftErrorResultType(type)) {
  4125. Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
  4126. << getParameterABISpelling(abi)
  4127. << /*pointer to pointer */ 1 << type;
  4128. }
  4129. D->addAttr(::new (Context)
  4130. SwiftErrorResultAttr(range, Context, spellingIndex));
  4131. return;
  4132. case ParameterABI::SwiftIndirectResult:
  4133. if (!isValidSwiftIndirectResultType(type)) {
  4134. Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
  4135. << getParameterABISpelling(abi)
  4136. << /*pointer*/ 0 << type;
  4137. }
  4138. D->addAttr(::new (Context)
  4139. SwiftIndirectResultAttr(range, Context, spellingIndex));
  4140. return;
  4141. }
  4142. llvm_unreachable("bad parameter ABI attribute");
  4143. }
  4144. /// Checks a regparm attribute, returning true if it is ill-formed and
  4145. /// otherwise setting numParams to the appropriate value.
  4146. bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) {
  4147. if (AL.isInvalid())
  4148. return true;
  4149. if (!checkAttributeNumArgs(*this, AL, 1)) {
  4150. AL.setInvalid();
  4151. return true;
  4152. }
  4153. uint32_t NP;
  4154. Expr *NumParamsExpr = AL.getArgAsExpr(0);
  4155. if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) {
  4156. AL.setInvalid();
  4157. return true;
  4158. }
  4159. if (Context.getTargetInfo().getRegParmMax() == 0) {
  4160. Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform)
  4161. << NumParamsExpr->getSourceRange();
  4162. AL.setInvalid();
  4163. return true;
  4164. }
  4165. numParams = NP;
  4166. if (numParams > Context.getTargetInfo().getRegParmMax()) {
  4167. Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number)
  4168. << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
  4169. AL.setInvalid();
  4170. return true;
  4171. }
  4172. return false;
  4173. }
  4174. // Checks whether an argument of launch_bounds attribute is
  4175. // acceptable, performs implicit conversion to Rvalue, and returns
  4176. // non-nullptr Expr result on success. Otherwise, it returns nullptr
  4177. // and may output an error.
  4178. static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
  4179. const CUDALaunchBoundsAttr &AL,
  4180. const unsigned Idx) {
  4181. if (S.DiagnoseUnexpandedParameterPack(E))
  4182. return nullptr;
  4183. // Accept template arguments for now as they depend on something else.
  4184. // We'll get to check them when they eventually get instantiated.
  4185. if (E->isValueDependent())
  4186. return E;
  4187. llvm::APSInt I(64);
  4188. if (!E->isIntegerConstantExpr(I, S.Context)) {
  4189. S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
  4190. << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
  4191. return nullptr;
  4192. }
  4193. // Make sure we can fit it in 32 bits.
  4194. if (!I.isIntN(32)) {
  4195. S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
  4196. << 32 << /* Unsigned */ 1;
  4197. return nullptr;
  4198. }
  4199. if (I < 0)
  4200. S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
  4201. << &AL << Idx << E->getSourceRange();
  4202. // We may need to perform implicit conversion of the argument.
  4203. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4204. S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
  4205. ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
  4206. assert(!ValArg.isInvalid() &&
  4207. "Unexpected PerformCopyInitialization() failure.");
  4208. return ValArg.getAs<Expr>();
  4209. }
  4210. void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
  4211. Expr *MinBlocks, unsigned SpellingListIndex) {
  4212. CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
  4213. SpellingListIndex);
  4214. MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
  4215. if (MaxThreads == nullptr)
  4216. return;
  4217. if (MinBlocks) {
  4218. MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
  4219. if (MinBlocks == nullptr)
  4220. return;
  4221. }
  4222. D->addAttr(::new (Context) CUDALaunchBoundsAttr(
  4223. AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
  4224. }
  4225. static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4226. if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
  4227. !checkAttributeAtMostNumArgs(S, AL, 2))
  4228. return;
  4229. S.AddLaunchBoundsAttr(AL.getRange(), D, AL.getArgAsExpr(0),
  4230. AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr,
  4231. AL.getAttributeSpellingListIndex());
  4232. }
  4233. static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
  4234. const ParsedAttr &AL) {
  4235. if (!AL.isArgIdent(0)) {
  4236. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  4237. << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier;
  4238. return;
  4239. }
  4240. ParamIdx ArgumentIdx;
  4241. if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1),
  4242. ArgumentIdx))
  4243. return;
  4244. ParamIdx TypeTagIdx;
  4245. if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2),
  4246. TypeTagIdx))
  4247. return;
  4248. bool IsPointer = AL.getName()->getName() == "pointer_with_type_tag";
  4249. if (IsPointer) {
  4250. // Ensure that buffer has a pointer type.
  4251. unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex();
  4252. if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) ||
  4253. !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType())
  4254. S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0;
  4255. }
  4256. D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(
  4257. AL.getRange(), S.Context, AL.getArgAsIdent(0)->Ident, ArgumentIdx,
  4258. TypeTagIdx, IsPointer, AL.getAttributeSpellingListIndex()));
  4259. }
  4260. static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
  4261. const ParsedAttr &AL) {
  4262. if (!AL.isArgIdent(0)) {
  4263. S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
  4264. << AL << 1 << AANT_ArgumentIdentifier;
  4265. return;
  4266. }
  4267. if (!checkAttributeNumArgs(S, AL, 1))
  4268. return;
  4269. if (!isa<VarDecl>(D)) {
  4270. S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type)
  4271. << AL << ExpectedVariable;
  4272. return;
  4273. }
  4274. IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident;
  4275. TypeSourceInfo *MatchingCTypeLoc = nullptr;
  4276. S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc);
  4277. assert(MatchingCTypeLoc && "no type source info for attribute argument");
  4278. D->addAttr(::new (S.Context)
  4279. TypeTagForDatatypeAttr(AL.getRange(), S.Context, PointerKind,
  4280. MatchingCTypeLoc,
  4281. AL.getLayoutCompatible(),
  4282. AL.getMustBeNull(),
  4283. AL.getAttributeSpellingListIndex()));
  4284. }
  4285. static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4286. ParamIdx ArgCount;
  4287. if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0),
  4288. ArgCount,
  4289. true /* CanIndexImplicitThis */))
  4290. return;
  4291. // ArgCount isn't a parameter index [0;n), it's a count [1;n]
  4292. D->addAttr(::new (S.Context) XRayLogArgsAttr(
  4293. AL.getRange(), S.Context, ArgCount.getSourceIndex(),
  4294. AL.getAttributeSpellingListIndex()));
  4295. }
  4296. //===----------------------------------------------------------------------===//
  4297. // Checker-specific attribute handlers.
  4298. //===----------------------------------------------------------------------===//
  4299. static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) {
  4300. return QT->isDependentType() || QT->isObjCRetainableType();
  4301. }
  4302. static bool isValidSubjectOfNSAttribute(QualType QT) {
  4303. return QT->isDependentType() || QT->isObjCObjectPointerType() ||
  4304. QT->isObjCNSObjectType();
  4305. }
  4306. static bool isValidSubjectOfCFAttribute(QualType QT) {
  4307. return QT->isDependentType() || QT->isPointerType() ||
  4308. isValidSubjectOfNSAttribute(QT);
  4309. }
  4310. static bool isValidSubjectOfOSAttribute(QualType QT) {
  4311. if (QT->isDependentType())
  4312. return true;
  4313. QualType PT = QT->getPointeeType();
  4314. return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr;
  4315. }
  4316. void Sema::AddXConsumedAttr(Decl *D, SourceRange SR, unsigned SpellingIndex,
  4317. RetainOwnershipKind K,
  4318. bool IsTemplateInstantiation) {
  4319. ValueDecl *VD = cast<ValueDecl>(D);
  4320. switch (K) {
  4321. case RetainOwnershipKind::OS:
  4322. handleSimpleAttributeOrDiagnose<OSConsumedAttr>(
  4323. *this, VD, SR, SpellingIndex, isValidSubjectOfOSAttribute(VD->getType()),
  4324. diag::warn_ns_attribute_wrong_parameter_type,
  4325. /*ExtraArgs=*/SR, "os_consumed", /*pointers*/ 1);
  4326. return;
  4327. case RetainOwnershipKind::NS:
  4328. handleSimpleAttributeOrDiagnose<NSConsumedAttr>(
  4329. *this, VD, SR, SpellingIndex, isValidSubjectOfNSAttribute(VD->getType()),
  4330. // These attributes are normally just advisory, but in ARC, ns_consumed
  4331. // is significant. Allow non-dependent code to contain inappropriate
  4332. // attributes even in ARC, but require template instantiations to be
  4333. // set up correctly.
  4334. ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount)
  4335. ? diag::err_ns_attribute_wrong_parameter_type
  4336. : diag::warn_ns_attribute_wrong_parameter_type),
  4337. /*ExtraArgs=*/SR, "ns_consumed", /*objc pointers*/ 0);
  4338. return;
  4339. case RetainOwnershipKind::CF:
  4340. handleSimpleAttributeOrDiagnose<CFConsumedAttr>(
  4341. *this, VD, SR, SpellingIndex,
  4342. isValidSubjectOfCFAttribute(VD->getType()),
  4343. diag::warn_ns_attribute_wrong_parameter_type,
  4344. /*ExtraArgs=*/SR, "cf_consumed", /*pointers*/1);
  4345. return;
  4346. }
  4347. }
  4348. static Sema::RetainOwnershipKind
  4349. parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) {
  4350. switch (AL.getKind()) {
  4351. case ParsedAttr::AT_CFConsumed:
  4352. case ParsedAttr::AT_CFReturnsRetained:
  4353. case ParsedAttr::AT_CFReturnsNotRetained:
  4354. return Sema::RetainOwnershipKind::CF;
  4355. case ParsedAttr::AT_OSConsumesThis:
  4356. case ParsedAttr::AT_OSConsumed:
  4357. case ParsedAttr::AT_OSReturnsRetained:
  4358. case ParsedAttr::AT_OSReturnsNotRetained:
  4359. case ParsedAttr::AT_OSReturnsRetainedOnZero:
  4360. case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
  4361. return Sema::RetainOwnershipKind::OS;
  4362. case ParsedAttr::AT_NSConsumesSelf:
  4363. case ParsedAttr::AT_NSConsumed:
  4364. case ParsedAttr::AT_NSReturnsRetained:
  4365. case ParsedAttr::AT_NSReturnsNotRetained:
  4366. case ParsedAttr::AT_NSReturnsAutoreleased:
  4367. return Sema::RetainOwnershipKind::NS;
  4368. default:
  4369. llvm_unreachable("Wrong argument supplied");
  4370. }
  4371. }
  4372. bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc, QualType QT) {
  4373. if (isValidSubjectOfNSReturnsRetainedAttribute(QT))
  4374. return false;
  4375. Diag(Loc, diag::warn_ns_attribute_wrong_return_type)
  4376. << "'ns_returns_retained'" << 0 << 0;
  4377. return true;
  4378. }
  4379. /// \return whether the parameter is a pointer to OSObject pointer.
  4380. static bool isValidOSObjectOutParameter(const Decl *D) {
  4381. const auto *PVD = dyn_cast<ParmVarDecl>(D);
  4382. if (!PVD)
  4383. return false;
  4384. QualType QT = PVD->getType();
  4385. QualType PT = QT->getPointeeType();
  4386. return !PT.isNull() && isValidSubjectOfOSAttribute(PT);
  4387. }
  4388. static void handleXReturnsXRetainedAttr(Sema &S, Decl *D,
  4389. const ParsedAttr &AL) {
  4390. QualType ReturnType;
  4391. Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL);
  4392. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
  4393. ReturnType = MD->getReturnType();
  4394. } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
  4395. (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) {
  4396. return; // ignore: was handled as a type attribute
  4397. } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
  4398. ReturnType = PD->getType();
  4399. } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  4400. ReturnType = FD->getReturnType();
  4401. } else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) {
  4402. // Attributes on parameters are used for out-parameters,
  4403. // passed as pointers-to-pointers.
  4404. unsigned DiagID = K == Sema::RetainOwnershipKind::CF
  4405. ? /*pointer-to-CF-pointer*/2
  4406. : /*pointer-to-OSObject-pointer*/3;
  4407. ReturnType = Param->getType()->getPointeeType();
  4408. if (ReturnType.isNull()) {
  4409. S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
  4410. << AL << DiagID << AL.getRange();
  4411. return;
  4412. }
  4413. } else if (AL.isUsedAsTypeAttr()) {
  4414. return;
  4415. } else {
  4416. AttributeDeclKind ExpectedDeclKind;
  4417. switch (AL.getKind()) {
  4418. default: llvm_unreachable("invalid ownership attribute");
  4419. case ParsedAttr::AT_NSReturnsRetained:
  4420. case ParsedAttr::AT_NSReturnsAutoreleased:
  4421. case ParsedAttr::AT_NSReturnsNotRetained:
  4422. ExpectedDeclKind = ExpectedFunctionOrMethod;
  4423. break;
  4424. case ParsedAttr::AT_OSReturnsRetained:
  4425. case ParsedAttr::AT_OSReturnsNotRetained:
  4426. case ParsedAttr::AT_CFReturnsRetained:
  4427. case ParsedAttr::AT_CFReturnsNotRetained:
  4428. ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
  4429. break;
  4430. }
  4431. S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type)
  4432. << AL.getRange() << AL << ExpectedDeclKind;
  4433. return;
  4434. }
  4435. bool TypeOK;
  4436. bool Cf;
  4437. unsigned ParmDiagID = 2; // Pointer-to-CF-pointer
  4438. switch (AL.getKind()) {
  4439. default: llvm_unreachable("invalid ownership attribute");
  4440. case ParsedAttr::AT_NSReturnsRetained:
  4441. TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType);
  4442. Cf = false;
  4443. break;
  4444. case ParsedAttr::AT_NSReturnsAutoreleased:
  4445. case ParsedAttr::AT_NSReturnsNotRetained:
  4446. TypeOK = isValidSubjectOfNSAttribute(ReturnType);
  4447. Cf = false;
  4448. break;
  4449. case ParsedAttr::AT_CFReturnsRetained:
  4450. case ParsedAttr::AT_CFReturnsNotRetained:
  4451. TypeOK = isValidSubjectOfCFAttribute(ReturnType);
  4452. Cf = true;
  4453. break;
  4454. case ParsedAttr::AT_OSReturnsRetained:
  4455. case ParsedAttr::AT_OSReturnsNotRetained:
  4456. TypeOK = isValidSubjectOfOSAttribute(ReturnType);
  4457. Cf = true;
  4458. ParmDiagID = 3; // Pointer-to-OSObject-pointer
  4459. break;
  4460. }
  4461. if (!TypeOK) {
  4462. if (AL.isUsedAsTypeAttr())
  4463. return;
  4464. if (isa<ParmVarDecl>(D)) {
  4465. S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
  4466. << AL << ParmDiagID << AL.getRange();
  4467. } else {
  4468. // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
  4469. enum : unsigned {
  4470. Function,
  4471. Method,
  4472. Property
  4473. } SubjectKind = Function;
  4474. if (isa<ObjCMethodDecl>(D))
  4475. SubjectKind = Method;
  4476. else if (isa<ObjCPropertyDecl>(D))
  4477. SubjectKind = Property;
  4478. S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
  4479. << AL << SubjectKind << Cf << AL.getRange();
  4480. }
  4481. return;
  4482. }
  4483. switch (AL.getKind()) {
  4484. default:
  4485. llvm_unreachable("invalid ownership attribute");
  4486. case ParsedAttr::AT_NSReturnsAutoreleased:
  4487. handleSimpleAttribute<NSReturnsAutoreleasedAttr>(S, D, AL);
  4488. return;
  4489. case ParsedAttr::AT_CFReturnsNotRetained:
  4490. handleSimpleAttribute<CFReturnsNotRetainedAttr>(S, D, AL);
  4491. return;
  4492. case ParsedAttr::AT_NSReturnsNotRetained:
  4493. handleSimpleAttribute<NSReturnsNotRetainedAttr>(S, D, AL);
  4494. return;
  4495. case ParsedAttr::AT_CFReturnsRetained:
  4496. handleSimpleAttribute<CFReturnsRetainedAttr>(S, D, AL);
  4497. return;
  4498. case ParsedAttr::AT_NSReturnsRetained:
  4499. handleSimpleAttribute<NSReturnsRetainedAttr>(S, D, AL);
  4500. return;
  4501. case ParsedAttr::AT_OSReturnsRetained:
  4502. handleSimpleAttribute<OSReturnsRetainedAttr>(S, D, AL);
  4503. return;
  4504. case ParsedAttr::AT_OSReturnsNotRetained:
  4505. handleSimpleAttribute<OSReturnsNotRetainedAttr>(S, D, AL);
  4506. return;
  4507. };
  4508. }
  4509. static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
  4510. const ParsedAttr &Attrs) {
  4511. const int EP_ObjCMethod = 1;
  4512. const int EP_ObjCProperty = 2;
  4513. SourceLocation loc = Attrs.getLoc();
  4514. QualType resultType;
  4515. if (isa<ObjCMethodDecl>(D))
  4516. resultType = cast<ObjCMethodDecl>(D)->getReturnType();
  4517. else
  4518. resultType = cast<ObjCPropertyDecl>(D)->getType();
  4519. if (!resultType->isReferenceType() &&
  4520. (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
  4521. S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
  4522. << SourceRange(loc) << Attrs
  4523. << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
  4524. << /*non-retainable pointer*/ 2;
  4525. // Drop the attribute.
  4526. return;
  4527. }
  4528. D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
  4529. Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
  4530. }
  4531. static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
  4532. const ParsedAttr &Attrs) {
  4533. const auto *Method = cast<ObjCMethodDecl>(D);
  4534. const DeclContext *DC = Method->getDeclContext();
  4535. if (const auto *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
  4536. S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
  4537. << 0;
  4538. S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
  4539. return;
  4540. }
  4541. if (Method->getMethodFamily() == OMF_dealloc) {
  4542. S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
  4543. << 1;
  4544. return;
  4545. }
  4546. D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(
  4547. Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
  4548. }
  4549. static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4550. IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
  4551. if (!Parm) {
  4552. S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
  4553. return;
  4554. }
  4555. // Typedefs only allow objc_bridge(id) and have some additional checking.
  4556. if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  4557. if (!Parm->Ident->isStr("id")) {
  4558. S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL;
  4559. return;
  4560. }
  4561. // Only allow 'cv void *'.
  4562. QualType T = TD->getUnderlyingType();
  4563. if (!T->isVoidPointerType()) {
  4564. S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
  4565. return;
  4566. }
  4567. }
  4568. D->addAttr(::new (S.Context)
  4569. ObjCBridgeAttr(AL.getRange(), S.Context, Parm->Ident,
  4570. AL.getAttributeSpellingListIndex()));
  4571. }
  4572. static void handleObjCBridgeMutableAttr(Sema &S, Decl *D,
  4573. const ParsedAttr &AL) {
  4574. IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
  4575. if (!Parm) {
  4576. S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
  4577. return;
  4578. }
  4579. D->addAttr(::new (S.Context)
  4580. ObjCBridgeMutableAttr(AL.getRange(), S.Context, Parm->Ident,
  4581. AL.getAttributeSpellingListIndex()));
  4582. }
  4583. static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D,
  4584. const ParsedAttr &AL) {
  4585. IdentifierInfo *RelatedClass =
  4586. AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr;
  4587. if (!RelatedClass) {
  4588. S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
  4589. return;
  4590. }
  4591. IdentifierInfo *ClassMethod =
  4592. AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr;
  4593. IdentifierInfo *InstanceMethod =
  4594. AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr;
  4595. D->addAttr(::new (S.Context)
  4596. ObjCBridgeRelatedAttr(AL.getRange(), S.Context, RelatedClass,
  4597. ClassMethod, InstanceMethod,
  4598. AL.getAttributeSpellingListIndex()));
  4599. }
  4600. static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
  4601. const ParsedAttr &AL) {
  4602. DeclContext *Ctx = D->getDeclContext();
  4603. // This attribute can only be applied to methods in interfaces or class
  4604. // extensions.
  4605. if (!isa<ObjCInterfaceDecl>(Ctx) &&
  4606. !(isa<ObjCCategoryDecl>(Ctx) &&
  4607. cast<ObjCCategoryDecl>(Ctx)->IsClassExtension())) {
  4608. S.Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
  4609. return;
  4610. }
  4611. ObjCInterfaceDecl *IFace;
  4612. if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Ctx))
  4613. IFace = CatDecl->getClassInterface();
  4614. else
  4615. IFace = cast<ObjCInterfaceDecl>(Ctx);
  4616. if (!IFace)
  4617. return;
  4618. IFace->setHasDesignatedInitializers();
  4619. D->addAttr(::new (S.Context)
  4620. ObjCDesignatedInitializerAttr(AL.getRange(), S.Context,
  4621. AL.getAttributeSpellingListIndex()));
  4622. }
  4623. static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) {
  4624. StringRef MetaDataName;
  4625. if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName))
  4626. return;
  4627. D->addAttr(::new (S.Context)
  4628. ObjCRuntimeNameAttr(AL.getRange(), S.Context,
  4629. MetaDataName,
  4630. AL.getAttributeSpellingListIndex()));
  4631. }
  4632. // When a user wants to use objc_boxable with a union or struct
  4633. // but they don't have access to the declaration (legacy/third-party code)
  4634. // then they can 'enable' this feature with a typedef:
  4635. // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
  4636. static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) {
  4637. bool notify = false;
  4638. auto *RD = dyn_cast<RecordDecl>(D);
  4639. if (RD && RD->getDefinition()) {
  4640. RD = RD->getDefinition();
  4641. notify = true;
  4642. }
  4643. if (RD) {
  4644. ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
  4645. ObjCBoxableAttr(AL.getRange(), S.Context,
  4646. AL.getAttributeSpellingListIndex());
  4647. RD->addAttr(BoxableAttr);
  4648. if (notify) {
  4649. // we need to notify ASTReader/ASTWriter about
  4650. // modification of existing declaration
  4651. if (ASTMutationListener *L = S.getASTMutationListener())
  4652. L->AddedAttributeToRecord(BoxableAttr, RD);
  4653. }
  4654. }
  4655. }
  4656. static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4657. if (hasDeclarator(D)) return;
  4658. S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type)
  4659. << AL.getRange() << AL << ExpectedVariable;
  4660. }
  4661. static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
  4662. const ParsedAttr &AL) {
  4663. const auto *VD = cast<ValueDecl>(D);
  4664. QualType QT = VD->getType();
  4665. if (!QT->isDependentType() &&
  4666. !QT->isObjCLifetimeType()) {
  4667. S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type)
  4668. << QT;
  4669. return;
  4670. }
  4671. Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime();
  4672. // If we have no lifetime yet, check the lifetime we're presumably
  4673. // going to infer.
  4674. if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType())
  4675. Lifetime = QT->getObjCARCImplicitLifetime();
  4676. switch (Lifetime) {
  4677. case Qualifiers::OCL_None:
  4678. assert(QT->isDependentType() &&
  4679. "didn't infer lifetime for non-dependent type?");
  4680. break;
  4681. case Qualifiers::OCL_Weak: // meaningful
  4682. case Qualifiers::OCL_Strong: // meaningful
  4683. break;
  4684. case Qualifiers::OCL_ExplicitNone:
  4685. case Qualifiers::OCL_Autoreleasing:
  4686. S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
  4687. << (Lifetime == Qualifiers::OCL_Autoreleasing);
  4688. break;
  4689. }
  4690. D->addAttr(::new (S.Context)
  4691. ObjCPreciseLifetimeAttr(AL.getRange(), S.Context,
  4692. AL.getAttributeSpellingListIndex()));
  4693. }
  4694. //===----------------------------------------------------------------------===//
  4695. // Microsoft specific attribute handlers.
  4696. //===----------------------------------------------------------------------===//
  4697. UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range,
  4698. unsigned AttrSpellingListIndex, StringRef Uuid) {
  4699. if (const auto *UA = D->getAttr<UuidAttr>()) {
  4700. if (UA->getGuid().equals_lower(Uuid))
  4701. return nullptr;
  4702. Diag(UA->getLocation(), diag::err_mismatched_uuid);
  4703. Diag(Range.getBegin(), diag::note_previous_uuid);
  4704. D->dropAttr<UuidAttr>();
  4705. }
  4706. return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex);
  4707. }
  4708. static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4709. if (!S.LangOpts.CPlusPlus) {
  4710. S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
  4711. << AL << AttributeLangSupport::C;
  4712. return;
  4713. }
  4714. StringRef StrRef;
  4715. SourceLocation LiteralLoc;
  4716. if (!S.checkStringLiteralArgumentAttr(AL, 0, StrRef, &LiteralLoc))
  4717. return;
  4718. // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
  4719. // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
  4720. if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
  4721. StrRef = StrRef.drop_front().drop_back();
  4722. // Validate GUID length.
  4723. if (StrRef.size() != 36) {
  4724. S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
  4725. return;
  4726. }
  4727. for (unsigned i = 0; i < 36; ++i) {
  4728. if (i == 8 || i == 13 || i == 18 || i == 23) {
  4729. if (StrRef[i] != '-') {
  4730. S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
  4731. return;
  4732. }
  4733. } else if (!isHexDigit(StrRef[i])) {
  4734. S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
  4735. return;
  4736. }
  4737. }
  4738. // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
  4739. // the only thing in the [] list, the [] too), and add an insertion of
  4740. // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas
  4741. // separating attributes nor of the [ and the ] are in the AST.
  4742. // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
  4743. // on cfe-dev.
  4744. if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
  4745. S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated);
  4746. UuidAttr *UA = S.mergeUuidAttr(D, AL.getRange(),
  4747. AL.getAttributeSpellingListIndex(), StrRef);
  4748. if (UA)
  4749. D->addAttr(UA);
  4750. }
  4751. static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4752. if (!S.LangOpts.CPlusPlus) {
  4753. S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
  4754. << AL << AttributeLangSupport::C;
  4755. return;
  4756. }
  4757. MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
  4758. D, AL.getRange(), /*BestCase=*/true,
  4759. AL.getAttributeSpellingListIndex(),
  4760. (MSInheritanceAttr::Spelling)AL.getSemanticSpelling());
  4761. if (IA) {
  4762. D->addAttr(IA);
  4763. S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
  4764. }
  4765. }
  4766. static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4767. const auto *VD = cast<VarDecl>(D);
  4768. if (!S.Context.getTargetInfo().isTLSSupported()) {
  4769. S.Diag(AL.getLoc(), diag::err_thread_unsupported);
  4770. return;
  4771. }
  4772. if (VD->getTSCSpec() != TSCS_unspecified) {
  4773. S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable);
  4774. return;
  4775. }
  4776. if (VD->hasLocalStorage()) {
  4777. S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
  4778. return;
  4779. }
  4780. D->addAttr(::new (S.Context) ThreadAttr(AL.getRange(), S.Context,
  4781. AL.getAttributeSpellingListIndex()));
  4782. }
  4783. static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4784. SmallVector<StringRef, 4> Tags;
  4785. for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
  4786. StringRef Tag;
  4787. if (!S.checkStringLiteralArgumentAttr(AL, I, Tag))
  4788. return;
  4789. Tags.push_back(Tag);
  4790. }
  4791. if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
  4792. if (!NS->isInline()) {
  4793. S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
  4794. return;
  4795. }
  4796. if (NS->isAnonymousNamespace()) {
  4797. S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
  4798. return;
  4799. }
  4800. if (AL.getNumArgs() == 0)
  4801. Tags.push_back(NS->getName());
  4802. } else if (!checkAttributeAtLeastNumArgs(S, AL, 1))
  4803. return;
  4804. // Store tags sorted and without duplicates.
  4805. llvm::sort(Tags);
  4806. Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
  4807. D->addAttr(::new (S.Context)
  4808. AbiTagAttr(AL.getRange(), S.Context, Tags.data(), Tags.size(),
  4809. AL.getAttributeSpellingListIndex()));
  4810. }
  4811. static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4812. // Check the attribute arguments.
  4813. if (AL.getNumArgs() > 1) {
  4814. S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
  4815. return;
  4816. }
  4817. StringRef Str;
  4818. SourceLocation ArgLoc;
  4819. if (AL.getNumArgs() == 0)
  4820. Str = "";
  4821. else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
  4822. return;
  4823. ARMInterruptAttr::InterruptType Kind;
  4824. if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
  4825. S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
  4826. << ArgLoc;
  4827. return;
  4828. }
  4829. unsigned Index = AL.getAttributeSpellingListIndex();
  4830. D->addAttr(::new (S.Context)
  4831. ARMInterruptAttr(AL.getLoc(), S.Context, Kind, Index));
  4832. }
  4833. static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4834. // MSP430 'interrupt' attribute is applied to
  4835. // a function with no parameters and void return type.
  4836. if (!isFunctionOrMethod(D)) {
  4837. S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
  4838. << "'interrupt'" << ExpectedFunctionOrMethod;
  4839. return;
  4840. }
  4841. if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
  4842. S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
  4843. << /*MSP430*/ 1 << 0;
  4844. return;
  4845. }
  4846. if (!getFunctionOrMethodResultType(D)->isVoidType()) {
  4847. S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
  4848. << /*MSP430*/ 1 << 1;
  4849. return;
  4850. }
  4851. // The attribute takes one integer argument.
  4852. if (!checkAttributeNumArgs(S, AL, 1))
  4853. return;
  4854. if (!AL.isArgExpr(0)) {
  4855. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  4856. << AL << AANT_ArgumentIntegerConstant;
  4857. return;
  4858. }
  4859. Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
  4860. llvm::APSInt NumParams(32);
  4861. if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
  4862. S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
  4863. << AL << AANT_ArgumentIntegerConstant
  4864. << NumParamsExpr->getSourceRange();
  4865. return;
  4866. }
  4867. // The argument should be in range 0..63.
  4868. unsigned Num = NumParams.getLimitedValue(255);
  4869. if (Num > 63) {
  4870. S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
  4871. << AL << (int)NumParams.getSExtValue()
  4872. << NumParamsExpr->getSourceRange();
  4873. return;
  4874. }
  4875. D->addAttr(::new (S.Context)
  4876. MSP430InterruptAttr(AL.getLoc(), S.Context, Num,
  4877. AL.getAttributeSpellingListIndex()));
  4878. D->addAttr(UsedAttr::CreateImplicit(S.Context));
  4879. }
  4880. static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4881. // Only one optional argument permitted.
  4882. if (AL.getNumArgs() > 1) {
  4883. S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
  4884. return;
  4885. }
  4886. StringRef Str;
  4887. SourceLocation ArgLoc;
  4888. if (AL.getNumArgs() == 0)
  4889. Str = "";
  4890. else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
  4891. return;
  4892. // Semantic checks for a function with the 'interrupt' attribute for MIPS:
  4893. // a) Must be a function.
  4894. // b) Must have no parameters.
  4895. // c) Must have the 'void' return type.
  4896. // d) Cannot have the 'mips16' attribute, as that instruction set
  4897. // lacks the 'eret' instruction.
  4898. // e) The attribute itself must either have no argument or one of the
  4899. // valid interrupt types, see [MipsInterruptDocs].
  4900. if (!isFunctionOrMethod(D)) {
  4901. S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
  4902. << "'interrupt'" << ExpectedFunctionOrMethod;
  4903. return;
  4904. }
  4905. if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
  4906. S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
  4907. << /*MIPS*/ 0 << 0;
  4908. return;
  4909. }
  4910. if (!getFunctionOrMethodResultType(D)->isVoidType()) {
  4911. S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
  4912. << /*MIPS*/ 0 << 1;
  4913. return;
  4914. }
  4915. if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL))
  4916. return;
  4917. MipsInterruptAttr::InterruptType Kind;
  4918. if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
  4919. S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
  4920. << AL << "'" + std::string(Str) + "'";
  4921. return;
  4922. }
  4923. D->addAttr(::new (S.Context) MipsInterruptAttr(
  4924. AL.getLoc(), S.Context, Kind, AL.getAttributeSpellingListIndex()));
  4925. }
  4926. static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4927. // Semantic checks for a function with the 'interrupt' attribute.
  4928. // a) Must be a function.
  4929. // b) Must have the 'void' return type.
  4930. // c) Must take 1 or 2 arguments.
  4931. // d) The 1st argument must be a pointer.
  4932. // e) The 2nd argument (if any) must be an unsigned integer.
  4933. if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
  4934. CXXMethodDecl::isStaticOverloadedOperator(
  4935. cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
  4936. S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
  4937. << AL << ExpectedFunctionWithProtoType;
  4938. return;
  4939. }
  4940. // Interrupt handler must have void return type.
  4941. if (!getFunctionOrMethodResultType(D)->isVoidType()) {
  4942. S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
  4943. diag::err_anyx86_interrupt_attribute)
  4944. << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
  4945. ? 0
  4946. : 1)
  4947. << 0;
  4948. return;
  4949. }
  4950. // Interrupt handler must have 1 or 2 parameters.
  4951. unsigned NumParams = getFunctionOrMethodNumParams(D);
  4952. if (NumParams < 1 || NumParams > 2) {
  4953. S.Diag(D->getBeginLoc(), diag::err_anyx86_interrupt_attribute)
  4954. << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
  4955. ? 0
  4956. : 1)
  4957. << 1;
  4958. return;
  4959. }
  4960. // The first argument must be a pointer.
  4961. if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
  4962. S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
  4963. diag::err_anyx86_interrupt_attribute)
  4964. << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
  4965. ? 0
  4966. : 1)
  4967. << 2;
  4968. return;
  4969. }
  4970. // The second argument, if present, must be an unsigned integer.
  4971. unsigned TypeSize =
  4972. S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
  4973. ? 64
  4974. : 32;
  4975. if (NumParams == 2 &&
  4976. (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
  4977. S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
  4978. S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
  4979. diag::err_anyx86_interrupt_attribute)
  4980. << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
  4981. ? 0
  4982. : 1)
  4983. << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
  4984. return;
  4985. }
  4986. D->addAttr(::new (S.Context) AnyX86InterruptAttr(
  4987. AL.getLoc(), S.Context, AL.getAttributeSpellingListIndex()));
  4988. D->addAttr(UsedAttr::CreateImplicit(S.Context));
  4989. }
  4990. static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  4991. if (!isFunctionOrMethod(D)) {
  4992. S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
  4993. << "'interrupt'" << ExpectedFunction;
  4994. return;
  4995. }
  4996. if (!checkAttributeNumArgs(S, AL, 0))
  4997. return;
  4998. handleSimpleAttribute<AVRInterruptAttr>(S, D, AL);
  4999. }
  5000. static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5001. if (!isFunctionOrMethod(D)) {
  5002. S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
  5003. << "'signal'" << ExpectedFunction;
  5004. return;
  5005. }
  5006. if (!checkAttributeNumArgs(S, AL, 0))
  5007. return;
  5008. handleSimpleAttribute<AVRSignalAttr>(S, D, AL);
  5009. }
  5010. static void handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5011. if (!isFunctionOrMethod(D)) {
  5012. S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
  5013. << "'import_module'" << ExpectedFunction;
  5014. return;
  5015. }
  5016. auto *FD = cast<FunctionDecl>(D);
  5017. if (FD->isThisDeclarationADefinition()) {
  5018. S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
  5019. return;
  5020. }
  5021. StringRef Str;
  5022. SourceLocation ArgLoc;
  5023. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
  5024. return;
  5025. FD->addAttr(::new (S.Context) WebAssemblyImportModuleAttr(
  5026. AL.getRange(), S.Context, Str,
  5027. AL.getAttributeSpellingListIndex()));
  5028. }
  5029. static void handleWebAssemblyImportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5030. if (!isFunctionOrMethod(D)) {
  5031. S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
  5032. << "'import_name'" << ExpectedFunction;
  5033. return;
  5034. }
  5035. auto *FD = cast<FunctionDecl>(D);
  5036. if (FD->isThisDeclarationADefinition()) {
  5037. S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
  5038. return;
  5039. }
  5040. StringRef Str;
  5041. SourceLocation ArgLoc;
  5042. if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
  5043. return;
  5044. FD->addAttr(::new (S.Context) WebAssemblyImportNameAttr(
  5045. AL.getRange(), S.Context, Str,
  5046. AL.getAttributeSpellingListIndex()));
  5047. }
  5048. static void handleRISCVInterruptAttr(Sema &S, Decl *D,
  5049. const ParsedAttr &AL) {
  5050. // Warn about repeated attributes.
  5051. if (const auto *A = D->getAttr<RISCVInterruptAttr>()) {
  5052. S.Diag(AL.getRange().getBegin(),
  5053. diag::warn_riscv_repeated_interrupt_attribute);
  5054. S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute);
  5055. return;
  5056. }
  5057. // Check the attribute argument. Argument is optional.
  5058. if (!checkAttributeAtMostNumArgs(S, AL, 1))
  5059. return;
  5060. StringRef Str;
  5061. SourceLocation ArgLoc;
  5062. // 'machine'is the default interrupt mode.
  5063. if (AL.getNumArgs() == 0)
  5064. Str = "machine";
  5065. else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
  5066. return;
  5067. // Semantic checks for a function with the 'interrupt' attribute:
  5068. // - Must be a function.
  5069. // - Must have no parameters.
  5070. // - Must have the 'void' return type.
  5071. // - The attribute itself must either have no argument or one of the
  5072. // valid interrupt types, see [RISCVInterruptDocs].
  5073. if (D->getFunctionType() == nullptr) {
  5074. S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
  5075. << "'interrupt'" << ExpectedFunction;
  5076. return;
  5077. }
  5078. if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
  5079. S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
  5080. << /*RISC-V*/ 2 << 0;
  5081. return;
  5082. }
  5083. if (!getFunctionOrMethodResultType(D)->isVoidType()) {
  5084. S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
  5085. << /*RISC-V*/ 2 << 1;
  5086. return;
  5087. }
  5088. RISCVInterruptAttr::InterruptType Kind;
  5089. if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
  5090. S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
  5091. << ArgLoc;
  5092. return;
  5093. }
  5094. D->addAttr(::new (S.Context) RISCVInterruptAttr(
  5095. AL.getLoc(), S.Context, Kind, AL.getAttributeSpellingListIndex()));
  5096. }
  5097. static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5098. // Dispatch the interrupt attribute based on the current target.
  5099. switch (S.Context.getTargetInfo().getTriple().getArch()) {
  5100. case llvm::Triple::msp430:
  5101. handleMSP430InterruptAttr(S, D, AL);
  5102. break;
  5103. case llvm::Triple::mipsel:
  5104. case llvm::Triple::mips:
  5105. handleMipsInterruptAttr(S, D, AL);
  5106. break;
  5107. case llvm::Triple::x86:
  5108. case llvm::Triple::x86_64:
  5109. handleAnyX86InterruptAttr(S, D, AL);
  5110. break;
  5111. case llvm::Triple::avr:
  5112. handleAVRInterruptAttr(S, D, AL);
  5113. break;
  5114. case llvm::Triple::riscv32:
  5115. case llvm::Triple::riscv64:
  5116. handleRISCVInterruptAttr(S, D, AL);
  5117. break;
  5118. default:
  5119. handleARMInterruptAttr(S, D, AL);
  5120. break;
  5121. }
  5122. }
  5123. static bool
  5124. checkAMDGPUFlatWorkGroupSizeArguments(Sema &S, Expr *MinExpr, Expr *MaxExpr,
  5125. const AMDGPUFlatWorkGroupSizeAttr &Attr) {
  5126. // Accept template arguments for now as they depend on something else.
  5127. // We'll get to check them when they eventually get instantiated.
  5128. if (MinExpr->isValueDependent() || MaxExpr->isValueDependent())
  5129. return false;
  5130. uint32_t Min = 0;
  5131. if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
  5132. return true;
  5133. uint32_t Max = 0;
  5134. if (!checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
  5135. return true;
  5136. if (Min == 0 && Max != 0) {
  5137. S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
  5138. << &Attr << 0;
  5139. return true;
  5140. }
  5141. if (Min > Max) {
  5142. S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
  5143. << &Attr << 1;
  5144. return true;
  5145. }
  5146. return false;
  5147. }
  5148. void Sema::addAMDGPUFlatWorkGroupSizeAttr(SourceRange AttrRange, Decl *D,
  5149. Expr *MinExpr, Expr *MaxExpr,
  5150. unsigned SpellingListIndex) {
  5151. AMDGPUFlatWorkGroupSizeAttr TmpAttr(AttrRange, Context, MinExpr, MaxExpr,
  5152. SpellingListIndex);
  5153. if (checkAMDGPUFlatWorkGroupSizeArguments(*this, MinExpr, MaxExpr, TmpAttr))
  5154. return;
  5155. D->addAttr(::new (Context) AMDGPUFlatWorkGroupSizeAttr(
  5156. AttrRange, Context, MinExpr, MaxExpr, SpellingListIndex));
  5157. }
  5158. static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
  5159. const ParsedAttr &AL) {
  5160. Expr *MinExpr = AL.getArgAsExpr(0);
  5161. Expr *MaxExpr = AL.getArgAsExpr(1);
  5162. S.addAMDGPUFlatWorkGroupSizeAttr(AL.getRange(), D, MinExpr, MaxExpr,
  5163. AL.getAttributeSpellingListIndex());
  5164. }
  5165. static bool checkAMDGPUWavesPerEUArguments(Sema &S, Expr *MinExpr,
  5166. Expr *MaxExpr,
  5167. const AMDGPUWavesPerEUAttr &Attr) {
  5168. if (S.DiagnoseUnexpandedParameterPack(MinExpr) ||
  5169. (MaxExpr && S.DiagnoseUnexpandedParameterPack(MaxExpr)))
  5170. return true;
  5171. // Accept template arguments for now as they depend on something else.
  5172. // We'll get to check them when they eventually get instantiated.
  5173. if (MinExpr->isValueDependent() || (MaxExpr && MaxExpr->isValueDependent()))
  5174. return false;
  5175. uint32_t Min = 0;
  5176. if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
  5177. return true;
  5178. uint32_t Max = 0;
  5179. if (MaxExpr && !checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
  5180. return true;
  5181. if (Min == 0 && Max != 0) {
  5182. S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
  5183. << &Attr << 0;
  5184. return true;
  5185. }
  5186. if (Max != 0 && Min > Max) {
  5187. S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
  5188. << &Attr << 1;
  5189. return true;
  5190. }
  5191. return false;
  5192. }
  5193. void Sema::addAMDGPUWavesPerEUAttr(SourceRange AttrRange, Decl *D,
  5194. Expr *MinExpr, Expr *MaxExpr,
  5195. unsigned SpellingListIndex) {
  5196. AMDGPUWavesPerEUAttr TmpAttr(AttrRange, Context, MinExpr, MaxExpr,
  5197. SpellingListIndex);
  5198. if (checkAMDGPUWavesPerEUArguments(*this, MinExpr, MaxExpr, TmpAttr))
  5199. return;
  5200. D->addAttr(::new (Context) AMDGPUWavesPerEUAttr(AttrRange, Context, MinExpr,
  5201. MaxExpr, SpellingListIndex));
  5202. }
  5203. static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5204. if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
  5205. !checkAttributeAtMostNumArgs(S, AL, 2))
  5206. return;
  5207. Expr *MinExpr = AL.getArgAsExpr(0);
  5208. Expr *MaxExpr = (AL.getNumArgs() > 1) ? AL.getArgAsExpr(1) : nullptr;
  5209. S.addAMDGPUWavesPerEUAttr(AL.getRange(), D, MinExpr, MaxExpr,
  5210. AL.getAttributeSpellingListIndex());
  5211. }
  5212. static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5213. uint32_t NumSGPR = 0;
  5214. Expr *NumSGPRExpr = AL.getArgAsExpr(0);
  5215. if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR))
  5216. return;
  5217. D->addAttr(::new (S.Context)
  5218. AMDGPUNumSGPRAttr(AL.getLoc(), S.Context, NumSGPR,
  5219. AL.getAttributeSpellingListIndex()));
  5220. }
  5221. static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5222. uint32_t NumVGPR = 0;
  5223. Expr *NumVGPRExpr = AL.getArgAsExpr(0);
  5224. if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR))
  5225. return;
  5226. D->addAttr(::new (S.Context)
  5227. AMDGPUNumVGPRAttr(AL.getLoc(), S.Context, NumVGPR,
  5228. AL.getAttributeSpellingListIndex()));
  5229. }
  5230. static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
  5231. const ParsedAttr &AL) {
  5232. // If we try to apply it to a function pointer, don't warn, but don't
  5233. // do anything, either. It doesn't matter anyway, because there's nothing
  5234. // special about calling a force_align_arg_pointer function.
  5235. const auto *VD = dyn_cast<ValueDecl>(D);
  5236. if (VD && VD->getType()->isFunctionPointerType())
  5237. return;
  5238. // Also don't warn on function pointer typedefs.
  5239. const auto *TD = dyn_cast<TypedefNameDecl>(D);
  5240. if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
  5241. TD->getUnderlyingType()->isFunctionType()))
  5242. return;
  5243. // Attribute can only be applied to function types.
  5244. if (!isa<FunctionDecl>(D)) {
  5245. S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
  5246. << AL << ExpectedFunction;
  5247. return;
  5248. }
  5249. D->addAttr(::new (S.Context)
  5250. X86ForceAlignArgPointerAttr(AL.getRange(), S.Context,
  5251. AL.getAttributeSpellingListIndex()));
  5252. }
  5253. static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) {
  5254. uint32_t Version;
  5255. Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
  5256. if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version))
  5257. return;
  5258. // TODO: Investigate what happens with the next major version of MSVC.
  5259. if (Version != LangOptions::MSVC2015 / 100) {
  5260. S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
  5261. << AL << Version << VersionExpr->getSourceRange();
  5262. return;
  5263. }
  5264. // The attribute expects a "major" version number like 19, but new versions of
  5265. // MSVC have moved to updating the "minor", or less significant numbers, so we
  5266. // have to multiply by 100 now.
  5267. Version *= 100;
  5268. D->addAttr(::new (S.Context)
  5269. LayoutVersionAttr(AL.getRange(), S.Context, Version,
  5270. AL.getAttributeSpellingListIndex()));
  5271. }
  5272. DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
  5273. unsigned AttrSpellingListIndex) {
  5274. if (D->hasAttr<DLLExportAttr>()) {
  5275. Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
  5276. return nullptr;
  5277. }
  5278. if (D->hasAttr<DLLImportAttr>())
  5279. return nullptr;
  5280. return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
  5281. }
  5282. DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
  5283. unsigned AttrSpellingListIndex) {
  5284. if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
  5285. Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
  5286. D->dropAttr<DLLImportAttr>();
  5287. }
  5288. if (D->hasAttr<DLLExportAttr>())
  5289. return nullptr;
  5290. return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
  5291. }
  5292. static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) {
  5293. if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
  5294. S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  5295. S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A;
  5296. return;
  5297. }
  5298. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  5299. if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport &&
  5300. !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  5301. // MinGW doesn't allow dllimport on inline functions.
  5302. S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
  5303. << A;
  5304. return;
  5305. }
  5306. }
  5307. if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  5308. if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  5309. MD->getParent()->isLambda()) {
  5310. S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A;
  5311. return;
  5312. }
  5313. }
  5314. unsigned Index = A.getAttributeSpellingListIndex();
  5315. Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport
  5316. ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
  5317. : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
  5318. if (NewAttr)
  5319. D->addAttr(NewAttr);
  5320. }
  5321. MSInheritanceAttr *
  5322. Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
  5323. unsigned AttrSpellingListIndex,
  5324. MSInheritanceAttr::Spelling SemanticSpelling) {
  5325. if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
  5326. if (IA->getSemanticSpelling() == SemanticSpelling)
  5327. return nullptr;
  5328. Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
  5329. << 1 /*previous declaration*/;
  5330. Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
  5331. D->dropAttr<MSInheritanceAttr>();
  5332. }
  5333. auto *RD = cast<CXXRecordDecl>(D);
  5334. if (RD->hasDefinition()) {
  5335. if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
  5336. SemanticSpelling)) {
  5337. return nullptr;
  5338. }
  5339. } else {
  5340. if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
  5341. Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
  5342. << 1 /*partial specialization*/;
  5343. return nullptr;
  5344. }
  5345. if (RD->getDescribedClassTemplate()) {
  5346. Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
  5347. << 0 /*primary template*/;
  5348. return nullptr;
  5349. }
  5350. }
  5351. return ::new (Context)
  5352. MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
  5353. }
  5354. static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5355. // The capability attributes take a single string parameter for the name of
  5356. // the capability they represent. The lockable attribute does not take any
  5357. // parameters. However, semantically, both attributes represent the same
  5358. // concept, and so they use the same semantic attribute. Eventually, the
  5359. // lockable attribute will be removed.
  5360. //
  5361. // For backward compatibility, any capability which has no specified string
  5362. // literal will be considered a "mutex."
  5363. StringRef N("mutex");
  5364. SourceLocation LiteralLoc;
  5365. if (AL.getKind() == ParsedAttr::AT_Capability &&
  5366. !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc))
  5367. return;
  5368. // Currently, there are only two names allowed for a capability: role and
  5369. // mutex (case insensitive). Diagnose other capability names.
  5370. if (!N.equals_lower("mutex") && !N.equals_lower("role"))
  5371. S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
  5372. D->addAttr(::new (S.Context) CapabilityAttr(AL.getRange(), S.Context, N,
  5373. AL.getAttributeSpellingListIndex()));
  5374. }
  5375. static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5376. SmallVector<Expr*, 1> Args;
  5377. if (!checkLockFunAttrCommon(S, D, AL, Args))
  5378. return;
  5379. D->addAttr(::new (S.Context) AssertCapabilityAttr(AL.getRange(), S.Context,
  5380. Args.data(), Args.size(),
  5381. AL.getAttributeSpellingListIndex()));
  5382. }
  5383. static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
  5384. const ParsedAttr &AL) {
  5385. SmallVector<Expr*, 1> Args;
  5386. if (!checkLockFunAttrCommon(S, D, AL, Args))
  5387. return;
  5388. D->addAttr(::new (S.Context) AcquireCapabilityAttr(AL.getRange(),
  5389. S.Context,
  5390. Args.data(), Args.size(),
  5391. AL.getAttributeSpellingListIndex()));
  5392. }
  5393. static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
  5394. const ParsedAttr &AL) {
  5395. SmallVector<Expr*, 2> Args;
  5396. if (!checkTryLockFunAttrCommon(S, D, AL, Args))
  5397. return;
  5398. D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(AL.getRange(),
  5399. S.Context,
  5400. AL.getArgAsExpr(0),
  5401. Args.data(),
  5402. Args.size(),
  5403. AL.getAttributeSpellingListIndex()));
  5404. }
  5405. static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
  5406. const ParsedAttr &AL) {
  5407. // Check that all arguments are lockable objects.
  5408. SmallVector<Expr *, 1> Args;
  5409. checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true);
  5410. D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
  5411. AL.getRange(), S.Context, Args.data(), Args.size(),
  5412. AL.getAttributeSpellingListIndex()));
  5413. }
  5414. static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
  5415. const ParsedAttr &AL) {
  5416. if (!checkAttributeAtLeastNumArgs(S, AL, 1))
  5417. return;
  5418. // check that all arguments are lockable objects
  5419. SmallVector<Expr*, 1> Args;
  5420. checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
  5421. if (Args.empty())
  5422. return;
  5423. RequiresCapabilityAttr *RCA = ::new (S.Context)
  5424. RequiresCapabilityAttr(AL.getRange(), S.Context, Args.data(),
  5425. Args.size(), AL.getAttributeSpellingListIndex());
  5426. D->addAttr(RCA);
  5427. }
  5428. static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5429. if (const auto *NSD = dyn_cast<NamespaceDecl>(D)) {
  5430. if (NSD->isAnonymousNamespace()) {
  5431. S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace);
  5432. // Do not want to attach the attribute to the namespace because that will
  5433. // cause confusing diagnostic reports for uses of declarations within the
  5434. // namespace.
  5435. return;
  5436. }
  5437. }
  5438. // Handle the cases where the attribute has a text message.
  5439. StringRef Str, Replacement;
  5440. if (AL.isArgExpr(0) && AL.getArgAsExpr(0) &&
  5441. !S.checkStringLiteralArgumentAttr(AL, 0, Str))
  5442. return;
  5443. // Only support a single optional message for Declspec and CXX11.
  5444. if (AL.isDeclspecAttribute() || AL.isCXX11Attribute())
  5445. checkAttributeAtMostNumArgs(S, AL, 1);
  5446. else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) &&
  5447. !S.checkStringLiteralArgumentAttr(AL, 1, Replacement))
  5448. return;
  5449. if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope())
  5450. S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL;
  5451. D->addAttr(::new (S.Context)
  5452. DeprecatedAttr(AL.getRange(), S.Context, Str, Replacement,
  5453. AL.getAttributeSpellingListIndex()));
  5454. }
  5455. static bool isGlobalVar(const Decl *D) {
  5456. if (const auto *S = dyn_cast<VarDecl>(D))
  5457. return S->hasGlobalStorage();
  5458. return false;
  5459. }
  5460. static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5461. if (!checkAttributeAtLeastNumArgs(S, AL, 1))
  5462. return;
  5463. std::vector<StringRef> Sanitizers;
  5464. for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
  5465. StringRef SanitizerName;
  5466. SourceLocation LiteralLoc;
  5467. if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc))
  5468. return;
  5469. if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) ==
  5470. SanitizerMask())
  5471. S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
  5472. else if (isGlobalVar(D) && SanitizerName != "address")
  5473. S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
  5474. << AL << ExpectedFunctionOrMethod;
  5475. Sanitizers.push_back(SanitizerName);
  5476. }
  5477. D->addAttr(::new (S.Context) NoSanitizeAttr(
  5478. AL.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
  5479. AL.getAttributeSpellingListIndex()));
  5480. }
  5481. static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
  5482. const ParsedAttr &AL) {
  5483. StringRef AttrName = AL.getName()->getName();
  5484. normalizeName(AttrName);
  5485. StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
  5486. .Case("no_address_safety_analysis", "address")
  5487. .Case("no_sanitize_address", "address")
  5488. .Case("no_sanitize_thread", "thread")
  5489. .Case("no_sanitize_memory", "memory");
  5490. if (isGlobalVar(D) && SanitizerName != "address")
  5491. S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
  5492. << AL << ExpectedFunction;
  5493. D->addAttr(::new (S.Context)
  5494. NoSanitizeAttr(AL.getRange(), S.Context, &SanitizerName, 1,
  5495. AL.getAttributeSpellingListIndex()));
  5496. }
  5497. static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5498. if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL))
  5499. D->addAttr(Internal);
  5500. }
  5501. static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5502. if (S.LangOpts.OpenCLVersion != 200)
  5503. S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version)
  5504. << AL << "2.0" << 0;
  5505. else
  5506. S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored) << AL
  5507. << "2.0";
  5508. }
  5509. /// Handles semantic checking for features that are common to all attributes,
  5510. /// such as checking whether a parameter was properly specified, or the correct
  5511. /// number of arguments were passed, etc.
  5512. static bool handleCommonAttributeFeatures(Sema &S, Decl *D,
  5513. const ParsedAttr &AL) {
  5514. // Several attributes carry different semantics than the parsing requires, so
  5515. // those are opted out of the common argument checks.
  5516. //
  5517. // We also bail on unknown and ignored attributes because those are handled
  5518. // as part of the target-specific handling logic.
  5519. if (AL.getKind() == ParsedAttr::UnknownAttribute)
  5520. return false;
  5521. // Check whether the attribute requires specific language extensions to be
  5522. // enabled.
  5523. if (!AL.diagnoseLangOpts(S))
  5524. return true;
  5525. // Check whether the attribute appertains to the given subject.
  5526. if (!AL.diagnoseAppertainsTo(S, D))
  5527. return true;
  5528. if (AL.hasCustomParsing())
  5529. return false;
  5530. if (AL.getMinArgs() == AL.getMaxArgs()) {
  5531. // If there are no optional arguments, then checking for the argument count
  5532. // is trivial.
  5533. if (!checkAttributeNumArgs(S, AL, AL.getMinArgs()))
  5534. return true;
  5535. } else {
  5536. // There are optional arguments, so checking is slightly more involved.
  5537. if (AL.getMinArgs() &&
  5538. !checkAttributeAtLeastNumArgs(S, AL, AL.getMinArgs()))
  5539. return true;
  5540. else if (!AL.hasVariadicArg() && AL.getMaxArgs() &&
  5541. !checkAttributeAtMostNumArgs(S, AL, AL.getMaxArgs()))
  5542. return true;
  5543. }
  5544. if (S.CheckAttrTarget(AL))
  5545. return true;
  5546. return false;
  5547. }
  5548. static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5549. if (D->isInvalidDecl())
  5550. return;
  5551. // Check if there is only one access qualifier.
  5552. if (D->hasAttr<OpenCLAccessAttr>()) {
  5553. if (D->getAttr<OpenCLAccessAttr>()->getSemanticSpelling() ==
  5554. AL.getSemanticSpelling()) {
  5555. S.Diag(AL.getLoc(), diag::warn_duplicate_declspec)
  5556. << AL.getName()->getName() << AL.getRange();
  5557. } else {
  5558. S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers)
  5559. << D->getSourceRange();
  5560. D->setInvalidDecl(true);
  5561. return;
  5562. }
  5563. }
  5564. // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
  5565. // image object can be read and written.
  5566. // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
  5567. // object. Using the read_write (or __read_write) qualifier with the pipe
  5568. // qualifier is a compilation error.
  5569. if (const auto *PDecl = dyn_cast<ParmVarDecl>(D)) {
  5570. const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
  5571. if (AL.getName()->getName().find("read_write") != StringRef::npos) {
  5572. if ((!S.getLangOpts().OpenCLCPlusPlus &&
  5573. S.getLangOpts().OpenCLVersion < 200) ||
  5574. DeclTy->isPipeType()) {
  5575. S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write)
  5576. << AL << PDecl->getType() << DeclTy->isImageType();
  5577. D->setInvalidDecl(true);
  5578. return;
  5579. }
  5580. }
  5581. }
  5582. D->addAttr(::new (S.Context) OpenCLAccessAttr(
  5583. AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
  5584. }
  5585. static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) {
  5586. if (!cast<VarDecl>(D)->hasGlobalStorage()) {
  5587. S.Diag(D->getLocation(), diag::err_destroy_attr_on_non_static_var)
  5588. << (A.getKind() == ParsedAttr::AT_AlwaysDestroy);
  5589. return;
  5590. }
  5591. if (A.getKind() == ParsedAttr::AT_AlwaysDestroy)
  5592. handleSimpleAttributeWithExclusions<AlwaysDestroyAttr, NoDestroyAttr>(S, D, A);
  5593. else
  5594. handleSimpleAttributeWithExclusions<NoDestroyAttr, AlwaysDestroyAttr>(S, D, A);
  5595. }
  5596. static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5597. assert(cast<VarDecl>(D)->getStorageDuration() == SD_Automatic &&
  5598. "uninitialized is only valid on automatic duration variables");
  5599. unsigned Index = AL.getAttributeSpellingListIndex();
  5600. D->addAttr(::new (S.Context)
  5601. UninitializedAttr(AL.getLoc(), S.Context, Index));
  5602. }
  5603. static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD,
  5604. bool DiagnoseFailure) {
  5605. QualType Ty = VD->getType();
  5606. if (!Ty->isObjCRetainableType()) {
  5607. if (DiagnoseFailure) {
  5608. S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
  5609. << 0;
  5610. }
  5611. return false;
  5612. }
  5613. Qualifiers::ObjCLifetime LifetimeQual = Ty.getQualifiers().getObjCLifetime();
  5614. // Sema::inferObjCARCLifetime must run after processing decl attributes
  5615. // (because __block lowers to an attribute), so if the lifetime hasn't been
  5616. // explicitly specified, infer it locally now.
  5617. if (LifetimeQual == Qualifiers::OCL_None)
  5618. LifetimeQual = Ty->getObjCARCImplicitLifetime();
  5619. // The attributes only really makes sense for __strong variables; ignore any
  5620. // attempts to annotate a parameter with any other lifetime qualifier.
  5621. if (LifetimeQual != Qualifiers::OCL_Strong) {
  5622. if (DiagnoseFailure) {
  5623. S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
  5624. << 1;
  5625. }
  5626. return false;
  5627. }
  5628. // Tampering with the type of a VarDecl here is a bit of a hack, but we need
  5629. // to ensure that the variable is 'const' so that we can error on
  5630. // modification, which can otherwise over-release.
  5631. VD->setType(Ty.withConst());
  5632. VD->setARCPseudoStrong(true);
  5633. return true;
  5634. }
  5635. static void handleObjCExternallyRetainedAttr(Sema &S, Decl *D,
  5636. const ParsedAttr &AL) {
  5637. if (auto *VD = dyn_cast<VarDecl>(D)) {
  5638. assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically");
  5639. if (!VD->hasLocalStorage()) {
  5640. S.Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
  5641. << 0;
  5642. return;
  5643. }
  5644. if (!tryMakeVariablePseudoStrong(S, VD, /*DiagnoseFailure=*/true))
  5645. return;
  5646. handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
  5647. return;
  5648. }
  5649. // If D is a function-like declaration (method, block, or function), then we
  5650. // make every parameter psuedo-strong.
  5651. for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E; ++I) {
  5652. auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, I));
  5653. QualType Ty = PVD->getType();
  5654. // If a user wrote a parameter with __strong explicitly, then assume they
  5655. // want "real" strong semantics for that parameter. This works because if
  5656. // the parameter was written with __strong, then the strong qualifier will
  5657. // be non-local.
  5658. if (Ty.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() ==
  5659. Qualifiers::OCL_Strong)
  5660. continue;
  5661. tryMakeVariablePseudoStrong(S, PVD, /*DiagnoseFailure=*/false);
  5662. }
  5663. handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
  5664. }
  5665. static void handleFortifyStdLib(Sema &S, Decl *D, const ParsedAttr &AL) {
  5666. auto *FD = cast<FunctionDecl>(D);
  5667. unsigned VariantID = Builtin::getFortifiedVariantFunction(FD->getBuiltinID());
  5668. if (VariantID == 0) {
  5669. S.Diag(D->getLocation(), diag::err_fortify_std_lib_bad_decl);
  5670. return;
  5671. }
  5672. uint32_t BOSType, Flag;
  5673. if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), BOSType, 0, true) ||
  5674. !checkUInt32Argument(S, AL, AL.getArgAsExpr(1), Flag, 1, true))
  5675. return;
  5676. if (BOSType > 3) {
  5677. S.Diag(AL.getArgAsExpr(0)->getBeginLoc(),
  5678. diag::err_attribute_argument_out_of_range)
  5679. << AL << 0 << 3;
  5680. return;
  5681. }
  5682. D->addAttr(::new (S.getASTContext()) FortifyStdLibAttr(
  5683. AL.getLoc(), S.getASTContext(), BOSType, Flag,
  5684. AL.getAttributeSpellingListIndex()));
  5685. }
  5686. static void handleMIGServerRoutineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  5687. // Check that the return type is a `typedef int kern_return_t` or a typedef
  5688. // around it, because otherwise MIG convention checks make no sense.
  5689. // BlockDecl doesn't store a return type, so it's annoying to check,
  5690. // so let's skip it for now.
  5691. if (!isa<BlockDecl>(D)) {
  5692. QualType T = getFunctionOrMethodResultType(D);
  5693. bool IsKernReturnT = false;
  5694. while (const auto *TT = T->getAs<TypedefType>()) {
  5695. IsKernReturnT = (TT->getDecl()->getName() == "kern_return_t");
  5696. T = TT->desugar();
  5697. }
  5698. if (!IsKernReturnT || T.getCanonicalType() != S.getASTContext().IntTy) {
  5699. S.Diag(D->getBeginLoc(),
  5700. diag::warn_mig_server_routine_does_not_return_kern_return_t);
  5701. return;
  5702. }
  5703. }
  5704. handleSimpleAttribute<MIGServerRoutineAttr>(S, D, AL);
  5705. }
  5706. //===----------------------------------------------------------------------===//
  5707. // Top Level Sema Entry Points
  5708. //===----------------------------------------------------------------------===//
  5709. /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
  5710. /// the attribute applies to decls. If the attribute is a type attribute, just
  5711. /// silently ignore it if a GNU attribute.
  5712. static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
  5713. const ParsedAttr &AL,
  5714. bool IncludeCXX11Attributes) {
  5715. if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
  5716. return;
  5717. // Ignore C++11 attributes on declarator chunks: they appertain to the type
  5718. // instead.
  5719. if (AL.isCXX11Attribute() && !IncludeCXX11Attributes)
  5720. return;
  5721. // Unknown attributes are automatically warned on. Target-specific attributes
  5722. // which do not apply to the current target architecture are treated as
  5723. // though they were unknown attributes.
  5724. if (AL.getKind() == ParsedAttr::UnknownAttribute ||
  5725. !AL.existsInTarget(S.Context.getTargetInfo())) {
  5726. S.Diag(AL.getLoc(),
  5727. AL.isDeclspecAttribute()
  5728. ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
  5729. : (unsigned)diag::warn_unknown_attribute_ignored)
  5730. << AL;
  5731. return;
  5732. }
  5733. if (handleCommonAttributeFeatures(S, D, AL))
  5734. return;
  5735. switch (AL.getKind()) {
  5736. default:
  5737. if (!AL.isStmtAttr()) {
  5738. // Type attributes are handled elsewhere; silently move on.
  5739. assert(AL.isTypeAttr() && "Non-type attribute not handled");
  5740. break;
  5741. }
  5742. S.Diag(AL.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
  5743. << AL << D->getLocation();
  5744. break;
  5745. case ParsedAttr::AT_Interrupt:
  5746. handleInterruptAttr(S, D, AL);
  5747. break;
  5748. case ParsedAttr::AT_X86ForceAlignArgPointer:
  5749. handleX86ForceAlignArgPointerAttr(S, D, AL);
  5750. break;
  5751. case ParsedAttr::AT_DLLExport:
  5752. case ParsedAttr::AT_DLLImport:
  5753. handleDLLAttr(S, D, AL);
  5754. break;
  5755. case ParsedAttr::AT_Mips16:
  5756. handleSimpleAttributeWithExclusions<Mips16Attr, MicroMipsAttr,
  5757. MipsInterruptAttr>(S, D, AL);
  5758. break;
  5759. case ParsedAttr::AT_NoMips16:
  5760. handleSimpleAttribute<NoMips16Attr>(S, D, AL);
  5761. break;
  5762. case ParsedAttr::AT_MicroMips:
  5763. handleSimpleAttributeWithExclusions<MicroMipsAttr, Mips16Attr>(S, D, AL);
  5764. break;
  5765. case ParsedAttr::AT_NoMicroMips:
  5766. handleSimpleAttribute<NoMicroMipsAttr>(S, D, AL);
  5767. break;
  5768. case ParsedAttr::AT_MipsLongCall:
  5769. handleSimpleAttributeWithExclusions<MipsLongCallAttr, MipsShortCallAttr>(
  5770. S, D, AL);
  5771. break;
  5772. case ParsedAttr::AT_MipsShortCall:
  5773. handleSimpleAttributeWithExclusions<MipsShortCallAttr, MipsLongCallAttr>(
  5774. S, D, AL);
  5775. break;
  5776. case ParsedAttr::AT_AMDGPUFlatWorkGroupSize:
  5777. handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL);
  5778. break;
  5779. case ParsedAttr::AT_AMDGPUWavesPerEU:
  5780. handleAMDGPUWavesPerEUAttr(S, D, AL);
  5781. break;
  5782. case ParsedAttr::AT_AMDGPUNumSGPR:
  5783. handleAMDGPUNumSGPRAttr(S, D, AL);
  5784. break;
  5785. case ParsedAttr::AT_AMDGPUNumVGPR:
  5786. handleAMDGPUNumVGPRAttr(S, D, AL);
  5787. break;
  5788. case ParsedAttr::AT_AVRSignal:
  5789. handleAVRSignalAttr(S, D, AL);
  5790. break;
  5791. case ParsedAttr::AT_WebAssemblyImportModule:
  5792. handleWebAssemblyImportModuleAttr(S, D, AL);
  5793. break;
  5794. case ParsedAttr::AT_WebAssemblyImportName:
  5795. handleWebAssemblyImportNameAttr(S, D, AL);
  5796. break;
  5797. case ParsedAttr::AT_IBAction:
  5798. handleSimpleAttribute<IBActionAttr>(S, D, AL);
  5799. break;
  5800. case ParsedAttr::AT_IBOutlet:
  5801. handleIBOutlet(S, D, AL);
  5802. break;
  5803. case ParsedAttr::AT_IBOutletCollection:
  5804. handleIBOutletCollection(S, D, AL);
  5805. break;
  5806. case ParsedAttr::AT_IFunc:
  5807. handleIFuncAttr(S, D, AL);
  5808. break;
  5809. case ParsedAttr::AT_Alias:
  5810. handleAliasAttr(S, D, AL);
  5811. break;
  5812. case ParsedAttr::AT_Aligned:
  5813. handleAlignedAttr(S, D, AL);
  5814. break;
  5815. case ParsedAttr::AT_AlignValue:
  5816. handleAlignValueAttr(S, D, AL);
  5817. break;
  5818. case ParsedAttr::AT_AllocSize:
  5819. handleAllocSizeAttr(S, D, AL);
  5820. break;
  5821. case ParsedAttr::AT_AlwaysInline:
  5822. handleAlwaysInlineAttr(S, D, AL);
  5823. break;
  5824. case ParsedAttr::AT_Artificial:
  5825. handleSimpleAttribute<ArtificialAttr>(S, D, AL);
  5826. break;
  5827. case ParsedAttr::AT_AnalyzerNoReturn:
  5828. handleAnalyzerNoReturnAttr(S, D, AL);
  5829. break;
  5830. case ParsedAttr::AT_TLSModel:
  5831. handleTLSModelAttr(S, D, AL);
  5832. break;
  5833. case ParsedAttr::AT_Annotate:
  5834. handleAnnotateAttr(S, D, AL);
  5835. break;
  5836. case ParsedAttr::AT_Availability:
  5837. handleAvailabilityAttr(S, D, AL);
  5838. break;
  5839. case ParsedAttr::AT_CarriesDependency:
  5840. handleDependencyAttr(S, scope, D, AL);
  5841. break;
  5842. case ParsedAttr::AT_CPUDispatch:
  5843. case ParsedAttr::AT_CPUSpecific:
  5844. handleCPUSpecificAttr(S, D, AL);
  5845. break;
  5846. case ParsedAttr::AT_Common:
  5847. handleCommonAttr(S, D, AL);
  5848. break;
  5849. case ParsedAttr::AT_CUDAConstant:
  5850. handleConstantAttr(S, D, AL);
  5851. break;
  5852. case ParsedAttr::AT_PassObjectSize:
  5853. handlePassObjectSizeAttr(S, D, AL);
  5854. break;
  5855. case ParsedAttr::AT_Constructor:
  5856. handleConstructorAttr(S, D, AL);
  5857. break;
  5858. case ParsedAttr::AT_CXX11NoReturn:
  5859. handleSimpleAttribute<CXX11NoReturnAttr>(S, D, AL);
  5860. break;
  5861. case ParsedAttr::AT_Deprecated:
  5862. handleDeprecatedAttr(S, D, AL);
  5863. break;
  5864. case ParsedAttr::AT_Destructor:
  5865. handleDestructorAttr(S, D, AL);
  5866. break;
  5867. case ParsedAttr::AT_EnableIf:
  5868. handleEnableIfAttr(S, D, AL);
  5869. break;
  5870. case ParsedAttr::AT_DiagnoseIf:
  5871. handleDiagnoseIfAttr(S, D, AL);
  5872. break;
  5873. case ParsedAttr::AT_ExtVectorType:
  5874. handleExtVectorTypeAttr(S, D, AL);
  5875. break;
  5876. case ParsedAttr::AT_ExternalSourceSymbol:
  5877. handleExternalSourceSymbolAttr(S, D, AL);
  5878. break;
  5879. case ParsedAttr::AT_MinSize:
  5880. handleMinSizeAttr(S, D, AL);
  5881. break;
  5882. case ParsedAttr::AT_OptimizeNone:
  5883. handleOptimizeNoneAttr(S, D, AL);
  5884. break;
  5885. case ParsedAttr::AT_FlagEnum:
  5886. handleSimpleAttribute<FlagEnumAttr>(S, D, AL);
  5887. break;
  5888. case ParsedAttr::AT_EnumExtensibility:
  5889. handleEnumExtensibilityAttr(S, D, AL);
  5890. break;
  5891. case ParsedAttr::AT_Flatten:
  5892. handleSimpleAttribute<FlattenAttr>(S, D, AL);
  5893. break;
  5894. case ParsedAttr::AT_Format:
  5895. handleFormatAttr(S, D, AL);
  5896. break;
  5897. case ParsedAttr::AT_FormatArg:
  5898. handleFormatArgAttr(S, D, AL);
  5899. break;
  5900. case ParsedAttr::AT_Callback:
  5901. handleCallbackAttr(S, D, AL);
  5902. break;
  5903. case ParsedAttr::AT_CUDAGlobal:
  5904. handleGlobalAttr(S, D, AL);
  5905. break;
  5906. case ParsedAttr::AT_CUDADevice:
  5907. handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
  5908. AL);
  5909. break;
  5910. case ParsedAttr::AT_CUDAHost:
  5911. handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D, AL);
  5912. break;
  5913. case ParsedAttr::AT_GNUInline:
  5914. handleGNUInlineAttr(S, D, AL);
  5915. break;
  5916. case ParsedAttr::AT_CUDALaunchBounds:
  5917. handleLaunchBoundsAttr(S, D, AL);
  5918. break;
  5919. case ParsedAttr::AT_Restrict:
  5920. handleRestrictAttr(S, D, AL);
  5921. break;
  5922. case ParsedAttr::AT_LifetimeBound:
  5923. handleSimpleAttribute<LifetimeBoundAttr>(S, D, AL);
  5924. break;
  5925. case ParsedAttr::AT_MayAlias:
  5926. handleSimpleAttribute<MayAliasAttr>(S, D, AL);
  5927. break;
  5928. case ParsedAttr::AT_Mode:
  5929. handleModeAttr(S, D, AL);
  5930. break;
  5931. case ParsedAttr::AT_NoAlias:
  5932. handleSimpleAttribute<NoAliasAttr>(S, D, AL);
  5933. break;
  5934. case ParsedAttr::AT_NoCommon:
  5935. handleSimpleAttribute<NoCommonAttr>(S, D, AL);
  5936. break;
  5937. case ParsedAttr::AT_NoSplitStack:
  5938. handleSimpleAttribute<NoSplitStackAttr>(S, D, AL);
  5939. break;
  5940. case ParsedAttr::AT_NonNull:
  5941. if (auto *PVD = dyn_cast<ParmVarDecl>(D))
  5942. handleNonNullAttrParameter(S, PVD, AL);
  5943. else
  5944. handleNonNullAttr(S, D, AL);
  5945. break;
  5946. case ParsedAttr::AT_ReturnsNonNull:
  5947. handleReturnsNonNullAttr(S, D, AL);
  5948. break;
  5949. case ParsedAttr::AT_NoEscape:
  5950. handleNoEscapeAttr(S, D, AL);
  5951. break;
  5952. case ParsedAttr::AT_AssumeAligned:
  5953. handleAssumeAlignedAttr(S, D, AL);
  5954. break;
  5955. case ParsedAttr::AT_AllocAlign:
  5956. handleAllocAlignAttr(S, D, AL);
  5957. break;
  5958. case ParsedAttr::AT_Overloadable:
  5959. handleSimpleAttribute<OverloadableAttr>(S, D, AL);
  5960. break;
  5961. case ParsedAttr::AT_Ownership:
  5962. handleOwnershipAttr(S, D, AL);
  5963. break;
  5964. case ParsedAttr::AT_Cold:
  5965. handleSimpleAttributeWithExclusions<ColdAttr, HotAttr>(S, D, AL);
  5966. break;
  5967. case ParsedAttr::AT_Hot:
  5968. handleSimpleAttributeWithExclusions<HotAttr, ColdAttr>(S, D, AL);
  5969. break;
  5970. case ParsedAttr::AT_Naked:
  5971. handleNakedAttr(S, D, AL);
  5972. break;
  5973. case ParsedAttr::AT_NoReturn:
  5974. handleNoReturnAttr(S, D, AL);
  5975. break;
  5976. case ParsedAttr::AT_AnyX86NoCfCheck:
  5977. handleNoCfCheckAttr(S, D, AL);
  5978. break;
  5979. case ParsedAttr::AT_NoThrow:
  5980. handleSimpleAttribute<NoThrowAttr>(S, D, AL);
  5981. break;
  5982. case ParsedAttr::AT_CUDAShared:
  5983. handleSharedAttr(S, D, AL);
  5984. break;
  5985. case ParsedAttr::AT_VecReturn:
  5986. handleVecReturnAttr(S, D, AL);
  5987. break;
  5988. case ParsedAttr::AT_ObjCOwnership:
  5989. handleObjCOwnershipAttr(S, D, AL);
  5990. break;
  5991. case ParsedAttr::AT_ObjCPreciseLifetime:
  5992. handleObjCPreciseLifetimeAttr(S, D, AL);
  5993. break;
  5994. case ParsedAttr::AT_ObjCReturnsInnerPointer:
  5995. handleObjCReturnsInnerPointerAttr(S, D, AL);
  5996. break;
  5997. case ParsedAttr::AT_ObjCRequiresSuper:
  5998. handleObjCRequiresSuperAttr(S, D, AL);
  5999. break;
  6000. case ParsedAttr::AT_ObjCBridge:
  6001. handleObjCBridgeAttr(S, D, AL);
  6002. break;
  6003. case ParsedAttr::AT_ObjCBridgeMutable:
  6004. handleObjCBridgeMutableAttr(S, D, AL);
  6005. break;
  6006. case ParsedAttr::AT_ObjCBridgeRelated:
  6007. handleObjCBridgeRelatedAttr(S, D, AL);
  6008. break;
  6009. case ParsedAttr::AT_ObjCDesignatedInitializer:
  6010. handleObjCDesignatedInitializer(S, D, AL);
  6011. break;
  6012. case ParsedAttr::AT_ObjCRuntimeName:
  6013. handleObjCRuntimeName(S, D, AL);
  6014. break;
  6015. case ParsedAttr::AT_ObjCRuntimeVisible:
  6016. handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, AL);
  6017. break;
  6018. case ParsedAttr::AT_ObjCBoxable:
  6019. handleObjCBoxable(S, D, AL);
  6020. break;
  6021. case ParsedAttr::AT_CFAuditedTransfer:
  6022. handleSimpleAttributeWithExclusions<CFAuditedTransferAttr,
  6023. CFUnknownTransferAttr>(S, D, AL);
  6024. break;
  6025. case ParsedAttr::AT_CFUnknownTransfer:
  6026. handleSimpleAttributeWithExclusions<CFUnknownTransferAttr,
  6027. CFAuditedTransferAttr>(S, D, AL);
  6028. break;
  6029. case ParsedAttr::AT_CFConsumed:
  6030. case ParsedAttr::AT_NSConsumed:
  6031. case ParsedAttr::AT_OSConsumed:
  6032. S.AddXConsumedAttr(D, AL.getRange(), AL.getAttributeSpellingListIndex(),
  6033. parsedAttrToRetainOwnershipKind(AL),
  6034. /*IsTemplateInstantiation=*/false);
  6035. break;
  6036. case ParsedAttr::AT_NSConsumesSelf:
  6037. handleSimpleAttribute<NSConsumesSelfAttr>(S, D, AL);
  6038. break;
  6039. case ParsedAttr::AT_OSConsumesThis:
  6040. handleSimpleAttribute<OSConsumesThisAttr>(S, D, AL);
  6041. break;
  6042. case ParsedAttr::AT_OSReturnsRetainedOnZero:
  6043. handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnZeroAttr>(
  6044. S, D, AL, isValidOSObjectOutParameter(D),
  6045. diag::warn_ns_attribute_wrong_parameter_type,
  6046. /*Extra Args=*/AL, /*pointer-to-OSObject-pointer*/ 3, AL.getRange());
  6047. break;
  6048. case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
  6049. handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnNonZeroAttr>(
  6050. S, D, AL, isValidOSObjectOutParameter(D),
  6051. diag::warn_ns_attribute_wrong_parameter_type,
  6052. /*Extra Args=*/AL, /*pointer-to-OSObject-poointer*/ 3, AL.getRange());
  6053. break;
  6054. case ParsedAttr::AT_NSReturnsAutoreleased:
  6055. case ParsedAttr::AT_NSReturnsNotRetained:
  6056. case ParsedAttr::AT_NSReturnsRetained:
  6057. case ParsedAttr::AT_CFReturnsNotRetained:
  6058. case ParsedAttr::AT_CFReturnsRetained:
  6059. case ParsedAttr::AT_OSReturnsNotRetained:
  6060. case ParsedAttr::AT_OSReturnsRetained:
  6061. handleXReturnsXRetainedAttr(S, D, AL);
  6062. break;
  6063. case ParsedAttr::AT_WorkGroupSizeHint:
  6064. handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL);
  6065. break;
  6066. case ParsedAttr::AT_ReqdWorkGroupSize:
  6067. handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL);
  6068. break;
  6069. case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize:
  6070. handleSubGroupSize(S, D, AL);
  6071. break;
  6072. case ParsedAttr::AT_VecTypeHint:
  6073. handleVecTypeHint(S, D, AL);
  6074. break;
  6075. case ParsedAttr::AT_RequireConstantInit:
  6076. handleSimpleAttribute<RequireConstantInitAttr>(S, D, AL);
  6077. break;
  6078. case ParsedAttr::AT_InitPriority:
  6079. handleInitPriorityAttr(S, D, AL);
  6080. break;
  6081. case ParsedAttr::AT_Packed:
  6082. handlePackedAttr(S, D, AL);
  6083. break;
  6084. case ParsedAttr::AT_Section:
  6085. handleSectionAttr(S, D, AL);
  6086. break;
  6087. case ParsedAttr::AT_SpeculativeLoadHardening:
  6088. handleSimpleAttributeWithExclusions<SpeculativeLoadHardeningAttr,
  6089. NoSpeculativeLoadHardeningAttr>(S, D,
  6090. AL);
  6091. break;
  6092. case ParsedAttr::AT_NoSpeculativeLoadHardening:
  6093. handleSimpleAttributeWithExclusions<NoSpeculativeLoadHardeningAttr,
  6094. SpeculativeLoadHardeningAttr>(S, D, AL);
  6095. break;
  6096. case ParsedAttr::AT_CodeSeg:
  6097. handleCodeSegAttr(S, D, AL);
  6098. break;
  6099. case ParsedAttr::AT_Target:
  6100. handleTargetAttr(S, D, AL);
  6101. break;
  6102. case ParsedAttr::AT_MinVectorWidth:
  6103. handleMinVectorWidthAttr(S, D, AL);
  6104. break;
  6105. case ParsedAttr::AT_Unavailable:
  6106. handleAttrWithMessage<UnavailableAttr>(S, D, AL);
  6107. break;
  6108. case ParsedAttr::AT_ArcWeakrefUnavailable:
  6109. handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, AL);
  6110. break;
  6111. case ParsedAttr::AT_ObjCRootClass:
  6112. handleSimpleAttribute<ObjCRootClassAttr>(S, D, AL);
  6113. break;
  6114. case ParsedAttr::AT_ObjCNonLazyClass:
  6115. handleSimpleAttribute<ObjCNonLazyClassAttr>(S, D, AL);
  6116. break;
  6117. case ParsedAttr::AT_ObjCSubclassingRestricted:
  6118. handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, AL);
  6119. break;
  6120. case ParsedAttr::AT_ObjCExplicitProtocolImpl:
  6121. handleObjCSuppresProtocolAttr(S, D, AL);
  6122. break;
  6123. case ParsedAttr::AT_ObjCRequiresPropertyDefs:
  6124. handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, AL);
  6125. break;
  6126. case ParsedAttr::AT_Unused:
  6127. handleUnusedAttr(S, D, AL);
  6128. break;
  6129. case ParsedAttr::AT_ReturnsTwice:
  6130. handleSimpleAttribute<ReturnsTwiceAttr>(S, D, AL);
  6131. break;
  6132. case ParsedAttr::AT_NotTailCalled:
  6133. handleSimpleAttributeWithExclusions<NotTailCalledAttr, AlwaysInlineAttr>(
  6134. S, D, AL);
  6135. break;
  6136. case ParsedAttr::AT_DisableTailCalls:
  6137. handleSimpleAttributeWithExclusions<DisableTailCallsAttr, NakedAttr>(S, D,
  6138. AL);
  6139. break;
  6140. case ParsedAttr::AT_Used:
  6141. handleSimpleAttribute<UsedAttr>(S, D, AL);
  6142. break;
  6143. case ParsedAttr::AT_Visibility:
  6144. handleVisibilityAttr(S, D, AL, false);
  6145. break;
  6146. case ParsedAttr::AT_TypeVisibility:
  6147. handleVisibilityAttr(S, D, AL, true);
  6148. break;
  6149. case ParsedAttr::AT_WarnUnused:
  6150. handleSimpleAttribute<WarnUnusedAttr>(S, D, AL);
  6151. break;
  6152. case ParsedAttr::AT_WarnUnusedResult:
  6153. handleWarnUnusedResult(S, D, AL);
  6154. break;
  6155. case ParsedAttr::AT_Weak:
  6156. handleSimpleAttribute<WeakAttr>(S, D, AL);
  6157. break;
  6158. case ParsedAttr::AT_WeakRef:
  6159. handleWeakRefAttr(S, D, AL);
  6160. break;
  6161. case ParsedAttr::AT_WeakImport:
  6162. handleWeakImportAttr(S, D, AL);
  6163. break;
  6164. case ParsedAttr::AT_TransparentUnion:
  6165. handleTransparentUnionAttr(S, D, AL);
  6166. break;
  6167. case ParsedAttr::AT_ObjCException:
  6168. handleSimpleAttribute<ObjCExceptionAttr>(S, D, AL);
  6169. break;
  6170. case ParsedAttr::AT_ObjCMethodFamily:
  6171. handleObjCMethodFamilyAttr(S, D, AL);
  6172. break;
  6173. case ParsedAttr::AT_ObjCNSObject:
  6174. handleObjCNSObject(S, D, AL);
  6175. break;
  6176. case ParsedAttr::AT_ObjCIndependentClass:
  6177. handleObjCIndependentClass(S, D, AL);
  6178. break;
  6179. case ParsedAttr::AT_Blocks:
  6180. handleBlocksAttr(S, D, AL);
  6181. break;
  6182. case ParsedAttr::AT_Sentinel:
  6183. handleSentinelAttr(S, D, AL);
  6184. break;
  6185. case ParsedAttr::AT_Const:
  6186. handleSimpleAttribute<ConstAttr>(S, D, AL);
  6187. break;
  6188. case ParsedAttr::AT_Pure:
  6189. handleSimpleAttribute<PureAttr>(S, D, AL);
  6190. break;
  6191. case ParsedAttr::AT_Cleanup:
  6192. handleCleanupAttr(S, D, AL);
  6193. break;
  6194. case ParsedAttr::AT_NoDebug:
  6195. handleNoDebugAttr(S, D, AL);
  6196. break;
  6197. case ParsedAttr::AT_NoDuplicate:
  6198. handleSimpleAttribute<NoDuplicateAttr>(S, D, AL);
  6199. break;
  6200. case ParsedAttr::AT_Convergent:
  6201. handleSimpleAttribute<ConvergentAttr>(S, D, AL);
  6202. break;
  6203. case ParsedAttr::AT_NoInline:
  6204. handleSimpleAttribute<NoInlineAttr>(S, D, AL);
  6205. break;
  6206. case ParsedAttr::AT_NoInstrumentFunction: // Interacts with -pg.
  6207. handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, AL);
  6208. break;
  6209. case ParsedAttr::AT_NoStackProtector:
  6210. // Interacts with -fstack-protector options.
  6211. handleSimpleAttribute<NoStackProtectorAttr>(S, D, AL);
  6212. break;
  6213. case ParsedAttr::AT_StdCall:
  6214. case ParsedAttr::AT_CDecl:
  6215. case ParsedAttr::AT_FastCall:
  6216. case ParsedAttr::AT_ThisCall:
  6217. case ParsedAttr::AT_Pascal:
  6218. case ParsedAttr::AT_RegCall:
  6219. case ParsedAttr::AT_SwiftCall:
  6220. case ParsedAttr::AT_VectorCall:
  6221. case ParsedAttr::AT_MSABI:
  6222. case ParsedAttr::AT_SysVABI:
  6223. case ParsedAttr::AT_Pcs:
  6224. case ParsedAttr::AT_IntelOclBicc:
  6225. case ParsedAttr::AT_PreserveMost:
  6226. case ParsedAttr::AT_PreserveAll:
  6227. case ParsedAttr::AT_AArch64VectorPcs:
  6228. handleCallConvAttr(S, D, AL);
  6229. break;
  6230. case ParsedAttr::AT_Suppress:
  6231. handleSuppressAttr(S, D, AL);
  6232. break;
  6233. case ParsedAttr::AT_OpenCLKernel:
  6234. handleSimpleAttribute<OpenCLKernelAttr>(S, D, AL);
  6235. break;
  6236. case ParsedAttr::AT_OpenCLAccess:
  6237. handleOpenCLAccessAttr(S, D, AL);
  6238. break;
  6239. case ParsedAttr::AT_OpenCLNoSVM:
  6240. handleOpenCLNoSVMAttr(S, D, AL);
  6241. break;
  6242. case ParsedAttr::AT_SwiftContext:
  6243. handleParameterABIAttr(S, D, AL, ParameterABI::SwiftContext);
  6244. break;
  6245. case ParsedAttr::AT_SwiftErrorResult:
  6246. handleParameterABIAttr(S, D, AL, ParameterABI::SwiftErrorResult);
  6247. break;
  6248. case ParsedAttr::AT_SwiftIndirectResult:
  6249. handleParameterABIAttr(S, D, AL, ParameterABI::SwiftIndirectResult);
  6250. break;
  6251. case ParsedAttr::AT_InternalLinkage:
  6252. handleInternalLinkageAttr(S, D, AL);
  6253. break;
  6254. case ParsedAttr::AT_ExcludeFromExplicitInstantiation:
  6255. handleSimpleAttribute<ExcludeFromExplicitInstantiationAttr>(S, D, AL);
  6256. break;
  6257. case ParsedAttr::AT_LTOVisibilityPublic:
  6258. handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, AL);
  6259. break;
  6260. // Microsoft attributes:
  6261. case ParsedAttr::AT_EmptyBases:
  6262. handleSimpleAttribute<EmptyBasesAttr>(S, D, AL);
  6263. break;
  6264. case ParsedAttr::AT_LayoutVersion:
  6265. handleLayoutVersion(S, D, AL);
  6266. break;
  6267. case ParsedAttr::AT_TrivialABI:
  6268. handleSimpleAttribute<TrivialABIAttr>(S, D, AL);
  6269. break;
  6270. case ParsedAttr::AT_MSNoVTable:
  6271. handleSimpleAttribute<MSNoVTableAttr>(S, D, AL);
  6272. break;
  6273. case ParsedAttr::AT_MSStruct:
  6274. handleSimpleAttribute<MSStructAttr>(S, D, AL);
  6275. break;
  6276. case ParsedAttr::AT_Uuid:
  6277. handleUuidAttr(S, D, AL);
  6278. break;
  6279. case ParsedAttr::AT_MSInheritance:
  6280. handleMSInheritanceAttr(S, D, AL);
  6281. break;
  6282. case ParsedAttr::AT_SelectAny:
  6283. handleSimpleAttribute<SelectAnyAttr>(S, D, AL);
  6284. break;
  6285. case ParsedAttr::AT_Thread:
  6286. handleDeclspecThreadAttr(S, D, AL);
  6287. break;
  6288. case ParsedAttr::AT_AbiTag:
  6289. handleAbiTagAttr(S, D, AL);
  6290. break;
  6291. // Thread safety attributes:
  6292. case ParsedAttr::AT_AssertExclusiveLock:
  6293. handleAssertExclusiveLockAttr(S, D, AL);
  6294. break;
  6295. case ParsedAttr::AT_AssertSharedLock:
  6296. handleAssertSharedLockAttr(S, D, AL);
  6297. break;
  6298. case ParsedAttr::AT_GuardedVar:
  6299. handleSimpleAttribute<GuardedVarAttr>(S, D, AL);
  6300. break;
  6301. case ParsedAttr::AT_PtGuardedVar:
  6302. handlePtGuardedVarAttr(S, D, AL);
  6303. break;
  6304. case ParsedAttr::AT_ScopedLockable:
  6305. handleSimpleAttribute<ScopedLockableAttr>(S, D, AL);
  6306. break;
  6307. case ParsedAttr::AT_NoSanitize:
  6308. handleNoSanitizeAttr(S, D, AL);
  6309. break;
  6310. case ParsedAttr::AT_NoSanitizeSpecific:
  6311. handleNoSanitizeSpecificAttr(S, D, AL);
  6312. break;
  6313. case ParsedAttr::AT_NoThreadSafetyAnalysis:
  6314. handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, AL);
  6315. break;
  6316. case ParsedAttr::AT_GuardedBy:
  6317. handleGuardedByAttr(S, D, AL);
  6318. break;
  6319. case ParsedAttr::AT_PtGuardedBy:
  6320. handlePtGuardedByAttr(S, D, AL);
  6321. break;
  6322. case ParsedAttr::AT_ExclusiveTrylockFunction:
  6323. handleExclusiveTrylockFunctionAttr(S, D, AL);
  6324. break;
  6325. case ParsedAttr::AT_LockReturned:
  6326. handleLockReturnedAttr(S, D, AL);
  6327. break;
  6328. case ParsedAttr::AT_LocksExcluded:
  6329. handleLocksExcludedAttr(S, D, AL);
  6330. break;
  6331. case ParsedAttr::AT_SharedTrylockFunction:
  6332. handleSharedTrylockFunctionAttr(S, D, AL);
  6333. break;
  6334. case ParsedAttr::AT_AcquiredBefore:
  6335. handleAcquiredBeforeAttr(S, D, AL);
  6336. break;
  6337. case ParsedAttr::AT_AcquiredAfter:
  6338. handleAcquiredAfterAttr(S, D, AL);
  6339. break;
  6340. // Capability analysis attributes.
  6341. case ParsedAttr::AT_Capability:
  6342. case ParsedAttr::AT_Lockable:
  6343. handleCapabilityAttr(S, D, AL);
  6344. break;
  6345. case ParsedAttr::AT_RequiresCapability:
  6346. handleRequiresCapabilityAttr(S, D, AL);
  6347. break;
  6348. case ParsedAttr::AT_AssertCapability:
  6349. handleAssertCapabilityAttr(S, D, AL);
  6350. break;
  6351. case ParsedAttr::AT_AcquireCapability:
  6352. handleAcquireCapabilityAttr(S, D, AL);
  6353. break;
  6354. case ParsedAttr::AT_ReleaseCapability:
  6355. handleReleaseCapabilityAttr(S, D, AL);
  6356. break;
  6357. case ParsedAttr::AT_TryAcquireCapability:
  6358. handleTryAcquireCapabilityAttr(S, D, AL);
  6359. break;
  6360. // Consumed analysis attributes.
  6361. case ParsedAttr::AT_Consumable:
  6362. handleConsumableAttr(S, D, AL);
  6363. break;
  6364. case ParsedAttr::AT_ConsumableAutoCast:
  6365. handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, AL);
  6366. break;
  6367. case ParsedAttr::AT_ConsumableSetOnRead:
  6368. handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, AL);
  6369. break;
  6370. case ParsedAttr::AT_CallableWhen:
  6371. handleCallableWhenAttr(S, D, AL);
  6372. break;
  6373. case ParsedAttr::AT_ParamTypestate:
  6374. handleParamTypestateAttr(S, D, AL);
  6375. break;
  6376. case ParsedAttr::AT_ReturnTypestate:
  6377. handleReturnTypestateAttr(S, D, AL);
  6378. break;
  6379. case ParsedAttr::AT_SetTypestate:
  6380. handleSetTypestateAttr(S, D, AL);
  6381. break;
  6382. case ParsedAttr::AT_TestTypestate:
  6383. handleTestTypestateAttr(S, D, AL);
  6384. break;
  6385. // Type safety attributes.
  6386. case ParsedAttr::AT_ArgumentWithTypeTag:
  6387. handleArgumentWithTypeTagAttr(S, D, AL);
  6388. break;
  6389. case ParsedAttr::AT_TypeTagForDatatype:
  6390. handleTypeTagForDatatypeAttr(S, D, AL);
  6391. break;
  6392. case ParsedAttr::AT_AnyX86NoCallerSavedRegisters:
  6393. handleSimpleAttribute<AnyX86NoCallerSavedRegistersAttr>(S, D, AL);
  6394. break;
  6395. case ParsedAttr::AT_RenderScriptKernel:
  6396. handleSimpleAttribute<RenderScriptKernelAttr>(S, D, AL);
  6397. break;
  6398. // XRay attributes.
  6399. case ParsedAttr::AT_XRayInstrument:
  6400. handleSimpleAttribute<XRayInstrumentAttr>(S, D, AL);
  6401. break;
  6402. case ParsedAttr::AT_XRayLogArgs:
  6403. handleXRayLogArgsAttr(S, D, AL);
  6404. break;
  6405. // Move semantics attribute.
  6406. case ParsedAttr::AT_Reinitializes:
  6407. handleSimpleAttribute<ReinitializesAttr>(S, D, AL);
  6408. break;
  6409. case ParsedAttr::AT_AlwaysDestroy:
  6410. case ParsedAttr::AT_NoDestroy:
  6411. handleDestroyAttr(S, D, AL);
  6412. break;
  6413. case ParsedAttr::AT_Uninitialized:
  6414. handleUninitializedAttr(S, D, AL);
  6415. break;
  6416. case ParsedAttr::AT_ObjCExternallyRetained:
  6417. handleObjCExternallyRetainedAttr(S, D, AL);
  6418. break;
  6419. case ParsedAttr::AT_FortifyStdLib:
  6420. handleFortifyStdLib(S, D, AL);
  6421. break;
  6422. case ParsedAttr::AT_MIGServerRoutine:
  6423. handleMIGServerRoutineAttr(S, D, AL);
  6424. break;
  6425. }
  6426. }
  6427. /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
  6428. /// attribute list to the specified decl, ignoring any type attributes.
  6429. void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
  6430. const ParsedAttributesView &AttrList,
  6431. bool IncludeCXX11Attributes) {
  6432. if (AttrList.empty())
  6433. return;
  6434. for (const ParsedAttr &AL : AttrList)
  6435. ProcessDeclAttribute(*this, S, D, AL, IncludeCXX11Attributes);
  6436. // FIXME: We should be able to handle these cases in TableGen.
  6437. // GCC accepts
  6438. // static int a9 __attribute__((weakref));
  6439. // but that looks really pointless. We reject it.
  6440. if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
  6441. Diag(AttrList.begin()->getLoc(), diag::err_attribute_weakref_without_alias)
  6442. << cast<NamedDecl>(D);
  6443. D->dropAttr<WeakRefAttr>();
  6444. return;
  6445. }
  6446. // FIXME: We should be able to handle this in TableGen as well. It would be
  6447. // good to have a way to specify "these attributes must appear as a group",
  6448. // for these. Additionally, it would be good to have a way to specify "these
  6449. // attribute must never appear as a group" for attributes like cold and hot.
  6450. if (!D->hasAttr<OpenCLKernelAttr>()) {
  6451. // These attributes cannot be applied to a non-kernel function.
  6452. if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
  6453. // FIXME: This emits a different error message than
  6454. // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
  6455. Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
  6456. D->setInvalidDecl();
  6457. } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) {
  6458. Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
  6459. D->setInvalidDecl();
  6460. } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) {
  6461. Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
  6462. D->setInvalidDecl();
  6463. } else if (const auto *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
  6464. Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
  6465. D->setInvalidDecl();
  6466. } else if (!D->hasAttr<CUDAGlobalAttr>()) {
  6467. if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
  6468. Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
  6469. << A << ExpectedKernelFunction;
  6470. D->setInvalidDecl();
  6471. } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
  6472. Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
  6473. << A << ExpectedKernelFunction;
  6474. D->setInvalidDecl();
  6475. } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
  6476. Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
  6477. << A << ExpectedKernelFunction;
  6478. D->setInvalidDecl();
  6479. } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
  6480. Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
  6481. << A << ExpectedKernelFunction;
  6482. D->setInvalidDecl();
  6483. }
  6484. }
  6485. }
  6486. // Do this check after processing D's attributes because the attribute
  6487. // objc_method_family can change whether the given method is in the init
  6488. // family, and it can be applied after objc_designated_initializer. This is a
  6489. // bit of a hack, but we need it to be compatible with versions of clang that
  6490. // processed the attribute list in the wrong order.
  6491. if (D->hasAttr<ObjCDesignatedInitializerAttr>() &&
  6492. cast<ObjCMethodDecl>(D)->getMethodFamily() != OMF_init) {
  6493. Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
  6494. D->dropAttr<ObjCDesignatedInitializerAttr>();
  6495. }
  6496. }
  6497. // Helper for delayed processing TransparentUnion attribute.
  6498. void Sema::ProcessDeclAttributeDelayed(Decl *D,
  6499. const ParsedAttributesView &AttrList) {
  6500. for (const ParsedAttr &AL : AttrList)
  6501. if (AL.getKind() == ParsedAttr::AT_TransparentUnion) {
  6502. handleTransparentUnionAttr(*this, D, AL);
  6503. break;
  6504. }
  6505. }
  6506. // Annotation attributes are the only attributes allowed after an access
  6507. // specifier.
  6508. bool Sema::ProcessAccessDeclAttributeList(
  6509. AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) {
  6510. for (const ParsedAttr &AL : AttrList) {
  6511. if (AL.getKind() == ParsedAttr::AT_Annotate) {
  6512. ProcessDeclAttribute(*this, nullptr, ASDecl, AL, AL.isCXX11Attribute());
  6513. } else {
  6514. Diag(AL.getLoc(), diag::err_only_annotate_after_access_spec);
  6515. return true;
  6516. }
  6517. }
  6518. return false;
  6519. }
  6520. /// checkUnusedDeclAttributes - Check a list of attributes to see if it
  6521. /// contains any decl attributes that we should warn about.
  6522. static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) {
  6523. for (const ParsedAttr &AL : A) {
  6524. // Only warn if the attribute is an unignored, non-type attribute.
  6525. if (AL.isUsedAsTypeAttr() || AL.isInvalid())
  6526. continue;
  6527. if (AL.getKind() == ParsedAttr::IgnoredAttribute)
  6528. continue;
  6529. if (AL.getKind() == ParsedAttr::UnknownAttribute) {
  6530. S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
  6531. << AL << AL.getRange();
  6532. } else {
  6533. S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL
  6534. << AL.getRange();
  6535. }
  6536. }
  6537. }
  6538. /// checkUnusedDeclAttributes - Given a declarator which is not being
  6539. /// used to build a declaration, complain about any decl attributes
  6540. /// which might be lying around on it.
  6541. void Sema::checkUnusedDeclAttributes(Declarator &D) {
  6542. ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes());
  6543. ::checkUnusedDeclAttributes(*this, D.getAttributes());
  6544. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
  6545. ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
  6546. }
  6547. /// DeclClonePragmaWeak - clone existing decl (maybe definition),
  6548. /// \#pragma weak needs a non-definition decl and source may not have one.
  6549. NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
  6550. SourceLocation Loc) {
  6551. assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
  6552. NamedDecl *NewD = nullptr;
  6553. if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
  6554. FunctionDecl *NewFD;
  6555. // FIXME: Missing call to CheckFunctionDeclaration().
  6556. // FIXME: Mangling?
  6557. // FIXME: Is the qualifier info correct?
  6558. // FIXME: Is the DeclContext correct?
  6559. NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
  6560. Loc, Loc, DeclarationName(II),
  6561. FD->getType(), FD->getTypeSourceInfo(),
  6562. SC_None, false/*isInlineSpecified*/,
  6563. FD->hasPrototype(),
  6564. false/*isConstexprSpecified*/);
  6565. NewD = NewFD;
  6566. if (FD->getQualifier())
  6567. NewFD->setQualifierInfo(FD->getQualifierLoc());
  6568. // Fake up parameter variables; they are declared as if this were
  6569. // a typedef.
  6570. QualType FDTy = FD->getType();
  6571. if (const auto *FT = FDTy->getAs<FunctionProtoType>()) {
  6572. SmallVector<ParmVarDecl*, 16> Params;
  6573. for (const auto &AI : FT->param_types()) {
  6574. ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
  6575. Param->setScopeInfo(0, Params.size());
  6576. Params.push_back(Param);
  6577. }
  6578. NewFD->setParams(Params);
  6579. }
  6580. } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
  6581. NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
  6582. VD->getInnerLocStart(), VD->getLocation(), II,
  6583. VD->getType(), VD->getTypeSourceInfo(),
  6584. VD->getStorageClass());
  6585. if (VD->getQualifier())
  6586. cast<VarDecl>(NewD)->setQualifierInfo(VD->getQualifierLoc());
  6587. }
  6588. return NewD;
  6589. }
  6590. /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
  6591. /// applied to it, possibly with an alias.
  6592. void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
  6593. if (W.getUsed()) return; // only do this once
  6594. W.setUsed(true);
  6595. if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
  6596. IdentifierInfo *NDId = ND->getIdentifier();
  6597. NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
  6598. NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
  6599. W.getLocation()));
  6600. NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
  6601. WeakTopLevelDecl.push_back(NewD);
  6602. // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
  6603. // to insert Decl at TU scope, sorry.
  6604. DeclContext *SavedContext = CurContext;
  6605. CurContext = Context.getTranslationUnitDecl();
  6606. NewD->setDeclContext(CurContext);
  6607. NewD->setLexicalDeclContext(CurContext);
  6608. PushOnScopeChains(NewD, S);
  6609. CurContext = SavedContext;
  6610. } else { // just add weak to existing
  6611. ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
  6612. }
  6613. }
  6614. void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
  6615. // It's valid to "forward-declare" #pragma weak, in which case we
  6616. // have to do this.
  6617. LoadExternalWeakUndeclaredIdentifiers();
  6618. if (!WeakUndeclaredIdentifiers.empty()) {
  6619. NamedDecl *ND = nullptr;
  6620. if (auto *VD = dyn_cast<VarDecl>(D))
  6621. if (VD->isExternC())
  6622. ND = VD;
  6623. if (auto *FD = dyn_cast<FunctionDecl>(D))
  6624. if (FD->isExternC())
  6625. ND = FD;
  6626. if (ND) {
  6627. if (IdentifierInfo *Id = ND->getIdentifier()) {
  6628. auto I = WeakUndeclaredIdentifiers.find(Id);
  6629. if (I != WeakUndeclaredIdentifiers.end()) {
  6630. WeakInfo W = I->second;
  6631. DeclApplyPragmaWeak(S, ND, W);
  6632. WeakUndeclaredIdentifiers[Id] = W;
  6633. }
  6634. }
  6635. }
  6636. }
  6637. }
  6638. /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
  6639. /// it, apply them to D. This is a bit tricky because PD can have attributes
  6640. /// specified in many different places, and we need to find and apply them all.
  6641. void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
  6642. // Apply decl attributes from the DeclSpec if present.
  6643. if (!PD.getDeclSpec().getAttributes().empty())
  6644. ProcessDeclAttributeList(S, D, PD.getDeclSpec().getAttributes());
  6645. // Walk the declarator structure, applying decl attributes that were in a type
  6646. // position to the decl itself. This handles cases like:
  6647. // int *__attr__(x)** D;
  6648. // when X is a decl attribute.
  6649. for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
  6650. ProcessDeclAttributeList(S, D, PD.getTypeObject(i).getAttrs(),
  6651. /*IncludeCXX11Attributes=*/false);
  6652. // Finally, apply any attributes on the decl itself.
  6653. ProcessDeclAttributeList(S, D, PD.getAttributes());
  6654. // Apply additional attributes specified by '#pragma clang attribute'.
  6655. AddPragmaAttributes(S, D);
  6656. }
  6657. /// Is the given declaration allowed to use a forbidden type?
  6658. /// If so, it'll still be annotated with an attribute that makes it
  6659. /// illegal to actually use.
  6660. static bool isForbiddenTypeAllowed(Sema &S, Decl *D,
  6661. const DelayedDiagnostic &diag,
  6662. UnavailableAttr::ImplicitReason &reason) {
  6663. // Private ivars are always okay. Unfortunately, people don't
  6664. // always properly make their ivars private, even in system headers.
  6665. // Plus we need to make fields okay, too.
  6666. if (!isa<FieldDecl>(D) && !isa<ObjCPropertyDecl>(D) &&
  6667. !isa<FunctionDecl>(D))
  6668. return false;
  6669. // Silently accept unsupported uses of __weak in both user and system
  6670. // declarations when it's been disabled, for ease of integration with
  6671. // -fno-objc-arc files. We do have to take some care against attempts
  6672. // to define such things; for now, we've only done that for ivars
  6673. // and properties.
  6674. if ((isa<ObjCIvarDecl>(D) || isa<ObjCPropertyDecl>(D))) {
  6675. if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
  6676. diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
  6677. reason = UnavailableAttr::IR_ForbiddenWeak;
  6678. return true;
  6679. }
  6680. }
  6681. // Allow all sorts of things in system headers.
  6682. if (S.Context.getSourceManager().isInSystemHeader(D->getLocation())) {
  6683. // Currently, all the failures dealt with this way are due to ARC
  6684. // restrictions.
  6685. reason = UnavailableAttr::IR_ARCForbiddenType;
  6686. return true;
  6687. }
  6688. return false;
  6689. }
  6690. /// Handle a delayed forbidden-type diagnostic.
  6691. static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD,
  6692. Decl *D) {
  6693. auto Reason = UnavailableAttr::IR_None;
  6694. if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) {
  6695. assert(Reason && "didn't set reason?");
  6696. D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc));
  6697. return;
  6698. }
  6699. if (S.getLangOpts().ObjCAutoRefCount)
  6700. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  6701. // FIXME: we may want to suppress diagnostics for all
  6702. // kind of forbidden type messages on unavailable functions.
  6703. if (FD->hasAttr<UnavailableAttr>() &&
  6704. DD.getForbiddenTypeDiagnostic() ==
  6705. diag::err_arc_array_param_no_ownership) {
  6706. DD.Triggered = true;
  6707. return;
  6708. }
  6709. }
  6710. S.Diag(DD.Loc, DD.getForbiddenTypeDiagnostic())
  6711. << DD.getForbiddenTypeOperand() << DD.getForbiddenTypeArgument();
  6712. DD.Triggered = true;
  6713. }
  6714. static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
  6715. const Decl *D) {
  6716. // Check each AvailabilityAttr to find the one for this platform.
  6717. for (const auto *A : D->attrs()) {
  6718. if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
  6719. // FIXME: this is copied from CheckAvailability. We should try to
  6720. // de-duplicate.
  6721. // Check if this is an App Extension "platform", and if so chop off
  6722. // the suffix for matching with the actual platform.
  6723. StringRef ActualPlatform = Avail->getPlatform()->getName();
  6724. StringRef RealizedPlatform = ActualPlatform;
  6725. if (Context.getLangOpts().AppExt) {
  6726. size_t suffix = RealizedPlatform.rfind("_app_extension");
  6727. if (suffix != StringRef::npos)
  6728. RealizedPlatform = RealizedPlatform.slice(0, suffix);
  6729. }
  6730. StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
  6731. // Match the platform name.
  6732. if (RealizedPlatform == TargetPlatform)
  6733. return Avail;
  6734. }
  6735. }
  6736. return nullptr;
  6737. }
  6738. /// The diagnostic we should emit for \c D, and the declaration that
  6739. /// originated it, or \c AR_Available.
  6740. ///
  6741. /// \param D The declaration to check.
  6742. /// \param Message If non-null, this will be populated with the message from
  6743. /// the availability attribute that is selected.
  6744. /// \param ClassReceiver If we're checking the the method of a class message
  6745. /// send, the class. Otherwise nullptr.
  6746. static std::pair<AvailabilityResult, const NamedDecl *>
  6747. ShouldDiagnoseAvailabilityOfDecl(Sema &S, const NamedDecl *D,
  6748. std::string *Message,
  6749. ObjCInterfaceDecl *ClassReceiver) {
  6750. AvailabilityResult Result = D->getAvailability(Message);
  6751. // For typedefs, if the typedef declaration appears available look
  6752. // to the underlying type to see if it is more restrictive.
  6753. while (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  6754. if (Result == AR_Available) {
  6755. if (const auto *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  6756. D = TT->getDecl();
  6757. Result = D->getAvailability(Message);
  6758. continue;
  6759. }
  6760. }
  6761. break;
  6762. }
  6763. // Forward class declarations get their attributes from their definition.
  6764. if (const auto *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
  6765. if (IDecl->getDefinition()) {
  6766. D = IDecl->getDefinition();
  6767. Result = D->getAvailability(Message);
  6768. }
  6769. }
  6770. if (const auto *ECD = dyn_cast<EnumConstantDecl>(D))
  6771. if (Result == AR_Available) {
  6772. const DeclContext *DC = ECD->getDeclContext();
  6773. if (const auto *TheEnumDecl = dyn_cast<EnumDecl>(DC)) {
  6774. Result = TheEnumDecl->getAvailability(Message);
  6775. D = TheEnumDecl;
  6776. }
  6777. }
  6778. // For +new, infer availability from -init.
  6779. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
  6780. if (S.NSAPIObj && ClassReceiver) {
  6781. ObjCMethodDecl *Init = ClassReceiver->lookupInstanceMethod(
  6782. S.NSAPIObj->getInitSelector());
  6783. if (Init && Result == AR_Available && MD->isClassMethod() &&
  6784. MD->getSelector() == S.NSAPIObj->getNewSelector() &&
  6785. MD->definedInNSObject(S.getASTContext())) {
  6786. Result = Init->getAvailability(Message);
  6787. D = Init;
  6788. }
  6789. }
  6790. }
  6791. return {Result, D};
  6792. }
  6793. /// whether we should emit a diagnostic for \c K and \c DeclVersion in
  6794. /// the context of \c Ctx. For example, we should emit an unavailable diagnostic
  6795. /// in a deprecated context, but not the other way around.
  6796. static bool
  6797. ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K,
  6798. VersionTuple DeclVersion, Decl *Ctx,
  6799. const NamedDecl *OffendingDecl) {
  6800. assert(K != AR_Available && "Expected an unavailable declaration here!");
  6801. // Checks if we should emit the availability diagnostic in the context of C.
  6802. auto CheckContext = [&](const Decl *C) {
  6803. if (K == AR_NotYetIntroduced) {
  6804. if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C))
  6805. if (AA->getIntroduced() >= DeclVersion)
  6806. return true;
  6807. } else if (K == AR_Deprecated) {
  6808. if (C->isDeprecated())
  6809. return true;
  6810. } else if (K == AR_Unavailable) {
  6811. // It is perfectly fine to refer to an 'unavailable' Objective-C method
  6812. // when it is referenced from within the @implementation itself. In this
  6813. // context, we interpret unavailable as a form of access control.
  6814. if (const auto *MD = dyn_cast<ObjCMethodDecl>(OffendingDecl)) {
  6815. if (const auto *Impl = dyn_cast<ObjCImplDecl>(C)) {
  6816. if (MD->getClassInterface() == Impl->getClassInterface())
  6817. return true;
  6818. }
  6819. }
  6820. }
  6821. if (C->isUnavailable())
  6822. return true;
  6823. return false;
  6824. };
  6825. do {
  6826. if (CheckContext(Ctx))
  6827. return false;
  6828. // An implementation implicitly has the availability of the interface.
  6829. // Unless it is "+load" method.
  6830. if (const auto *MethodD = dyn_cast<ObjCMethodDecl>(Ctx))
  6831. if (MethodD->isClassMethod() &&
  6832. MethodD->getSelector().getAsString() == "load")
  6833. return true;
  6834. if (const auto *CatOrImpl = dyn_cast<ObjCImplDecl>(Ctx)) {
  6835. if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
  6836. if (CheckContext(Interface))
  6837. return false;
  6838. }
  6839. // A category implicitly has the availability of the interface.
  6840. else if (const auto *CatD = dyn_cast<ObjCCategoryDecl>(Ctx))
  6841. if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
  6842. if (CheckContext(Interface))
  6843. return false;
  6844. } while ((Ctx = cast_or_null<Decl>(Ctx->getDeclContext())));
  6845. return true;
  6846. }
  6847. static bool
  6848. shouldDiagnoseAvailabilityByDefault(const ASTContext &Context,
  6849. const VersionTuple &DeploymentVersion,
  6850. const VersionTuple &DeclVersion) {
  6851. const auto &Triple = Context.getTargetInfo().getTriple();
  6852. VersionTuple ForceAvailabilityFromVersion;
  6853. switch (Triple.getOS()) {
  6854. case llvm::Triple::IOS:
  6855. case llvm::Triple::TvOS:
  6856. ForceAvailabilityFromVersion = VersionTuple(/*Major=*/11);
  6857. break;
  6858. case llvm::Triple::WatchOS:
  6859. ForceAvailabilityFromVersion = VersionTuple(/*Major=*/4);
  6860. break;
  6861. case llvm::Triple::Darwin:
  6862. case llvm::Triple::MacOSX:
  6863. ForceAvailabilityFromVersion = VersionTuple(/*Major=*/10, /*Minor=*/13);
  6864. break;
  6865. default:
  6866. // New targets should always warn about availability.
  6867. return Triple.getVendor() == llvm::Triple::Apple;
  6868. }
  6869. return DeploymentVersion >= ForceAvailabilityFromVersion ||
  6870. DeclVersion >= ForceAvailabilityFromVersion;
  6871. }
  6872. static NamedDecl *findEnclosingDeclToAnnotate(Decl *OrigCtx) {
  6873. for (Decl *Ctx = OrigCtx; Ctx;
  6874. Ctx = cast_or_null<Decl>(Ctx->getDeclContext())) {
  6875. if (isa<TagDecl>(Ctx) || isa<FunctionDecl>(Ctx) || isa<ObjCMethodDecl>(Ctx))
  6876. return cast<NamedDecl>(Ctx);
  6877. if (auto *CD = dyn_cast<ObjCContainerDecl>(Ctx)) {
  6878. if (auto *Imp = dyn_cast<ObjCImplDecl>(Ctx))
  6879. return Imp->getClassInterface();
  6880. return CD;
  6881. }
  6882. }
  6883. return dyn_cast<NamedDecl>(OrigCtx);
  6884. }
  6885. namespace {
  6886. struct AttributeInsertion {
  6887. StringRef Prefix;
  6888. SourceLocation Loc;
  6889. StringRef Suffix;
  6890. static AttributeInsertion createInsertionAfter(const NamedDecl *D) {
  6891. return {" ", D->getEndLoc(), ""};
  6892. }
  6893. static AttributeInsertion createInsertionAfter(SourceLocation Loc) {
  6894. return {" ", Loc, ""};
  6895. }
  6896. static AttributeInsertion createInsertionBefore(const NamedDecl *D) {
  6897. return {"", D->getBeginLoc(), "\n"};
  6898. }
  6899. };
  6900. } // end anonymous namespace
  6901. /// Tries to parse a string as ObjC method name.
  6902. ///
  6903. /// \param Name The string to parse. Expected to originate from availability
  6904. /// attribute argument.
  6905. /// \param SlotNames The vector that will be populated with slot names. In case
  6906. /// of unsuccessful parsing can contain invalid data.
  6907. /// \returns A number of method parameters if parsing was successful, None
  6908. /// otherwise.
  6909. static Optional<unsigned>
  6910. tryParseObjCMethodName(StringRef Name, SmallVectorImpl<StringRef> &SlotNames,
  6911. const LangOptions &LangOpts) {
  6912. // Accept replacements starting with - or + as valid ObjC method names.
  6913. if (!Name.empty() && (Name.front() == '-' || Name.front() == '+'))
  6914. Name = Name.drop_front(1);
  6915. if (Name.empty())
  6916. return None;
  6917. Name.split(SlotNames, ':');
  6918. unsigned NumParams;
  6919. if (Name.back() == ':') {
  6920. // Remove an empty string at the end that doesn't represent any slot.
  6921. SlotNames.pop_back();
  6922. NumParams = SlotNames.size();
  6923. } else {
  6924. if (SlotNames.size() != 1)
  6925. // Not a valid method name, just a colon-separated string.
  6926. return None;
  6927. NumParams = 0;
  6928. }
  6929. // Verify all slot names are valid.
  6930. bool AllowDollar = LangOpts.DollarIdents;
  6931. for (StringRef S : SlotNames) {
  6932. if (S.empty())
  6933. continue;
  6934. if (!isValidIdentifier(S, AllowDollar))
  6935. return None;
  6936. }
  6937. return NumParams;
  6938. }
  6939. /// Returns a source location in which it's appropriate to insert a new
  6940. /// attribute for the given declaration \D.
  6941. static Optional<AttributeInsertion>
  6942. createAttributeInsertion(const NamedDecl *D, const SourceManager &SM,
  6943. const LangOptions &LangOpts) {
  6944. if (isa<ObjCPropertyDecl>(D))
  6945. return AttributeInsertion::createInsertionAfter(D);
  6946. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
  6947. if (MD->hasBody())
  6948. return None;
  6949. return AttributeInsertion::createInsertionAfter(D);
  6950. }
  6951. if (const auto *TD = dyn_cast<TagDecl>(D)) {
  6952. SourceLocation Loc =
  6953. Lexer::getLocForEndOfToken(TD->getInnerLocStart(), 0, SM, LangOpts);
  6954. if (Loc.isInvalid())
  6955. return None;
  6956. // Insert after the 'struct'/whatever keyword.
  6957. return AttributeInsertion::createInsertionAfter(Loc);
  6958. }
  6959. return AttributeInsertion::createInsertionBefore(D);
  6960. }
  6961. /// Actually emit an availability diagnostic for a reference to an unavailable
  6962. /// decl.
  6963. ///
  6964. /// \param Ctx The context that the reference occurred in
  6965. /// \param ReferringDecl The exact declaration that was referenced.
  6966. /// \param OffendingDecl A related decl to \c ReferringDecl that has an
  6967. /// availability attribute corresponding to \c K attached to it. Note that this
  6968. /// may not be the same as ReferringDecl, i.e. if an EnumDecl is annotated and
  6969. /// we refer to a member EnumConstantDecl, ReferringDecl is the EnumConstantDecl
  6970. /// and OffendingDecl is the EnumDecl.
  6971. static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
  6972. Decl *Ctx, const NamedDecl *ReferringDecl,
  6973. const NamedDecl *OffendingDecl,
  6974. StringRef Message,
  6975. ArrayRef<SourceLocation> Locs,
  6976. const ObjCInterfaceDecl *UnknownObjCClass,
  6977. const ObjCPropertyDecl *ObjCProperty,
  6978. bool ObjCPropertyAccess) {
  6979. // Diagnostics for deprecated or unavailable.
  6980. unsigned diag, diag_message, diag_fwdclass_message;
  6981. unsigned diag_available_here = diag::note_availability_specified_here;
  6982. SourceLocation NoteLocation = OffendingDecl->getLocation();
  6983. // Matches 'diag::note_property_attribute' options.
  6984. unsigned property_note_select;
  6985. // Matches diag::note_availability_specified_here.
  6986. unsigned available_here_select_kind;
  6987. VersionTuple DeclVersion;
  6988. if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, OffendingDecl))
  6989. DeclVersion = AA->getIntroduced();
  6990. if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx,
  6991. OffendingDecl))
  6992. return;
  6993. SourceLocation Loc = Locs.front();
  6994. // The declaration can have multiple availability attributes, we are looking
  6995. // at one of them.
  6996. const AvailabilityAttr *A = getAttrForPlatform(S.Context, OffendingDecl);
  6997. if (A && A->isInherited()) {
  6998. for (const Decl *Redecl = OffendingDecl->getMostRecentDecl(); Redecl;
  6999. Redecl = Redecl->getPreviousDecl()) {
  7000. const AvailabilityAttr *AForRedecl =
  7001. getAttrForPlatform(S.Context, Redecl);
  7002. if (AForRedecl && !AForRedecl->isInherited()) {
  7003. // If D is a declaration with inherited attributes, the note should
  7004. // point to the declaration with actual attributes.
  7005. NoteLocation = Redecl->getLocation();
  7006. break;
  7007. }
  7008. }
  7009. }
  7010. switch (K) {
  7011. case AR_NotYetIntroduced: {
  7012. // We would like to emit the diagnostic even if -Wunguarded-availability is
  7013. // not specified for deployment targets >= to iOS 11 or equivalent or
  7014. // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or
  7015. // later.
  7016. const AvailabilityAttr *AA =
  7017. getAttrForPlatform(S.getASTContext(), OffendingDecl);
  7018. VersionTuple Introduced = AA->getIntroduced();
  7019. bool UseNewWarning = shouldDiagnoseAvailabilityByDefault(
  7020. S.Context, S.Context.getTargetInfo().getPlatformMinVersion(),
  7021. Introduced);
  7022. unsigned Warning = UseNewWarning ? diag::warn_unguarded_availability_new
  7023. : diag::warn_unguarded_availability;
  7024. std::string PlatformName = AvailabilityAttr::getPrettyPlatformName(
  7025. S.getASTContext().getTargetInfo().getPlatformName());
  7026. S.Diag(Loc, Warning) << OffendingDecl << PlatformName
  7027. << Introduced.getAsString();
  7028. S.Diag(OffendingDecl->getLocation(),
  7029. diag::note_partial_availability_specified_here)
  7030. << OffendingDecl << PlatformName << Introduced.getAsString()
  7031. << S.Context.getTargetInfo().getPlatformMinVersion().getAsString();
  7032. if (const auto *Enclosing = findEnclosingDeclToAnnotate(Ctx)) {
  7033. if (const auto *TD = dyn_cast<TagDecl>(Enclosing))
  7034. if (TD->getDeclName().isEmpty()) {
  7035. S.Diag(TD->getLocation(),
  7036. diag::note_decl_unguarded_availability_silence)
  7037. << /*Anonymous*/ 1 << TD->getKindName();
  7038. return;
  7039. }
  7040. auto FixitNoteDiag =
  7041. S.Diag(Enclosing->getLocation(),
  7042. diag::note_decl_unguarded_availability_silence)
  7043. << /*Named*/ 0 << Enclosing;
  7044. // Don't offer a fixit for declarations with availability attributes.
  7045. if (Enclosing->hasAttr<AvailabilityAttr>())
  7046. return;
  7047. if (!S.getPreprocessor().isMacroDefined("API_AVAILABLE"))
  7048. return;
  7049. Optional<AttributeInsertion> Insertion = createAttributeInsertion(
  7050. Enclosing, S.getSourceManager(), S.getLangOpts());
  7051. if (!Insertion)
  7052. return;
  7053. std::string PlatformName =
  7054. AvailabilityAttr::getPlatformNameSourceSpelling(
  7055. S.getASTContext().getTargetInfo().getPlatformName())
  7056. .lower();
  7057. std::string Introduced =
  7058. OffendingDecl->getVersionIntroduced().getAsString();
  7059. FixitNoteDiag << FixItHint::CreateInsertion(
  7060. Insertion->Loc,
  7061. (llvm::Twine(Insertion->Prefix) + "API_AVAILABLE(" + PlatformName +
  7062. "(" + Introduced + "))" + Insertion->Suffix)
  7063. .str());
  7064. }
  7065. return;
  7066. }
  7067. case AR_Deprecated:
  7068. diag = !ObjCPropertyAccess ? diag::warn_deprecated
  7069. : diag::warn_property_method_deprecated;
  7070. diag_message = diag::warn_deprecated_message;
  7071. diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
  7072. property_note_select = /* deprecated */ 0;
  7073. available_here_select_kind = /* deprecated */ 2;
  7074. if (const auto *AL = OffendingDecl->getAttr<DeprecatedAttr>())
  7075. NoteLocation = AL->getLocation();
  7076. break;
  7077. case AR_Unavailable:
  7078. diag = !ObjCPropertyAccess ? diag::err_unavailable
  7079. : diag::err_property_method_unavailable;
  7080. diag_message = diag::err_unavailable_message;
  7081. diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
  7082. property_note_select = /* unavailable */ 1;
  7083. available_here_select_kind = /* unavailable */ 0;
  7084. if (auto AL = OffendingDecl->getAttr<UnavailableAttr>()) {
  7085. if (AL->isImplicit() && AL->getImplicitReason()) {
  7086. // Most of these failures are due to extra restrictions in ARC;
  7087. // reflect that in the primary diagnostic when applicable.
  7088. auto flagARCError = [&] {
  7089. if (S.getLangOpts().ObjCAutoRefCount &&
  7090. S.getSourceManager().isInSystemHeader(
  7091. OffendingDecl->getLocation()))
  7092. diag = diag::err_unavailable_in_arc;
  7093. };
  7094. switch (AL->getImplicitReason()) {
  7095. case UnavailableAttr::IR_None: break;
  7096. case UnavailableAttr::IR_ARCForbiddenType:
  7097. flagARCError();
  7098. diag_available_here = diag::note_arc_forbidden_type;
  7099. break;
  7100. case UnavailableAttr::IR_ForbiddenWeak:
  7101. if (S.getLangOpts().ObjCWeakRuntime)
  7102. diag_available_here = diag::note_arc_weak_disabled;
  7103. else
  7104. diag_available_here = diag::note_arc_weak_no_runtime;
  7105. break;
  7106. case UnavailableAttr::IR_ARCForbiddenConversion:
  7107. flagARCError();
  7108. diag_available_here = diag::note_performs_forbidden_arc_conversion;
  7109. break;
  7110. case UnavailableAttr::IR_ARCInitReturnsUnrelated:
  7111. flagARCError();
  7112. diag_available_here = diag::note_arc_init_returns_unrelated;
  7113. break;
  7114. case UnavailableAttr::IR_ARCFieldWithOwnership:
  7115. flagARCError();
  7116. diag_available_here = diag::note_arc_field_with_ownership;
  7117. break;
  7118. }
  7119. }
  7120. }
  7121. break;
  7122. case AR_Available:
  7123. llvm_unreachable("Warning for availability of available declaration?");
  7124. }
  7125. SmallVector<FixItHint, 12> FixIts;
  7126. if (K == AR_Deprecated) {
  7127. StringRef Replacement;
  7128. if (auto AL = OffendingDecl->getAttr<DeprecatedAttr>())
  7129. Replacement = AL->getReplacement();
  7130. if (auto AL = getAttrForPlatform(S.Context, OffendingDecl))
  7131. Replacement = AL->getReplacement();
  7132. CharSourceRange UseRange;
  7133. if (!Replacement.empty())
  7134. UseRange =
  7135. CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
  7136. if (UseRange.isValid()) {
  7137. if (const auto *MethodDecl = dyn_cast<ObjCMethodDecl>(ReferringDecl)) {
  7138. Selector Sel = MethodDecl->getSelector();
  7139. SmallVector<StringRef, 12> SelectorSlotNames;
  7140. Optional<unsigned> NumParams = tryParseObjCMethodName(
  7141. Replacement, SelectorSlotNames, S.getLangOpts());
  7142. if (NumParams && NumParams.getValue() == Sel.getNumArgs()) {
  7143. assert(SelectorSlotNames.size() == Locs.size());
  7144. for (unsigned I = 0; I < Locs.size(); ++I) {
  7145. if (!Sel.getNameForSlot(I).empty()) {
  7146. CharSourceRange NameRange = CharSourceRange::getCharRange(
  7147. Locs[I], S.getLocForEndOfToken(Locs[I]));
  7148. FixIts.push_back(FixItHint::CreateReplacement(
  7149. NameRange, SelectorSlotNames[I]));
  7150. } else
  7151. FixIts.push_back(
  7152. FixItHint::CreateInsertion(Locs[I], SelectorSlotNames[I]));
  7153. }
  7154. } else
  7155. FixIts.push_back(FixItHint::CreateReplacement(UseRange, Replacement));
  7156. } else
  7157. FixIts.push_back(FixItHint::CreateReplacement(UseRange, Replacement));
  7158. }
  7159. }
  7160. if (!Message.empty()) {
  7161. S.Diag(Loc, diag_message) << ReferringDecl << Message << FixIts;
  7162. if (ObjCProperty)
  7163. S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
  7164. << ObjCProperty->getDeclName() << property_note_select;
  7165. } else if (!UnknownObjCClass) {
  7166. S.Diag(Loc, diag) << ReferringDecl << FixIts;
  7167. if (ObjCProperty)
  7168. S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
  7169. << ObjCProperty->getDeclName() << property_note_select;
  7170. } else {
  7171. S.Diag(Loc, diag_fwdclass_message) << ReferringDecl << FixIts;
  7172. S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
  7173. }
  7174. S.Diag(NoteLocation, diag_available_here)
  7175. << OffendingDecl << available_here_select_kind;
  7176. }
  7177. static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
  7178. Decl *Ctx) {
  7179. assert(DD.Kind == DelayedDiagnostic::Availability &&
  7180. "Expected an availability diagnostic here");
  7181. DD.Triggered = true;
  7182. DoEmitAvailabilityWarning(
  7183. S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityReferringDecl(),
  7184. DD.getAvailabilityOffendingDecl(), DD.getAvailabilityMessage(),
  7185. DD.getAvailabilitySelectorLocs(), DD.getUnknownObjCClass(),
  7186. DD.getObjCProperty(), false);
  7187. }
  7188. void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
  7189. assert(DelayedDiagnostics.getCurrentPool());
  7190. DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
  7191. DelayedDiagnostics.popWithoutEmitting(state);
  7192. // When delaying diagnostics to run in the context of a parsed
  7193. // declaration, we only want to actually emit anything if parsing
  7194. // succeeds.
  7195. if (!decl) return;
  7196. // We emit all the active diagnostics in this pool or any of its
  7197. // parents. In general, we'll get one pool for the decl spec
  7198. // and a child pool for each declarator; in a decl group like:
  7199. // deprecated_typedef foo, *bar, baz();
  7200. // only the declarator pops will be passed decls. This is correct;
  7201. // we really do need to consider delayed diagnostics from the decl spec
  7202. // for each of the different declarations.
  7203. const DelayedDiagnosticPool *pool = &poppedPool;
  7204. do {
  7205. bool AnyAccessFailures = false;
  7206. for (DelayedDiagnosticPool::pool_iterator
  7207. i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
  7208. // This const_cast is a bit lame. Really, Triggered should be mutable.
  7209. DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
  7210. if (diag.Triggered)
  7211. continue;
  7212. switch (diag.Kind) {
  7213. case DelayedDiagnostic::Availability:
  7214. // Don't bother giving deprecation/unavailable diagnostics if
  7215. // the decl is invalid.
  7216. if (!decl->isInvalidDecl())
  7217. handleDelayedAvailabilityCheck(*this, diag, decl);
  7218. break;
  7219. case DelayedDiagnostic::Access:
  7220. // Only produce one access control diagnostic for a structured binding
  7221. // declaration: we don't need to tell the user that all the fields are
  7222. // inaccessible one at a time.
  7223. if (AnyAccessFailures && isa<DecompositionDecl>(decl))
  7224. continue;
  7225. HandleDelayedAccessCheck(diag, decl);
  7226. if (diag.Triggered)
  7227. AnyAccessFailures = true;
  7228. break;
  7229. case DelayedDiagnostic::ForbiddenType:
  7230. handleDelayedForbiddenType(*this, diag, decl);
  7231. break;
  7232. }
  7233. }
  7234. } while ((pool = pool->getParent()));
  7235. }
  7236. /// Given a set of delayed diagnostics, re-emit them as if they had
  7237. /// been delayed in the current context instead of in the given pool.
  7238. /// Essentially, this just moves them to the current pool.
  7239. void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
  7240. DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
  7241. assert(curPool && "re-emitting in undelayed context not supported");
  7242. curPool->steal(pool);
  7243. }
  7244. static void EmitAvailabilityWarning(Sema &S, AvailabilityResult AR,
  7245. const NamedDecl *ReferringDecl,
  7246. const NamedDecl *OffendingDecl,
  7247. StringRef Message,
  7248. ArrayRef<SourceLocation> Locs,
  7249. const ObjCInterfaceDecl *UnknownObjCClass,
  7250. const ObjCPropertyDecl *ObjCProperty,
  7251. bool ObjCPropertyAccess) {
  7252. // Delay if we're currently parsing a declaration.
  7253. if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
  7254. S.DelayedDiagnostics.add(
  7255. DelayedDiagnostic::makeAvailability(
  7256. AR, Locs, ReferringDecl, OffendingDecl, UnknownObjCClass,
  7257. ObjCProperty, Message, ObjCPropertyAccess));
  7258. return;
  7259. }
  7260. Decl *Ctx = cast<Decl>(S.getCurLexicalContext());
  7261. DoEmitAvailabilityWarning(S, AR, Ctx, ReferringDecl, OffendingDecl,
  7262. Message, Locs, UnknownObjCClass, ObjCProperty,
  7263. ObjCPropertyAccess);
  7264. }
  7265. namespace {
  7266. /// Returns true if the given statement can be a body-like child of \p Parent.
  7267. bool isBodyLikeChildStmt(const Stmt *S, const Stmt *Parent) {
  7268. switch (Parent->getStmtClass()) {
  7269. case Stmt::IfStmtClass:
  7270. return cast<IfStmt>(Parent)->getThen() == S ||
  7271. cast<IfStmt>(Parent)->getElse() == S;
  7272. case Stmt::WhileStmtClass:
  7273. return cast<WhileStmt>(Parent)->getBody() == S;
  7274. case Stmt::DoStmtClass:
  7275. return cast<DoStmt>(Parent)->getBody() == S;
  7276. case Stmt::ForStmtClass:
  7277. return cast<ForStmt>(Parent)->getBody() == S;
  7278. case Stmt::CXXForRangeStmtClass:
  7279. return cast<CXXForRangeStmt>(Parent)->getBody() == S;
  7280. case Stmt::ObjCForCollectionStmtClass:
  7281. return cast<ObjCForCollectionStmt>(Parent)->getBody() == S;
  7282. case Stmt::CaseStmtClass:
  7283. case Stmt::DefaultStmtClass:
  7284. return cast<SwitchCase>(Parent)->getSubStmt() == S;
  7285. default:
  7286. return false;
  7287. }
  7288. }
  7289. class StmtUSEFinder : public RecursiveASTVisitor<StmtUSEFinder> {
  7290. const Stmt *Target;
  7291. public:
  7292. bool VisitStmt(Stmt *S) { return S != Target; }
  7293. /// Returns true if the given statement is present in the given declaration.
  7294. static bool isContained(const Stmt *Target, const Decl *D) {
  7295. StmtUSEFinder Visitor;
  7296. Visitor.Target = Target;
  7297. return !Visitor.TraverseDecl(const_cast<Decl *>(D));
  7298. }
  7299. };
  7300. /// Traverses the AST and finds the last statement that used a given
  7301. /// declaration.
  7302. class LastDeclUSEFinder : public RecursiveASTVisitor<LastDeclUSEFinder> {
  7303. const Decl *D;
  7304. public:
  7305. bool VisitDeclRefExpr(DeclRefExpr *DRE) {
  7306. if (DRE->getDecl() == D)
  7307. return false;
  7308. return true;
  7309. }
  7310. static const Stmt *findLastStmtThatUsesDecl(const Decl *D,
  7311. const CompoundStmt *Scope) {
  7312. LastDeclUSEFinder Visitor;
  7313. Visitor.D = D;
  7314. for (auto I = Scope->body_rbegin(), E = Scope->body_rend(); I != E; ++I) {
  7315. const Stmt *S = *I;
  7316. if (!Visitor.TraverseStmt(const_cast<Stmt *>(S)))
  7317. return S;
  7318. }
  7319. return nullptr;
  7320. }
  7321. };
  7322. /// This class implements -Wunguarded-availability.
  7323. ///
  7324. /// This is done with a traversal of the AST of a function that makes reference
  7325. /// to a partially available declaration. Whenever we encounter an \c if of the
  7326. /// form: \c if(@available(...)), we use the version from the condition to visit
  7327. /// the then statement.
  7328. class DiagnoseUnguardedAvailability
  7329. : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> {
  7330. typedef RecursiveASTVisitor<DiagnoseUnguardedAvailability> Base;
  7331. Sema &SemaRef;
  7332. Decl *Ctx;
  7333. /// Stack of potentially nested 'if (@available(...))'s.
  7334. SmallVector<VersionTuple, 8> AvailabilityStack;
  7335. SmallVector<const Stmt *, 16> StmtStack;
  7336. void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range,
  7337. ObjCInterfaceDecl *ClassReceiver = nullptr);
  7338. public:
  7339. DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx)
  7340. : SemaRef(SemaRef), Ctx(Ctx) {
  7341. AvailabilityStack.push_back(
  7342. SemaRef.Context.getTargetInfo().getPlatformMinVersion());
  7343. }
  7344. bool TraverseDecl(Decl *D) {
  7345. // Avoid visiting nested functions to prevent duplicate warnings.
  7346. if (!D || isa<FunctionDecl>(D))
  7347. return true;
  7348. return Base::TraverseDecl(D);
  7349. }
  7350. bool TraverseStmt(Stmt *S) {
  7351. if (!S)
  7352. return true;
  7353. StmtStack.push_back(S);
  7354. bool Result = Base::TraverseStmt(S);
  7355. StmtStack.pop_back();
  7356. return Result;
  7357. }
  7358. void IssueDiagnostics(Stmt *S) { TraverseStmt(S); }
  7359. bool TraverseIfStmt(IfStmt *If);
  7360. bool TraverseLambdaExpr(LambdaExpr *E) { return true; }
  7361. // for 'case X:' statements, don't bother looking at the 'X'; it can't lead
  7362. // to any useful diagnostics.
  7363. bool TraverseCaseStmt(CaseStmt *CS) { return TraverseStmt(CS->getSubStmt()); }
  7364. bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *PRE) {
  7365. if (PRE->isClassReceiver())
  7366. DiagnoseDeclAvailability(PRE->getClassReceiver(), PRE->getReceiverLocation());
  7367. return true;
  7368. }
  7369. bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) {
  7370. if (ObjCMethodDecl *D = Msg->getMethodDecl()) {
  7371. ObjCInterfaceDecl *ID = nullptr;
  7372. QualType ReceiverTy = Msg->getClassReceiver();
  7373. if (!ReceiverTy.isNull() && ReceiverTy->getAsObjCInterfaceType())
  7374. ID = ReceiverTy->getAsObjCInterfaceType()->getInterface();
  7375. DiagnoseDeclAvailability(
  7376. D, SourceRange(Msg->getSelectorStartLoc(), Msg->getEndLoc()), ID);
  7377. }
  7378. return true;
  7379. }
  7380. bool VisitDeclRefExpr(DeclRefExpr *DRE) {
  7381. DiagnoseDeclAvailability(DRE->getDecl(),
  7382. SourceRange(DRE->getBeginLoc(), DRE->getEndLoc()));
  7383. return true;
  7384. }
  7385. bool VisitMemberExpr(MemberExpr *ME) {
  7386. DiagnoseDeclAvailability(ME->getMemberDecl(),
  7387. SourceRange(ME->getBeginLoc(), ME->getEndLoc()));
  7388. return true;
  7389. }
  7390. bool VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
  7391. SemaRef.Diag(E->getBeginLoc(), diag::warn_at_available_unchecked_use)
  7392. << (!SemaRef.getLangOpts().ObjC);
  7393. return true;
  7394. }
  7395. bool VisitTypeLoc(TypeLoc Ty);
  7396. };
  7397. void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability(
  7398. NamedDecl *D, SourceRange Range, ObjCInterfaceDecl *ReceiverClass) {
  7399. AvailabilityResult Result;
  7400. const NamedDecl *OffendingDecl;
  7401. std::tie(Result, OffendingDecl) =
  7402. ShouldDiagnoseAvailabilityOfDecl(SemaRef, D, nullptr, ReceiverClass);
  7403. if (Result != AR_Available) {
  7404. // All other diagnostic kinds have already been handled in
  7405. // DiagnoseAvailabilityOfDecl.
  7406. if (Result != AR_NotYetIntroduced)
  7407. return;
  7408. const AvailabilityAttr *AA =
  7409. getAttrForPlatform(SemaRef.getASTContext(), OffendingDecl);
  7410. VersionTuple Introduced = AA->getIntroduced();
  7411. if (AvailabilityStack.back() >= Introduced)
  7412. return;
  7413. // If the context of this function is less available than D, we should not
  7414. // emit a diagnostic.
  7415. if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx,
  7416. OffendingDecl))
  7417. return;
  7418. // We would like to emit the diagnostic even if -Wunguarded-availability is
  7419. // not specified for deployment targets >= to iOS 11 or equivalent or
  7420. // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or
  7421. // later.
  7422. unsigned DiagKind =
  7423. shouldDiagnoseAvailabilityByDefault(
  7424. SemaRef.Context,
  7425. SemaRef.Context.getTargetInfo().getPlatformMinVersion(), Introduced)
  7426. ? diag::warn_unguarded_availability_new
  7427. : diag::warn_unguarded_availability;
  7428. std::string PlatformName = AvailabilityAttr::getPrettyPlatformName(
  7429. SemaRef.getASTContext().getTargetInfo().getPlatformName());
  7430. SemaRef.Diag(Range.getBegin(), DiagKind)
  7431. << Range << D << PlatformName << Introduced.getAsString();
  7432. SemaRef.Diag(OffendingDecl->getLocation(),
  7433. diag::note_partial_availability_specified_here)
  7434. << OffendingDecl << PlatformName << Introduced.getAsString()
  7435. << SemaRef.Context.getTargetInfo()
  7436. .getPlatformMinVersion()
  7437. .getAsString();
  7438. auto FixitDiag =
  7439. SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence)
  7440. << Range << D
  7441. << (SemaRef.getLangOpts().ObjC ? /*@available*/ 0
  7442. : /*__builtin_available*/ 1);
  7443. // Find the statement which should be enclosed in the if @available check.
  7444. if (StmtStack.empty())
  7445. return;
  7446. const Stmt *StmtOfUse = StmtStack.back();
  7447. const CompoundStmt *Scope = nullptr;
  7448. for (const Stmt *S : llvm::reverse(StmtStack)) {
  7449. if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
  7450. Scope = CS;
  7451. break;
  7452. }
  7453. if (isBodyLikeChildStmt(StmtOfUse, S)) {
  7454. // The declaration won't be seen outside of the statement, so we don't
  7455. // have to wrap the uses of any declared variables in if (@available).
  7456. // Therefore we can avoid setting Scope here.
  7457. break;
  7458. }
  7459. StmtOfUse = S;
  7460. }
  7461. const Stmt *LastStmtOfUse = nullptr;
  7462. if (isa<DeclStmt>(StmtOfUse) && Scope) {
  7463. for (const Decl *D : cast<DeclStmt>(StmtOfUse)->decls()) {
  7464. if (StmtUSEFinder::isContained(StmtStack.back(), D)) {
  7465. LastStmtOfUse = LastDeclUSEFinder::findLastStmtThatUsesDecl(D, Scope);
  7466. break;
  7467. }
  7468. }
  7469. }
  7470. const SourceManager &SM = SemaRef.getSourceManager();
  7471. SourceLocation IfInsertionLoc =
  7472. SM.getExpansionLoc(StmtOfUse->getBeginLoc());
  7473. SourceLocation StmtEndLoc =
  7474. SM.getExpansionRange(
  7475. (LastStmtOfUse ? LastStmtOfUse : StmtOfUse)->getEndLoc())
  7476. .getEnd();
  7477. if (SM.getFileID(IfInsertionLoc) != SM.getFileID(StmtEndLoc))
  7478. return;
  7479. StringRef Indentation = Lexer::getIndentationForLine(IfInsertionLoc, SM);
  7480. const char *ExtraIndentation = " ";
  7481. std::string FixItString;
  7482. llvm::raw_string_ostream FixItOS(FixItString);
  7483. FixItOS << "if (" << (SemaRef.getLangOpts().ObjC ? "@available"
  7484. : "__builtin_available")
  7485. << "("
  7486. << AvailabilityAttr::getPlatformNameSourceSpelling(
  7487. SemaRef.getASTContext().getTargetInfo().getPlatformName())
  7488. << " " << Introduced.getAsString() << ", *)) {\n"
  7489. << Indentation << ExtraIndentation;
  7490. FixitDiag << FixItHint::CreateInsertion(IfInsertionLoc, FixItOS.str());
  7491. SourceLocation ElseInsertionLoc = Lexer::findLocationAfterToken(
  7492. StmtEndLoc, tok::semi, SM, SemaRef.getLangOpts(),
  7493. /*SkipTrailingWhitespaceAndNewLine=*/false);
  7494. if (ElseInsertionLoc.isInvalid())
  7495. ElseInsertionLoc =
  7496. Lexer::getLocForEndOfToken(StmtEndLoc, 0, SM, SemaRef.getLangOpts());
  7497. FixItOS.str().clear();
  7498. FixItOS << "\n"
  7499. << Indentation << "} else {\n"
  7500. << Indentation << ExtraIndentation
  7501. << "// Fallback on earlier versions\n"
  7502. << Indentation << "}";
  7503. FixitDiag << FixItHint::CreateInsertion(ElseInsertionLoc, FixItOS.str());
  7504. }
  7505. }
  7506. bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) {
  7507. const Type *TyPtr = Ty.getTypePtr();
  7508. SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()};
  7509. if (Range.isInvalid())
  7510. return true;
  7511. if (const auto *TT = dyn_cast<TagType>(TyPtr)) {
  7512. TagDecl *TD = TT->getDecl();
  7513. DiagnoseDeclAvailability(TD, Range);
  7514. } else if (const auto *TD = dyn_cast<TypedefType>(TyPtr)) {
  7515. TypedefNameDecl *D = TD->getDecl();
  7516. DiagnoseDeclAvailability(D, Range);
  7517. } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) {
  7518. if (NamedDecl *D = ObjCO->getInterface())
  7519. DiagnoseDeclAvailability(D, Range);
  7520. }
  7521. return true;
  7522. }
  7523. bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
  7524. VersionTuple CondVersion;
  7525. if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) {
  7526. CondVersion = E->getVersion();
  7527. // If we're using the '*' case here or if this check is redundant, then we
  7528. // use the enclosing version to check both branches.
  7529. if (CondVersion.empty() || CondVersion <= AvailabilityStack.back())
  7530. return TraverseStmt(If->getThen()) && TraverseStmt(If->getElse());
  7531. } else {
  7532. // This isn't an availability checking 'if', we can just continue.
  7533. return Base::TraverseIfStmt(If);
  7534. }
  7535. AvailabilityStack.push_back(CondVersion);
  7536. bool ShouldContinue = TraverseStmt(If->getThen());
  7537. AvailabilityStack.pop_back();
  7538. return ShouldContinue && TraverseStmt(If->getElse());
  7539. }
  7540. } // end anonymous namespace
  7541. void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) {
  7542. Stmt *Body = nullptr;
  7543. if (auto *FD = D->getAsFunction()) {
  7544. // FIXME: We only examine the pattern decl for availability violations now,
  7545. // but we should also examine instantiated templates.
  7546. if (FD->isTemplateInstantiation())
  7547. return;
  7548. Body = FD->getBody();
  7549. } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
  7550. Body = MD->getBody();
  7551. else if (auto *BD = dyn_cast<BlockDecl>(D))
  7552. Body = BD->getBody();
  7553. assert(Body && "Need a body here!");
  7554. DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body);
  7555. }
  7556. void Sema::DiagnoseAvailabilityOfDecl(NamedDecl *D,
  7557. ArrayRef<SourceLocation> Locs,
  7558. const ObjCInterfaceDecl *UnknownObjCClass,
  7559. bool ObjCPropertyAccess,
  7560. bool AvoidPartialAvailabilityChecks,
  7561. ObjCInterfaceDecl *ClassReceiver) {
  7562. std::string Message;
  7563. AvailabilityResult Result;
  7564. const NamedDecl* OffendingDecl;
  7565. // See if this declaration is unavailable, deprecated, or partial.
  7566. std::tie(Result, OffendingDecl) =
  7567. ShouldDiagnoseAvailabilityOfDecl(*this, D, &Message, ClassReceiver);
  7568. if (Result == AR_Available)
  7569. return;
  7570. if (Result == AR_NotYetIntroduced) {
  7571. if (AvoidPartialAvailabilityChecks)
  7572. return;
  7573. // We need to know the @available context in the current function to
  7574. // diagnose this use, let DiagnoseUnguardedAvailabilityViolations do that
  7575. // when we're done parsing the current function.
  7576. if (getCurFunctionOrMethodDecl()) {
  7577. getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
  7578. return;
  7579. } else if (getCurBlock() || getCurLambda()) {
  7580. getCurFunction()->HasPotentialAvailabilityViolations = true;
  7581. return;
  7582. }
  7583. }
  7584. const ObjCPropertyDecl *ObjCPDecl = nullptr;
  7585. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
  7586. if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
  7587. AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
  7588. if (PDeclResult == Result)
  7589. ObjCPDecl = PD;
  7590. }
  7591. }
  7592. EmitAvailabilityWarning(*this, Result, D, OffendingDecl, Message, Locs,
  7593. UnknownObjCClass, ObjCPDecl, ObjCPropertyAccess);
  7594. }