SemaType.cpp 301 KB

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