SemaDeclAttr.cpp 291 KB

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