SemaType.cpp 310 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301
  1. //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
  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 type-related semantic analysis.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "TypeLocBuilder.h"
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTMutationListener.h"
  16. #include "clang/AST/ASTStructuralEquivalence.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/DeclTemplate.h"
  20. #include "clang/AST/Expr.h"
  21. #include "clang/AST/TypeLoc.h"
  22. #include "clang/AST/TypeLocVisitor.h"
  23. #include "clang/Basic/PartialDiagnostic.h"
  24. #include "clang/Basic/TargetInfo.h"
  25. #include "clang/Lex/Preprocessor.h"
  26. #include "clang/Sema/DeclSpec.h"
  27. #include "clang/Sema/DelayedDiagnostic.h"
  28. #include "clang/Sema/Lookup.h"
  29. #include "clang/Sema/ScopeInfo.h"
  30. #include "clang/Sema/SemaInternal.h"
  31. #include "clang/Sema/Template.h"
  32. #include "clang/Sema/TemplateInstCallback.h"
  33. #include "llvm/ADT/SmallPtrSet.h"
  34. #include "llvm/ADT/SmallString.h"
  35. #include "llvm/ADT/StringSwitch.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. using namespace clang;
  38. enum TypeDiagSelector {
  39. TDS_Function,
  40. TDS_Pointer,
  41. TDS_ObjCObjOrBlock
  42. };
  43. /// isOmittedBlockReturnType - Return true if this declarator is missing a
  44. /// return type because this is a omitted return type on a block literal.
  45. static bool isOmittedBlockReturnType(const Declarator &D) {
  46. if (D.getContext() != DeclaratorContext::BlockLiteralContext ||
  47. D.getDeclSpec().hasTypeSpecifier())
  48. return false;
  49. if (D.getNumTypeObjects() == 0)
  50. return true; // ^{ ... }
  51. if (D.getNumTypeObjects() == 1 &&
  52. D.getTypeObject(0).Kind == DeclaratorChunk::Function)
  53. return true; // ^(int X, float Y) { ... }
  54. return false;
  55. }
  56. /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
  57. /// doesn't apply to the given type.
  58. static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
  59. QualType type) {
  60. TypeDiagSelector WhichType;
  61. bool useExpansionLoc = true;
  62. switch (attr.getKind()) {
  63. case ParsedAttr::AT_ObjCGC:
  64. WhichType = TDS_Pointer;
  65. break;
  66. case ParsedAttr::AT_ObjCOwnership:
  67. WhichType = TDS_ObjCObjOrBlock;
  68. break;
  69. default:
  70. // Assume everything else was a function attribute.
  71. WhichType = TDS_Function;
  72. useExpansionLoc = false;
  73. break;
  74. }
  75. SourceLocation loc = attr.getLoc();
  76. StringRef name = attr.getName()->getName();
  77. // The GC attributes are usually written with macros; special-case them.
  78. IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
  79. : nullptr;
  80. if (useExpansionLoc && loc.isMacroID() && II) {
  81. if (II->isStr("strong")) {
  82. if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
  83. } else if (II->isStr("weak")) {
  84. if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
  85. }
  86. }
  87. S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
  88. << type;
  89. }
  90. // objc_gc applies to Objective-C pointers or, otherwise, to the
  91. // smallest available pointer type (i.e. 'void*' in 'void**').
  92. #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
  93. case ParsedAttr::AT_ObjCGC: \
  94. case ParsedAttr::AT_ObjCOwnership
  95. // Calling convention attributes.
  96. #define CALLING_CONV_ATTRS_CASELIST \
  97. case ParsedAttr::AT_CDecl: \
  98. case ParsedAttr::AT_FastCall: \
  99. case ParsedAttr::AT_StdCall: \
  100. case ParsedAttr::AT_ThisCall: \
  101. case ParsedAttr::AT_RegCall: \
  102. case ParsedAttr::AT_Pascal: \
  103. case ParsedAttr::AT_SwiftCall: \
  104. case ParsedAttr::AT_VectorCall: \
  105. case ParsedAttr::AT_AArch64VectorPcs: \
  106. case ParsedAttr::AT_MSABI: \
  107. case ParsedAttr::AT_SysVABI: \
  108. case ParsedAttr::AT_Pcs: \
  109. case ParsedAttr::AT_IntelOclBicc: \
  110. case ParsedAttr::AT_PreserveMost: \
  111. case ParsedAttr::AT_PreserveAll
  112. // Function type attributes.
  113. #define FUNCTION_TYPE_ATTRS_CASELIST \
  114. case ParsedAttr::AT_NSReturnsRetained: \
  115. case ParsedAttr::AT_NoReturn: \
  116. case ParsedAttr::AT_Regparm: \
  117. case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
  118. case ParsedAttr::AT_AnyX86NoCfCheck: \
  119. CALLING_CONV_ATTRS_CASELIST
  120. // Microsoft-specific type qualifiers.
  121. #define MS_TYPE_ATTRS_CASELIST \
  122. case ParsedAttr::AT_Ptr32: \
  123. case ParsedAttr::AT_Ptr64: \
  124. case ParsedAttr::AT_SPtr: \
  125. case ParsedAttr::AT_UPtr
  126. // Nullability qualifiers.
  127. #define NULLABILITY_TYPE_ATTRS_CASELIST \
  128. case ParsedAttr::AT_TypeNonNull: \
  129. case ParsedAttr::AT_TypeNullable: \
  130. case ParsedAttr::AT_TypeNullUnspecified
  131. namespace {
  132. /// An object which stores processing state for the entire
  133. /// GetTypeForDeclarator process.
  134. class TypeProcessingState {
  135. Sema &sema;
  136. /// The declarator being processed.
  137. Declarator &declarator;
  138. /// The index of the declarator chunk we're currently processing.
  139. /// May be the total number of valid chunks, indicating the
  140. /// DeclSpec.
  141. unsigned chunkIndex;
  142. /// Whether there are non-trivial modifications to the decl spec.
  143. bool trivial;
  144. /// Whether we saved the attributes in the decl spec.
  145. bool hasSavedAttrs;
  146. /// The original set of attributes on the DeclSpec.
  147. SmallVector<ParsedAttr *, 2> savedAttrs;
  148. /// A list of attributes to diagnose the uselessness of when the
  149. /// processing is complete.
  150. SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
  151. /// Attributes corresponding to AttributedTypeLocs that we have not yet
  152. /// populated.
  153. // FIXME: The two-phase mechanism by which we construct Types and fill
  154. // their TypeLocs makes it hard to correctly assign these. We keep the
  155. // attributes in creation order as an attempt to make them line up
  156. // properly.
  157. using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
  158. SmallVector<TypeAttrPair, 8> AttrsForTypes;
  159. bool AttrsForTypesSorted = true;
  160. /// Flag to indicate we parsed a noderef attribute. This is used for
  161. /// validating that noderef was used on a pointer or array.
  162. bool parsedNoDeref;
  163. public:
  164. TypeProcessingState(Sema &sema, Declarator &declarator)
  165. : sema(sema), declarator(declarator),
  166. chunkIndex(declarator.getNumTypeObjects()), trivial(true),
  167. hasSavedAttrs(false), parsedNoDeref(false) {}
  168. Sema &getSema() const {
  169. return sema;
  170. }
  171. Declarator &getDeclarator() const {
  172. return declarator;
  173. }
  174. bool isProcessingDeclSpec() const {
  175. return chunkIndex == declarator.getNumTypeObjects();
  176. }
  177. unsigned getCurrentChunkIndex() const {
  178. return chunkIndex;
  179. }
  180. void setCurrentChunkIndex(unsigned idx) {
  181. assert(idx <= declarator.getNumTypeObjects());
  182. chunkIndex = idx;
  183. }
  184. ParsedAttributesView &getCurrentAttributes() const {
  185. if (isProcessingDeclSpec())
  186. return getMutableDeclSpec().getAttributes();
  187. return declarator.getTypeObject(chunkIndex).getAttrs();
  188. }
  189. /// Save the current set of attributes on the DeclSpec.
  190. void saveDeclSpecAttrs() {
  191. // Don't try to save them multiple times.
  192. if (hasSavedAttrs) return;
  193. DeclSpec &spec = getMutableDeclSpec();
  194. for (ParsedAttr &AL : spec.getAttributes())
  195. savedAttrs.push_back(&AL);
  196. trivial &= savedAttrs.empty();
  197. hasSavedAttrs = true;
  198. }
  199. /// Record that we had nowhere to put the given type attribute.
  200. /// We will diagnose such attributes later.
  201. void addIgnoredTypeAttr(ParsedAttr &attr) {
  202. ignoredTypeAttrs.push_back(&attr);
  203. }
  204. /// Diagnose all the ignored type attributes, given that the
  205. /// declarator worked out to the given type.
  206. void diagnoseIgnoredTypeAttrs(QualType type) const {
  207. for (auto *Attr : ignoredTypeAttrs)
  208. diagnoseBadTypeAttribute(getSema(), *Attr, type);
  209. }
  210. /// Get an attributed type for the given attribute, and remember the Attr
  211. /// object so that we can attach it to the AttributedTypeLoc.
  212. QualType getAttributedType(Attr *A, QualType ModifiedType,
  213. QualType EquivType) {
  214. QualType T =
  215. sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType);
  216. AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
  217. AttrsForTypesSorted = false;
  218. return T;
  219. }
  220. /// Completely replace the \c auto in \p TypeWithAuto by
  221. /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
  222. /// necessary.
  223. QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
  224. QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
  225. if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
  226. // Attributed type still should be an attributed type after replacement.
  227. auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
  228. for (TypeAttrPair &A : AttrsForTypes) {
  229. if (A.first == AttrTy)
  230. A.first = NewAttrTy;
  231. }
  232. AttrsForTypesSorted = false;
  233. }
  234. return T;
  235. }
  236. /// Extract and remove the Attr* for a given attributed type.
  237. const Attr *takeAttrForAttributedType(const AttributedType *AT) {
  238. if (!AttrsForTypesSorted) {
  239. std::stable_sort(AttrsForTypes.begin(), AttrsForTypes.end(),
  240. [](const TypeAttrPair &A, const TypeAttrPair &B) {
  241. return A.first < B.first;
  242. });
  243. AttrsForTypesSorted = true;
  244. }
  245. // FIXME: This is quadratic if we have lots of reuses of the same
  246. // attributed type.
  247. for (auto It = std::partition_point(
  248. AttrsForTypes.begin(), AttrsForTypes.end(),
  249. [=](const TypeAttrPair &A) { return A.first < AT; });
  250. It != AttrsForTypes.end() && It->first == AT; ++It) {
  251. if (It->second) {
  252. const Attr *Result = It->second;
  253. It->second = nullptr;
  254. return Result;
  255. }
  256. }
  257. llvm_unreachable("no Attr* for AttributedType*");
  258. }
  259. void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
  260. bool didParseNoDeref() const { return parsedNoDeref; }
  261. ~TypeProcessingState() {
  262. if (trivial) return;
  263. restoreDeclSpecAttrs();
  264. }
  265. private:
  266. DeclSpec &getMutableDeclSpec() const {
  267. return const_cast<DeclSpec&>(declarator.getDeclSpec());
  268. }
  269. void restoreDeclSpecAttrs() {
  270. assert(hasSavedAttrs);
  271. getMutableDeclSpec().getAttributes().clearListOnly();
  272. for (ParsedAttr *AL : savedAttrs)
  273. getMutableDeclSpec().getAttributes().addAtEnd(AL);
  274. }
  275. };
  276. } // end anonymous namespace
  277. static void moveAttrFromListToList(ParsedAttr &attr,
  278. ParsedAttributesView &fromList,
  279. ParsedAttributesView &toList) {
  280. fromList.remove(&attr);
  281. toList.addAtEnd(&attr);
  282. }
  283. /// The location of a type attribute.
  284. enum TypeAttrLocation {
  285. /// The attribute is in the decl-specifier-seq.
  286. TAL_DeclSpec,
  287. /// The attribute is part of a DeclaratorChunk.
  288. TAL_DeclChunk,
  289. /// The attribute is immediately after the declaration's name.
  290. TAL_DeclName
  291. };
  292. static void processTypeAttrs(TypeProcessingState &state, QualType &type,
  293. TypeAttrLocation TAL, ParsedAttributesView &attrs);
  294. static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
  295. QualType &type);
  296. static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
  297. ParsedAttr &attr, QualType &type);
  298. static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
  299. QualType &type);
  300. static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
  301. ParsedAttr &attr, QualType &type);
  302. static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
  303. ParsedAttr &attr, QualType &type) {
  304. if (attr.getKind() == ParsedAttr::AT_ObjCGC)
  305. return handleObjCGCTypeAttr(state, attr, type);
  306. assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
  307. return handleObjCOwnershipTypeAttr(state, attr, type);
  308. }
  309. /// Given the index of a declarator chunk, check whether that chunk
  310. /// directly specifies the return type of a function and, if so, find
  311. /// an appropriate place for it.
  312. ///
  313. /// \param i - a notional index which the search will start
  314. /// immediately inside
  315. ///
  316. /// \param onlyBlockPointers Whether we should only look into block
  317. /// pointer types (vs. all pointer types).
  318. static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
  319. unsigned i,
  320. bool onlyBlockPointers) {
  321. assert(i <= declarator.getNumTypeObjects());
  322. DeclaratorChunk *result = nullptr;
  323. // First, look inwards past parens for a function declarator.
  324. for (; i != 0; --i) {
  325. DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
  326. switch (fnChunk.Kind) {
  327. case DeclaratorChunk::Paren:
  328. continue;
  329. // If we find anything except a function, bail out.
  330. case DeclaratorChunk::Pointer:
  331. case DeclaratorChunk::BlockPointer:
  332. case DeclaratorChunk::Array:
  333. case DeclaratorChunk::Reference:
  334. case DeclaratorChunk::MemberPointer:
  335. case DeclaratorChunk::Pipe:
  336. return result;
  337. // If we do find a function declarator, scan inwards from that,
  338. // looking for a (block-)pointer declarator.
  339. case DeclaratorChunk::Function:
  340. for (--i; i != 0; --i) {
  341. DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
  342. switch (ptrChunk.Kind) {
  343. case DeclaratorChunk::Paren:
  344. case DeclaratorChunk::Array:
  345. case DeclaratorChunk::Function:
  346. case DeclaratorChunk::Reference:
  347. case DeclaratorChunk::Pipe:
  348. continue;
  349. case DeclaratorChunk::MemberPointer:
  350. case DeclaratorChunk::Pointer:
  351. if (onlyBlockPointers)
  352. continue;
  353. LLVM_FALLTHROUGH;
  354. case DeclaratorChunk::BlockPointer:
  355. result = &ptrChunk;
  356. goto continue_outer;
  357. }
  358. llvm_unreachable("bad declarator chunk kind");
  359. }
  360. // If we run out of declarators doing that, we're done.
  361. return result;
  362. }
  363. llvm_unreachable("bad declarator chunk kind");
  364. // Okay, reconsider from our new point.
  365. continue_outer: ;
  366. }
  367. // Ran out of chunks, bail out.
  368. return result;
  369. }
  370. /// Given that an objc_gc attribute was written somewhere on a
  371. /// declaration *other* than on the declarator itself (for which, use
  372. /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
  373. /// didn't apply in whatever position it was written in, try to move
  374. /// it to a more appropriate position.
  375. static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
  376. ParsedAttr &attr, QualType type) {
  377. Declarator &declarator = state.getDeclarator();
  378. // Move it to the outermost normal or block pointer declarator.
  379. for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
  380. DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
  381. switch (chunk.Kind) {
  382. case DeclaratorChunk::Pointer:
  383. case DeclaratorChunk::BlockPointer: {
  384. // But don't move an ARC ownership attribute to the return type
  385. // of a block.
  386. DeclaratorChunk *destChunk = nullptr;
  387. if (state.isProcessingDeclSpec() &&
  388. attr.getKind() == ParsedAttr::AT_ObjCOwnership)
  389. destChunk = maybeMovePastReturnType(declarator, i - 1,
  390. /*onlyBlockPointers=*/true);
  391. if (!destChunk) destChunk = &chunk;
  392. moveAttrFromListToList(attr, state.getCurrentAttributes(),
  393. destChunk->getAttrs());
  394. return;
  395. }
  396. case DeclaratorChunk::Paren:
  397. case DeclaratorChunk::Array:
  398. continue;
  399. // We may be starting at the return type of a block.
  400. case DeclaratorChunk::Function:
  401. if (state.isProcessingDeclSpec() &&
  402. attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
  403. if (DeclaratorChunk *dest = maybeMovePastReturnType(
  404. declarator, i,
  405. /*onlyBlockPointers=*/true)) {
  406. moveAttrFromListToList(attr, state.getCurrentAttributes(),
  407. dest->getAttrs());
  408. return;
  409. }
  410. }
  411. goto error;
  412. // Don't walk through these.
  413. case DeclaratorChunk::Reference:
  414. case DeclaratorChunk::MemberPointer:
  415. case DeclaratorChunk::Pipe:
  416. goto error;
  417. }
  418. }
  419. error:
  420. diagnoseBadTypeAttribute(state.getSema(), attr, type);
  421. }
  422. /// Distribute an objc_gc type attribute that was written on the
  423. /// declarator.
  424. static void distributeObjCPointerTypeAttrFromDeclarator(
  425. TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
  426. Declarator &declarator = state.getDeclarator();
  427. // objc_gc goes on the innermost pointer to something that's not a
  428. // pointer.
  429. unsigned innermost = -1U;
  430. bool considerDeclSpec = true;
  431. for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
  432. DeclaratorChunk &chunk = declarator.getTypeObject(i);
  433. switch (chunk.Kind) {
  434. case DeclaratorChunk::Pointer:
  435. case DeclaratorChunk::BlockPointer:
  436. innermost = i;
  437. continue;
  438. case DeclaratorChunk::Reference:
  439. case DeclaratorChunk::MemberPointer:
  440. case DeclaratorChunk::Paren:
  441. case DeclaratorChunk::Array:
  442. case DeclaratorChunk::Pipe:
  443. continue;
  444. case DeclaratorChunk::Function:
  445. considerDeclSpec = false;
  446. goto done;
  447. }
  448. }
  449. done:
  450. // That might actually be the decl spec if we weren't blocked by
  451. // anything in the declarator.
  452. if (considerDeclSpec) {
  453. if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
  454. // Splice the attribute into the decl spec. Prevents the
  455. // attribute from being applied multiple times and gives
  456. // the source-location-filler something to work with.
  457. state.saveDeclSpecAttrs();
  458. declarator.getMutableDeclSpec().getAttributes().takeOneFrom(
  459. declarator.getAttributes(), &attr);
  460. return;
  461. }
  462. }
  463. // Otherwise, if we found an appropriate chunk, splice the attribute
  464. // into it.
  465. if (innermost != -1U) {
  466. moveAttrFromListToList(attr, declarator.getAttributes(),
  467. declarator.getTypeObject(innermost).getAttrs());
  468. return;
  469. }
  470. // Otherwise, diagnose when we're done building the type.
  471. declarator.getAttributes().remove(&attr);
  472. state.addIgnoredTypeAttr(attr);
  473. }
  474. /// A function type attribute was written somewhere in a declaration
  475. /// *other* than on the declarator itself or in the decl spec. Given
  476. /// that it didn't apply in whatever position it was written in, try
  477. /// to move it to a more appropriate position.
  478. static void distributeFunctionTypeAttr(TypeProcessingState &state,
  479. ParsedAttr &attr, QualType type) {
  480. Declarator &declarator = state.getDeclarator();
  481. // Try to push the attribute from the return type of a function to
  482. // the function itself.
  483. for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
  484. DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
  485. switch (chunk.Kind) {
  486. case DeclaratorChunk::Function:
  487. moveAttrFromListToList(attr, state.getCurrentAttributes(),
  488. chunk.getAttrs());
  489. return;
  490. case DeclaratorChunk::Paren:
  491. case DeclaratorChunk::Pointer:
  492. case DeclaratorChunk::BlockPointer:
  493. case DeclaratorChunk::Array:
  494. case DeclaratorChunk::Reference:
  495. case DeclaratorChunk::MemberPointer:
  496. case DeclaratorChunk::Pipe:
  497. continue;
  498. }
  499. }
  500. diagnoseBadTypeAttribute(state.getSema(), attr, type);
  501. }
  502. /// Try to distribute a function type attribute to the innermost
  503. /// function chunk or type. Returns true if the attribute was
  504. /// distributed, false if no location was found.
  505. static bool distributeFunctionTypeAttrToInnermost(
  506. TypeProcessingState &state, ParsedAttr &attr,
  507. ParsedAttributesView &attrList, QualType &declSpecType) {
  508. Declarator &declarator = state.getDeclarator();
  509. // Put it on the innermost function chunk, if there is one.
  510. for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
  511. DeclaratorChunk &chunk = declarator.getTypeObject(i);
  512. if (chunk.Kind != DeclaratorChunk::Function) continue;
  513. moveAttrFromListToList(attr, attrList, chunk.getAttrs());
  514. return true;
  515. }
  516. return handleFunctionTypeAttr(state, attr, declSpecType);
  517. }
  518. /// A function type attribute was written in the decl spec. Try to
  519. /// apply it somewhere.
  520. static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
  521. ParsedAttr &attr,
  522. QualType &declSpecType) {
  523. state.saveDeclSpecAttrs();
  524. // C++11 attributes before the decl specifiers actually appertain to
  525. // the declarators. Move them straight there. We don't support the
  526. // 'put them wherever you like' semantics we allow for GNU attributes.
  527. if (attr.isCXX11Attribute()) {
  528. moveAttrFromListToList(attr, state.getCurrentAttributes(),
  529. state.getDeclarator().getAttributes());
  530. return;
  531. }
  532. // Try to distribute to the innermost.
  533. if (distributeFunctionTypeAttrToInnermost(
  534. state, attr, state.getCurrentAttributes(), declSpecType))
  535. return;
  536. // If that failed, diagnose the bad attribute when the declarator is
  537. // fully built.
  538. state.addIgnoredTypeAttr(attr);
  539. }
  540. /// A function type attribute was written on the declarator. Try to
  541. /// apply it somewhere.
  542. static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
  543. ParsedAttr &attr,
  544. QualType &declSpecType) {
  545. Declarator &declarator = state.getDeclarator();
  546. // Try to distribute to the innermost.
  547. if (distributeFunctionTypeAttrToInnermost(
  548. state, attr, declarator.getAttributes(), declSpecType))
  549. return;
  550. // If that failed, diagnose the bad attribute when the declarator is
  551. // fully built.
  552. declarator.getAttributes().remove(&attr);
  553. state.addIgnoredTypeAttr(attr);
  554. }
  555. /// Given that there are attributes written on the declarator
  556. /// itself, try to distribute any type attributes to the appropriate
  557. /// declarator chunk.
  558. ///
  559. /// These are attributes like the following:
  560. /// int f ATTR;
  561. /// int (f ATTR)();
  562. /// but not necessarily this:
  563. /// int f() ATTR;
  564. static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
  565. QualType &declSpecType) {
  566. // Collect all the type attributes from the declarator itself.
  567. assert(!state.getDeclarator().getAttributes().empty() &&
  568. "declarator has no attrs!");
  569. // The called functions in this loop actually remove things from the current
  570. // list, so iterating over the existing list isn't possible. Instead, make a
  571. // non-owning copy and iterate over that.
  572. ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
  573. for (ParsedAttr &attr : AttrsCopy) {
  574. // Do not distribute C++11 attributes. They have strict rules for what
  575. // they appertain to.
  576. if (attr.isCXX11Attribute())
  577. continue;
  578. switch (attr.getKind()) {
  579. OBJC_POINTER_TYPE_ATTRS_CASELIST:
  580. distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType);
  581. break;
  582. FUNCTION_TYPE_ATTRS_CASELIST:
  583. distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType);
  584. break;
  585. MS_TYPE_ATTRS_CASELIST:
  586. // Microsoft type attributes cannot go after the declarator-id.
  587. continue;
  588. NULLABILITY_TYPE_ATTRS_CASELIST:
  589. // Nullability specifiers cannot go after the declarator-id.
  590. // Objective-C __kindof does not get distributed.
  591. case ParsedAttr::AT_ObjCKindOf:
  592. continue;
  593. default:
  594. break;
  595. }
  596. }
  597. }
  598. /// Add a synthetic '()' to a block-literal declarator if it is
  599. /// required, given the return type.
  600. static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
  601. QualType declSpecType) {
  602. Declarator &declarator = state.getDeclarator();
  603. // First, check whether the declarator would produce a function,
  604. // i.e. whether the innermost semantic chunk is a function.
  605. if (declarator.isFunctionDeclarator()) {
  606. // If so, make that declarator a prototyped declarator.
  607. declarator.getFunctionTypeInfo().hasPrototype = true;
  608. return;
  609. }
  610. // If there are any type objects, the type as written won't name a
  611. // function, regardless of the decl spec type. This is because a
  612. // block signature declarator is always an abstract-declarator, and
  613. // abstract-declarators can't just be parentheses chunks. Therefore
  614. // we need to build a function chunk unless there are no type
  615. // objects and the decl spec type is a function.
  616. if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
  617. return;
  618. // Note that there *are* cases with invalid declarators where
  619. // declarators consist solely of parentheses. In general, these
  620. // occur only in failed efforts to make function declarators, so
  621. // faking up the function chunk is still the right thing to do.
  622. // Otherwise, we need to fake up a function declarator.
  623. SourceLocation loc = declarator.getBeginLoc();
  624. // ...and *prepend* it to the declarator.
  625. SourceLocation NoLoc;
  626. declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
  627. /*HasProto=*/true,
  628. /*IsAmbiguous=*/false,
  629. /*LParenLoc=*/NoLoc,
  630. /*ArgInfo=*/nullptr,
  631. /*NumArgs=*/0,
  632. /*EllipsisLoc=*/NoLoc,
  633. /*RParenLoc=*/NoLoc,
  634. /*RefQualifierIsLvalueRef=*/true,
  635. /*RefQualifierLoc=*/NoLoc,
  636. /*MutableLoc=*/NoLoc, EST_None,
  637. /*ESpecRange=*/SourceRange(),
  638. /*Exceptions=*/nullptr,
  639. /*ExceptionRanges=*/nullptr,
  640. /*NumExceptions=*/0,
  641. /*NoexceptExpr=*/nullptr,
  642. /*ExceptionSpecTokens=*/nullptr,
  643. /*DeclsInPrototype=*/None, loc, loc, declarator));
  644. // For consistency, make sure the state still has us as processing
  645. // the decl spec.
  646. assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
  647. state.setCurrentChunkIndex(declarator.getNumTypeObjects());
  648. }
  649. static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
  650. unsigned &TypeQuals,
  651. QualType TypeSoFar,
  652. unsigned RemoveTQs,
  653. unsigned DiagID) {
  654. // If this occurs outside a template instantiation, warn the user about
  655. // it; they probably didn't mean to specify a redundant qualifier.
  656. typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
  657. for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
  658. QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
  659. QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
  660. QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
  661. if (!(RemoveTQs & Qual.first))
  662. continue;
  663. if (!S.inTemplateInstantiation()) {
  664. if (TypeQuals & Qual.first)
  665. S.Diag(Qual.second, DiagID)
  666. << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
  667. << FixItHint::CreateRemoval(Qual.second);
  668. }
  669. TypeQuals &= ~Qual.first;
  670. }
  671. }
  672. /// Return true if this is omitted block return type. Also check type
  673. /// attributes and type qualifiers when returning true.
  674. static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
  675. QualType Result) {
  676. if (!isOmittedBlockReturnType(declarator))
  677. return false;
  678. // Warn if we see type attributes for omitted return type on a block literal.
  679. SmallVector<ParsedAttr *, 2> ToBeRemoved;
  680. for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
  681. if (AL.isInvalid() || !AL.isTypeAttr())
  682. continue;
  683. S.Diag(AL.getLoc(),
  684. diag::warn_block_literal_attributes_on_omitted_return_type)
  685. << AL.getName();
  686. ToBeRemoved.push_back(&AL);
  687. }
  688. // Remove bad attributes from the list.
  689. for (ParsedAttr *AL : ToBeRemoved)
  690. declarator.getMutableDeclSpec().getAttributes().remove(AL);
  691. // Warn if we see type qualifiers for omitted return type on a block literal.
  692. const DeclSpec &DS = declarator.getDeclSpec();
  693. unsigned TypeQuals = DS.getTypeQualifiers();
  694. diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
  695. diag::warn_block_literal_qualifiers_on_omitted_return_type);
  696. declarator.getMutableDeclSpec().ClearTypeQualifiers();
  697. return true;
  698. }
  699. /// Apply Objective-C type arguments to the given type.
  700. static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
  701. ArrayRef<TypeSourceInfo *> typeArgs,
  702. SourceRange typeArgsRange,
  703. bool failOnError = false) {
  704. // We can only apply type arguments to an Objective-C class type.
  705. const auto *objcObjectType = type->getAs<ObjCObjectType>();
  706. if (!objcObjectType || !objcObjectType->getInterface()) {
  707. S.Diag(loc, diag::err_objc_type_args_non_class)
  708. << type
  709. << typeArgsRange;
  710. if (failOnError)
  711. return QualType();
  712. return type;
  713. }
  714. // The class type must be parameterized.
  715. ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
  716. ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
  717. if (!typeParams) {
  718. S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
  719. << objcClass->getDeclName()
  720. << FixItHint::CreateRemoval(typeArgsRange);
  721. if (failOnError)
  722. return QualType();
  723. return type;
  724. }
  725. // The type must not already be specialized.
  726. if (objcObjectType->isSpecialized()) {
  727. S.Diag(loc, diag::err_objc_type_args_specialized_class)
  728. << type
  729. << FixItHint::CreateRemoval(typeArgsRange);
  730. if (failOnError)
  731. return QualType();
  732. return type;
  733. }
  734. // Check the type arguments.
  735. SmallVector<QualType, 4> finalTypeArgs;
  736. unsigned numTypeParams = typeParams->size();
  737. bool anyPackExpansions = false;
  738. for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
  739. TypeSourceInfo *typeArgInfo = typeArgs[i];
  740. QualType typeArg = typeArgInfo->getType();
  741. // Type arguments cannot have explicit qualifiers or nullability.
  742. // We ignore indirect sources of these, e.g. behind typedefs or
  743. // template arguments.
  744. if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
  745. bool diagnosed = false;
  746. SourceRange rangeToRemove;
  747. if (auto attr = qual.getAs<AttributedTypeLoc>()) {
  748. rangeToRemove = attr.getLocalSourceRange();
  749. if (attr.getTypePtr()->getImmediateNullability()) {
  750. typeArg = attr.getTypePtr()->getModifiedType();
  751. S.Diag(attr.getBeginLoc(),
  752. diag::err_objc_type_arg_explicit_nullability)
  753. << typeArg << FixItHint::CreateRemoval(rangeToRemove);
  754. diagnosed = true;
  755. }
  756. }
  757. if (!diagnosed) {
  758. S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified)
  759. << typeArg << typeArg.getQualifiers().getAsString()
  760. << FixItHint::CreateRemoval(rangeToRemove);
  761. }
  762. }
  763. // Remove qualifiers even if they're non-local.
  764. typeArg = typeArg.getUnqualifiedType();
  765. finalTypeArgs.push_back(typeArg);
  766. if (typeArg->getAs<PackExpansionType>())
  767. anyPackExpansions = true;
  768. // Find the corresponding type parameter, if there is one.
  769. ObjCTypeParamDecl *typeParam = nullptr;
  770. if (!anyPackExpansions) {
  771. if (i < numTypeParams) {
  772. typeParam = typeParams->begin()[i];
  773. } else {
  774. // Too many arguments.
  775. S.Diag(loc, diag::err_objc_type_args_wrong_arity)
  776. << false
  777. << objcClass->getDeclName()
  778. << (unsigned)typeArgs.size()
  779. << numTypeParams;
  780. S.Diag(objcClass->getLocation(), diag::note_previous_decl)
  781. << objcClass;
  782. if (failOnError)
  783. return QualType();
  784. return type;
  785. }
  786. }
  787. // Objective-C object pointer types must be substitutable for the bounds.
  788. if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
  789. // If we don't have a type parameter to match against, assume
  790. // everything is fine. There was a prior pack expansion that
  791. // means we won't be able to match anything.
  792. if (!typeParam) {
  793. assert(anyPackExpansions && "Too many arguments?");
  794. continue;
  795. }
  796. // Retrieve the bound.
  797. QualType bound = typeParam->getUnderlyingType();
  798. const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
  799. // Determine whether the type argument is substitutable for the bound.
  800. if (typeArgObjC->isObjCIdType()) {
  801. // When the type argument is 'id', the only acceptable type
  802. // parameter bound is 'id'.
  803. if (boundObjC->isObjCIdType())
  804. continue;
  805. } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
  806. // Otherwise, we follow the assignability rules.
  807. continue;
  808. }
  809. // Diagnose the mismatch.
  810. S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
  811. diag::err_objc_type_arg_does_not_match_bound)
  812. << typeArg << bound << typeParam->getDeclName();
  813. S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
  814. << typeParam->getDeclName();
  815. if (failOnError)
  816. return QualType();
  817. return type;
  818. }
  819. // Block pointer types are permitted for unqualified 'id' bounds.
  820. if (typeArg->isBlockPointerType()) {
  821. // If we don't have a type parameter to match against, assume
  822. // everything is fine. There was a prior pack expansion that
  823. // means we won't be able to match anything.
  824. if (!typeParam) {
  825. assert(anyPackExpansions && "Too many arguments?");
  826. continue;
  827. }
  828. // Retrieve the bound.
  829. QualType bound = typeParam->getUnderlyingType();
  830. if (bound->isBlockCompatibleObjCPointerType(S.Context))
  831. continue;
  832. // Diagnose the mismatch.
  833. S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
  834. diag::err_objc_type_arg_does_not_match_bound)
  835. << typeArg << bound << typeParam->getDeclName();
  836. S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
  837. << typeParam->getDeclName();
  838. if (failOnError)
  839. return QualType();
  840. return type;
  841. }
  842. // Dependent types will be checked at instantiation time.
  843. if (typeArg->isDependentType()) {
  844. continue;
  845. }
  846. // Diagnose non-id-compatible type arguments.
  847. S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
  848. diag::err_objc_type_arg_not_id_compatible)
  849. << typeArg << typeArgInfo->getTypeLoc().getSourceRange();
  850. if (failOnError)
  851. return QualType();
  852. return type;
  853. }
  854. // Make sure we didn't have the wrong number of arguments.
  855. if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
  856. S.Diag(loc, diag::err_objc_type_args_wrong_arity)
  857. << (typeArgs.size() < typeParams->size())
  858. << objcClass->getDeclName()
  859. << (unsigned)finalTypeArgs.size()
  860. << (unsigned)numTypeParams;
  861. S.Diag(objcClass->getLocation(), diag::note_previous_decl)
  862. << objcClass;
  863. if (failOnError)
  864. return QualType();
  865. return type;
  866. }
  867. // Success. Form the specialized type.
  868. return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
  869. }
  870. QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
  871. SourceLocation ProtocolLAngleLoc,
  872. ArrayRef<ObjCProtocolDecl *> Protocols,
  873. ArrayRef<SourceLocation> ProtocolLocs,
  874. SourceLocation ProtocolRAngleLoc,
  875. bool FailOnError) {
  876. QualType Result = QualType(Decl->getTypeForDecl(), 0);
  877. if (!Protocols.empty()) {
  878. bool HasError;
  879. Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
  880. HasError);
  881. if (HasError) {
  882. Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
  883. << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
  884. if (FailOnError) Result = QualType();
  885. }
  886. if (FailOnError && Result.isNull())
  887. return QualType();
  888. }
  889. return Result;
  890. }
  891. QualType Sema::BuildObjCObjectType(QualType BaseType,
  892. SourceLocation Loc,
  893. SourceLocation TypeArgsLAngleLoc,
  894. ArrayRef<TypeSourceInfo *> TypeArgs,
  895. SourceLocation TypeArgsRAngleLoc,
  896. SourceLocation ProtocolLAngleLoc,
  897. ArrayRef<ObjCProtocolDecl *> Protocols,
  898. ArrayRef<SourceLocation> ProtocolLocs,
  899. SourceLocation ProtocolRAngleLoc,
  900. bool FailOnError) {
  901. QualType Result = BaseType;
  902. if (!TypeArgs.empty()) {
  903. Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
  904. SourceRange(TypeArgsLAngleLoc,
  905. TypeArgsRAngleLoc),
  906. FailOnError);
  907. if (FailOnError && Result.isNull())
  908. return QualType();
  909. }
  910. if (!Protocols.empty()) {
  911. bool HasError;
  912. Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
  913. HasError);
  914. if (HasError) {
  915. Diag(Loc, diag::err_invalid_protocol_qualifiers)
  916. << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
  917. if (FailOnError) Result = QualType();
  918. }
  919. if (FailOnError && Result.isNull())
  920. return QualType();
  921. }
  922. return Result;
  923. }
  924. TypeResult Sema::actOnObjCProtocolQualifierType(
  925. SourceLocation lAngleLoc,
  926. ArrayRef<Decl *> protocols,
  927. ArrayRef<SourceLocation> protocolLocs,
  928. SourceLocation rAngleLoc) {
  929. // Form id<protocol-list>.
  930. QualType Result = Context.getObjCObjectType(
  931. Context.ObjCBuiltinIdTy, { },
  932. llvm::makeArrayRef(
  933. (ObjCProtocolDecl * const *)protocols.data(),
  934. protocols.size()),
  935. false);
  936. Result = Context.getObjCObjectPointerType(Result);
  937. TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
  938. TypeLoc ResultTL = ResultTInfo->getTypeLoc();
  939. auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
  940. ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
  941. auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
  942. .castAs<ObjCObjectTypeLoc>();
  943. ObjCObjectTL.setHasBaseTypeAsWritten(false);
  944. ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
  945. // No type arguments.
  946. ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
  947. ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
  948. // Fill in protocol qualifiers.
  949. ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
  950. ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
  951. for (unsigned i = 0, n = protocols.size(); i != n; ++i)
  952. ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
  953. // We're done. Return the completed type to the parser.
  954. return CreateParsedType(Result, ResultTInfo);
  955. }
  956. TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
  957. Scope *S,
  958. SourceLocation Loc,
  959. ParsedType BaseType,
  960. SourceLocation TypeArgsLAngleLoc,
  961. ArrayRef<ParsedType> TypeArgs,
  962. SourceLocation TypeArgsRAngleLoc,
  963. SourceLocation ProtocolLAngleLoc,
  964. ArrayRef<Decl *> Protocols,
  965. ArrayRef<SourceLocation> ProtocolLocs,
  966. SourceLocation ProtocolRAngleLoc) {
  967. TypeSourceInfo *BaseTypeInfo = nullptr;
  968. QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
  969. if (T.isNull())
  970. return true;
  971. // Handle missing type-source info.
  972. if (!BaseTypeInfo)
  973. BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  974. // Extract type arguments.
  975. SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
  976. for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
  977. TypeSourceInfo *TypeArgInfo = nullptr;
  978. QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
  979. if (TypeArg.isNull()) {
  980. ActualTypeArgInfos.clear();
  981. break;
  982. }
  983. assert(TypeArgInfo && "No type source info?");
  984. ActualTypeArgInfos.push_back(TypeArgInfo);
  985. }
  986. // Build the object type.
  987. QualType Result = BuildObjCObjectType(
  988. T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
  989. TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
  990. ProtocolLAngleLoc,
  991. llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
  992. Protocols.size()),
  993. ProtocolLocs, ProtocolRAngleLoc,
  994. /*FailOnError=*/false);
  995. if (Result == T)
  996. return BaseType;
  997. // Create source information for this type.
  998. TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
  999. TypeLoc ResultTL = ResultTInfo->getTypeLoc();
  1000. // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
  1001. // object pointer type. Fill in source information for it.
  1002. if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
  1003. // The '*' is implicit.
  1004. ObjCObjectPointerTL.setStarLoc(SourceLocation());
  1005. ResultTL = ObjCObjectPointerTL.getPointeeLoc();
  1006. }
  1007. if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
  1008. // Protocol qualifier information.
  1009. if (OTPTL.getNumProtocols() > 0) {
  1010. assert(OTPTL.getNumProtocols() == Protocols.size());
  1011. OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
  1012. OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
  1013. for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
  1014. OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
  1015. }
  1016. // We're done. Return the completed type to the parser.
  1017. return CreateParsedType(Result, ResultTInfo);
  1018. }
  1019. auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
  1020. // Type argument information.
  1021. if (ObjCObjectTL.getNumTypeArgs() > 0) {
  1022. assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
  1023. ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
  1024. ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
  1025. for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
  1026. ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
  1027. } else {
  1028. ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
  1029. ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
  1030. }
  1031. // Protocol qualifier information.
  1032. if (ObjCObjectTL.getNumProtocols() > 0) {
  1033. assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
  1034. ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
  1035. ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
  1036. for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
  1037. ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
  1038. } else {
  1039. ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
  1040. ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
  1041. }
  1042. // Base type.
  1043. ObjCObjectTL.setHasBaseTypeAsWritten(true);
  1044. if (ObjCObjectTL.getType() == T)
  1045. ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
  1046. else
  1047. ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
  1048. // We're done. Return the completed type to the parser.
  1049. return CreateParsedType(Result, ResultTInfo);
  1050. }
  1051. static OpenCLAccessAttr::Spelling
  1052. getImageAccess(const ParsedAttributesView &Attrs) {
  1053. for (const ParsedAttr &AL : Attrs)
  1054. if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
  1055. return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
  1056. return OpenCLAccessAttr::Keyword_read_only;
  1057. }
  1058. /// Convert the specified declspec to the appropriate type
  1059. /// object.
  1060. /// \param state Specifies the declarator containing the declaration specifier
  1061. /// to be converted, along with other associated processing state.
  1062. /// \returns The type described by the declaration specifiers. This function
  1063. /// never returns null.
  1064. static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
  1065. // FIXME: Should move the logic from DeclSpec::Finish to here for validity
  1066. // checking.
  1067. Sema &S = state.getSema();
  1068. Declarator &declarator = state.getDeclarator();
  1069. DeclSpec &DS = declarator.getMutableDeclSpec();
  1070. SourceLocation DeclLoc = declarator.getIdentifierLoc();
  1071. if (DeclLoc.isInvalid())
  1072. DeclLoc = DS.getBeginLoc();
  1073. ASTContext &Context = S.Context;
  1074. QualType Result;
  1075. switch (DS.getTypeSpecType()) {
  1076. case DeclSpec::TST_void:
  1077. Result = Context.VoidTy;
  1078. break;
  1079. case DeclSpec::TST_char:
  1080. if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
  1081. Result = Context.CharTy;
  1082. else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
  1083. Result = Context.SignedCharTy;
  1084. else {
  1085. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
  1086. "Unknown TSS value");
  1087. Result = Context.UnsignedCharTy;
  1088. }
  1089. break;
  1090. case DeclSpec::TST_wchar:
  1091. if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
  1092. Result = Context.WCharTy;
  1093. else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
  1094. S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
  1095. << DS.getSpecifierName(DS.getTypeSpecType(),
  1096. Context.getPrintingPolicy());
  1097. Result = Context.getSignedWCharType();
  1098. } else {
  1099. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
  1100. "Unknown TSS value");
  1101. S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
  1102. << DS.getSpecifierName(DS.getTypeSpecType(),
  1103. Context.getPrintingPolicy());
  1104. Result = Context.getUnsignedWCharType();
  1105. }
  1106. break;
  1107. case DeclSpec::TST_char8:
  1108. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
  1109. "Unknown TSS value");
  1110. Result = Context.Char8Ty;
  1111. break;
  1112. case DeclSpec::TST_char16:
  1113. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
  1114. "Unknown TSS value");
  1115. Result = Context.Char16Ty;
  1116. break;
  1117. case DeclSpec::TST_char32:
  1118. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
  1119. "Unknown TSS value");
  1120. Result = Context.Char32Ty;
  1121. break;
  1122. case DeclSpec::TST_unspecified:
  1123. // If this is a missing declspec in a block literal return context, then it
  1124. // is inferred from the return statements inside the block.
  1125. // The declspec is always missing in a lambda expr context; it is either
  1126. // specified with a trailing return type or inferred.
  1127. if (S.getLangOpts().CPlusPlus14 &&
  1128. declarator.getContext() == DeclaratorContext::LambdaExprContext) {
  1129. // In C++1y, a lambda's implicit return type is 'auto'.
  1130. Result = Context.getAutoDeductType();
  1131. break;
  1132. } else if (declarator.getContext() ==
  1133. DeclaratorContext::LambdaExprContext ||
  1134. checkOmittedBlockReturnType(S, declarator,
  1135. Context.DependentTy)) {
  1136. Result = Context.DependentTy;
  1137. break;
  1138. }
  1139. // Unspecified typespec defaults to int in C90. However, the C90 grammar
  1140. // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
  1141. // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
  1142. // Note that the one exception to this is function definitions, which are
  1143. // allowed to be completely missing a declspec. This is handled in the
  1144. // parser already though by it pretending to have seen an 'int' in this
  1145. // case.
  1146. if (S.getLangOpts().ImplicitInt) {
  1147. // In C89 mode, we only warn if there is a completely missing declspec
  1148. // when one is not allowed.
  1149. if (DS.isEmpty()) {
  1150. S.Diag(DeclLoc, diag::ext_missing_declspec)
  1151. << DS.getSourceRange()
  1152. << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
  1153. }
  1154. } else if (!DS.hasTypeSpecifier()) {
  1155. // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
  1156. // "At least one type specifier shall be given in the declaration
  1157. // specifiers in each declaration, and in the specifier-qualifier list in
  1158. // each struct declaration and type name."
  1159. if (S.getLangOpts().CPlusPlus) {
  1160. S.Diag(DeclLoc, diag::err_missing_type_specifier)
  1161. << DS.getSourceRange();
  1162. // When this occurs in C++ code, often something is very broken with the
  1163. // value being declared, poison it as invalid so we don't get chains of
  1164. // errors.
  1165. declarator.setInvalidType(true);
  1166. } else if (S.getLangOpts().OpenCLVersion >= 200 && DS.isTypeSpecPipe()){
  1167. S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
  1168. << DS.getSourceRange();
  1169. declarator.setInvalidType(true);
  1170. } else {
  1171. S.Diag(DeclLoc, diag::ext_missing_type_specifier)
  1172. << DS.getSourceRange();
  1173. }
  1174. }
  1175. LLVM_FALLTHROUGH;
  1176. case DeclSpec::TST_int: {
  1177. if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
  1178. switch (DS.getTypeSpecWidth()) {
  1179. case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
  1180. case DeclSpec::TSW_short: Result = Context.ShortTy; break;
  1181. case DeclSpec::TSW_long: Result = Context.LongTy; break;
  1182. case DeclSpec::TSW_longlong:
  1183. Result = Context.LongLongTy;
  1184. // 'long long' is a C99 or C++11 feature.
  1185. if (!S.getLangOpts().C99) {
  1186. if (S.getLangOpts().CPlusPlus)
  1187. S.Diag(DS.getTypeSpecWidthLoc(),
  1188. S.getLangOpts().CPlusPlus11 ?
  1189. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  1190. else
  1191. S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
  1192. }
  1193. break;
  1194. }
  1195. } else {
  1196. switch (DS.getTypeSpecWidth()) {
  1197. case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
  1198. case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
  1199. case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
  1200. case DeclSpec::TSW_longlong:
  1201. Result = Context.UnsignedLongLongTy;
  1202. // 'long long' is a C99 or C++11 feature.
  1203. if (!S.getLangOpts().C99) {
  1204. if (S.getLangOpts().CPlusPlus)
  1205. S.Diag(DS.getTypeSpecWidthLoc(),
  1206. S.getLangOpts().CPlusPlus11 ?
  1207. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  1208. else
  1209. S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
  1210. }
  1211. break;
  1212. }
  1213. }
  1214. break;
  1215. }
  1216. case DeclSpec::TST_accum: {
  1217. switch (DS.getTypeSpecWidth()) {
  1218. case DeclSpec::TSW_short:
  1219. Result = Context.ShortAccumTy;
  1220. break;
  1221. case DeclSpec::TSW_unspecified:
  1222. Result = Context.AccumTy;
  1223. break;
  1224. case DeclSpec::TSW_long:
  1225. Result = Context.LongAccumTy;
  1226. break;
  1227. case DeclSpec::TSW_longlong:
  1228. llvm_unreachable("Unable to specify long long as _Accum width");
  1229. }
  1230. if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
  1231. Result = Context.getCorrespondingUnsignedType(Result);
  1232. if (DS.isTypeSpecSat())
  1233. Result = Context.getCorrespondingSaturatedType(Result);
  1234. break;
  1235. }
  1236. case DeclSpec::TST_fract: {
  1237. switch (DS.getTypeSpecWidth()) {
  1238. case DeclSpec::TSW_short:
  1239. Result = Context.ShortFractTy;
  1240. break;
  1241. case DeclSpec::TSW_unspecified:
  1242. Result = Context.FractTy;
  1243. break;
  1244. case DeclSpec::TSW_long:
  1245. Result = Context.LongFractTy;
  1246. break;
  1247. case DeclSpec::TSW_longlong:
  1248. llvm_unreachable("Unable to specify long long as _Fract width");
  1249. }
  1250. if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
  1251. Result = Context.getCorrespondingUnsignedType(Result);
  1252. if (DS.isTypeSpecSat())
  1253. Result = Context.getCorrespondingSaturatedType(Result);
  1254. break;
  1255. }
  1256. case DeclSpec::TST_int128:
  1257. if (!S.Context.getTargetInfo().hasInt128Type() &&
  1258. !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
  1259. S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
  1260. << "__int128";
  1261. if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
  1262. Result = Context.UnsignedInt128Ty;
  1263. else
  1264. Result = Context.Int128Ty;
  1265. break;
  1266. case DeclSpec::TST_float16:
  1267. // CUDA host and device may have different _Float16 support, therefore
  1268. // do not diagnose _Float16 usage to avoid false alarm.
  1269. // ToDo: more precise diagnostics for CUDA.
  1270. if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
  1271. !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
  1272. S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
  1273. << "_Float16";
  1274. Result = Context.Float16Ty;
  1275. break;
  1276. case DeclSpec::TST_half: Result = Context.HalfTy; break;
  1277. case DeclSpec::TST_float: Result = Context.FloatTy; break;
  1278. case DeclSpec::TST_double:
  1279. if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
  1280. Result = Context.LongDoubleTy;
  1281. else
  1282. Result = Context.DoubleTy;
  1283. break;
  1284. case DeclSpec::TST_float128:
  1285. if (!S.Context.getTargetInfo().hasFloat128Type() &&
  1286. !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
  1287. S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
  1288. << "__float128";
  1289. Result = Context.Float128Ty;
  1290. break;
  1291. case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
  1292. break;
  1293. case DeclSpec::TST_decimal32: // _Decimal32
  1294. case DeclSpec::TST_decimal64: // _Decimal64
  1295. case DeclSpec::TST_decimal128: // _Decimal128
  1296. S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
  1297. Result = Context.IntTy;
  1298. declarator.setInvalidType(true);
  1299. break;
  1300. case DeclSpec::TST_class:
  1301. case DeclSpec::TST_enum:
  1302. case DeclSpec::TST_union:
  1303. case DeclSpec::TST_struct:
  1304. case DeclSpec::TST_interface: {
  1305. TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
  1306. if (!D) {
  1307. // This can happen in C++ with ambiguous lookups.
  1308. Result = Context.IntTy;
  1309. declarator.setInvalidType(true);
  1310. break;
  1311. }
  1312. // If the type is deprecated or unavailable, diagnose it.
  1313. S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
  1314. assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
  1315. DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
  1316. // TypeQuals handled by caller.
  1317. Result = Context.getTypeDeclType(D);
  1318. // In both C and C++, make an ElaboratedType.
  1319. ElaboratedTypeKeyword Keyword
  1320. = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
  1321. Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
  1322. DS.isTypeSpecOwned() ? D : nullptr);
  1323. break;
  1324. }
  1325. case DeclSpec::TST_typename: {
  1326. assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
  1327. DS.getTypeSpecSign() == 0 &&
  1328. "Can't handle qualifiers on typedef names yet!");
  1329. Result = S.GetTypeFromParser(DS.getRepAsType());
  1330. if (Result.isNull()) {
  1331. declarator.setInvalidType(true);
  1332. }
  1333. // TypeQuals handled by caller.
  1334. break;
  1335. }
  1336. case DeclSpec::TST_typeofType:
  1337. // FIXME: Preserve type source info.
  1338. Result = S.GetTypeFromParser(DS.getRepAsType());
  1339. assert(!Result.isNull() && "Didn't get a type for typeof?");
  1340. if (!Result->isDependentType())
  1341. if (const TagType *TT = Result->getAs<TagType>())
  1342. S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
  1343. // TypeQuals handled by caller.
  1344. Result = Context.getTypeOfType(Result);
  1345. break;
  1346. case DeclSpec::TST_typeofExpr: {
  1347. Expr *E = DS.getRepAsExpr();
  1348. assert(E && "Didn't get an expression for typeof?");
  1349. // TypeQuals handled by caller.
  1350. Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
  1351. if (Result.isNull()) {
  1352. Result = Context.IntTy;
  1353. declarator.setInvalidType(true);
  1354. }
  1355. break;
  1356. }
  1357. case DeclSpec::TST_decltype: {
  1358. Expr *E = DS.getRepAsExpr();
  1359. assert(E && "Didn't get an expression for decltype?");
  1360. // TypeQuals handled by caller.
  1361. Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
  1362. if (Result.isNull()) {
  1363. Result = Context.IntTy;
  1364. declarator.setInvalidType(true);
  1365. }
  1366. break;
  1367. }
  1368. case DeclSpec::TST_underlyingType:
  1369. Result = S.GetTypeFromParser(DS.getRepAsType());
  1370. assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
  1371. Result = S.BuildUnaryTransformType(Result,
  1372. UnaryTransformType::EnumUnderlyingType,
  1373. DS.getTypeSpecTypeLoc());
  1374. if (Result.isNull()) {
  1375. Result = Context.IntTy;
  1376. declarator.setInvalidType(true);
  1377. }
  1378. break;
  1379. case DeclSpec::TST_auto:
  1380. Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
  1381. break;
  1382. case DeclSpec::TST_auto_type:
  1383. Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
  1384. break;
  1385. case DeclSpec::TST_decltype_auto:
  1386. Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto,
  1387. /*IsDependent*/ false);
  1388. break;
  1389. case DeclSpec::TST_unknown_anytype:
  1390. Result = Context.UnknownAnyTy;
  1391. break;
  1392. case DeclSpec::TST_atomic:
  1393. Result = S.GetTypeFromParser(DS.getRepAsType());
  1394. assert(!Result.isNull() && "Didn't get a type for _Atomic?");
  1395. Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
  1396. if (Result.isNull()) {
  1397. Result = Context.IntTy;
  1398. declarator.setInvalidType(true);
  1399. }
  1400. break;
  1401. #define GENERIC_IMAGE_TYPE(ImgType, Id) \
  1402. case DeclSpec::TST_##ImgType##_t: \
  1403. switch (getImageAccess(DS.getAttributes())) { \
  1404. case OpenCLAccessAttr::Keyword_write_only: \
  1405. Result = Context.Id##WOTy; \
  1406. break; \
  1407. case OpenCLAccessAttr::Keyword_read_write: \
  1408. Result = Context.Id##RWTy; \
  1409. break; \
  1410. case OpenCLAccessAttr::Keyword_read_only: \
  1411. Result = Context.Id##ROTy; \
  1412. break; \
  1413. } \
  1414. break;
  1415. #include "clang/Basic/OpenCLImageTypes.def"
  1416. case DeclSpec::TST_error:
  1417. Result = Context.IntTy;
  1418. declarator.setInvalidType(true);
  1419. break;
  1420. }
  1421. if (S.getLangOpts().OpenCL &&
  1422. S.checkOpenCLDisabledTypeDeclSpec(DS, Result))
  1423. declarator.setInvalidType(true);
  1424. bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
  1425. DS.getTypeSpecType() == DeclSpec::TST_fract;
  1426. // Only fixed point types can be saturated
  1427. if (DS.isTypeSpecSat() && !IsFixedPointType)
  1428. S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
  1429. << DS.getSpecifierName(DS.getTypeSpecType(),
  1430. Context.getPrintingPolicy());
  1431. // Handle complex types.
  1432. if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
  1433. if (S.getLangOpts().Freestanding)
  1434. S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
  1435. Result = Context.getComplexType(Result);
  1436. } else if (DS.isTypeAltiVecVector()) {
  1437. unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
  1438. assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
  1439. VectorType::VectorKind VecKind = VectorType::AltiVecVector;
  1440. if (DS.isTypeAltiVecPixel())
  1441. VecKind = VectorType::AltiVecPixel;
  1442. else if (DS.isTypeAltiVecBool())
  1443. VecKind = VectorType::AltiVecBool;
  1444. Result = Context.getVectorType(Result, 128/typeSize, VecKind);
  1445. }
  1446. // FIXME: Imaginary.
  1447. if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
  1448. S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
  1449. // Before we process any type attributes, synthesize a block literal
  1450. // function declarator if necessary.
  1451. if (declarator.getContext() == DeclaratorContext::BlockLiteralContext)
  1452. maybeSynthesizeBlockSignature(state, Result);
  1453. // Apply any type attributes from the decl spec. This may cause the
  1454. // list of type attributes to be temporarily saved while the type
  1455. // attributes are pushed around.
  1456. // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
  1457. if (!DS.isTypeSpecPipe())
  1458. processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
  1459. // Apply const/volatile/restrict qualifiers to T.
  1460. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  1461. // Warn about CV qualifiers on function types.
  1462. // C99 6.7.3p8:
  1463. // If the specification of a function type includes any type qualifiers,
  1464. // the behavior is undefined.
  1465. // C++11 [dcl.fct]p7:
  1466. // The effect of a cv-qualifier-seq in a function declarator is not the
  1467. // same as adding cv-qualification on top of the function type. In the
  1468. // latter case, the cv-qualifiers are ignored.
  1469. if (TypeQuals && Result->isFunctionType()) {
  1470. diagnoseAndRemoveTypeQualifiers(
  1471. S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
  1472. S.getLangOpts().CPlusPlus
  1473. ? diag::warn_typecheck_function_qualifiers_ignored
  1474. : diag::warn_typecheck_function_qualifiers_unspecified);
  1475. // No diagnostic for 'restrict' or '_Atomic' applied to a
  1476. // function type; we'll diagnose those later, in BuildQualifiedType.
  1477. }
  1478. // C++11 [dcl.ref]p1:
  1479. // Cv-qualified references are ill-formed except when the
  1480. // cv-qualifiers are introduced through the use of a typedef-name
  1481. // or decltype-specifier, in which case the cv-qualifiers are ignored.
  1482. //
  1483. // There don't appear to be any other contexts in which a cv-qualified
  1484. // reference type could be formed, so the 'ill-formed' clause here appears
  1485. // to never happen.
  1486. if (TypeQuals && Result->isReferenceType()) {
  1487. diagnoseAndRemoveTypeQualifiers(
  1488. S, DS, TypeQuals, Result,
  1489. DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
  1490. diag::warn_typecheck_reference_qualifiers);
  1491. }
  1492. // C90 6.5.3 constraints: "The same type qualifier shall not appear more
  1493. // than once in the same specifier-list or qualifier-list, either directly
  1494. // or via one or more typedefs."
  1495. if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
  1496. && TypeQuals & Result.getCVRQualifiers()) {
  1497. if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
  1498. S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
  1499. << "const";
  1500. }
  1501. if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
  1502. S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
  1503. << "volatile";
  1504. }
  1505. // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
  1506. // produce a warning in this case.
  1507. }
  1508. QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
  1509. // If adding qualifiers fails, just use the unqualified type.
  1510. if (Qualified.isNull())
  1511. declarator.setInvalidType(true);
  1512. else
  1513. Result = Qualified;
  1514. }
  1515. assert(!Result.isNull() && "This function should not return a null type");
  1516. return Result;
  1517. }
  1518. static std::string getPrintableNameForEntity(DeclarationName Entity) {
  1519. if (Entity)
  1520. return Entity.getAsString();
  1521. return "type name";
  1522. }
  1523. QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
  1524. Qualifiers Qs, const DeclSpec *DS) {
  1525. if (T.isNull())
  1526. return QualType();
  1527. // Ignore any attempt to form a cv-qualified reference.
  1528. if (T->isReferenceType()) {
  1529. Qs.removeConst();
  1530. Qs.removeVolatile();
  1531. }
  1532. // Enforce C99 6.7.3p2: "Types other than pointer types derived from
  1533. // object or incomplete types shall not be restrict-qualified."
  1534. if (Qs.hasRestrict()) {
  1535. unsigned DiagID = 0;
  1536. QualType ProblemTy;
  1537. if (T->isAnyPointerType() || T->isReferenceType() ||
  1538. T->isMemberPointerType()) {
  1539. QualType EltTy;
  1540. if (T->isObjCObjectPointerType())
  1541. EltTy = T;
  1542. else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
  1543. EltTy = PTy->getPointeeType();
  1544. else
  1545. EltTy = T->getPointeeType();
  1546. // If we have a pointer or reference, the pointee must have an object
  1547. // incomplete type.
  1548. if (!EltTy->isIncompleteOrObjectType()) {
  1549. DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
  1550. ProblemTy = EltTy;
  1551. }
  1552. } else if (!T->isDependentType()) {
  1553. DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
  1554. ProblemTy = T;
  1555. }
  1556. if (DiagID) {
  1557. Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
  1558. Qs.removeRestrict();
  1559. }
  1560. }
  1561. return Context.getQualifiedType(T, Qs);
  1562. }
  1563. QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
  1564. unsigned CVRAU, const DeclSpec *DS) {
  1565. if (T.isNull())
  1566. return QualType();
  1567. // Ignore any attempt to form a cv-qualified reference.
  1568. if (T->isReferenceType())
  1569. CVRAU &=
  1570. ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
  1571. // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
  1572. // TQ_unaligned;
  1573. unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
  1574. // C11 6.7.3/5:
  1575. // If the same qualifier appears more than once in the same
  1576. // specifier-qualifier-list, either directly or via one or more typedefs,
  1577. // the behavior is the same as if it appeared only once.
  1578. //
  1579. // It's not specified what happens when the _Atomic qualifier is applied to
  1580. // a type specified with the _Atomic specifier, but we assume that this
  1581. // should be treated as if the _Atomic qualifier appeared multiple times.
  1582. if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
  1583. // C11 6.7.3/5:
  1584. // If other qualifiers appear along with the _Atomic qualifier in a
  1585. // specifier-qualifier-list, the resulting type is the so-qualified
  1586. // atomic type.
  1587. //
  1588. // Don't need to worry about array types here, since _Atomic can't be
  1589. // applied to such types.
  1590. SplitQualType Split = T.getSplitUnqualifiedType();
  1591. T = BuildAtomicType(QualType(Split.Ty, 0),
  1592. DS ? DS->getAtomicSpecLoc() : Loc);
  1593. if (T.isNull())
  1594. return T;
  1595. Split.Quals.addCVRQualifiers(CVR);
  1596. return BuildQualifiedType(T, Loc, Split.Quals);
  1597. }
  1598. Qualifiers Q = Qualifiers::fromCVRMask(CVR);
  1599. Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
  1600. return BuildQualifiedType(T, Loc, Q, DS);
  1601. }
  1602. /// Build a paren type including \p T.
  1603. QualType Sema::BuildParenType(QualType T) {
  1604. return Context.getParenType(T);
  1605. }
  1606. /// Given that we're building a pointer or reference to the given
  1607. static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
  1608. SourceLocation loc,
  1609. bool isReference) {
  1610. // Bail out if retention is unrequired or already specified.
  1611. if (!type->isObjCLifetimeType() ||
  1612. type.getObjCLifetime() != Qualifiers::OCL_None)
  1613. return type;
  1614. Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
  1615. // If the object type is const-qualified, we can safely use
  1616. // __unsafe_unretained. This is safe (because there are no read
  1617. // barriers), and it'll be safe to coerce anything but __weak* to
  1618. // the resulting type.
  1619. if (type.isConstQualified()) {
  1620. implicitLifetime = Qualifiers::OCL_ExplicitNone;
  1621. // Otherwise, check whether the static type does not require
  1622. // retaining. This currently only triggers for Class (possibly
  1623. // protocol-qualifed, and arrays thereof).
  1624. } else if (type->isObjCARCImplicitlyUnretainedType()) {
  1625. implicitLifetime = Qualifiers::OCL_ExplicitNone;
  1626. // If we are in an unevaluated context, like sizeof, skip adding a
  1627. // qualification.
  1628. } else if (S.isUnevaluatedContext()) {
  1629. return type;
  1630. // If that failed, give an error and recover using __strong. __strong
  1631. // is the option most likely to prevent spurious second-order diagnostics,
  1632. // like when binding a reference to a field.
  1633. } else {
  1634. // These types can show up in private ivars in system headers, so
  1635. // we need this to not be an error in those cases. Instead we
  1636. // want to delay.
  1637. if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
  1638. S.DelayedDiagnostics.add(
  1639. sema::DelayedDiagnostic::makeForbiddenType(loc,
  1640. diag::err_arc_indirect_no_ownership, type, isReference));
  1641. } else {
  1642. S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
  1643. }
  1644. implicitLifetime = Qualifiers::OCL_Strong;
  1645. }
  1646. assert(implicitLifetime && "didn't infer any lifetime!");
  1647. Qualifiers qs;
  1648. qs.addObjCLifetime(implicitLifetime);
  1649. return S.Context.getQualifiedType(type, qs);
  1650. }
  1651. static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
  1652. std::string Quals = FnTy->getMethodQuals().getAsString();
  1653. switch (FnTy->getRefQualifier()) {
  1654. case RQ_None:
  1655. break;
  1656. case RQ_LValue:
  1657. if (!Quals.empty())
  1658. Quals += ' ';
  1659. Quals += '&';
  1660. break;
  1661. case RQ_RValue:
  1662. if (!Quals.empty())
  1663. Quals += ' ';
  1664. Quals += "&&";
  1665. break;
  1666. }
  1667. return Quals;
  1668. }
  1669. namespace {
  1670. /// Kinds of declarator that cannot contain a qualified function type.
  1671. ///
  1672. /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
  1673. /// a function type with a cv-qualifier or a ref-qualifier can only appear
  1674. /// at the topmost level of a type.
  1675. ///
  1676. /// Parens and member pointers are permitted. We don't diagnose array and
  1677. /// function declarators, because they don't allow function types at all.
  1678. ///
  1679. /// The values of this enum are used in diagnostics.
  1680. enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
  1681. } // end anonymous namespace
  1682. /// Check whether the type T is a qualified function type, and if it is,
  1683. /// diagnose that it cannot be contained within the given kind of declarator.
  1684. static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
  1685. QualifiedFunctionKind QFK) {
  1686. // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
  1687. const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
  1688. if (!FPT || (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
  1689. return false;
  1690. S.Diag(Loc, diag::err_compound_qualified_function_type)
  1691. << QFK << isa<FunctionType>(T.IgnoreParens()) << T
  1692. << getFunctionQualifiersAsString(FPT);
  1693. return true;
  1694. }
  1695. /// Build a pointer type.
  1696. ///
  1697. /// \param T The type to which we'll be building a pointer.
  1698. ///
  1699. /// \param Loc The location of the entity whose type involves this
  1700. /// pointer type or, if there is no such entity, the location of the
  1701. /// type that will have pointer type.
  1702. ///
  1703. /// \param Entity The name of the entity that involves the pointer
  1704. /// type, if known.
  1705. ///
  1706. /// \returns A suitable pointer type, if there are no
  1707. /// errors. Otherwise, returns a NULL type.
  1708. QualType Sema::BuildPointerType(QualType T,
  1709. SourceLocation Loc, DeclarationName Entity) {
  1710. if (T->isReferenceType()) {
  1711. // C++ 8.3.2p4: There shall be no ... pointers to references ...
  1712. Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
  1713. << getPrintableNameForEntity(Entity) << T;
  1714. return QualType();
  1715. }
  1716. if (T->isFunctionType() && getLangOpts().OpenCL) {
  1717. Diag(Loc, diag::err_opencl_function_pointer);
  1718. return QualType();
  1719. }
  1720. if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
  1721. return QualType();
  1722. assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
  1723. // In ARC, it is forbidden to build pointers to unqualified pointers.
  1724. if (getLangOpts().ObjCAutoRefCount)
  1725. T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
  1726. // Build the pointer type.
  1727. return Context.getPointerType(T);
  1728. }
  1729. /// Build a reference type.
  1730. ///
  1731. /// \param T The type to which we'll be building a reference.
  1732. ///
  1733. /// \param Loc The location of the entity whose type involves this
  1734. /// reference type or, if there is no such entity, the location of the
  1735. /// type that will have reference type.
  1736. ///
  1737. /// \param Entity The name of the entity that involves the reference
  1738. /// type, if known.
  1739. ///
  1740. /// \returns A suitable reference type, if there are no
  1741. /// errors. Otherwise, returns a NULL type.
  1742. QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
  1743. SourceLocation Loc,
  1744. DeclarationName Entity) {
  1745. assert(Context.getCanonicalType(T) != Context.OverloadTy &&
  1746. "Unresolved overloaded function type");
  1747. // C++0x [dcl.ref]p6:
  1748. // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
  1749. // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
  1750. // type T, an attempt to create the type "lvalue reference to cv TR" creates
  1751. // the type "lvalue reference to T", while an attempt to create the type
  1752. // "rvalue reference to cv TR" creates the type TR.
  1753. bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
  1754. // C++ [dcl.ref]p4: There shall be no references to references.
  1755. //
  1756. // According to C++ DR 106, references to references are only
  1757. // diagnosed when they are written directly (e.g., "int & &"),
  1758. // but not when they happen via a typedef:
  1759. //
  1760. // typedef int& intref;
  1761. // typedef intref& intref2;
  1762. //
  1763. // Parser::ParseDeclaratorInternal diagnoses the case where
  1764. // references are written directly; here, we handle the
  1765. // collapsing of references-to-references as described in C++0x.
  1766. // DR 106 and 540 introduce reference-collapsing into C++98/03.
  1767. // C++ [dcl.ref]p1:
  1768. // A declarator that specifies the type "reference to cv void"
  1769. // is ill-formed.
  1770. if (T->isVoidType()) {
  1771. Diag(Loc, diag::err_reference_to_void);
  1772. return QualType();
  1773. }
  1774. if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
  1775. return QualType();
  1776. // In ARC, it is forbidden to build references to unqualified pointers.
  1777. if (getLangOpts().ObjCAutoRefCount)
  1778. T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
  1779. // Handle restrict on references.
  1780. if (LValueRef)
  1781. return Context.getLValueReferenceType(T, SpelledAsLValue);
  1782. return Context.getRValueReferenceType(T);
  1783. }
  1784. /// Build a Read-only Pipe type.
  1785. ///
  1786. /// \param T The type to which we'll be building a Pipe.
  1787. ///
  1788. /// \param Loc We do not use it for now.
  1789. ///
  1790. /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
  1791. /// NULL type.
  1792. QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
  1793. return Context.getReadPipeType(T);
  1794. }
  1795. /// Build a Write-only Pipe type.
  1796. ///
  1797. /// \param T The type to which we'll be building a Pipe.
  1798. ///
  1799. /// \param Loc We do not use it for now.
  1800. ///
  1801. /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
  1802. /// NULL type.
  1803. QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
  1804. return Context.getWritePipeType(T);
  1805. }
  1806. /// Check whether the specified array size makes the array type a VLA. If so,
  1807. /// return true, if not, return the size of the array in SizeVal.
  1808. static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
  1809. // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
  1810. // (like gnu99, but not c99) accept any evaluatable value as an extension.
  1811. class VLADiagnoser : public Sema::VerifyICEDiagnoser {
  1812. public:
  1813. VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
  1814. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  1815. }
  1816. void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
  1817. S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
  1818. }
  1819. } Diagnoser;
  1820. return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
  1821. S.LangOpts.GNUMode ||
  1822. S.LangOpts.OpenCL).isInvalid();
  1823. }
  1824. /// Build an array type.
  1825. ///
  1826. /// \param T The type of each element in the array.
  1827. ///
  1828. /// \param ASM C99 array size modifier (e.g., '*', 'static').
  1829. ///
  1830. /// \param ArraySize Expression describing the size of the array.
  1831. ///
  1832. /// \param Brackets The range from the opening '[' to the closing ']'.
  1833. ///
  1834. /// \param Entity The name of the entity that involves the array
  1835. /// type, if known.
  1836. ///
  1837. /// \returns A suitable array type, if there are no errors. Otherwise,
  1838. /// returns a NULL type.
  1839. QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
  1840. Expr *ArraySize, unsigned Quals,
  1841. SourceRange Brackets, DeclarationName Entity) {
  1842. SourceLocation Loc = Brackets.getBegin();
  1843. if (getLangOpts().CPlusPlus) {
  1844. // C++ [dcl.array]p1:
  1845. // T is called the array element type; this type shall not be a reference
  1846. // type, the (possibly cv-qualified) type void, a function type or an
  1847. // abstract class type.
  1848. //
  1849. // C++ [dcl.array]p3:
  1850. // When several "array of" specifications are adjacent, [...] only the
  1851. // first of the constant expressions that specify the bounds of the arrays
  1852. // may be omitted.
  1853. //
  1854. // Note: function types are handled in the common path with C.
  1855. if (T->isReferenceType()) {
  1856. Diag(Loc, diag::err_illegal_decl_array_of_references)
  1857. << getPrintableNameForEntity(Entity) << T;
  1858. return QualType();
  1859. }
  1860. if (T->isVoidType() || T->isIncompleteArrayType()) {
  1861. Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
  1862. return QualType();
  1863. }
  1864. if (RequireNonAbstractType(Brackets.getBegin(), T,
  1865. diag::err_array_of_abstract_type))
  1866. return QualType();
  1867. // Mentioning a member pointer type for an array type causes us to lock in
  1868. // an inheritance model, even if it's inside an unused typedef.
  1869. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  1870. if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
  1871. if (!MPTy->getClass()->isDependentType())
  1872. (void)isCompleteType(Loc, T);
  1873. } else {
  1874. // C99 6.7.5.2p1: If the element type is an incomplete or function type,
  1875. // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
  1876. if (RequireCompleteType(Loc, T,
  1877. diag::err_illegal_decl_array_incomplete_type))
  1878. return QualType();
  1879. }
  1880. if (T->isFunctionType()) {
  1881. Diag(Loc, diag::err_illegal_decl_array_of_functions)
  1882. << getPrintableNameForEntity(Entity) << T;
  1883. return QualType();
  1884. }
  1885. if (const RecordType *EltTy = T->getAs<RecordType>()) {
  1886. // If the element type is a struct or union that contains a variadic
  1887. // array, accept it as a GNU extension: C99 6.7.2.1p2.
  1888. if (EltTy->getDecl()->hasFlexibleArrayMember())
  1889. Diag(Loc, diag::ext_flexible_array_in_array) << T;
  1890. } else if (T->isObjCObjectType()) {
  1891. Diag(Loc, diag::err_objc_array_of_interfaces) << T;
  1892. return QualType();
  1893. }
  1894. // Do placeholder conversions on the array size expression.
  1895. if (ArraySize && ArraySize->hasPlaceholderType()) {
  1896. ExprResult Result = CheckPlaceholderExpr(ArraySize);
  1897. if (Result.isInvalid()) return QualType();
  1898. ArraySize = Result.get();
  1899. }
  1900. // Do lvalue-to-rvalue conversions on the array size expression.
  1901. if (ArraySize && !ArraySize->isRValue()) {
  1902. ExprResult Result = DefaultLvalueConversion(ArraySize);
  1903. if (Result.isInvalid())
  1904. return QualType();
  1905. ArraySize = Result.get();
  1906. }
  1907. // C99 6.7.5.2p1: The size expression shall have integer type.
  1908. // C++11 allows contextual conversions to such types.
  1909. if (!getLangOpts().CPlusPlus11 &&
  1910. ArraySize && !ArraySize->isTypeDependent() &&
  1911. !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
  1912. Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
  1913. << ArraySize->getType() << ArraySize->getSourceRange();
  1914. return QualType();
  1915. }
  1916. llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
  1917. if (!ArraySize) {
  1918. if (ASM == ArrayType::Star)
  1919. T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
  1920. else
  1921. T = Context.getIncompleteArrayType(T, ASM, Quals);
  1922. } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
  1923. T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
  1924. } else if ((!T->isDependentType() && !T->isIncompleteType() &&
  1925. !T->isConstantSizeType()) ||
  1926. isArraySizeVLA(*this, ArraySize, ConstVal)) {
  1927. // Even in C++11, don't allow contextual conversions in the array bound
  1928. // of a VLA.
  1929. if (getLangOpts().CPlusPlus11 &&
  1930. !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
  1931. Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
  1932. << ArraySize->getType() << ArraySize->getSourceRange();
  1933. return QualType();
  1934. }
  1935. // C99: an array with an element type that has a non-constant-size is a VLA.
  1936. // C99: an array with a non-ICE size is a VLA. We accept any expression
  1937. // that we can fold to a non-zero positive value as an extension.
  1938. T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
  1939. } else {
  1940. // C99 6.7.5.2p1: If the expression is a constant expression, it shall
  1941. // have a value greater than zero.
  1942. if (ConstVal.isSigned() && ConstVal.isNegative()) {
  1943. if (Entity)
  1944. Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
  1945. << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
  1946. else
  1947. Diag(ArraySize->getBeginLoc(), diag::err_typecheck_negative_array_size)
  1948. << ArraySize->getSourceRange();
  1949. return QualType();
  1950. }
  1951. if (ConstVal == 0) {
  1952. // GCC accepts zero sized static arrays. We allow them when
  1953. // we're not in a SFINAE context.
  1954. Diag(ArraySize->getBeginLoc(), isSFINAEContext()
  1955. ? diag::err_typecheck_zero_array_size
  1956. : diag::ext_typecheck_zero_array_size)
  1957. << ArraySize->getSourceRange();
  1958. if (ASM == ArrayType::Static) {
  1959. Diag(ArraySize->getBeginLoc(),
  1960. diag::warn_typecheck_zero_static_array_size)
  1961. << ArraySize->getSourceRange();
  1962. ASM = ArrayType::Normal;
  1963. }
  1964. } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
  1965. !T->isIncompleteType() && !T->isUndeducedType()) {
  1966. // Is the array too large?
  1967. unsigned ActiveSizeBits
  1968. = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
  1969. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  1970. Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
  1971. << ConstVal.toString(10) << ArraySize->getSourceRange();
  1972. return QualType();
  1973. }
  1974. }
  1975. T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
  1976. }
  1977. // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
  1978. if (getLangOpts().OpenCL && T->isVariableArrayType()) {
  1979. Diag(Loc, diag::err_opencl_vla);
  1980. return QualType();
  1981. }
  1982. if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) {
  1983. // CUDA device code and some other targets don't support VLAs.
  1984. targetDiag(Loc, (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
  1985. ? diag::err_cuda_vla
  1986. : diag::err_vla_unsupported)
  1987. << ((getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
  1988. ? CurrentCUDATarget()
  1989. : CFT_InvalidTarget);
  1990. }
  1991. // If this is not C99, extwarn about VLA's and C99 array size modifiers.
  1992. if (!getLangOpts().C99) {
  1993. if (T->isVariableArrayType()) {
  1994. // Prohibit the use of VLAs during template argument deduction.
  1995. if (isSFINAEContext()) {
  1996. Diag(Loc, diag::err_vla_in_sfinae);
  1997. return QualType();
  1998. }
  1999. // Just extwarn about VLAs.
  2000. else
  2001. Diag(Loc, diag::ext_vla);
  2002. } else if (ASM != ArrayType::Normal || Quals != 0)
  2003. Diag(Loc,
  2004. getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
  2005. : diag::ext_c99_array_usage) << ASM;
  2006. }
  2007. if (T->isVariableArrayType()) {
  2008. // Warn about VLAs for -Wvla.
  2009. Diag(Loc, diag::warn_vla_used);
  2010. }
  2011. // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
  2012. // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
  2013. // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
  2014. if (getLangOpts().OpenCL) {
  2015. const QualType ArrType = Context.getBaseElementType(T);
  2016. if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
  2017. ArrType->isSamplerT() || ArrType->isImageType()) {
  2018. Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
  2019. return QualType();
  2020. }
  2021. }
  2022. return T;
  2023. }
  2024. QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
  2025. SourceLocation AttrLoc) {
  2026. // The base type must be integer (not Boolean or enumeration) or float, and
  2027. // can't already be a vector.
  2028. if (!CurType->isDependentType() &&
  2029. (!CurType->isBuiltinType() || CurType->isBooleanType() ||
  2030. (!CurType->isIntegerType() && !CurType->isRealFloatingType()))) {
  2031. Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
  2032. return QualType();
  2033. }
  2034. if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
  2035. return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
  2036. VectorType::GenericVector);
  2037. llvm::APSInt VecSize(32);
  2038. if (!SizeExpr->isIntegerConstantExpr(VecSize, Context)) {
  2039. Diag(AttrLoc, diag::err_attribute_argument_type)
  2040. << "vector_size" << AANT_ArgumentIntegerConstant
  2041. << SizeExpr->getSourceRange();
  2042. return QualType();
  2043. }
  2044. if (CurType->isDependentType())
  2045. return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
  2046. VectorType::GenericVector);
  2047. unsigned VectorSize = static_cast<unsigned>(VecSize.getZExtValue() * 8);
  2048. unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
  2049. if (VectorSize == 0) {
  2050. Diag(AttrLoc, diag::err_attribute_zero_size) << SizeExpr->getSourceRange();
  2051. return QualType();
  2052. }
  2053. // vecSize is specified in bytes - convert to bits.
  2054. if (VectorSize % TypeSize) {
  2055. Diag(AttrLoc, diag::err_attribute_invalid_size)
  2056. << SizeExpr->getSourceRange();
  2057. return QualType();
  2058. }
  2059. if (VectorType::isVectorSizeTooLarge(VectorSize / TypeSize)) {
  2060. Diag(AttrLoc, diag::err_attribute_size_too_large)
  2061. << SizeExpr->getSourceRange();
  2062. return QualType();
  2063. }
  2064. return Context.getVectorType(CurType, VectorSize / TypeSize,
  2065. VectorType::GenericVector);
  2066. }
  2067. /// Build an ext-vector type.
  2068. ///
  2069. /// Run the required checks for the extended vector type.
  2070. QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
  2071. SourceLocation AttrLoc) {
  2072. // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
  2073. // in conjunction with complex types (pointers, arrays, functions, etc.).
  2074. //
  2075. // Additionally, OpenCL prohibits vectors of booleans (they're considered a
  2076. // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
  2077. // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
  2078. // of bool aren't allowed.
  2079. if ((!T->isDependentType() && !T->isIntegerType() &&
  2080. !T->isRealFloatingType()) ||
  2081. T->isBooleanType()) {
  2082. Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
  2083. return QualType();
  2084. }
  2085. if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
  2086. llvm::APSInt vecSize(32);
  2087. if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
  2088. Diag(AttrLoc, diag::err_attribute_argument_type)
  2089. << "ext_vector_type" << AANT_ArgumentIntegerConstant
  2090. << ArraySize->getSourceRange();
  2091. return QualType();
  2092. }
  2093. // Unlike gcc's vector_size attribute, the size is specified as the
  2094. // number of elements, not the number of bytes.
  2095. unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
  2096. if (vectorSize == 0) {
  2097. Diag(AttrLoc, diag::err_attribute_zero_size)
  2098. << ArraySize->getSourceRange();
  2099. return QualType();
  2100. }
  2101. if (VectorType::isVectorSizeTooLarge(vectorSize)) {
  2102. Diag(AttrLoc, diag::err_attribute_size_too_large)
  2103. << ArraySize->getSourceRange();
  2104. return QualType();
  2105. }
  2106. return Context.getExtVectorType(T, vectorSize);
  2107. }
  2108. return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
  2109. }
  2110. bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
  2111. if (T->isArrayType() || T->isFunctionType()) {
  2112. Diag(Loc, diag::err_func_returning_array_function)
  2113. << T->isFunctionType() << T;
  2114. return true;
  2115. }
  2116. // Functions cannot return half FP.
  2117. if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
  2118. Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
  2119. FixItHint::CreateInsertion(Loc, "*");
  2120. return true;
  2121. }
  2122. // Methods cannot return interface types. All ObjC objects are
  2123. // passed by reference.
  2124. if (T->isObjCObjectType()) {
  2125. Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
  2126. << 0 << T << FixItHint::CreateInsertion(Loc, "*");
  2127. return true;
  2128. }
  2129. return false;
  2130. }
  2131. /// Check the extended parameter information. Most of the necessary
  2132. /// checking should occur when applying the parameter attribute; the
  2133. /// only other checks required are positional restrictions.
  2134. static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
  2135. const FunctionProtoType::ExtProtoInfo &EPI,
  2136. llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
  2137. assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
  2138. bool hasCheckedSwiftCall = false;
  2139. auto checkForSwiftCC = [&](unsigned paramIndex) {
  2140. // Only do this once.
  2141. if (hasCheckedSwiftCall) return;
  2142. hasCheckedSwiftCall = true;
  2143. if (EPI.ExtInfo.getCC() == CC_Swift) return;
  2144. S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
  2145. << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI());
  2146. };
  2147. for (size_t paramIndex = 0, numParams = paramTypes.size();
  2148. paramIndex != numParams; ++paramIndex) {
  2149. switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
  2150. // Nothing interesting to check for orindary-ABI parameters.
  2151. case ParameterABI::Ordinary:
  2152. continue;
  2153. // swift_indirect_result parameters must be a prefix of the function
  2154. // arguments.
  2155. case ParameterABI::SwiftIndirectResult:
  2156. checkForSwiftCC(paramIndex);
  2157. if (paramIndex != 0 &&
  2158. EPI.ExtParameterInfos[paramIndex - 1].getABI()
  2159. != ParameterABI::SwiftIndirectResult) {
  2160. S.Diag(getParamLoc(paramIndex),
  2161. diag::err_swift_indirect_result_not_first);
  2162. }
  2163. continue;
  2164. case ParameterABI::SwiftContext:
  2165. checkForSwiftCC(paramIndex);
  2166. continue;
  2167. // swift_error parameters must be preceded by a swift_context parameter.
  2168. case ParameterABI::SwiftErrorResult:
  2169. checkForSwiftCC(paramIndex);
  2170. if (paramIndex == 0 ||
  2171. EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
  2172. ParameterABI::SwiftContext) {
  2173. S.Diag(getParamLoc(paramIndex),
  2174. diag::err_swift_error_result_not_after_swift_context);
  2175. }
  2176. continue;
  2177. }
  2178. llvm_unreachable("bad ABI kind");
  2179. }
  2180. }
  2181. QualType Sema::BuildFunctionType(QualType T,
  2182. MutableArrayRef<QualType> ParamTypes,
  2183. SourceLocation Loc, DeclarationName Entity,
  2184. const FunctionProtoType::ExtProtoInfo &EPI) {
  2185. bool Invalid = false;
  2186. Invalid |= CheckFunctionReturnType(T, Loc);
  2187. for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
  2188. // FIXME: Loc is too inprecise here, should use proper locations for args.
  2189. QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
  2190. if (ParamType->isVoidType()) {
  2191. Diag(Loc, diag::err_param_with_void_type);
  2192. Invalid = true;
  2193. } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
  2194. // Disallow half FP arguments.
  2195. Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
  2196. FixItHint::CreateInsertion(Loc, "*");
  2197. Invalid = true;
  2198. }
  2199. ParamTypes[Idx] = ParamType;
  2200. }
  2201. if (EPI.ExtParameterInfos) {
  2202. checkExtParameterInfos(*this, ParamTypes, EPI,
  2203. [=](unsigned i) { return Loc; });
  2204. }
  2205. if (EPI.ExtInfo.getProducesResult()) {
  2206. // This is just a warning, so we can't fail to build if we see it.
  2207. checkNSReturnsRetainedReturnType(Loc, T);
  2208. }
  2209. if (Invalid)
  2210. return QualType();
  2211. return Context.getFunctionType(T, ParamTypes, EPI);
  2212. }
  2213. /// Build a member pointer type \c T Class::*.
  2214. ///
  2215. /// \param T the type to which the member pointer refers.
  2216. /// \param Class the class type into which the member pointer points.
  2217. /// \param Loc the location where this type begins
  2218. /// \param Entity the name of the entity that will have this member pointer type
  2219. ///
  2220. /// \returns a member pointer type, if successful, or a NULL type if there was
  2221. /// an error.
  2222. QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
  2223. SourceLocation Loc,
  2224. DeclarationName Entity) {
  2225. // Verify that we're not building a pointer to pointer to function with
  2226. // exception specification.
  2227. if (CheckDistantExceptionSpec(T)) {
  2228. Diag(Loc, diag::err_distant_exception_spec);
  2229. return QualType();
  2230. }
  2231. // C++ 8.3.3p3: A pointer to member shall not point to ... a member
  2232. // with reference type, or "cv void."
  2233. if (T->isReferenceType()) {
  2234. Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
  2235. << getPrintableNameForEntity(Entity) << T;
  2236. return QualType();
  2237. }
  2238. if (T->isVoidType()) {
  2239. Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
  2240. << getPrintableNameForEntity(Entity);
  2241. return QualType();
  2242. }
  2243. if (!Class->isDependentType() && !Class->isRecordType()) {
  2244. Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
  2245. return QualType();
  2246. }
  2247. // Adjust the default free function calling convention to the default method
  2248. // calling convention.
  2249. bool IsCtorOrDtor =
  2250. (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
  2251. (Entity.getNameKind() == DeclarationName::CXXDestructorName);
  2252. if (T->isFunctionType())
  2253. adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
  2254. return Context.getMemberPointerType(T, Class.getTypePtr());
  2255. }
  2256. /// Build a block pointer type.
  2257. ///
  2258. /// \param T The type to which we'll be building a block pointer.
  2259. ///
  2260. /// \param Loc The source location, used for diagnostics.
  2261. ///
  2262. /// \param Entity The name of the entity that involves the block pointer
  2263. /// type, if known.
  2264. ///
  2265. /// \returns A suitable block pointer type, if there are no
  2266. /// errors. Otherwise, returns a NULL type.
  2267. QualType Sema::BuildBlockPointerType(QualType T,
  2268. SourceLocation Loc,
  2269. DeclarationName Entity) {
  2270. if (!T->isFunctionType()) {
  2271. Diag(Loc, diag::err_nonfunction_block_type);
  2272. return QualType();
  2273. }
  2274. if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
  2275. return QualType();
  2276. return Context.getBlockPointerType(T);
  2277. }
  2278. QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
  2279. QualType QT = Ty.get();
  2280. if (QT.isNull()) {
  2281. if (TInfo) *TInfo = nullptr;
  2282. return QualType();
  2283. }
  2284. TypeSourceInfo *DI = nullptr;
  2285. if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
  2286. QT = LIT->getType();
  2287. DI = LIT->getTypeSourceInfo();
  2288. }
  2289. if (TInfo) *TInfo = DI;
  2290. return QT;
  2291. }
  2292. static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
  2293. Qualifiers::ObjCLifetime ownership,
  2294. unsigned chunkIndex);
  2295. /// Given that this is the declaration of a parameter under ARC,
  2296. /// attempt to infer attributes and such for pointer-to-whatever
  2297. /// types.
  2298. static void inferARCWriteback(TypeProcessingState &state,
  2299. QualType &declSpecType) {
  2300. Sema &S = state.getSema();
  2301. Declarator &declarator = state.getDeclarator();
  2302. // TODO: should we care about decl qualifiers?
  2303. // Check whether the declarator has the expected form. We walk
  2304. // from the inside out in order to make the block logic work.
  2305. unsigned outermostPointerIndex = 0;
  2306. bool isBlockPointer = false;
  2307. unsigned numPointers = 0;
  2308. for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
  2309. unsigned chunkIndex = i;
  2310. DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
  2311. switch (chunk.Kind) {
  2312. case DeclaratorChunk::Paren:
  2313. // Ignore parens.
  2314. break;
  2315. case DeclaratorChunk::Reference:
  2316. case DeclaratorChunk::Pointer:
  2317. // Count the number of pointers. Treat references
  2318. // interchangeably as pointers; if they're mis-ordered, normal
  2319. // type building will discover that.
  2320. outermostPointerIndex = chunkIndex;
  2321. numPointers++;
  2322. break;
  2323. case DeclaratorChunk::BlockPointer:
  2324. // If we have a pointer to block pointer, that's an acceptable
  2325. // indirect reference; anything else is not an application of
  2326. // the rules.
  2327. if (numPointers != 1) return;
  2328. numPointers++;
  2329. outermostPointerIndex = chunkIndex;
  2330. isBlockPointer = true;
  2331. // We don't care about pointer structure in return values here.
  2332. goto done;
  2333. case DeclaratorChunk::Array: // suppress if written (id[])?
  2334. case DeclaratorChunk::Function:
  2335. case DeclaratorChunk::MemberPointer:
  2336. case DeclaratorChunk::Pipe:
  2337. return;
  2338. }
  2339. }
  2340. done:
  2341. // If we have *one* pointer, then we want to throw the qualifier on
  2342. // the declaration-specifiers, which means that it needs to be a
  2343. // retainable object type.
  2344. if (numPointers == 1) {
  2345. // If it's not a retainable object type, the rule doesn't apply.
  2346. if (!declSpecType->isObjCRetainableType()) return;
  2347. // If it already has lifetime, don't do anything.
  2348. if (declSpecType.getObjCLifetime()) return;
  2349. // Otherwise, modify the type in-place.
  2350. Qualifiers qs;
  2351. if (declSpecType->isObjCARCImplicitlyUnretainedType())
  2352. qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
  2353. else
  2354. qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
  2355. declSpecType = S.Context.getQualifiedType(declSpecType, qs);
  2356. // If we have *two* pointers, then we want to throw the qualifier on
  2357. // the outermost pointer.
  2358. } else if (numPointers == 2) {
  2359. // If we don't have a block pointer, we need to check whether the
  2360. // declaration-specifiers gave us something that will turn into a
  2361. // retainable object pointer after we slap the first pointer on it.
  2362. if (!isBlockPointer && !declSpecType->isObjCObjectType())
  2363. return;
  2364. // Look for an explicit lifetime attribute there.
  2365. DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
  2366. if (chunk.Kind != DeclaratorChunk::Pointer &&
  2367. chunk.Kind != DeclaratorChunk::BlockPointer)
  2368. return;
  2369. for (const ParsedAttr &AL : chunk.getAttrs())
  2370. if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
  2371. return;
  2372. transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
  2373. outermostPointerIndex);
  2374. // Any other number of pointers/references does not trigger the rule.
  2375. } else return;
  2376. // TODO: mark whether we did this inference?
  2377. }
  2378. void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
  2379. SourceLocation FallbackLoc,
  2380. SourceLocation ConstQualLoc,
  2381. SourceLocation VolatileQualLoc,
  2382. SourceLocation RestrictQualLoc,
  2383. SourceLocation AtomicQualLoc,
  2384. SourceLocation UnalignedQualLoc) {
  2385. if (!Quals)
  2386. return;
  2387. struct Qual {
  2388. const char *Name;
  2389. unsigned Mask;
  2390. SourceLocation Loc;
  2391. } const QualKinds[5] = {
  2392. { "const", DeclSpec::TQ_const, ConstQualLoc },
  2393. { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
  2394. { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
  2395. { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
  2396. { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
  2397. };
  2398. SmallString<32> QualStr;
  2399. unsigned NumQuals = 0;
  2400. SourceLocation Loc;
  2401. FixItHint FixIts[5];
  2402. // Build a string naming the redundant qualifiers.
  2403. for (auto &E : QualKinds) {
  2404. if (Quals & E.Mask) {
  2405. if (!QualStr.empty()) QualStr += ' ';
  2406. QualStr += E.Name;
  2407. // If we have a location for the qualifier, offer a fixit.
  2408. SourceLocation QualLoc = E.Loc;
  2409. if (QualLoc.isValid()) {
  2410. FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
  2411. if (Loc.isInvalid() ||
  2412. getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
  2413. Loc = QualLoc;
  2414. }
  2415. ++NumQuals;
  2416. }
  2417. }
  2418. Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
  2419. << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
  2420. }
  2421. // Diagnose pointless type qualifiers on the return type of a function.
  2422. static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
  2423. Declarator &D,
  2424. unsigned FunctionChunkIndex) {
  2425. if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
  2426. // FIXME: TypeSourceInfo doesn't preserve location information for
  2427. // qualifiers.
  2428. S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
  2429. RetTy.getLocalCVRQualifiers(),
  2430. D.getIdentifierLoc());
  2431. return;
  2432. }
  2433. for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
  2434. End = D.getNumTypeObjects();
  2435. OuterChunkIndex != End; ++OuterChunkIndex) {
  2436. DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
  2437. switch (OuterChunk.Kind) {
  2438. case DeclaratorChunk::Paren:
  2439. continue;
  2440. case DeclaratorChunk::Pointer: {
  2441. DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
  2442. S.diagnoseIgnoredQualifiers(
  2443. diag::warn_qual_return_type,
  2444. PTI.TypeQuals,
  2445. SourceLocation(),
  2446. SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
  2447. SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
  2448. SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
  2449. SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc),
  2450. SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc));
  2451. return;
  2452. }
  2453. case DeclaratorChunk::Function:
  2454. case DeclaratorChunk::BlockPointer:
  2455. case DeclaratorChunk::Reference:
  2456. case DeclaratorChunk::Array:
  2457. case DeclaratorChunk::MemberPointer:
  2458. case DeclaratorChunk::Pipe:
  2459. // FIXME: We can't currently provide an accurate source location and a
  2460. // fix-it hint for these.
  2461. unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
  2462. S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
  2463. RetTy.getCVRQualifiers() | AtomicQual,
  2464. D.getIdentifierLoc());
  2465. return;
  2466. }
  2467. llvm_unreachable("unknown declarator chunk kind");
  2468. }
  2469. // If the qualifiers come from a conversion function type, don't diagnose
  2470. // them -- they're not necessarily redundant, since such a conversion
  2471. // operator can be explicitly called as "x.operator const int()".
  2472. if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
  2473. return;
  2474. // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
  2475. // which are present there.
  2476. S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
  2477. D.getDeclSpec().getTypeQualifiers(),
  2478. D.getIdentifierLoc(),
  2479. D.getDeclSpec().getConstSpecLoc(),
  2480. D.getDeclSpec().getVolatileSpecLoc(),
  2481. D.getDeclSpec().getRestrictSpecLoc(),
  2482. D.getDeclSpec().getAtomicSpecLoc(),
  2483. D.getDeclSpec().getUnalignedSpecLoc());
  2484. }
  2485. static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
  2486. TypeSourceInfo *&ReturnTypeInfo) {
  2487. Sema &SemaRef = state.getSema();
  2488. Declarator &D = state.getDeclarator();
  2489. QualType T;
  2490. ReturnTypeInfo = nullptr;
  2491. // The TagDecl owned by the DeclSpec.
  2492. TagDecl *OwnedTagDecl = nullptr;
  2493. switch (D.getName().getKind()) {
  2494. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  2495. case UnqualifiedIdKind::IK_OperatorFunctionId:
  2496. case UnqualifiedIdKind::IK_Identifier:
  2497. case UnqualifiedIdKind::IK_LiteralOperatorId:
  2498. case UnqualifiedIdKind::IK_TemplateId:
  2499. T = ConvertDeclSpecToType(state);
  2500. if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
  2501. OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  2502. // Owned declaration is embedded in declarator.
  2503. OwnedTagDecl->setEmbeddedInDeclarator(true);
  2504. }
  2505. break;
  2506. case UnqualifiedIdKind::IK_ConstructorName:
  2507. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  2508. case UnqualifiedIdKind::IK_DestructorName:
  2509. // Constructors and destructors don't have return types. Use
  2510. // "void" instead.
  2511. T = SemaRef.Context.VoidTy;
  2512. processTypeAttrs(state, T, TAL_DeclSpec,
  2513. D.getMutableDeclSpec().getAttributes());
  2514. break;
  2515. case UnqualifiedIdKind::IK_DeductionGuideName:
  2516. // Deduction guides have a trailing return type and no type in their
  2517. // decl-specifier sequence. Use a placeholder return type for now.
  2518. T = SemaRef.Context.DependentTy;
  2519. break;
  2520. case UnqualifiedIdKind::IK_ConversionFunctionId:
  2521. // The result type of a conversion function is the type that it
  2522. // converts to.
  2523. T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
  2524. &ReturnTypeInfo);
  2525. break;
  2526. }
  2527. if (!D.getAttributes().empty())
  2528. distributeTypeAttrsFromDeclarator(state, T);
  2529. // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
  2530. if (DeducedType *Deduced = T->getContainedDeducedType()) {
  2531. AutoType *Auto = dyn_cast<AutoType>(Deduced);
  2532. int Error = -1;
  2533. // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
  2534. // class template argument deduction)?
  2535. bool IsCXXAutoType =
  2536. (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
  2537. bool IsDeducedReturnType = false;
  2538. switch (D.getContext()) {
  2539. case DeclaratorContext::LambdaExprContext:
  2540. // Declared return type of a lambda-declarator is implicit and is always
  2541. // 'auto'.
  2542. break;
  2543. case DeclaratorContext::ObjCParameterContext:
  2544. case DeclaratorContext::ObjCResultContext:
  2545. case DeclaratorContext::PrototypeContext:
  2546. Error = 0;
  2547. break;
  2548. case DeclaratorContext::LambdaExprParameterContext:
  2549. // In C++14, generic lambdas allow 'auto' in their parameters.
  2550. if (!SemaRef.getLangOpts().CPlusPlus14 ||
  2551. !Auto || Auto->getKeyword() != AutoTypeKeyword::Auto)
  2552. Error = 16;
  2553. else {
  2554. // If auto is mentioned in a lambda parameter context, convert it to a
  2555. // template parameter type.
  2556. sema::LambdaScopeInfo *LSI = SemaRef.getCurLambda();
  2557. assert(LSI && "No LambdaScopeInfo on the stack!");
  2558. const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
  2559. const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
  2560. const bool IsParameterPack = D.hasEllipsis();
  2561. // Create the TemplateTypeParmDecl here to retrieve the corresponding
  2562. // template parameter type. Template parameters are temporarily added
  2563. // to the TU until the associated TemplateDecl is created.
  2564. TemplateTypeParmDecl *CorrespondingTemplateParam =
  2565. TemplateTypeParmDecl::Create(
  2566. SemaRef.Context, SemaRef.Context.getTranslationUnitDecl(),
  2567. /*KeyLoc*/ SourceLocation(), /*NameLoc*/ D.getBeginLoc(),
  2568. TemplateParameterDepth, AutoParameterPosition,
  2569. /*Identifier*/ nullptr, false, IsParameterPack);
  2570. LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
  2571. // Replace the 'auto' in the function parameter with this invented
  2572. // template type parameter.
  2573. // FIXME: Retain some type sugar to indicate that this was written
  2574. // as 'auto'.
  2575. T = state.ReplaceAutoType(
  2576. T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0));
  2577. }
  2578. break;
  2579. case DeclaratorContext::MemberContext: {
  2580. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
  2581. D.isFunctionDeclarator())
  2582. break;
  2583. bool Cxx = SemaRef.getLangOpts().CPlusPlus;
  2584. switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
  2585. case TTK_Enum: llvm_unreachable("unhandled tag kind");
  2586. case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
  2587. case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
  2588. case TTK_Class: Error = 5; /* Class member */ break;
  2589. case TTK_Interface: Error = 6; /* Interface member */ break;
  2590. }
  2591. if (D.getDeclSpec().isFriendSpecified())
  2592. Error = 20; // Friend type
  2593. break;
  2594. }
  2595. case DeclaratorContext::CXXCatchContext:
  2596. case DeclaratorContext::ObjCCatchContext:
  2597. Error = 7; // Exception declaration
  2598. break;
  2599. case DeclaratorContext::TemplateParamContext:
  2600. if (isa<DeducedTemplateSpecializationType>(Deduced))
  2601. Error = 19; // Template parameter
  2602. else if (!SemaRef.getLangOpts().CPlusPlus17)
  2603. Error = 8; // Template parameter (until C++17)
  2604. break;
  2605. case DeclaratorContext::BlockLiteralContext:
  2606. Error = 9; // Block literal
  2607. break;
  2608. case DeclaratorContext::TemplateArgContext:
  2609. // Within a template argument list, a deduced template specialization
  2610. // type will be reinterpreted as a template template argument.
  2611. if (isa<DeducedTemplateSpecializationType>(Deduced) &&
  2612. !D.getNumTypeObjects() &&
  2613. D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier)
  2614. break;
  2615. LLVM_FALLTHROUGH;
  2616. case DeclaratorContext::TemplateTypeArgContext:
  2617. Error = 10; // Template type argument
  2618. break;
  2619. case DeclaratorContext::AliasDeclContext:
  2620. case DeclaratorContext::AliasTemplateContext:
  2621. Error = 12; // Type alias
  2622. break;
  2623. case DeclaratorContext::TrailingReturnContext:
  2624. case DeclaratorContext::TrailingReturnVarContext:
  2625. if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
  2626. Error = 13; // Function return type
  2627. IsDeducedReturnType = true;
  2628. break;
  2629. case DeclaratorContext::ConversionIdContext:
  2630. if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
  2631. Error = 14; // conversion-type-id
  2632. IsDeducedReturnType = true;
  2633. break;
  2634. case DeclaratorContext::FunctionalCastContext:
  2635. if (isa<DeducedTemplateSpecializationType>(Deduced))
  2636. break;
  2637. LLVM_FALLTHROUGH;
  2638. case DeclaratorContext::TypeNameContext:
  2639. Error = 15; // Generic
  2640. break;
  2641. case DeclaratorContext::FileContext:
  2642. case DeclaratorContext::BlockContext:
  2643. case DeclaratorContext::ForContext:
  2644. case DeclaratorContext::InitStmtContext:
  2645. case DeclaratorContext::ConditionContext:
  2646. // FIXME: P0091R3 (erroneously) does not permit class template argument
  2647. // deduction in conditions, for-init-statements, and other declarations
  2648. // that are not simple-declarations.
  2649. break;
  2650. case DeclaratorContext::CXXNewContext:
  2651. // FIXME: P0091R3 does not permit class template argument deduction here,
  2652. // but we follow GCC and allow it anyway.
  2653. if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
  2654. Error = 17; // 'new' type
  2655. break;
  2656. case DeclaratorContext::KNRTypeListContext:
  2657. Error = 18; // K&R function parameter
  2658. break;
  2659. }
  2660. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  2661. Error = 11;
  2662. // In Objective-C it is an error to use 'auto' on a function declarator
  2663. // (and everywhere for '__auto_type').
  2664. if (D.isFunctionDeclarator() &&
  2665. (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
  2666. Error = 13;
  2667. bool HaveTrailing = false;
  2668. // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
  2669. // contains a trailing return type. That is only legal at the outermost
  2670. // level. Check all declarator chunks (outermost first) anyway, to give
  2671. // better diagnostics.
  2672. // We don't support '__auto_type' with trailing return types.
  2673. // FIXME: Should we only do this for 'auto' and not 'decltype(auto)'?
  2674. if (SemaRef.getLangOpts().CPlusPlus11 && IsCXXAutoType &&
  2675. D.hasTrailingReturnType()) {
  2676. HaveTrailing = true;
  2677. Error = -1;
  2678. }
  2679. SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
  2680. if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
  2681. AutoRange = D.getName().getSourceRange();
  2682. if (Error != -1) {
  2683. unsigned Kind;
  2684. if (Auto) {
  2685. switch (Auto->getKeyword()) {
  2686. case AutoTypeKeyword::Auto: Kind = 0; break;
  2687. case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
  2688. case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
  2689. }
  2690. } else {
  2691. assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
  2692. "unknown auto type");
  2693. Kind = 3;
  2694. }
  2695. auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
  2696. TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
  2697. SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
  2698. << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
  2699. << QualType(Deduced, 0) << AutoRange;
  2700. if (auto *TD = TN.getAsTemplateDecl())
  2701. SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
  2702. T = SemaRef.Context.IntTy;
  2703. D.setInvalidType(true);
  2704. } else if (!HaveTrailing &&
  2705. D.getContext() != DeclaratorContext::LambdaExprContext) {
  2706. // If there was a trailing return type, we already got
  2707. // warn_cxx98_compat_trailing_return_type in the parser.
  2708. SemaRef.Diag(AutoRange.getBegin(),
  2709. D.getContext() ==
  2710. DeclaratorContext::LambdaExprParameterContext
  2711. ? diag::warn_cxx11_compat_generic_lambda
  2712. : IsDeducedReturnType
  2713. ? diag::warn_cxx11_compat_deduced_return_type
  2714. : diag::warn_cxx98_compat_auto_type_specifier)
  2715. << AutoRange;
  2716. }
  2717. }
  2718. if (SemaRef.getLangOpts().CPlusPlus &&
  2719. OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
  2720. // Check the contexts where C++ forbids the declaration of a new class
  2721. // or enumeration in a type-specifier-seq.
  2722. unsigned DiagID = 0;
  2723. switch (D.getContext()) {
  2724. case DeclaratorContext::TrailingReturnContext:
  2725. case DeclaratorContext::TrailingReturnVarContext:
  2726. // Class and enumeration definitions are syntactically not allowed in
  2727. // trailing return types.
  2728. llvm_unreachable("parser should not have allowed this");
  2729. break;
  2730. case DeclaratorContext::FileContext:
  2731. case DeclaratorContext::MemberContext:
  2732. case DeclaratorContext::BlockContext:
  2733. case DeclaratorContext::ForContext:
  2734. case DeclaratorContext::InitStmtContext:
  2735. case DeclaratorContext::BlockLiteralContext:
  2736. case DeclaratorContext::LambdaExprContext:
  2737. // C++11 [dcl.type]p3:
  2738. // A type-specifier-seq shall not define a class or enumeration unless
  2739. // it appears in the type-id of an alias-declaration (7.1.3) that is not
  2740. // the declaration of a template-declaration.
  2741. case DeclaratorContext::AliasDeclContext:
  2742. break;
  2743. case DeclaratorContext::AliasTemplateContext:
  2744. DiagID = diag::err_type_defined_in_alias_template;
  2745. break;
  2746. case DeclaratorContext::TypeNameContext:
  2747. case DeclaratorContext::FunctionalCastContext:
  2748. case DeclaratorContext::ConversionIdContext:
  2749. case DeclaratorContext::TemplateParamContext:
  2750. case DeclaratorContext::CXXNewContext:
  2751. case DeclaratorContext::CXXCatchContext:
  2752. case DeclaratorContext::ObjCCatchContext:
  2753. case DeclaratorContext::TemplateArgContext:
  2754. case DeclaratorContext::TemplateTypeArgContext:
  2755. DiagID = diag::err_type_defined_in_type_specifier;
  2756. break;
  2757. case DeclaratorContext::PrototypeContext:
  2758. case DeclaratorContext::LambdaExprParameterContext:
  2759. case DeclaratorContext::ObjCParameterContext:
  2760. case DeclaratorContext::ObjCResultContext:
  2761. case DeclaratorContext::KNRTypeListContext:
  2762. // C++ [dcl.fct]p6:
  2763. // Types shall not be defined in return or parameter types.
  2764. DiagID = diag::err_type_defined_in_param_type;
  2765. break;
  2766. case DeclaratorContext::ConditionContext:
  2767. // C++ 6.4p2:
  2768. // The type-specifier-seq shall not contain typedef and shall not declare
  2769. // a new class or enumeration.
  2770. DiagID = diag::err_type_defined_in_condition;
  2771. break;
  2772. }
  2773. if (DiagID != 0) {
  2774. SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
  2775. << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
  2776. D.setInvalidType(true);
  2777. }
  2778. }
  2779. assert(!T.isNull() && "This function should not return a null type");
  2780. return T;
  2781. }
  2782. /// Produce an appropriate diagnostic for an ambiguity between a function
  2783. /// declarator and a C++ direct-initializer.
  2784. static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
  2785. DeclaratorChunk &DeclType, QualType RT) {
  2786. const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
  2787. assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
  2788. // If the return type is void there is no ambiguity.
  2789. if (RT->isVoidType())
  2790. return;
  2791. // An initializer for a non-class type can have at most one argument.
  2792. if (!RT->isRecordType() && FTI.NumParams > 1)
  2793. return;
  2794. // An initializer for a reference must have exactly one argument.
  2795. if (RT->isReferenceType() && FTI.NumParams != 1)
  2796. return;
  2797. // Only warn if this declarator is declaring a function at block scope, and
  2798. // doesn't have a storage class (such as 'extern') specified.
  2799. if (!D.isFunctionDeclarator() ||
  2800. D.getFunctionDefinitionKind() != FDK_Declaration ||
  2801. !S.CurContext->isFunctionOrMethod() ||
  2802. D.getDeclSpec().getStorageClassSpec()
  2803. != DeclSpec::SCS_unspecified)
  2804. return;
  2805. // Inside a condition, a direct initializer is not permitted. We allow one to
  2806. // be parsed in order to give better diagnostics in condition parsing.
  2807. if (D.getContext() == DeclaratorContext::ConditionContext)
  2808. return;
  2809. SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
  2810. S.Diag(DeclType.Loc,
  2811. FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
  2812. : diag::warn_empty_parens_are_function_decl)
  2813. << ParenRange;
  2814. // If the declaration looks like:
  2815. // T var1,
  2816. // f();
  2817. // and name lookup finds a function named 'f', then the ',' was
  2818. // probably intended to be a ';'.
  2819. if (!D.isFirstDeclarator() && D.getIdentifier()) {
  2820. FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
  2821. FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
  2822. if (Comma.getFileID() != Name.getFileID() ||
  2823. Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
  2824. LookupResult Result(S, D.getIdentifier(), SourceLocation(),
  2825. Sema::LookupOrdinaryName);
  2826. if (S.LookupName(Result, S.getCurScope()))
  2827. S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
  2828. << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
  2829. << D.getIdentifier();
  2830. Result.suppressDiagnostics();
  2831. }
  2832. }
  2833. if (FTI.NumParams > 0) {
  2834. // For a declaration with parameters, eg. "T var(T());", suggest adding
  2835. // parens around the first parameter to turn the declaration into a
  2836. // variable declaration.
  2837. SourceRange Range = FTI.Params[0].Param->getSourceRange();
  2838. SourceLocation B = Range.getBegin();
  2839. SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
  2840. // FIXME: Maybe we should suggest adding braces instead of parens
  2841. // in C++11 for classes that don't have an initializer_list constructor.
  2842. S.Diag(B, diag::note_additional_parens_for_variable_declaration)
  2843. << FixItHint::CreateInsertion(B, "(")
  2844. << FixItHint::CreateInsertion(E, ")");
  2845. } else {
  2846. // For a declaration without parameters, eg. "T var();", suggest replacing
  2847. // the parens with an initializer to turn the declaration into a variable
  2848. // declaration.
  2849. const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
  2850. // Empty parens mean value-initialization, and no parens mean
  2851. // default initialization. These are equivalent if the default
  2852. // constructor is user-provided or if zero-initialization is a
  2853. // no-op.
  2854. if (RD && RD->hasDefinition() &&
  2855. (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
  2856. S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
  2857. << FixItHint::CreateRemoval(ParenRange);
  2858. else {
  2859. std::string Init =
  2860. S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
  2861. if (Init.empty() && S.LangOpts.CPlusPlus11)
  2862. Init = "{}";
  2863. if (!Init.empty())
  2864. S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
  2865. << FixItHint::CreateReplacement(ParenRange, Init);
  2866. }
  2867. }
  2868. }
  2869. /// Produce an appropriate diagnostic for a declarator with top-level
  2870. /// parentheses.
  2871. static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
  2872. DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
  2873. assert(Paren.Kind == DeclaratorChunk::Paren &&
  2874. "do not have redundant top-level parentheses");
  2875. // This is a syntactic check; we're not interested in cases that arise
  2876. // during template instantiation.
  2877. if (S.inTemplateInstantiation())
  2878. return;
  2879. // Check whether this could be intended to be a construction of a temporary
  2880. // object in C++ via a function-style cast.
  2881. bool CouldBeTemporaryObject =
  2882. S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
  2883. !D.isInvalidType() && D.getIdentifier() &&
  2884. D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
  2885. (T->isRecordType() || T->isDependentType()) &&
  2886. D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator();
  2887. bool StartsWithDeclaratorId = true;
  2888. for (auto &C : D.type_objects()) {
  2889. switch (C.Kind) {
  2890. case DeclaratorChunk::Paren:
  2891. if (&C == &Paren)
  2892. continue;
  2893. LLVM_FALLTHROUGH;
  2894. case DeclaratorChunk::Pointer:
  2895. StartsWithDeclaratorId = false;
  2896. continue;
  2897. case DeclaratorChunk::Array:
  2898. if (!C.Arr.NumElts)
  2899. CouldBeTemporaryObject = false;
  2900. continue;
  2901. case DeclaratorChunk::Reference:
  2902. // FIXME: Suppress the warning here if there is no initializer; we're
  2903. // going to give an error anyway.
  2904. // We assume that something like 'T (&x) = y;' is highly likely to not
  2905. // be intended to be a temporary object.
  2906. CouldBeTemporaryObject = false;
  2907. StartsWithDeclaratorId = false;
  2908. continue;
  2909. case DeclaratorChunk::Function:
  2910. // In a new-type-id, function chunks require parentheses.
  2911. if (D.getContext() == DeclaratorContext::CXXNewContext)
  2912. return;
  2913. // FIXME: "A(f())" deserves a vexing-parse warning, not just a
  2914. // redundant-parens warning, but we don't know whether the function
  2915. // chunk was syntactically valid as an expression here.
  2916. CouldBeTemporaryObject = false;
  2917. continue;
  2918. case DeclaratorChunk::BlockPointer:
  2919. case DeclaratorChunk::MemberPointer:
  2920. case DeclaratorChunk::Pipe:
  2921. // These cannot appear in expressions.
  2922. CouldBeTemporaryObject = false;
  2923. StartsWithDeclaratorId = false;
  2924. continue;
  2925. }
  2926. }
  2927. // FIXME: If there is an initializer, assume that this is not intended to be
  2928. // a construction of a temporary object.
  2929. // Check whether the name has already been declared; if not, this is not a
  2930. // function-style cast.
  2931. if (CouldBeTemporaryObject) {
  2932. LookupResult Result(S, D.getIdentifier(), SourceLocation(),
  2933. Sema::LookupOrdinaryName);
  2934. if (!S.LookupName(Result, S.getCurScope()))
  2935. CouldBeTemporaryObject = false;
  2936. Result.suppressDiagnostics();
  2937. }
  2938. SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
  2939. if (!CouldBeTemporaryObject) {
  2940. // If we have A (::B), the parentheses affect the meaning of the program.
  2941. // Suppress the warning in that case. Don't bother looking at the DeclSpec
  2942. // here: even (e.g.) "int ::x" is visually ambiguous even though it's
  2943. // formally unambiguous.
  2944. if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
  2945. for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
  2946. NNS = NNS->getPrefix()) {
  2947. if (NNS->getKind() == NestedNameSpecifier::Global)
  2948. return;
  2949. }
  2950. }
  2951. S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
  2952. << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
  2953. << FixItHint::CreateRemoval(Paren.EndLoc);
  2954. return;
  2955. }
  2956. S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
  2957. << ParenRange << D.getIdentifier();
  2958. auto *RD = T->getAsCXXRecordDecl();
  2959. if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
  2960. S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
  2961. << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
  2962. << D.getIdentifier();
  2963. // FIXME: A cast to void is probably a better suggestion in cases where it's
  2964. // valid (when there is no initializer and we're not in a condition).
  2965. S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
  2966. << FixItHint::CreateInsertion(D.getBeginLoc(), "(")
  2967. << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")");
  2968. S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
  2969. << FixItHint::CreateRemoval(Paren.Loc)
  2970. << FixItHint::CreateRemoval(Paren.EndLoc);
  2971. }
  2972. /// Helper for figuring out the default CC for a function declarator type. If
  2973. /// this is the outermost chunk, then we can determine the CC from the
  2974. /// declarator context. If not, then this could be either a member function
  2975. /// type or normal function type.
  2976. static CallingConv getCCForDeclaratorChunk(
  2977. Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
  2978. const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
  2979. assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
  2980. // Check for an explicit CC attribute.
  2981. for (const ParsedAttr &AL : AttrList) {
  2982. switch (AL.getKind()) {
  2983. CALLING_CONV_ATTRS_CASELIST : {
  2984. // Ignore attributes that don't validate or can't apply to the
  2985. // function type. We'll diagnose the failure to apply them in
  2986. // handleFunctionTypeAttr.
  2987. CallingConv CC;
  2988. if (!S.CheckCallingConvAttr(AL, CC) &&
  2989. (!FTI.isVariadic || supportsVariadicCall(CC))) {
  2990. return CC;
  2991. }
  2992. break;
  2993. }
  2994. default:
  2995. break;
  2996. }
  2997. }
  2998. bool IsCXXInstanceMethod = false;
  2999. if (S.getLangOpts().CPlusPlus) {
  3000. // Look inwards through parentheses to see if this chunk will form a
  3001. // member pointer type or if we're the declarator. Any type attributes
  3002. // between here and there will override the CC we choose here.
  3003. unsigned I = ChunkIndex;
  3004. bool FoundNonParen = false;
  3005. while (I && !FoundNonParen) {
  3006. --I;
  3007. if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
  3008. FoundNonParen = true;
  3009. }
  3010. if (FoundNonParen) {
  3011. // If we're not the declarator, we're a regular function type unless we're
  3012. // in a member pointer.
  3013. IsCXXInstanceMethod =
  3014. D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
  3015. } else if (D.getContext() == DeclaratorContext::LambdaExprContext) {
  3016. // This can only be a call operator for a lambda, which is an instance
  3017. // method.
  3018. IsCXXInstanceMethod = true;
  3019. } else {
  3020. // We're the innermost decl chunk, so must be a function declarator.
  3021. assert(D.isFunctionDeclarator());
  3022. // If we're inside a record, we're declaring a method, but it could be
  3023. // explicitly or implicitly static.
  3024. IsCXXInstanceMethod =
  3025. D.isFirstDeclarationOfMember() &&
  3026. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  3027. !D.isStaticMember();
  3028. }
  3029. }
  3030. CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
  3031. IsCXXInstanceMethod);
  3032. // Attribute AT_OpenCLKernel affects the calling convention for SPIR
  3033. // and AMDGPU targets, hence it cannot be treated as a calling
  3034. // convention attribute. This is the simplest place to infer
  3035. // calling convention for OpenCL kernels.
  3036. if (S.getLangOpts().OpenCL) {
  3037. for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
  3038. if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
  3039. CC = CC_OpenCLKernel;
  3040. break;
  3041. }
  3042. }
  3043. }
  3044. return CC;
  3045. }
  3046. namespace {
  3047. /// A simple notion of pointer kinds, which matches up with the various
  3048. /// pointer declarators.
  3049. enum class SimplePointerKind {
  3050. Pointer,
  3051. BlockPointer,
  3052. MemberPointer,
  3053. Array,
  3054. };
  3055. } // end anonymous namespace
  3056. IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
  3057. switch (nullability) {
  3058. case NullabilityKind::NonNull:
  3059. if (!Ident__Nonnull)
  3060. Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
  3061. return Ident__Nonnull;
  3062. case NullabilityKind::Nullable:
  3063. if (!Ident__Nullable)
  3064. Ident__Nullable = PP.getIdentifierInfo("_Nullable");
  3065. return Ident__Nullable;
  3066. case NullabilityKind::Unspecified:
  3067. if (!Ident__Null_unspecified)
  3068. Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
  3069. return Ident__Null_unspecified;
  3070. }
  3071. llvm_unreachable("Unknown nullability kind.");
  3072. }
  3073. /// Retrieve the identifier "NSError".
  3074. IdentifierInfo *Sema::getNSErrorIdent() {
  3075. if (!Ident_NSError)
  3076. Ident_NSError = PP.getIdentifierInfo("NSError");
  3077. return Ident_NSError;
  3078. }
  3079. /// Check whether there is a nullability attribute of any kind in the given
  3080. /// attribute list.
  3081. static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
  3082. for (const ParsedAttr &AL : attrs) {
  3083. if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
  3084. AL.getKind() == ParsedAttr::AT_TypeNullable ||
  3085. AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
  3086. return true;
  3087. }
  3088. return false;
  3089. }
  3090. namespace {
  3091. /// Describes the kind of a pointer a declarator describes.
  3092. enum class PointerDeclaratorKind {
  3093. // Not a pointer.
  3094. NonPointer,
  3095. // Single-level pointer.
  3096. SingleLevelPointer,
  3097. // Multi-level pointer (of any pointer kind).
  3098. MultiLevelPointer,
  3099. // CFFooRef*
  3100. MaybePointerToCFRef,
  3101. // CFErrorRef*
  3102. CFErrorRefPointer,
  3103. // NSError**
  3104. NSErrorPointerPointer,
  3105. };
  3106. /// Describes a declarator chunk wrapping a pointer that marks inference as
  3107. /// unexpected.
  3108. // These values must be kept in sync with diagnostics.
  3109. enum class PointerWrappingDeclaratorKind {
  3110. /// Pointer is top-level.
  3111. None = -1,
  3112. /// Pointer is an array element.
  3113. Array = 0,
  3114. /// Pointer is the referent type of a C++ reference.
  3115. Reference = 1
  3116. };
  3117. } // end anonymous namespace
  3118. /// Classify the given declarator, whose type-specified is \c type, based on
  3119. /// what kind of pointer it refers to.
  3120. ///
  3121. /// This is used to determine the default nullability.
  3122. static PointerDeclaratorKind
  3123. classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
  3124. PointerWrappingDeclaratorKind &wrappingKind) {
  3125. unsigned numNormalPointers = 0;
  3126. // For any dependent type, we consider it a non-pointer.
  3127. if (type->isDependentType())
  3128. return PointerDeclaratorKind::NonPointer;
  3129. // Look through the declarator chunks to identify pointers.
  3130. for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
  3131. DeclaratorChunk &chunk = declarator.getTypeObject(i);
  3132. switch (chunk.Kind) {
  3133. case DeclaratorChunk::Array:
  3134. if (numNormalPointers == 0)
  3135. wrappingKind = PointerWrappingDeclaratorKind::Array;
  3136. break;
  3137. case DeclaratorChunk::Function:
  3138. case DeclaratorChunk::Pipe:
  3139. break;
  3140. case DeclaratorChunk::BlockPointer:
  3141. case DeclaratorChunk::MemberPointer:
  3142. return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
  3143. : PointerDeclaratorKind::SingleLevelPointer;
  3144. case DeclaratorChunk::Paren:
  3145. break;
  3146. case DeclaratorChunk::Reference:
  3147. if (numNormalPointers == 0)
  3148. wrappingKind = PointerWrappingDeclaratorKind::Reference;
  3149. break;
  3150. case DeclaratorChunk::Pointer:
  3151. ++numNormalPointers;
  3152. if (numNormalPointers > 2)
  3153. return PointerDeclaratorKind::MultiLevelPointer;
  3154. break;
  3155. }
  3156. }
  3157. // Then, dig into the type specifier itself.
  3158. unsigned numTypeSpecifierPointers = 0;
  3159. do {
  3160. // Decompose normal pointers.
  3161. if (auto ptrType = type->getAs<PointerType>()) {
  3162. ++numNormalPointers;
  3163. if (numNormalPointers > 2)
  3164. return PointerDeclaratorKind::MultiLevelPointer;
  3165. type = ptrType->getPointeeType();
  3166. ++numTypeSpecifierPointers;
  3167. continue;
  3168. }
  3169. // Decompose block pointers.
  3170. if (type->getAs<BlockPointerType>()) {
  3171. return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
  3172. : PointerDeclaratorKind::SingleLevelPointer;
  3173. }
  3174. // Decompose member pointers.
  3175. if (type->getAs<MemberPointerType>()) {
  3176. return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
  3177. : PointerDeclaratorKind::SingleLevelPointer;
  3178. }
  3179. // Look at Objective-C object pointers.
  3180. if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
  3181. ++numNormalPointers;
  3182. ++numTypeSpecifierPointers;
  3183. // If this is NSError**, report that.
  3184. if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
  3185. if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
  3186. numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
  3187. return PointerDeclaratorKind::NSErrorPointerPointer;
  3188. }
  3189. }
  3190. break;
  3191. }
  3192. // Look at Objective-C class types.
  3193. if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
  3194. if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
  3195. if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
  3196. return PointerDeclaratorKind::NSErrorPointerPointer;
  3197. }
  3198. break;
  3199. }
  3200. // If at this point we haven't seen a pointer, we won't see one.
  3201. if (numNormalPointers == 0)
  3202. return PointerDeclaratorKind::NonPointer;
  3203. if (auto recordType = type->getAs<RecordType>()) {
  3204. RecordDecl *recordDecl = recordType->getDecl();
  3205. bool isCFError = false;
  3206. if (S.CFError) {
  3207. // If we already know about CFError, test it directly.
  3208. isCFError = (S.CFError == recordDecl);
  3209. } else {
  3210. // Check whether this is CFError, which we identify based on its bridge
  3211. // to NSError. CFErrorRef used to be declared with "objc_bridge" but is
  3212. // now declared with "objc_bridge_mutable", so look for either one of
  3213. // the two attributes.
  3214. if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
  3215. IdentifierInfo *bridgedType = nullptr;
  3216. if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>())
  3217. bridgedType = bridgeAttr->getBridgedType();
  3218. else if (auto bridgeAttr =
  3219. recordDecl->getAttr<ObjCBridgeMutableAttr>())
  3220. bridgedType = bridgeAttr->getBridgedType();
  3221. if (bridgedType == S.getNSErrorIdent()) {
  3222. S.CFError = recordDecl;
  3223. isCFError = true;
  3224. }
  3225. }
  3226. }
  3227. // If this is CFErrorRef*, report it as such.
  3228. if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
  3229. return PointerDeclaratorKind::CFErrorRefPointer;
  3230. }
  3231. break;
  3232. }
  3233. break;
  3234. } while (true);
  3235. switch (numNormalPointers) {
  3236. case 0:
  3237. return PointerDeclaratorKind::NonPointer;
  3238. case 1:
  3239. return PointerDeclaratorKind::SingleLevelPointer;
  3240. case 2:
  3241. return PointerDeclaratorKind::MaybePointerToCFRef;
  3242. default:
  3243. return PointerDeclaratorKind::MultiLevelPointer;
  3244. }
  3245. }
  3246. static FileID getNullabilityCompletenessCheckFileID(Sema &S,
  3247. SourceLocation loc) {
  3248. // If we're anywhere in a function, method, or closure context, don't perform
  3249. // completeness checks.
  3250. for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
  3251. if (ctx->isFunctionOrMethod())
  3252. return FileID();
  3253. if (ctx->isFileContext())
  3254. break;
  3255. }
  3256. // We only care about the expansion location.
  3257. loc = S.SourceMgr.getExpansionLoc(loc);
  3258. FileID file = S.SourceMgr.getFileID(loc);
  3259. if (file.isInvalid())
  3260. return FileID();
  3261. // Retrieve file information.
  3262. bool invalid = false;
  3263. const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
  3264. if (invalid || !sloc.isFile())
  3265. return FileID();
  3266. // We don't want to perform completeness checks on the main file or in
  3267. // system headers.
  3268. const SrcMgr::FileInfo &fileInfo = sloc.getFile();
  3269. if (fileInfo.getIncludeLoc().isInvalid())
  3270. return FileID();
  3271. if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
  3272. S.Diags.getSuppressSystemWarnings()) {
  3273. return FileID();
  3274. }
  3275. return file;
  3276. }
  3277. /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
  3278. /// taking into account whitespace before and after.
  3279. static void fixItNullability(Sema &S, DiagnosticBuilder &Diag,
  3280. SourceLocation PointerLoc,
  3281. NullabilityKind Nullability) {
  3282. assert(PointerLoc.isValid());
  3283. if (PointerLoc.isMacroID())
  3284. return;
  3285. SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
  3286. if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
  3287. return;
  3288. const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
  3289. if (!NextChar)
  3290. return;
  3291. SmallString<32> InsertionTextBuf{" "};
  3292. InsertionTextBuf += getNullabilitySpelling(Nullability);
  3293. InsertionTextBuf += " ";
  3294. StringRef InsertionText = InsertionTextBuf.str();
  3295. if (isWhitespace(*NextChar)) {
  3296. InsertionText = InsertionText.drop_back();
  3297. } else if (NextChar[-1] == '[') {
  3298. if (NextChar[0] == ']')
  3299. InsertionText = InsertionText.drop_back().drop_front();
  3300. else
  3301. InsertionText = InsertionText.drop_front();
  3302. } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) &&
  3303. !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) {
  3304. InsertionText = InsertionText.drop_back().drop_front();
  3305. }
  3306. Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
  3307. }
  3308. static void emitNullabilityConsistencyWarning(Sema &S,
  3309. SimplePointerKind PointerKind,
  3310. SourceLocation PointerLoc,
  3311. SourceLocation PointerEndLoc) {
  3312. assert(PointerLoc.isValid());
  3313. if (PointerKind == SimplePointerKind::Array) {
  3314. S.Diag(PointerLoc, diag::warn_nullability_missing_array);
  3315. } else {
  3316. S.Diag(PointerLoc, diag::warn_nullability_missing)
  3317. << static_cast<unsigned>(PointerKind);
  3318. }
  3319. auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
  3320. if (FixItLoc.isMacroID())
  3321. return;
  3322. auto addFixIt = [&](NullabilityKind Nullability) {
  3323. auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
  3324. Diag << static_cast<unsigned>(Nullability);
  3325. Diag << static_cast<unsigned>(PointerKind);
  3326. fixItNullability(S, Diag, FixItLoc, Nullability);
  3327. };
  3328. addFixIt(NullabilityKind::Nullable);
  3329. addFixIt(NullabilityKind::NonNull);
  3330. }
  3331. /// Complains about missing nullability if the file containing \p pointerLoc
  3332. /// has other uses of nullability (either the keywords or the \c assume_nonnull
  3333. /// pragma).
  3334. ///
  3335. /// If the file has \e not seen other uses of nullability, this particular
  3336. /// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
  3337. static void
  3338. checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
  3339. SourceLocation pointerLoc,
  3340. SourceLocation pointerEndLoc = SourceLocation()) {
  3341. // Determine which file we're performing consistency checking for.
  3342. FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
  3343. if (file.isInvalid())
  3344. return;
  3345. // If we haven't seen any type nullability in this file, we won't warn now
  3346. // about anything.
  3347. FileNullability &fileNullability = S.NullabilityMap[file];
  3348. if (!fileNullability.SawTypeNullability) {
  3349. // If this is the first pointer declarator in the file, and the appropriate
  3350. // warning is on, record it in case we need to diagnose it retroactively.
  3351. diag::kind diagKind;
  3352. if (pointerKind == SimplePointerKind::Array)
  3353. diagKind = diag::warn_nullability_missing_array;
  3354. else
  3355. diagKind = diag::warn_nullability_missing;
  3356. if (fileNullability.PointerLoc.isInvalid() &&
  3357. !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
  3358. fileNullability.PointerLoc = pointerLoc;
  3359. fileNullability.PointerEndLoc = pointerEndLoc;
  3360. fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
  3361. }
  3362. return;
  3363. }
  3364. // Complain about missing nullability.
  3365. emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
  3366. }
  3367. /// Marks that a nullability feature has been used in the file containing
  3368. /// \p loc.
  3369. ///
  3370. /// If this file already had pointer types in it that were missing nullability,
  3371. /// the first such instance is retroactively diagnosed.
  3372. ///
  3373. /// \sa checkNullabilityConsistency
  3374. static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
  3375. FileID file = getNullabilityCompletenessCheckFileID(S, loc);
  3376. if (file.isInvalid())
  3377. return;
  3378. FileNullability &fileNullability = S.NullabilityMap[file];
  3379. if (fileNullability.SawTypeNullability)
  3380. return;
  3381. fileNullability.SawTypeNullability = true;
  3382. // If we haven't seen any type nullability before, now we have. Retroactively
  3383. // diagnose the first unannotated pointer, if there was one.
  3384. if (fileNullability.PointerLoc.isInvalid())
  3385. return;
  3386. auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
  3387. emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
  3388. fileNullability.PointerEndLoc);
  3389. }
  3390. /// Returns true if any of the declarator chunks before \p endIndex include a
  3391. /// level of indirection: array, pointer, reference, or pointer-to-member.
  3392. ///
  3393. /// Because declarator chunks are stored in outer-to-inner order, testing
  3394. /// every chunk before \p endIndex is testing all chunks that embed the current
  3395. /// chunk as part of their type.
  3396. ///
  3397. /// It is legal to pass the result of Declarator::getNumTypeObjects() as the
  3398. /// end index, in which case all chunks are tested.
  3399. static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
  3400. unsigned i = endIndex;
  3401. while (i != 0) {
  3402. // Walk outwards along the declarator chunks.
  3403. --i;
  3404. const DeclaratorChunk &DC = D.getTypeObject(i);
  3405. switch (DC.Kind) {
  3406. case DeclaratorChunk::Paren:
  3407. break;
  3408. case DeclaratorChunk::Array:
  3409. case DeclaratorChunk::Pointer:
  3410. case DeclaratorChunk::Reference:
  3411. case DeclaratorChunk::MemberPointer:
  3412. return true;
  3413. case DeclaratorChunk::Function:
  3414. case DeclaratorChunk::BlockPointer:
  3415. case DeclaratorChunk::Pipe:
  3416. // These are invalid anyway, so just ignore.
  3417. break;
  3418. }
  3419. }
  3420. return false;
  3421. }
  3422. static bool IsNoDerefableChunk(DeclaratorChunk Chunk) {
  3423. return (Chunk.Kind == DeclaratorChunk::Pointer ||
  3424. Chunk.Kind == DeclaratorChunk::Array);
  3425. }
  3426. template<typename AttrT>
  3427. static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &Attr) {
  3428. Attr.setUsedAsTypeAttr();
  3429. return ::new (Ctx)
  3430. AttrT(Attr.getRange(), Ctx, Attr.getAttributeSpellingListIndex());
  3431. }
  3432. static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr,
  3433. NullabilityKind NK) {
  3434. switch (NK) {
  3435. case NullabilityKind::NonNull:
  3436. return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
  3437. case NullabilityKind::Nullable:
  3438. return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
  3439. case NullabilityKind::Unspecified:
  3440. return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
  3441. }
  3442. llvm_unreachable("unknown NullabilityKind");
  3443. }
  3444. // Diagnose whether this is a case with the multiple addr spaces.
  3445. // Returns true if this is an invalid case.
  3446. // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
  3447. // by qualifiers for two or more different address spaces."
  3448. static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld,
  3449. LangAS ASNew,
  3450. SourceLocation AttrLoc) {
  3451. if (ASOld != LangAS::Default) {
  3452. if (ASOld != ASNew) {
  3453. S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
  3454. return true;
  3455. }
  3456. // Emit a warning if they are identical; it's likely unintended.
  3457. S.Diag(AttrLoc,
  3458. diag::warn_attribute_address_multiple_identical_qualifiers);
  3459. }
  3460. return false;
  3461. }
  3462. static TypeSourceInfo *
  3463. GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
  3464. QualType T, TypeSourceInfo *ReturnTypeInfo);
  3465. static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
  3466. QualType declSpecType,
  3467. TypeSourceInfo *TInfo) {
  3468. // The TypeSourceInfo that this function returns will not be a null type.
  3469. // If there is an error, this function will fill in a dummy type as fallback.
  3470. QualType T = declSpecType;
  3471. Declarator &D = state.getDeclarator();
  3472. Sema &S = state.getSema();
  3473. ASTContext &Context = S.Context;
  3474. const LangOptions &LangOpts = S.getLangOpts();
  3475. // The name we're declaring, if any.
  3476. DeclarationName Name;
  3477. if (D.getIdentifier())
  3478. Name = D.getIdentifier();
  3479. // Does this declaration declare a typedef-name?
  3480. bool IsTypedefName =
  3481. D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
  3482. D.getContext() == DeclaratorContext::AliasDeclContext ||
  3483. D.getContext() == DeclaratorContext::AliasTemplateContext;
  3484. // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
  3485. bool IsQualifiedFunction = T->isFunctionProtoType() &&
  3486. (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
  3487. T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
  3488. // If T is 'decltype(auto)', the only declarators we can have are parens
  3489. // and at most one function declarator if this is a function declaration.
  3490. // If T is a deduced class template specialization type, we can have no
  3491. // declarator chunks at all.
  3492. if (auto *DT = T->getAs<DeducedType>()) {
  3493. const AutoType *AT = T->getAs<AutoType>();
  3494. bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
  3495. if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
  3496. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  3497. unsigned Index = E - I - 1;
  3498. DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
  3499. unsigned DiagId = IsClassTemplateDeduction
  3500. ? diag::err_deduced_class_template_compound_type
  3501. : diag::err_decltype_auto_compound_type;
  3502. unsigned DiagKind = 0;
  3503. switch (DeclChunk.Kind) {
  3504. case DeclaratorChunk::Paren:
  3505. // FIXME: Rejecting this is a little silly.
  3506. if (IsClassTemplateDeduction) {
  3507. DiagKind = 4;
  3508. break;
  3509. }
  3510. continue;
  3511. case DeclaratorChunk::Function: {
  3512. if (IsClassTemplateDeduction) {
  3513. DiagKind = 3;
  3514. break;
  3515. }
  3516. unsigned FnIndex;
  3517. if (D.isFunctionDeclarationContext() &&
  3518. D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
  3519. continue;
  3520. DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
  3521. break;
  3522. }
  3523. case DeclaratorChunk::Pointer:
  3524. case DeclaratorChunk::BlockPointer:
  3525. case DeclaratorChunk::MemberPointer:
  3526. DiagKind = 0;
  3527. break;
  3528. case DeclaratorChunk::Reference:
  3529. DiagKind = 1;
  3530. break;
  3531. case DeclaratorChunk::Array:
  3532. DiagKind = 2;
  3533. break;
  3534. case DeclaratorChunk::Pipe:
  3535. break;
  3536. }
  3537. S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
  3538. D.setInvalidType(true);
  3539. break;
  3540. }
  3541. }
  3542. }
  3543. // Determine whether we should infer _Nonnull on pointer types.
  3544. Optional<NullabilityKind> inferNullability;
  3545. bool inferNullabilityCS = false;
  3546. bool inferNullabilityInnerOnly = false;
  3547. bool inferNullabilityInnerOnlyComplete = false;
  3548. // Are we in an assume-nonnull region?
  3549. bool inAssumeNonNullRegion = false;
  3550. SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
  3551. if (assumeNonNullLoc.isValid()) {
  3552. inAssumeNonNullRegion = true;
  3553. recordNullabilitySeen(S, assumeNonNullLoc);
  3554. }
  3555. // Whether to complain about missing nullability specifiers or not.
  3556. enum {
  3557. /// Never complain.
  3558. CAMN_No,
  3559. /// Complain on the inner pointers (but not the outermost
  3560. /// pointer).
  3561. CAMN_InnerPointers,
  3562. /// Complain about any pointers that don't have nullability
  3563. /// specified or inferred.
  3564. CAMN_Yes
  3565. } complainAboutMissingNullability = CAMN_No;
  3566. unsigned NumPointersRemaining = 0;
  3567. auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
  3568. if (IsTypedefName) {
  3569. // For typedefs, we do not infer any nullability (the default),
  3570. // and we only complain about missing nullability specifiers on
  3571. // inner pointers.
  3572. complainAboutMissingNullability = CAMN_InnerPointers;
  3573. if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
  3574. !T->getNullability(S.Context)) {
  3575. // Note that we allow but don't require nullability on dependent types.
  3576. ++NumPointersRemaining;
  3577. }
  3578. for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
  3579. DeclaratorChunk &chunk = D.getTypeObject(i);
  3580. switch (chunk.Kind) {
  3581. case DeclaratorChunk::Array:
  3582. case DeclaratorChunk::Function:
  3583. case DeclaratorChunk::Pipe:
  3584. break;
  3585. case DeclaratorChunk::BlockPointer:
  3586. case DeclaratorChunk::MemberPointer:
  3587. ++NumPointersRemaining;
  3588. break;
  3589. case DeclaratorChunk::Paren:
  3590. case DeclaratorChunk::Reference:
  3591. continue;
  3592. case DeclaratorChunk::Pointer:
  3593. ++NumPointersRemaining;
  3594. continue;
  3595. }
  3596. }
  3597. } else {
  3598. bool isFunctionOrMethod = false;
  3599. switch (auto context = state.getDeclarator().getContext()) {
  3600. case DeclaratorContext::ObjCParameterContext:
  3601. case DeclaratorContext::ObjCResultContext:
  3602. case DeclaratorContext::PrototypeContext:
  3603. case DeclaratorContext::TrailingReturnContext:
  3604. case DeclaratorContext::TrailingReturnVarContext:
  3605. isFunctionOrMethod = true;
  3606. LLVM_FALLTHROUGH;
  3607. case DeclaratorContext::MemberContext:
  3608. if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
  3609. complainAboutMissingNullability = CAMN_No;
  3610. break;
  3611. }
  3612. // Weak properties are inferred to be nullable.
  3613. if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
  3614. inferNullability = NullabilityKind::Nullable;
  3615. break;
  3616. }
  3617. LLVM_FALLTHROUGH;
  3618. case DeclaratorContext::FileContext:
  3619. case DeclaratorContext::KNRTypeListContext: {
  3620. complainAboutMissingNullability = CAMN_Yes;
  3621. // Nullability inference depends on the type and declarator.
  3622. auto wrappingKind = PointerWrappingDeclaratorKind::None;
  3623. switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
  3624. case PointerDeclaratorKind::NonPointer:
  3625. case PointerDeclaratorKind::MultiLevelPointer:
  3626. // Cannot infer nullability.
  3627. break;
  3628. case PointerDeclaratorKind::SingleLevelPointer:
  3629. // Infer _Nonnull if we are in an assumes-nonnull region.
  3630. if (inAssumeNonNullRegion) {
  3631. complainAboutInferringWithinChunk = wrappingKind;
  3632. inferNullability = NullabilityKind::NonNull;
  3633. inferNullabilityCS =
  3634. (context == DeclaratorContext::ObjCParameterContext ||
  3635. context == DeclaratorContext::ObjCResultContext);
  3636. }
  3637. break;
  3638. case PointerDeclaratorKind::CFErrorRefPointer:
  3639. case PointerDeclaratorKind::NSErrorPointerPointer:
  3640. // Within a function or method signature, infer _Nullable at both
  3641. // levels.
  3642. if (isFunctionOrMethod && inAssumeNonNullRegion)
  3643. inferNullability = NullabilityKind::Nullable;
  3644. break;
  3645. case PointerDeclaratorKind::MaybePointerToCFRef:
  3646. if (isFunctionOrMethod) {
  3647. // On pointer-to-pointer parameters marked cf_returns_retained or
  3648. // cf_returns_not_retained, if the outer pointer is explicit then
  3649. // infer the inner pointer as _Nullable.
  3650. auto hasCFReturnsAttr =
  3651. [](const ParsedAttributesView &AttrList) -> bool {
  3652. return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
  3653. AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
  3654. };
  3655. if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
  3656. if (hasCFReturnsAttr(D.getAttributes()) ||
  3657. hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
  3658. hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
  3659. inferNullability = NullabilityKind::Nullable;
  3660. inferNullabilityInnerOnly = true;
  3661. }
  3662. }
  3663. }
  3664. break;
  3665. }
  3666. break;
  3667. }
  3668. case DeclaratorContext::ConversionIdContext:
  3669. complainAboutMissingNullability = CAMN_Yes;
  3670. break;
  3671. case DeclaratorContext::AliasDeclContext:
  3672. case DeclaratorContext::AliasTemplateContext:
  3673. case DeclaratorContext::BlockContext:
  3674. case DeclaratorContext::BlockLiteralContext:
  3675. case DeclaratorContext::ConditionContext:
  3676. case DeclaratorContext::CXXCatchContext:
  3677. case DeclaratorContext::CXXNewContext:
  3678. case DeclaratorContext::ForContext:
  3679. case DeclaratorContext::InitStmtContext:
  3680. case DeclaratorContext::LambdaExprContext:
  3681. case DeclaratorContext::LambdaExprParameterContext:
  3682. case DeclaratorContext::ObjCCatchContext:
  3683. case DeclaratorContext::TemplateParamContext:
  3684. case DeclaratorContext::TemplateArgContext:
  3685. case DeclaratorContext::TemplateTypeArgContext:
  3686. case DeclaratorContext::TypeNameContext:
  3687. case DeclaratorContext::FunctionalCastContext:
  3688. // Don't infer in these contexts.
  3689. break;
  3690. }
  3691. }
  3692. // Local function that returns true if its argument looks like a va_list.
  3693. auto isVaList = [&S](QualType T) -> bool {
  3694. auto *typedefTy = T->getAs<TypedefType>();
  3695. if (!typedefTy)
  3696. return false;
  3697. TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
  3698. do {
  3699. if (typedefTy->getDecl() == vaListTypedef)
  3700. return true;
  3701. if (auto *name = typedefTy->getDecl()->getIdentifier())
  3702. if (name->isStr("va_list"))
  3703. return true;
  3704. typedefTy = typedefTy->desugar()->getAs<TypedefType>();
  3705. } while (typedefTy);
  3706. return false;
  3707. };
  3708. // Local function that checks the nullability for a given pointer declarator.
  3709. // Returns true if _Nonnull was inferred.
  3710. auto inferPointerNullability =
  3711. [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
  3712. SourceLocation pointerEndLoc,
  3713. ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
  3714. // We've seen a pointer.
  3715. if (NumPointersRemaining > 0)
  3716. --NumPointersRemaining;
  3717. // If a nullability attribute is present, there's nothing to do.
  3718. if (hasNullabilityAttr(attrs))
  3719. return nullptr;
  3720. // If we're supposed to infer nullability, do so now.
  3721. if (inferNullability && !inferNullabilityInnerOnlyComplete) {
  3722. ParsedAttr::Syntax syntax = inferNullabilityCS
  3723. ? ParsedAttr::AS_ContextSensitiveKeyword
  3724. : ParsedAttr::AS_Keyword;
  3725. ParsedAttr *nullabilityAttr = Pool.create(
  3726. S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
  3727. nullptr, SourceLocation(), nullptr, 0, syntax);
  3728. attrs.addAtEnd(nullabilityAttr);
  3729. if (inferNullabilityCS) {
  3730. state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
  3731. ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
  3732. }
  3733. if (pointerLoc.isValid() &&
  3734. complainAboutInferringWithinChunk !=
  3735. PointerWrappingDeclaratorKind::None) {
  3736. auto Diag =
  3737. S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
  3738. Diag << static_cast<int>(complainAboutInferringWithinChunk);
  3739. fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
  3740. }
  3741. if (inferNullabilityInnerOnly)
  3742. inferNullabilityInnerOnlyComplete = true;
  3743. return nullabilityAttr;
  3744. }
  3745. // If we're supposed to complain about missing nullability, do so
  3746. // now if it's truly missing.
  3747. switch (complainAboutMissingNullability) {
  3748. case CAMN_No:
  3749. break;
  3750. case CAMN_InnerPointers:
  3751. if (NumPointersRemaining == 0)
  3752. break;
  3753. LLVM_FALLTHROUGH;
  3754. case CAMN_Yes:
  3755. checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
  3756. }
  3757. return nullptr;
  3758. };
  3759. // If the type itself could have nullability but does not, infer pointer
  3760. // nullability and perform consistency checking.
  3761. if (S.CodeSynthesisContexts.empty()) {
  3762. if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
  3763. !T->getNullability(S.Context)) {
  3764. if (isVaList(T)) {
  3765. // Record that we've seen a pointer, but do nothing else.
  3766. if (NumPointersRemaining > 0)
  3767. --NumPointersRemaining;
  3768. } else {
  3769. SimplePointerKind pointerKind = SimplePointerKind::Pointer;
  3770. if (T->isBlockPointerType())
  3771. pointerKind = SimplePointerKind::BlockPointer;
  3772. else if (T->isMemberPointerType())
  3773. pointerKind = SimplePointerKind::MemberPointer;
  3774. if (auto *attr = inferPointerNullability(
  3775. pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
  3776. D.getDeclSpec().getEndLoc(),
  3777. D.getMutableDeclSpec().getAttributes(),
  3778. D.getMutableDeclSpec().getAttributePool())) {
  3779. T = state.getAttributedType(
  3780. createNullabilityAttr(Context, *attr, *inferNullability), T, T);
  3781. }
  3782. }
  3783. }
  3784. if (complainAboutMissingNullability == CAMN_Yes &&
  3785. T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
  3786. D.isPrototypeContext() &&
  3787. !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
  3788. checkNullabilityConsistency(S, SimplePointerKind::Array,
  3789. D.getDeclSpec().getTypeSpecTypeLoc());
  3790. }
  3791. }
  3792. bool ExpectNoDerefChunk =
  3793. state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
  3794. // Walk the DeclTypeInfo, building the recursive type as we go.
  3795. // DeclTypeInfos are ordered from the identifier out, which is
  3796. // opposite of what we want :).
  3797. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  3798. unsigned chunkIndex = e - i - 1;
  3799. state.setCurrentChunkIndex(chunkIndex);
  3800. DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
  3801. IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
  3802. switch (DeclType.Kind) {
  3803. case DeclaratorChunk::Paren:
  3804. if (i == 0)
  3805. warnAboutRedundantParens(S, D, T);
  3806. T = S.BuildParenType(T);
  3807. break;
  3808. case DeclaratorChunk::BlockPointer:
  3809. // If blocks are disabled, emit an error.
  3810. if (!LangOpts.Blocks)
  3811. S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
  3812. // Handle pointer nullability.
  3813. inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
  3814. DeclType.EndLoc, DeclType.getAttrs(),
  3815. state.getDeclarator().getAttributePool());
  3816. T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
  3817. if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
  3818. // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
  3819. // qualified with const.
  3820. if (LangOpts.OpenCL)
  3821. DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
  3822. T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
  3823. }
  3824. break;
  3825. case DeclaratorChunk::Pointer:
  3826. // Verify that we're not building a pointer to pointer to function with
  3827. // exception specification.
  3828. if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
  3829. S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
  3830. D.setInvalidType(true);
  3831. // Build the type anyway.
  3832. }
  3833. // Handle pointer nullability
  3834. inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
  3835. DeclType.EndLoc, DeclType.getAttrs(),
  3836. state.getDeclarator().getAttributePool());
  3837. if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
  3838. T = Context.getObjCObjectPointerType(T);
  3839. if (DeclType.Ptr.TypeQuals)
  3840. T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
  3841. break;
  3842. }
  3843. // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
  3844. // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
  3845. // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
  3846. if (LangOpts.OpenCL) {
  3847. if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
  3848. T->isBlockPointerType()) {
  3849. S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
  3850. D.setInvalidType(true);
  3851. }
  3852. }
  3853. T = S.BuildPointerType(T, DeclType.Loc, Name);
  3854. if (DeclType.Ptr.TypeQuals)
  3855. T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
  3856. break;
  3857. case DeclaratorChunk::Reference: {
  3858. // Verify that we're not building a reference to pointer to function with
  3859. // exception specification.
  3860. if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
  3861. S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
  3862. D.setInvalidType(true);
  3863. // Build the type anyway.
  3864. }
  3865. T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
  3866. if (DeclType.Ref.HasRestrict)
  3867. T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
  3868. break;
  3869. }
  3870. case DeclaratorChunk::Array: {
  3871. // Verify that we're not building an array of pointers to function with
  3872. // exception specification.
  3873. if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
  3874. S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
  3875. D.setInvalidType(true);
  3876. // Build the type anyway.
  3877. }
  3878. DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
  3879. Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
  3880. ArrayType::ArraySizeModifier ASM;
  3881. if (ATI.isStar)
  3882. ASM = ArrayType::Star;
  3883. else if (ATI.hasStatic)
  3884. ASM = ArrayType::Static;
  3885. else
  3886. ASM = ArrayType::Normal;
  3887. if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
  3888. // FIXME: This check isn't quite right: it allows star in prototypes
  3889. // for function definitions, and disallows some edge cases detailed
  3890. // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
  3891. S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
  3892. ASM = ArrayType::Normal;
  3893. D.setInvalidType(true);
  3894. }
  3895. // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
  3896. // shall appear only in a declaration of a function parameter with an
  3897. // array type, ...
  3898. if (ASM == ArrayType::Static || ATI.TypeQuals) {
  3899. if (!(D.isPrototypeContext() ||
  3900. D.getContext() == DeclaratorContext::KNRTypeListContext)) {
  3901. S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
  3902. (ASM == ArrayType::Static ? "'static'" : "type qualifier");
  3903. // Remove the 'static' and the type qualifiers.
  3904. if (ASM == ArrayType::Static)
  3905. ASM = ArrayType::Normal;
  3906. ATI.TypeQuals = 0;
  3907. D.setInvalidType(true);
  3908. }
  3909. // C99 6.7.5.2p1: ... and then only in the outermost array type
  3910. // derivation.
  3911. if (hasOuterPointerLikeChunk(D, chunkIndex)) {
  3912. S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
  3913. (ASM == ArrayType::Static ? "'static'" : "type qualifier");
  3914. if (ASM == ArrayType::Static)
  3915. ASM = ArrayType::Normal;
  3916. ATI.TypeQuals = 0;
  3917. D.setInvalidType(true);
  3918. }
  3919. }
  3920. const AutoType *AT = T->getContainedAutoType();
  3921. // Allow arrays of auto if we are a generic lambda parameter.
  3922. // i.e. [](auto (&array)[5]) { return array[0]; }; OK
  3923. if (AT &&
  3924. D.getContext() != DeclaratorContext::LambdaExprParameterContext) {
  3925. // We've already diagnosed this for decltype(auto).
  3926. if (!AT->isDecltypeAuto())
  3927. S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
  3928. << getPrintableNameForEntity(Name) << T;
  3929. T = QualType();
  3930. break;
  3931. }
  3932. // Array parameters can be marked nullable as well, although it's not
  3933. // necessary if they're marked 'static'.
  3934. if (complainAboutMissingNullability == CAMN_Yes &&
  3935. !hasNullabilityAttr(DeclType.getAttrs()) &&
  3936. ASM != ArrayType::Static &&
  3937. D.isPrototypeContext() &&
  3938. !hasOuterPointerLikeChunk(D, chunkIndex)) {
  3939. checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
  3940. }
  3941. T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
  3942. SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
  3943. break;
  3944. }
  3945. case DeclaratorChunk::Function: {
  3946. // If the function declarator has a prototype (i.e. it is not () and
  3947. // does not have a K&R-style identifier list), then the arguments are part
  3948. // of the type, otherwise the argument list is ().
  3949. const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
  3950. IsQualifiedFunction =
  3951. FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier();
  3952. // Check for auto functions and trailing return type and adjust the
  3953. // return type accordingly.
  3954. if (!D.isInvalidType()) {
  3955. // trailing-return-type is only required if we're declaring a function,
  3956. // and not, for instance, a pointer to a function.
  3957. if (D.getDeclSpec().hasAutoTypeSpec() &&
  3958. !FTI.hasTrailingReturnType() && chunkIndex == 0) {
  3959. if (!S.getLangOpts().CPlusPlus14) {
  3960. S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
  3961. D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
  3962. ? diag::err_auto_missing_trailing_return
  3963. : diag::err_deduced_return_type);
  3964. T = Context.IntTy;
  3965. D.setInvalidType(true);
  3966. } else {
  3967. S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
  3968. diag::warn_cxx11_compat_deduced_return_type);
  3969. }
  3970. } else if (FTI.hasTrailingReturnType()) {
  3971. // T must be exactly 'auto' at this point. See CWG issue 681.
  3972. if (isa<ParenType>(T)) {
  3973. S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
  3974. << T << D.getSourceRange();
  3975. D.setInvalidType(true);
  3976. } else if (D.getName().getKind() ==
  3977. UnqualifiedIdKind::IK_DeductionGuideName) {
  3978. if (T != Context.DependentTy) {
  3979. S.Diag(D.getDeclSpec().getBeginLoc(),
  3980. diag::err_deduction_guide_with_complex_decl)
  3981. << D.getSourceRange();
  3982. D.setInvalidType(true);
  3983. }
  3984. } else if (D.getContext() != DeclaratorContext::LambdaExprContext &&
  3985. (T.hasQualifiers() || !isa<AutoType>(T) ||
  3986. cast<AutoType>(T)->getKeyword() !=
  3987. AutoTypeKeyword::Auto)) {
  3988. S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
  3989. diag::err_trailing_return_without_auto)
  3990. << T << D.getDeclSpec().getSourceRange();
  3991. D.setInvalidType(true);
  3992. }
  3993. T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
  3994. if (T.isNull()) {
  3995. // An error occurred parsing the trailing return type.
  3996. T = Context.IntTy;
  3997. D.setInvalidType(true);
  3998. }
  3999. } else {
  4000. // This function type is not the type of the entity being declared,
  4001. // so checking the 'auto' is not the responsibility of this chunk.
  4002. }
  4003. }
  4004. // C99 6.7.5.3p1: The return type may not be a function or array type.
  4005. // For conversion functions, we'll diagnose this particular error later.
  4006. if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
  4007. (D.getName().getKind() !=
  4008. UnqualifiedIdKind::IK_ConversionFunctionId)) {
  4009. unsigned diagID = diag::err_func_returning_array_function;
  4010. // Last processing chunk in block context means this function chunk
  4011. // represents the block.
  4012. if (chunkIndex == 0 &&
  4013. D.getContext() == DeclaratorContext::BlockLiteralContext)
  4014. diagID = diag::err_block_returning_array_function;
  4015. S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
  4016. T = Context.IntTy;
  4017. D.setInvalidType(true);
  4018. }
  4019. // Do not allow returning half FP value.
  4020. // FIXME: This really should be in BuildFunctionType.
  4021. if (T->isHalfType()) {
  4022. if (S.getLangOpts().OpenCL) {
  4023. if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
  4024. S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
  4025. << T << 0 /*pointer hint*/;
  4026. D.setInvalidType(true);
  4027. }
  4028. } else if (!S.getLangOpts().HalfArgsAndReturns) {
  4029. S.Diag(D.getIdentifierLoc(),
  4030. diag::err_parameters_retval_cannot_have_fp16_type) << 1;
  4031. D.setInvalidType(true);
  4032. }
  4033. }
  4034. if (LangOpts.OpenCL) {
  4035. // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
  4036. // function.
  4037. if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
  4038. T->isPipeType()) {
  4039. S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
  4040. << T << 1 /*hint off*/;
  4041. D.setInvalidType(true);
  4042. }
  4043. // OpenCL doesn't support variadic functions and blocks
  4044. // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
  4045. // We also allow here any toolchain reserved identifiers.
  4046. if (FTI.isVariadic &&
  4047. !(D.getIdentifier() &&
  4048. ((D.getIdentifier()->getName() == "printf" &&
  4049. (LangOpts.OpenCLCPlusPlus || LangOpts.OpenCLVersion >= 120)) ||
  4050. D.getIdentifier()->getName().startswith("__")))) {
  4051. S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
  4052. D.setInvalidType(true);
  4053. }
  4054. }
  4055. // Methods cannot return interface types. All ObjC objects are
  4056. // passed by reference.
  4057. if (T->isObjCObjectType()) {
  4058. SourceLocation DiagLoc, FixitLoc;
  4059. if (TInfo) {
  4060. DiagLoc = TInfo->getTypeLoc().getBeginLoc();
  4061. FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
  4062. } else {
  4063. DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
  4064. FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
  4065. }
  4066. S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
  4067. << 0 << T
  4068. << FixItHint::CreateInsertion(FixitLoc, "*");
  4069. T = Context.getObjCObjectPointerType(T);
  4070. if (TInfo) {
  4071. TypeLocBuilder TLB;
  4072. TLB.pushFullCopy(TInfo->getTypeLoc());
  4073. ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
  4074. TLoc.setStarLoc(FixitLoc);
  4075. TInfo = TLB.getTypeSourceInfo(Context, T);
  4076. }
  4077. D.setInvalidType(true);
  4078. }
  4079. // cv-qualifiers on return types are pointless except when the type is a
  4080. // class type in C++.
  4081. if ((T.getCVRQualifiers() || T->isAtomicType()) &&
  4082. !(S.getLangOpts().CPlusPlus &&
  4083. (T->isDependentType() || T->isRecordType()))) {
  4084. if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
  4085. D.getFunctionDefinitionKind() == FDK_Definition) {
  4086. // [6.9.1/3] qualified void return is invalid on a C
  4087. // function definition. Apparently ok on declarations and
  4088. // in C++ though (!)
  4089. S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
  4090. } else
  4091. diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
  4092. }
  4093. // Objective-C ARC ownership qualifiers are ignored on the function
  4094. // return type (by type canonicalization). Complain if this attribute
  4095. // was written here.
  4096. if (T.getQualifiers().hasObjCLifetime()) {
  4097. SourceLocation AttrLoc;
  4098. if (chunkIndex + 1 < D.getNumTypeObjects()) {
  4099. DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
  4100. for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
  4101. if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
  4102. AttrLoc = AL.getLoc();
  4103. break;
  4104. }
  4105. }
  4106. }
  4107. if (AttrLoc.isInvalid()) {
  4108. for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
  4109. if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
  4110. AttrLoc = AL.getLoc();
  4111. break;
  4112. }
  4113. }
  4114. }
  4115. if (AttrLoc.isValid()) {
  4116. // The ownership attributes are almost always written via
  4117. // the predefined
  4118. // __strong/__weak/__autoreleasing/__unsafe_unretained.
  4119. if (AttrLoc.isMacroID())
  4120. AttrLoc =
  4121. S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin();
  4122. S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
  4123. << T.getQualifiers().getObjCLifetime();
  4124. }
  4125. }
  4126. if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
  4127. // C++ [dcl.fct]p6:
  4128. // Types shall not be defined in return or parameter types.
  4129. TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  4130. S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
  4131. << Context.getTypeDeclType(Tag);
  4132. }
  4133. // Exception specs are not allowed in typedefs. Complain, but add it
  4134. // anyway.
  4135. if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
  4136. S.Diag(FTI.getExceptionSpecLocBeg(),
  4137. diag::err_exception_spec_in_typedef)
  4138. << (D.getContext() == DeclaratorContext::AliasDeclContext ||
  4139. D.getContext() == DeclaratorContext::AliasTemplateContext);
  4140. // If we see "T var();" or "T var(T());" at block scope, it is probably
  4141. // an attempt to initialize a variable, not a function declaration.
  4142. if (FTI.isAmbiguous)
  4143. warnAboutAmbiguousFunction(S, D, DeclType, T);
  4144. FunctionType::ExtInfo EI(
  4145. getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
  4146. if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus
  4147. && !LangOpts.OpenCL) {
  4148. // Simple void foo(), where the incoming T is the result type.
  4149. T = Context.getFunctionNoProtoType(T, EI);
  4150. } else {
  4151. // We allow a zero-parameter variadic function in C if the
  4152. // function is marked with the "overloadable" attribute. Scan
  4153. // for this attribute now.
  4154. if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus)
  4155. if (!D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable))
  4156. S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
  4157. if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
  4158. // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
  4159. // definition.
  4160. S.Diag(FTI.Params[0].IdentLoc,
  4161. diag::err_ident_list_in_fn_declaration);
  4162. D.setInvalidType(true);
  4163. // Recover by creating a K&R-style function type.
  4164. T = Context.getFunctionNoProtoType(T, EI);
  4165. break;
  4166. }
  4167. FunctionProtoType::ExtProtoInfo EPI;
  4168. EPI.ExtInfo = EI;
  4169. EPI.Variadic = FTI.isVariadic;
  4170. EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
  4171. EPI.TypeQuals.addCVRUQualifiers(
  4172. FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers()
  4173. : 0);
  4174. EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
  4175. : FTI.RefQualifierIsLValueRef? RQ_LValue
  4176. : RQ_RValue;
  4177. // Otherwise, we have a function with a parameter list that is
  4178. // potentially variadic.
  4179. SmallVector<QualType, 16> ParamTys;
  4180. ParamTys.reserve(FTI.NumParams);
  4181. SmallVector<FunctionProtoType::ExtParameterInfo, 16>
  4182. ExtParameterInfos(FTI.NumParams);
  4183. bool HasAnyInterestingExtParameterInfos = false;
  4184. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  4185. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  4186. QualType ParamTy = Param->getType();
  4187. assert(!ParamTy.isNull() && "Couldn't parse type?");
  4188. // Look for 'void'. void is allowed only as a single parameter to a
  4189. // function with no other parameters (C99 6.7.5.3p10). We record
  4190. // int(void) as a FunctionProtoType with an empty parameter list.
  4191. if (ParamTy->isVoidType()) {
  4192. // If this is something like 'float(int, void)', reject it. 'void'
  4193. // is an incomplete type (C99 6.2.5p19) and function decls cannot
  4194. // have parameters of incomplete type.
  4195. if (FTI.NumParams != 1 || FTI.isVariadic) {
  4196. S.Diag(DeclType.Loc, diag::err_void_only_param);
  4197. ParamTy = Context.IntTy;
  4198. Param->setType(ParamTy);
  4199. } else if (FTI.Params[i].Ident) {
  4200. // Reject, but continue to parse 'int(void abc)'.
  4201. S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
  4202. ParamTy = Context.IntTy;
  4203. Param->setType(ParamTy);
  4204. } else {
  4205. // Reject, but continue to parse 'float(const void)'.
  4206. if (ParamTy.hasQualifiers())
  4207. S.Diag(DeclType.Loc, diag::err_void_param_qualified);
  4208. // Do not add 'void' to the list.
  4209. break;
  4210. }
  4211. } else if (ParamTy->isHalfType()) {
  4212. // Disallow half FP parameters.
  4213. // FIXME: This really should be in BuildFunctionType.
  4214. if (S.getLangOpts().OpenCL) {
  4215. if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
  4216. S.Diag(Param->getLocation(),
  4217. diag::err_opencl_half_param) << ParamTy;
  4218. D.setInvalidType();
  4219. Param->setInvalidDecl();
  4220. }
  4221. } else if (!S.getLangOpts().HalfArgsAndReturns) {
  4222. S.Diag(Param->getLocation(),
  4223. diag::err_parameters_retval_cannot_have_fp16_type) << 0;
  4224. D.setInvalidType();
  4225. }
  4226. } else if (!FTI.hasPrototype) {
  4227. if (ParamTy->isPromotableIntegerType()) {
  4228. ParamTy = Context.getPromotedIntegerType(ParamTy);
  4229. Param->setKNRPromoted(true);
  4230. } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
  4231. if (BTy->getKind() == BuiltinType::Float) {
  4232. ParamTy = Context.DoubleTy;
  4233. Param->setKNRPromoted(true);
  4234. }
  4235. }
  4236. }
  4237. if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
  4238. ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
  4239. HasAnyInterestingExtParameterInfos = true;
  4240. }
  4241. if (auto attr = Param->getAttr<ParameterABIAttr>()) {
  4242. ExtParameterInfos[i] =
  4243. ExtParameterInfos[i].withABI(attr->getABI());
  4244. HasAnyInterestingExtParameterInfos = true;
  4245. }
  4246. if (Param->hasAttr<PassObjectSizeAttr>()) {
  4247. ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
  4248. HasAnyInterestingExtParameterInfos = true;
  4249. }
  4250. if (Param->hasAttr<NoEscapeAttr>()) {
  4251. ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
  4252. HasAnyInterestingExtParameterInfos = true;
  4253. }
  4254. ParamTys.push_back(ParamTy);
  4255. }
  4256. if (HasAnyInterestingExtParameterInfos) {
  4257. EPI.ExtParameterInfos = ExtParameterInfos.data();
  4258. checkExtParameterInfos(S, ParamTys, EPI,
  4259. [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
  4260. }
  4261. SmallVector<QualType, 4> Exceptions;
  4262. SmallVector<ParsedType, 2> DynamicExceptions;
  4263. SmallVector<SourceRange, 2> DynamicExceptionRanges;
  4264. Expr *NoexceptExpr = nullptr;
  4265. if (FTI.getExceptionSpecType() == EST_Dynamic) {
  4266. // FIXME: It's rather inefficient to have to split into two vectors
  4267. // here.
  4268. unsigned N = FTI.getNumExceptions();
  4269. DynamicExceptions.reserve(N);
  4270. DynamicExceptionRanges.reserve(N);
  4271. for (unsigned I = 0; I != N; ++I) {
  4272. DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
  4273. DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
  4274. }
  4275. } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
  4276. NoexceptExpr = FTI.NoexceptExpr;
  4277. }
  4278. S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
  4279. FTI.getExceptionSpecType(),
  4280. DynamicExceptions,
  4281. DynamicExceptionRanges,
  4282. NoexceptExpr,
  4283. Exceptions,
  4284. EPI.ExceptionSpec);
  4285. // FIXME: Set address space from attrs for C++ mode here.
  4286. // OpenCLCPlusPlus: A class member function has an address space.
  4287. auto IsClassMember = [&]() {
  4288. return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
  4289. state.getDeclarator()
  4290. .getCXXScopeSpec()
  4291. .getScopeRep()
  4292. ->getKind() == NestedNameSpecifier::TypeSpec) ||
  4293. state.getDeclarator().getContext() ==
  4294. DeclaratorContext::MemberContext;
  4295. };
  4296. if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
  4297. LangAS ASIdx = LangAS::Default;
  4298. // Take address space attr if any and mark as invalid to avoid adding
  4299. // them later while creating QualType.
  4300. if (FTI.MethodQualifiers)
  4301. for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) {
  4302. LangAS ASIdxNew = attr.asOpenCLLangAS();
  4303. if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
  4304. attr.getLoc()))
  4305. D.setInvalidType(true);
  4306. else
  4307. ASIdx = ASIdxNew;
  4308. }
  4309. // If a class member function's address space is not set, set it to
  4310. // __generic.
  4311. LangAS AS =
  4312. (ASIdx == LangAS::Default ? LangAS::opencl_generic : ASIdx);
  4313. EPI.TypeQuals.addAddressSpace(AS);
  4314. }
  4315. T = Context.getFunctionType(T, ParamTys, EPI);
  4316. }
  4317. break;
  4318. }
  4319. case DeclaratorChunk::MemberPointer: {
  4320. // The scope spec must refer to a class, or be dependent.
  4321. CXXScopeSpec &SS = DeclType.Mem.Scope();
  4322. QualType ClsType;
  4323. // Handle pointer nullability.
  4324. inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
  4325. DeclType.EndLoc, DeclType.getAttrs(),
  4326. state.getDeclarator().getAttributePool());
  4327. if (SS.isInvalid()) {
  4328. // Avoid emitting extra errors if we already errored on the scope.
  4329. D.setInvalidType(true);
  4330. } else if (S.isDependentScopeSpecifier(SS) ||
  4331. dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
  4332. NestedNameSpecifier *NNS = SS.getScopeRep();
  4333. NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
  4334. switch (NNS->getKind()) {
  4335. case NestedNameSpecifier::Identifier:
  4336. ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
  4337. NNS->getAsIdentifier());
  4338. break;
  4339. case NestedNameSpecifier::Namespace:
  4340. case NestedNameSpecifier::NamespaceAlias:
  4341. case NestedNameSpecifier::Global:
  4342. case NestedNameSpecifier::Super:
  4343. llvm_unreachable("Nested-name-specifier must name a type");
  4344. case NestedNameSpecifier::TypeSpec:
  4345. case NestedNameSpecifier::TypeSpecWithTemplate:
  4346. ClsType = QualType(NNS->getAsType(), 0);
  4347. // Note: if the NNS has a prefix and ClsType is a nondependent
  4348. // TemplateSpecializationType, then the NNS prefix is NOT included
  4349. // in ClsType; hence we wrap ClsType into an ElaboratedType.
  4350. // NOTE: in particular, no wrap occurs if ClsType already is an
  4351. // Elaborated, DependentName, or DependentTemplateSpecialization.
  4352. if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
  4353. ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
  4354. break;
  4355. }
  4356. } else {
  4357. S.Diag(DeclType.Mem.Scope().getBeginLoc(),
  4358. diag::err_illegal_decl_mempointer_in_nonclass)
  4359. << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
  4360. << DeclType.Mem.Scope().getRange();
  4361. D.setInvalidType(true);
  4362. }
  4363. if (!ClsType.isNull())
  4364. T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
  4365. D.getIdentifier());
  4366. if (T.isNull()) {
  4367. T = Context.IntTy;
  4368. D.setInvalidType(true);
  4369. } else if (DeclType.Mem.TypeQuals) {
  4370. T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
  4371. }
  4372. break;
  4373. }
  4374. case DeclaratorChunk::Pipe: {
  4375. T = S.BuildReadPipeType(T, DeclType.Loc);
  4376. processTypeAttrs(state, T, TAL_DeclSpec,
  4377. D.getMutableDeclSpec().getAttributes());
  4378. break;
  4379. }
  4380. }
  4381. if (T.isNull()) {
  4382. D.setInvalidType(true);
  4383. T = Context.IntTy;
  4384. }
  4385. // See if there are any attributes on this declarator chunk.
  4386. processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs());
  4387. if (DeclType.Kind != DeclaratorChunk::Paren) {
  4388. if (ExpectNoDerefChunk) {
  4389. if (!IsNoDerefableChunk(DeclType))
  4390. S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
  4391. ExpectNoDerefChunk = false;
  4392. }
  4393. ExpectNoDerefChunk = state.didParseNoDeref();
  4394. }
  4395. }
  4396. if (ExpectNoDerefChunk)
  4397. S.Diag(state.getDeclarator().getBeginLoc(),
  4398. diag::warn_noderef_on_non_pointer_or_array);
  4399. // GNU warning -Wstrict-prototypes
  4400. // Warn if a function declaration is without a prototype.
  4401. // This warning is issued for all kinds of unprototyped function
  4402. // declarations (i.e. function type typedef, function pointer etc.)
  4403. // C99 6.7.5.3p14:
  4404. // The empty list in a function declarator that is not part of a definition
  4405. // of that function specifies that no information about the number or types
  4406. // of the parameters is supplied.
  4407. if (!LangOpts.CPlusPlus && D.getFunctionDefinitionKind() == FDK_Declaration) {
  4408. bool IsBlock = false;
  4409. for (const DeclaratorChunk &DeclType : D.type_objects()) {
  4410. switch (DeclType.Kind) {
  4411. case DeclaratorChunk::BlockPointer:
  4412. IsBlock = true;
  4413. break;
  4414. case DeclaratorChunk::Function: {
  4415. const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
  4416. if (FTI.NumParams == 0 && !FTI.isVariadic)
  4417. S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
  4418. << IsBlock
  4419. << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
  4420. IsBlock = false;
  4421. break;
  4422. }
  4423. default:
  4424. break;
  4425. }
  4426. }
  4427. }
  4428. assert(!T.isNull() && "T must not be null after this point");
  4429. if (LangOpts.CPlusPlus && T->isFunctionType()) {
  4430. const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
  4431. assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
  4432. // C++ 8.3.5p4:
  4433. // A cv-qualifier-seq shall only be part of the function type
  4434. // for a nonstatic member function, the function type to which a pointer
  4435. // to member refers, or the top-level function type of a function typedef
  4436. // declaration.
  4437. //
  4438. // Core issue 547 also allows cv-qualifiers on function types that are
  4439. // top-level template type arguments.
  4440. enum { NonMember, Member, DeductionGuide } Kind = NonMember;
  4441. if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
  4442. Kind = DeductionGuide;
  4443. else if (!D.getCXXScopeSpec().isSet()) {
  4444. if ((D.getContext() == DeclaratorContext::MemberContext ||
  4445. D.getContext() == DeclaratorContext::LambdaExprContext) &&
  4446. !D.getDeclSpec().isFriendSpecified())
  4447. Kind = Member;
  4448. } else {
  4449. DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
  4450. if (!DC || DC->isRecord())
  4451. Kind = Member;
  4452. }
  4453. // C++11 [dcl.fct]p6 (w/DR1417):
  4454. // An attempt to specify a function type with a cv-qualifier-seq or a
  4455. // ref-qualifier (including by typedef-name) is ill-formed unless it is:
  4456. // - the function type for a non-static member function,
  4457. // - the function type to which a pointer to member refers,
  4458. // - the top-level function type of a function typedef declaration or
  4459. // alias-declaration,
  4460. // - the type-id in the default argument of a type-parameter, or
  4461. // - the type-id of a template-argument for a type-parameter
  4462. //
  4463. // FIXME: Checking this here is insufficient. We accept-invalid on:
  4464. //
  4465. // template<typename T> struct S { void f(T); };
  4466. // S<int() const> s;
  4467. //
  4468. // ... for instance.
  4469. if (IsQualifiedFunction &&
  4470. !(Kind == Member &&
  4471. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
  4472. !IsTypedefName &&
  4473. D.getContext() != DeclaratorContext::TemplateArgContext &&
  4474. D.getContext() != DeclaratorContext::TemplateTypeArgContext) {
  4475. SourceLocation Loc = D.getBeginLoc();
  4476. SourceRange RemovalRange;
  4477. unsigned I;
  4478. if (D.isFunctionDeclarator(I)) {
  4479. SmallVector<SourceLocation, 4> RemovalLocs;
  4480. const DeclaratorChunk &Chunk = D.getTypeObject(I);
  4481. assert(Chunk.Kind == DeclaratorChunk::Function);
  4482. if (Chunk.Fun.hasRefQualifier())
  4483. RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
  4484. if (Chunk.Fun.hasMethodTypeQualifiers())
  4485. Chunk.Fun.MethodQualifiers->forEachQualifier(
  4486. [&](DeclSpec::TQ TypeQual, StringRef QualName,
  4487. SourceLocation SL) { RemovalLocs.push_back(SL); });
  4488. if (!RemovalLocs.empty()) {
  4489. llvm::sort(RemovalLocs,
  4490. BeforeThanCompare<SourceLocation>(S.getSourceManager()));
  4491. RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
  4492. Loc = RemovalLocs.front();
  4493. }
  4494. }
  4495. S.Diag(Loc, diag::err_invalid_qualified_function_type)
  4496. << Kind << D.isFunctionDeclarator() << T
  4497. << getFunctionQualifiersAsString(FnTy)
  4498. << FixItHint::CreateRemoval(RemovalRange);
  4499. // Strip the cv-qualifiers and ref-qualifiers from the type.
  4500. FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
  4501. EPI.TypeQuals.removeCVRQualifiers();
  4502. EPI.RefQualifier = RQ_None;
  4503. T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
  4504. EPI);
  4505. // Rebuild any parens around the identifier in the function type.
  4506. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  4507. if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
  4508. break;
  4509. T = S.BuildParenType(T);
  4510. }
  4511. }
  4512. }
  4513. // Apply any undistributed attributes from the declarator.
  4514. processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
  4515. // Diagnose any ignored type attributes.
  4516. state.diagnoseIgnoredTypeAttrs(T);
  4517. // C++0x [dcl.constexpr]p9:
  4518. // A constexpr specifier used in an object declaration declares the object
  4519. // as const.
  4520. if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
  4521. T.addConst();
  4522. }
  4523. // If there was an ellipsis in the declarator, the declaration declares a
  4524. // parameter pack whose type may be a pack expansion type.
  4525. if (D.hasEllipsis()) {
  4526. // C++0x [dcl.fct]p13:
  4527. // A declarator-id or abstract-declarator containing an ellipsis shall
  4528. // only be used in a parameter-declaration. Such a parameter-declaration
  4529. // is a parameter pack (14.5.3). [...]
  4530. switch (D.getContext()) {
  4531. case DeclaratorContext::PrototypeContext:
  4532. case DeclaratorContext::LambdaExprParameterContext:
  4533. // C++0x [dcl.fct]p13:
  4534. // [...] When it is part of a parameter-declaration-clause, the
  4535. // parameter pack is a function parameter pack (14.5.3). The type T
  4536. // of the declarator-id of the function parameter pack shall contain
  4537. // a template parameter pack; each template parameter pack in T is
  4538. // expanded by the function parameter pack.
  4539. //
  4540. // We represent function parameter packs as function parameters whose
  4541. // type is a pack expansion.
  4542. if (!T->containsUnexpandedParameterPack()) {
  4543. S.Diag(D.getEllipsisLoc(),
  4544. diag::err_function_parameter_pack_without_parameter_packs)
  4545. << T << D.getSourceRange();
  4546. D.setEllipsisLoc(SourceLocation());
  4547. } else {
  4548. T = Context.getPackExpansionType(T, None);
  4549. }
  4550. break;
  4551. case DeclaratorContext::TemplateParamContext:
  4552. // C++0x [temp.param]p15:
  4553. // If a template-parameter is a [...] is a parameter-declaration that
  4554. // declares a parameter pack (8.3.5), then the template-parameter is a
  4555. // template parameter pack (14.5.3).
  4556. //
  4557. // Note: core issue 778 clarifies that, if there are any unexpanded
  4558. // parameter packs in the type of the non-type template parameter, then
  4559. // it expands those parameter packs.
  4560. if (T->containsUnexpandedParameterPack())
  4561. T = Context.getPackExpansionType(T, None);
  4562. else
  4563. S.Diag(D.getEllipsisLoc(),
  4564. LangOpts.CPlusPlus11
  4565. ? diag::warn_cxx98_compat_variadic_templates
  4566. : diag::ext_variadic_templates);
  4567. break;
  4568. case DeclaratorContext::FileContext:
  4569. case DeclaratorContext::KNRTypeListContext:
  4570. case DeclaratorContext::ObjCParameterContext: // FIXME: special diagnostic
  4571. // here?
  4572. case DeclaratorContext::ObjCResultContext: // FIXME: special diagnostic
  4573. // here?
  4574. case DeclaratorContext::TypeNameContext:
  4575. case DeclaratorContext::FunctionalCastContext:
  4576. case DeclaratorContext::CXXNewContext:
  4577. case DeclaratorContext::AliasDeclContext:
  4578. case DeclaratorContext::AliasTemplateContext:
  4579. case DeclaratorContext::MemberContext:
  4580. case DeclaratorContext::BlockContext:
  4581. case DeclaratorContext::ForContext:
  4582. case DeclaratorContext::InitStmtContext:
  4583. case DeclaratorContext::ConditionContext:
  4584. case DeclaratorContext::CXXCatchContext:
  4585. case DeclaratorContext::ObjCCatchContext:
  4586. case DeclaratorContext::BlockLiteralContext:
  4587. case DeclaratorContext::LambdaExprContext:
  4588. case DeclaratorContext::ConversionIdContext:
  4589. case DeclaratorContext::TrailingReturnContext:
  4590. case DeclaratorContext::TrailingReturnVarContext:
  4591. case DeclaratorContext::TemplateArgContext:
  4592. case DeclaratorContext::TemplateTypeArgContext:
  4593. // FIXME: We may want to allow parameter packs in block-literal contexts
  4594. // in the future.
  4595. S.Diag(D.getEllipsisLoc(),
  4596. diag::err_ellipsis_in_declarator_not_parameter);
  4597. D.setEllipsisLoc(SourceLocation());
  4598. break;
  4599. }
  4600. }
  4601. assert(!T.isNull() && "T must not be null at the end of this function");
  4602. if (D.isInvalidType())
  4603. return Context.getTrivialTypeSourceInfo(T);
  4604. return GetTypeSourceInfoForDeclarator(state, T, TInfo);
  4605. }
  4606. /// GetTypeForDeclarator - Convert the type for the specified
  4607. /// declarator to Type instances.
  4608. ///
  4609. /// The result of this call will never be null, but the associated
  4610. /// type may be a null type if there's an unrecoverable error.
  4611. TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
  4612. // Determine the type of the declarator. Not all forms of declarator
  4613. // have a type.
  4614. TypeProcessingState state(*this, D);
  4615. TypeSourceInfo *ReturnTypeInfo = nullptr;
  4616. QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
  4617. if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
  4618. inferARCWriteback(state, T);
  4619. return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
  4620. }
  4621. static void transferARCOwnershipToDeclSpec(Sema &S,
  4622. QualType &declSpecTy,
  4623. Qualifiers::ObjCLifetime ownership) {
  4624. if (declSpecTy->isObjCRetainableType() &&
  4625. declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
  4626. Qualifiers qs;
  4627. qs.addObjCLifetime(ownership);
  4628. declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
  4629. }
  4630. }
  4631. static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
  4632. Qualifiers::ObjCLifetime ownership,
  4633. unsigned chunkIndex) {
  4634. Sema &S = state.getSema();
  4635. Declarator &D = state.getDeclarator();
  4636. // Look for an explicit lifetime attribute.
  4637. DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
  4638. if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
  4639. return;
  4640. const char *attrStr = nullptr;
  4641. switch (ownership) {
  4642. case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
  4643. case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
  4644. case Qualifiers::OCL_Strong: attrStr = "strong"; break;
  4645. case Qualifiers::OCL_Weak: attrStr = "weak"; break;
  4646. case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
  4647. }
  4648. IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
  4649. Arg->Ident = &S.Context.Idents.get(attrStr);
  4650. Arg->Loc = SourceLocation();
  4651. ArgsUnion Args(Arg);
  4652. // If there wasn't one, add one (with an invalid source location
  4653. // so that we don't make an AttributedType for it).
  4654. ParsedAttr *attr = D.getAttributePool().create(
  4655. &S.Context.Idents.get("objc_ownership"), SourceLocation(),
  4656. /*scope*/ nullptr, SourceLocation(),
  4657. /*args*/ &Args, 1, ParsedAttr::AS_GNU);
  4658. chunk.getAttrs().addAtEnd(attr);
  4659. // TODO: mark whether we did this inference?
  4660. }
  4661. /// Used for transferring ownership in casts resulting in l-values.
  4662. static void transferARCOwnership(TypeProcessingState &state,
  4663. QualType &declSpecTy,
  4664. Qualifiers::ObjCLifetime ownership) {
  4665. Sema &S = state.getSema();
  4666. Declarator &D = state.getDeclarator();
  4667. int inner = -1;
  4668. bool hasIndirection = false;
  4669. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  4670. DeclaratorChunk &chunk = D.getTypeObject(i);
  4671. switch (chunk.Kind) {
  4672. case DeclaratorChunk::Paren:
  4673. // Ignore parens.
  4674. break;
  4675. case DeclaratorChunk::Array:
  4676. case DeclaratorChunk::Reference:
  4677. case DeclaratorChunk::Pointer:
  4678. if (inner != -1)
  4679. hasIndirection = true;
  4680. inner = i;
  4681. break;
  4682. case DeclaratorChunk::BlockPointer:
  4683. if (inner != -1)
  4684. transferARCOwnershipToDeclaratorChunk(state, ownership, i);
  4685. return;
  4686. case DeclaratorChunk::Function:
  4687. case DeclaratorChunk::MemberPointer:
  4688. case DeclaratorChunk::Pipe:
  4689. return;
  4690. }
  4691. }
  4692. if (inner == -1)
  4693. return;
  4694. DeclaratorChunk &chunk = D.getTypeObject(inner);
  4695. if (chunk.Kind == DeclaratorChunk::Pointer) {
  4696. if (declSpecTy->isObjCRetainableType())
  4697. return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
  4698. if (declSpecTy->isObjCObjectType() && hasIndirection)
  4699. return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
  4700. } else {
  4701. assert(chunk.Kind == DeclaratorChunk::Array ||
  4702. chunk.Kind == DeclaratorChunk::Reference);
  4703. return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
  4704. }
  4705. }
  4706. TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
  4707. TypeProcessingState state(*this, D);
  4708. TypeSourceInfo *ReturnTypeInfo = nullptr;
  4709. QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
  4710. if (getLangOpts().ObjC) {
  4711. Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
  4712. if (ownership != Qualifiers::OCL_None)
  4713. transferARCOwnership(state, declSpecTy, ownership);
  4714. }
  4715. return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
  4716. }
  4717. static void fillAttributedTypeLoc(AttributedTypeLoc TL,
  4718. TypeProcessingState &State) {
  4719. TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
  4720. }
  4721. namespace {
  4722. class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
  4723. ASTContext &Context;
  4724. TypeProcessingState &State;
  4725. const DeclSpec &DS;
  4726. public:
  4727. TypeSpecLocFiller(ASTContext &Context, TypeProcessingState &State,
  4728. const DeclSpec &DS)
  4729. : Context(Context), State(State), DS(DS) {}
  4730. void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  4731. Visit(TL.getModifiedLoc());
  4732. fillAttributedTypeLoc(TL, State);
  4733. }
  4734. void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  4735. Visit(TL.getUnqualifiedLoc());
  4736. }
  4737. void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
  4738. TL.setNameLoc(DS.getTypeSpecTypeLoc());
  4739. }
  4740. void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
  4741. TL.setNameLoc(DS.getTypeSpecTypeLoc());
  4742. // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
  4743. // addition field. What we have is good enough for dispay of location
  4744. // of 'fixit' on interface name.
  4745. TL.setNameEndLoc(DS.getEndLoc());
  4746. }
  4747. void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
  4748. TypeSourceInfo *RepTInfo = nullptr;
  4749. Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
  4750. TL.copy(RepTInfo->getTypeLoc());
  4751. }
  4752. void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  4753. TypeSourceInfo *RepTInfo = nullptr;
  4754. Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
  4755. TL.copy(RepTInfo->getTypeLoc());
  4756. }
  4757. void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
  4758. TypeSourceInfo *TInfo = nullptr;
  4759. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4760. // If we got no declarator info from previous Sema routines,
  4761. // just fill with the typespec loc.
  4762. if (!TInfo) {
  4763. TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
  4764. return;
  4765. }
  4766. TypeLoc OldTL = TInfo->getTypeLoc();
  4767. if (TInfo->getType()->getAs<ElaboratedType>()) {
  4768. ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
  4769. TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
  4770. .castAs<TemplateSpecializationTypeLoc>();
  4771. TL.copy(NamedTL);
  4772. } else {
  4773. TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
  4774. assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
  4775. }
  4776. }
  4777. void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
  4778. assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
  4779. TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
  4780. TL.setParensRange(DS.getTypeofParensRange());
  4781. }
  4782. void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
  4783. assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
  4784. TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
  4785. TL.setParensRange(DS.getTypeofParensRange());
  4786. assert(DS.getRepAsType());
  4787. TypeSourceInfo *TInfo = nullptr;
  4788. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4789. TL.setUnderlyingTInfo(TInfo);
  4790. }
  4791. void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
  4792. // FIXME: This holds only because we only have one unary transform.
  4793. assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
  4794. TL.setKWLoc(DS.getTypeSpecTypeLoc());
  4795. TL.setParensRange(DS.getTypeofParensRange());
  4796. assert(DS.getRepAsType());
  4797. TypeSourceInfo *TInfo = nullptr;
  4798. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4799. TL.setUnderlyingTInfo(TInfo);
  4800. }
  4801. void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
  4802. // By default, use the source location of the type specifier.
  4803. TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
  4804. if (TL.needsExtraLocalData()) {
  4805. // Set info for the written builtin specifiers.
  4806. TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
  4807. // Try to have a meaningful source location.
  4808. if (TL.getWrittenSignSpec() != TSS_unspecified)
  4809. TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
  4810. if (TL.getWrittenWidthSpec() != TSW_unspecified)
  4811. TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
  4812. }
  4813. }
  4814. void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
  4815. ElaboratedTypeKeyword Keyword
  4816. = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
  4817. if (DS.getTypeSpecType() == TST_typename) {
  4818. TypeSourceInfo *TInfo = nullptr;
  4819. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4820. if (TInfo) {
  4821. TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
  4822. return;
  4823. }
  4824. }
  4825. TL.setElaboratedKeywordLoc(Keyword != ETK_None
  4826. ? DS.getTypeSpecTypeLoc()
  4827. : SourceLocation());
  4828. const CXXScopeSpec& SS = DS.getTypeSpecScope();
  4829. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  4830. Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
  4831. }
  4832. void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
  4833. assert(DS.getTypeSpecType() == TST_typename);
  4834. TypeSourceInfo *TInfo = nullptr;
  4835. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4836. assert(TInfo);
  4837. TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
  4838. }
  4839. void VisitDependentTemplateSpecializationTypeLoc(
  4840. DependentTemplateSpecializationTypeLoc TL) {
  4841. assert(DS.getTypeSpecType() == TST_typename);
  4842. TypeSourceInfo *TInfo = nullptr;
  4843. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4844. assert(TInfo);
  4845. TL.copy(
  4846. TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
  4847. }
  4848. void VisitTagTypeLoc(TagTypeLoc TL) {
  4849. TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
  4850. }
  4851. void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
  4852. // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
  4853. // or an _Atomic qualifier.
  4854. if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
  4855. TL.setKWLoc(DS.getTypeSpecTypeLoc());
  4856. TL.setParensRange(DS.getTypeofParensRange());
  4857. TypeSourceInfo *TInfo = nullptr;
  4858. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4859. assert(TInfo);
  4860. TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
  4861. } else {
  4862. TL.setKWLoc(DS.getAtomicSpecLoc());
  4863. // No parens, to indicate this was spelled as an _Atomic qualifier.
  4864. TL.setParensRange(SourceRange());
  4865. Visit(TL.getValueLoc());
  4866. }
  4867. }
  4868. void VisitPipeTypeLoc(PipeTypeLoc TL) {
  4869. TL.setKWLoc(DS.getTypeSpecTypeLoc());
  4870. TypeSourceInfo *TInfo = nullptr;
  4871. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4872. TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
  4873. }
  4874. void VisitTypeLoc(TypeLoc TL) {
  4875. // FIXME: add other typespec types and change this to an assert.
  4876. TL.initialize(Context, DS.getTypeSpecTypeLoc());
  4877. }
  4878. };
  4879. class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
  4880. ASTContext &Context;
  4881. TypeProcessingState &State;
  4882. const DeclaratorChunk &Chunk;
  4883. public:
  4884. DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
  4885. const DeclaratorChunk &Chunk)
  4886. : Context(Context), State(State), Chunk(Chunk) {}
  4887. void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  4888. llvm_unreachable("qualified type locs not expected here!");
  4889. }
  4890. void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
  4891. llvm_unreachable("decayed type locs not expected here!");
  4892. }
  4893. void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  4894. fillAttributedTypeLoc(TL, State);
  4895. }
  4896. void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
  4897. // nothing
  4898. }
  4899. void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
  4900. assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
  4901. TL.setCaretLoc(Chunk.Loc);
  4902. }
  4903. void VisitPointerTypeLoc(PointerTypeLoc TL) {
  4904. assert(Chunk.Kind == DeclaratorChunk::Pointer);
  4905. TL.setStarLoc(Chunk.Loc);
  4906. }
  4907. void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  4908. assert(Chunk.Kind == DeclaratorChunk::Pointer);
  4909. TL.setStarLoc(Chunk.Loc);
  4910. }
  4911. void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
  4912. assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
  4913. const CXXScopeSpec& SS = Chunk.Mem.Scope();
  4914. NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
  4915. const Type* ClsTy = TL.getClass();
  4916. QualType ClsQT = QualType(ClsTy, 0);
  4917. TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
  4918. // Now copy source location info into the type loc component.
  4919. TypeLoc ClsTL = ClsTInfo->getTypeLoc();
  4920. switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
  4921. case NestedNameSpecifier::Identifier:
  4922. assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
  4923. {
  4924. DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
  4925. DNTLoc.setElaboratedKeywordLoc(SourceLocation());
  4926. DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
  4927. DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
  4928. }
  4929. break;
  4930. case NestedNameSpecifier::TypeSpec:
  4931. case NestedNameSpecifier::TypeSpecWithTemplate:
  4932. if (isa<ElaboratedType>(ClsTy)) {
  4933. ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
  4934. ETLoc.setElaboratedKeywordLoc(SourceLocation());
  4935. ETLoc.setQualifierLoc(NNSLoc.getPrefix());
  4936. TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
  4937. NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
  4938. } else {
  4939. ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
  4940. }
  4941. break;
  4942. case NestedNameSpecifier::Namespace:
  4943. case NestedNameSpecifier::NamespaceAlias:
  4944. case NestedNameSpecifier::Global:
  4945. case NestedNameSpecifier::Super:
  4946. llvm_unreachable("Nested-name-specifier must name a type");
  4947. }
  4948. // Finally fill in MemberPointerLocInfo fields.
  4949. TL.setStarLoc(Chunk.Loc);
  4950. TL.setClassTInfo(ClsTInfo);
  4951. }
  4952. void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
  4953. assert(Chunk.Kind == DeclaratorChunk::Reference);
  4954. // 'Amp' is misleading: this might have been originally
  4955. /// spelled with AmpAmp.
  4956. TL.setAmpLoc(Chunk.Loc);
  4957. }
  4958. void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
  4959. assert(Chunk.Kind == DeclaratorChunk::Reference);
  4960. assert(!Chunk.Ref.LValueRef);
  4961. TL.setAmpAmpLoc(Chunk.Loc);
  4962. }
  4963. void VisitArrayTypeLoc(ArrayTypeLoc TL) {
  4964. assert(Chunk.Kind == DeclaratorChunk::Array);
  4965. TL.setLBracketLoc(Chunk.Loc);
  4966. TL.setRBracketLoc(Chunk.EndLoc);
  4967. TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
  4968. }
  4969. void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
  4970. assert(Chunk.Kind == DeclaratorChunk::Function);
  4971. TL.setLocalRangeBegin(Chunk.Loc);
  4972. TL.setLocalRangeEnd(Chunk.EndLoc);
  4973. const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
  4974. TL.setLParenLoc(FTI.getLParenLoc());
  4975. TL.setRParenLoc(FTI.getRParenLoc());
  4976. for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
  4977. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  4978. TL.setParam(tpi++, Param);
  4979. }
  4980. TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
  4981. }
  4982. void VisitParenTypeLoc(ParenTypeLoc TL) {
  4983. assert(Chunk.Kind == DeclaratorChunk::Paren);
  4984. TL.setLParenLoc(Chunk.Loc);
  4985. TL.setRParenLoc(Chunk.EndLoc);
  4986. }
  4987. void VisitPipeTypeLoc(PipeTypeLoc TL) {
  4988. assert(Chunk.Kind == DeclaratorChunk::Pipe);
  4989. TL.setKWLoc(Chunk.Loc);
  4990. }
  4991. void VisitTypeLoc(TypeLoc TL) {
  4992. llvm_unreachable("unsupported TypeLoc kind in declarator!");
  4993. }
  4994. };
  4995. } // end anonymous namespace
  4996. static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
  4997. SourceLocation Loc;
  4998. switch (Chunk.Kind) {
  4999. case DeclaratorChunk::Function:
  5000. case DeclaratorChunk::Array:
  5001. case DeclaratorChunk::Paren:
  5002. case DeclaratorChunk::Pipe:
  5003. llvm_unreachable("cannot be _Atomic qualified");
  5004. case DeclaratorChunk::Pointer:
  5005. Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
  5006. break;
  5007. case DeclaratorChunk::BlockPointer:
  5008. case DeclaratorChunk::Reference:
  5009. case DeclaratorChunk::MemberPointer:
  5010. // FIXME: Provide a source location for the _Atomic keyword.
  5011. break;
  5012. }
  5013. ATL.setKWLoc(Loc);
  5014. ATL.setParensRange(SourceRange());
  5015. }
  5016. static void
  5017. fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL,
  5018. const ParsedAttributesView &Attrs) {
  5019. for (const ParsedAttr &AL : Attrs) {
  5020. if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
  5021. DASTL.setAttrNameLoc(AL.getLoc());
  5022. DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
  5023. DASTL.setAttrOperandParensRange(SourceRange());
  5024. return;
  5025. }
  5026. }
  5027. llvm_unreachable(
  5028. "no address_space attribute found at the expected location!");
  5029. }
  5030. /// Create and instantiate a TypeSourceInfo with type source information.
  5031. ///
  5032. /// \param T QualType referring to the type as written in source code.
  5033. ///
  5034. /// \param ReturnTypeInfo For declarators whose return type does not show
  5035. /// up in the normal place in the declaration specifiers (such as a C++
  5036. /// conversion function), this pointer will refer to a type source information
  5037. /// for that return type.
  5038. static TypeSourceInfo *
  5039. GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
  5040. QualType T, TypeSourceInfo *ReturnTypeInfo) {
  5041. Sema &S = State.getSema();
  5042. Declarator &D = State.getDeclarator();
  5043. TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T);
  5044. UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
  5045. // Handle parameter packs whose type is a pack expansion.
  5046. if (isa<PackExpansionType>(T)) {
  5047. CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
  5048. CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
  5049. }
  5050. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  5051. // An AtomicTypeLoc might be produced by an atomic qualifier in this
  5052. // declarator chunk.
  5053. if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
  5054. fillAtomicQualLoc(ATL, D.getTypeObject(i));
  5055. CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
  5056. }
  5057. while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
  5058. fillAttributedTypeLoc(TL, State);
  5059. CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
  5060. }
  5061. while (DependentAddressSpaceTypeLoc TL =
  5062. CurrTL.getAs<DependentAddressSpaceTypeLoc>()) {
  5063. fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs());
  5064. CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
  5065. }
  5066. // FIXME: Ordering here?
  5067. while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
  5068. CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
  5069. DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
  5070. CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
  5071. }
  5072. // If we have different source information for the return type, use
  5073. // that. This really only applies to C++ conversion functions.
  5074. if (ReturnTypeInfo) {
  5075. TypeLoc TL = ReturnTypeInfo->getTypeLoc();
  5076. assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
  5077. memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
  5078. } else {
  5079. TypeSpecLocFiller(S.Context, State, D.getDeclSpec()).Visit(CurrTL);
  5080. }
  5081. return TInfo;
  5082. }
  5083. /// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
  5084. ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
  5085. // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
  5086. // and Sema during declaration parsing. Try deallocating/caching them when
  5087. // it's appropriate, instead of allocating them and keeping them around.
  5088. LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
  5089. TypeAlignment);
  5090. new (LocT) LocInfoType(T, TInfo);
  5091. assert(LocT->getTypeClass() != T->getTypeClass() &&
  5092. "LocInfoType's TypeClass conflicts with an existing Type class");
  5093. return ParsedType::make(QualType(LocT, 0));
  5094. }
  5095. void LocInfoType::getAsStringInternal(std::string &Str,
  5096. const PrintingPolicy &Policy) const {
  5097. llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
  5098. " was used directly instead of getting the QualType through"
  5099. " GetTypeFromParser");
  5100. }
  5101. TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
  5102. // C99 6.7.6: Type names have no identifier. This is already validated by
  5103. // the parser.
  5104. assert(D.getIdentifier() == nullptr &&
  5105. "Type name should have no identifier!");
  5106. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  5107. QualType T = TInfo->getType();
  5108. if (D.isInvalidType())
  5109. return true;
  5110. // Make sure there are no unused decl attributes on the declarator.
  5111. // We don't want to do this for ObjC parameters because we're going
  5112. // to apply them to the actual parameter declaration.
  5113. // Likewise, we don't want to do this for alias declarations, because
  5114. // we are actually going to build a declaration from this eventually.
  5115. if (D.getContext() != DeclaratorContext::ObjCParameterContext &&
  5116. D.getContext() != DeclaratorContext::AliasDeclContext &&
  5117. D.getContext() != DeclaratorContext::AliasTemplateContext)
  5118. checkUnusedDeclAttributes(D);
  5119. if (getLangOpts().CPlusPlus) {
  5120. // Check that there are no default arguments (C++ only).
  5121. CheckExtraCXXDefaultArguments(D);
  5122. }
  5123. return CreateParsedType(T, TInfo);
  5124. }
  5125. ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
  5126. QualType T = Context.getObjCInstanceType();
  5127. TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  5128. return CreateParsedType(T, TInfo);
  5129. }
  5130. //===----------------------------------------------------------------------===//
  5131. // Type Attribute Processing
  5132. //===----------------------------------------------------------------------===//
  5133. /// Build an AddressSpace index from a constant expression and diagnose any
  5134. /// errors related to invalid address_spaces. Returns true on successfully
  5135. /// building an AddressSpace index.
  5136. static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
  5137. const Expr *AddrSpace,
  5138. SourceLocation AttrLoc) {
  5139. if (!AddrSpace->isValueDependent()) {
  5140. llvm::APSInt addrSpace(32);
  5141. if (!AddrSpace->isIntegerConstantExpr(addrSpace, S.Context)) {
  5142. S.Diag(AttrLoc, diag::err_attribute_argument_type)
  5143. << "'address_space'" << AANT_ArgumentIntegerConstant
  5144. << AddrSpace->getSourceRange();
  5145. return false;
  5146. }
  5147. // Bounds checking.
  5148. if (addrSpace.isSigned()) {
  5149. if (addrSpace.isNegative()) {
  5150. S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
  5151. << AddrSpace->getSourceRange();
  5152. return false;
  5153. }
  5154. addrSpace.setIsSigned(false);
  5155. }
  5156. llvm::APSInt max(addrSpace.getBitWidth());
  5157. max =
  5158. Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace;
  5159. if (addrSpace > max) {
  5160. S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
  5161. << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
  5162. return false;
  5163. }
  5164. ASIdx =
  5165. getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
  5166. return true;
  5167. }
  5168. // Default value for DependentAddressSpaceTypes
  5169. ASIdx = LangAS::Default;
  5170. return true;
  5171. }
  5172. /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression
  5173. /// is uninstantiated. If instantiated it will apply the appropriate address
  5174. /// space to the type. This function allows dependent template variables to be
  5175. /// used in conjunction with the address_space attribute
  5176. QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
  5177. SourceLocation AttrLoc) {
  5178. if (!AddrSpace->isValueDependent()) {
  5179. if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
  5180. AttrLoc))
  5181. return QualType();
  5182. return Context.getAddrSpaceQualType(T, ASIdx);
  5183. }
  5184. // A check with similar intentions as checking if a type already has an
  5185. // address space except for on a dependent types, basically if the
  5186. // current type is already a DependentAddressSpaceType then its already
  5187. // lined up to have another address space on it and we can't have
  5188. // multiple address spaces on the one pointer indirection
  5189. if (T->getAs<DependentAddressSpaceType>()) {
  5190. Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
  5191. return QualType();
  5192. }
  5193. return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
  5194. }
  5195. QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
  5196. SourceLocation AttrLoc) {
  5197. LangAS ASIdx;
  5198. if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
  5199. return QualType();
  5200. return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
  5201. }
  5202. /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
  5203. /// specified type. The attribute contains 1 argument, the id of the address
  5204. /// space for the type.
  5205. static void HandleAddressSpaceTypeAttribute(QualType &Type,
  5206. const ParsedAttr &Attr,
  5207. TypeProcessingState &State) {
  5208. Sema &S = State.getSema();
  5209. // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
  5210. // qualified by an address-space qualifier."
  5211. if (Type->isFunctionType()) {
  5212. S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
  5213. Attr.setInvalid();
  5214. return;
  5215. }
  5216. LangAS ASIdx;
  5217. if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
  5218. // Check the attribute arguments.
  5219. if (Attr.getNumArgs() != 1) {
  5220. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
  5221. << 1;
  5222. Attr.setInvalid();
  5223. return;
  5224. }
  5225. Expr *ASArgExpr;
  5226. if (Attr.isArgIdent(0)) {
  5227. // Special case where the argument is a template id.
  5228. CXXScopeSpec SS;
  5229. SourceLocation TemplateKWLoc;
  5230. UnqualifiedId id;
  5231. id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
  5232. ExprResult AddrSpace = S.ActOnIdExpression(
  5233. S.getCurScope(), SS, TemplateKWLoc, id, /*HasTrailingLParen=*/false,
  5234. /*IsAddressOfOperand=*/false);
  5235. if (AddrSpace.isInvalid())
  5236. return;
  5237. ASArgExpr = static_cast<Expr *>(AddrSpace.get());
  5238. } else {
  5239. ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
  5240. }
  5241. LangAS ASIdx;
  5242. if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
  5243. Attr.setInvalid();
  5244. return;
  5245. }
  5246. ASTContext &Ctx = S.Context;
  5247. auto *ASAttr = ::new (Ctx) AddressSpaceAttr(
  5248. Attr.getRange(), Ctx, Attr.getAttributeSpellingListIndex(),
  5249. static_cast<unsigned>(ASIdx));
  5250. // If the expression is not value dependent (not templated), then we can
  5251. // apply the address space qualifiers just to the equivalent type.
  5252. // Otherwise, we make an AttributedType with the modified and equivalent
  5253. // type the same, and wrap it in a DependentAddressSpaceType. When this
  5254. // dependent type is resolved, the qualifier is added to the equivalent type
  5255. // later.
  5256. QualType T;
  5257. if (!ASArgExpr->isValueDependent()) {
  5258. QualType EquivType =
  5259. S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
  5260. if (EquivType.isNull()) {
  5261. Attr.setInvalid();
  5262. return;
  5263. }
  5264. T = State.getAttributedType(ASAttr, Type, EquivType);
  5265. } else {
  5266. T = State.getAttributedType(ASAttr, Type, Type);
  5267. T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
  5268. }
  5269. if (!T.isNull())
  5270. Type = T;
  5271. else
  5272. Attr.setInvalid();
  5273. } else {
  5274. // The keyword-based type attributes imply which address space to use.
  5275. ASIdx = Attr.asOpenCLLangAS();
  5276. if (ASIdx == LangAS::Default)
  5277. llvm_unreachable("Invalid address space");
  5278. if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
  5279. Attr.getLoc())) {
  5280. Attr.setInvalid();
  5281. return;
  5282. }
  5283. Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
  5284. }
  5285. }
  5286. /// Does this type have a "direct" ownership qualifier? That is,
  5287. /// is it written like "__strong id", as opposed to something like
  5288. /// "typeof(foo)", where that happens to be strong?
  5289. static bool hasDirectOwnershipQualifier(QualType type) {
  5290. // Fast path: no qualifier at all.
  5291. assert(type.getQualifiers().hasObjCLifetime());
  5292. while (true) {
  5293. // __strong id
  5294. if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
  5295. if (attr->getAttrKind() == attr::ObjCOwnership)
  5296. return true;
  5297. type = attr->getModifiedType();
  5298. // X *__strong (...)
  5299. } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
  5300. type = paren->getInnerType();
  5301. // That's it for things we want to complain about. In particular,
  5302. // we do not want to look through typedefs, typeof(expr),
  5303. // typeof(type), or any other way that the type is somehow
  5304. // abstracted.
  5305. } else {
  5306. return false;
  5307. }
  5308. }
  5309. }
  5310. /// handleObjCOwnershipTypeAttr - Process an objc_ownership
  5311. /// attribute on the specified type.
  5312. ///
  5313. /// Returns 'true' if the attribute was handled.
  5314. static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
  5315. ParsedAttr &attr, QualType &type) {
  5316. bool NonObjCPointer = false;
  5317. if (!type->isDependentType() && !type->isUndeducedType()) {
  5318. if (const PointerType *ptr = type->getAs<PointerType>()) {
  5319. QualType pointee = ptr->getPointeeType();
  5320. if (pointee->isObjCRetainableType() || pointee->isPointerType())
  5321. return false;
  5322. // It is important not to lose the source info that there was an attribute
  5323. // applied to non-objc pointer. We will create an attributed type but
  5324. // its type will be the same as the original type.
  5325. NonObjCPointer = true;
  5326. } else if (!type->isObjCRetainableType()) {
  5327. return false;
  5328. }
  5329. // Don't accept an ownership attribute in the declspec if it would
  5330. // just be the return type of a block pointer.
  5331. if (state.isProcessingDeclSpec()) {
  5332. Declarator &D = state.getDeclarator();
  5333. if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
  5334. /*onlyBlockPointers=*/true))
  5335. return false;
  5336. }
  5337. }
  5338. Sema &S = state.getSema();
  5339. SourceLocation AttrLoc = attr.getLoc();
  5340. if (AttrLoc.isMacroID())
  5341. AttrLoc =
  5342. S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin();
  5343. if (!attr.isArgIdent(0)) {
  5344. S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
  5345. << AANT_ArgumentString;
  5346. attr.setInvalid();
  5347. return true;
  5348. }
  5349. IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
  5350. Qualifiers::ObjCLifetime lifetime;
  5351. if (II->isStr("none"))
  5352. lifetime = Qualifiers::OCL_ExplicitNone;
  5353. else if (II->isStr("strong"))
  5354. lifetime = Qualifiers::OCL_Strong;
  5355. else if (II->isStr("weak"))
  5356. lifetime = Qualifiers::OCL_Weak;
  5357. else if (II->isStr("autoreleasing"))
  5358. lifetime = Qualifiers::OCL_Autoreleasing;
  5359. else {
  5360. S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
  5361. << attr.getName() << II;
  5362. attr.setInvalid();
  5363. return true;
  5364. }
  5365. // Just ignore lifetime attributes other than __weak and __unsafe_unretained
  5366. // outside of ARC mode.
  5367. if (!S.getLangOpts().ObjCAutoRefCount &&
  5368. lifetime != Qualifiers::OCL_Weak &&
  5369. lifetime != Qualifiers::OCL_ExplicitNone) {
  5370. return true;
  5371. }
  5372. SplitQualType underlyingType = type.split();
  5373. // Check for redundant/conflicting ownership qualifiers.
  5374. if (Qualifiers::ObjCLifetime previousLifetime
  5375. = type.getQualifiers().getObjCLifetime()) {
  5376. // If it's written directly, that's an error.
  5377. if (hasDirectOwnershipQualifier(type)) {
  5378. S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
  5379. << type;
  5380. return true;
  5381. }
  5382. // Otherwise, if the qualifiers actually conflict, pull sugar off
  5383. // and remove the ObjCLifetime qualifiers.
  5384. if (previousLifetime != lifetime) {
  5385. // It's possible to have multiple local ObjCLifetime qualifiers. We
  5386. // can't stop after we reach a type that is directly qualified.
  5387. const Type *prevTy = nullptr;
  5388. while (!prevTy || prevTy != underlyingType.Ty) {
  5389. prevTy = underlyingType.Ty;
  5390. underlyingType = underlyingType.getSingleStepDesugaredType();
  5391. }
  5392. underlyingType.Quals.removeObjCLifetime();
  5393. }
  5394. }
  5395. underlyingType.Quals.addObjCLifetime(lifetime);
  5396. if (NonObjCPointer) {
  5397. StringRef name = attr.getName()->getName();
  5398. switch (lifetime) {
  5399. case Qualifiers::OCL_None:
  5400. case Qualifiers::OCL_ExplicitNone:
  5401. break;
  5402. case Qualifiers::OCL_Strong: name = "__strong"; break;
  5403. case Qualifiers::OCL_Weak: name = "__weak"; break;
  5404. case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
  5405. }
  5406. S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
  5407. << TDS_ObjCObjOrBlock << type;
  5408. }
  5409. // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
  5410. // because having both 'T' and '__unsafe_unretained T' exist in the type
  5411. // system causes unfortunate widespread consistency problems. (For example,
  5412. // they're not considered compatible types, and we mangle them identicially
  5413. // as template arguments.) These problems are all individually fixable,
  5414. // but it's easier to just not add the qualifier and instead sniff it out
  5415. // in specific places using isObjCInertUnsafeUnretainedType().
  5416. //
  5417. // Doing this does means we miss some trivial consistency checks that
  5418. // would've triggered in ARC, but that's better than trying to solve all
  5419. // the coexistence problems with __unsafe_unretained.
  5420. if (!S.getLangOpts().ObjCAutoRefCount &&
  5421. lifetime == Qualifiers::OCL_ExplicitNone) {
  5422. type = state.getAttributedType(
  5423. createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr),
  5424. type, type);
  5425. return true;
  5426. }
  5427. QualType origType = type;
  5428. if (!NonObjCPointer)
  5429. type = S.Context.getQualifiedType(underlyingType);
  5430. // If we have a valid source location for the attribute, use an
  5431. // AttributedType instead.
  5432. if (AttrLoc.isValid()) {
  5433. type = state.getAttributedType(::new (S.Context) ObjCOwnershipAttr(
  5434. attr.getRange(), S.Context, II,
  5435. attr.getAttributeSpellingListIndex()),
  5436. origType, type);
  5437. }
  5438. auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
  5439. unsigned diagnostic, QualType type) {
  5440. if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
  5441. S.DelayedDiagnostics.add(
  5442. sema::DelayedDiagnostic::makeForbiddenType(
  5443. S.getSourceManager().getExpansionLoc(loc),
  5444. diagnostic, type, /*ignored*/ 0));
  5445. } else {
  5446. S.Diag(loc, diagnostic);
  5447. }
  5448. };
  5449. // Sometimes, __weak isn't allowed.
  5450. if (lifetime == Qualifiers::OCL_Weak &&
  5451. !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
  5452. // Use a specialized diagnostic if the runtime just doesn't support them.
  5453. unsigned diagnostic =
  5454. (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
  5455. : diag::err_arc_weak_no_runtime);
  5456. // In any case, delay the diagnostic until we know what we're parsing.
  5457. diagnoseOrDelay(S, AttrLoc, diagnostic, type);
  5458. attr.setInvalid();
  5459. return true;
  5460. }
  5461. // Forbid __weak for class objects marked as
  5462. // objc_arc_weak_reference_unavailable
  5463. if (lifetime == Qualifiers::OCL_Weak) {
  5464. if (const ObjCObjectPointerType *ObjT =
  5465. type->getAs<ObjCObjectPointerType>()) {
  5466. if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
  5467. if (Class->isArcWeakrefUnavailable()) {
  5468. S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
  5469. S.Diag(ObjT->getInterfaceDecl()->getLocation(),
  5470. diag::note_class_declared);
  5471. }
  5472. }
  5473. }
  5474. }
  5475. return true;
  5476. }
  5477. /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
  5478. /// attribute on the specified type. Returns true to indicate that
  5479. /// the attribute was handled, false to indicate that the type does
  5480. /// not permit the attribute.
  5481. static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
  5482. QualType &type) {
  5483. Sema &S = state.getSema();
  5484. // Delay if this isn't some kind of pointer.
  5485. if (!type->isPointerType() &&
  5486. !type->isObjCObjectPointerType() &&
  5487. !type->isBlockPointerType())
  5488. return false;
  5489. if (type.getObjCGCAttr() != Qualifiers::GCNone) {
  5490. S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
  5491. attr.setInvalid();
  5492. return true;
  5493. }
  5494. // Check the attribute arguments.
  5495. if (!attr.isArgIdent(0)) {
  5496. S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
  5497. << attr << AANT_ArgumentString;
  5498. attr.setInvalid();
  5499. return true;
  5500. }
  5501. Qualifiers::GC GCAttr;
  5502. if (attr.getNumArgs() > 1) {
  5503. S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
  5504. << 1;
  5505. attr.setInvalid();
  5506. return true;
  5507. }
  5508. IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
  5509. if (II->isStr("weak"))
  5510. GCAttr = Qualifiers::Weak;
  5511. else if (II->isStr("strong"))
  5512. GCAttr = Qualifiers::Strong;
  5513. else {
  5514. S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
  5515. << attr.getName() << II;
  5516. attr.setInvalid();
  5517. return true;
  5518. }
  5519. QualType origType = type;
  5520. type = S.Context.getObjCGCQualType(origType, GCAttr);
  5521. // Make an attributed type to preserve the source information.
  5522. if (attr.getLoc().isValid())
  5523. type = state.getAttributedType(
  5524. ::new (S.Context) ObjCGCAttr(attr.getRange(), S.Context, II,
  5525. attr.getAttributeSpellingListIndex()),
  5526. origType, type);
  5527. return true;
  5528. }
  5529. namespace {
  5530. /// A helper class to unwrap a type down to a function for the
  5531. /// purposes of applying attributes there.
  5532. ///
  5533. /// Use:
  5534. /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
  5535. /// if (unwrapped.isFunctionType()) {
  5536. /// const FunctionType *fn = unwrapped.get();
  5537. /// // change fn somehow
  5538. /// T = unwrapped.wrap(fn);
  5539. /// }
  5540. struct FunctionTypeUnwrapper {
  5541. enum WrapKind {
  5542. Desugar,
  5543. Attributed,
  5544. Parens,
  5545. Pointer,
  5546. BlockPointer,
  5547. Reference,
  5548. MemberPointer
  5549. };
  5550. QualType Original;
  5551. const FunctionType *Fn;
  5552. SmallVector<unsigned char /*WrapKind*/, 8> Stack;
  5553. FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
  5554. while (true) {
  5555. const Type *Ty = T.getTypePtr();
  5556. if (isa<FunctionType>(Ty)) {
  5557. Fn = cast<FunctionType>(Ty);
  5558. return;
  5559. } else if (isa<ParenType>(Ty)) {
  5560. T = cast<ParenType>(Ty)->getInnerType();
  5561. Stack.push_back(Parens);
  5562. } else if (isa<PointerType>(Ty)) {
  5563. T = cast<PointerType>(Ty)->getPointeeType();
  5564. Stack.push_back(Pointer);
  5565. } else if (isa<BlockPointerType>(Ty)) {
  5566. T = cast<BlockPointerType>(Ty)->getPointeeType();
  5567. Stack.push_back(BlockPointer);
  5568. } else if (isa<MemberPointerType>(Ty)) {
  5569. T = cast<MemberPointerType>(Ty)->getPointeeType();
  5570. Stack.push_back(MemberPointer);
  5571. } else if (isa<ReferenceType>(Ty)) {
  5572. T = cast<ReferenceType>(Ty)->getPointeeType();
  5573. Stack.push_back(Reference);
  5574. } else if (isa<AttributedType>(Ty)) {
  5575. T = cast<AttributedType>(Ty)->getEquivalentType();
  5576. Stack.push_back(Attributed);
  5577. } else {
  5578. const Type *DTy = Ty->getUnqualifiedDesugaredType();
  5579. if (Ty == DTy) {
  5580. Fn = nullptr;
  5581. return;
  5582. }
  5583. T = QualType(DTy, 0);
  5584. Stack.push_back(Desugar);
  5585. }
  5586. }
  5587. }
  5588. bool isFunctionType() const { return (Fn != nullptr); }
  5589. const FunctionType *get() const { return Fn; }
  5590. QualType wrap(Sema &S, const FunctionType *New) {
  5591. // If T wasn't modified from the unwrapped type, do nothing.
  5592. if (New == get()) return Original;
  5593. Fn = New;
  5594. return wrap(S.Context, Original, 0);
  5595. }
  5596. private:
  5597. QualType wrap(ASTContext &C, QualType Old, unsigned I) {
  5598. if (I == Stack.size())
  5599. return C.getQualifiedType(Fn, Old.getQualifiers());
  5600. // Build up the inner type, applying the qualifiers from the old
  5601. // type to the new type.
  5602. SplitQualType SplitOld = Old.split();
  5603. // As a special case, tail-recurse if there are no qualifiers.
  5604. if (SplitOld.Quals.empty())
  5605. return wrap(C, SplitOld.Ty, I);
  5606. return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
  5607. }
  5608. QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
  5609. if (I == Stack.size()) return QualType(Fn, 0);
  5610. switch (static_cast<WrapKind>(Stack[I++])) {
  5611. case Desugar:
  5612. // This is the point at which we potentially lose source
  5613. // information.
  5614. return wrap(C, Old->getUnqualifiedDesugaredType(), I);
  5615. case Attributed:
  5616. return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
  5617. case Parens: {
  5618. QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
  5619. return C.getParenType(New);
  5620. }
  5621. case Pointer: {
  5622. QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
  5623. return C.getPointerType(New);
  5624. }
  5625. case BlockPointer: {
  5626. QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
  5627. return C.getBlockPointerType(New);
  5628. }
  5629. case MemberPointer: {
  5630. const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
  5631. QualType New = wrap(C, OldMPT->getPointeeType(), I);
  5632. return C.getMemberPointerType(New, OldMPT->getClass());
  5633. }
  5634. case Reference: {
  5635. const ReferenceType *OldRef = cast<ReferenceType>(Old);
  5636. QualType New = wrap(C, OldRef->getPointeeType(), I);
  5637. if (isa<LValueReferenceType>(OldRef))
  5638. return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
  5639. else
  5640. return C.getRValueReferenceType(New);
  5641. }
  5642. }
  5643. llvm_unreachable("unknown wrapping kind");
  5644. }
  5645. };
  5646. } // end anonymous namespace
  5647. static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
  5648. ParsedAttr &PAttr, QualType &Type) {
  5649. Sema &S = State.getSema();
  5650. Attr *A;
  5651. switch (PAttr.getKind()) {
  5652. default: llvm_unreachable("Unknown attribute kind");
  5653. case ParsedAttr::AT_Ptr32:
  5654. A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr);
  5655. break;
  5656. case ParsedAttr::AT_Ptr64:
  5657. A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr);
  5658. break;
  5659. case ParsedAttr::AT_SPtr:
  5660. A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
  5661. break;
  5662. case ParsedAttr::AT_UPtr:
  5663. A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
  5664. break;
  5665. }
  5666. attr::Kind NewAttrKind = A->getKind();
  5667. QualType Desugared = Type;
  5668. const AttributedType *AT = dyn_cast<AttributedType>(Type);
  5669. while (AT) {
  5670. attr::Kind CurAttrKind = AT->getAttrKind();
  5671. // You cannot specify duplicate type attributes, so if the attribute has
  5672. // already been applied, flag it.
  5673. if (NewAttrKind == CurAttrKind) {
  5674. S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact)
  5675. << PAttr.getName();
  5676. return true;
  5677. }
  5678. // You cannot have both __sptr and __uptr on the same type, nor can you
  5679. // have __ptr32 and __ptr64.
  5680. if ((CurAttrKind == attr::Ptr32 && NewAttrKind == attr::Ptr64) ||
  5681. (CurAttrKind == attr::Ptr64 && NewAttrKind == attr::Ptr32)) {
  5682. S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
  5683. << "'__ptr32'" << "'__ptr64'";
  5684. return true;
  5685. } else if ((CurAttrKind == attr::SPtr && NewAttrKind == attr::UPtr) ||
  5686. (CurAttrKind == attr::UPtr && NewAttrKind == attr::SPtr)) {
  5687. S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
  5688. << "'__sptr'" << "'__uptr'";
  5689. return true;
  5690. }
  5691. Desugared = AT->getEquivalentType();
  5692. AT = dyn_cast<AttributedType>(Desugared);
  5693. }
  5694. // Pointer type qualifiers can only operate on pointer types, but not
  5695. // pointer-to-member types.
  5696. //
  5697. // FIXME: Should we really be disallowing this attribute if there is any
  5698. // type sugar between it and the pointer (other than attributes)? Eg, this
  5699. // disallows the attribute on a parenthesized pointer.
  5700. // And if so, should we really allow *any* type attribute?
  5701. if (!isa<PointerType>(Desugared)) {
  5702. if (Type->isMemberPointerType())
  5703. S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
  5704. else
  5705. S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
  5706. return true;
  5707. }
  5708. Type = State.getAttributedType(A, Type, Type);
  5709. return false;
  5710. }
  5711. /// Map a nullability attribute kind to a nullability kind.
  5712. static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) {
  5713. switch (kind) {
  5714. case ParsedAttr::AT_TypeNonNull:
  5715. return NullabilityKind::NonNull;
  5716. case ParsedAttr::AT_TypeNullable:
  5717. return NullabilityKind::Nullable;
  5718. case ParsedAttr::AT_TypeNullUnspecified:
  5719. return NullabilityKind::Unspecified;
  5720. default:
  5721. llvm_unreachable("not a nullability attribute kind");
  5722. }
  5723. }
  5724. /// Applies a nullability type specifier to the given type, if possible.
  5725. ///
  5726. /// \param state The type processing state.
  5727. ///
  5728. /// \param type The type to which the nullability specifier will be
  5729. /// added. On success, this type will be updated appropriately.
  5730. ///
  5731. /// \param attr The attribute as written on the type.
  5732. ///
  5733. /// \param allowOnArrayType Whether to accept nullability specifiers on an
  5734. /// array type (e.g., because it will decay to a pointer).
  5735. ///
  5736. /// \returns true if a problem has been diagnosed, false on success.
  5737. static bool checkNullabilityTypeSpecifier(TypeProcessingState &state,
  5738. QualType &type,
  5739. ParsedAttr &attr,
  5740. bool allowOnArrayType) {
  5741. Sema &S = state.getSema();
  5742. NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind());
  5743. SourceLocation nullabilityLoc = attr.getLoc();
  5744. bool isContextSensitive = attr.isContextSensitiveKeywordAttribute();
  5745. recordNullabilitySeen(S, nullabilityLoc);
  5746. // Check for existing nullability attributes on the type.
  5747. QualType desugared = type;
  5748. while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
  5749. // Check whether there is already a null
  5750. if (auto existingNullability = attributed->getImmediateNullability()) {
  5751. // Duplicated nullability.
  5752. if (nullability == *existingNullability) {
  5753. S.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
  5754. << DiagNullabilityKind(nullability, isContextSensitive)
  5755. << FixItHint::CreateRemoval(nullabilityLoc);
  5756. break;
  5757. }
  5758. // Conflicting nullability.
  5759. S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
  5760. << DiagNullabilityKind(nullability, isContextSensitive)
  5761. << DiagNullabilityKind(*existingNullability, false);
  5762. return true;
  5763. }
  5764. desugared = attributed->getModifiedType();
  5765. }
  5766. // If there is already a different nullability specifier, complain.
  5767. // This (unlike the code above) looks through typedefs that might
  5768. // have nullability specifiers on them, which means we cannot
  5769. // provide a useful Fix-It.
  5770. if (auto existingNullability = desugared->getNullability(S.Context)) {
  5771. if (nullability != *existingNullability) {
  5772. S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
  5773. << DiagNullabilityKind(nullability, isContextSensitive)
  5774. << DiagNullabilityKind(*existingNullability, false);
  5775. // Try to find the typedef with the existing nullability specifier.
  5776. if (auto typedefType = desugared->getAs<TypedefType>()) {
  5777. TypedefNameDecl *typedefDecl = typedefType->getDecl();
  5778. QualType underlyingType = typedefDecl->getUnderlyingType();
  5779. if (auto typedefNullability
  5780. = AttributedType::stripOuterNullability(underlyingType)) {
  5781. if (*typedefNullability == *existingNullability) {
  5782. S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
  5783. << DiagNullabilityKind(*existingNullability, false);
  5784. }
  5785. }
  5786. }
  5787. return true;
  5788. }
  5789. }
  5790. // If this definitely isn't a pointer type, reject the specifier.
  5791. if (!desugared->canHaveNullability() &&
  5792. !(allowOnArrayType && desugared->isArrayType())) {
  5793. S.Diag(nullabilityLoc, diag::err_nullability_nonpointer)
  5794. << DiagNullabilityKind(nullability, isContextSensitive) << type;
  5795. return true;
  5796. }
  5797. // For the context-sensitive keywords/Objective-C property
  5798. // attributes, require that the type be a single-level pointer.
  5799. if (isContextSensitive) {
  5800. // Make sure that the pointee isn't itself a pointer type.
  5801. const Type *pointeeType;
  5802. if (desugared->isArrayType())
  5803. pointeeType = desugared->getArrayElementTypeNoTypeQual();
  5804. else
  5805. pointeeType = desugared->getPointeeType().getTypePtr();
  5806. if (pointeeType->isAnyPointerType() ||
  5807. pointeeType->isObjCObjectPointerType() ||
  5808. pointeeType->isMemberPointerType()) {
  5809. S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
  5810. << DiagNullabilityKind(nullability, true)
  5811. << type;
  5812. S.Diag(nullabilityLoc, diag::note_nullability_type_specifier)
  5813. << DiagNullabilityKind(nullability, false)
  5814. << type
  5815. << FixItHint::CreateReplacement(nullabilityLoc,
  5816. getNullabilitySpelling(nullability));
  5817. return true;
  5818. }
  5819. }
  5820. // Form the attributed type.
  5821. type = state.getAttributedType(
  5822. createNullabilityAttr(S.Context, attr, nullability), type, type);
  5823. return false;
  5824. }
  5825. /// Check the application of the Objective-C '__kindof' qualifier to
  5826. /// the given type.
  5827. static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
  5828. ParsedAttr &attr) {
  5829. Sema &S = state.getSema();
  5830. if (isa<ObjCTypeParamType>(type)) {
  5831. // Build the attributed type to record where __kindof occurred.
  5832. type = state.getAttributedType(
  5833. createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type);
  5834. return false;
  5835. }
  5836. // Find out if it's an Objective-C object or object pointer type;
  5837. const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
  5838. const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
  5839. : type->getAs<ObjCObjectType>();
  5840. // If not, we can't apply __kindof.
  5841. if (!objType) {
  5842. // FIXME: Handle dependent types that aren't yet object types.
  5843. S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
  5844. << type;
  5845. return true;
  5846. }
  5847. // Rebuild the "equivalent" type, which pushes __kindof down into
  5848. // the object type.
  5849. // There is no need to apply kindof on an unqualified id type.
  5850. QualType equivType = S.Context.getObjCObjectType(
  5851. objType->getBaseType(), objType->getTypeArgsAsWritten(),
  5852. objType->getProtocols(),
  5853. /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
  5854. // If we started with an object pointer type, rebuild it.
  5855. if (ptrType) {
  5856. equivType = S.Context.getObjCObjectPointerType(equivType);
  5857. if (auto nullability = type->getNullability(S.Context)) {
  5858. // We create a nullability attribute from the __kindof attribute.
  5859. // Make sure that will make sense.
  5860. assert(attr.getAttributeSpellingListIndex() == 0 &&
  5861. "multiple spellings for __kindof?");
  5862. Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
  5863. A->setImplicit(true);
  5864. equivType = state.getAttributedType(A, equivType, equivType);
  5865. }
  5866. }
  5867. // Build the attributed type to record where __kindof occurred.
  5868. type = state.getAttributedType(
  5869. createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType);
  5870. return false;
  5871. }
  5872. /// Distribute a nullability type attribute that cannot be applied to
  5873. /// the type specifier to a pointer, block pointer, or member pointer
  5874. /// declarator, complaining if necessary.
  5875. ///
  5876. /// \returns true if the nullability annotation was distributed, false
  5877. /// otherwise.
  5878. static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
  5879. QualType type, ParsedAttr &attr) {
  5880. Declarator &declarator = state.getDeclarator();
  5881. /// Attempt to move the attribute to the specified chunk.
  5882. auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
  5883. // If there is already a nullability attribute there, don't add
  5884. // one.
  5885. if (hasNullabilityAttr(chunk.getAttrs()))
  5886. return false;
  5887. // Complain about the nullability qualifier being in the wrong
  5888. // place.
  5889. enum {
  5890. PK_Pointer,
  5891. PK_BlockPointer,
  5892. PK_MemberPointer,
  5893. PK_FunctionPointer,
  5894. PK_MemberFunctionPointer,
  5895. } pointerKind
  5896. = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
  5897. : PK_Pointer)
  5898. : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
  5899. : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
  5900. auto diag = state.getSema().Diag(attr.getLoc(),
  5901. diag::warn_nullability_declspec)
  5902. << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
  5903. attr.isContextSensitiveKeywordAttribute())
  5904. << type
  5905. << static_cast<unsigned>(pointerKind);
  5906. // FIXME: MemberPointer chunks don't carry the location of the *.
  5907. if (chunk.Kind != DeclaratorChunk::MemberPointer) {
  5908. diag << FixItHint::CreateRemoval(attr.getLoc())
  5909. << FixItHint::CreateInsertion(
  5910. state.getSema().getPreprocessor()
  5911. .getLocForEndOfToken(chunk.Loc),
  5912. " " + attr.getName()->getName().str() + " ");
  5913. }
  5914. moveAttrFromListToList(attr, state.getCurrentAttributes(),
  5915. chunk.getAttrs());
  5916. return true;
  5917. };
  5918. // Move it to the outermost pointer, member pointer, or block
  5919. // pointer declarator.
  5920. for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
  5921. DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
  5922. switch (chunk.Kind) {
  5923. case DeclaratorChunk::Pointer:
  5924. case DeclaratorChunk::BlockPointer:
  5925. case DeclaratorChunk::MemberPointer:
  5926. return moveToChunk(chunk, false);
  5927. case DeclaratorChunk::Paren:
  5928. case DeclaratorChunk::Array:
  5929. continue;
  5930. case DeclaratorChunk::Function:
  5931. // Try to move past the return type to a function/block/member
  5932. // function pointer.
  5933. if (DeclaratorChunk *dest = maybeMovePastReturnType(
  5934. declarator, i,
  5935. /*onlyBlockPointers=*/false)) {
  5936. return moveToChunk(*dest, true);
  5937. }
  5938. return false;
  5939. // Don't walk through these.
  5940. case DeclaratorChunk::Reference:
  5941. case DeclaratorChunk::Pipe:
  5942. return false;
  5943. }
  5944. }
  5945. return false;
  5946. }
  5947. static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) {
  5948. assert(!Attr.isInvalid());
  5949. switch (Attr.getKind()) {
  5950. default:
  5951. llvm_unreachable("not a calling convention attribute");
  5952. case ParsedAttr::AT_CDecl:
  5953. return createSimpleAttr<CDeclAttr>(Ctx, Attr);
  5954. case ParsedAttr::AT_FastCall:
  5955. return createSimpleAttr<FastCallAttr>(Ctx, Attr);
  5956. case ParsedAttr::AT_StdCall:
  5957. return createSimpleAttr<StdCallAttr>(Ctx, Attr);
  5958. case ParsedAttr::AT_ThisCall:
  5959. return createSimpleAttr<ThisCallAttr>(Ctx, Attr);
  5960. case ParsedAttr::AT_RegCall:
  5961. return createSimpleAttr<RegCallAttr>(Ctx, Attr);
  5962. case ParsedAttr::AT_Pascal:
  5963. return createSimpleAttr<PascalAttr>(Ctx, Attr);
  5964. case ParsedAttr::AT_SwiftCall:
  5965. return createSimpleAttr<SwiftCallAttr>(Ctx, Attr);
  5966. case ParsedAttr::AT_VectorCall:
  5967. return createSimpleAttr<VectorCallAttr>(Ctx, Attr);
  5968. case ParsedAttr::AT_AArch64VectorPcs:
  5969. return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr);
  5970. case ParsedAttr::AT_Pcs: {
  5971. // The attribute may have had a fixit applied where we treated an
  5972. // identifier as a string literal. The contents of the string are valid,
  5973. // but the form may not be.
  5974. StringRef Str;
  5975. if (Attr.isArgExpr(0))
  5976. Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
  5977. else
  5978. Str = Attr.getArgAsIdent(0)->Ident->getName();
  5979. PcsAttr::PCSType Type;
  5980. if (!PcsAttr::ConvertStrToPCSType(Str, Type))
  5981. llvm_unreachable("already validated the attribute");
  5982. return ::new (Ctx) PcsAttr(Attr.getRange(), Ctx, Type,
  5983. Attr.getAttributeSpellingListIndex());
  5984. }
  5985. case ParsedAttr::AT_IntelOclBicc:
  5986. return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr);
  5987. case ParsedAttr::AT_MSABI:
  5988. return createSimpleAttr<MSABIAttr>(Ctx, Attr);
  5989. case ParsedAttr::AT_SysVABI:
  5990. return createSimpleAttr<SysVABIAttr>(Ctx, Attr);
  5991. case ParsedAttr::AT_PreserveMost:
  5992. return createSimpleAttr<PreserveMostAttr>(Ctx, Attr);
  5993. case ParsedAttr::AT_PreserveAll:
  5994. return createSimpleAttr<PreserveAllAttr>(Ctx, Attr);
  5995. }
  5996. llvm_unreachable("unexpected attribute kind!");
  5997. }
  5998. /// Process an individual function attribute. Returns true to
  5999. /// indicate that the attribute was handled, false if it wasn't.
  6000. static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
  6001. QualType &type) {
  6002. Sema &S = state.getSema();
  6003. FunctionTypeUnwrapper unwrapped(S, type);
  6004. if (attr.getKind() == ParsedAttr::AT_NoReturn) {
  6005. if (S.CheckAttrNoArgs(attr))
  6006. return true;
  6007. // Delay if this is not a function type.
  6008. if (!unwrapped.isFunctionType())
  6009. return false;
  6010. // Otherwise we can process right away.
  6011. FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
  6012. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  6013. return true;
  6014. }
  6015. // ns_returns_retained is not always a type attribute, but if we got
  6016. // here, we're treating it as one right now.
  6017. if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
  6018. if (attr.getNumArgs()) return true;
  6019. // Delay if this is not a function type.
  6020. if (!unwrapped.isFunctionType())
  6021. return false;
  6022. // Check whether the return type is reasonable.
  6023. if (S.checkNSReturnsRetainedReturnType(attr.getLoc(),
  6024. unwrapped.get()->getReturnType()))
  6025. return true;
  6026. // Only actually change the underlying type in ARC builds.
  6027. QualType origType = type;
  6028. if (state.getSema().getLangOpts().ObjCAutoRefCount) {
  6029. FunctionType::ExtInfo EI
  6030. = unwrapped.get()->getExtInfo().withProducesResult(true);
  6031. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  6032. }
  6033. type = state.getAttributedType(
  6034. createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr),
  6035. origType, type);
  6036. return true;
  6037. }
  6038. if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
  6039. if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
  6040. return true;
  6041. // Delay if this is not a function type.
  6042. if (!unwrapped.isFunctionType())
  6043. return false;
  6044. FunctionType::ExtInfo EI =
  6045. unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
  6046. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  6047. return true;
  6048. }
  6049. if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
  6050. if (!S.getLangOpts().CFProtectionBranch) {
  6051. S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
  6052. attr.setInvalid();
  6053. return true;
  6054. }
  6055. if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
  6056. return true;
  6057. // If this is not a function type, warning will be asserted by subject
  6058. // check.
  6059. if (!unwrapped.isFunctionType())
  6060. return true;
  6061. FunctionType::ExtInfo EI =
  6062. unwrapped.get()->getExtInfo().withNoCfCheck(true);
  6063. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  6064. return true;
  6065. }
  6066. if (attr.getKind() == ParsedAttr::AT_Regparm) {
  6067. unsigned value;
  6068. if (S.CheckRegparmAttr(attr, value))
  6069. return true;
  6070. // Delay if this is not a function type.
  6071. if (!unwrapped.isFunctionType())
  6072. return false;
  6073. // Diagnose regparm with fastcall.
  6074. const FunctionType *fn = unwrapped.get();
  6075. CallingConv CC = fn->getCallConv();
  6076. if (CC == CC_X86FastCall) {
  6077. S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
  6078. << FunctionType::getNameForCallConv(CC)
  6079. << "regparm";
  6080. attr.setInvalid();
  6081. return true;
  6082. }
  6083. FunctionType::ExtInfo EI =
  6084. unwrapped.get()->getExtInfo().withRegParm(value);
  6085. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  6086. return true;
  6087. }
  6088. // Delay if the type didn't work out to a function.
  6089. if (!unwrapped.isFunctionType()) return false;
  6090. // Otherwise, a calling convention.
  6091. CallingConv CC;
  6092. if (S.CheckCallingConvAttr(attr, CC))
  6093. return true;
  6094. const FunctionType *fn = unwrapped.get();
  6095. CallingConv CCOld = fn->getCallConv();
  6096. Attr *CCAttr = getCCTypeAttr(S.Context, attr);
  6097. if (CCOld != CC) {
  6098. // Error out on when there's already an attribute on the type
  6099. // and the CCs don't match.
  6100. if (S.getCallingConvAttributedType(type)) {
  6101. S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
  6102. << FunctionType::getNameForCallConv(CC)
  6103. << FunctionType::getNameForCallConv(CCOld);
  6104. attr.setInvalid();
  6105. return true;
  6106. }
  6107. }
  6108. // Diagnose use of variadic functions with calling conventions that
  6109. // don't support them (e.g. because they're callee-cleanup).
  6110. // We delay warning about this on unprototyped function declarations
  6111. // until after redeclaration checking, just in case we pick up a
  6112. // prototype that way. And apparently we also "delay" warning about
  6113. // unprototyped function types in general, despite not necessarily having
  6114. // much ability to diagnose it later.
  6115. if (!supportsVariadicCall(CC)) {
  6116. const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
  6117. if (FnP && FnP->isVariadic()) {
  6118. // stdcall and fastcall are ignored with a warning for GCC and MS
  6119. // compatibility.
  6120. if (CC == CC_X86StdCall || CC == CC_X86FastCall)
  6121. return S.Diag(attr.getLoc(), diag::warn_cconv_ignored)
  6122. << FunctionType::getNameForCallConv(CC)
  6123. << (int)Sema::CallingConventionIgnoredReason::VariadicFunction;
  6124. attr.setInvalid();
  6125. return S.Diag(attr.getLoc(), diag::err_cconv_varargs)
  6126. << FunctionType::getNameForCallConv(CC);
  6127. }
  6128. }
  6129. // Also diagnose fastcall with regparm.
  6130. if (CC == CC_X86FastCall && fn->getHasRegParm()) {
  6131. S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
  6132. << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
  6133. attr.setInvalid();
  6134. return true;
  6135. }
  6136. // Modify the CC from the wrapped function type, wrap it all back, and then
  6137. // wrap the whole thing in an AttributedType as written. The modified type
  6138. // might have a different CC if we ignored the attribute.
  6139. QualType Equivalent;
  6140. if (CCOld == CC) {
  6141. Equivalent = type;
  6142. } else {
  6143. auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
  6144. Equivalent =
  6145. unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  6146. }
  6147. type = state.getAttributedType(CCAttr, type, Equivalent);
  6148. return true;
  6149. }
  6150. bool Sema::hasExplicitCallingConv(QualType &T) {
  6151. QualType R = T.IgnoreParens();
  6152. while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
  6153. if (AT->isCallingConv())
  6154. return true;
  6155. R = AT->getModifiedType().IgnoreParens();
  6156. }
  6157. return false;
  6158. }
  6159. void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
  6160. SourceLocation Loc) {
  6161. FunctionTypeUnwrapper Unwrapped(*this, T);
  6162. const FunctionType *FT = Unwrapped.get();
  6163. bool IsVariadic = (isa<FunctionProtoType>(FT) &&
  6164. cast<FunctionProtoType>(FT)->isVariadic());
  6165. CallingConv CurCC = FT->getCallConv();
  6166. CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
  6167. if (CurCC == ToCC)
  6168. return;
  6169. // MS compiler ignores explicit calling convention attributes on structors. We
  6170. // should do the same.
  6171. if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
  6172. // Issue a warning on ignored calling convention -- except of __stdcall.
  6173. // Again, this is what MS compiler does.
  6174. if (CurCC != CC_X86StdCall)
  6175. Diag(Loc, diag::warn_cconv_ignored)
  6176. << FunctionType::getNameForCallConv(CurCC)
  6177. << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor;
  6178. // Default adjustment.
  6179. } else {
  6180. // Only adjust types with the default convention. For example, on Windows
  6181. // we should adjust a __cdecl type to __thiscall for instance methods, and a
  6182. // __thiscall type to __cdecl for static methods.
  6183. CallingConv DefaultCC =
  6184. Context.getDefaultCallingConvention(IsVariadic, IsStatic);
  6185. if (CurCC != DefaultCC || DefaultCC == ToCC)
  6186. return;
  6187. if (hasExplicitCallingConv(T))
  6188. return;
  6189. }
  6190. FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
  6191. QualType Wrapped = Unwrapped.wrap(*this, FT);
  6192. T = Context.getAdjustedType(T, Wrapped);
  6193. }
  6194. /// HandleVectorSizeAttribute - this attribute is only applicable to integral
  6195. /// and float scalars, although arrays, pointers, and function return values are
  6196. /// allowed in conjunction with this construct. Aggregates with this attribute
  6197. /// are invalid, even if they are of the same size as a corresponding scalar.
  6198. /// The raw attribute should contain precisely 1 argument, the vector size for
  6199. /// the variable, measured in bytes. If curType and rawAttr are well formed,
  6200. /// this routine will return a new vector type.
  6201. static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
  6202. Sema &S) {
  6203. // Check the attribute arguments.
  6204. if (Attr.getNumArgs() != 1) {
  6205. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
  6206. << 1;
  6207. Attr.setInvalid();
  6208. return;
  6209. }
  6210. Expr *SizeExpr;
  6211. // Special case where the argument is a template id.
  6212. if (Attr.isArgIdent(0)) {
  6213. CXXScopeSpec SS;
  6214. SourceLocation TemplateKWLoc;
  6215. UnqualifiedId Id;
  6216. Id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
  6217. ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
  6218. Id, /*HasTrailingLParen=*/false,
  6219. /*IsAddressOfOperand=*/false);
  6220. if (Size.isInvalid())
  6221. return;
  6222. SizeExpr = Size.get();
  6223. } else {
  6224. SizeExpr = Attr.getArgAsExpr(0);
  6225. }
  6226. QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
  6227. if (!T.isNull())
  6228. CurType = T;
  6229. else
  6230. Attr.setInvalid();
  6231. }
  6232. /// Process the OpenCL-like ext_vector_type attribute when it occurs on
  6233. /// a type.
  6234. static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
  6235. Sema &S) {
  6236. // check the attribute arguments.
  6237. if (Attr.getNumArgs() != 1) {
  6238. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
  6239. << 1;
  6240. return;
  6241. }
  6242. Expr *sizeExpr;
  6243. // Special case where the argument is a template id.
  6244. if (Attr.isArgIdent(0)) {
  6245. CXXScopeSpec SS;
  6246. SourceLocation TemplateKWLoc;
  6247. UnqualifiedId id;
  6248. id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
  6249. ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
  6250. id, /*HasTrailingLParen=*/false,
  6251. /*IsAddressOfOperand=*/false);
  6252. if (Size.isInvalid())
  6253. return;
  6254. sizeExpr = Size.get();
  6255. } else {
  6256. sizeExpr = Attr.getArgAsExpr(0);
  6257. }
  6258. // Create the vector type.
  6259. QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
  6260. if (!T.isNull())
  6261. CurType = T;
  6262. }
  6263. static bool isPermittedNeonBaseType(QualType &Ty,
  6264. VectorType::VectorKind VecKind, Sema &S) {
  6265. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  6266. if (!BTy)
  6267. return false;
  6268. llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
  6269. // Signed poly is mathematically wrong, but has been baked into some ABIs by
  6270. // now.
  6271. bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
  6272. Triple.getArch() == llvm::Triple::aarch64_be;
  6273. if (VecKind == VectorType::NeonPolyVector) {
  6274. if (IsPolyUnsigned) {
  6275. // AArch64 polynomial vectors are unsigned and support poly64.
  6276. return BTy->getKind() == BuiltinType::UChar ||
  6277. BTy->getKind() == BuiltinType::UShort ||
  6278. BTy->getKind() == BuiltinType::ULong ||
  6279. BTy->getKind() == BuiltinType::ULongLong;
  6280. } else {
  6281. // AArch32 polynomial vector are signed.
  6282. return BTy->getKind() == BuiltinType::SChar ||
  6283. BTy->getKind() == BuiltinType::Short;
  6284. }
  6285. }
  6286. // Non-polynomial vector types: the usual suspects are allowed, as well as
  6287. // float64_t on AArch64.
  6288. bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
  6289. Triple.getArch() == llvm::Triple::aarch64_be;
  6290. if (Is64Bit && BTy->getKind() == BuiltinType::Double)
  6291. return true;
  6292. return BTy->getKind() == BuiltinType::SChar ||
  6293. BTy->getKind() == BuiltinType::UChar ||
  6294. BTy->getKind() == BuiltinType::Short ||
  6295. BTy->getKind() == BuiltinType::UShort ||
  6296. BTy->getKind() == BuiltinType::Int ||
  6297. BTy->getKind() == BuiltinType::UInt ||
  6298. BTy->getKind() == BuiltinType::Long ||
  6299. BTy->getKind() == BuiltinType::ULong ||
  6300. BTy->getKind() == BuiltinType::LongLong ||
  6301. BTy->getKind() == BuiltinType::ULongLong ||
  6302. BTy->getKind() == BuiltinType::Float ||
  6303. BTy->getKind() == BuiltinType::Half;
  6304. }
  6305. /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
  6306. /// "neon_polyvector_type" attributes are used to create vector types that
  6307. /// are mangled according to ARM's ABI. Otherwise, these types are identical
  6308. /// to those created with the "vector_size" attribute. Unlike "vector_size"
  6309. /// the argument to these Neon attributes is the number of vector elements,
  6310. /// not the vector size in bytes. The vector width and element type must
  6311. /// match one of the standard Neon vector types.
  6312. static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
  6313. Sema &S, VectorType::VectorKind VecKind) {
  6314. // Target must have NEON
  6315. if (!S.Context.getTargetInfo().hasFeature("neon")) {
  6316. S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr;
  6317. Attr.setInvalid();
  6318. return;
  6319. }
  6320. // Check the attribute arguments.
  6321. if (Attr.getNumArgs() != 1) {
  6322. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
  6323. << 1;
  6324. Attr.setInvalid();
  6325. return;
  6326. }
  6327. // The number of elements must be an ICE.
  6328. Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
  6329. llvm::APSInt numEltsInt(32);
  6330. if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
  6331. !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
  6332. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
  6333. << Attr << AANT_ArgumentIntegerConstant
  6334. << numEltsExpr->getSourceRange();
  6335. Attr.setInvalid();
  6336. return;
  6337. }
  6338. // Only certain element types are supported for Neon vectors.
  6339. if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
  6340. S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
  6341. Attr.setInvalid();
  6342. return;
  6343. }
  6344. // The total size of the vector must be 64 or 128 bits.
  6345. unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
  6346. unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
  6347. unsigned vecSize = typeSize * numElts;
  6348. if (vecSize != 64 && vecSize != 128) {
  6349. S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
  6350. Attr.setInvalid();
  6351. return;
  6352. }
  6353. CurType = S.Context.getVectorType(CurType, numElts, VecKind);
  6354. }
  6355. /// Handle OpenCL Access Qualifier Attribute.
  6356. static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
  6357. Sema &S) {
  6358. // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
  6359. if (!(CurType->isImageType() || CurType->isPipeType())) {
  6360. S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
  6361. Attr.setInvalid();
  6362. return;
  6363. }
  6364. if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
  6365. QualType BaseTy = TypedefTy->desugar();
  6366. std::string PrevAccessQual;
  6367. if (BaseTy->isPipeType()) {
  6368. if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
  6369. OpenCLAccessAttr *Attr =
  6370. TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
  6371. PrevAccessQual = Attr->getSpelling();
  6372. } else {
  6373. PrevAccessQual = "read_only";
  6374. }
  6375. } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
  6376. switch (ImgType->getKind()) {
  6377. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  6378. case BuiltinType::Id: \
  6379. PrevAccessQual = #Access; \
  6380. break;
  6381. #include "clang/Basic/OpenCLImageTypes.def"
  6382. default:
  6383. llvm_unreachable("Unable to find corresponding image type.");
  6384. }
  6385. } else {
  6386. llvm_unreachable("unexpected type");
  6387. }
  6388. StringRef AttrName = Attr.getName()->getName();
  6389. if (PrevAccessQual == AttrName.ltrim("_")) {
  6390. // Duplicated qualifiers
  6391. S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
  6392. << AttrName << Attr.getRange();
  6393. } else {
  6394. // Contradicting qualifiers
  6395. S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
  6396. }
  6397. S.Diag(TypedefTy->getDecl()->getBeginLoc(),
  6398. diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
  6399. } else if (CurType->isPipeType()) {
  6400. if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
  6401. QualType ElemType = CurType->getAs<PipeType>()->getElementType();
  6402. CurType = S.Context.getWritePipeType(ElemType);
  6403. }
  6404. }
  6405. }
  6406. static void deduceOpenCLImplicitAddrSpace(TypeProcessingState &State,
  6407. QualType &T, TypeAttrLocation TAL) {
  6408. Declarator &D = State.getDeclarator();
  6409. // Handle the cases where address space should not be deduced.
  6410. //
  6411. // The pointee type of a pointer type is always deduced since a pointer always
  6412. // points to some memory location which should has an address space.
  6413. //
  6414. // There are situations that at the point of certain declarations, the address
  6415. // space may be unknown and better to be left as default. For example, when
  6416. // defining a typedef or struct type, they are not associated with any
  6417. // specific address space. Later on, they may be used with any address space
  6418. // to declare a variable.
  6419. //
  6420. // The return value of a function is r-value, therefore should not have
  6421. // address space.
  6422. //
  6423. // The void type does not occupy memory, therefore should not have address
  6424. // space, except when it is used as a pointee type.
  6425. //
  6426. // Since LLVM assumes function type is in default address space, it should not
  6427. // have address space.
  6428. auto ChunkIndex = State.getCurrentChunkIndex();
  6429. bool IsPointee =
  6430. ChunkIndex > 0 &&
  6431. (D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Pointer ||
  6432. D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::BlockPointer ||
  6433. D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Reference);
  6434. bool IsFuncReturnType =
  6435. ChunkIndex > 0 &&
  6436. D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Function;
  6437. bool IsFuncType =
  6438. ChunkIndex < D.getNumTypeObjects() &&
  6439. D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function;
  6440. if ( // Do not deduce addr space for function return type and function type,
  6441. // otherwise it will fail some sema check.
  6442. IsFuncReturnType || IsFuncType ||
  6443. // Do not deduce addr space for member types of struct, except the pointee
  6444. // type of a pointer member type.
  6445. (D.getContext() == DeclaratorContext::MemberContext && !IsPointee) ||
  6446. // Do not deduce addr space for types used to define a typedef and the
  6447. // typedef itself, except the pointee type of a pointer type which is used
  6448. // to define the typedef.
  6449. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef &&
  6450. !IsPointee) ||
  6451. // Do not deduce addr space of the void type, e.g. in f(void), otherwise
  6452. // it will fail some sema check.
  6453. (T->isVoidType() && !IsPointee) ||
  6454. // Do not deduce addr spaces for dependent types because they might end
  6455. // up instantiating to a type with an explicit address space qualifier.
  6456. T->isDependentType() ||
  6457. // Do not deduce addr space of decltype because it will be taken from
  6458. // its argument.
  6459. T->isDecltypeType())
  6460. return;
  6461. LangAS ImpAddr = LangAS::Default;
  6462. // Put OpenCL automatic variable in private address space.
  6463. // OpenCL v1.2 s6.5:
  6464. // The default address space name for arguments to a function in a
  6465. // program, or local variables of a function is __private. All function
  6466. // arguments shall be in the __private address space.
  6467. if (State.getSema().getLangOpts().OpenCLVersion <= 120 &&
  6468. !State.getSema().getLangOpts().OpenCLCPlusPlus) {
  6469. ImpAddr = LangAS::opencl_private;
  6470. } else {
  6471. // If address space is not set, OpenCL 2.0 defines non private default
  6472. // address spaces for some cases:
  6473. // OpenCL 2.0, section 6.5:
  6474. // The address space for a variable at program scope or a static variable
  6475. // inside a function can either be __global or __constant, but defaults to
  6476. // __global if not specified.
  6477. // (...)
  6478. // Pointers that are declared without pointing to a named address space
  6479. // point to the generic address space.
  6480. if (IsPointee) {
  6481. ImpAddr = LangAS::opencl_generic;
  6482. } else {
  6483. if (D.getContext() == DeclaratorContext::TemplateArgContext) {
  6484. // Do not deduce address space for non-pointee type in template arg.
  6485. } else if (D.getContext() == DeclaratorContext::FileContext) {
  6486. ImpAddr = LangAS::opencl_global;
  6487. } else {
  6488. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
  6489. D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) {
  6490. ImpAddr = LangAS::opencl_global;
  6491. } else {
  6492. ImpAddr = LangAS::opencl_private;
  6493. }
  6494. }
  6495. }
  6496. }
  6497. T = State.getSema().Context.getAddrSpaceQualType(T, ImpAddr);
  6498. }
  6499. static void HandleLifetimeBoundAttr(TypeProcessingState &State,
  6500. QualType &CurType,
  6501. ParsedAttr &Attr) {
  6502. if (State.getDeclarator().isDeclarationOfFunction()) {
  6503. CurType = State.getAttributedType(
  6504. createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
  6505. CurType, CurType);
  6506. } else {
  6507. Attr.diagnoseAppertainsTo(State.getSema(), nullptr);
  6508. }
  6509. }
  6510. static void processTypeAttrs(TypeProcessingState &state, QualType &type,
  6511. TypeAttrLocation TAL,
  6512. ParsedAttributesView &attrs) {
  6513. // Scan through and apply attributes to this type where it makes sense. Some
  6514. // attributes (such as __address_space__, __vector_size__, etc) apply to the
  6515. // type, but others can be present in the type specifiers even though they
  6516. // apply to the decl. Here we apply type attributes and ignore the rest.
  6517. // This loop modifies the list pretty frequently, but we still need to make
  6518. // sure we visit every element once. Copy the attributes list, and iterate
  6519. // over that.
  6520. ParsedAttributesView AttrsCopy{attrs};
  6521. state.setParsedNoDeref(false);
  6522. for (ParsedAttr &attr : AttrsCopy) {
  6523. // Skip attributes that were marked to be invalid.
  6524. if (attr.isInvalid())
  6525. continue;
  6526. if (attr.isCXX11Attribute()) {
  6527. // [[gnu::...]] attributes are treated as declaration attributes, so may
  6528. // not appertain to a DeclaratorChunk. If we handle them as type
  6529. // attributes, accept them in that position and diagnose the GCC
  6530. // incompatibility.
  6531. if (attr.isGNUScope()) {
  6532. bool IsTypeAttr = attr.isTypeAttr();
  6533. if (TAL == TAL_DeclChunk) {
  6534. state.getSema().Diag(attr.getLoc(),
  6535. IsTypeAttr
  6536. ? diag::warn_gcc_ignores_type_attr
  6537. : diag::warn_cxx11_gnu_attribute_on_type)
  6538. << attr.getName();
  6539. if (!IsTypeAttr)
  6540. continue;
  6541. }
  6542. } else if (TAL != TAL_DeclChunk &&
  6543. attr.getKind() != ParsedAttr::AT_AddressSpace) {
  6544. // Otherwise, only consider type processing for a C++11 attribute if
  6545. // it's actually been applied to a type.
  6546. // We also allow C++11 address_space attributes to pass through.
  6547. continue;
  6548. }
  6549. }
  6550. // If this is an attribute we can handle, do so now,
  6551. // otherwise, add it to the FnAttrs list for rechaining.
  6552. switch (attr.getKind()) {
  6553. default:
  6554. // A C++11 attribute on a declarator chunk must appertain to a type.
  6555. if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
  6556. state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
  6557. << attr;
  6558. attr.setUsedAsTypeAttr();
  6559. }
  6560. break;
  6561. case ParsedAttr::UnknownAttribute:
  6562. if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
  6563. state.getSema().Diag(attr.getLoc(),
  6564. diag::warn_unknown_attribute_ignored)
  6565. << attr.getName();
  6566. break;
  6567. case ParsedAttr::IgnoredAttribute:
  6568. break;
  6569. case ParsedAttr::AT_MayAlias:
  6570. // FIXME: This attribute needs to actually be handled, but if we ignore
  6571. // it it breaks large amounts of Linux software.
  6572. attr.setUsedAsTypeAttr();
  6573. break;
  6574. case ParsedAttr::AT_OpenCLPrivateAddressSpace:
  6575. case ParsedAttr::AT_OpenCLGlobalAddressSpace:
  6576. case ParsedAttr::AT_OpenCLLocalAddressSpace:
  6577. case ParsedAttr::AT_OpenCLConstantAddressSpace:
  6578. case ParsedAttr::AT_OpenCLGenericAddressSpace:
  6579. case ParsedAttr::AT_AddressSpace:
  6580. HandleAddressSpaceTypeAttribute(type, attr, state);
  6581. attr.setUsedAsTypeAttr();
  6582. break;
  6583. OBJC_POINTER_TYPE_ATTRS_CASELIST:
  6584. if (!handleObjCPointerTypeAttr(state, attr, type))
  6585. distributeObjCPointerTypeAttr(state, attr, type);
  6586. attr.setUsedAsTypeAttr();
  6587. break;
  6588. case ParsedAttr::AT_VectorSize:
  6589. HandleVectorSizeAttr(type, attr, state.getSema());
  6590. attr.setUsedAsTypeAttr();
  6591. break;
  6592. case ParsedAttr::AT_ExtVectorType:
  6593. HandleExtVectorTypeAttr(type, attr, state.getSema());
  6594. attr.setUsedAsTypeAttr();
  6595. break;
  6596. case ParsedAttr::AT_NeonVectorType:
  6597. HandleNeonVectorTypeAttr(type, attr, state.getSema(),
  6598. VectorType::NeonVector);
  6599. attr.setUsedAsTypeAttr();
  6600. break;
  6601. case ParsedAttr::AT_NeonPolyVectorType:
  6602. HandleNeonVectorTypeAttr(type, attr, state.getSema(),
  6603. VectorType::NeonPolyVector);
  6604. attr.setUsedAsTypeAttr();
  6605. break;
  6606. case ParsedAttr::AT_OpenCLAccess:
  6607. HandleOpenCLAccessAttr(type, attr, state.getSema());
  6608. attr.setUsedAsTypeAttr();
  6609. break;
  6610. case ParsedAttr::AT_LifetimeBound:
  6611. if (TAL == TAL_DeclChunk)
  6612. HandleLifetimeBoundAttr(state, type, attr);
  6613. break;
  6614. case ParsedAttr::AT_NoDeref: {
  6615. ASTContext &Ctx = state.getSema().Context;
  6616. type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
  6617. type, type);
  6618. attr.setUsedAsTypeAttr();
  6619. state.setParsedNoDeref(true);
  6620. break;
  6621. }
  6622. MS_TYPE_ATTRS_CASELIST:
  6623. if (!handleMSPointerTypeQualifierAttr(state, attr, type))
  6624. attr.setUsedAsTypeAttr();
  6625. break;
  6626. NULLABILITY_TYPE_ATTRS_CASELIST:
  6627. // Either add nullability here or try to distribute it. We
  6628. // don't want to distribute the nullability specifier past any
  6629. // dependent type, because that complicates the user model.
  6630. if (type->canHaveNullability() || type->isDependentType() ||
  6631. type->isArrayType() ||
  6632. !distributeNullabilityTypeAttr(state, type, attr)) {
  6633. unsigned endIndex;
  6634. if (TAL == TAL_DeclChunk)
  6635. endIndex = state.getCurrentChunkIndex();
  6636. else
  6637. endIndex = state.getDeclarator().getNumTypeObjects();
  6638. bool allowOnArrayType =
  6639. state.getDeclarator().isPrototypeContext() &&
  6640. !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
  6641. if (checkNullabilityTypeSpecifier(
  6642. state,
  6643. type,
  6644. attr,
  6645. allowOnArrayType)) {
  6646. attr.setInvalid();
  6647. }
  6648. attr.setUsedAsTypeAttr();
  6649. }
  6650. break;
  6651. case ParsedAttr::AT_ObjCKindOf:
  6652. // '__kindof' must be part of the decl-specifiers.
  6653. switch (TAL) {
  6654. case TAL_DeclSpec:
  6655. break;
  6656. case TAL_DeclChunk:
  6657. case TAL_DeclName:
  6658. state.getSema().Diag(attr.getLoc(),
  6659. diag::err_objc_kindof_wrong_position)
  6660. << FixItHint::CreateRemoval(attr.getLoc())
  6661. << FixItHint::CreateInsertion(
  6662. state.getDeclarator().getDeclSpec().getBeginLoc(),
  6663. "__kindof ");
  6664. break;
  6665. }
  6666. // Apply it regardless.
  6667. if (checkObjCKindOfType(state, type, attr))
  6668. attr.setInvalid();
  6669. break;
  6670. FUNCTION_TYPE_ATTRS_CASELIST:
  6671. attr.setUsedAsTypeAttr();
  6672. // Never process function type attributes as part of the
  6673. // declaration-specifiers.
  6674. if (TAL == TAL_DeclSpec)
  6675. distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
  6676. // Otherwise, handle the possible delays.
  6677. else if (!handleFunctionTypeAttr(state, attr, type))
  6678. distributeFunctionTypeAttr(state, attr, type);
  6679. break;
  6680. }
  6681. }
  6682. if (!state.getSema().getLangOpts().OpenCL ||
  6683. type.getAddressSpace() != LangAS::Default)
  6684. return;
  6685. deduceOpenCLImplicitAddrSpace(state, type, TAL);
  6686. }
  6687. void Sema::completeExprArrayBound(Expr *E) {
  6688. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  6689. if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
  6690. if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
  6691. auto *Def = Var->getDefinition();
  6692. if (!Def) {
  6693. SourceLocation PointOfInstantiation = E->getExprLoc();
  6694. InstantiateVariableDefinition(PointOfInstantiation, Var);
  6695. Def = Var->getDefinition();
  6696. // If we don't already have a point of instantiation, and we managed
  6697. // to instantiate a definition, this is the point of instantiation.
  6698. // Otherwise, we don't request an end-of-TU instantiation, so this is
  6699. // not a point of instantiation.
  6700. // FIXME: Is this really the right behavior?
  6701. if (Var->getPointOfInstantiation().isInvalid() && Def) {
  6702. assert(Var->getTemplateSpecializationKind() ==
  6703. TSK_ImplicitInstantiation &&
  6704. "explicit instantiation with no point of instantiation");
  6705. Var->setTemplateSpecializationKind(
  6706. Var->getTemplateSpecializationKind(), PointOfInstantiation);
  6707. }
  6708. }
  6709. // Update the type to the definition's type both here and within the
  6710. // expression.
  6711. if (Def) {
  6712. DRE->setDecl(Def);
  6713. QualType T = Def->getType();
  6714. DRE->setType(T);
  6715. // FIXME: Update the type on all intervening expressions.
  6716. E->setType(T);
  6717. }
  6718. // We still go on to try to complete the type independently, as it
  6719. // may also require instantiations or diagnostics if it remains
  6720. // incomplete.
  6721. }
  6722. }
  6723. }
  6724. }
  6725. /// Ensure that the type of the given expression is complete.
  6726. ///
  6727. /// This routine checks whether the expression \p E has a complete type. If the
  6728. /// expression refers to an instantiable construct, that instantiation is
  6729. /// performed as needed to complete its type. Furthermore
  6730. /// Sema::RequireCompleteType is called for the expression's type (or in the
  6731. /// case of a reference type, the referred-to type).
  6732. ///
  6733. /// \param E The expression whose type is required to be complete.
  6734. /// \param Diagnoser The object that will emit a diagnostic if the type is
  6735. /// incomplete.
  6736. ///
  6737. /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
  6738. /// otherwise.
  6739. bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) {
  6740. QualType T = E->getType();
  6741. // Incomplete array types may be completed by the initializer attached to
  6742. // their definitions. For static data members of class templates and for
  6743. // variable templates, we need to instantiate the definition to get this
  6744. // initializer and complete the type.
  6745. if (T->isIncompleteArrayType()) {
  6746. completeExprArrayBound(E);
  6747. T = E->getType();
  6748. }
  6749. // FIXME: Are there other cases which require instantiating something other
  6750. // than the type to complete the type of an expression?
  6751. return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
  6752. }
  6753. bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
  6754. BoundTypeDiagnoser<> Diagnoser(DiagID);
  6755. return RequireCompleteExprType(E, Diagnoser);
  6756. }
  6757. /// Ensure that the type T is a complete type.
  6758. ///
  6759. /// This routine checks whether the type @p T is complete in any
  6760. /// context where a complete type is required. If @p T is a complete
  6761. /// type, returns false. If @p T is a class template specialization,
  6762. /// this routine then attempts to perform class template
  6763. /// instantiation. If instantiation fails, or if @p T is incomplete
  6764. /// and cannot be completed, issues the diagnostic @p diag (giving it
  6765. /// the type @p T) and returns true.
  6766. ///
  6767. /// @param Loc The location in the source that the incomplete type
  6768. /// diagnostic should refer to.
  6769. ///
  6770. /// @param T The type that this routine is examining for completeness.
  6771. ///
  6772. /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
  6773. /// @c false otherwise.
  6774. bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
  6775. TypeDiagnoser &Diagnoser) {
  6776. if (RequireCompleteTypeImpl(Loc, T, &Diagnoser))
  6777. return true;
  6778. if (const TagType *Tag = T->getAs<TagType>()) {
  6779. if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
  6780. Tag->getDecl()->setCompleteDefinitionRequired();
  6781. Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
  6782. }
  6783. }
  6784. return false;
  6785. }
  6786. bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) {
  6787. llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
  6788. if (!Suggested)
  6789. return false;
  6790. // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
  6791. // and isolate from other C++ specific checks.
  6792. StructuralEquivalenceContext Ctx(
  6793. D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls,
  6794. StructuralEquivalenceKind::Default,
  6795. false /*StrictTypeSpelling*/, true /*Complain*/,
  6796. true /*ErrorOnTagTypeMismatch*/);
  6797. return Ctx.IsEquivalent(D, Suggested);
  6798. }
  6799. /// Determine whether there is any declaration of \p D that was ever a
  6800. /// definition (perhaps before module merging) and is currently visible.
  6801. /// \param D The definition of the entity.
  6802. /// \param Suggested Filled in with the declaration that should be made visible
  6803. /// in order to provide a definition of this entity.
  6804. /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
  6805. /// not defined. This only matters for enums with a fixed underlying
  6806. /// type, since in all other cases, a type is complete if and only if it
  6807. /// is defined.
  6808. bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
  6809. bool OnlyNeedComplete) {
  6810. // Easy case: if we don't have modules, all declarations are visible.
  6811. if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
  6812. return true;
  6813. // If this definition was instantiated from a template, map back to the
  6814. // pattern from which it was instantiated.
  6815. if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
  6816. // We're in the middle of defining it; this definition should be treated
  6817. // as visible.
  6818. return true;
  6819. } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  6820. if (auto *Pattern = RD->getTemplateInstantiationPattern())
  6821. RD = Pattern;
  6822. D = RD->getDefinition();
  6823. } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
  6824. if (auto *Pattern = ED->getTemplateInstantiationPattern())
  6825. ED = Pattern;
  6826. if (OnlyNeedComplete && ED->isFixed()) {
  6827. // If the enum has a fixed underlying type, and we're only looking for a
  6828. // complete type (not a definition), any visible declaration of it will
  6829. // do.
  6830. *Suggested = nullptr;
  6831. for (auto *Redecl : ED->redecls()) {
  6832. if (isVisible(Redecl))
  6833. return true;
  6834. if (Redecl->isThisDeclarationADefinition() ||
  6835. (Redecl->isCanonicalDecl() && !*Suggested))
  6836. *Suggested = Redecl;
  6837. }
  6838. return false;
  6839. }
  6840. D = ED->getDefinition();
  6841. } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  6842. if (auto *Pattern = FD->getTemplateInstantiationPattern())
  6843. FD = Pattern;
  6844. D = FD->getDefinition();
  6845. } else if (auto *VD = dyn_cast<VarDecl>(D)) {
  6846. if (auto *Pattern = VD->getTemplateInstantiationPattern())
  6847. VD = Pattern;
  6848. D = VD->getDefinition();
  6849. }
  6850. assert(D && "missing definition for pattern of instantiated definition");
  6851. *Suggested = D;
  6852. auto DefinitionIsVisible = [&] {
  6853. // The (primary) definition might be in a visible module.
  6854. if (isVisible(D))
  6855. return true;
  6856. // A visible module might have a merged definition instead.
  6857. if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D)
  6858. : hasVisibleMergedDefinition(D)) {
  6859. if (CodeSynthesisContexts.empty() &&
  6860. !getLangOpts().ModulesLocalVisibility) {
  6861. // Cache the fact that this definition is implicitly visible because
  6862. // there is a visible merged definition.
  6863. D->setVisibleDespiteOwningModule();
  6864. }
  6865. return true;
  6866. }
  6867. return false;
  6868. };
  6869. if (DefinitionIsVisible())
  6870. return true;
  6871. // The external source may have additional definitions of this entity that are
  6872. // visible, so complete the redeclaration chain now and ask again.
  6873. if (auto *Source = Context.getExternalSource()) {
  6874. Source->CompleteRedeclChain(D);
  6875. return DefinitionIsVisible();
  6876. }
  6877. return false;
  6878. }
  6879. /// Locks in the inheritance model for the given class and all of its bases.
  6880. static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
  6881. RD = RD->getMostRecentNonInjectedDecl();
  6882. if (!RD->hasAttr<MSInheritanceAttr>()) {
  6883. MSInheritanceAttr::Spelling IM;
  6884. switch (S.MSPointerToMemberRepresentationMethod) {
  6885. case LangOptions::PPTMK_BestCase:
  6886. IM = RD->calculateInheritanceModel();
  6887. break;
  6888. case LangOptions::PPTMK_FullGeneralitySingleInheritance:
  6889. IM = MSInheritanceAttr::Keyword_single_inheritance;
  6890. break;
  6891. case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
  6892. IM = MSInheritanceAttr::Keyword_multiple_inheritance;
  6893. break;
  6894. case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
  6895. IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
  6896. break;
  6897. }
  6898. RD->addAttr(MSInheritanceAttr::CreateImplicit(
  6899. S.getASTContext(), IM,
  6900. /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
  6901. LangOptions::PPTMK_BestCase,
  6902. S.ImplicitMSInheritanceAttrLoc.isValid()
  6903. ? S.ImplicitMSInheritanceAttrLoc
  6904. : RD->getSourceRange()));
  6905. S.Consumer.AssignInheritanceModel(RD);
  6906. }
  6907. }
  6908. /// The implementation of RequireCompleteType
  6909. bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
  6910. TypeDiagnoser *Diagnoser) {
  6911. // FIXME: Add this assertion to make sure we always get instantiation points.
  6912. // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
  6913. // FIXME: Add this assertion to help us flush out problems with
  6914. // checking for dependent types and type-dependent expressions.
  6915. //
  6916. // assert(!T->isDependentType() &&
  6917. // "Can't ask whether a dependent type is complete");
  6918. if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
  6919. if (!MPTy->getClass()->isDependentType()) {
  6920. if (getLangOpts().CompleteMemberPointers &&
  6921. !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() &&
  6922. RequireCompleteType(Loc, QualType(MPTy->getClass(), 0),
  6923. diag::err_memptr_incomplete))
  6924. return true;
  6925. // We lock in the inheritance model once somebody has asked us to ensure
  6926. // that a pointer-to-member type is complete.
  6927. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  6928. (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
  6929. assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
  6930. }
  6931. }
  6932. }
  6933. NamedDecl *Def = nullptr;
  6934. bool Incomplete = T->isIncompleteType(&Def);
  6935. // Check that any necessary explicit specializations are visible. For an
  6936. // enum, we just need the declaration, so don't check this.
  6937. if (Def && !isa<EnumDecl>(Def))
  6938. checkSpecializationVisibility(Loc, Def);
  6939. // If we have a complete type, we're done.
  6940. if (!Incomplete) {
  6941. // If we know about the definition but it is not visible, complain.
  6942. NamedDecl *SuggestedDef = nullptr;
  6943. if (Def &&
  6944. !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
  6945. // If the user is going to see an error here, recover by making the
  6946. // definition visible.
  6947. bool TreatAsComplete = Diagnoser && !isSFINAEContext();
  6948. if (Diagnoser && SuggestedDef)
  6949. diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition,
  6950. /*Recover*/TreatAsComplete);
  6951. return !TreatAsComplete;
  6952. } else if (Def && !TemplateInstCallbacks.empty()) {
  6953. CodeSynthesisContext TempInst;
  6954. TempInst.Kind = CodeSynthesisContext::Memoization;
  6955. TempInst.Template = Def;
  6956. TempInst.Entity = Def;
  6957. TempInst.PointOfInstantiation = Loc;
  6958. atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
  6959. atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
  6960. }
  6961. return false;
  6962. }
  6963. TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
  6964. ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
  6965. // Give the external source a chance to provide a definition of the type.
  6966. // This is kept separate from completing the redeclaration chain so that
  6967. // external sources such as LLDB can avoid synthesizing a type definition
  6968. // unless it's actually needed.
  6969. if (Tag || IFace) {
  6970. // Avoid diagnosing invalid decls as incomplete.
  6971. if (Def->isInvalidDecl())
  6972. return true;
  6973. // Give the external AST source a chance to complete the type.
  6974. if (auto *Source = Context.getExternalSource()) {
  6975. if (Tag && Tag->hasExternalLexicalStorage())
  6976. Source->CompleteType(Tag);
  6977. if (IFace && IFace->hasExternalLexicalStorage())
  6978. Source->CompleteType(IFace);
  6979. // If the external source completed the type, go through the motions
  6980. // again to ensure we're allowed to use the completed type.
  6981. if (!T->isIncompleteType())
  6982. return RequireCompleteTypeImpl(Loc, T, Diagnoser);
  6983. }
  6984. }
  6985. // If we have a class template specialization or a class member of a
  6986. // class template specialization, or an array with known size of such,
  6987. // try to instantiate it.
  6988. if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
  6989. bool Instantiated = false;
  6990. bool Diagnosed = false;
  6991. if (RD->isDependentContext()) {
  6992. // Don't try to instantiate a dependent class (eg, a member template of
  6993. // an instantiated class template specialization).
  6994. // FIXME: Can this ever happen?
  6995. } else if (auto *ClassTemplateSpec =
  6996. dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
  6997. if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
  6998. Diagnosed = InstantiateClassTemplateSpecialization(
  6999. Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
  7000. /*Complain=*/Diagnoser);
  7001. Instantiated = true;
  7002. }
  7003. } else {
  7004. CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
  7005. if (!RD->isBeingDefined() && Pattern) {
  7006. MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
  7007. assert(MSI && "Missing member specialization information?");
  7008. // This record was instantiated from a class within a template.
  7009. if (MSI->getTemplateSpecializationKind() !=
  7010. TSK_ExplicitSpecialization) {
  7011. Diagnosed = InstantiateClass(Loc, RD, Pattern,
  7012. getTemplateInstantiationArgs(RD),
  7013. TSK_ImplicitInstantiation,
  7014. /*Complain=*/Diagnoser);
  7015. Instantiated = true;
  7016. }
  7017. }
  7018. }
  7019. if (Instantiated) {
  7020. // Instantiate* might have already complained that the template is not
  7021. // defined, if we asked it to.
  7022. if (Diagnoser && Diagnosed)
  7023. return true;
  7024. // If we instantiated a definition, check that it's usable, even if
  7025. // instantiation produced an error, so that repeated calls to this
  7026. // function give consistent answers.
  7027. if (!T->isIncompleteType())
  7028. return RequireCompleteTypeImpl(Loc, T, Diagnoser);
  7029. }
  7030. }
  7031. // FIXME: If we didn't instantiate a definition because of an explicit
  7032. // specialization declaration, check that it's visible.
  7033. if (!Diagnoser)
  7034. return true;
  7035. Diagnoser->diagnose(*this, Loc, T);
  7036. // If the type was a forward declaration of a class/struct/union
  7037. // type, produce a note.
  7038. if (Tag && !Tag->isInvalidDecl())
  7039. Diag(Tag->getLocation(),
  7040. Tag->isBeingDefined() ? diag::note_type_being_defined
  7041. : diag::note_forward_declaration)
  7042. << Context.getTagDeclType(Tag);
  7043. // If the Objective-C class was a forward declaration, produce a note.
  7044. if (IFace && !IFace->isInvalidDecl())
  7045. Diag(IFace->getLocation(), diag::note_forward_class);
  7046. // If we have external information that we can use to suggest a fix,
  7047. // produce a note.
  7048. if (ExternalSource)
  7049. ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
  7050. return true;
  7051. }
  7052. bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
  7053. unsigned DiagID) {
  7054. BoundTypeDiagnoser<> Diagnoser(DiagID);
  7055. return RequireCompleteType(Loc, T, Diagnoser);
  7056. }
  7057. /// Get diagnostic %select index for tag kind for
  7058. /// literal type diagnostic message.
  7059. /// WARNING: Indexes apply to particular diagnostics only!
  7060. ///
  7061. /// \returns diagnostic %select index.
  7062. static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
  7063. switch (Tag) {
  7064. case TTK_Struct: return 0;
  7065. case TTK_Interface: return 1;
  7066. case TTK_Class: return 2;
  7067. default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
  7068. }
  7069. }
  7070. /// Ensure that the type T is a literal type.
  7071. ///
  7072. /// This routine checks whether the type @p T is a literal type. If @p T is an
  7073. /// incomplete type, an attempt is made to complete it. If @p T is a literal
  7074. /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
  7075. /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
  7076. /// it the type @p T), along with notes explaining why the type is not a
  7077. /// literal type, and returns true.
  7078. ///
  7079. /// @param Loc The location in the source that the non-literal type
  7080. /// diagnostic should refer to.
  7081. ///
  7082. /// @param T The type that this routine is examining for literalness.
  7083. ///
  7084. /// @param Diagnoser Emits a diagnostic if T is not a literal type.
  7085. ///
  7086. /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
  7087. /// @c false otherwise.
  7088. bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
  7089. TypeDiagnoser &Diagnoser) {
  7090. assert(!T->isDependentType() && "type should not be dependent");
  7091. QualType ElemType = Context.getBaseElementType(T);
  7092. if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
  7093. T->isLiteralType(Context))
  7094. return false;
  7095. Diagnoser.diagnose(*this, Loc, T);
  7096. if (T->isVariableArrayType())
  7097. return true;
  7098. const RecordType *RT = ElemType->getAs<RecordType>();
  7099. if (!RT)
  7100. return true;
  7101. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  7102. // A partially-defined class type can't be a literal type, because a literal
  7103. // class type must have a trivial destructor (which can't be checked until
  7104. // the class definition is complete).
  7105. if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
  7106. return true;
  7107. // [expr.prim.lambda]p3:
  7108. // This class type is [not] a literal type.
  7109. if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
  7110. Diag(RD->getLocation(), diag::note_non_literal_lambda);
  7111. return true;
  7112. }
  7113. // If the class has virtual base classes, then it's not an aggregate, and
  7114. // cannot have any constexpr constructors or a trivial default constructor,
  7115. // so is non-literal. This is better to diagnose than the resulting absence
  7116. // of constexpr constructors.
  7117. if (RD->getNumVBases()) {
  7118. Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
  7119. << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
  7120. for (const auto &I : RD->vbases())
  7121. Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
  7122. << I.getSourceRange();
  7123. } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
  7124. !RD->hasTrivialDefaultConstructor()) {
  7125. Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
  7126. } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
  7127. for (const auto &I : RD->bases()) {
  7128. if (!I.getType()->isLiteralType(Context)) {
  7129. Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
  7130. << RD << I.getType() << I.getSourceRange();
  7131. return true;
  7132. }
  7133. }
  7134. for (const auto *I : RD->fields()) {
  7135. if (!I->getType()->isLiteralType(Context) ||
  7136. I->getType().isVolatileQualified()) {
  7137. Diag(I->getLocation(), diag::note_non_literal_field)
  7138. << RD << I << I->getType()
  7139. << I->getType().isVolatileQualified();
  7140. return true;
  7141. }
  7142. }
  7143. } else if (!RD->hasTrivialDestructor()) {
  7144. // All fields and bases are of literal types, so have trivial destructors.
  7145. // If this class's destructor is non-trivial it must be user-declared.
  7146. CXXDestructorDecl *Dtor = RD->getDestructor();
  7147. assert(Dtor && "class has literal fields and bases but no dtor?");
  7148. if (!Dtor)
  7149. return true;
  7150. Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
  7151. diag::note_non_literal_user_provided_dtor :
  7152. diag::note_non_literal_nontrivial_dtor) << RD;
  7153. if (!Dtor->isUserProvided())
  7154. SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI,
  7155. /*Diagnose*/true);
  7156. }
  7157. return true;
  7158. }
  7159. bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
  7160. BoundTypeDiagnoser<> Diagnoser(DiagID);
  7161. return RequireLiteralType(Loc, T, Diagnoser);
  7162. }
  7163. /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified
  7164. /// by the nested-name-specifier contained in SS, and that is (re)declared by
  7165. /// OwnedTagDecl, which is nullptr if this is not a (re)declaration.
  7166. QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
  7167. const CXXScopeSpec &SS, QualType T,
  7168. TagDecl *OwnedTagDecl) {
  7169. if (T.isNull())
  7170. return T;
  7171. NestedNameSpecifier *NNS;
  7172. if (SS.isValid())
  7173. NNS = SS.getScopeRep();
  7174. else {
  7175. if (Keyword == ETK_None)
  7176. return T;
  7177. NNS = nullptr;
  7178. }
  7179. return Context.getElaboratedType(Keyword, NNS, T, OwnedTagDecl);
  7180. }
  7181. QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
  7182. assert(!E->hasPlaceholderType() && "unexpected placeholder");
  7183. if (!getLangOpts().CPlusPlus && E->refersToBitField())
  7184. Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
  7185. if (!E->isTypeDependent()) {
  7186. QualType T = E->getType();
  7187. if (const TagType *TT = T->getAs<TagType>())
  7188. DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
  7189. }
  7190. return Context.getTypeOfExprType(E);
  7191. }
  7192. /// getDecltypeForExpr - Given an expr, will return the decltype for
  7193. /// that expression, according to the rules in C++11
  7194. /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
  7195. static QualType getDecltypeForExpr(Sema &S, Expr *E) {
  7196. if (E->isTypeDependent())
  7197. return S.Context.DependentTy;
  7198. // C++11 [dcl.type.simple]p4:
  7199. // The type denoted by decltype(e) is defined as follows:
  7200. //
  7201. // - if e is an unparenthesized id-expression or an unparenthesized class
  7202. // member access (5.2.5), decltype(e) is the type of the entity named
  7203. // by e. If there is no such entity, or if e names a set of overloaded
  7204. // functions, the program is ill-formed;
  7205. //
  7206. // We apply the same rules for Objective-C ivar and property references.
  7207. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  7208. const ValueDecl *VD = DRE->getDecl();
  7209. return VD->getType();
  7210. } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  7211. if (const ValueDecl *VD = ME->getMemberDecl())
  7212. if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
  7213. return VD->getType();
  7214. } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
  7215. return IR->getDecl()->getType();
  7216. } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
  7217. if (PR->isExplicitProperty())
  7218. return PR->getExplicitProperty()->getType();
  7219. } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
  7220. return PE->getType();
  7221. }
  7222. // C++11 [expr.lambda.prim]p18:
  7223. // Every occurrence of decltype((x)) where x is a possibly
  7224. // parenthesized id-expression that names an entity of automatic
  7225. // storage duration is treated as if x were transformed into an
  7226. // access to a corresponding data member of the closure type that
  7227. // would have been declared if x were an odr-use of the denoted
  7228. // entity.
  7229. using namespace sema;
  7230. if (S.getCurLambda()) {
  7231. if (isa<ParenExpr>(E)) {
  7232. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  7233. if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
  7234. QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
  7235. if (!T.isNull())
  7236. return S.Context.getLValueReferenceType(T);
  7237. }
  7238. }
  7239. }
  7240. }
  7241. // C++11 [dcl.type.simple]p4:
  7242. // [...]
  7243. QualType T = E->getType();
  7244. switch (E->getValueKind()) {
  7245. // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
  7246. // type of e;
  7247. case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
  7248. // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
  7249. // type of e;
  7250. case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
  7251. // - otherwise, decltype(e) is the type of e.
  7252. case VK_RValue: break;
  7253. }
  7254. return T;
  7255. }
  7256. QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
  7257. bool AsUnevaluated) {
  7258. assert(!E->hasPlaceholderType() && "unexpected placeholder");
  7259. if (AsUnevaluated && CodeSynthesisContexts.empty() &&
  7260. E->HasSideEffects(Context, false)) {
  7261. // The expression operand for decltype is in an unevaluated expression
  7262. // context, so side effects could result in unintended consequences.
  7263. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  7264. }
  7265. return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
  7266. }
  7267. QualType Sema::BuildUnaryTransformType(QualType BaseType,
  7268. UnaryTransformType::UTTKind UKind,
  7269. SourceLocation Loc) {
  7270. switch (UKind) {
  7271. case UnaryTransformType::EnumUnderlyingType:
  7272. if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
  7273. Diag(Loc, diag::err_only_enums_have_underlying_types);
  7274. return QualType();
  7275. } else {
  7276. QualType Underlying = BaseType;
  7277. if (!BaseType->isDependentType()) {
  7278. // The enum could be incomplete if we're parsing its definition or
  7279. // recovering from an error.
  7280. NamedDecl *FwdDecl = nullptr;
  7281. if (BaseType->isIncompleteType(&FwdDecl)) {
  7282. Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
  7283. Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
  7284. return QualType();
  7285. }
  7286. EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
  7287. assert(ED && "EnumType has no EnumDecl");
  7288. DiagnoseUseOfDecl(ED, Loc);
  7289. Underlying = ED->getIntegerType();
  7290. assert(!Underlying.isNull());
  7291. }
  7292. return Context.getUnaryTransformType(BaseType, Underlying,
  7293. UnaryTransformType::EnumUnderlyingType);
  7294. }
  7295. }
  7296. llvm_unreachable("unknown unary transform type");
  7297. }
  7298. QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
  7299. if (!T->isDependentType()) {
  7300. // FIXME: It isn't entirely clear whether incomplete atomic types
  7301. // are allowed or not; for simplicity, ban them for the moment.
  7302. if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
  7303. return QualType();
  7304. int DisallowedKind = -1;
  7305. if (T->isArrayType())
  7306. DisallowedKind = 1;
  7307. else if (T->isFunctionType())
  7308. DisallowedKind = 2;
  7309. else if (T->isReferenceType())
  7310. DisallowedKind = 3;
  7311. else if (T->isAtomicType())
  7312. DisallowedKind = 4;
  7313. else if (T.hasQualifiers())
  7314. DisallowedKind = 5;
  7315. else if (!T.isTriviallyCopyableType(Context))
  7316. // Some other non-trivially-copyable type (probably a C++ class)
  7317. DisallowedKind = 6;
  7318. if (DisallowedKind != -1) {
  7319. Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
  7320. return QualType();
  7321. }
  7322. // FIXME: Do we need any handling for ARC here?
  7323. }
  7324. // Build the pointer type.
  7325. return Context.getAtomicType(T);
  7326. }