SemaDeclAttr.cpp 334 KB

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